/** * The church's Accounts, as this site's OIDC client (WEBSITE-1.0-PLAN §1, §10), built on * `@crosscode/auth-client` from the Accounts link (links/connect.ts). Its address is the one the * Hub listed; the client id is this site's Hub install id and the client secret comes from the * link's secret, so there's no `.env` setting for any of it (as Cross Events 3.x). */ import type * as AuthClient from '@crosscode/auth-client'; import type { AccountsClient } from '@crosscode/auth-client'; import type { Ctx } from '../context.js'; import { ApiError } from '../http.js'; export type AuthClientModule = typeof AuthClient; export const loadAuthClient = (): Promise => import('@crosscode/auth-client'); export class AccountsUnavailable extends ApiError { constructor(message: string) { super(503, 'ACCOUNTS_UNAVAILABLE', message); } } /** The Accounts link, or null while the Website isn't linked to Accounts. */ export async function accountsLink(ctx: Ctx) { return ctx.db.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } }); } const cache = new WeakMap }>(); /** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */ export async function accounts(ctx: Ctx): Promise { const link = await accountsLink(ctx); if (!link) throw new AccountsUnavailable('The Website isn\'t linked to the church\'s Accounts yet. It links by itself within 15 minutes of being installed.'); const clientId = await ctx.settings.get('hub_install_id'); if (!clientId) throw new AccountsUnavailable('The Website isn\'t connected to the Hub yet.'); const key = `${link.installId}|${link.updatedAt.getTime()}|${clientId}|${ctx.config.publicUrl}`; let hit = cache.get(ctx); if (!hit || hit.key !== key) { const client = ctx.authClient().then((m) => m.accountsClient({ accountsUrl: link.url, productUrl: ctx.config.publicUrl, clientId, linkSecret: ctx.secrets.decrypt(link.secret), allowInsecure: !ctx.config.production && link.url.startsWith('http:'), })); // A failed discovery (Accounts down for a moment) is tried again next time. client.catch(() => { if (cache.get(ctx)?.key === key) cache.delete(ctx); }); hit = { key, client }; cache.set(ctx, hit); } try { return await hit.client; } catch (e) { throw new AccountsUnavailable(`The church's Accounts can't be reached right now (${(e as Error).message}). Please try again in a minute.`); } }