Router.Africa — Auth and Session Security
Two things in one place: how the public API authenticates (kept compatible with OpenAI’s, so existing SDKs work unchanged), and the controls that make the dashboard’s cookie session hard to steal, reuse or confuse. It implements the Dashboard auth model, Dashboard session mechanism and Public API authentication entries in decisions-log.md; where they disagree, the decisions log wins.
What this promises, and what it doesn’t. No design is “100% safe” and none can be proven unbreakable. This doc lists each way a session or key can be misused, names the control for it, states the risk that remains, and defines tests (section 6) that fail if a control is weakened. A stolen cookie on a compromised device, or a script running inside our own pages, can still act as that user until the session ends. The controls make that rare, short-lived, limited in what it can do, and visible in the audit log.
1. Two credential planes, never mixed
Section titled “1. Two credential planes, never mixed”| Plane | Origin | Worker | Credential | Cookie header | Authorization header |
|---|---|---|---|---|---|
| Public API | api.router.africa |
apps/api |
Our API key: Authorization: Bearer sk-ra-… |
Never read. Ignored, never forwarded | The only credential, Bearer scheme only |
| Dashboard | app.router.africa |
apps/dashboard-api |
Session cookie | The only credential | Ignored. An API key does not authenticate here |
| Admin | admin.router.africa |
apps/dashboard-api, admin route group |
A separate session cookie (staff) | The only credential | Ignored |
The admin origin also sits behind Cloudflare Access (staff identities only), so the page and its API routes don’t load for anyone else; the staff session cookie is still the credential the backend checks (decisions log, Admin origin access).
Rules that follow from the decisions log’s hard constraint (one credential mechanism per surface, so no leftover credential can win):
- R1.
apps/apinever imports Better Auth and never reads or sets a cookie. A valid dashboard session sent toapi.router.africagets401, exactly as if no credential were sent. - R2.
apps/dashboard-apinever looks at an API key. A valid API key sent to a dashboard or admin route gets401. - R3. A session belongs to one audience (
sessions.audience,apporadmin) and is refused on the other, even if someone copies the cookie value across (see 3.1). - R4. No credential ever appears in a URL (query string or path), on either plane.
- R5. No credential is ever kept in
localStorage,sessionStorage, IndexedDB or any client-side cache. The session lives only in theHttpOnlycookie, which page scripts can’t read; a token in web storage would be readable by any script on the page. The API key shown once at creation is held in memory only until the user leaves the screen, and is never persisted, logged or sent to analytics or error reporting.
2. Public API authentication (OpenAI-compatible)
Section titled “2. Public API authentication (OpenAI-compatible)”Goal: an OpenAI SDK pointed at https://api.router.africa/v1 with our key needs no other change, and the failure cases look like OpenAI’s so client code that handles them keeps working.
2.1 Requests
Section titled “2.1 Requests”Authorization: Bearer <key>is the accepted form on every route. Scheme matched case-insensitively, one space, noBasic, noapi-key, no key in the query string or body. Exception (decided 2026-11-07):POST /v1/messagesalso acceptsx-api-key: <key>, so the Anthropic SDK works with only a base-URL change; Bearer still works there. Any other route ignoresx-api-keyand answersmissing_api_key.OpenAI-Organization,OpenAI-ProjectandOpenAI-Betaare accepted and ignored (SDKs send them when the user configures them; erroring would break those users). They never grant or change access: the key alone determines the workspace.- Unknown headers (
X-Stainless-*,User-Agent, and so on) are ignored. - The client’s
Authorizationheader is never forwarded to Bifrost.apps/apiauthenticates the key against Postgres, then calls Bifrost with the mapped virtual key in whatever header Bifrost accepts (for examplex-bf-vk). - No CORS. The API is server-to-server, so browsers can’t call it with a key (decided).
- One auth pass per request (review of P3.02, 2026-11-01). One key-auth middleware covers
/v1/*; the key, workspace, org, gateway credential and model gate are read in one query (findRequestContext), because every Worker query is a round trip to the database region. - The body is read once, capped at 16 MiB before it is buffered (
413 payload_too_large). It is refused if it contains one of our keys (400 key_not_in_header), and cached so the route can read it again. OnlyPOST /v1/chat/completionsreads a body. The query-string key check usesURLSearchParams, so a malformed escape is a clean rejection, not a500, and encoded keys are still caught. - Failed key lookups are throttled per client IP (review of P3.02, 2026-11-01). Each rejected lookup counts in a Workers Rate Limiting binding (
AUTH_FAILURE_LIMITER, 30 a minute). An IP over the limit gets429 edge_rate_limitedbefore any database lookup. Keys that work never count. Why: the checksum stops typos, not scripts, because the key format is public. This sits alongside the Cloudflare edge rules and the rejected-key cache (decisions log, Edge rate limiting).
2.2 Key format
Section titled “2.2 Key format”sk-ra- + 37 random base62 characters (about 220 bits) + a 6-character checksum: CRC32 of everything before it, written in base62. The sk- prefix is the de facto shape SDKs and tools expect (some validate it); -ra- makes ours recognisable. The full key is shown once at creation; api_keys.key_prefix stores the first 12 characters (sk-ra- plus 6 random) for display, so keys in one workspace look different. Lookup is by SHA-256 of the whole key; with that entropy a fast unsalted hash is fine, and there is no timing signal to exploit. The backlog’s earlier ra_live_ idea is superseded.
The checksum is not a secret and adds no security by itself. It lets apps/api reject a malformed key (wrong prefix, wrong length, bad checksum, typo, truncation, a flood of garbage) locally, before any database lookup, which protects the hold/settle hot path from junk traffic, and it lets a secret scanner confirm a string is really one of ours before reporting it. The rejection is the same 401 invalid_api_key as any other bad key, so nobody can tell “malformed” from “revoked”. No customer or workspace identifier is embedded in the key; the owner of a leaked key is found by hashing it and looking it up.
2.3 Authentication and access failures
Section titled “2.3 Authentication and access failures”Superseded for the wire format (2026-10-26): the body shape, status codes and
reasonvalues are now inapi-errors.md(OpenRouter’s envelope; decisions log, API error contract and response extras). The rules below — one answer for every bad key, masking,x-request-idon every response — still apply.
Body shape, as OpenAI’s: {"error": {"message": string, "type": string, "param": null, "code": string|null}}. The type and code values are proposed; confirm each against OpenAI’s live responses when the error catalogue is written (api-surface.md, comparison #39 and #40).
| Situation | Status | type |
code |
Message |
|---|---|---|---|---|
No Authorization header, or not Bearer |
401 | invalid_request_error |
null |
You didn’t provide an API key. Send it in an Authorization header: Authorization: Bearer YOUR_KEY. |
Key unknown, revoked, expired, or still pending |
401 | invalid_request_error |
invalid_api_key |
Incorrect API key provided: sk-ra-…abcd. You can find your API key at https://app.router.africa/keys. |
| Workspace frozen | 403 | permission_error |
account_suspended |
This account is suspended. Contact support. |
Model not on, or not in the key’s allowed_models |
404 | invalid_request_error |
model_not_found |
The model x does not exist or you do not have access to it. |
Every 401 carries WWW-Authenticate: Bearer realm="router.africa". Rules:
- One message for every bad key, whatever the reason, so nobody can probe whether a key ever existed, was revoked or expired. The same goes for “model off” versus “model not allowed for this key”.
- Mask the key in the message (prefix and last four only). The full key never appears in a response, log or trace.
- Every response, success or error, carries
x-request-id(our request id, the same one sent to Bifrost and stored in the request log), as OpenAI’s do, so SDK error output and support requests line up.
2.4 Out-of-credit and limit responses (error catalogue, not decided here)
Section titled “2.4 Out-of-credit and limit responses (error catalogue, not decided here)”Settled in
api-errors.md(2026-10-26): out of credits and a key over its spend cap are402 payment_required(reasonsinsufficient_credits,key_spend_cap_exceeded), not429, so SDKs don’t retry them. Flagged there for review.
OpenAI now returns 429 for an exhausted balance (code credit_balance_exhausted), a spend limit (project_spend_limit_exceeded, organization_spend_limit_exceeded) and a rate limit, with Retry-After on rate limits. Bifrost’s own budget error is 402. To stay OpenAI-compatible, apps/api translates at the edge: no credits, or a key over its spend cap, becomes a 429 with a distinct code, never a bare 402. Note the SDK consequence: OpenAI’s SDKs retry 429s by default, so “no credits” will be retried a couple of times before surfacing; the distinct code is what lets callers stop. Which codes and whether to use 402 instead is the error-catalogue decision.
3. Dashboard session hardening
Section titled “3. Dashboard session hardening”The session is an opaque random token in a cookie, looked up in core.sessions on every request (decisions log, Dashboard session mechanism). These are the controls around it.
3.1 The cookie
Section titled “3.1 The cookie”| Property | Value | Why |
|---|---|---|
| Name | __Host-ra-session (dashboard), __Host-ra-admin-session (admin) |
The __Host- prefix makes the browser refuse the cookie unless it is Secure, Path=/ and has no Domain, so a sibling subdomain can’t set or overwrite it (cookie tossing). If the pinned Better Auth version can’t rename its cookies, use its __Secure- prefix with no Domain, which is still host-only |
HttpOnly |
yes | Page scripts can’t read it |
Secure |
yes | HTTPS only |
SameSite |
Lax (dashboard), Strict (admin) |
Not sent on cross-site requests; admin has no cross-site entry point |
Domain |
never set | Host-only: app. and admin. cookies are never sent to each other, api. or the marketing site |
| Signature | Signed with a secret per environment and per audience (BETTER_AUTH_SECRET_APP, BETTER_AUTH_SECRET_ADMIN), 32+ random bytes |
A dashboard cookie value pasted into the admin origin fails its signature check |
| Content | Random token only. No role, org, plan or permission is stored in the cookie | Authorization is read from the database on every request. Cookie cache stays off |
Other cookies Better Auth sets (OAuth state, two-factor challenge, “remember me”) get the same attributes.
3.2 Server rules
Section titled “3.2 Server rules”- Audience check.
sessions.audienceis set at creation from the origin that logged the user in and verified on every request. The admin middleware also requiresusers.rolein (support,admin), a non-banned user, andtwo_factor_enabled. - Everything is read live. Ban, role change, org membership, staff role and two-factor status take effect on the next request, because nothing about them is cached in the cookie.
- New session on every login, and on password change, password reset and two-factor change (against session fixation). A password reset or change revokes all other sessions (
revokeSessionsOnPasswordReset;revokeOtherSessionson change). - Lifetimes (proposed, tunable). Dashboard: 7 days sliding, refreshed after 1 day, with an absolute limit of 30 days enforced by our middleware from
sessions.created_at. Admin: 8 hours, not sliding past 12 hours, no “remember me”. - Step-up for sensitive actions. These need a login within the last 15 minutes and otherwise return
403with codereauth_required(the UI asks the user to sign in again): create, rotate or revoke an API key, top up, transfer credits, change or remove a member, disable two-factor, change email or password, delete a workspace or org, and read stored prompts or responses (the most sensitive data we hold, so a stolen cookie alone can’t open it). - No IP, device, browser or country binding, and no logout because of a change in any of them (decided 2026-09-21). People travel, switch networks and use mobile data, and being signed out for that is worse than the risk it would reduce.
ip_addressanduser_agentare recorded, and a new sign-in from an unseen device or country sends an email through Resend so a stolen session is noticed; the session list, force logout and step-up (below) do the rest. - The customer can see and end their sessions (Security screen), and staff can force logout. Deleting the row ends the session at once.
- Kill switch. In a breach, deleting every row in
sessions(or rotating the secrets) signs everyone out immediately. This is possible because the database is authoritative; write it as a runbook step.
3.3 Requests
Section titled “3.3 Requests”- CSRF.
SameSite, plus on every non-GET request our middleware requires anOrigin(orSec-Fetch-Site: same-origin) matching the exact allow-list of our own origins, plus a JSON content type. State never changes on aGET. Better Auth’s own routes use its trusted-origins check with the same exact list (no wildcards). - CORS. Exact-origin allow-list,
Allow-Credentialsonly ever with that one exact origin, never*. The SPA and its API share an origin, so most calls need none. - No caching of authenticated responses. Every
apps/dashboard-apiresponse isCache-Control: no-storewithVary: Cookie, and Cloudflare cache rules bypass the API paths onapp.andadmin.(never “cache everything”). This closes cache poisoning and deception, where one user is served another’s response. - Rate limits on the auth endpoints (
rate_limitstable): stricter on sign-in, password reset and two-factor verify. Turnstile on signup, sign-in and reset. Sign-in returns one generic error for “no such email” and “wrong password”. - OAuth.
stateand PKCE (Better Auth), exact registered redirect URIs, and anycallbackURLorredirectToparameter validated against the trusted-origins list, so there is no open redirect. - Impersonation is read-only and audited (
db-schema.md4.0). An impersonation session hasaudience = 'app', so it can never reach admin routes.
3.4 The page itself
Section titled “3.4 The page itself”- CSP on the dashboard and admin apps:
default-src 'self'; script-src 'self'(no inline scripts, noeval),object-src 'none',base-uri 'none',form-action 'self',frame-ancestors 'none'. PlusX-Content-Type-Options: nosniff,Referrer-Policy: strict-origin-when-cross-origin. - HSTS with
includeSubDomainsonrouter.africa. Submit for preload only when sure every subdomain will always be HTTPS; preload is hard to undo. - Stored prompts and responses are attacker-controlled text (a customer’s model output can contain anything) and are shown to org admins and to staff. Render them as plain text only, never as HTML or unsanitised markdown, and never through
innerHTML. This is the most likely route to a script running in a privileged session, so it gets its own test (section 6). - DNS hygiene. Keep an inventory of every
*.router.africarecord and remove dangling ones, so no subdomain can be taken over and used to attack the parent domain. - Never log credentials.
Cookie,Set-Cookie,Authorizationand anyx-api-keyare stripped from Datadog traces, Workers logs, error reports and queue messages (extends the decisions log’s “headers are never stored”). A lint rule forbids logging a whole request or headers object.
4. Threats, controls and what remains
Section titled “4. Threats, controls and what remains”| Threat | Control | Residual risk |
|---|---|---|
| Cookie stolen by a script (XSS) | HttpOnly, strict CSP, text-only rendering of stored content, pinned dependencies |
A script running in the page can still act as the user in that page. Step-up, read-only impersonation and audit limit and expose the damage |
| Cookie stolen from a device (malware, shared computer) | Short admin sessions, 30-day absolute limit, step-up for money, access changes and stored-content reads, session list, new-sign-in email, force logout and ban | Valid until revoked or expired; a determined attacker on a compromised device can use it |
| Sniffing | HTTPS only, Secure, HSTS |
None expected |
| Cookie tossing from a sibling subdomain | __Host- prefix, no Domain, DNS hygiene |
None expected |
| CSRF | SameSite, Origin and Sec-Fetch-Site check, no state change on GET, JSON only |
Low |
| Session fixation | New session on every login and privilege change | None expected |
| API key used as a cookie, or a cookie as an API key | Separate Workers, origins and credentials; R1 to R4; tests | None expected while the tests pass |
| App session used on admin | Separate cookie names, secrets and audience, plus staff role and two-factor |
Needs both a leaked admin secret and a staff account |
| One user served another’s response | no-store, cache bypass, Vary: Cookie |
A misconfigured Cloudflare rule; covered by a header test |
| Credentials leaked through logs | Scrub list, lint rule | A new logging path added later; the lint rule and review catch it |
| Account takeover (linking, reset, weak password) | Verified-email linking, reset revokes sessions, breached-password check, two-factor and passkeys, rate limits and Turnstile | Phishing of a user without two-factor |
| Privilege escalation through cookie contents | Nothing but a random token in the cookie; permissions read live | None expected |
| Compromised or abusive staff | Two-factor required, admin-only read-only impersonation, short sessions, full audit including impersonated_by |
A malicious admin can still use admin powers, which are logged |
| Library or supply-chain vulnerability | Exact version pins, review of auth-related release notes, conformance suite on every dependency bump, kill switch | A zero-day before a fix exists |
| Enumeration of keys, emails or models | One error for every bad key and every bad model, one generic sign-in error | Sign-up “email already registered” behaviour; verify in staging (section 7) |
5. Future-proofing
Section titled “5. Future-proofing”- One module owns it. Cookie names, attributes, lifetimes, secrets, plugin set and the R1 to R4 checks live in
packages/authand two small middlewares (one per plane). Nothing else touches sessions or reads a credential. - The database is authoritative, so cookie attributes, names and even the signing secret can change without migrating sessions or touching clients, and new revocation rules (per device, per org, global) are one query.
- Pin and prove. Better Auth and its plugins are pinned to exact versions. A dependency bump runs the conformance suite before merge; a change that weakens a control fails a test instead of shipping quietly.
- No second credential path is ever added (bearer, JWT or API-key plugins stay off); adding one is a decisions-log change, not a config flip.
6. Conformance suite (the auth contract, run in CI)
Section titled “6. Conformance suite (the auth contract, run in CI)”Written with @cloudflare/vitest-pool-workers, against the real Workers. Each item fails the build if broken.
- A valid dashboard session cookie sent to
api.router.africa→401, and no cookie is ever set byapps/api. - A valid API key sent as
Authorization: Bearerto anyapps/dashboard-apiroute →401. - Every accepted API-key form:
Bearer, case-insensitive, on every route, andx-api-keyonPOST /v1/messagesonly;Basic,api-key, key in query string and key in body →401(andx-api-keyon any other route →401 missing_api_key). - Unknown, revoked, expired and
pendingkeys, and keys with the wrong prefix, length or checksum, return the identical401body apart from the masked key, and a malformed key causes no database query. The key is masked, and never echoed in full. OpenAI-OrganizationandOpenAI-Projectwith another workspace’s ids change nothing; unknown headers don’t error.- The client’s
Authorizationheader is absent on the requestapps/apimakes to Bifrost. - Every
apps/apiresponse carriesx-request-id; every 401 carriesWWW-Authenticate. - Session
Set-CookiehasHttpOnly,Secure,Path=/, the rightSameSite, the__Host-prefix and noDomain. After login and after creating an API key, a browser test finds no session token and no API key inlocalStorage,sessionStorageor IndexedDB (R5). - A tampered or unsigned cookie → rejected. An expired, revoked or banned session → rejected on the very next request.
- An
appsession presented to an admin route → rejected; an admin session presented to an app route → rejected; a customer session on an admin route →403. - A copied cookie value moved to the other origin’s cookie name → rejected (different secret and
audience). - A staff user without two-factor gets nothing from admin routes.
- Cross-origin
POSTwith a valid cookie and no matchingOrigin→ rejected;GETnever changes state. - A session with
impersonated_byset → every non-GET and every stored-content read is rejected; it never reaches admin routes. - A session older than the absolute limit → rejected even if not expired.
- Sensitive actions with a stale login →
403 reauth_required. - Password reset and password change revoke all other sessions.
apps/dashboard-apiresponses carryCache-Control: no-storeandVary: Cookie.- Stored content containing
<script>,<img onerror>and markdown links renders as inert text (browser test). - No log or trace line in a request-handling test run contains the strings
Cookie,Authorizationor the test key.
7. Open, to verify at build
Section titled “7. Open, to verify at build”Cookie prefix— resolved 2026-10-26 (1.7.7): Better Auth adds the__Secure-prefix itself, so__Host-isn’t available. The fallback applies:__Secure-ra-session, noDomain, so the cookie stays host-only.- Two Better Auth instances (one per audience) versus one with an
audiencecheck; either is fine if items 10 and 11 pass. Sign-up enumeration and secret rotation— resolved 2026-10-26 (1.7.7): sign-up answers the same way for an existing email and emails the owner instead (onExistingUserSignUp, built in the first auth PR). Secret rotation is supported through versioned secrets (secrets/BETTER_AUTH_SECRETS="2:new,1:old"): the first entry signs, older ones still verify.- Also confirmed for 1.7.7 (P1.01): GitHub and GitLab providers ship in the package; account linking refuses an untrusted provider (GitHub, GitLab) whose email is unverified, and requires the local email to be verified (
requireLocalEmailVerifieddefaults to true); stored OAuth tokens can be encrypted (account.encryptOAuthTokens, on). - The
typeandcodevalues in 2.3 against OpenAI’s live responses, and the out-of-credit and spend-limit codes in 2.4 (the error catalogue). - Cloudflare cache rules and response headers set the way sections 3.3 and 3.4 say, checked on staging with the header test.
8. Later: CLI and MCP (guidance, not decided)
Section titled “8. Later: CLI and MCP (guidance, not decided)”Not built at launch; recorded so the launch design doesn’t block it (hooks: future-optimizations.md, Auth and integrations).
What works for what
| Use | Credential | New work |
|---|---|---|
| A CLI, agent or MCP-based tool that calls models (chat, embeddings) | The existing API key, Authorization: Bearer sk-ra-…, from an environment variable or config |
None. It is just the OpenAI-compatible API |
| A CLI that manages the account (usage, balance, keys) | A delegated token minted through the OAuth 2.0 device authorization flow (ra login shows a code, the user approves it in the browser where they are already signed in, with two-factor) |
A fourth credential class and a consent screen |
| A remote MCP server we host (account tools for Claude, Cursor and similar) | The same delegated tokens, obtained through OAuth 2.1 authorization code with PKCE and dynamic client registration, which the MCP specification expects | The same class, another grant type, a reserved hostname (mcp.router.africa) |
Better Auth has plugins for both (device authorization; MCP and OAuth provider), verified against its docs on 2026-09-21. Two of their defaults must not be used as they come, because they cut across the decisions above: the device flow’s standalone mode hands the CLI a session token used as a Bearer (the dashboard session in portable form, with full powers), and the MCP plugin issues JWT access tokens that are verified offline and can’t be revoked before they expire. Use the OAuth-provider mode, which issues scoped tokens, and keep the delegated class isolated as below.
Rules for the delegated class (R6 to R9, extending R1 to R5)
- R6. A separate class, never interchangeable. Its own token prefix, its own audience, its own route group in
apps/dashboard-api(ormcp.router.africa), never onapps/api. A delegated token sent to an inference route, a dashboard cookie route or an admin route gets401; an API key or a cookie sent to the delegated routes gets401. The bearer and JWT plugins, if enabled for this, apply only to that route group. - R7. Least privilege, read-only by default. Scopes like
usage:read,balance:read,keys:read. Never delegable, to any token: top-ups, credit transfers, member or role changes, and reading stored prompts or responses. Creating or revoking a key needs an explicitkeys:writescope granted on the consent screen, and is not offered to MCP clients. An MCP client is driven by a model, so a hostile web page or tool result can steer it (prompt injection); a token that can’t move money or read content limits what that can do. - R8. Short-lived and revocable. Access tokens live minutes (about 15), refresh tokens are rotating and stored hashed in the database, and both die when the user revokes the app on the Security screen (“Connected apps”), changes their password or is banned. If the JWT plugin is used for access tokens, the short life is what bounds the lack of instant revocation.
- R9. Consent is a step-up, and phishing-aware. Approving a device or app needs a fresh login and two-factor. The consent screen names the app, the scopes and the requesting location. Device codes expire in about 10 minutes and entry is rate-limited, because the attack on a device flow is tricking a user into entering an attacker’s code.
Also: the CLI keeps its tokens in the operating system’s keychain, not a plain file. Issuing, using and revoking a delegated token are audit events (oauth.token_issued, oauth.token_revoked). Conformance tests for R6 to R9 are added to section 6 when this is built.