Files
crosscode-platform/apps/events/backend/src/accounts/client.ts
T
joshuaandClaude Opus 5.5 c627c61de1 Cross Events 3.0.0: sign-in through the church's Accounts
Settings -> Sign-in: check, move (everyone into Accounts with their password
hashes and authenticator apps, count/hash check, then switch) and undo for
14 days. Sign-in through auth-client with a one-time handoff to Events' own
token; staff roles stepped up to mfa; sign-out and back-channel logout;
user.updated/export/deleted; admin 2FA reset, unlock and profile changes via
Accounts; /login, /register, /forgot-password forward once moved; Events'
own sign-in endpoints answer SIGN_IN_MOVED. User.accountId, AccountsSignIn.

npm run test:accounts runs Events' code against the real Accounts app (11
tests); 5 new Jest tests. MIGRATING-TO-3.md, plan "Changes while building".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:10:30 +02:00

75 lines
3.5 KiB
TypeScript

/**
* The church's Accounts, as this site's OIDC client (3.0.0, docs/EVENTS-3.0-PLAN.md §1): built on
* `@crosscode/auth-client` from the Accounts link that Connect made (Settings → Linked products).
* Its address is the one the Hub listed; its client id is this site's Hub install id and its client
* secret comes from the link's secret, so there's no `.env` setting for any of it.
*
* `@crosscode/auth-client` and `openid-client` are ES modules and this backend is CommonJS, which
* compiles `import()` into `require()`. The loader below keeps a real dynamic import, so it works on
* every Node the servers run (20+), not only where `require()` of ES modules is allowed.
*/
import type { AccountsClient } from '@crosscode/auth-client';
import { hubInstallId, siteUrl } from '../feed/context';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
/* eslint-enable @typescript-eslint/no-require-imports */
export type AuthClientModule = typeof import('@crosscode/auth-client');
// eslint-disable-next-line @typescript-eslint/no-implied-eval -- a real import(), see above
const importEsm = new Function('specifier', 'return import(specifier)') as (s: string) => Promise<AuthClientModule>;
let loader: () => Promise<AuthClientModule> = () => importEsm('@crosscode/auth-client');
/** Tests: use another auth-client (a fake, or the real one loaded another way). */
export function setAuthClientLoader(next: () => Promise<AuthClientModule>): void {
loader = next;
cached = null;
}
export class AccountsUnavailable extends Error {
status = 503;
code = 'ACCOUNTS_UNAVAILABLE';
}
export type AccountsLink = { installId: string; url: string; secret: string; updatedAt: Date };
/** The Accounts link, or null when Accounts isn't connected. */
export async function accountsLink(): Promise<AccountsLink | null> {
return prisma.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } });
}
let cached: { key: string; client: Promise<AccountsClient> } | null = null;
/** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */
export async function accounts(): Promise<AccountsClient> {
const link = await accountsLink();
if (!link) throw new AccountsUnavailable('Accounts isn\'t connected. Connect it under Settings → Linked products.');
const [clientId, productUrl] = await Promise.all([hubInstallId(), siteUrl()]);
if (!clientId) throw new AccountsUnavailable('This site isn\'t connected to the Hub yet.');
const key = `${link.installId}|${new Date(link.updatedAt).getTime()}|${clientId}|${productUrl}`;
if (!cached || cached.key !== key) {
const client = loader().then((m) => m.accountsClient({
accountsUrl: link.url,
productUrl,
clientId,
linkSecret: decrypt(link.secret),
allowInsecure: process.env.NODE_ENV !== 'production' && link.url.startsWith('http:'),
}));
// A failed discovery (Accounts down for a moment) is tried again next time.
client.catch(() => { if (cached?.key === key) cached = null; });
cached = { key, client };
}
try {
return await cached.client;
} catch (e) {
throw new AccountsUnavailable(`Accounts can't be reached right now (${(e as Error).message}). Please try again in a minute.`);
}
}
/** The module itself (for its error classes). */
export function authClientModule(): Promise<AuthClientModule> {
return loader();
}