/** * Connect and Disconnect (`crosscode.link/1`, as Cross Events 2.4 and Accounts). The Website links * to the church's **Accounts** (signing in: the link's secret is where the client secret comes * from, and Accounts registers this site as an OIDC client when it accepts) and, for the event * feed, to **Events** and later the **App**. * * Trust comes from the Hub's list on both sides: a message is accepted only from an install in this * site's cached `linkedProducts` (same church), signed with the key the Hub listed for it. */ 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, linkedProducts, listedProduct } from './store.js'; export class LinkError extends Error { constructor(message: string, public code: string, public status = 400) { super(message); } } /** The products the Website links to. */ const LINKABLE = new Set(['accounts', 'events', 'app']); const NONCE_KEEP_MS = 60 * 60 * 1000; type Actor = { id: string | null; role: string }; async function self(ctx: Ctx) { const installId = await ctx.settings.get('hub_install_id'); if (!installId) throw new LinkError('The Website 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: 'website' 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, lastSyncError: null }; 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: Actor | 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) }); /** This site connects (an admin pressed Connect, or the automatic connect to Accounts below). */ export async function connectTo(ctx: Ctx, installId: string, actor: Actor, req?: Request) { const sibling = await listedProduct(ctx, installId); if (!sibling || !LINKABLE.has(sibling.product)) throw new LinkError('That product isn\'t in the list the Hub gave this site. 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 this site doesn't understand.`, 'BAD_REPLY', 502); const r: LinkConnected = parsed.data; if (!verifyLink(r as unknown as Record, sibling.publicKey, { now: ctx.now() }).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, 'website'); return link; } /** Answers `POST /api/links/v1/connect` (a sibling's admin pressed Connect there). */ 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 || !LINKABLE.has(sibling.product)) { throw new LinkError('This site 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); } /** This site ends a link. The local link goes even if the sibling can't be reached. */ export async function disconnectFrom(ctx: Ctx, installId: string, actor: Actor, 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, 'website'); return { told, problem }; } /** Answers `POST /api/links/v1/disconnect`, checked against the key saved when the link was made. */ 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); } /** * The Website signs in through Accounts, so it connects to the church's Accounts by itself once the * Hub lists one and nothing is linked yet (as Events 3.x's autoConnect). Run after each heartbeat. * Never throws: a failure is tried again at the next heartbeat. */ export async function connectAccountsIfListed(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> { if (await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })) return 'skipped'; const listed = (await linkedProducts(ctx)).find((p) => p.product === 'accounts'); if (!listed) return 'skipped'; try { await connectTo(ctx, listed.installId, { id: null, role: 'system' }); return 'connected'; } catch (e) { console.warn('[links] Connecting to Accounts failed:', (e as Error).message); return 'failed'; } }