packages/auth-client: the product side of signing in through Accounts

Start a sign-in with the return path (state, nonce, PKCE), finish it,
sign-out address, back-channel logout tokens and Accounts' signed
user.* calls. Tested against the real provider. Root lint covers
Accounts' backend.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 13:45:39 +02:00
co-authored by Claude Opus 5.5
parent f202a5a88e
commit a3e3921b4f
12 changed files with 318 additions and 7 deletions
+1
View File
@@ -31,6 +31,7 @@
"zod": "^4.6.7"
},
"devDependencies": {
"@crosscode/auth-client": "*",
"@types/bcryptjs": "^2.4.6",
"@types/express": "^5.0.6",
"@types/node": "^20.19.43",
+1 -1
View File
@@ -7,7 +7,7 @@
* from the linked products, so neither can be typed in wrong.
*/
import { churchObjectSchema, churchSchema, CHURCH_SCHEMA, type Church } from '@crosscode/contracts';
import { z } from 'zod';
import type { z } from 'zod';
import type { Ctx } from '../context.js';
import { customerId } from '../hub/licence.js';
import { queueCall } from '../links/deliveries.js';
@@ -100,7 +100,7 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI
if ((stage === 'verify_email' || (stage === 'two_factor' && a.twoFactorMethod !== 'totp')) && !pending.codeSentAt) {
const method = stage === 'verify_email' ? 'email' : (a.twoFactorMethod as 'email' | 'whatsapp');
const sent = await sendCode(ctx, a, method, stage === 'verify_email' ? 'verify_email' : 'sign_in');
pending = await save(ctx, pending, { codeHash: sent.codeHash, codeSentAt: ctx.now(), attempts: 0 });
await save(ctx, pending, { codeHash: sent.codeHash, codeSentAt: ctx.now(), attempts: 0 });
}
const extra: Record<string, unknown> = { name: a.name, email: a.email };
if (stage === 'verify_email') extra.sentTo = maskedTarget(a, 'email');
@@ -0,0 +1,85 @@
// @crosscode/auth-client (the product side, packages/auth-client) against the real provider:
// what the Website, App and Events 3.0 will run.
import assert from 'node:assert/strict';
import { after, before, describe, test } from 'node:test';
import { OIDC_CLIENT_PATHS } from '@crosscode/contracts';
import { accountsClient, type AccountsClient } from '@crosscode/auth-client';
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
import { runDue } from '../src/links/deliveries.js';
import { signOutEverywhere } from '../src/oidc/sessions.js';
let h: Harness;
let auth: AccountsClient;
before(async () => {
h = await startHarness();
auth = await accountsClient({ accountsUrl: h.publicUrl, productUrl: h.productUrl, clientId: PRODUCT_ID, linkSecret: h.linkSecret, allowInsecure: true });
await h.makeAccount({ email: 'client@hope.test', password: 'Correct-horse-1' });
});
after(async () => { await h.close(); });
async function signInWith(returnTo: string) {
const browser = new Browser();
const { url, cookie } = await auth.startSignIn(returnTo);
const signin = await browser.follow(url, (u) => u.pathname === '/signin');
const uid = signin.url.searchParams.get('uid')!;
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'client@hope.test', password: 'Correct-horse-1' });
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
return auth.finishSignIn(back.url, cookie);
}
describe('@crosscode/auth-client', () => {
test('signs in and returns to the page', async () => {
const r = await signInWith('/sermons/2026/advent?part=2');
assert.equal(r.claims.email, 'client@hope.test');
assert.equal(r.returnTo, '/sermons/2026/advent?part=2');
assert.ok(r.idToken);
});
test('a foreign return address is never followed', async () => {
for (const evil of ['//evil.example/x', 'https://evil.example/', '/\\evil.example']) {
assert.equal((await signInWith(evil)).returnTo, '/', evil);
}
});
test('without the cookie from starting, finishing fails', async () => {
await assert.rejects(auth.finishSignIn(`${h.productUrl}${OIDC_CLIENT_PATHS.callback}?code=x&state=y`, undefined), /expired/);
});
test('checks Accounts\' signed calls and refuses changed ones', async () => {
const { profileChanged } = await import('../src/accounts/service.js');
const a = (await h.db.account.findUnique({ where: { email: 'client@hope.test' } }))!;
h.received.length = 0;
await profileChanged(h.ctx, a.id as string);
await runDue(h.ctx);
const call = h.received.find((r) => r.path === '/api/accounts/v1/events')!;
const read = auth.verifyAccountsCall(call.body, call.headers as Record<string, string>);
assert.equal(read.type, 'user.updated');
assert.equal(read.sub, a.id);
assert.throws(() => auth.verifyAccountsCall(call.body.replace('client@hope.test', 'attacker@evil.test'), call.headers as Record<string, string>), /isn't signed/);
});
test('checks a back-channel logout token', async () => {
const browser = new Browser();
const { url, cookie } = await auth.startSignIn('/');
const signin = await browser.follow(url, (u) => u.pathname === '/signin');
const step = await h.api(browser, 'POST', `/api/v2/interaction/${signin.url.searchParams.get('uid')}/password`, { email: 'client@hope.test', password: 'Correct-horse-1' });
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
const { claims } = await auth.finishSignIn(back.url, cookie);
h.received.length = 0;
await signOutEverywhere(h.ctx, h.provider, claims.sub);
const logout = h.received.find((r) => r.path === OIDC_CLIENT_PATHS.backchannelLogout)!;
const token = new URLSearchParams(logout.body).get('logout_token')!;
const out = await auth.verifyLogoutToken(token);
assert.equal(out.sub, claims.sub);
assert.ok(out.sid);
const [hd, p, s] = token.split('.');
const forged = `${hd}.${Buffer.from(JSON.stringify({ ...JSON.parse(Buffer.from(p!, 'base64url').toString()), sub: 'someone-else' })).toString('base64url')}.${s}`;
await assert.rejects(auth.verifyLogoutToken(forged), /isn't valid/);
});
test('the sign-out address ends at the product', () => {
const u = new URL(auth.signOutUrl('id-token'));
assert.equal(u.pathname, '/api/oidc/session/end');
assert.equal(u.searchParams.get('post_logout_redirect_uri'), `${h.productUrl}/`);
});
});
@@ -137,7 +137,7 @@ export async function startHarness(opts: { now?: () => Date } = {}) {
const { url } = await browser.follow(started.url, (u) => u.pathname === '/signin' || u.pathname === OIDC_CLIENT_PATHS.callback);
if (url.pathname === OIDC_CLIENT_PATHS.callback) return finishSignIn(url, started);
const uid = url.searchParams.get('uid')!;
let step = await api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
const step = await api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
if (step.body.stage !== 'done') return { pending: step.body, uid, started };
const back = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === OIDC_CLIENT_PATHS.callback);
return finishSignIn(back.url, started);
+2 -1
View File
@@ -18,5 +18,6 @@ export default defineConfig([
},
},
// Cross Events keeps its own lint (frontend/eslint.config.mjs, tsc for the backend) for now.
globalIgnores(["**/node_modules/**", "**/dist/**", "**/coverage/**", "**/schemas/**", "apps/events/**"]),
// The Accounts frontend has its own Next lint (apps/accounts/frontend/eslint.config.mjs); Prisma's client is generated.
globalIgnores(["**/node_modules/**", "**/dist/**", "**/coverage/**", "**/schemas/**", "apps/events/**", "apps/accounts/frontend/**", "**/src/generated/**", "**/.next/**"]),
]);
+17 -3
View File
@@ -63,6 +63,7 @@
"zod": "^4.6.7"
},
"devDependencies": {
"@crosscode/auth-client": "*",
"@types/bcryptjs": "^2.4.6",
"@types/express": "^5.0.6",
"@types/node": "^20.19.43",
@@ -975,6 +976,10 @@
"resolved": "apps/app",
"link": true
},
"node_modules/@crosscode/auth-client": {
"resolved": "packages/auth-client",
"link": true
},
"node_modules/@crosscode/contracts": {
"resolved": "packages/contracts",
"link": true
@@ -16297,7 +16302,6 @@
"version": "3.8.8",
"resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-3.8.8.tgz",
"integrity": "sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/panva"
@@ -16578,7 +16582,6 @@
"version": "6.8.9",
"resolved": "https://registry.npmjs.org/openid-client/-/openid-client-6.8.9.tgz",
"integrity": "sha512-6mXMRNJxDOf6BflEWLXul1UwzLFz++9Ofz1PYwPwwsJsyXBsbfkO+Jo255SW1qnFNLYz4EJWHz42X4OJJrya/g==",
"dev": true,
"license": "MIT",
"dependencies": {
"jose": "^6.2.15",
@@ -21261,6 +21264,14 @@
"url": "https://github.com/sponsors/wooorm"
}
},
"packages/auth-client": {
"name": "@crosscode/auth-client",
"version": "1.0.0",
"dependencies": {
"@crosscode/contracts": "*",
"openid-client": "6.8.9"
}
},
"packages/contracts": {
"name": "@crosscode/contracts",
"version": "1.5.0",
@@ -21307,7 +21318,10 @@
},
"packages/ui": {
"name": "@crosscode/ui",
"version": "0.0.0"
"version": "0.1.0",
"peerDependencies": {
"react": ">=19"
}
}
}
}
+9
View File
@@ -0,0 +1,9 @@
# @crosscode/auth-client
The product side of signing in through the church's Accounts (docs/ACCOUNTS-1.0-PLAN.md §5). The
Church Website, the Church App and Cross Events 3.0 use it, so every product returns people to the
exact page they came from, checks state, nonce and PKCE, and handles back-channel logout and
Accounts' signed `user.*` calls the same way. Usage is in the comment at the top of `src/index.ts`.
Built on `openid-client` 6 (ES modules only). Tested against the real provider in
`apps/accounts/backend/tests/authClient.test.ts`.
+22
View File
@@ -0,0 +1,22 @@
{
"name": "@crosscode/auth-client",
"version": "1.0.0",
"private": true,
"description": "The product side of signing in through the church's Accounts (docs/ACCOUNTS-1.0-PLAN.md §5): start a sign-in with the return path, finish it, back-channel logout and Accounts' signed calls",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
"./package.json": "./package.json"
},
"files": ["dist", "README.md"],
"scripts": {
"build": "tsup",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@crosscode/contracts": "*",
"openid-client": "6.8.9"
}
}
+153
View File
@@ -0,0 +1,153 @@
/**
* @crosscode/auth-client — signing in through the church's Accounts, the product side
* (docs/ACCOUNTS-1.0-PLAN.md §3–6). The Church Website, the Church App and Cross Events 3.0 all use
* it, so every product returns people to the page they came from in the same safe way:
*
* const auth = await accountsClient({ accountsUrl, productUrl, clientId: installId, linkSecret });
* // "Sign in" (or a page that needs it):
* const { url, cookie } = await auth.startSignIn(req.originalUrl); // set `cookie` HttpOnly, then redirect to `url`
* // GET /api/auth/callback:
* const { claims, returnTo } = await auth.finishSignIn(fullCallbackUrl, cookie); // start your own session, redirect to returnTo
* // POST /api/auth/backchannel-logout:
* const { sub, sid } = await auth.verifyLogoutToken(form.logout_token); // end that person's sessions
* // POST /api/accounts/v1/events:
* const call = auth.verifyAccountsCall(rawBody, headers); // user.updated / user.deleted / user.export
*
* The client secret is derived from the product's link with Accounts (Connect), so a product only
* keeps its link secret. Roles are never in the claims: each product keeps its own, keyed by `sub`.
*/
import crypto from 'node:crypto';
import * as oidc from 'openid-client';
import {
accountsCallSchema, ACR_MFA, decodeState, encodeState, identityClaimsSchema, OIDC_CLIENT_PATHS, OIDC_PROVIDER_PATHS, OIDC_SCOPES,
safeReturnPath, type AccountsCall, type IdentityClaims,
} from '@crosscode/contracts';
import { LINK_HEADERS, oidcClientSecret, verify } from '@crosscode/contracts/signing';
export type AccountsClientOptions = {
/** The church's Accounts address, e.g. https://accounts.hopefamily.co.za */
accountsUrl: string;
/** This product's address as the Hub lists it, e.g. https://www.hopefamily.co.za */
productUrl: string;
/** This product's Hub install id (its client_id at Accounts). */
clientId: string;
/** The secret of this product's link with Accounts. */
linkSecret: string;
/** Local testing only: allow http. */
allowInsecure?: boolean;
};
/** What goes in the short-lived HttpOnly cookie between starting and finishing a sign-in. */
type Pending = { nonce: string; verifier: string; state: string };
export class SignInError extends Error {
constructor(message: string, public code: string) {
super(message);
}
}
export async function accountsClient(o: AccountsClientOptions) {
const base = o.productUrl.replace(/\/+$/, '');
const issuer = new URL(`${o.accountsUrl.replace(/\/+$/, '')}${OIDC_PROVIDER_PATHS.issuer}`);
const config = await oidc.discovery(issuer, o.clientId, oidcClientSecret(o.linkSecret), undefined, o.allowInsecure ? { execute: [oidc.allowInsecureRequests] } : undefined);
const redirectUri = `${base}${OIDC_CLIENT_PATHS.callback}`;
return {
config,
/** Starts a sign-in that comes back to `returnTo` (the page the person was on). `requireTwoFactor` for staff roles. */
async startSignIn(returnTo: string, opts: { requireTwoFactor?: boolean; loginHint?: string } = {}) {
const nonce = oidc.randomNonce();
const verifier = oidc.randomPKCECodeVerifier();
const state = encodeState({ nonce: crypto.randomBytes(16).toString('base64url'), returnTo: safeReturnPath(returnTo) });
const url = oidc.buildAuthorizationUrl(config, {
redirect_uri: redirectUri,
scope: OIDC_SCOPES.join(' '),
state,
nonce,
code_challenge: await oidc.calculatePKCECodeChallenge(verifier),
code_challenge_method: 'S256',
...(opts.requireTwoFactor ? { acr_values: ACR_MFA } : {}),
...(opts.loginHint ? { login_hint: opts.loginHint } : {}),
});
const pending: Pending = { nonce, verifier, state };
return { url: url.toString(), cookie: Buffer.from(JSON.stringify(pending)).toString('base64url') };
},
/** Finishes a sign-in at the callback. Returns the person and the safe page to send them to. */
async finishSignIn(callbackUrl: string | URL, cookie: string | undefined): Promise<{ claims: IdentityClaims; returnTo: string; idToken: string }> {
let pending: Pending;
try {
pending = JSON.parse(Buffer.from(String(cookie ?? ''), 'base64url').toString('utf8')) as Pending;
} catch {
throw new SignInError('The sign-in expired. Please try again.', 'NO_PENDING');
}
if (!pending?.verifier || !pending.state) throw new SignInError('The sign-in expired. Please try again.', 'NO_PENDING');
const tokens = await oidc.authorizationCodeGrant(config, new URL(callbackUrl), {
pkceCodeVerifier: pending.verifier, expectedState: pending.state, expectedNonce: pending.nonce, idTokenExpected: true,
});
const parsed = identityClaimsSchema.safeParse(tokens.claims());
if (!parsed.success) throw new SignInError('Accounts answered with claims this product doesn\'t understand.', 'BAD_CLAIMS');
return { claims: parsed.data, returnTo: safeReturnPath(decodeState(pending.state)?.returnTo), idToken: tokens.id_token! };
},
/** Where "Sign out" sends the browser: signed out of all the church's products, then back here. */
signOutUrl(idToken?: string) {
return oidc.buildEndSessionUrl(config, {
post_logout_redirect_uri: `${base}${OIDC_CLIENT_PATHS.postLogout}`,
...(idToken ? { id_token_hint: idToken } : {}),
}).toString();
},
/** Checks a back-channel logout token (OIDC Back-Channel Logout 1.0) and says whose sessions to end. */
async verifyLogoutToken(token: string): Promise<{ sub: string; sid: string | null }> {
const [h, p, s] = String(token).split('.');
if (!h || !p || !s) throw new SignInError('Not a logout token.', 'BAD_TOKEN');
let header: { kid?: string; alg?: string };
let payload: Record<string, unknown>;
try {
header = JSON.parse(Buffer.from(h, 'base64url').toString()) as typeof header;
payload = JSON.parse(Buffer.from(p, 'base64url').toString()) as typeof payload;
} catch {
throw new SignInError('Not a logout token.', 'BAD_TOKEN');
}
const meta = config.serverMetadata();
const jwks = (await fetch(meta.jwks_uri!).then((r) => r.json())) as { keys: (crypto.JsonWebKey & { kid?: string })[] };
const jwk = jwks.keys.find((k) => k.kid === header.kid);
if (!jwk || header.alg !== 'ES256') throw new SignInError('Unknown signing key.', 'BAD_TOKEN');
const signed = crypto.verify('sha256', Buffer.from(`${h}.${p}`), { key: crypto.createPublicKey({ key: jwk, format: 'jwk' }), dsaEncoding: 'ieee-p1363' }, Buffer.from(s, 'base64url'));
const now = Math.floor(Date.now() / 1000);
const events = payload.events as Record<string, unknown> | undefined;
const valid = signed
&& payload.iss === meta.issuer
&& payload.aud === o.clientId
&& !!events?.['http://schemas.openid.net/event/backchannel-logout']
&& !('nonce' in payload)
&& Number(payload.iat) <= now + 60
&& (payload.exp === undefined || Number(payload.exp) >= now);
if (!valid) throw new SignInError('That logout token isn\'t valid.', 'BAD_TOKEN');
return { sub: String(payload.sub), sid: payload.sid ? String(payload.sid) : null };
},
/** Checks and reads a back-channel call from Accounts (signed with the link secret). */
verifyAccountsCall(rawBody: string | Uint8Array, headers: Record<string, string | string[] | undefined>): AccountsCall {
const get = (n: string) => {
const v = headers[n] ?? headers[n.toLowerCase()];
return Array.isArray(v) ? v[0] : v;
};
const check = verify({ secret: o.linkSecret, timestamp: get(LINK_HEADERS.timestamp), signature: get(LINK_HEADERS.signature), rawBody });
if (!check.ok) throw new SignInError('That call isn\'t signed by Accounts.', check.code);
let body: unknown;
try {
body = JSON.parse(typeof rawBody === 'string' ? rawBody : Buffer.from(rawBody).toString('utf8'));
} catch {
throw new SignInError('Not JSON.', 'INVALID_REQUEST');
}
const parsed = accountsCallSchema.safeParse(body);
if (!parsed.success) throw new SignInError('Not a crosscode.identity/1 call.', 'INVALID_REQUEST');
return parsed.data;
},
};
}
export type AccountsClient = Awaited<ReturnType<typeof accountsClient>>;
+14
View File
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2023",
"module": "nodenext",
"moduleResolution": "nodenext",
"lib": ["ES2023", "DOM"],
"strict": true,
"skipLibCheck": true,
"esModuleInterop": true,
"noEmit": true,
"types": ["node"]
},
"include": ["src", "tsup.config.ts"]
}
+12
View File
@@ -0,0 +1,12 @@
import { defineConfig } from "tsup";
// ES modules only (openid-client is ESM only), types included.
export default defineConfig({
entry: ["src/index.ts"],
format: ["esm"],
dts: true,
sourcemap: true,
clean: true,
target: "es2022",
external: ["@crosscode/contracts", "openid-client"],
});