Repository navigation
Phase B4: OIDC token, userinfo, revocation and introspection - #2042
Merged
Conversation
📦 Package PreviewYour package is ready to test! bun install -g nemar-cli@PR2042Version: 🤖 Updated on each push. |
neuromechanist
merged commit Nov 5, 2026
6b8711e
into
feature/issue-2014-epic-oidc-provider
2 checks passed
neuromechanist
deleted the
feature/issue-2018-phase4-oidc-token-userinfo-revocation-and
branch
November 5, 2026 01:04
This was referenced Nov 5, 2026
neuromechanist
added a commit
that referenced
this pull request
Nov 6, 2026
* Phase B1: ADR 0119, partner hosts, __Host- cookie and OIDC subject (#2031) * docs: ADR 0119, NEMAR as an OIDC provider * feat: exclude partner hosts from origin checks * feat: __Host- session cookie behind a flag * feat: users.oidc_subject and owner lookup * feat: reserve the nmu_ username prefix * docs: refresh compute notes for ADR 0119 * docs: ADR 0119 notes the single legacy clear * docs: ADR 0119 names the cookie exposure * docs: correct stale session cookie docblocks * fix: brand OidcSubject, correct shared docblocks * docs: say who deletes TOLERATED_GAPS entry * feat: __Host- names for the ORCID flow cookies * feat: reversible flag, slide and sign-out rules * test: name-aware session cookie in live tests * docs: ADR 0119 states the cookie principle * docs: refresh stale cookie comments, 0120 notes * fix: sign-out cascades for every carried account * docs: ADR 0119 rule 9 matches the Context * fix: name every account in the sign-out log * Phase B2: OIDC client registry, signing keys and discovery (#2033) * Add the OIDC scope, token and id vocabulary * Add migration 0121 for OIDC clients and keys * Add OIDC config and signing key service * Amend ADR 0119 rule 8: first-party needs NEMAR hosts * Serve OIDC discovery and keys on the issuer host * Add owner routes for OIDC clients and keys * Declare OIDC_SECRET as a Worker secret * Add nemar admin oidc commands * Retype OIDC vocabulary and share encoders * Add revoked key state and unique active names * Harden OIDC key rotation and add revocation * Tighten OIDC client registration rules * Close OIDC surface bypasses and cached errors * Add keys revoke and emergency rotation to the CLI * Record OIDC key and client decisions in ADR 0119 * Note what the key set cache depends on * Use router path, add --emergency, ADR note * Phase B3: OIDC authorization and consent (#2036) * Add the OIDC authorization wire contract * Add migration 0122 for OIDC grants and codes * Add the OIDC sign-in rule and ORCID proof * Add OIDC authorization and consent service * Add a per-account OIDC authorize budget * Serve OIDC authorize and consent routes * Add OIDC consent, rule and error copy * Record phase B3 rules in ADR 0119 * Correct the OIDC error copy comment * Treat an empty request parameter as omitted * Pin the OIDC authorize cap in the caps table * Mint a fresh session at every ORCID sign-in * Link an ORCID iD only from a __Host- session * Give OIDC codes a row id and strict times * Refuse a redirect query naming code or state * Move ID token reading into its own module * Sign the reauth marker, guard the caller * Show the redirect host on the consent screen * Say the authorization routes need the flag * Record round-1 authorization rules in ADR 0119 * Start an ORCID link only from the POST route * State the flag-off ORCID link residual * Phase B4: OIDC token, userinfo, revocation and introspection (#2042) * Add oidc_tokens table (migration 0123) * Add OIDC token, userinfo, revoke, introspect * Refuse OIDC tokens on every non-OIDC route * Add the oauth-ip rate limit bucket * Name the nemar.account claims in discovery * Test token statements, router and bearer * Use a plain string in the bearer test * Let the statement decide the refresh token * Record token rules 13 and 14 in ADR 0119 * Note the /oauth routes beside the cookie flag * Revoke on any second presentation of a code * Make the access expiry index partial * Revoke a refresh token's siblings on rotation * Revoke a used code only after PKCE matches * Serve userinfo and introspection in read-only * Seed owner-only data in the allowlist test * Bare bearer challenge, userinfo scope pinned * Omit token_type for a refresh token; type user * Test the content type and a late reuse * Scan the constant-time comparisons * Test database and signing faults * Test trimming, form decoding, grant binding * Correct the surface and bearer docblocks * Record round-1 token rules in ADR 0119 * Let the lost claim detect a code's replay * Refuse a retry once the first child was used * Exempt only POST in read-only maintenance * Record round-2 token rules in ADR 0119 * Correct the ADR 0119 index line * Test the grace's time limit on its own * Phase B5: OIDC revocation cascades and back-channel logout (#2045) * Add oidc_logout_deliveries (migration 0124) The intent row of a back-channel logout, and the closed words of an ending: reasons, statuses, error classes and the retry schedule. Tested on bun:sqlite and Miniflare D1; d1-check passes. * End OIDC grants in every credential cascade One cascade module (oidcEndStatements) is added to the batch of admin revoke, the owner soft delete and its sweep, ORCID unlink and relink, a kind change away from person, the owner end-account route and the client disable. It queues the logouts, revokes the tokens and grants and deletes unused codes. Role demotion, key revocation and sign-out are deliberate non-paths with tests. Tested through the real routes; each caller mutation-checked; caller count held by a source scan. * Send back-channel logouts after a cascade The sender signs a logout+jwt and posts it to the client's registered https address after the batch commits (waitUntil), never following a redirect, with a 5 second timeout, no answer body read and no credential. 5xx and network errors retry at 1m, 5m, 30m, 2h and 12h from a production-only 30 minute tick. A dev worker sends only to loopback or OIDC_LOGOUT_DEV_HOSTS and records the rest as fenced. Owner list view added. * Add end-account and logout-deliveries commands nemar admin oidc end-account (the manual merge step and incident tool) and logout-deliveries, and the disable command now reports what it revoked. * Run the cascade statements on Miniflare D1 Every cascade and delivery store statement, as the real functions build it, runs on D1 itself, where bun:sqlite accepts SQL that D1 refuses. * Record the OIDC cascade and logout in ADR 0119 Rule 12 gains the cascade function, its order, filters and caller list, rule 15 the delivery, token, request and fence, with consequences and open questions. Index line, AGENTS.md and implementation notes updated; wording pinned by test. * Refuse a loopback host with a trailing dot localhost. names localhost; the production address check now strips trailing dots before testing the host. Tested for production and dev. * Document the kind change and the dev hosts var The kind route comment names the grants it now ends; wrangler documents the absent OIDC_LOGOUT_DEV_HOSTS var; a userinfo test expects a disabled client's token row to be revoked. * Retry throttled logouts, close the class list A 408 or 429 is retried on the same six-attempt schedule with the class http_throttled; Retry-After is only a lower bound for the wait, capped at 12 hours, and only for those two. last_error_class is now a closed list in the unreleased migration, held equal as a set to the vocabulary for reason, status and class. * Prune finished logout deliveries in the tick The production tick deletes sent and fenced deliveries after 30 days and failed ones after 180, at most 500 a tick and after its delivery work, and never a pending row. The windows are named defaults in shared/oidc.ts for the owner to set before the first client registers. Dev has no tick and is not pruned. * Log a database fault in the first attempt attemptDueLogouts never throws, so the catch after it was dead and a fault in the first attempt (or the sweep's) left no trace. The tally is now logged as a count and the error's class, never its text, an address, a token or a subject. * Agree on a trailing dot and test the fence isLoopbackHost and isLocalOrLiteral fold a trailing dot, so registration of a logout or redirect address and the sender's check at send time agree. Tests: production ignores OIDC_LOGOUT_DEV_HOSTS for a local host that the list names, a stored address that is no longer sendable is recorded address_refused through the sender, dotted forms in the registry and verdict tables. * Test the lease, unreported and the pins Claimed-never-recorded attempts are taken up again when the lease lapses and failed as unreported once all six are used; the claim's two-minute lease is read from the database and pinned above the 5 second timeout; the timeout window is tight; the token-store reason test no longer feeds one list through itself. * Hold the cascade callers by every reference The caller scan now resolves import bindings of the cascade module (named, aliased, namespace, destructured, alias chains) and flags every other use outside it as a stray: a value, a raw SQL constant, a dynamic import, a re-export, a default import, a namespace element access, a module-level reference. Each way is planted and shown caught. * Correct the end-account text, tighten types The end-account question no longer says the person is asked again at every client (a first-party client does not ask), and the help says to pair the command with a revocation, deletion or kind change for a merge loser. The reason is a z.enum that never echoes a value, an unsent delivery's status and class are a typed pair, the soft delete and sweep paths get the restore test, and the stand-in reports the cause of an openssl failure. * Record the round-1 rulings in ADR 0119 Rule 12 says a new path adds to OIDC_END_CALLERS and to the docs and private lists only when it runs their statements, that only the sweep is guarded, and that a merge loser's end-account is paired with a revocation, deletion or kind change. Rule 15 decides throttling with Retry-After, unreported, the owner routes without the cookie flag, and retention; open points updated. * Drop kind change from the merge-loser steps A kind change away from person ends only the person_proven_orcid grants, and a non-person account still meets active_account, so it cuts no merge loser off. The end-account help and ADR 0119 rule 12 now say to run end-account and then revoke or delete the loser, and why in that order. Tested: kind change keeps active_account grants and signs in again; the merge procedure through the real routes; wording pins fail on the old text. * Cap a Retry-After of any length A run of 11 or more digits was read as no Retry-After, so a partner asking for the longest wait got the shortest. parseRetryAfter now accepts any run of digits and caps digits and dates at 12 hours; the cap lives there and recordOf only takes the longer of it and the schedule. Tested: 12, 25 and 400 digits through the sender and a pure parser table; restoring the 10-digit limit fails both. * Correct the delivery span and failed help With Retry-After capped at 12 hours, a failed row's last attempt can come about 63 hours after its creation, not under a day: the retention comment, ADR rule 15 and its consequences now say within three days, derived from the constants and pinned by a test. The logout-deliveries help now lists what is final and what is retried, read from a table of every status from 200 to 599 through the real sender. * Flag an exported alias of the cascade The caller scan saw no call and no value in export const endIt = oidcEndStatements, so a caller in another file could hide behind it. An alias whose name is exported by its declaration (const, let, var, a destructured pattern, a namespace member, a later assignment to an exported let) is now a stray, reported once. Both headers say a call that never runs, or whose result is discarded, passes the scan. Tested with the real scanner on planted source; removing the check fails it. * Phase B6: OIDC end-to-end test (S0, S1) (#2048) * Pin relying-party libraries for the OIDC test * Add OIDC end-to-end test with a real library * Declare OIDC token error words once * Check the token error type at compile time * Scope e2e hooks and add verifier controls * Pin openid-client 6.8.9 * Amend ADR 0119 on key re-encryption * Narrow the key recovery to current and next * List every verifier control in the e2e header * Guard the e2e hooks against failed setup * Phase B6: OIDC conformance rig and run (S4, S5) (#2049) * Add the conformance plan configurations * Add the conformance rig and its pre-flight * Pin the conformance suite images by digest * Add the OIDC conformance workflow * Accept a redirect as the suite being up * Run the suite scripts in their local mode * Let every Basic module run to its outcome * Give the rig a client for each purpose * Record the approved deviations and skips * Stop the rig and pin Python before upload * Test the expected files and workflow limits * Give each plan its own expected failures * Expect both client_secret_post failures * Accept a combined decision in the PKCE check * Say what the exported results copy * Log each authorization error the rig answers * Check the authorization errors before upload * Wait for the rig to exit before upload * Bound the suite start and lower the Basic limit * Say the suite goes on after the secret check * Test the PKCE refusal, scopes and the pre-flight * Test the authorization check and stop step * Fail on malformed authorization lines * Match strictly and report a missing log * Test the check's entry point and its step * Log a rule refusal as access_denied * Read an error in the redirect fragment * Count authorization requests against their lines * Test each kind of authorization line * Kill a rig that ignores the stop * State the residual risk of a global allowed set * Fix the tier claims in two OIDC test headers (#2053) * Claim the unit-pure tier in two OIDC headers * Fix OIDC test header wording * Add a process CI tier and move the two OIDC process tests into it (#2056) * Route CI TIER: process files out of unit-pure Add scripts/ci/process-files.sh, which lists the files whose header claims the process tier, and have unit-pure-files.sh skip them. The routing test reads the new pattern from the script. Tested: bun test test/ci-tier-routing.unit.test.ts. * Add the process-tier CI job One job, on the unit-pure trigger, that runs the files process-files.sh lists and refuses an empty list. No secrets, no sharding. Tested: routing test; actionlint shows only the three SC2086 notes already present on the base. * Move the two OIDC process tests to the process tier oidc-conformance-rig and oidc-e2e now claim CI TIER: process, with the reason stated. The routing test asserts they are listed by process-files.sh and absent from the unit-pure list. Tested: routing test; both files run on their own. * Run the process tier in the deploy gate The pure list skips process files, so test-gate gains a step that runs scripts/ci/process-files.sh with the same empty-list refusal. The routing test asserts the gate runs it. Tested: routing test, both OIDC files, actionlint, typecheck, lint. * Give the OIDC alias scan test 60 s (#2052) * Reword the OIDC compute-spend consent sentence (#2057) * Reword the OIDC compute-spend consent sentence * Update ADR 0119 consent screen wording * Remove the temporary conformance push trigger (#2059)
This branch was previously deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Phase B4 of the OpenID Connect (OIDC) provider epic (#2014), implementing #2018 with the amendment comments on it: migration 0123 (
oidc_tokens), the four/oauthendpoints (token, userinfo, revocation, introspection),oidcBearer(scopes), the refusal of an OpenID Connect token on every other route, the identity token's claims, and theoauth-iprate-limit bucket. A client can redeem a code with Proof Key for Code Exchange (PKCE) for an identity token, an opaque access token and (withoffline_access) a rotating refresh token, read userinfo, revoke and introspect, and use client credentials for machine-only scopes. Every endpoint answers 404 unless the request is on the OIDC surface ANDHOST_PREFIXED_SESSION_COOKIEis"1"(the authorization routes'oidcAuthorizeSurface), so production stays dark. No new use ofOIDC_SECRET(identity tokens are signed through the existing key path), so the per-purpose subkey derivation the B3 amendment asks for before a new use is not triggered here.Round 1 (Opus checkpoint and Sonnet verification review)
Every finding is fixed on this branch; migration 0123 is edited in place (unreleased).
kind = 'access', so the prune at the head of every minting batch no longer walks retained refresh rows. A test pins the index definition on bun:sqlite and Miniflare D1 and the prune's plan (both expiry indexes, no table scan). The prune is not bounded with aLIMIT: it deletes what expired since the last batch, which stays small.Make the access expiry index partialrefresh_superseded), in the rotation batch, only once this request's child exists. The revoke reasons are one closed list,OIDC_TOKEN_REVOKE_REASONS, and a test holds every statement to it.Revoke a refresh token's siblings on rotationRevoke a used code only after PKCE matches,Let the lost claim detect a code's replay(with the verifier first, the early used-code branch became redundant with the batch's lost claim, which revokes the same way; mutation M61 showed it, so the branch is gone and the lost claim is the one path)POST /oauth/userinfoandPOST /oauth/introspect; the token endpoint and revocation answer 503;fullrefuses all four. Tested through the real Worker in both modes, the legacy mount and longer paths included.Serve userinfo and introspection in read-only/notices, no credential's), and the owner's key to differ. The request count is 560 distinct requests, 1,120 calls (the earlier "1,119" counted log lines).Seed owner-only data in the allowlist testBearerchallenge has an empty body.Bare bearer challenge, userinfo scope pinnedtoken_type.Omit token_type for a refresh token; type userRecord round-1 token rules in ADR 0119application/json,text/plain, multipart or an empty type isinvalid_requestand spends nothing; the form type with acharsetparameter is read.Test the content type and a late reuseoidcBearerScopesexposes a made middleware's scopes and the inventory pins["openid"]on both routes.Bare bearer challenge, userinfo scope pinnedrefresh_reuse).Test the content type and a late reuseoidc-constant-time-source.test.tsholds the verifier and the client secret to the sharedtimingSafeEqual, with no equality operator on either.Scan the constant-time comparisonsoidc-token-faults.test.ts: a signing-key read or a batch that fails is a 5xx withno-store, spends and mints nothing, and the code redeems afterwards; a failed refresh batch neither rotates nor revokes; a failed lookup at userinfo and introspection is a 5xx, neverinvalid_tokenor{active: false}.Test database and signing faultsoidc-discovery.tsandoauth.tsname both guards (oidcSurfacefor discovery, the key set and the owner routes;oidcAuthorizeSurface, the surface and the cookie flag, for the authorization routes and the four endpoints).Correct the surface and bearer docblockslookupTokenreturns the token's own columns anduser: account or null; a machine token is never read as an account of NULL columns.Omit token_type for a refresh token; type user+as a space in the Basic pair (onreadBasicCredentials, since no NEMAR id or secret holds one), trimmed names, the grant binding inCODE_GATES(two cases, each differing in one clause; the clause is kept as defence in depth with a comment), andaccountTier's other branches, kept and unit-tested because they mirror the website's derivation for any other caller. Theoidc-bearer.ts,CODE_ACCOUNT_SQLand refresh test wording is corrected, and that test now covers the disabled client (401invalid_client, nothing spent).Test trimming, form decoding, grant binding,Correct the surface and bearer docblocksDecisions for the owner (ADR 0119 is
proposed; rules 13 and 14 are reworded)invalid_requestat the route), revokes nothing. The conformance phase (Phase B6: Sign in with NEMAR docs and conformance #2020) may expectinvalid_grantrather thaninvalid_requestfor malformed input to the token endpoint; which one NEMAR answers is the owner's call.POST /oauth/userinfoandPOST /oauth/introspect(POST only, exact paths; GET is served as every read is), refuses the token endpoint and revocation; in read-only no partner can refresh.The issue's "When merged" step (design section 3) is the driver's docs pull request.
Round 2 (Opus delta)
refresh_reuse). The sibling revocation drops its "unspent" condition: a spent sibling can no longer arise through the routes, and the store test that pinned a spent sibling as "not revoked" now pins it revoked. Worker-level tests through the real route: holder A refreshes and rotates again, then holder B presents the parent inside the 30 seconds (invalid_grant, every family row revoked, A's access token 401); the first child revoked before the retry; the first child still unspent (the retry works, and exclusivity holds); a middle generation three deep.Refuse a retry once the first child was used,Test the grace's time limit on its own(the full re-run showed M22, the grace's time limit, masked by the new untouched-child check in the existing test; a test with the first child untouched and the parent past 30 seconds now isolates it)c.req.method === "POST" && READ_ONLY_OIDC_READS.has(path). PUT, DELETE and PATCH on/oauth/userinfoand/oauth/introspectanswer 503 (tested); the maintenance test's docblock no longer says "whatever their method".Exempt only POST in read-only maintenance.context/decisions/README.mdis corrected to match.Record round-2 token rules in ADR 0119,Correct the ADR 0119 index lineWhat changed
backend/src/db/migrations/0123_oidc_tokens.sql:oidc_tokens(token_hashunique SHA-256,kind,client_idas the client ROW id,user_id,grant_id,code_id,family_id(32 hex),parent_id,audience,scopes,expires_at,absolute_expires_at,used_at,revoked_at,revoked_reason,created_at). CHECKs: an account's token has a grant, a code and a family and a client's token has none; access lives at most 900 seconds and has no absolute expiry or spend; refresh lives at most 30 days, never past its absolute expiry, which is at most 90 days after it; every time is indatetime()'s own form (datetime(x) IS x), so text comparison is time comparison; revoked time and reason together; reason is a shape (lowercase, digits,_, at most 40), not a closed list, so Phase B5: OIDC revocation cascades and back-channel logout #2019 adds its words without a rebuild. Partial indexes on family, user, code and parent, and indexes on both expiries for the prune. No foreign keys (as 0121 and 0122).backend/src/services/oidc-tokens.ts: the store (values, hashes, every statement as an exported*_SQLconstant) and the three grants, revocation and introspection.backend/src/services/oidc-claims.ts: claims per scope, stated once for the identity token and userinfo.backend/src/services/account-tier.ts:accountTier(status, serviceAccess)(unverified,base,upload, mirroring the website'sderiveAccountTier).backend/src/services/oidc-clients.ts:authenticateClient(client_secret_basiconly) andstillFirstParty.backend/src/routes/oauth.ts, mounted at/oauthinindex.tsbeside the discovery router (which keeps/oauth/jwks).backend/src/middleware/oidc-bearer.ts:oidcBearer(requiredScopes), which setsc.var.oidcToken(client, account with its claim columns from the same read, scopes, audience);isOidcBearerMiddlewarelets a route table be checked for it by reference.backend/src/middleware/auth.ts:resolveApiKeyUseranswersoidc_tokenfor anynmo_value before the length floor and before any lookup;resolveBearerUsermaps it to 401{error, code: "oidc_token_not_accepted"};optionalAuthMiddlewaretreats it as no identity;rpc/principal.tsmaps it toinvalid_credential. TypeScript holds every switch exhaustive.backend/src/middleware/rateLimit.ts: theoauth-ipbucket, 2,000 a minute per address, for exactly/oauth/token,/oauth/revokeand/oauth/introspect(the/nemarspelling included), chosen before the bearer branch. Userinfo carries a bearer access token and rides the token bucket.shared/oidc.ts:nemar.accountnamesnemar_kind,nemar_status,nemar_tier;claims_supportedaddsauth_timeandat_hash.backend/src/index.ts:__workerRouteTable()(a function, not the app: an exported object withfetchcould be read as an entrypoint) for the allowlist test.routes/callbacks/bounded-json.ts:readCappedexported and reused for the form body.proposed): rules 13 and 14 added, the claim names in rule 6's table, a consequence (spent refresh rows), receipts; the index line in.context/decisions/README.mdextended;test/adr-0119-wording.unit.test.tspins both rules.backend/src/types/bindings.tsandbackend/wrangler-sccn.tomlname the/oauthendpoints beside the authorization routes.The order every token request walks
oidcAuthorizeSurface(404 as an unrouted path), thennoStore(Cache-Control: no-storeandPragma: no-cacheon every answer from there on).application/x-www-form-urlencoded, at most 16 KiB (declared and counted), UTF-8, no parameter twice; otherwiseinvalid_request.client_secretorclient_assertionin the body refused even beside a valid header, aclient_idin the body only if it is the header's. Any failure: 401invalid_clientwithWWW-Authenticate: Basic realm="oauth", charset="UTF-8".grant_type, and the client must be allowed it (unauthorized_client).code,redirect_uriand a verifier of 43 to 128 unreserved characters are required (invalid_request). The code is read: unknown or another client's isinvalid_grantand writes nothing; the verifier against the S256 challenge and the redirect address are compared in constant time, and a mismatch writes nothing, used code or not; a used code of this client that matches is a second redemption at once (as below). The identity token is signed before the batch (a signing failure mints nothing). One batch: prune; the access tokenINSERT ... SELECTwhose WHERE is the issue's claim predicate verbatim (code_hash = ? AND client_id = ? AND used_at IS NULL AND expires_at > datetime('now')) plus the gates (client active and allowed the grant, the account's subject and the client's sign-in rule read live, the grant live and this account's to this client, every code scope within the grant and the client's allowed scopes, none machine-only); the refresh token only beside that access token row and only withoffline_accessin the code and the refresh grant on the client; andUPDATE oidc_codes SET used_atonly when this request's access token row exists. The access token INSERT'smeta.changesis the winner. A loser whose code is used by now is a second redemption:CODE_REPLAY_REVOKE_SQLrevokes every token whosecode_idis the code's (rotations carry it), reasoncode_replay, and nothing else is written.invalid_grantand writes nothing; ascope(empty is omitted) must be catalogue names within the token's (invalid_scope, nothing spent); afirst_partygrant whose client no longer qualifies isinvalid_grantwith no write. One batch: prune; the child INSERT (parent live, unrevoked, this client's; client active and allowed refresh; grant live, of the consent kind read; account passes; and EITHER unspent with no child OR spent under 30 seconds ago with exactly one child); the access token beside the child;used_atset on the parent only if unset; and the presented token's unspent refresh siblings revoked (refresh_superseded, round 1), only once this request's child exists. A loser runsREFRESH_REUSE_REVOKE_SQL, which re-checks in its own WHERE that the parent is revoked, or spent past 30 seconds, or retried already, and only then revokes the whole family (refresh_reuse).scopemeans the client's own machine-only scopes; any scope that is not machine-only, unknown or not the client's isinvalid_scope; one access token, no account, grant, code or family.Decisions made inside the issue's freedom (for review)
routes/oauth.tsmounted at/oauth. The issue said to extend the router Phase B2: OIDC client registry, signing keys and discovery #2016 mounted for the key set; Phase B2: OIDC client registry, signing keys and discovery #2016 put/oauth/jwkson the discovery router mounted at/, so the four endpoints are their own router beside it (its table is pinned inoauth-route-inventory.test.ts).INSERT ... SELECT, andused_atis written by a second statement of the same batch only when that request's token row exists. AnUPDATEfirst cannot tie a laterINSERTof the same batch to THIS request's claim except by trusting that a used code always has its tokens; and a claim whose mint then failed (an inactive account) would burn the code. Winner: the INSERT'smeta.changes.invalid_grantand writes nothing, used code or not. Whoever redeemed the code first held the right verifier, so a second redemption by the legitimate client still matches and still revokes everything the code issued (code_replay); someone who captured a victim's code cannot have the legitimate client present it again with another verifier to end the victim's tokens. Another client's code, used or not, is refused and writes nothing.invalid_request, checked before any read; a well-formed wrong one isinvalid_grant. A missingredirect_uriisinvalid_request; a different one isinvalid_grant.code_id, rotations included, soCODE_REPLAY_REVOKE_SQLis onecode_idmatch and still ends the family.family_idis 32 random hex per redemption. A rotation's child refresh token and the access token minted with it both name the presented token asparent_id.refresh_superseded), so whichever is rotated first wins; the other, presented later, is a revoked token and revokes the whole family (refresh_reuse). A single session that refreshed twice keeps working with whichever answer it stored; two holders of one token cannot both go on rotating. A third presentation of the parent inside the 30 seconds, any presentation after, or a revoked token revokes the family.used_atis set once, so the 30 seconds run from the first rotation. The siblings' access tokens are left to expire (one of them may be the one the rotating session is still using).invalid_grantand writes nothing. Another client's refresh token isinvalid_grant, writes nothing, and never revokes that family.scopeis omitted (RFC 6749 3.2); a named scope must be in the catalogue and in the refresh token's scopes (invalid_scope, nothing spent); the access token gets the narrowed set and the new refresh token keeps its own (RFC 6749 section 6). No identity token on refresh.first_partygrant whose client no longer qualifies (re-checked withisFirstPartyRedirectover every redirect, as the B3 amendment asks) is refused at refresh with no write; it is not revoked here (Phase B5: OIDC revocation cascades and back-channel logout #2019). The consent kind read is bound into the rotation's INSERT.offline_accessin the code, the refresh grant on the client); the answer carries one only when its row exists.scopeget the client's own machine-only scopes; an unknown, person-granted or unallowed scope isinvalid_scope(unknown names are refused here, unlike the authorization request, which drops them); a client disabled between authentication and the insert isinvalid_client.client_idin the body is allowed only when it equals the header's (RFC 6749 3.2.1);client_secret,client_assertionandclient_assertion_typein the body are refused; the challenge isBasic realm="oauth", charset="UTF-8". The body is read (and bounded) before the client authenticates.invalid_client;{error, error_description}only, the description a fixed sentence;Pragma: no-cachebesideno-store.WWW-Authenticate: Bearerwith an empty body and no error code anywhere (RFC 6750 3.1, round 1); invalid isBearer error="invalid_token"; a missing scope is 403Bearer error="insufficient_scope", scope="...". GET and POST answer alike, and both require exactlyopenid(pinned by the router inventory, round 1).nameis the given and family names joined;orcidandorcid_verifiedonly for an account with a well-formed iD (neither otherwise);nemar_tierisbaseoruploadfrom a newaccountTierthat mirrors the website'sderiveAccountTier;nemar_statusisusers.status;nemar_kindisusers.account_kind.claims_supportedgainsauth_time,at_hashand the threenemar_claims.token_type(RFC 7662 defines it for access tokens, round 1); an access token to its client or to a caller whoseintrospection_audiencesholds its audience; a spent refresh token is inactive; the active answer isactive, scope, client_id, token_type ("Bearer", access tokens only), exp, iat, sub (account tokens only), aud, iss; inactive is exactly{"active": false}. A database fault is a 5xx, never{"active": false}.client_revoked); 200 with an empty body.oidc_tokencovers everynmo_value (access, refresh and client secret), checked before the length floor. On an optional-auth route the token gets the anonymous answer (withauthAttempted, as any bearer does), exactly as an unknown key does.oauth-ipis 2,000 a minute, the same as the website'ssite-ip(one address answering for many people).oidc-harness.ts'scallkeeps an explicitContent-Type(it used to force JSON). B2's discovery test used/oauth/tokenas its example of a limited path in the generic bucket; that path now has a bucket of its own, so the test uses/oauth/userinfothere and checks the token endpoint's own bucket separately.Deviations from the issue text
invalid_request, notinvalid_grant(and, after round 1, a used code presented with a missing or malformed verifier or redirect revokes nothing; the owner's call whether Phase B6: Sign in with NEMAR docs and conformance #2020 needsinvalid_grantthere).authAttemptedand a private dataset then answers "your key was rejected" rather than "not found"; for/notices, where that flag plays no part, the token's answer is also asserted equal to no credential's./oauth/token,/oauth/revokeand/oauth/introspectfor the new bucket, and that is what is built; userinfo is not in it.bun test; by the amendment of 2026-11-04 only targeted suites were run.What to look at (checkpoint)
ACCESS_FROM_CODE_SQL,REFRESH_FROM_CODE_SQLandCODE_SPEND_SQL(services/oidc-tokens.ts): that one batch cannot mint twice, and that a refused mint writes nothing.REFRESH_CHILD_SQL(the two branches of the finalAND) andREFRESH_REUSE_REVOKE_SQL(the same condition, re-checked): the retry, the third presentation, the presentation past 30 seconds, a revoked token.TOKEN_LOOKUP_SQL'sactiveexpression: everything a use re-reads, theLEFT JOINs, and a client credentials token.resolveApiKeyUser's prefix check andoidc-token-allowlist.test.ts: the request list comes from__workerRouteTable(); the comparison of an access token with an unknown key; the count of routes that answeredoidc_token_not_accepted.claimsForScopes(services/oidc-claims.ts) and the claim tests: theorcid_verifiedproof isORCID_PROVEN_SQL, neverusers.orcid_verified.authenticateClient(services/oidc-clients.ts): the form decoding, the body credentials, theclient_idmatch.REFRESH_SIBLINGS_REVOKE_SQL); a used code revokes only after its verifier and redirect match, through the batch's lost claim; no identity token on refresh; notoken_typefor a refresh token at introspection; read-only maintenance serving POST userinfo and introspection.0123_oidc_tokens.sql),REFRESH_SIBLINGS_REVOKE_SQLand its place in the rotation batch, the reordered redemption,READ_ONLY_OIDC_READSinmiddleware/maintenance.ts,lookupToken's shape, and the new fault, maintenance and source-scan suites.Tests
New, all through the REAL Worker over every migration on bun:sqlite unless named otherwise (counts at the head):
backend/test/oidc-token-endpoint.test.ts(33): the surface; client authentication (no header, wrong secret, unknown client, malformed headers, a CLI key,+and percent decoding, secrets and assertions in the body, a disabled client, the previous secret inside and after its grace); the request's shape (a valid form under the wrong content type included); the full PKCE flow from the real authorization routes, the identity token verified against the published key set,at_hash,auth_time,nonce; wrong verifier, verifier bounds, wrong and missing redirect, another client's code, unknown and expired codes, all writing nothing; a second redemption; a used code with a wrong verifier or redirect, or a missing or malformed one, revoking nothing; a replay after a rotation; two redemptions forced to interleave withwrapD1; the sign-in rule and grant re-read; the code's scopes; refresh token only withoffline_access; a machine scope on a code; client credentials.backend/test/oidc-token-refresh.test.ts(23, round 2 adds a late retry after the first child was rotated, after it was revoked, while it is untouched, three generations deep, and past the grace with the child untouched): rotation; the retry; a third presentation; the two-holder scenario ending with the family revoked (either holder first); one session that refreshed twice keeping either answer; past the grace; 25 seconds; a spent token after its own expiry; a revoked token; idle and absolute expiry; narrowing and widening; another client's token; inactive account, revoked grant, disabled client; a first-party client that stopped qualifying; the refresh grant.backend/test/oidc-token-resources.test.ts(21): claims scope by scope (GET and POST), attested and mismatched iDs, missing and padded name parts, the tier andaccountTier's other branches, live reads; every userinfo refusal by both methods, the bare challenge's empty body; revocation; introspection (notoken_typefor a refresh token).backend/test/oidc-token-store.test.ts(30), on bun:sqlite AND Miniflare D1: the table's CHECKs, the partial index and the prune's plan, every statement gate by gate (the grant binding and the sibling revocation included), and the closed list of revoke reasons.backend/test/oidc-token-allowlist.test.ts(6): every route of__workerRouteTable()(560 distinct requests, 1,120 calls) answers a live access token as an unknownnm_key;oidc_token_not_acceptedwherever the key path refused; seeded owner-only data and the owner's own key prove the optional-auth comparison can fail; no answer carries the account's username, email or subject; refresh token and client secret;resolvePrincipal;oidcBeareronly on userinfo.backend/test/oidc-token-maintenance.test.ts(5, POST only),backend/test/oidc-token-faults.test.ts(4),backend/test/oidc-constant-time-source.test.ts(3),backend/test/oidc-bearer.test.ts(5),backend/test/oauth-route-inventory.test.ts(3).backend/test/rate-limit-buckets.test.ts: theoauth-ipbucket (5);rate-limit-site-identity.test.ts: the caps table.oidc-catalogue.test.ts,oidc-discovery.test.ts,test/adr-0119-wording.unit.test.ts(rules 13 and 14, round 1 wording), the harness'scall(keeps an explicitContent-Type).Mutation evidence
Each a single exact edit of one guarded line or block (the runner refuses an edit that matches zero or two places), run with the guarding test file as its own argument, the file restored byte for byte,
git status --porcelainclean after. On the head commit: 92 mutations, 91 killed. The one survivor is M56, by design: the TypeScript early refusal of another client's code before PKCE is compared; its SQL twin (the claim'sclient_id = ?, M05) is the guard and is killed on its own. M57 and M61 were removed from the code after earlier runs showed each masked by a proven twin. R03 and R07 targeted text that round 2 replaced; Q07 and Q09 are their successors, and R08 now widens the POST-only exemption to every/oauth/path.Round 2 (Q01 to Q09):
oidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-store.test.tsoidc-token-maintenance.test.tsoidc-token-maintenance.test.tsRound 1 (R01 to R26):
oidc-token-store.test.tsoidc-token-refresh.test.tsoidc-token-store.test.tsoidc-token-store.test.tsoidc-token-endpoint.test.tsoidc-token-maintenance.test.tsoidc-token-resources.test.tsoidc-token-resources.test.tsoidc-token-refresh.test.tsoidc-token-endpoint.test.tsoidc-token-resources.test.tsoidc-token-refresh.test.tsoidc-constant-time-source.test.tsoidc-constant-time-source.test.tsoidc-token-faults.test.tsoidc-token-faults.test.tsoidc-token-faults.test.tsoidc-token-faults.test.tsoidc-token-endpoint.test.tsoidc-token-resources.test.tsoidc-token-store.test.tsoidc-token-store.test.tsoidc-token-resources.test.tsoidc-token-allowlist.test.tsCarried from the first submission and re-run on the head:
oidc-token-allowlist.test.tsoidc-token-endpoint.test.tsoidc-token-store.test.tsoidc-token-endpoint.test.tsoidc-token-store.test.tsoidc-token-store.test.tsoidc-token-endpoint.test.tsoidc-token-endpoint.test.tsoidc-token-endpoint.test.tsoidc-token-store.test.tsoidc-token-endpoint.test.tsoidc-token-store.test.tsoidc-token-endpoint.test.tsoidc-token-endpoint.test.tsoidc-token-endpoint.test.tsoidc-token-endpoint.test.tsoidc-token-endpoint.test.tsoidc-token-endpoint.test.tsoidc-token-endpoint.test.tsoidc-token-store.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-store.test.tsoidc-token-store.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-store.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-refresh.test.tsoidc-token-store.test.tsoidc-token-refresh.test.tsoidc-token-resources.test.tsoidc-token-resources.test.tsoidc-token-resources.test.tsoidc-token-resources.test.tsoidc-token-resources.test.tsoidc-token-resources.test.tsoidc-token-resources.test.tsoidc-token-resources.test.tsoidc-token-endpoint.test.tsoidc-token-store.test.tsoidc-bearer.test.tsoidc-token-resources.test.tsoidc-token-endpoint.test.tsoidc-token-endpoint.test.tsoidc-token-endpoint.test.tsoidc-token-resources.test.tsoidc-token-resources.test.tsrate-limit-buckets.test.tsoidc-token-endpoint.test.tsoidc-token-store.test.tsoidc-token-store.test.tsoidc-bearer.test.tsoidc-token-endpoint.test.tsGates
Round 2 (head
77ac26b2):bun run typecheck: exit 0.bunx biome checkon the 6 TypeScript files round 2 touches:Checked 6 files ... No fixes applied.; on the 33 the whole PR touches:Checked 33 files ... No fixes applied.bun run migrations:d1-check: not run in round 2, because migration 0123 did not change (it ran once at the end of round 1:All migrations applied on real D1.Catalog matches bun:sqlite (177 objects, 53 tables). OK.).oidc-*,orcid-*andoauth-*suite,maintenance,rate-limit-buckets):Ran 870 tests across 36 files.870 pass, 0 fail. The B4 suites among them: refresh 23, store 30 (bun:sqlite and Miniflare D1), endpoint 33, resources 21, maintenance 5, faults 4, allowlist 6.adr-0119-wording,adr-index:Ran 21 tests across 2 files.21 pass, 0 fail.Round 1 (head
4e36b660):bun run lintChecked 179 files ... No fixes applied.; the wider targeted set (the API-key path suites too)Ran 1664 tests across 54 files.1664 pass; root ADR and admin suites 65 pass; repo-widebunx biome check backend/src shared testFound 41 errors. Found 29 warnings., all in 9 files this PR does not touch.Not run
bun test: not run, would check every suite in one process because the owner's rule of 2026-11-04 runs it only when the epic goes todev.For the driver or the owner
nemar_kind,nemar_statusandnemar_tier, and rules 13 and 14's behaviour, in design section 3 ofadmin/design/compute-gateway(the issue's "When merged" step; ADR 0119 is done here).oidcBearerexposes the token's audience but does not check it; a compute route that serves one audience checks it itself (the compute epics).