/** * 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; let loader: () => Promise = () => importEsm('@crosscode/auth-client'); /** Tests: use another auth-client (a fake, or the real one loaded another way). */ export function setAuthClientLoader(next: () => Promise): 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 { return prisma.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } }); } let cached: { key: string; client: Promise } | null = null; /** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */ export async function accounts(): Promise { 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 { return loader(); }