/** * Connect and Disconnect (`crosscode.link/1`, docs/EVENTS-2.4-PLAN.md §2). * * Trust comes from the Hub's list on both sides: a message is accepted only from an install in * this site's own cached `linkedProducts` (same church), signed with the key the Hub listed for * it. The Hub isn't called while connecting. Both sides then hold the same secret, which signs the * calls between them (the `event.changed` webhook). */ import { LINK_PATHS, LINK_SCHEMA, linkConnectedSchema, linkConnectSchema, linkDisconnectSchema, type LinkConnect, type LinkConnected, type LinkDisconnect, type hub, } from '@crosscode/contracts'; import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing'; import { hubInstallId, siteUrl } from '../feed/context'; import { callSibling, LinkCallError, siblingUrl } from './http'; import { keyPair, listedProduct } from './store'; /* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */ const prisma = require('../config/db'); const { encrypt } = require('../utils/encryption') as { encrypt(v: string): string }; const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise }; /* eslint-enable @typescript-eslint/no-require-imports */ export class LinkError extends Error { constructor(message: string, public code: string, public status = 400) { super(message); } } const NONCE_KEEP_MS = 60 * 60 * 1000; type Self = { installId: string; url: string; privateKeyPem: string }; async function self(): Promise { const installId = await hubInstallId(); if (!installId) throw new LinkError('This site isn\'t connected to the Hub, so it can\'t link to other products yet.', 'LINKS_UNAVAILABLE', 503); const url = await siteUrl(); if (!/^https?:\/\//.test(url)) throw new LinkError('Set the site\'s web address first (Site settings → Organisation).', 'LINKS_UNAVAILABLE', 503); const { privateKeyPem } = await keyPair(); return { installId, url, privateKeyPem }; } const party = (s: Self) => ({ product: 'events' as const, installId: s.installId, url: s.url }); /** Records a nonce; false when it was seen before (a replay). Old nonces are cleaned up. */ async function firstUse(nonce: string, now: Date): Promise { await prisma.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {}); try { await prisma.linkNonce.create({ data: { nonce, seenAt: now } }); return true; } catch (e) { if ((e as { code?: string })?.code === 'P2002') return false; throw e; } } async function audit(action: string, link: { installId: string; product: string }, actor: { id: string | null; role: string } | null, ip: string | null, metadata: object = {}) { await logAdminAction({ actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, ...metadata }, ip, }); } async function saveLink(sibling: hub.LinkedProduct, secret: string, connectedById: string | null, now: Date) { const data = { product: sibling.product, url: sibling.url, publicKey: sibling.publicKey, secret: encrypt(secret), connectedAt: now, connectedById, lastSyncError: null }; return prisma.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data }); } // ─── This site connects (an admin clicked Connect) ───────────────────────────── export async function connectTo(installId: string, actor: { id: string | null; role: string }, ip: string | null, now = new Date()) { const sibling = await listedProduct(installId); if (!sibling) 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(); const secret = newLinkSecret(); const message = signLink>({ schema: LINK_SCHEMA, type: 'link.connect', from: party(me), to: { installId: sibling.installId }, secret, issuedAt: now.toISOString(), nonce: newLinkNonce(), }, me.privateKeyPem); let reply: unknown; try { reply = await callSibling(await siblingUrl(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; const check = verifyLink(r as unknown as Record, sibling.publicKey, { now: new Date() }); if (!check.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(sibling, secret, actor.id, now); await audit('product_link_connected', link, actor, ip, { by: 'this_site' }); return link; } // ─── A sibling connects to this site ─────────────────────────────────────────── /** Answers `POST /api/links/v1/connect`. Throws LinkError (with the code the sibling is told). */ export async function acceptConnect(body: unknown, ip: string | null, now = new Date()): 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(); if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400); const sibling = await listedProduct(m.from.installId); if (!sibling || sibling.product !== m.from.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 }); 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(m.nonce, now))) throw new LinkError('That message was already used.', 'REPLAYED', 409); const link = await saveLink(sibling, m.secret, null, now); await audit('product_link_connected', link, null, ip, { by: 'sibling' }); return signLink>({ schema: LINK_SCHEMA, type: 'link.connected', from: party(me), to: { installId: sibling.installId }, inReplyTo: m.nonce, issuedAt: new Date().toISOString(), nonce: newLinkNonce(), }, me.privateKeyPem); } // ─── Disconnect ─────────────────────────────────────────────────────────────── /** This site ends a link. The local link goes even if the sibling can't be reached. */ export async function disconnectFrom(installId: string, actor: { id: string; role: string }, ip: string | null, now = new Date()): Promise<{ siblingTold: boolean; message: string | null }> { const link = await prisma.productLink.findUnique({ where: { installId } }); if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404); let siblingTold = false; let problem: string | null = null; try { const me = await self(); const message = signLink>({ schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: now.toISOString(), nonce: newLinkNonce(), }, me.privateKeyPem); await callSibling(await siblingUrl(link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) }); siblingTold = true; } catch (e) { problem = (e as Error).message; } // Its imported events go with it (ImportedEvent cascades). await prisma.productLink.delete({ where: { installId } }); await audit('product_link_disconnected', link, actor, ip, { by: 'this_site', siblingTold }); return { siblingTold, message: problem }; } /** Answers `POST /api/links/v1/disconnect`, checked against the key saved when the link was made. */ export async function acceptDisconnect(body: unknown, ip: string | null, now = new Date()): 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(); if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400); const link = await prisma.productLink.findUnique({ where: { installId: m.from.installId } }); // Already gone: nothing to do, and nothing to tell (the sibling just wants it ended). if (!link) return; const check = verifyLink(m as unknown as Record, link.publicKey, { now }); if (!check.ok) throw new LinkError('The signature doesn\'t match this link.', check.code, 401); if (!(await firstUse(m.nonce, now))) throw new LinkError('That message was already used.', 'REPLAYED', 409); await prisma.productLink.delete({ where: { installId: link.installId } }); await audit('product_link_disconnected', link, null, ip, { by: 'sibling' }); }