/** * What the church's other products call (`crosscode.link/1` and friends), as the Website's * links/routes.ts. Errors use the link protocol's `{ code, message }`. * * POST /links/v1/connect, /disconnect a sibling connects or disconnects * POST /church/v1/changed Accounts: the church profile changed (signed) * * GET /feed/v1/events?updatedSince= the App's events (crosscode.event-feed/1), public * POST /feed/v1/changed a sibling's events changed: fetch them now (signed) * * POST /accounts/v1/messaging-changed Accounts: the church's email or WhatsApp settings changed: * fetch them again (signed, APP-1.0-PLAN ยง8) */ import express from 'express'; import { CHURCH_PATHS, churchChangedSchema, eventChangedSchema, FEED_PATHS, IDENTITY_REQUEST_SCHEMA, LINK_PATHS, MESSAGING_CHANGED_PATH, messagingChangedSchema } from '@crosscode/contracts'; import { LINK_HEADERS, verify } from '@crosscode/contracts/signing'; import type { Ctx } from '../context.js'; import { churchChanged } from '../church/profile.js'; import { acceptConnect, acceptDisconnect, LinkError } from './connect.js'; import { buildFeed, publishOn, syncLink } from '../events/feed.js'; import { enabledModules } from '../modules.js'; import { fetchMessagingSoon } from '../messaging/settings.js'; export function linksRouter(ctx: Ctx) { const r = express.Router(); const json = express.json({ limit: '32kb' }); const say = (res: express.Response, status: number, code: string, message: string) => res.status(status).json({ code, message }); const fail = (res: express.Response, e: unknown) => { if (e instanceof LinkError) return say(res, e.status, e.code, e.message); console.error('[links]', e); return say(res, 500, 'INTERNAL', 'Something went wrong.'); }; r.post(LINK_PATHS.connect.replace(/^\/api/, ''), json, async (req, res) => { try { res.json(await acceptConnect(ctx, req.body, req)); } catch (e) { fail(res, e); } }); r.post(LINK_PATHS.disconnect.replace(/^\/api/, ''), json, async (req, res) => { try { await acceptDisconnect(ctx, req.body, req); res.json({ ok: true }); } catch (e) { fail(res, e); } }); /** A signed message from a linked sibling: its link, or the reason it's refused. */ async function signedBy(req: express.Request, res: express.Response, accountsOnly = false) { const sender = String(req.get(LINK_HEADERS.sender) || ''); const link = sender ? await ctx.db.productLink.findUnique({ where: { installId: sender } }) : null; if (!link || (accountsOnly && link.product !== 'accounts')) { say(res, 404, 'NOT_LINKED', 'The App has no link with that install.'); return null; } const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from(''); const check = verify({ secret: ctx.secrets.decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody, now: ctx.now() }); if (!check.ok) { say(res, 401, check.code, 'The signature doesn\'t match this link.'); return null; } let body: unknown; try { body = JSON.parse(rawBody.toString('utf8')); } catch { body = null; } return { link, body }; } const raw = express.raw({ type: () => true, limit: '16kb' }); r.get(FEED_PATHS.events.replace(/^\/api/, ''), async (req, res) => { try { if (!(await enabledModules(ctx)).includes('events') || !(await publishOn(ctx))) return say(res, 404, 'FEED_OFF', 'The App doesn\'t publish its events.'); if (!(await ctx.settings.get('hub_install_id'))) return say(res, 503, 'FEED_UNAVAILABLE', 'The App isn\'t connected to the Hub yet, so it has no feed.'); const rawSince = typeof req.query.updatedSince === 'string' ? req.query.updatedSince : null; const since = rawSince ? new Date(rawSince) : null; if (rawSince && (!since || !Number.isFinite(since.getTime()))) return say(res, 400, 'INVALID_REQUEST', 'updatedSince must be an ISO 8601 date and time.'); res.set('Cache-Control', 'no-store'); return res.json(await buildFeed(ctx, since)); } catch (e) { return fail(res, e); } }); r.post(FEED_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => { try { const got = await signedBy(req, res); if (!got) return undefined; if (!eventChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t an event.changed message.'); // Fetched after answering: the sibling doesn't wait for it. if (got.link.showEvents) setImmediate(() => { syncLink(ctx, got.link).catch(() => {}); }); return res.status(202).json({ accepted: true, fetching: got.link.showEvents }); } catch (e) { return fail(res, e); } }); r.post(CHURCH_PATHS.changed.replace(/^\/api/, ''), raw, async (req, res) => { try { const got = await signedBy(req, res, true); if (!got) return undefined; if (!churchChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t a church.changed message.'); churchChanged(ctx); return res.status(202).json({ accepted: true }); } catch (e) { return fail(res, e); } }); r.post(MESSAGING_CHANGED_PATH.replace(/^\/api/, ''), raw, async (req, res) => { try { const got = await signedBy(req, res, true); if (!got) return undefined; if (!messagingChangedSchema.safeParse(got.body).success) return say(res, 400, 'INVALID_REQUEST', 'That isn\'t a messaging.changed message.'); // Fetched after answering: Accounts doesn't wait for it (the send job tries again if it fails). fetchMessagingSoon(ctx); return res.json({ schema: IDENTITY_REQUEST_SCHEMA, ok: true }); } catch (e) { return fail(res, e); } }); return r; }