Accounts 1.0.0 backend: OIDC provider, sign-in steps, account and admin API
oidc-provider 9.13.3 with PKCE, ES256, crosscode.identity/1 claims and back-channel logout; clients are the linked products (Connect). Sign-in steps (password, sign-up, email check, 2FA and its setup, privacy notice, news question, password reset) survive to the product. Account page and admin API, church profile, export and deletion fan-out, Hub v2 client, jobs. End-to-end tests with a test product on openid-client. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* oidc-provider's storage in Postgres (`OidcPayload`, one row per model and id), so sessions and
|
||||
* codes survive restarts and work with more than one process. Clients aren't stored here: they're
|
||||
* the linked products (oidc/clients.ts).
|
||||
*/
|
||||
import type { Adapter, AdapterPayload } from 'oidc-provider';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { clientMetadataFor } from './clients.js';
|
||||
|
||||
/** Models whose rows are found by grant (revoked together). */
|
||||
const GRANTABLE = new Set(['AccessToken', 'AuthorizationCode', 'RefreshToken', 'DeviceCode', 'BackchannelAuthenticationRequest']);
|
||||
|
||||
export function adapterFor(ctx: Ctx) {
|
||||
return class PrismaAdapter implements Adapter {
|
||||
constructor(private readonly model: string) {}
|
||||
|
||||
private key(id: string) {
|
||||
return `${this.model}:${id}`;
|
||||
}
|
||||
|
||||
async upsert(id: string, payload: AdapterPayload, expiresIn: number): Promise<void> {
|
||||
const data = {
|
||||
model: this.model,
|
||||
payload: payload as never,
|
||||
grantId: payload.grantId ?? null,
|
||||
userCode: payload.userCode ?? null,
|
||||
uid: payload.uid ?? null,
|
||||
accountId: this.model === 'Session' ? (payload.accountId ?? null) : null,
|
||||
expiresAt: expiresIn ? new Date(ctx.now().getTime() + expiresIn * 1000) : null,
|
||||
};
|
||||
await ctx.db.oidcPayload.upsert({ where: { id: this.key(id) }, create: { id: this.key(id), ...data }, update: data });
|
||||
}
|
||||
|
||||
private live(row: { payload: unknown; expiresAt: Date | null; consumedAt: Date | null } | null): AdapterPayload | undefined {
|
||||
if (!row || (row.expiresAt && row.expiresAt <= ctx.now())) return undefined;
|
||||
return { ...(row.payload as AdapterPayload), ...(row.consumedAt ? { consumed: Math.floor(row.consumedAt.getTime() / 1000) } : {}) };
|
||||
}
|
||||
|
||||
async find(id: string): Promise<AdapterPayload | undefined> {
|
||||
if (this.model === 'Client') return (await clientMetadataFor(ctx, id)) as AdapterPayload | undefined;
|
||||
return this.live(await ctx.db.oidcPayload.findUnique({ where: { id: this.key(id) } }));
|
||||
}
|
||||
|
||||
async findByUserCode(userCode: string) {
|
||||
return this.live(await ctx.db.oidcPayload.findFirst({ where: { model: this.model, userCode } }));
|
||||
}
|
||||
|
||||
async findByUid(uid: string) {
|
||||
return this.live(await ctx.db.oidcPayload.findFirst({ where: { model: this.model, uid } }));
|
||||
}
|
||||
|
||||
async consume(id: string) {
|
||||
await ctx.db.oidcPayload.update({ where: { id: this.key(id) }, data: { consumedAt: ctx.now() } }).catch(() => {});
|
||||
}
|
||||
|
||||
async destroy(id: string) {
|
||||
await ctx.db.oidcPayload.deleteMany({ where: { id: this.key(id) } });
|
||||
}
|
||||
|
||||
async revokeByGrantId(grantId: string) {
|
||||
if (GRANTABLE.has(this.model) || this.model === 'Grant') await ctx.db.oidcPayload.deleteMany({ where: { grantId } });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** The `oidc-cleanup` job: rows past their expiry. */
|
||||
export async function deleteExpired(ctx: Ctx) {
|
||||
return ctx.db.oidcPayload.deleteMany({ where: { expiresAt: { lt: ctx.now() } } });
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* OIDC clients (docs/ACCOUNTS-1.0-PLAN.md §4): every linked product is one, with no registration
|
||||
* screen. `client_id` is its Hub install id, the secret is derived from its link's secret, and its
|
||||
* addresses are the fixed paths on the address the Hub listed for it (exact matches only).
|
||||
*
|
||||
* Plus Accounts' own pages (`accounts-self`): the account page signs in through the same flow.
|
||||
*/
|
||||
import { oidcClientAddresses } from '@crosscode/contracts';
|
||||
import { oidcClientSecret } from '@crosscode/contracts/signing';
|
||||
import type { ClientMetadata } from 'oidc-provider';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export const SELF_CLIENT_ID = 'accounts-self';
|
||||
export const SELF_CALLBACK = '/api/self/callback';
|
||||
|
||||
const PRODUCT_NAMES: Record<string, string> = { events: 'Cross Events', website: 'the church website', app: 'the church app' };
|
||||
|
||||
export function selfClient(ctx: Ctx): ClientMetadata {
|
||||
return {
|
||||
client_id: SELF_CLIENT_ID,
|
||||
client_name: 'Your account',
|
||||
token_endpoint_auth_method: 'none',
|
||||
grant_types: ['authorization_code'],
|
||||
response_types: ['code'],
|
||||
redirect_uris: [`${ctx.config.publicUrl}${SELF_CALLBACK}`],
|
||||
post_logout_redirect_uris: [`${ctx.config.publicUrl}/signed-out`],
|
||||
};
|
||||
}
|
||||
|
||||
export async function clientMetadataFor(ctx: Ctx, clientId: string): Promise<ClientMetadata | undefined> {
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId: clientId } }).catch(() => null);
|
||||
if (!link) return undefined;
|
||||
const a = oidcClientAddresses(link.url);
|
||||
return {
|
||||
client_id: link.installId,
|
||||
client_secret: oidcClientSecret(ctx.secrets.decrypt(link.secret)),
|
||||
client_name: PRODUCT_NAMES[link.product] ?? link.product,
|
||||
token_endpoint_auth_method: 'client_secret_basic',
|
||||
grant_types: ['authorization_code'],
|
||||
response_types: ['code'],
|
||||
redirect_uris: [a.redirectUri],
|
||||
post_logout_redirect_uris: [a.postLogoutRedirectUri],
|
||||
backchannel_logout_uri: a.backchannelLogoutUri,
|
||||
backchannel_logout_session_required: true,
|
||||
'crosscode.product': link.product,
|
||||
} as ClientMetadata;
|
||||
}
|
||||
|
||||
export function productName(product: string | undefined): string {
|
||||
return (product && PRODUCT_NAMES[product]) || 'this site';
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* The few pages oidc-provider renders itself (an error, the sign-out confirmation, "signed out"),
|
||||
* in the church's colours. No inline scripts (the CSP forbids them): the sign-out page submits
|
||||
* itself with /api/static/logout.js.
|
||||
*/
|
||||
import type { KoaContextWithOIDC } from 'oidc-provider';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { branding } from '../church/profile.js';
|
||||
|
||||
const esc = (s: unknown) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!);
|
||||
|
||||
async function page(ctx: Ctx, title: string, body: string): Promise<string> {
|
||||
const b = await branding(ctx).catch(() => ({ name: 'Sign in', colours: { primary: '#1f4e79' }, logoUrl: null }));
|
||||
return `<!doctype html><html lang="en-ZA"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex">
|
||||
<title>${esc(title)} · ${esc(b.name)}</title>
|
||||
<style>body{font-family:system-ui,sans-serif;background:#f7f7f8;color:#1f2937;margin:0;display:flex;min-height:100vh;align-items:center;justify-content:center;padding:16px}
|
||||
main{background:#fff;border-radius:16px;box-shadow:0 1px 3px rgba(0,0,0,.08);padding:32px;max-width:420px;width:100%;text-align:center}
|
||||
h1{font-size:1.25rem;margin:0 0 12px}p{color:#4b5563;line-height:1.5}button,a.btn{display:inline-block;background:${esc(b.colours.primary)};color:#fff;border:0;border-radius:10px;padding:10px 20px;font-size:1rem;text-decoration:none;cursor:pointer}
|
||||
img{max-height:56px;margin-bottom:16px}</style></head>
|
||||
<body><main>${b.logoUrl ? `<img src="${esc(b.logoUrl)}" alt="">` : ''}<p style="margin:0 0 8px;font-weight:600">${esc(b.name)}</p>${body}</main></body></html>`;
|
||||
}
|
||||
|
||||
export function renderError(ctx: Ctx) {
|
||||
return async (k: KoaContextWithOIDC, out: { error: string; error_description?: string }, err?: Error) => {
|
||||
console.warn(`[oidc] ${out.error}: ${out.error_description ?? ''}${err && !(err as { expose?: boolean }).expose ? ` (${err.stack})` : ''}`);
|
||||
k.type = 'html';
|
||||
const message = out.error === 'invalid_redirect_uri' || out.error === 'invalid_client'
|
||||
? 'This sign-in link isn\'t from one of the church\'s sites, so it was stopped.'
|
||||
: out.error_description || 'Something went wrong with signing in.';
|
||||
k.body = await page(ctx, 'Sign-in problem', `<h1>We couldn't sign you in</h1><p>${esc(message)}</p><a class="btn" href="/account">Go to your account</a>`);
|
||||
};
|
||||
}
|
||||
|
||||
export function renderLogout(ctx: Ctx) {
|
||||
return async (k: KoaContextWithOIDC, form: string) => {
|
||||
k.type = 'html';
|
||||
k.body = await page(ctx, 'Signing out', `${form}<h1>Signing you out…</h1><p>You'll be signed out of all the church's sites.</p>
|
||||
<button form="op.logoutForm" type="submit" name="logout" value="yes">Sign out</button>
|
||||
<script src="/api/static/logout.js"></script>`);
|
||||
};
|
||||
}
|
||||
|
||||
export function renderLoggedOut(ctx: Ctx) {
|
||||
return async (k: KoaContextWithOIDC) => {
|
||||
k.type = 'html';
|
||||
k.body = await page(ctx, 'Signed out', '<h1>You\'re signed out</h1><p>You\'ve been signed out of all the church\'s sites.</p><a class="btn" href="/account">Sign in again</a>');
|
||||
};
|
||||
}
|
||||
|
||||
/** Submits the sign-out form straight away (the person already chose to sign out on the product). */
|
||||
export const LOGOUT_JS = 'document.addEventListener("DOMContentLoaded",function(){var f=document.getElementById("op.logoutForm");if(f){var i=document.createElement("input");i.type="hidden";i.name="logout";i.value="yes";f.appendChild(i);f.submit();}});';
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* 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'] },
|
||||
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 },
|
||||
},
|
||||
interactions: { url: (_k, interaction) => `/signin?uid=${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),
|
||||
rotateRefreshToken: false,
|
||||
issueRefreshToken: () => false,
|
||||
};
|
||||
const provider = new Provider(issuerOf(ctx), config);
|
||||
provider.proxy = ctx.config.trustProxy;
|
||||
return provider;
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* The Accounts session (oidc-provider's own cookie) for the account pages and admin, and signing
|
||||
* someone out everywhere: every session of theirs ends, and each product that session signed in to
|
||||
* is told by OIDC Back-Channel Logout (docs/ACCOUNTS-1.0-PLAN.md §3).
|
||||
*/
|
||||
import type { Request, Response } from 'express';
|
||||
import type Provider from 'oidc-provider';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { Account } from '../generated/prisma/client.js';
|
||||
|
||||
export type SignedIn = { account: Account; amr: string[]; acr: string | null; sessionId: string };
|
||||
|
||||
export async function currentSession(ctx: Ctx, provider: Provider, req: Request, res: Response): Promise<SignedIn | null> {
|
||||
const k = provider.createContext(req, res);
|
||||
const session = await provider.Session.get(k);
|
||||
if (!session?.accountId) return null;
|
||||
const account = await ctx.db.account.findUnique({ where: { id: session.accountId } });
|
||||
if (!account || account.status !== 'active') return null;
|
||||
return { account, amr: (session.amr as string[] | undefined) ?? [], acr: (session.acr as string | undefined) ?? null, sessionId: session.jti };
|
||||
}
|
||||
|
||||
type StoredSession = { authorizations?: Record<string, { sid?: string; grantId?: string }> };
|
||||
|
||||
/** Ends every session of the account and tells the products. Returns how many products were told. */
|
||||
export async function signOutEverywhere(ctx: Ctx, provider: Provider, accountId: string): Promise<number> {
|
||||
const rows = await ctx.db.oidcPayload.findMany({ where: { model: 'Session', accountId } });
|
||||
let told = 0;
|
||||
for (const row of rows) {
|
||||
const auths = (row.payload as StoredSession).authorizations ?? {};
|
||||
for (const [clientId, auth] of Object.entries(auths)) {
|
||||
if (auth.grantId) await ctx.db.oidcPayload.deleteMany({ where: { grantId: auth.grantId } });
|
||||
try {
|
||||
const client = await provider.Client.find(clientId);
|
||||
if (client?.backchannelLogoutUri) {
|
||||
await (client as unknown as { backchannelLogout(sub: string, sid: string): Promise<void> }).backchannelLogout(accountId, auth.sid ?? '');
|
||||
told++;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn(`[sessions] back-channel logout to ${clientId} failed:`, (e as Error).message);
|
||||
}
|
||||
}
|
||||
await ctx.db.oidcPayload.deleteMany({ where: { id: row.id } });
|
||||
}
|
||||
return told;
|
||||
}
|
||||
Reference in New Issue
Block a user