/** * Back-channel calls to linked products (docs/ACCOUNTS-1.0-PLAN.md ยง6): `crosscode.identity/1` * user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, and `church.changed`. Each is a * `Delivery`, signed with the link's secret (`LINK_HEADERS`), retried after 1 min, 5 min, 30 min, * 2 h, 12 h, then daily for a week. The reply is kept, and `onReply` acts on it (deletion, * export). */ import crypto from 'node:crypto'; import { ACCOUNTS_CALL_PATH, CHURCH_PATHS } from '@crosscode/contracts'; import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing'; import type { Ctx } from '../context.js'; import { callSibling, siblingUrl } from './http.js'; const RETRY_MS = [60e3, 5 * 60e3, 30 * 60e3, 2 * 3600e3, 12 * 3600e3, ...Array(7).fill(24 * 3600e3)] as number[]; export const MAX_ATTEMPTS = RETRY_MS.length + 1; export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed'; /** Queues a call to every linked product (or the ones given). Returns the deliveries made. */ export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: string) => object, opts: { linkIds?: string[] } = {}) { const links = await ctx.db.productLink.findMany(opts.linkIds ? { where: { installId: { in: opts.linkIds } } } : undefined); const made = []; for (const link of links) { const callId = crypto.randomUUID(); made.push(await ctx.db.delivery.create({ data: { linkId: link.installId, callId, type, path: type === 'church.changed' ? CHURCH_PATHS.changed : ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() }, })); } return made; } type ReplyHandler = (ctx: Ctx, delivery: { id: string; linkId: string; type: string; body: unknown }, reply: unknown) => Promise; const handlers = new Map(); /** What to do with a product's answer to a call type (privacy/deletion.ts, privacy/export.ts). */ export function onReply(type: CallType, handler: ReplyHandler) { handlers.set(type, handler); } export async function send(ctx: Ctx, deliveryId: string): Promise { const d = await ctx.db.delivery.findUnique({ where: { id: deliveryId } }); if (!d || d.status !== 'pending') return false; const link = await ctx.db.productLink.findUnique({ where: { installId: d.linkId } }); const sender = await ctx.settings.get('hub_install_id'); const attempts = d.attempts + 1; try { if (!link || !sender) throw new Error(link ? 'Accounts isn\'t connected to the Hub' : 'The product is no longer linked'); const raw = JSON.stringify(d.body); const headers = signedHeaders(LINK_HEADERS, { senderId: sender, secret: ctx.secrets.decrypt(link.secret), rawBody: raw, now: ctx.now() }); const reply = await callSibling(await siblingUrl(ctx, link.url, d.path), { method: 'POST', body: raw, headers }); await ctx.db.delivery.update({ where: { id: d.id }, data: { status: 'delivered', attempts, deliveredAt: ctx.now(), reply: (reply ?? null) as never, lastError: null } }); await handlers.get(d.type)?.(ctx, d, reply); return true; } catch (e) { const failed = attempts >= MAX_ATTEMPTS || !link; await ctx.db.delivery.update({ where: { id: d.id }, data: { attempts, lastError: String((e as Error).message).slice(0, 500), status: failed ? 'failed' : 'pending', nextAttemptAt: new Date(ctx.now().getTime() + (RETRY_MS[attempts - 1] ?? RETRY_MS.at(-1)!)) }, }); return false; } } /** The `deliveries` job (every minute): everything due, oldest first. */ export async function runDue(ctx: Ctx, limit = 50) { const due = await ctx.db.delivery.findMany({ where: { status: 'pending', nextAttemptAt: { lte: ctx.now() } }, orderBy: { nextAttemptAt: 'asc' }, take: limit }); let sent = 0; for (const d of due) if (await send(ctx, d.id)) sent++; return { due: due.length, sent }; }