Skip to content

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.


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/api never imports Better Auth and never reads or sets a cookie. A valid dashboard session sent to api.router.africa gets 401, exactly as if no credential were sent.
  • R2. apps/dashboard-api never looks at an API key. A valid API key sent to a dashboard or admin route gets 401.
  • R3. A session belongs to one audience (sessions.audience, app or admin) 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 the HttpOnly cookie, 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.

  • Authorization: Bearer <key> is the accepted form on every route. Scheme matched case-insensitively, one space, no Basic, no api-key, no key in the query string or body. Exception (decided 2026-11-07): POST /v1/messages also accepts x-api-key: <key>, so the Anthropic SDK works with only a base-URL change; Bearer still works there. Any other route ignores x-api-key and answers missing_api_key.
  • OpenAI-Organization, OpenAI-Project and OpenAI-Beta are 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 Authorization header is never forwarded to Bifrost. apps/api authenticates the key against Postgres, then calls Bifrost with the mapped virtual key in whatever header Bifrost accepts (for example x-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. Only POST /v1/chat/completions reads a body. The query-string key check uses URLSearchParams, so a malformed escape is a clean rejection, not a 500, 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 gets 429 edge_rate_limited before 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).

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.

Superseded for the wire format (2026-10-26): the body shape, status codes and reason values are now in api-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-id on 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 are 402 payment_required (reasons insufficient_credits, key_spend_cap_exceeded), not 429, 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.

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.

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.

  • Audience check. sessions.audience is set at creation from the origin that logged the user in and verified on every request. The admin middleware also requires users.role in (support, admin), a non-banned user, and two_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; revokeOtherSessions on 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 403 with code reauth_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_address and user_agent are 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.
  • CSRF. SameSite, plus on every non-GET request our middleware requires an Origin (or Sec-Fetch-Site: same-origin) matching the exact allow-list of our own origins, plus a JSON content type. State never changes on a GET. Better Auth’s own routes use its trusted-origins check with the same exact list (no wildcards).
  • CORS. Exact-origin allow-list, Allow-Credentials only 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-api response is Cache-Control: no-store with Vary: Cookie, and Cloudflare cache rules bypass the API paths on app. and admin. (never “cache everything”). This closes cache poisoning and deception, where one user is served another’s response.
  • Rate limits on the auth endpoints (rate_limits table): 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. state and PKCE (Better Auth), exact registered redirect URIs, and any callbackURL or redirectTo parameter validated against the trusted-origins list, so there is no open redirect.
  • Impersonation is read-only and audited (db-schema.md 4.0). An impersonation session has audience = 'app', so it can never reach admin routes.
  • CSP on the dashboard and admin apps: default-src 'self'; script-src 'self' (no inline scripts, no eval), object-src 'none', base-uri 'none', form-action 'self', frame-ancestors 'none'. Plus X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin.
  • HSTS with includeSubDomains on router.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.africa record and remove dangling ones, so no subdomain can be taken over and used to attack the parent domain.
  • Never log credentials. Cookie, Set-Cookie, Authorization and any x-api-key are 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.
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)
  • One module owns it. Cookie names, attributes, lifetimes, secrets, plugin set and the R1 to R4 checks live in packages/auth and 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.

  1. A valid dashboard session cookie sent to api.router.africa → 401, and no cookie is ever set by apps/api.
  2. A valid API key sent as Authorization: Bearer to any apps/dashboard-api route → 401.
  3. Every accepted API-key form: Bearer, case-insensitive, on every route, and x-api-key on POST /v1/messages only; Basic, api-key, key in query string and key in body → 401 (and x-api-key on any other route → 401 missing_api_key).
  4. Unknown, revoked, expired and pending keys, and keys with the wrong prefix, length or checksum, return the identical 401 body apart from the masked key, and a malformed key causes no database query. The key is masked, and never echoed in full.
  5. OpenAI-Organization and OpenAI-Project with another workspace’s ids change nothing; unknown headers don’t error.
  6. The client’s Authorization header is absent on the request apps/api makes to Bifrost.
  7. Every apps/api response carries x-request-id; every 401 carries WWW-Authenticate.
  8. Session Set-Cookie has HttpOnly, Secure, Path=/, the right SameSite, the __Host- prefix and no Domain. After login and after creating an API key, a browser test finds no session token and no API key in localStorage, sessionStorage or IndexedDB (R5).
  9. A tampered or unsigned cookie → rejected. An expired, revoked or banned session → rejected on the very next request.
  10. An app session presented to an admin route → rejected; an admin session presented to an app route → rejected; a customer session on an admin route → 403.
  11. A copied cookie value moved to the other origin’s cookie name → rejected (different secret and audience).
  12. A staff user without two-factor gets nothing from admin routes.
  13. Cross-origin POST with a valid cookie and no matching Origin → rejected; GET never changes state.
  14. A session with impersonated_by set → every non-GET and every stored-content read is rejected; it never reaches admin routes.
  15. A session older than the absolute limit → rejected even if not expired.
  16. Sensitive actions with a stale login → 403 reauth_required.
  17. Password reset and password change revoke all other sessions.
  18. apps/dashboard-api responses carry Cache-Control: no-store and Vary: Cookie.
  19. Stored content containing <script>, <img onerror> and markdown links renders as inert text (browser test).
  20. No log or trace line in a request-handling test run contains the strings Cookie, Authorization or the test key.
  • 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, no Domain, so the cookie stays host-only.
  • Two Better Auth instances (one per audience) versus one with an audience check; 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 (requireLocalEmailVerified defaults to true); stored OAuth tokens can be encrypted (account.encryptOAuthTokens, on).
  • The type and code values 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 (or mcp.router.africa), never on apps/api. A delegated token sent to an inference route, a dashboard cookie route or an admin route gets 401; an API key or a cookie sent to the delegated routes gets 401. 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 explicit keys:write scope 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.