/** * @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 * // Asking Accounts something (contracts 1.8.0, crosscode.identity-request/1): * const { sub } = await auth.request({ type: 'people.ensure', actor, name, email, phone: null, returnUrl }); * * 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, ACCOUNTS_REQUEST_PATH, ACR_MFA, decodeState, encodeState, IDENTITY_REQUEST_SCHEMA, identityClaimsSchema, OIDC_CLIENT_PATHS, OIDC_PROVIDER_PATHS, OIDC_SCOPES, safeReturnPath, type AccountsCall, type IdentityClaims, type IdentityRequest, } from '@crosscode/contracts'; import { LINK_HEADERS, oidcClientSecret, sealLinkValue, signedHeaders, 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); } } /** Accounts refused or couldn't answer a request (`code` from IDENTITY_REQUEST_ERROR_CODES, or UNREACHABLE / BAD_REPLY). */ export class AccountsRequestError extends Error { constructor(message: string, public code: string, public status: number) { super(message); } } /** A request without its envelope: `schema` and `requestId` are filled in (pass `requestId` to retry the same one). */ export type RequestInput = IdentityRequest extends infer R ? R extends IdentityRequest ? Omit & { requestId?: string } : never : never; 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; signUp?: boolean } = {}) { 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 } : {}), // Accounts 1.1.0: open on "Create an account". ...(opts.signUp ? { screen: 'signup' } : {}), }); 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; 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 | 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 }; }, /** Seals a secret for an `import.batch` (a password hash, an authenticator secret) with the link's secret. */ seal(value: string): string { return sealLinkValue(o.linkSecret, value); }, /** Sends a `crosscode.identity-request/1` request to Accounts, signed with the link's secret, and returns its answer. */ async request>(input: RequestInput, opts: { timeoutMs?: number } = {}): Promise { const body = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), ...input }); const headers = signedHeaders(LINK_HEADERS, { senderId: o.clientId, secret: o.linkSecret, rawBody: body }); let res: Response; try { res = await fetch(`${o.accountsUrl.replace(/\/+$/, '')}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body, redirect: 'manual', signal: AbortSignal.timeout(opts.timeoutMs ?? 30000), headers: { 'content-type': 'application/json', accept: 'application/json', ...headers }, }); } catch (e) { throw new AccountsRequestError(`Accounts could not be reached: ${(e as Error).message}`, 'UNREACHABLE', 502); } const data = (await res.json().catch(() => null)) as (Record & { message?: string; code?: string }) | null; if (!res.ok) throw new AccountsRequestError(data?.message || `Accounts answered ${res.status}`, data?.code || `HTTP_${res.status}`, res.status); if (!data || data.schema !== IDENTITY_REQUEST_SCHEMA) throw new AccountsRequestError('Accounts answered in a way this product doesn\'t understand.', 'BAD_REPLY', 502); return data as T; }, /** Checks and reads a back-channel call from Accounts (signed with the link secret). */ verifyAccountsCall(rawBody: string | Uint8Array, headers: Record): 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>;