/** * Connect and Disconnect (`crosscode.link/1`, as Cross Events 2.4). On Accounts a link is also the * product's **OIDC client** (docs/ACCOUNTS-1.0-PLAN.md ยง4, oidc/clients.ts): connecting registers * it, disconnecting removes it. Usually the product connects (an admin there clicks Connect on * Accounts); an Accounts admin can connect from here too. */ import { LINK_PATHS, LINK_SCHEMA, linkConnectedSchema, linkConnectSchema, linkDisconnectSchema, type hub, type LinkConnect, type LinkConnected, type LinkDisconnect, } from '@crosscode/contracts'; import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing'; import type { Request } from 'express'; import type { Ctx } from '../context.js'; import { audit, clientIp } from '../lib/audit.js'; import { callSibling, LinkCallError, siblingUrl } from './http.js'; import { keyPair, listedProduct } from './store.js'; export class LinkError extends Error { constructor(message: string, public code: string, public status = 400) { super(message); } } /** Products that sign people in through Accounts. */ const CLIENT_PRODUCTS = new Set(['events', 'website', 'app']); const NONCE_KEEP_MS = 60 * 60 * 1000; async function self(ctx: Ctx) { const installId = await ctx.settings.get('hub_install_id'); if (!installId) throw new LinkError('Accounts isn\'t connected to the Hub yet, so it can\'t link to other products.', 'LINKS_UNAVAILABLE', 503); const { privateKeyPem } = await keyPair(ctx); return { installId, url: ctx.config.publicUrl, privateKeyPem }; } const party = (s: { installId: string; url: string }) => ({ product: 'accounts' as const, installId: s.installId, url: s.url }); async function firstUse(ctx: Ctx, nonce: string): Promise { const now = ctx.now(); await ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {}); try { await ctx.db.linkNonce.create({ data: { nonce, seenAt: now } }); return true; } catch (e) { if ((e as { code?: string }).code === 'P2002') return false; throw e; } } async function saveLink(ctx: Ctx, sibling: hub.LinkedProduct, secret: string, connectedById: string | null) { const data = { product: sibling.product, url: sibling.url.replace(/\/+$/, ''), publicKey: sibling.publicKey, secret: ctx.secrets.encrypt(secret), connectedAt: ctx.now(), connectedById }; return ctx.db.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data }); } const logLink = (ctx: Ctx, action: string, link: { installId: string; product: string }, actor: { id: string; role: string } | null, req: Request | undefined, by: string) => audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) }); export async function connectTo(ctx: Ctx, installId: string, actor: { id: string; role: string }, req?: Request) { const sibling = await listedProduct(ctx, installId); if (!sibling || !CLIENT_PRODUCTS.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave Accounts. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404); const me = await self(ctx); const secret = newLinkSecret(); const message = signLink>({ schema: LINK_SCHEMA, type: 'link.connect', from: party(me), to: { installId: sibling.installId }, secret, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(), }, me.privateKeyPem); let reply: unknown; try { reply = await callSibling(await siblingUrl(ctx, sibling.url, LINK_PATHS.connect), { method: 'POST', body: JSON.stringify(message) }); } catch (e) { if (e instanceof LinkCallError) throw new LinkError(`${sibling.url} refused to connect: ${e.message}`, e.code, 502); throw e; } const parsed = linkConnectedSchema.safeParse(reply); if (!parsed.success) throw new LinkError(`${sibling.url} answered in a way Accounts doesn't understand.`, 'BAD_REPLY', 502); const r: LinkConnected = parsed.data; if (!verifyLink(r as unknown as Record, sibling.publicKey).ok || r.inReplyTo !== message.nonce || r.from.installId !== sibling.installId || r.to.installId !== me.installId) { throw new LinkError(`${sibling.url}'s answer isn't signed with the key the Hub listed for it.`, 'BAD_SIGNATURE', 502); } const link = await saveLink(ctx, sibling, secret, actor.id); await logLink(ctx, 'product_link_connected', link, actor, req, 'accounts'); return link; } export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): Promise { const parsed = linkConnectSchema.safeParse(body); if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 connect message.', 'INVALID_REQUEST', 400); const m = parsed.data; const me = await self(ctx); if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400); const sibling = await listedProduct(ctx, m.from.installId); if (!sibling || sibling.product !== m.from.product || !CLIENT_PRODUCTS.has(sibling.product)) { throw new LinkError('Accounts doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403); } const check = verifyLink(m as unknown as Record, sibling.publicKey, { now: ctx.now() }); if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401); if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409); const link = await saveLink(ctx, sibling, m.secret, null); await logLink(ctx, 'product_link_connected', link, null, req, sibling.product); return signLink>({ schema: LINK_SCHEMA, type: 'link.connected', from: party(me), to: { installId: sibling.installId }, inReplyTo: m.nonce, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(), }, me.privateKeyPem); } export async function disconnectFrom(ctx: Ctx, installId: string, actor: { id: string; role: string }, req?: Request) { const link = await ctx.db.productLink.findUnique({ where: { installId } }); if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404); let told = false; let problem: string | null = null; try { const me = await self(ctx); const message = signLink>({ schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce() }, me.privateKeyPem); await callSibling(await siblingUrl(ctx, link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) }); told = true; } catch (e) { problem = (e as Error).message; } await ctx.db.productLink.delete({ where: { installId } }); await logLink(ctx, 'product_link_disconnected', link, actor, req, 'accounts'); return { told, problem }; } export async function acceptDisconnect(ctx: Ctx, body: unknown, req?: Request): Promise { const parsed = linkDisconnectSchema.safeParse(body); if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 disconnect message.', 'INVALID_REQUEST', 400); const m = parsed.data; const me = await self(ctx); if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400); const link = await ctx.db.productLink.findUnique({ where: { installId: m.from.installId } }); if (!link) return; if (!verifyLink(m as unknown as Record, link.publicKey, { now: ctx.now() }).ok) throw new LinkError('The signature doesn\'t match this link.', 'BAD_SIGNATURE', 401); if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409); await ctx.db.productLink.delete({ where: { installId: link.installId } }); await logLink(ctx, 'product_link_disconnected', link, null, req, link.product); }