Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,7 @@ ADMIN_TOKEN=

# Announce the server on the local network (mDNS) so Talk clients can find it
MDNS_ENABLED=true

# Let Talk clients pair with a 6-digit code the operator reads in the log or
# the dashboard (needs ADMIN_TOKEN)
PAIRING_ENABLED=true
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
turn it off. Under Docker the announcement only leaves the container with
`network_mode: host`. A failed announcement logs a warning and never stops the
server.
- A Talk client can now get a token by pairing: it asks for a request, and you read
it a 6-digit code that shows in the server log (WARNING) and under "Pairing
Requests" in the `/admin/` dashboard. Typing the code on the client mints a token
named `<client name> (paired)`. Codes last two minutes, five wrong tries cancel the
request, and five requests can wait at once, one per machine. Ten wrong codes in
total turn pairing off until the server restarts. Pairing is off while `ADMIN_TOKEN` is
empty (the startup warning says so), and `PAIRING_ENABLED=false` turns it off. The
mDNS record carries `pairing=1` or `pairing=0` accordingly.

### Changed

Expand Down
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ the workflows run that same file.
- A single GPU serialises work. `GPU_CONCURRENCY` defaults to 1 and requests queue
behind `GPU_TIMEOUT`. Raising concurrency on one card trades latency for OOM risk.
- `ADMIN_TOKEN` unset is a valid but useless state: `/admin` is off and every `/v1`
route answers 401. The startup warning is the only clue, so check it first when
route answers 401, and pairing is off too. The startup warning is the only clue, so check it first when
auth "mysteriously" fails.
- Minted tokens are shown once and stored hashed. There is no recovery path, only
revoke and re-mint.
Expand Down
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ the healthcheck stays red until the model is resident.
| GET | `/health` | none | Model state, device, queue depth |
| GET | `/admin/` | `ADMIN_TOKEN` | Token management dashboard |
| * | `/admin/tokens[...]` | `ADMIN_TOKEN` | Token CRUD and per-token usage |
| POST | `/pairing/request`, `/pairing/confirm` | none | Get a token with a code, see Pairing |

`/health` deliberately needs no token: it is what lets a client probe reachability
before it holds one, and what lets a monitor work without being given a secret.
Expand All @@ -94,6 +95,7 @@ All of it lives in `.env`.
| `DATABASE_URL` | `sqlite+aiosqlite:///./data/tokens.db` | Token store |
| `ADMIN_TOKEN` | (empty) | Admin credential, and empty disables `/admin` |
| `MDNS_ENABLED` | `true` | Announce the server on the local network |
| `PAIRING_ENABLED` | `true` | Let clients pair with a code, needs `ADMIN_TOKEN` |

`GPU_CONCURRENCY` stays at 1 for a reason: one card serialises the work anyway, and
raising it trades latency for an out-of-memory risk you only discover under load.
Expand All @@ -113,6 +115,23 @@ Multicast does not leave a Docker bridge network, so under Docker the announceme
only reaches the LAN with `network_mode: host` on the service (and then the `ports`
mapping is no longer needed). Otherwise clients still connect by typing the address.

### Pairing

A Talk client can get a token without anyone copying one. It asks the server for a
pairing request, and the server generates a 6-digit code that only you, the operator,
can see: it is logged at WARNING by the server (`make logs` under Docker) and listed
under "Pairing Requests" in the `/admin/` dashboard, which refreshes by itself. Read
the code to whoever is at the client and they type it there. The server then mints a
token named `<client name> (paired)`, and you can revoke it like any other.

A code lives two minutes, five wrong guesses cancel the request, and at most five
requests wait at once, one per machine: asking again replaces that machine's previous
request. Ten wrong codes in total, across every request, turn pairing off until the
server restarts and log a warning saying so, which is what keeps anyone on the network
from guessing their way through requests. Pairing mints tokens without an
administrator present, so it stays off while `ADMIN_TOKEN` is empty. `PAIRING_ENABLED=false` turns it off for good,
and the mDNS record then says `pairing=0` (`pairing=1` otherwise).

## Development

```bash
Expand Down
56 changes: 56 additions & 0 deletions docs/guides/endpoints.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ rest/main.py <-- application factory, health endpoint
| +-- rest/v1/transcriptions/router.py transcription endpoints
| +-- rest/v1/models/router.py model listing
+-- rest/admin/routes.py token dashboard and CRUD
+-- rest/pairing/ pairing routes and the pending-request store
```

