/** * What a linked product asks of Accounts (`crosscode.identity-request/1`, contracts 1.8.0, * docs/EVENTS-3.0-PLAN.md §4 and §8), at `POST /api/accounts/v1/requests`, signed with the link's * secret (`LINK_HEADERS`, the sender header carrying the product's install id): * * - `import.*`: moving the product's users in (Cross Events 3.0) with their password hashes and * authenticator secrets, which arrive sealed with the link's secret. Only Events imports, and * only between `import.begin` and `import.finish` / `import.abort`. * - `people.*`: what the product's admins can do to an account from the product. Only for people * the product knows (`ProductPerson`: imported, added or signed in through it). * * A request id seen before gets the first answer again, so a product can retry safely. */ import crypto from 'node:crypto'; import express, { type Request, type Response } from 'express'; import type Provider from 'oidc-provider'; import { ACCOUNTS_REQUEST_PATH, DEMO_EMAIL_DOMAIN, IDENTITY_REQUEST_SCHEMA, identityRequestSchema, type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult, } from '@crosscode/contracts'; import { LINK_HEADERS, openLinkValue, sealLinkValue, verify } from '@crosscode/contracts/signing'; import type { Ctx } from '../context.js'; import type { ProductLink } from '../generated/prisma/client.js'; import { limit } from '../http.js'; import { audit, clientIp, loginEvent } from '../lib/audit.js'; import { newAccountEmail, testEmail } from '../lib/emails.js'; import { hashToken, randomToken } from '../lib/crypto.js'; import { appVersion } from '../lib/version.js'; import { BUILT_IN_VERSION } from '../privacy/notice.js'; import { emailProblem, normaliseEmail, profileChanged, profileOf, setNewsConsent } from '../accounts/service.js'; import { turnOff } from '../accounts/twoFactor.js'; import { signOutEverywhere } from '../oidc/sessions.js'; import { anonymise } from '../privacy/deletion.js'; import { ProfileChangedError, ProfileError, updateProfile } from '../church/profile.js'; import { applyKnownOptOut, optOutNumber } from '../accounts/whatsapp.js'; import { messagingChanged } from './messaging.js'; /** Products that may change the church profile with church.update (1.7.0, WEBSITE-1.0-PLAN decision 10). */ const PROFILE_EDITORS = new Set(['website']); /** A demo person's address (contracts DEMO_EMAIL_DOMAIN, reserved: no real person has one). */ export const isDemoEmail = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`); export class RequestError extends Error { constructor(message: string, public code: string, public status = 400) { super(message); } } /** Products that may move their users in. */ const IMPORTERS = new Set(['events']); const SET_PASSWORD_DAYS = 7; const KEEP_REQUESTS_DAYS = 30; const reply = (body: T) => ({ schema: IDENTITY_REQUEST_SCHEMA, ...body }); const header = (req: Request, name: string) => { const v = req.headers[name]; return Array.isArray(v) ? v[0] : v; }; /** The link the request came from, after checking its signature. */ async function linkFor(ctx: Ctx, req: Request, raw: Buffer): Promise<{ link: ProductLink; secret: string }> { const sender = header(req, LINK_HEADERS.sender); const link = sender ? await ctx.db.productLink.findUnique({ where: { installId: String(sender) } }) : null; if (!link) throw new RequestError('That product isn\'t connected to Accounts.', 'NOT_LINKED', 403); const secret = ctx.secrets.decrypt(link.secret); const check = verify({ secret, timestamp: header(req, LINK_HEADERS.timestamp), signature: header(req, LINK_HEADERS.signature), rawBody: raw, now: ctx.now() }); if (!check.ok) throw new RequestError(check.code === 'STALE_REQUEST' ? 'The request is too old, or a clock is wrong.' : 'The request isn\'t signed with this link\'s secret.', check.code, 401); return { link, secret }; } async function knows(ctx: Ctx, linkId: string, accountId: string, via: string, opts: { upgrade?: boolean } = {}) { const existing = await ctx.db.productPerson.findFirst({ where: { linkId, accountId } }); if (!existing) await ctx.db.productPerson.create({ data: { linkId, accountId, via, createdAt: ctx.now() } }); else if (opts.upgrade && existing.via !== via) await ctx.db.productPerson.update({ where: { id: existing.id }, data: { via } }); } /** Records that a product signed someone in (so its people.* requests reach them). */ export async function signedInThrough(ctx: Ctx, clientId: string | null, accountId: string | null) { if (!clientId || !accountId) return; const link = await ctx.db.productLink.findUnique({ where: { installId: clientId } }); if (link) await knows(ctx, link.installId, accountId, 'sign_in').catch(() => {}); } async function knownAccount(ctx: Ctx, link: ProductLink, sub: string) { const known = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: sub } }); const a = known ? await ctx.db.account.findUnique({ where: { id: sub } }) : null; if (!a || a.status === 'deleted') throw new RequestError('That person isn\'t known to Accounts through this product.', 'UNKNOWN_PERSON', 404); return a; } const logRequest = (ctx: Ctx, link: ProductLink, r: IdentityRequest, action: string, targetId: string | null, req: Request, metadata: object = {}) => audit(ctx, { actorId: r.actor, actorRole: 'linked_product', action, targetType: targetId ? 'account' : 'product_link', targetId: targetId ?? link.installId, metadata: { product: link.product, installId: link.installId, ...metadata }, ip: clientIp(req) }); // ─── import.* ──────────────────────────────────────────────────────────────── const HASH = /^(\$argon2(id|i|d)\$|\$2[aby]\$)/; function opened(secret: string, sealed: string | null, what: string): string | null { if (sealed === null) return null; try { return openLinkValue(secret, sealed); } catch { throw new RequestError(`A ${what} couldn't be opened with this link's secret.`, 'INVALID_REQUEST', 400); } } /** What happens to one person; writes only when `write`. */ async function importOne(ctx: Ctx, link: ProductLink, secret: string, p: ImportPerson, write: boolean): Promise { const email = normaliseEmail(p.email); if (emailProblem(email)) return { id: p.id, outcome: 'refused', sub: null, reason: 'The email address isn\'t valid.' }; const passwordHash = opened(secret, p.passwordHash, 'password hash'); if (passwordHash !== null && !HASH.test(passwordHash)) return { id: p.id, outcome: 'refused', sub: null, reason: 'The password hash isn\'t bcrypt or Argon2.' }; const totp = p.twoFactor === 'totp' ? opened(secret, p.totpSecret, 'authenticator secret') : null; if (p.twoFactor === 'totp' && !totp) return { id: p.id, outcome: 'refused', sub: null, reason: 'An authenticator app is on but its secret is missing.' }; const byId = await ctx.db.account.findUnique({ where: { id: p.id } }); const byEmail = await ctx.db.account.findUnique({ where: { email } }); // Already moved by this product (a move run again): bring it up to date. if (byId) { const mine = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: byId.id, via: 'import' } }); if (!mine) return { id: p.id, outcome: 'refused', sub: null, reason: 'Accounts already has a different account with this id.' }; if (byEmail && byEmail.id !== byId.id) return { id: p.id, outcome: 'refused', sub: null, reason: 'Another account has this email address.' }; if (write) await ctx.db.account.update({ where: { id: byId.id }, data: fields(ctx, p, email, passwordHash, totp) }); return { id: p.id, outcome: 'updated', sub: byId.id, reason: null }; } // The email already has an account (made before the move): link to it, change nothing. if (byEmail) { if (write) await knows(ctx, link.installId, byEmail.id, 'import', { upgrade: true }); return { id: p.id, outcome: 'linked', sub: byEmail.id, reason: null }; } if (write) { const a = await ctx.db.account.create({ data: { id: p.id, ...fields(ctx, p, email, passwordHash, totp), createdAt: new Date(p.createdAt) } }); for (const n of p.noticeAcceptances) await ctx.db.noticeAcceptance.create({ data: { accountId: a.id, version: n.version, acceptedAt: new Date(n.acceptedAt) } }); for (const c of p.consentChanges) await ctx.db.consentChange.create({ data: { accountId: a.id, channel: c.channel, granted: c.granted, source: 'events_import', createdAt: new Date(c.at) } }); await knows(ctx, link.installId, a.id, 'import', { upgrade: true }); await loginEvent(ctx, a.id, 'account_created', undefined, { clientId: link.installId, detail: { by: 'import', product: link.product } }); await applyKnownOptOut(ctx, a.id); } return { id: p.id, outcome: 'created', sub: p.id, reason: null }; } function fields(ctx: Ctx, p: ImportPerson, email: string, passwordHash: string | null, totp: string | null) { return { name: p.name, email, emailVerified: p.emailVerified, phone: p.phone, passwordHash, twoFactorMethod: p.twoFactor, totpSecret: totp ? ctx.secrets.encrypt(totp) : null, totpLastStep: totp ? p.totpLastStep : null, // Their old recovery codes can't move (EVENTS-3.0-PLAN decision 2): new ones after the next sign-in. recoveryCodesNeeded: p.twoFactor !== null, failedSignIns: p.failedSignIns, lockedUntil: p.lockedUntil ? new Date(p.lockedUntil) : null, newsEmail: p.news.email, newsWhatsApp: p.news.whatsapp, newsAskedAt: p.newsAskedAt ? new Date(p.newsAskedAt) : null, noticeVersionAccepted: p.noticeVersionAccepted, lastSignInAt: p.lastSignInAt ? new Date(p.lastSignInAt) : null, status: p.status, deactivatedAt: p.status === 'deactivated' ? ctx.now() : null, role: p.admin ? ('admin' as const) : ('member' as const), }; } async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: string, r: IdentityRequest, req: Request): Promise { switch (r.type) { case 'import.begin': { if (!IMPORTERS.has(link.product)) throw new RequestError('Only Cross Events moves its users into Accounts.', 'WRONG_PRODUCT', 403); const own = await ctx.db.privacyNotice.findMany({ orderBy: { version: 'asc' } }); const noticesTaken = own.length === 0; if (!r.check) { if (noticesTaken) { for (const n of r.notices.filter((x) => x.version > BUILT_IN_VERSION)) { await ctx.db.privacyNotice.create({ data: { version: n.version, title: n.title, body: n.body, publishedAt: new Date(n.publishedAt), publishedById: null } }); } } await applyLook(ctx, r.church, false); await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: ctx.now() } }); await logRequest(ctx, link, r, 'import_started', null, req, { notices: noticesTaken ? r.notices.length : 0 }); } return reply({ noticesTaken, accountsNoticeVersions: own.map((n) => n.version), accountsVersion: appVersion() }); } case 'import.batch': { if (!IMPORTERS.has(link.product)) throw new RequestError('Only Cross Events moves its users into Accounts.', 'WRONG_PRODUCT', 403); if (!r.check && !link.importStartedAt) throw new RequestError('Start the move first (import.begin).', 'NOT_MOVING', 409); const seen = new Set(); const results: ImportResult[] = []; for (const p of r.people) { const email = normaliseEmail(p.email); if (seen.has(email)) { results.push({ id: p.id, outcome: 'refused', sub: null, reason: 'The same email address is twice in this move.' }); continue; } seen.add(email); results.push(await importOne(ctx, link, secret, p, !r.check)); } return reply({ results }); } case 'import.finish': { if (!link.importStartedAt) throw new RequestError('There\'s no move under way.', 'NOT_MOVING', 409); // Every account the product relies on must be here, not deleted, and known to it. const wanted = [...new Set(r.subs)]; const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: wanted } } })).map((x) => x.accountId)); const live = new Set((await ctx.db.account.findMany({ where: { id: { in: wanted }, status: { not: 'deleted' } }, select: { id: true } })).map((x) => x.id as string)); const missing = wanted.filter((s) => !known.has(s) || !live.has(s)); const matched = missing.length === 0; if (matched) await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: null } }); await logRequest(ctx, link, r, matched ? 'import_finished' : 'import_mismatch', null, req, { count: wanted.length - missing.length, expected: wanted.length }); return reply({ matched, count: wanted.length - missing.length, missing: missing.slice(0, 100) }); } case 'import.abort': { await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: null } }); await logRequest(ctx, link, r, 'import_aborted', null, req); return reply({ ok: true as const }); } case 'people.ensure': { const email = normaliseEmail(r.email); const existing = await ctx.db.account.findUnique({ where: { email } }); if (existing && existing.status === 'deleted') throw new RequestError('That email address belonged to a deleted account.', 'NOT_ALLOWED', 409); if (existing) { await knows(ctx, link.installId, existing.id, 'ensure'); await logRequest(ctx, link, r, 'person_linked_by_product', existing.id, req); return reply({ sub: existing.id, created: false }); } const a = await ctx.db.account.create({ data: { name: r.name, email, phone: r.phone, passwordHash: null, emailVerified: false } }); await knows(ctx, link.installId, a.id, 'ensure'); await applyKnownOptOut(ctx, a.id); const token = randomToken(); // Only the product's own address: never somewhere else. const returnUrl = new URL(r.returnUrl).origin === new URL(link.url).origin ? r.returnUrl : link.url; await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), returnUrl, expiresAt: new Date(ctx.now().getTime() + SET_PASSWORD_DAYS * 86400e3) } }); // 1.2.0: the account stands even when the email can't go (they can use "Forgot your password?" // once email works); the product is told. let emailSent = true; try { await ctx.messenger.email({ to: email, ...(await newAccountEmail(ctx, { name: r.name, url: `${ctx.config.publicUrl}/reset?token=${token}`, days: SET_PASSWORD_DAYS })) }); } catch (e) { emailSent = false; console.warn('[people.ensure] the "choose your password" email could not be sent:', (e as Error).message); } await loginEvent(ctx, a.id, 'account_created', req, { clientId: link.installId, detail: { by: 'product', product: link.product } }); await logRequest(ctx, link, r, 'person_created_by_product', a.id, req, { emailSent }); return reply({ sub: a.id, created: true, emailSent }); } case 'people.update': { const a = await knownAccount(ctx, link, r.sub); const data: Record = {}; if (r.name !== undefined) data.name = r.name; if (r.phone !== undefined) { data.phone = r.phone; if (r.phone !== a.phone) data.phoneVerified = false; } if (r.email !== undefined) { const email = normaliseEmail(r.email); if (email !== a.email) { const other = await ctx.db.account.findUnique({ where: { email } }); if (other) throw new RequestError('Another account has that email address.', 'EMAIL_TAKEN', 409); data.email = email; data.emailVerified = false; } } if (Object.keys(data).length) { await ctx.db.account.update({ where: { id: a.id }, data }); if (data.email) await loginEvent(ctx, a.id, 'email_changed', req, { clientId: link.installId, detail: { by: 'product' } }); if (!(data.phone && (await applyKnownOptOut(ctx, a.id)))) await profileChanged(ctx, a.id); } await logRequest(ctx, link, r, 'person_updated_by_product', a.id, req, { fields: Object.keys(data) }); return reply({ ok: true as const }); } case 'people.resetTwoFactor': { const a = await knownAccount(ctx, link, r.sub); if (a.role === 'admin') throw new RequestError('An Accounts admin\'s two-factor sign-in can only be reset in Accounts.', 'NOT_ALLOWED', 403); await turnOff(ctx, a.id); await ctx.db.account.update({ where: { id: a.id }, data: { recoveryCodesNeeded: false } }); await signOutEverywhere(ctx, provider, a.id); await loginEvent(ctx, a.id, 'two_factor_off', req, { clientId: link.installId, detail: { by: 'product' } }); await logRequest(ctx, link, r, 'two_factor_reset_by_product', a.id, req); return reply({ ok: true as const }); } case 'people.unlock': { const a = await knownAccount(ctx, link, r.sub); await ctx.db.account.update({ where: { id: a.id }, data: { lockedUntil: null, failedSignIns: 0 } }); await logRequest(ctx, link, r, 'account_unlocked_by_product', a.id, req); return reply({ ok: true as const }); } case 'people.setActive': { const a = await knownAccount(ctx, link, r.sub); if (a.role === 'admin' && !r.active) throw new RequestError('An Accounts admin can only be deactivated in Accounts.', 'NOT_ALLOWED', 403); await ctx.db.account.update({ where: { id: a.id }, data: r.active ? { status: 'active', deactivatedAt: null } : { status: 'deactivated', deactivatedAt: ctx.now() } }); if (!r.active) await signOutEverywhere(ctx, provider, a.id); await logRequest(ctx, link, r, r.active ? 'account_reactivated_by_product' : 'account_deactivated_by_product', a.id, req); return reply({ ok: true as const }); } case 'people.removeDemo': { // 1.3.0: a product's new demo data replaces the old; the old demo people's accounts go. const kept: { sub: string; reason: 'not_demo' | 'admin' | 'unknown' }[] = []; let removed = 0; const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: r.subs } }, select: { accountId: true } })).map((p) => p.accountId)); const accounts = new Map((await ctx.db.account.findMany({ where: { id: { in: [...known] } } })).map((a) => [a.id, a])); for (const sub of new Set(r.subs)) { const a = accounts.get(sub); if (!a || a.status === 'deleted') { kept.push({ sub, reason: 'unknown' }); continue; } if (!isDemoEmail(a.email)) { kept.push({ sub, reason: 'not_demo' }); continue; } if (a.role === 'admin') { kept.push({ sub, reason: 'admin' }); continue; } await signOutEverywhere(ctx, provider, a.id); await anonymise(ctx, a.id); await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } }); removed++; } await logRequest(ctx, link, r, 'demo_people_removed_by_product', null, req, { removed, kept: kept.length }); return reply({ removed, kept }); } case 'people.check': { // 1.5.0: the product's regular check that its copies are current. Profiles only for people // this product knows; a deleted account is said to be deleted (its sub was that person's). const subs = [...new Set(r.subs)]; const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: subs } }, select: { accountId: true } })).map((p) => p.accountId)); const accounts = new Map((await ctx.db.account.findMany({ where: { id: { in: subs } } })).map((a) => [a.id, a])); const people = subs.map((sub) => { const a = accounts.get(sub); if (a?.status === 'deleted') return { sub, status: 'deleted' as const, profile: null }; if (!a || !known.has(sub)) return { sub, status: 'unknown' as const, profile: null }; return { sub, status: a.status === 'deactivated' ? 'deactivated' as const : 'active' as const, profile: profileOf(a) }; }); const count = (s: string) => people.filter((p) => p.status === s).length; await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') }); return reply({ people }); } case 'messaging.get': { // 1.9.0 (APP-1.0-PLAN §8, decision 4): the church's one set of email and WhatsApp settings, // secrets sealed with the link's secret. The product is sent messaging.changed from now on. await ctx.db.productLink.update({ where: { installId: link.installId }, data: { messagingWantedAt: ctx.now() } }); const out = await messagingSettings(ctx, secret); await logRequest(ctx, link, r, 'messaging_settings_given', null, req, { email: !!out.email, whatsapp: !!out.whatsapp }); return reply(out); } case 'whatsapp.optout': { // 1.9.0 (decision 11): a STOP the product received. Kept here for every product. const accounts = await optOutNumber(ctx, r.phone, { keyword: r.keyword, source: link.product, receivedAt: new Date(r.receivedAt) }); await logRequest(ctx, link, r, 'whatsapp_stop_from_product', null, req, { accounts }); return reply({ accounts }); } case 'church.update': { // The product checked the person's role (Accounts doesn't know the Website's); Accounts // checks it's the Website, that the person signs in through it, and audits it as theirs. if (!PROFILE_EDITORS.has(link.product)) throw new RequestError("Only the church's Website changes the church profile from outside Accounts.", 'WRONG_PRODUCT', 403); const known = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: r.actor } }); if (!known) throw new RequestError("The person making the change isn't someone who signs in to this product.", 'NOT_ALLOWED', 403); try { const church = await updateProfile(ctx, r.church, { ifUpdatedAt: r.ifUpdatedAt }); await logRequest(ctx, link, r, 'church_profile_changed_by_product', null, req, { fields: Object.keys(r.church) }); return reply({ church }); } catch (e) { if (e instanceof ProfileChangedError) throw new RequestError(e.message, 'PROFILE_CHANGED', 409); if (e instanceof ProfileError) throw new RequestError(`${e.message} ${Object.entries(e.fields).map(([k, v]) => `${k}: ${v}`).join('; ')}`.trim(), 'INVALID_REQUEST', 400); throw e; } } case 'church.branding': { const changed = await applyLook(ctx, r.church, r.overwrite); await logRequest(ctx, link, r, 'church_look_from_product', null, req, { changed, overwrite: r.overwrite }); return reply({ ok: true as const }); } case 'messaging.status': return reply(await messagingStatus(ctx)); case 'messaging.test': case 'messaging.set': { const save = r.type === 'messaging.set'; const church = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church'; let email: { ok: boolean; error: string | null; saved: boolean } | null = null; let whatsapp: { ok: boolean; error: string | null; saved: boolean } | null = null; if (r.email) { const s = r.email.settings; const pass = s.pass === null ? ((await ctx.settings.get('smtp_pass')) ?? '') : opened(secret, s.pass, 'SMTP password'); const tryWith = { host: s.host, port: s.port, secure: s.secure, user: s.user, pass: pass ?? '', from: s.from }; try { await ctx.messenger.emailWith(tryWith, { to: r.email.to, ...(await testEmail(ctx, { from: link.product === 'events' ? 'Cross Events' : link.product })) }); email = { ok: true, error: null, saved: false }; if (save) { await ctx.settings.setMany({ smtp_host: s.host, smtp_port: String(s.port), smtp_secure: String(s.secure), smtp_user: s.user, smtp_from: s.from, ...(s.pass === null ? {} : { smtp_pass: pass }) }); email.saved = true; } } catch (e) { email = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false }; } } if (r.whatsapp) { const s = r.whatsapp.settings; const token = s.accessToken === null ? ((await ctx.settings.get('wawp_access_token')) ?? '') : opened(secret, s.accessToken, 'WAWP access token'); try { if (!token) throw new Error('Give the WAWP access token.'); await ctx.messenger.whatsappWith({ accessToken: token, instanceId: s.instanceId }, { to: r.whatsapp.to, text: `This is a test from ${church}'s sign-in. WhatsApp works: sign-in codes can be sent.` }); whatsapp = { ok: true, error: null, saved: false }; if (save) { await ctx.settings.setMany({ wawp_instance_id: s.instanceId, ...(s.accessToken === null ? {} : { wawp_access_token: token }) }); whatsapp.saved = true; } } catch (e) { whatsapp = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false }; } } if (save && (email?.saved || whatsapp?.saved)) await messagingChanged(ctx, { email: !!email?.saved, whatsapp: !!whatsapp?.saved }, link.installId); await logRequest(ctx, link, r, save ? 'messaging_set_by_product' : 'messaging_tested_by_product', null, req, { email: email && { ok: email.ok, saved: email.saved }, whatsapp: whatsapp && { ok: whatsapp.ok, saved: whatsapp.saved } }); const status = await messagingStatus(ctx); return reply({ email, whatsapp, status: { email: status.email, whatsapp: status.whatsapp } }); } case 'people.newsOff': { const a = await knownAccount(ctx, link, r.sub); const off = r.channel === 'all' ? { email: false, whatsapp: false } : { [r.channel]: false }; if (await setNewsConsent(ctx, a, off, 'product_unsubscribe')) await profileChanged(ctx, a.id); await logRequest(ctx, link, r, 'news_off_by_product', a.id, req, { channel: r.channel }); return reply({ ok: true as const }); } } } export function requestsRouter(ctx: Ctx, provider: Provider) { const r = express.Router(); r.post(ACCOUNTS_REQUEST_PATH.replace(/^\/api/, ''), limit(600), express.raw({ type: '*/*', limit: '4mb' }), async (req: Request, res: Response) => { try { const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from(''); const { link, secret } = await linkFor(ctx, req, raw); let body: unknown; try { body = JSON.parse(raw.toString('utf8')); } catch { throw new RequestError('The body must be JSON.', 'INVALID_REQUEST'); } const parsed = identityRequestSchema.safeParse(body); if (!parsed.success) throw new RequestError(`Not a crosscode.identity-request/1 request: ${parsed.error.issues[0]?.path.join('.') || ''} ${parsed.error.issues[0]?.message ?? ''}`.trim(), 'INVALID_REQUEST'); const request = parsed.data; const before = await ctx.db.productRequest.findUnique({ where: { requestId: request.requestId } }); if (before) { if (before.linkId !== link.installId) throw new RequestError('That request id was used by another product.', 'INVALID_REQUEST', 409); return res.json(before.reply); } const out = await handle(ctx, provider, link, secret, request, req); // Checks write nothing, so they needn't be remembered. // people.check (1.5.0) only reads, and its reply holds profiles: never kept. // messaging.get (1.9.0) carries sealed secrets: never kept either. const isCheck = ('check' in request && request.check) || request.type === 'people.check' || request.type === 'messaging.get'; if (!isCheck) { await ctx.db.productRequest.create({ data: { requestId: request.requestId, linkId: link.installId, type: request.type, reply: out as never, createdAt: ctx.now() } }).catch(() => {}); } return res.json(out); } catch (e) { if (e instanceof RequestError) return res.status(e.status).json({ message: e.message, code: e.code }); console.error('[requests]', e); return res.status(500).json({ message: 'Something went wrong.', code: 'SERVER_ERROR' }); } }); return r; } /** * The church's look on Accounts' pages from a product's (1.9.0): its name, logo and colours. * `overwrite: false` (a move) fills only what's empty; `true` (an admin's button) replaces them. * Returns the fields changed. */ async function applyLook(ctx: Ctx, look: ChurchLook, overwrite: boolean): Promise { type Stored = Record & { name?: string; branding?: { logoUrl?: string | null; iconUrl?: string | null; colours?: { primary?: string; accent?: string | null } } }; const stored = await ctx.settings.json('church_profile', {}); const branding = { logoUrl: null as string | null, iconUrl: null as string | null, ...(stored.branding ?? {}), colours: { primary: '#1f4e79', accent: '#f2a900', ...(stored.branding?.colours ?? {}) } }; const changed: string[] = []; const take = (has: unknown, value: unknown) => value !== null && value !== undefined && value !== '' && (overwrite || !has); const next: Stored = { ...stored }; if (take(stored.name, look.name)) { next.name = look.name!; changed.push('name'); } if (take(stored.branding?.logoUrl, look.logoUrl)) { branding.logoUrl = look.logoUrl!; changed.push('logo'); } if (take(stored.branding?.colours?.primary, look.primaryColour)) { branding.colours.primary = look.primaryColour!; changed.push('primary colour'); } if (take(stored.branding?.colours?.accent && stored.branding?.colours?.accent !== '#f2a900', look.accentColour)) { branding.colours.accent = look.accentColour!; changed.push('accent colour'); } if (!changed.length) return changed; next.branding = branding; next.updatedAt = ctx.now().toISOString(); await ctx.settings.set('church_profile', JSON.stringify(next)); return changed; } /** What can be sent now (no secrets), for a product's sign-in settings page. */ async function messagingStatus(ctx: Ctx) { const emailReady = await ctx.messenger.emailReady(); return { email: { ready: emailReady, host: emailReady ? ((await ctx.settings.get('smtp_host')) || ctx.config.smtp?.host || null) : null, from: emailReady ? ((await ctx.settings.get('smtp_from')) || ctx.config.smtp?.from || null) : null }, whatsapp: { ready: await ctx.messenger.whatsappReady(), instanceId: (await ctx.settings.get('wawp_instance_id')) || ctx.config.wawp?.instanceId || null }, }; } /** * messaging.get (1.9.0): what Accounts sends with (its saved settings, else the server's .env), * the password and token sealed with the link's secret. A part that isn't set up is null. */ async function messagingSettings(ctx: Ctx, secret: string) { const s = ctx.settings; const host = (await s.get('smtp_host')) || ctx.config.smtp?.host || null; const port = Number((await s.get('smtp_port')) || ctx.config.smtp?.port || 587); const pass = (await s.get('smtp_pass')) || ctx.config.smtp?.pass || ''; const from = (await s.get('smtp_from')) || ctx.config.smtp?.from || ''; const email = host && from ? { host, port, secure: (await s.get('smtp_secure')) === 'true' || (ctx.config.smtp?.secure ?? port === 465), user: (await s.get('smtp_user')) || ctx.config.smtp?.user || '', pass: pass ? sealLinkValue(secret, pass) : null, from, } : null; const token = (await s.get('wawp_access_token')) || ctx.config.wawp?.accessToken || null; const instanceId = (await s.get('wawp_instance_id')) || ctx.config.wawp?.instanceId || null; const whatsapp = token && instanceId ? { accessToken: sealLinkValue(secret, token), instanceId } : null; return { email, whatsapp, updatedAt: (await s.get('messaging_updated_at')) || null }; } /** Old remembered requests (the `cleanup` job). */ export async function forgetOldRequests(ctx: Ctx) { return ctx.db.productRequest.deleteMany({ where: { createdAt: { lt: new Date(ctx.now().getTime() - KEEP_REQUESTS_DAYS * 86400e3) } } }); } export const newRequestId = () => crypto.randomUUID();