Government Sign-In with OIDC
Updated
IntermediateWhat you'll learn
~35 min- Build an OIDC (OpenID Connect, the standard sign-in protocol most identity providers speak) authorization-code flow with PKCE (a one-time proof that the party finishing sign-in started it), state and nonce, as a confidential client (a server-side app that holds a client secret)
- Keep the session in your app: an opaque cookie id and a server-side record that holds the user, never the provider's tokens
- Set session lifetime as one named constant that your ISSO (the security officer who signs off on your system's controls) owns, and separate it from the AC-11 inactivity control
- Prove expiry at the constant, a new session id at sign-in, logout that invalidates the server-side session, and a forged state refused by a local mock provider
Auth in a government stack
You will build workforce sign-in against whichever identity provider (IdP) your agency runs, speaking the standard protocol through one library, openid-client, rather than a vendor SDK or a framework wrapper. Four things come out of it: a sign-in flow, a session the application owns, one constant that sets how long that session may live, and tests that fail if any of those drift.
The provider is not in the code. It arrives through the platform seam: platform.identity holds the issuer URL, the client id, the name of the secret that holds the client secret, the scopes, and a rolesFrom function. The worked example runs on the local implementation, which points at a mock provider on your laptop. Each platform lesson points the same code at a real one:
- Lesson 34: Microsoft Entra ID in Azure Government. MSAL, Microsoft’s own sign-in library, is the alternative to
openid-clientthere. - Lesson 35: the agency’s IdP behind an Application Load Balancer
authenticate-oidcrule, where the load balancer runs the flow and your app verifies the signedx-amzn-oidc-dataheader. Amazon Cognito is not available on the load balancer in GovCloud (AWS GovCloud ELB page). - Lesson 36: Google’s identity service or the agency’s IdP.
| Problem | The pattern | Where your platform lesson lands it | You decide |
|---|---|---|---|
| Who is the user | OIDC authorization code with PKCE, state and nonce, from a confidential client | 34: Entra ID, openid-client or MSAL · 35: agency IdP behind an ALB rule, verify the signed header · 36: Google or the agency IdP | Where identity is terminated |
| Where the session lives | Opaque id in a cookie, state on the server, no provider tokens kept | Unchanged on every platform; only the shared store behind SessionStore is the platform’s | Whether revocation must be immediate |
| How long it lives | One constant, set by the ISSO | Unchanged | The numbers, in writing |
| Where roles come from | platform.identity.rolesFrom(claims) returns the provider’s raw names; Lesson 5 maps them | 34: the roles claim · 35: claims in the IdP’s userinfo response · 36: the provider’s claim of record | Which source your directory team can maintain |
Plan the change with your agent
In gov-dev-reference-app, src/lib/auth/oidc.ts already ships so npm test runs out of the box, while the Next.js session and route files (session-config.ts, provider.ts, session.ts, src/app/auth/*, src/proxy.ts) belong to your Next.js app layer (audit src/lib/auth/oidc.ts against the checklist below, or run git rm src/lib/auth/oidc.ts on a practice branch to watch the agent build it from scratch). Open your workspace agent at the project root with the project-memory file from Lesson 2 in place, switch to Plan mode (Shift+Tab, /plan, or the desktop app’s mode picker), and start with a short request:
Read src/platform/types.ts and our project-memory file, and plan an OIDC sign-in and app-owned session layer using openid-client without next-auth or vendor SDKs. Ask me anything unclear before writing code.What to check in the plan before you approve
src/lib/auth/session-config.tsexportsSESSION_MAX_SECONDSas one named constant owned by the ISSO (not a NIST number) andSESSION_COOKIE = "__Host-app_sid".src/lib/auth/oidc.tsusesopenid-clientauthorization code flow withS256PKCE,state, andnonce, passesoidc.enableNonRepudiationChecksto discovery, and gets raw role names fromidentity.rolesFrom(claims).src/lib/auth/provider.tsbuilds the client fromgetPlatform()and fetches the client secret viaplatform.secrets.get(identity.clientSecretName).src/lib/auth/session.tsstores only{ createdAt, user, pending }on the server (no provider tokens), rotates to a fresh session ID inestablishSession(), and throws a 401SafeErrorinrequireSession()when missing or expired.- Login, callback, and logout route handlers set
HttpOnly,Secure,SameSite=Laxcookies, andsrc/proxy.tsdoes only a coarse cookie-presence redirect on the Node runtime.
If the agent’s initial plan keeps provider tokens in the session or skips session ID rotation at sign-in, nudge it before approving:
Do not store provider tokens in the session record, and rotate to a fresh session ID when callback finishes login.What you get
- Typed in the terminal:
claude - Mode:Plan mode
- You type in the session: Read src/platform/types.ts and our project-memory file, and plan an OIDC sign-in and app-owned session layer using openid-client without next-auth or vendor SDKs. Ask me anything unclear before writing code.
- The tool replies: I read src/platform/types.ts and AGENTS.md. Proposed plan: 1. src/lib/auth/session-config.ts: SESSION_MAX_SECONDS (ISSO-owned constant) and SESSION_COOKIE = "__Host-app_sid". 2. src/lib/auth/oidc.ts: clientFor, startLogin, and finishLogin using openid-client with S256 PKCE, state, nonce, and enableNonRepudiationChecks. 3. src/lib/auth/provider.ts: load identity and client secret via getPlatform() and platform.secrets.get(). 4. src/lib/auth/session.ts: server-side SessionStore holding user and pending state, plus requireSession(). 5. /auth/login, /auth/callback, and /auth/logout routes plus coarse redirect in src/proxy.ts. Should callback rotate the session ID when redeeming the code, and should we retain any ID or refresh tokens?
- You type in the session: Do not store provider tokens in the session record, and rotate to a fresh session ID when callback finishes login. Approved to build.
- The tool replies: I created these files: - src/lib/auth/session-config.ts: SESSION_MAX_SECONDS and SESSION_COOKIE - src/lib/auth/oidc.ts: clientFor, startLogin and finishLogin over openid-client, with S256 PKCE, state and nonce - src/lib/auth/provider.ts: builds the client once from getPlatform(); the client secret is read with platform.secrets.get(identity.clientSecretName) - src/lib/auth/session.ts: SessionStore, establishSession, destroySession, isExpired, requireSession - src/app/auth/login, callback and logout route handlers - src/proxy.ts: cookie-presence redirect only The session record holds { sub, issuer, roles, name } and the pending { verifier, state, nonce } between redirect and callback. It holds no provider tokens.
- You type in the session: Where does the issuer get checked now? I do not see an assertTenant.
- The tool replies: There is none, on purpose. finishLogin calls authorizationCodeGrant, and that call validates the ID token before it returns: the signature against the provider's published keys, the issuer from discovery, the audience against our client id, the nonce we sent, the state, and the PKCE verifier. A token another issuer signed fails inside that call. A second hand-written comparison would only repeat the library. The failure you can still cause is configuration: if platform.identity.issuer points at the wrong provider, every sign-in fails, and the env test below shows that.
- You type in the session: Run the env tests against the local mock provider.
- The tool replies: npm run test:env Test Files 4 passed (4) Tests 6 passed (6) The two that matter here: 1. The mock provider signs in caseworker-0042 and finishLogin returns { sub: 'caseworker-0042', issuer: 'http://localhost:8080/default', name: 'Test Caseworker', roles: ['Intake.Operator'] }. The role name is the provider's raw value, as rolesFrom returned it. 2. With the state in the callback URL replaced by 'forged', finishLogin is refused with the cause: unexpected "state" response parameter value.
- You type in the session: Now write the unit tests for expiry, a new id at sign-in, and logout. Import the constant.
- The tool replies: Created src/lib/auth/session.test.ts with three groups: 1. expiry: valid one second before SESSION_MAX_SECONDS, expired at SESSION_MAX_SECONDS 2. rotation: after establishSession the old id is gone, the new id differs, and the stored user is exactly the one passed in 3. logout: after destroySession, loading the session id returns nothing All three import SESSION_MAX_SECONDS rather than repeating a number, so the ISSO can change the constant without editing the tests.
Illustrative session; exact output varies by tool and agency configuration.
Now read what it wrote, in the order a request meets it.
The client: discovery, PKCE, state and nonce
The library fetches the provider’s published configuration from its issuer URL (OIDC discovery), so the code needs the issuer, a client id and a client secret, and nothing vendor-specific. Three values protect the round trip. PKCE (Proof Key for Code Exchange) makes a stolen authorization code useless on its own: you send a hashed challenge on the redirect and the original verifier when you redeem the code. state ties the callback to the browser that started it. The nonce ties the ID token to this login attempt. All three are generated per login and kept server-side in pending.
REFERENCE CODE src/lib/auth/oidc.ts: OIDC authorization-code client with PKCE, state, and nonce open reference hide reference Reference implementation from gov-dev-reference-app; open to inspect or compare with what your agent builds.
// Workforce sign-in against the identity provider of record (lesson 03): authorization// code with PKCE, state and nonce, as a confidential client. The provider comes from// the platform seam; this file never names a vendor. Lesson 34 points it at Entra ID in// Azure Government, 35 at the agency IdP behind AWS, 36 at Google or the agency IdP.import * as oidc from 'openid-client';import type { Identity } from '../../platform/types.ts';
export interface PendingLogin { verifier: string; state: string; nonce: string }export interface SignedInUser { sub: string; issuer: string; name: string; roles: string[] }
export async function clientFor(identity: Identity, clientSecret: string, opts: { allowHttp?: boolean } = {}) { // enableNonRepudiationChecks: verify the ID token's signature against the provider's // published keys, not only trust the TLS connection it arrived on. allowHttp: local issuer only. const execute = [oidc.enableNonRepudiationChecks, ...(opts.allowHttp ? [oidc.allowInsecureRequests] : [])]; return oidc.discovery(new URL(identity.issuer), identity.clientId, clientSecret, undefined, { execute });}
export async function startLogin(config: oidc.Configuration, identity: Identity, redirectUri: string) { const verifier = oidc.randomPKCECodeVerifier(); const pending: PendingLogin = { verifier, state: oidc.randomState(), nonce: oidc.randomNonce() }; const url = oidc.buildAuthorizationUrl(config, { redirect_uri: redirectUri, scope: identity.scopes.join(' '), code_challenge: await oidc.calculatePKCECodeChallenge(verifier), code_challenge_method: 'S256', state: pending.state, nonce: pending.nonce, }); return { url, pending };}
/** Redeems the code. The library checks state, PKCE, nonce, issuer, audience, expiry and (see clientFor) the ID token signature. */export async function finishLogin(config: oidc.Configuration, identity: Identity, callbackUrl: URL, pending: PendingLogin): Promise<SignedInUser> { const tokens = await oidc.authorizationCodeGrant(config, callbackUrl, { pkceCodeVerifier: pending.verifier, expectedState: pending.state, expectedNonce: pending.nonce, idTokenExpected: true, }); const claims = tokens.claims(); if (!claims) throw new Error('no ID token'); return { sub: claims.sub, issuer: claims.iss, name: typeof claims.name === 'string' ? claims.name : '', roles: identity.rolesFrom(claims), };}allowHttp exists for the local mock provider, which speaks plain HTTP on your laptop; provider.ts passes it only when platform.name is local. The comment on finishLogin is the point of the file: the library, not your code, checks issuer, audience, expiry, state and nonce. The signature is the one check you switch on. By default openid-client trusts an ID token because it arrived straight from the token endpoint over TLS, which the OpenID Connect specification allows for this flow; enableNonRepudiationChecks in clientFor makes it also verify the signature against the provider’s published keys, so the check holds even if a proxy or a misconfigured endpoint sits in the path.
The client secret is read through the seam. The local implementation keeps it in a file outside the repository that scripts/local-up.sh generates; the platform lessons read it from their platform’s secret store. A client secret keeps the example short. Your agency may require a certificate or a federated credential instead; the flow does not change.
REFERENCE CODE src/lib/auth/provider.ts: cached OIDC client builder through the platform seam open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { getPlatform } from "@/platform";import { clientFor } from "./oidc";
let cached: ReturnType<typeof build> | undefined;
async function build() { const platform = await getPlatform(); const { identity } = platform; // The secret's value is the client secret itself, on every platform. const clientSecret = await platform.secrets.get(identity.clientSecretName); const config = await clientFor(identity, clientSecret, { allowHttp: platform.name === "local" }); return { config, identity };}
// Discovery runs once per process; a failed start is not cached.export function signInProvider() { cached ??= build().catch((err) => { cached = undefined; throw err; }); return cached;}A session your app owns
The browser holds one thing: an opaque random id in a cookie. The user and the creation time live on the server, behind that id. The app keeps no provider tokens: sign-in needs the ID token once, to learn who the person is, and this application calls no provider API on their behalf. Revoking a session means deleting a record, which a self-contained signed cookie cannot do before it expires. Here is the reference implementation of src/lib/auth/session-config.ts that your agent writes:
// Set by the ISSO. Not a NIST number: 8 hours is an example, not a requirement.export const SESSION_MAX_SECONDS = 8 * 60 * 60;export const SESSION_COOKIE = "__Host-app_sid"; REFERENCE CODE src/lib/auth/session.ts: app-owned session store, ID rotation, and requireSession() open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { randomBytes } from "node:crypto";import { cookies } from "next/headers";import { SafeError } from "@/lib/response";import type { PendingLogin, SignedInUser } from "./oidc";import { SESSION_COOKIE, SESSION_MAX_SECONDS } from "./session-config";
export interface StoredSession { createdAt: number; // ms since epoch; set at sign-in, never refreshed user?: SignedInUser; // { sub, issuer, roles, name } pending?: PendingLogin; // { verifier, state, nonce } between redirect and callback}export interface SessionStore { get(id: string): Promise<StoredSession | undefined>; set(id: string, s: StoredSession): Promise<void>; delete(id: string): Promise<void>;}export const newSessionId = () => randomBytes(32).toString("base64url");
export function isExpired(s: StoredSession, nowMs: number): boolean { return nowMs - s.createdAt >= SESSION_MAX_SECONDS * 1000;}
// Sign-in is the moment the id changes: the pre-login id is deleted, the new one is returned.export async function establishSession(store: SessionStore, oldId: string, user: SignedInUser, nowMs = Date.now()) { const id = newSessionId(); await store.set(id, { createdAt: nowMs, user }); await store.delete(oldId); return id;}
export async function destroySession(store: SessionStore, id: string) { await store.delete(id);}
export async function requireSession(store: SessionStore, nowMs = Date.now()) { const id = (await cookies()).get(SESSION_COOKIE)?.value; const s = id ? await store.get(id) : undefined; if (!id || !s?.user) throw new SafeError("Authentication required", 401); if (isExpired(s, nowMs)) { await store.delete(id); throw new SafeError("Session expired", 401); } return { id, ...s.user };}Three details are easy to get wrong:
- Rotate the id at sign-in.
establishSessioncreates a new id after the code is redeemed and deletes the pre-login one, so an id planted before sign-in is worthless afterward. SameSite=Lax, notStrict. The return from your identity provider is a cross-site top-level navigation; aStrictcookie is not sent on it and the callback cannot find its pending record.HttpOnlykeeps scripts away from the id andSecurekeeps it off plain HTTP. The__Host-prefix makes the browser refuse the cookie unless it isSecure, has path/, and carries noDomain.- In a deployed app the store cannot be process memory. Two container instances would each hold half the sessions. Put a shared store behind the
SessionStoreinterface; the in-memory version is for tests and a single local process.
The login route writes a pending record under a fresh id, sets the same cookie, and redirects to the URL from startLogin():
REFERENCE CODE src/app/auth/login/route.ts: login redirect route that records pending PKCE state open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
// src/app/auth/login/route.ts (the part that matters)import { cookies } from "next/headers";import { NextRequest, NextResponse } from "next/server";import { startLogin } from "@/lib/auth/oidc";import { signInProvider } from "@/lib/auth/provider";import { newSessionId } from "@/lib/auth/session";import { SESSION_COOKIE } from "@/lib/auth/session-config";import { store } from "@/lib/auth/store";
export async function GET(request: NextRequest) { const { config, identity } = await signInProvider(); const redirectUri = new URL("/auth/callback", request.url).toString(); const { url, pending } = await startLogin(config, identity, redirectUri);
const id = newSessionId(); await store.set(id, { createdAt: Date.now(), pending }); (await cookies()).set(SESSION_COOKIE, id, { httpOnly: true, secure: true, sameSite: "lax", path: "/" }); return NextResponse.redirect(url);}The callback hands the whole URL to finishLogin, which does every comparison. What is left for the route is the session work:
REFERENCE CODE src/app/auth/callback/route.ts: callback route that redeems the code and rotates the session ID open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
// src/app/auth/callback/route.ts (the part that matters)import { cookies } from "next/headers";import { NextRequest, NextResponse } from "next/server";import { finishLogin } from "@/lib/auth/oidc";import { signInProvider } from "@/lib/auth/provider";import { establishSession } from "@/lib/auth/session";import { SESSION_COOKIE } from "@/lib/auth/session-config";import { store } from "@/lib/auth/store";
export async function GET(request: NextRequest) { const jar = await cookies(); const oldId = jar.get(SESSION_COOKIE)?.value; const pre = oldId ? await store.get(oldId) : undefined; const toLogin = () => NextResponse.redirect(new URL("/auth/login", request.url)); if (!oldId || !pre?.pending) return toLogin();
const { config, identity } = await signInProvider(); let user; try { // Checks state, nonce, PKCE, issuer, audience and the ID token signature. user = await finishLogin(config, identity, new URL(request.url), pre.pending); } catch { await store.delete(oldId); // a failed or forged callback ends the pending login return toLogin(); }
const newId = await establishSession(store, oldId, user); jar.set(SESSION_COOKIE, newId, { httpOnly: true, secure: true, sameSite: "lax", path: "/" }); return NextResponse.redirect(new URL("/", request.url));}Behind a load balancer that terminates TLS, request.url can carry the internal address; rebuild the callback URL from your public origin so it matches the redirect URI registered with the provider. The logout route is a POST that calls destroySession, deletes the cookie, and redirects.
AC-12 and AC-11: whose number is it?
AC-12 is a control in NIST SP 800-53 (the federal catalog of security controls), titled Session Termination. It reads: automatically terminate a user session after organization-defined conditions or trigger events. NIST’s guidance gives examples of such triggers: periods of user inactivity, responses to certain incidents, or time-of-day restrictions. The trigger is yours to define, which is why SESSION_MAX_SECONDS is one constant, commented as the ISSO’s, with 8 hours as an example and nothing more. NIST does not publish a number.
AC-11 is a different control, Device Lock: prevent further access after an organization-defined period of inactivity, or when the user locks the system, until the user re-authenticates. An idle timeout is a separate decision with a separate constant and a separate test; do not fold it into the absolute lifetime. If your ISSO sets one, add SESSION_IDLE_SECONDS beside the first constant and track a lastSeenAt on the record.
Code that implements these supports evidence for the controls. The control statement your ISSO writes, and the number in it, are theirs.
Source: NIST SP 800-53 Rev 5.2.0 in OSCAL, from NIST’s own repository.
Roles: raw names in, mapping in Lesson 5
finishLogin calls identity.rolesFrom(claims) and stores whatever strings come back. The local implementation reads the roles claim; the mock provider puts Intake.Operator there. Another provider may carry the same information under another claim, in groups, or in a userinfo response, and rolesFrom is the one place that knows. Nothing at sign-in decides what a role means. Lesson 5 maps raw names onto a closed role set at request time, ignores names it does not know, and denies when nothing resolves.
Take authorization from roles defined for your application, not from raw directory membership, where your provider allows it. They are small, application-specific, and do not grow with the user’s memberships. Groups can work, with a plan for overage: when a user belongs to more groups than a token can carry, some providers (Entra ID is one) omit the list and send an indicator that tells you to ask the directory instead. If you read groups, your code needs that second path and a test for it, or members of large groups silently lose access.
Routing: proxy.ts is a convenience
REFERENCE CODE src/proxy.ts: coarse cookie-presence redirect open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { NextResponse, type NextRequest } from "next/server";import { SESSION_COOKIE } from "@/lib/auth/session-config";
const PUBLIC = ["/auth", "/_next", "/favicon.ico"];
// Coarse routing only. NOT the auth boundary: every route handler and// Server Function calls requireSession() itself.export function proxy(request: NextRequest) { const { pathname } = request.nextUrl; if (PUBLIC.some((p) => pathname.startsWith(p))) return NextResponse.next(); if (!request.cookies.has(SESSION_COOKIE)) { return NextResponse.redirect(new URL("/auth/login", request.url)); } return NextResponse.next();}proxy.ts runs on the Node.js runtime only, and you cannot set runtime in it. A Server Function is a POST to the page route, so a matcher that excludes a path also skips the function behind it. The page redirect is a courtesy to the user; the check inside the handler is the control.
What about next-auth, Auth.js, or Better Auth?
Earlier versions of this module used next-auth. Here is why it no longer does:
- next-auth v5 never left beta. As of 2026-11-04 the latest v5 build is still a beta release, so there is no stable v5 to pin.
- Auth.js is in security-fix maintenance under Better Auth. The Auth.js project announced that it joined Better Auth, with security fixes continuing and new projects pointed to Better Auth. Source: Auth.js joins Better Auth.
- Better Auth is database-first, which puts a database on the sign-in path. Its default design stores users and sessions in a database. That can be right for you; in this module it would put your application database, and its credential, in front of every sign-in. Confirm against its current documentation before you decide.
Using a standards-based OIDC library directly keeps the dependency list small and the provider swappable, at the cost of owning the session code yourself. That trade is the agency’s to make.
Prove it
Two kinds of test. The unit tests import the constant and use the in-memory store, with no provider at all. The env test signs in for real against the mock provider that npm run local:up starts in a container (alongside the SQL Server and telemetry collector later lessons use).
REFERENCE TEST src/lib/auth/session.test.ts: unit tests for session expiry, ID rotation, and logout open reference hide reference Reference pattern for your workspace agent; open to inspect or compare this file. You do not type or paste this by hand.
import { describe, expect, it } from "vitest";import { SESSION_MAX_SECONDS } from "./session-config";import { destroySession, establishSession, isExpired, type SessionStore, type StoredSession } from "./session";
const memory = (): SessionStore => { const m = new Map<string, StoredSession>(); return { get: async (i) => m.get(i), set: async (i, s) => void m.set(i, s), delete: async (i) => void m.delete(i) };};const user = { sub: "caseworker-0042", issuer: "https://idp.example", roles: ["Intake.Operator"], name: "Test Caseworker" };
describe("session lifetime (AC-12 trigger, set by the ISSO)", () => { const t0 = 1_000_000; const s: StoredSession = { createdAt: t0 }; it("is valid one second before the constant", () => { expect(isExpired(s, t0 + (SESSION_MAX_SECONDS - 1) * 1000)).toBe(false); }); it("is expired at the constant", () => { expect(isExpired(s, t0 + SESSION_MAX_SECONDS * 1000)).toBe(true); });});
describe("sign-in rotates the session id", () => { it("deletes the pre-login id and stores exactly the user it was given", async () => { const store = memory(); await store.set("planted", { createdAt: 1, pending: { verifier: "v", state: "s", nonce: "n" } }); const id = await establishSession(store, "planted", user, 5); expect(id).not.toBe("planted"); expect(await store.get("planted")).toBeUndefined(); expect(await store.get(id)).toEqual({ createdAt: 5, user }); });});
describe("logout", () => { it("removes the server-side session", async () => { const store = memory(); await store.set("sid", { createdAt: Date.now(), user }); await destroySession(store, "sid"); expect(await store.get("sid")).toBeUndefined(); });});The env test, from the runnable reference for this module, drives the whole flow against the mock provider: it builds the client from the local platform’s identity and secret, starts a login, lets the mock sign in without a page, and redeems the callback.
REFERENCE TEST tests/env/oidc.env.test.ts (excerpt): end-to-end sign-in and forged-state check against the local mock provider open reference hide reference Reference implementation from gov-dev-reference-app; open to inspect or compare with what your agent builds.
// tests/env/oidc.env.test.ts (excerpt)async function signIn(tamper?: (u: URL) => void) { const { identity, secrets } = localPlatform; const clientSecret = await secrets.get(identity.clientSecretName); const config = await clientFor(identity, clientSecret, { allowHttp: true }); const { url, pending } = await startLogin(config, identity, redirectUri); const res = await fetch(url, { redirect: 'manual' }); // the mock signs in without a page const callback = new URL(res.headers.get('location')!); tamper?.(callback); return finishLogin(config, identity, callback, pending);}// ...run('sign-in against the local identity provider', () => { it('returns the user with roles from the provider, via the seam', async () => { expect(await signIn()).toEqual({ sub: 'caseworker-0042', issuer: 'http://localhost:8080/default', name: 'Test Caseworker', roles: ['Intake.Operator'] }); }); it('refuses a callback whose state was swapped', async () => { await expect(signIn((u) => u.searchParams.set('state', 'forged'))).rejects.toMatchObject({ cause: { message: expect.stringMatching(/unexpected "state"/) }, }); });});Run both:
npx vitest run src/lib/auth/session.test.tsnpm run test:envThe planted faults that must turn a test red: change >= in isExpired to > and the boundary test fails; make establishSession skip store.delete(oldId) and the rotation test fails; make destroySession a no-op and the logout test fails. The env test’s negative case is built in: the callback with a swapped state must be refused, so a change that stops finishLogin from checking it turns that test red. Try each once. A test you have never seen fail is a guess.
What these tests do not prove is a real sign-in against your agency’s provider: its redirect URI registration, its claim names, its multifactor policy. That is a manual check on your first deployment, and your platform lesson lists it.
Your ISSO tells you the session lifetime is changing from the value in your first draft. Which change is correct?
The old design had an assertTenant() call in the callback. This lesson has none. Why is the issuer check not missing?
proxy.ts redirects every request without a session cookie to sign-in. Why must requireSession() still run inside each route handler and Server Function?
Key takeaway
Sign in with the standard flow and let the library check the token: authorization code, PKCE, state and nonce, from a confidential client whose secret comes through platform.secrets. Own the session: an opaque cookie id, the user (sub, issuer, roles, name) on the server and no provider tokens, a new id at sign-in, one constant for the lifetime that your ISSO sets, and tests that import it. Treat proxy.ts as routing and put the real check in every handler. Names later lessons reuse: SESSION_MAX_SECONDS, SESSION_COOKIE, requireSession(), establishSession(), destroySession(), platform.identity.
- LEADERSHIP DECISION
- Name the identity provider of record and have the ISSO set the session lifetime in writing; the app follows both.
- PRACTITIONER ACTION
- Ship oidc.ts with signature checks on, the app-owned session, and the expiry, rotation and logout tests, then run the forged-state env test once.
- SUCCESS MEASURE
- Audit finding avoided: the AC-12 session-limit evidence is one constant, its owner's decision record, and a test that imports it.
Legend: LEADERSHIP DECISION = what a leader decides · PRACTITIONER ACTION = what the engineer does next · SUCCESS MEASURE = how you know, in calendar time, assessor-hours or cost, contract or revenue risk, or audit finding avoided