auth-session-conventions
Step 6 of the pipeline (WORKFLOW.md), on the auth surface specifically. Auth is the one place
where a regression doesn't show up as a failing test: the happy path keeps working, and the
breakage only appears an hour later when the first token expires. This block exists because that
already happened to us: a refresh flow broken by a change, shipped, and left broken because
nothing in the normal loop observed it.
When
As soon as a diff touches: a login/logout route, token issuing or renewal, session storage, an auth middleware/guard, or a permission check. Also when adding a first protected route to a service that had none.
Steps
1. Token lifecycle: the expiry path is part of the feature
- Test the flow after expiry, not just after login. A login that works proves nothing about the refresh. Force the expiry (shorten the TTL in a dev config, or fast-forward the clock) and replay the journey: this is the only way to observe the renewal path.
- One refresh in flight at a time. Several parallel requests hitting a 401 together must not each fire their own refresh: queue them behind a single renewal, then replay them. Mechanism in section 4.7, including the cross-tab case that a shared promise doesn't cover.
- A failed refresh logs out cleanly, it never retries in a loop: a refresh that 401s and gets retried indefinitely spins forever and hides the real cause.
- The expiry margin is explicit: renew shortly before expiry, never exactly at it, or clock skew between client and server produces intermittent failures no one can reproduce.
- A permission/role change invalidates the current token, it doesn't wait for it to expire naturally. A demoted or revoked user keeps acting on their old permission set for the rest of the token's TTL otherwise — the refresh renews the token, it doesn't re-derive it from the user's current state unless the backend forces that on the next refresh/request.
- An absolute session lifetime, on top of the rolling per-token TTL. The refresh mechanism can otherwise renew a session indefinitely as long as the user stays active, which is a different guarantee from "expires N minutes after issue": a hard cap forces re-authentication periodically regardless of activity, bounding how long a hijacked session stays usable. NIST SP 800-63B-4 (sections 2 and 5.2) defines both an overall timeout and an inactivity timeout and ends the session when either expires; the overall timeout is required at every assurance level, the inactivity timeout is a SHOULD at levels 2 and 3 and optional at level 1.
2. Storage and transport
- Never a token in a URL, in any form. Not in the path, not in the query string, not in a
fragment. A URL is copied into server access logs, into browser history, into the
Refererheader sent to third parties, and into every proxy and analytics tool on the path. The only credential allowed to travel in a redirect URL is a short-lived, single-use authorization code, exchanged once against the backend (see the reference flow below). This is the one rule in this block we hold against pressure: some teams do ship SSO by handing the token over in the redirect URL, and adopting it "to be consistent with them" would be adopting the leak. RFC 6750 section 2.3 also discourages bearer tokens in a query string because URLs are logged and kept in history, and RFC 9700 section 4.3.2 forbids access tokens in query parameters. - A token lives in a cookie (
Secure,SameSite), never inlocalStorage:localStorageis readable by any injected script and survives with no expiry semantics. Why this pattern isn't also a CSRF exposure: classic CSRF relies on the browser attaching a cookie automatically to a cross-site request; here the frontend reads the cookie in JS and attaches it itself as aBearerheader, so a forged cross-site request arrives with noAuthorizationheader at all.SameSite=Strict/Laxis still set (defence in depth, and it's what stops the cookie itself being read cross-site), but the CSRF question is answered by the transport shape, not by a separate CSRF token. - Known trade-off in our own pattern, stated rather than hidden: our frontends set that cookie
client-side and attach the token themselves as a
Bearerheader, so the cookie is nothttpOnlyand an injected script can read it.httpOnly+ a server-set cookie is strictly stronger and is the target for a new service that can be built that way. NIST SP 800-63B-4 section 5.1 likewise recommends HttpOnly, the__Host-name prefix, SameSite Lax or Strict and an opaque identifier. On an existing frontend, don't half-migrate: a token that's both in a JS-readable cookie and expected in a header gains nothing until the whole chain moves. - Never a token in a log either, and a clean URL doesn't get you this for free: the usual leak
isn't the URL, it's logging a whole object that happens to carry the credential. Watch four
paths in particular:
- HTTP client error objects. A failed request's error carries the request config, headers
included.
logger.error(err)on it writes theAuthorizationheader out in full. - Exception reporters and breadcrumbs. Crash/APM tooling serialises request headers and cookies by default: the allowlist/denylist has to be configured, not assumed.
- Debug dumps of a request (curl-style replay lines, "request/response" trace logging): convenient precisely because they're complete, which is the problem.
- The token as a correlation key. Never use it to tie logs together; that's what a
correlation ID is for.
Redact at the point of writing, on the field name (
authorization,cookie,set-cookie,access_token,refresh_token), not by trusting call sites to pass the right thing. A token in a log is a valid credential sitting in a system with wider read access than the app itself, and with a much longer retention than the token's own TTL.
- HTTP client error objects. A failed request's error carries the request config, headers
included.
- Logout invalidates on the server side too: clearing the client store while the token stays valid server-side is not a logout. NIST SP 800-63B-4 section 5.1 asks for the session secret to be erased or invalidated at logout.
3. Authorisation: the check lives on the server
- Every permission check is enforced server-side; the frontend check only hides UI, it never grants anything: hiding a button is not a permission.
- The permission name is verified against what the backend actually exposes, never guessed from the feature's name: a guard wired onto a permission that doesn't exist fails open or fails closed depending on the framework, and both are bugs.
- Scoped access (per tenant/agency/organisation) is applied in the query, not filtered after the fact: filtering in the response means the data was already fetched, and one forgotten branch leaks it.
4. Our reference login flow
This is the shape already in production on two of our Nuxt frontends against a Laravel backend. A new frontend follows it rather than inventing a variant.
- Provider redirect. The
/loginpage hands off to the identity provider. The frontend holds no password and never sees one. - Callback with a code. The provider returns to a dedicated callback route carrying a
short-lived
codein the query. That page renders nothing but a progress state. - Exchange, once. The callback exchanges the code against the backend for an access token. Guard the exchange with a single-flight promise: a callback page can mount twice (a client remount, the user refreshing) and a single-use code replayed a second time fails, logging the user out at the exact moment they were logging in.
- Token into a cookie, then a Bearer header. The API layer reads the cookie and attaches
Authorization: Bearer …to every call. A401from any call triggers logout, in one place (the API plugin), not per call site. - Deny by default at the router. A global route middleware protects every route, with an explicit allowlist of public routes (login, callback, error/waiting pages). New routes are protected because they're new, not because someone remembered to protect them.
- Typed auth outcomes, not a boolean. The exchange and the refresh return an explicit state, distinguishing at minimum: authenticated, unauthenticated, awaiting account approval, and error. Each maps to its own destination. A boolean flattens "your account isn't approved yet" into "login failed", which sends the user to retry a login that can never succeed.
- Single-flight refresh, across tabs. Both implementations dedupe the refresh, but not
equally: an in-memory shared promise only dedupes inside one JS context, so two open tabs
still fire two refreshes and can invalidate each other. The reference is the stronger one: a
cross-context lock (
navigator.locks) around the refresh, plus aBroadcastChannelso the other tabs refetch the user on the new token instead of racing for their own. An in-memory promise alone is acceptable only where a single tab is guaranteed, which in a browser it never is. Throttling the refresh (don't renew if the last one is very recent) is a useful complement, not a substitute: it narrows the race window without closing it. - Teardown is complete. Logout calls the backend, then clears local state in a
finallyso a failing call can't leave a half-session behind. Clearing means the token and everything derived from the identity: user, permissions, feature flags, and the domain state scoped to that user. A leftover scoped selection is what leaks one user's context into the next session. TheClear-Site-Dataresponse header on the logout call is the browser-level equivalent for anything the app itself doesn't track (cache, storage, service workers) — cheap insurance on a shared machine. The W3C working draft (2017, not a standard) says its cookies directive clears cookies for the whole registered domain, cannot spare one cookie, and is best effort; expire a single cookie withSet-Cookieinstead.
5. Verification before shipping
- Replay the journey: login → expiry → refresh → logout, plus one protected route with an insufficient permission (expect a clean refusal, not a crash).
- Replay it a second time concurrently (two tabs on the same session) if the diff touched the refresh: that's where the race shows up.
- Then search the logs the replay just produced for the token value you were issued, and for
Authorization/Bearer. A clean grep is the evidence; assuming the redaction works is not. Do this on the error paths too, since that's where whole objects get logged.
6. Native, desktop and command-line apps (public clients)
Sections 1 to 5 describe a browser frontend with a backend. An app installed on a user's device is a public client: it cannot keep a secret. Read 2026-10-02 from the IETF documents on OAuth for native apps and on the proof key for code exchange (RFC 8252, RFC 7636).
- Sign in through the system browser, never an embedded web view. An embedded view lets the host app read the user's credentials and cookies, and makes the user sign in from scratch in each app. Open the authorization request in the external browser and receive the result back in the app.
- Use the authorization code flow with PKCE; the implicit flow is not recommended. The client generates a
random code verifier, sends a hash of it (method
S256) in the authorization request, and presents the verifier when redeeming the code, so an app that intercepted the code cannot use it. The verifier is 43 to 128 characters from a restricted alphabet and should carry at least 256 bits of entropy (32 random bytes encoded as URL-safe base64 gives 43 characters). UseS256whenever the client can; never fall back toplainafterS256was refused (the error means the server is misconfigured). The authorization server should refuse native requests without PKCE. The implicit flow cannot be protected by PKCE and cannot renew a token without the user, so a refresh token needs the code flow. - Pick the redirect to the app that fits the platform, and know its weakness. A claimed
httpsURL is the least exposed to interception. A private-use scheme works but several apps can register the same scheme and the code may reach the wrong one (PKCE covers that); name it from a domain you control in reverse order (a bare name such asmyappdoes not qualify, since it is not based on a domain). A loopback redirect (httpto127.0.0.1or[::1]with a free port chosen at request time) is the desktop option: bind the loopback interface only, open the port for the request and close it once the response arrives, prefer the IP literal tolocalhost, and try both IPv4 and IPv6. The server must accept any port on a loopback redirect and match the rest exactly. - Do not ship a client secret in the app. A secret embedded in a distributed app is readable by every user, so it identifies the app but proves nothing. The server must treat such a client as public.
- Send a random
stateand refuse any response that does not match a pending request. It blocks a forged response delivered through the inter-app channel. With several identity providers in one app, use a distinct redirect URI for each and reject a response that arrives on a different one, so one provider cannot replay another's response.
Output / checkpoint
The expiry/refresh path was observed, not assumed: evidence attached (log, network trace, or
screenshot of the renewed request succeeding). No auth diff reaches gate with only the login
path exercised.
Guardrails
- Never weaken a check to make a test pass: a test that only goes green with the guard removed is reporting a real problem.
- Never invent a permission name to unblock yourself: ask what the backend exposes.
- Rotating or revoking credentials/secrets in a shared environment is a human decision, not something the agent does on its own initiative.
- This block covers the application-level flow. Provider configuration (SSO, identity provider, realms) is infra reality and stays outside this repo.
Origin
Gap found while scouting a market agent catalogue, crossed with an internal incident (a refresh flow broken by a change and left broken). Section 4 is extracted from two of our own frontends. Transport rules follow session-management guidance, section 6 follows RFC 8252 and RFC 7636, and the 2026-10-20 pass added RFC 6750, RFC 9700, NIST SP 800-63B-4 and the W3C Clear-Site-Data draft. Full provenance and what is still unsourced: references/origin.md. 🟡: never run by us.