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,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;
|
||||
}
|
||||
Reference in New Issue
Block a user