Files
crosscode-platform/apps/events/backend/src/links/connect.ts
T
joshuaandClaude Opus 5.5 f6a536ad64 Accounts 1.7.1, Website 1.0.2, Events 3.7.1: link right after an install; Preview behind the proxy
Found installing the Website for cross-demo2.

- All three: a connect involving an install that isn't in the cached copy
  of the Hub's list yet asks the Hub for a fresh list (one heartbeat, at
  most once a minute) instead of refusing. A new Website's admin couldn't
  sign in for up to 30 minutes.
- Accounts: a heartbeat on every start.
- Website: /admin links to Accounts on the spot (at most every 15 s), one
  connect to Accounts at a time, and the problem page says "not linked
  yet" (ACCOUNTS_NOT_LINKED). Preview redirected to the server's own
  http://localhost:<web port>: the preview routes now answer with a
  relative Location.
- Events: a new Website can connect for the event feed straight away.
- docs: VERSIONS, changelogs, WHATS-NEW.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:14:20 +02:00

215 lines
11 KiB
TypeScript

/**
* 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<void> };
/* 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;
const REFRESH_EVERY_MS = 60 * 1000;
let refresh: { at: number; run: Promise<unknown> } | null = null;
/** For tests. */
export function forgetRefresh(): void {
refresh = null;
}
/**
* 3.7.1: the install as the Hub listed it. If the cached list doesn't have it yet (it was installed
* after this site's last heartbeat, like a new Church Website), the site asks the Hub for a fresh
* list with a heartbeat and looks again, instead of refusing for up to 15 minutes. There's at most
* one such heartbeat a minute, so a message from an unknown install can't make this site call the
* Hub more often than that.
*/
async function listedOrRefreshed(installId: string, now: Date) {
const found = await listedProduct(installId);
if (found) return found;
if (!refresh || now.getTime() - refresh.at >= REFRESH_EVERY_MS) {
// eslint-disable-next-line @typescript-eslint/no-require-imports -- CommonJS, and hub/client.js needs this module's siblings
const run = Promise.resolve().then(() => require('../hub/client').heartbeat())
.catch((e: Error) => console.warn('[links] Asking the Hub for a fresh list failed:', e?.message || e));
refresh = { at: now.getTime(), run };
}
await refresh.run;
return listedProduct(installId);
}
type Self = { installId: string; url: string; privateKeyPem: string };
async function self(): Promise<Self> {
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<boolean> {
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 listedOrRefreshed(installId, now);
if (!sibling) throw new LinkError('The Hub doesn\'t list that product for this church.', 'NOT_LINKED', 404);
const me = await self();
const secret = newLinkSecret();
const message = signLink<Omit<LinkConnect, 'signature'>>({
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<string, unknown>, 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<LinkConnected> {
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 listedOrRefreshed(m.from.installId, now);
if (!sibling || sibling.product !== m.from.product) {
throw new LinkError('The Hub doesn\'t list that install for this church (this site asks it again at most once a minute).', 'NOT_LINKED', 403);
}
const check = verifyLink(m as unknown as Record<string, unknown>, 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<Omit<LinkConnected, 'signature'>>({
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<Omit<LinkDisconnect, 'signature'>>({
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<void> {
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<string, unknown>, 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' });
}