Files
crosscode-platform/apps/accounts/backend/src/links/deliveries.ts
T
joshuaandClaude Opus 5.5 ad488c3280 Accounts 1.9.0, @crosscode/demo 1.0.0: messaging.get, WhatsApp opt-out, demo scenarios
Accounts 1.9.0 (one migration):
- messaging.get (sealed settings) and the messaging.changed hint to products
  that asked, on admin or product changes
- the WhatsApp opt-out for every product: whatsapp.optout, Accounts' own WAWP
  webhook, WhatsAppOptOut kept per number, whatsapp_opted_out in user.updated,
  no WhatsApp from Accounts to an opted-out person, "Turn WhatsApp back on"
- demo scenarios: npm run demo -- --profile <scenario> --force replaces the
  church profile (with an SVG logo and icon at /api/demo-assets/) and the demo
  people, ids kept across loads

@crosscode/demo 1.0.0 (new): the eight scenarios' churches, people and logos.

crosscode script: crosscode demo <church> accounts, --scenario on every demo,
Accounts installs and builds packages/demo.

Checked on PostgreSQL 18: migrations, scenario loads, opt-out, npm run demo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:05:22 +02:00

73 lines
4.1 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`, `church.changed` and (1.9.0) `messaging.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, MESSAGING_CHANGED_PATH } 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' | 'messaging.changed';
/** Where each call goes on the product. 1.9.0 adds messaging.changed (only to products that asked for the settings). */
const PATHS: Partial<Record<CallType, string>> = { 'church.changed': CHURCH_PATHS.changed, 'messaging.changed': MESSAGING_CHANGED_PATH };
/** 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: PATHS[type] ?? 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 };
}