Files
crosscode-platform/apps/accounts/backend/src/links/deliveries.ts
T
joshuaandClaude Opus 5.5 069b66fd30 Accounts 1.0.0 backend: OIDC provider, sign-in steps, account and admin API
oidc-provider 9.13.3 with PKCE, ES256, crosscode.identity/1 claims and
back-channel logout; clients are the linked products (Connect). Sign-in
steps (password, sign-up, email check, 2FA and its setup, privacy notice,
news question, password reset) survive to the product. Account page and
admin API, church profile, export and deletion fan-out, Hub v2 client,
jobs. End-to-end tests with a test product on openid-client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:33:49 +02:00

70 lines
3.8 KiB
TypeScript

/**
* 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<void>;
const handlers = new Map<string, ReplyHandler>();
/** 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<boolean> {
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 };
}