Where a new endpoint goes:
Expand All @@ -27,6 +28,7 @@ Where a new endpoint goes:
- transcription (`/v1/audio/transcriptions*`) belongs in `rest/v1/transcriptions/router.py`
- model listing (`/v1/models`) belongs in `rest/v1/models/router.py`
- token management (`/admin/*`) belongs in `rest/admin/routes.py`
- pairing (`/pairing/*`) belongs in `rest/pairing/routes.py`

---

Expand Down Expand Up @@ -219,6 +221,58 @@ is how many requests are waiting for a GPU slot.
delete and per-token usage endpoints. A minted token is shown once and stored hashed,
so there is no recovery path, only revoke and mint again.

`GET /admin/pairing` lists the pending pairing requests with their codes and the
seconds each has left. It answers `{"enabled": false, "requests": []}` when pairing
is off.

---

### POST /pairing/request

| Property | Value |
|---|---|
| Method | `POST` |
| Path | `/pairing/request` |
| Auth | none |
| Response | `201` JSON |

Body: `{"client_name": "Laptop"}`, 1 to 64 characters once stripped. Opens a request
that lives 120 seconds and answers:

```json
{"request_id": "0b6f0c52-...", "expires_in": 120}
```

The 6-digit code is never in the response. It is logged at WARNING and listed in the
admin dashboard, so only the operator can read it. At most 5 requests wait at a time,
and beyond that the answer is `429`.

---

### POST /pairing/confirm

| Property | Value |
|---|---|
| Method | `POST` |
| Path | `/pairing/confirm` |
| Auth | none |
| Response | `200` JSON |

Body: `{"request_id": "...", "code": "123456"}`. A right code mints a token named
`<client_name> (paired)` and answers it once:

```json
{"token": "sk_...", "name": "Laptop (paired)"}
```

An unknown or expired request answers `410`. A wrong code answers `401`, and the fifth
wrong code drops the request, so later tries get `410`. A machine holds one request at a
time: a new `/pairing/request` from the same address replaces the previous one.

Both routes answer `404` when `PAIRING_ENABLED=false` or `ADMIN_TOKEN` is empty, and
after ten wrong codes in total, until the server restarts. They
are not counted as usage.

---

## HTTP error codes
Expand All @@ -227,7 +281,9 @@ so there is no recovery path, only revoke and mint again.
|---|---|---|
| `400` | `InvalidAudioError` | Bad file format or size, unsupported response format |
| `401` | -- | Missing, malformed or revoked Bearer token |
| `410` | -- | Pairing request unknown, expired or out of attempts |
| `422` | FastAPI validation | Missing or mistyped form field |
| `429` | -- | Too many pairing requests pending |
| `500` | `TranscriptionError` | The model failed to transcribe |
| `503` | `QueueTimeoutError` | Waited longer than `GPU_TIMEOUT` for the GPU |

Expand Down
40 changes: 39 additions & 1 deletion rest/admin/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import FileResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel
from pydantic import BaseModel, ConfigDict
from sqlalchemy.ext.asyncio import AsyncSession

from rest.auth.tokens import (
Expand All @@ -20,6 +20,7 @@
revoke_token,
)
from rest.db.database import get_db
from rest.pairing.store import get_store
from rest.settings import get_settings


Expand Down Expand Up @@ -73,6 +74,25 @@ class SuccessResponse(BaseModel):
success: bool


class PendingPairing(BaseModel):
"""A pairing request waiting for its code to be typed on the client."""

model_config = ConfigDict(frozen=True)

client_name: str
code: str
seconds_left: int


class PairingListResponse(BaseModel):
"""Pending pairing requests. Empty and disabled when pairing is off."""

model_config = ConfigDict(frozen=True)

enabled: bool
requests: list[PendingPairing]


admin_security = HTTPBearer(auto_error=False)


