Repository navigation
Description
Goal
After this phase a person signed in at app.nemar.org can be sent to /oauth/authorize by a registered client, see what the client may do, consent, and be redirected back with a single-use authorization code and the iss parameter.
The backend decides everything; the website page renders its verdict and carries the person's click.
Routing
- Readiness: ready
- Implementer: Opus
- Opus checkpoint: review before merge (validation order, consent token, CSP and
form-action) - Depends on: Phase B2: OIDC client registry, signing keys and discovery #2016 ; Unblocks: Phase B4: OIDC token, userinfo, revocation and introspection #2018
- Repository and base branch: nemarOrg/nemar-cli, epic branch, plus one website PR into
staging
Scope
In: migration 0122, two session-bound routes, code minting, consent, the website page with its copy and headers.
Out: the token endpoint (#2018), revocation (#2019), a person revoking their own grants.
Design references
Design section 3 (Flow, Request handling, Who may sign in, Clients); ADR 0079 and 0056; OpenID Connect Core 3.1.2, RFC 6749 4.1.2.1, RFC 9207.
Changes
backend/src/db/migrations/0122_oidc_grants_and_codes.sql.oidc_grants:id,user_id,client_id(theoidc_clientsrow id), sorted JSONscopes,consent_kind(first_party|user),created_at,revoked_at, and a partial unique index for one live grant per user and client.oidc_codes:code_hash(primary key),client_id,user_id,grant_id,redirect_uri,scopes,nonce,code_challenge,auth_time,created_at,expires_at,used_at; used rows stay until an hour past expiry (pruned in the check route) so Phase B4: OIDC token, userinfo, revocation and introspection #2018 can detect replay.backend/src/routes/auth-oidc.ts, mounted at/authinindex.ts:POST /auth/oidc/authorize(check) andPOST /auth/oidc/consent(decide). Each runswebSessionMiddleware,isAllowedOrigin,no-storeand a per-account budgetcheckOidcAuthorizeBudget(30 a minute, modelled oncheckPrivateGrantBudget); check also answers a visitor with no session.- Validation order, in
backend/src/services/oidc-authorize.ts. Unknown or disabled client, or aredirect_urithat is not an exact registered string: answer{kind: "error_page", code}and never redirect. Then errors that redirect witherror,stateandiss:invalid_request(notresponse_type=code, a method other than S256, no challenge, a response mode other than query),request_not_supported,request_uri_not_supported,invalid_scope(openidabsent, or a catalogue scope the client may not have; scopes outside the catalogue are dropped),login_requiredandconsent_requiredforprompt=none. Acceptdisplay,ui_locales,login_hint; a validid_token_hintfor another subject forces re-authentication.prompt=loginor amax_ageolder than the session'screated_atanswers{kind: "reauth"}; the page sends the person to/login?next=withprompt=loginreplaced bynemar_auth_after=<unix seconds>, which check honours by requiring a newer session. - Sign-in rule from the client row:
active_accountneeds status active and no deletion;person_proven_orcidalso needs kindpersonand the proven-ORCID predicate, exported once asORCID_PROVEN_SQLinservices/oidc-identity.ts(used again by Phase B4: OIDC token, userinfo, revocation and introspection #2018 and Phase B5: OIDC revocation cascades and back-channel logout #2019). A failure answers{kind: "rule_refused", reason}(orcid_not_proven,account_not_person,account_inactive) with a prebuiltaccess_deniedreturn URL. - Consent: none for
first_party;ask_onceasks when the scopes are not a subset of the live grant;alwaysalways asks. A decision needs a consent token, an HMAC (domain tagoidc-consent-v1, keyOIDC_SECRET) over session id, client, redirect, scope set,state, challenge and a 10 minute expiry, returned by check and verified by consent. Deny returns theaccess_deniedredirect. - Minting: a code is 256 random bits via
generateGrantCode, stored withhashGrantCode, expiry 60 seconds SQL-side; the insert re-reads client status, account status and session liveness in its own WHERE clause (shape ofDOCS_MINT_INSERT_SQL). Response:{kind: "redirect", location}withcode,stateandiss. - Website PR:
src/pages/oauth/authorize.astro(GET and POST accepted, server-rendered, shape ofsrc/pages/auth/private/authorize.astro),src/lib/oidc-authorize.tsandsrc/lib/oidc-authorize-api.ts(shape ofprivate-authorize.tsandprivate-auth-api.ts),/oauthadded toAPP_ROUTE_PREFIXESinsrc/lib/host.ts,frame-ancestors 'none'andX-Frame-Options: DENYfor this path insrc/middleware.ts,no-store,no-referrer. The site-wideform-action 'self'blocks the redirect to the client after the consent post (Chrome applies it to the redirect chain), so the page sets an internal header with the one validated redirect origin andapplySecurityHeadersadds it toform-actionfor this path only, then deletes it. - Copy:
oidc.consent.*,oidc.rule.*andoidc.error.*keys inshared/contract/account-copy.ts, literal strings only, transcribed to the website'ssrc/lib/account-copy.ts. A non-first-party client's consent text says it can act as the person; withcompute.reserveorcompute.submitit says the client can reserve and spend the person's compute time. Wire shapes inshared/contract/oidc-authorize.tswith a website drift test.
Tests (write these first)
- Every refusal path above through
app.fetchwith a real session (issueSession): error page versus redirect,issandstatepresent. Mutation: accept a redirect differing by a trailing slash. - Sign-in rule: an ADR 0106 attested iD is refused, an
oauth_identitiesiD passes. Mutation: testusers.orcid_verifiedinstead. - Consent: first-party skips,
ask_onceasks again on a wider set, a forged, expired or other-session consent token is refused. - The code: 60 seconds, hashed at rest, bound to the session account, minted only while the client and account are live (revoke the account between check and consent).
prompt=nonewithout a session answerslogin_required; stalemax_ageandprompt=loginanswerreauth.- Website vitest: each kind renders, the path's security headers,
form-actionwidened only for the validated origin, copy drift.
Acceptance criteria
- Only exact registered redirect URIs ever receive a code or a redirect.
- A person can allow or deny; the page cannot be framed.
- Codes are hashed and expire in 60 seconds.
Gates
bun run typecheck, bun run lint, bunx biome check backend/src shared test, the new tests, test/account-copy-parity.test.ts, bun run migrations:d1-check, full bun test; website bun run lint, bun run typecheck, bun run test.
Rules that bite here
- Origin is checked before the session is acted on, and a missing Origin is refused (the website pins one).
- All timestamps SQL-side (
datetime('now', ...)), never from JavaScript. - Never echo request values into pages unescaped; never log
stateor a code. - The page must never enter the edge cache; check the bypass.
Escalate to the owner if
- The compute spend sentence needs the owner's wording.
When merged
Add the route names to design section 3; screens are documented in #2020.
Activity
neuromechanist commentedon Nov 4, 2026
Driver amendment, 2026-11-04, from the phase B1 Opus checkpoint (PR #2031). This comment is part of the phase brief; where it differs from the body above, this comment wins.
/oauth/authorizepage treat a session read under the LEGACY cookie name (nemar_session) as no session: sign-in is required again, and only a__Host-nemar_sessionsession can approve a grant. Phase B1 makes a__Host-cookie something only a sign-in mints, so this costs a returning person at most one extra sign-in.__Host-prefixed, no Domain.neuromechanist commentedon Nov 4, 2026
Backend merged into the epic branch by #2036 (squash 891fc97). Round 1 and an Opus delta review converged (one real hole found and fixed in round 2: with the flag off the ORCID link flow could be armed by a plain GET start; link now starts only from the Origin-checked POST). Targeted tests pass; every guard mutated; the real-browser Allow and Deny run passed 29 of 29 checks. Named red on the PR's CI: the website parity test, which reads website staging and clears when website #501 lands. The website page is nemarOrg/website#501: it merges only after the epic reaches dev and CI is re-run; its form must be live no later than this API. Owner decisions are listed in the PR body and on the private tracker.