Files
crosscode-platform/apps/accounts/backend/src/oidc/provider.ts
T
joshuaandClaude Opus 5.5 733992e917 Accounts 1.1.0: moving Events' users in, people.* requests, new recovery codes
POST /api/accounts/v1/requests (crosscode.identity-request/1): import.* keeps
each person's Events id as sub, password hash and authenticator secret
(sealed in transit), consent, notices and lockout; linked when the email
already has an account. people.* for product admins, limited to people the
product knows. New recovery codes after the first 2FA sign-in for people
moved in with 2FA. screen=signup. auth-client: request(), seal(), signUp.
8 new tests (47 in all).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 13:40:15 +02:00

145 lines
7.3 KiB
TypeScript

/**
* The OpenID Connect provider (oidc-provider 9, docs/ACCOUNTS-1.0-PLAN.md §3): authorization code
* with PKCE (S256) for every client, no implicit or hybrid flows, no refresh tokens, ES256 keys
* made on first start, `crosscode.identity/1` claims, RP-initiated and back-channel logout.
*
* Sign-in steps happen in our own pages (interaction/): the provider sends people to
* `/signin?uid=…`. Products of the church are first-party, so there's no consent screen: a grant
* for the scopes asked for is made when they sign in (`loadExistingGrant`).
*/
import crypto from 'node:crypto';
import Provider, { interactionPolicy, type Configuration, type KoaContextWithOIDC } from 'oidc-provider';
import { ACR_MFA, OIDC_PROVIDER_PATHS, OIDC_SCOPES } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { identityClaims } from '../accounts/service.js';
import { currentNoticeVersion } from '../privacy/notice.js';
import { adapterFor } from './adapter.js';
import { selfClient } from './clients.js';
import { renderError, renderLogout, renderLoggedOut } from './pages.js';
const DAY = 24 * 60 * 60;
export const issuerOf = (ctx: Ctx) => `${ctx.config.publicUrl}${OIDC_PROVIDER_PATHS.issuer}`;
type Jwk = crypto.JsonWebKey & { kid: string; alg: string; use: string };
/** The signing keys (newest first), made the first time. `rotateKeys` adds a new one. */
export async function signingKeys(ctx: Ctx): Promise<Jwk[]> {
const keys = await ctx.settings.json<Jwk[]>('oidc_jwks', []);
if (keys.length) return keys;
return rotateKeys(ctx);
}
/** A new ES256 key in front; the previous one stays for checking tokens it signed (they last minutes). */
export async function rotateKeys(ctx: Ctx): Promise<Jwk[]> {
const old = await ctx.settings.json<Jwk[]>('oidc_jwks', []);
const { privateKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });
const jwk = { ...privateKey.export({ format: 'jwk' }), kid: crypto.randomBytes(8).toString('hex'), alg: 'ES256', use: 'sig' } as Jwk;
const keys = [jwk, ...old].slice(0, 2);
await ctx.settings.set('oidc_jwks', JSON.stringify(keys));
return keys;
}
/** The interaction policy: the usual login checks, plus ours (§2, §6). */
function policy(ctx: Ctx) {
const { base, Check } = interactionPolicy;
const p = base();
const login = p.get('login')!;
// A product asked for 2FA (`acr_values=mfa`) and this session signed in without it.
login.checks.add(new Check('mfa_required', 'This sign-in needs a second step', async (k: KoaContextWithOIDC) => {
const wanted = String(k.oidc.params?.acr_values ?? '').split(' ').includes(ACR_MFA);
return wanted && k.oidc.session?.acr !== ACR_MFA ? Check.REQUEST_PROMPT : Check.NO_NEED_TO_PROMPT;
}));
// A newer privacy notice since this person last accepted one, or their account changed.
login.checks.add(new Check('account_needs_attention', 'The privacy notice changed', async (k: KoaContextWithOIDC) => {
const sub = k.oidc.session?.accountId;
if (!sub) return Check.NO_NEED_TO_PROMPT;
const a = await ctx.db.account.findUnique({ where: { id: sub } });
if (!a || a.status !== 'active') return Check.REQUEST_PROMPT;
return a.noticeVersionAccepted < (await currentNoticeVersion(ctx)) ? Check.REQUEST_PROMPT : Check.NO_NEED_TO_PROMPT;
}));
return p;
}
export async function createProvider(ctx: Ctx): Promise<Provider> {
const keys = await signingKeys(ctx);
const sessionDays = Number((await ctx.settings.get('session_days')) || 30);
const config: Configuration = {
adapter: adapterFor(ctx),
clients: [selfClient(ctx)],
extraClientMetadata: { properties: ['crosscode.product'] },
// 1.1.0: `screen=signup` opens the sign-in page on "Create an account".
extraParams: ['screen'],
clientDefaults: { id_token_signed_response_alg: 'ES256', grant_types: ['authorization_code'], response_types: ['code'], token_endpoint_auth_method: 'client_secret_basic' },
findAccount: async (_k, sub) => {
const a = await ctx.db.account.findUnique({ where: { id: sub } });
if (!a || a.status !== 'active') return undefined;
return { accountId: sub, claims: async () => identityClaims(ctx, a) as never };
},
claims: {
openid: ['sub', 'acr', 'amr', 'auth_time'],
profile: ['name', 'given_name', 'family_name'],
email: ['email', 'email_verified'],
phone: ['phone_number', 'phone_number_verified'],
crosscode: ['schema', 'news_consent', 'two_factor', 'privacy_notice_version'],
},
scopes: [...OIDC_SCOPES],
acrValues: ['pwd', ACR_MFA],
// The claims go in the ID token too, so a product has everything without calling userinfo.
conformIdTokenClaims: false,
responseTypes: ['code'],
pkce: { required: () => true },
features: {
devInteractions: { enabled: false },
rpInitiatedLogout: { enabled: true, logoutSource: renderLogout(ctx), postLogoutSuccessSource: renderLoggedOut(ctx) },
backchannelLogout: { enabled: true },
revocation: { enabled: true },
userinfo: { enabled: true },
},
// oidc-provider scopes the interaction cookie to this address's path, so it's the API's path for
// the sign-in (every step's call is under it); that address sends the browser on to the page
// (interaction/routes.ts). Absolute, so a proxy that doesn't keep the Host header can't send
// people to the backend's own port.
interactions: { url: (_k, interaction) => `${ctx.config.publicUrl}/api/v2/interaction/${interaction.uid}`, policy: policy(ctx) },
loadExistingGrant: async (k) => {
const grantId = k.oidc.result?.consent?.grantId || k.oidc.session!.grantIdFor(k.oidc.client!.clientId);
if (grantId) {
const existing = await k.oidc.provider.Grant.find(grantId);
if (existing) return existing;
}
// The church's own products: no consent screen.
const grant = new k.oidc.provider.Grant({ clientId: k.oidc.client!.clientId, accountId: k.oidc.session!.accountId! });
grant.addOIDCScope(OIDC_SCOPES.join(' '));
await grant.save();
return grant;
},
cookies: {
keys: ctx.secrets.cookieKeys(),
long: { signed: true, httpOnly: true, sameSite: 'lax' },
short: { signed: true, httpOnly: true, sameSite: 'lax' },
},
jwks: { keys: keys as never },
enabledJWA: { idTokenSigningAlgValues: ['ES256'], userinfoSigningAlgValues: ['ES256'] },
ttl: {
AccessToken: 600,
AuthorizationCode: 60,
IdToken: 600,
Interaction: 3600,
Grant: sessionDays * DAY,
// "Keep me signed in": `sessionDays`; otherwise until the browser closes (a transient cookie), at most a day.
Session: (_k, session) => (session.transient ? DAY : sessionDays * DAY),
},
renderError: renderError(ctx),
// oidc-provider refuses private addresses for back-channel logout (its SSRF protection). Local
// testing only (LINKS_ALLOW_PRIVATE): send without that check, as for the other link calls.
...(ctx.config.allowPrivateLinks && !ctx.config.production
? { fetch: (input: string | URL | Request, init?: RequestInit) => { const { dispatcher: _d, ...rest } = (init ?? {}) as RequestInit & { dispatcher?: unknown }; return fetch(input, rest); } }
: {}),
rotateRefreshToken: false,
issueRefreshToken: () => false,
};
const provider = new Provider(issuerOf(ctx), config);
provider.proxy = ctx.config.trustProxy;
return provider;
}