Expand Down Expand Up @@ -180,3 +200,21 @@ async def get_token_statistics(
if stats is None:
raise HTTPException(status_code=404, detail="Token not found")
return TokenStatsResponse(**stats)


@router.get("/pairing", response_model=PairingListResponse)
async def list_pairing_requests(_admin: AdminAuth) -> PairingListResponse:
"""List pending pairing requests with their codes, for the operator."""
if not get_settings().pairing_active:
return PairingListResponse(enabled=False, requests=[])
return PairingListResponse(
enabled=True,
requests=[
PendingPairing(
client_name=request.client_name,
code=request.code,
seconds_left=seconds_left,
)
for request, seconds_left in get_store().pending()
],
)
47 changes: 47 additions & 0 deletions rest/admin/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,28 @@ <h3 class="text-sm font-semibold text-gray-400 mb-2">Endpoint Breakdown</h3>
</div>
</div>

<!-- Pairing Section -->
<div x-show="pairing.enabled" x-cloak class="mb-8 bg-gray-800 rounded-lg border border-gray-700">
<div class="p-6 border-b border-gray-700">
<h2 class="text-lg font-semibold">Pairing Requests</h2>
<p class="text-sm text-gray-400 mt-1">A client asking for a token shows up here. Read the code to whoever is typing it.</p>
</div>
<div class="divide-y divide-gray-700">
<template x-for="req in pairing.requests" :key="req.code + req.client_name">
<div class="px-6 py-4 flex items-center justify-between">
<span class="font-medium" x-text="req.client_name"></span>
<span class="flex items-center gap-4">
<span class="text-2xl font-mono tracking-widest text-yellow-400" x-text="req.code"></span>
<span class="text-sm text-gray-400" x-text="req.seconds_left + 's left'"></span>
</span>
</div>
</template>
<div x-show="pairing.requests.length === 0" class="px-6 py-8 text-center text-gray-500">
No pairing request pending.
</div>
</div>
</div>

<!-- Tokens Section -->
<div class="bg-gray-800 rounded-lg border border-gray-700">
<div class="p-6 border-b border-gray-700 flex items-center justify-between">
Expand Down Expand Up @@ -291,6 +313,8 @@ <h3 class="text-lg font-semibold">Revoke Token?</h3>
authenticated: false,
adminToken: '',
tokens: [],
pairing: { enabled: false, requests: [] },
pairingTimer: null,
loading: false,
showCreateModal: false,
newTokenName: '',
Expand All @@ -306,6 +330,7 @@ <h3 class="text-lg font-semibold">Revoke Token?</h3>
this.adminToken = saved;
this.authenticated = true;
this.loadTokens();
this.startPairingPoll();
}
},

Expand All @@ -319,6 +344,7 @@ <h3 class="text-lg font-semibold">Revoke Token?</h3>
sessionStorage.setItem('adminToken', this.adminToken);
this.authenticated = true;
this.loadTokens();
this.startPairingPoll();
} else {
this.showToast('Invalid admin token', 'error');
}
Expand All @@ -333,6 +359,27 @@ <h3 class="text-lg font-semibold">Revoke Token?</h3>
this.authenticated = false;
this.adminToken = '';
this.tokens = [];
clearInterval(this.pairingTimer);
this.pairing = { enabled: false, requests: [] };
},

startPairingPoll() {
clearInterval(this.pairingTimer);
this.loadPairing();
this.pairingTimer = setInterval(() => this.loadPairing(), 3000);
},

async loadPairing() {
try {
const res = await fetch('/admin/pairing', {
headers: { 'Authorization': `Bearer ${this.adminToken}` }
});
if (res.ok) {
this.pairing = await res.json();
}
} catch (e) {
// Next tick retries; a toast every 3 seconds would only nag.
}
},

async loadTokens() {
Expand Down
1 change: 1 addition & 0 deletions rest/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ def build_service_info(settings: Settings) -> ServiceInfo | None:
"engine": "faster-whisper",
"model": settings.WHISPER_MODEL,
"auth": "token",
"pairing": "1" if settings.pairing_active else "0",
},
server=f"{hostname}.local.",
addresses=[socket.inet_aton(a) for a in addresses],
Expand Down
8 changes: 6 additions & 2 deletions rest/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
add_exception_middleware,
)
from rest.models import HealthResponse
from rest.pairing import router as pairing_router
from rest.routes import router
from rest.settings import get_settings

Expand All @@ -42,8 +43,8 @@ async def lifespan(app: FastAPI):
if not settings.ADMIN_TOKEN:
logging.getLogger(__name__).warning(
"ADMIN_TOKEN is not set: /admin is disabled and no tokens can be "
"minted, so all /v1 requests will return 401. Set ADMIN_TOKEN to "
"enable token management."
"minted, so all /v1 requests will return 401. Pairing is off for "
"the same reason. Set ADMIN_TOKEN to enable token management."
)

await init_db()
Expand Down Expand Up @@ -105,6 +106,9 @@ def create_app() -> FastAPI:
# Routes: all /v1 endpoints require a valid Bearer token (see rest/routes.py)
app.include_router(router)

# Pairing: unauthenticated by design, gated by a code the operator reads
app.include_router(pairing_router)

# Admin token management (protected by its own ADMIN_TOKEN)
app.include_router(admin_router)

Expand Down
5 changes: 5 additions & 0 deletions rest/pairing/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Pairing module: hand a token to a client that types a code shown to the operator."""

from rest.pairing.routes import router

__all__ = ["router"]
Loading
Loading