# Auth Session Conventions

> Use when touching authentication, sessions, tokens or permission checks (login, refresh, logout, guards, middleware), the one surface where a regression stays invisible until it locks users out.

- Skill: `techmefr/auth-session-conventions` (Agent Skill, multi-file: 2 files)
- Install (CLI): `npx get-skill add techmefr/auth-session-conventions`
- Raw SKILL.md: https://api.skillmd.com/api/skills/techmefr/auth-session-conventions/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: techmefr (https://skillmd.com/u/techmefr)
- Updated: 2026-11-19
- Page: https://skillmd.com/skills/techmefr/auth-session-conventions

---


# 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
1. **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.
2. **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.
3. **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.
4. **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.
5. **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.
6. **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
1. **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 `Referer`
   header 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.
2. A token lives in a cookie (`Secure`, `SameSite`), never in `localStorage`: `localStorage` is
   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 a `Bearer`
   header, so a forged cross-site request arrives with no `Authorization` header at all.
   `SameSite=Strict`/`Lax` is 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.
3. **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 `Bearer` header, so the cookie is **not**
   `httpOnly` and 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.
4. **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 the `Authorization` header 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.
5. 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
1. Every permission check is enforced **server-side**; the frontend check only hides UI, it never
   grants anything: hiding a button is not a permission.
2. 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.
3. 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.

1. **Provider redirect.** The `/login` page hands off to the identity provider. The frontend holds
   no password and never sees one.
2. **Callback with a code.** The provider returns to a dedicated callback route carrying a
   short-lived `code` in the query. That page renders nothing but a progress state.
3. **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.
4. **Token into a cookie, then a Bearer header.** The API layer reads the cookie and attaches
   `Authorization: Bearer …` to every call. A `401` from any call triggers logout, in one place
   (the API plugin), not per call site.
5. **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.
6. **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.
7. **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 a `BroadcastChannel` so 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.
8. **Teardown is complete.** Logout calls the backend, then clears local state in a `finally` so 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. The
   `Clear-Site-Data` response 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 with `Set-Cookie` instead.

### 5. Verification before shipping
1. Replay the journey: login → expiry → refresh → logout, plus one protected route with an
   insufficient permission (expect a clean refusal, not a crash).
2. 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.
3. **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).
1. **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.
2. **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). Use `S256` whenever the client can; never fall back to
   `plain` after `S256` was 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.
3. **Pick the redirect to the app that fits the platform, and know its weakness.** A claimed `https` URL 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 as `myapp` does not qualify, since it is not based on a domain). A loopback redirect (`http` to `127.0.0.1` or `[::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 to `localhost`, and try both IPv4 and IPv6.
   The server must accept any port on a loopback redirect and match the rest exactly.
4. **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.
5. **Send a random `state` and 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`](./references/origin.md). 🟡: never run by us.

