import type { Endpoint, PayloadRequest } from 'payload' import type { RelayOptions } from './options.js' import { clientIp, consumeRateLimit, tooManyRequests } from '../../shared/rateLimit.js' import { readCappedBody } from '../../shared/readCappedBody.js' import { RELAY_CONFIRM_PATH, RELAY_DEFAULTS } from './constants.js' import { sha256Hex, takeNonce, writeRelayCandidate } from './store.js' const NONCE = /^[\w-]{32,128}$/ const TOKEN = /^ims_[\w-]{43}$/ const STATES = new Set(['active', 'pending', 'suspended']) const MAX_BODY = 2048 const notFound = () => new Response(null, { headers: { 'cache-control': 'no-store' }, status: 404 }) async function readBody(req: PayloadRequest): Promise { try { // read only up to the cap, whether or not the call declares its length (a chunked body has none) const text = (req as unknown as Request).body ? await readCappedBody(req as unknown as Request, MAX_BODY) : null if (text !== null) {return JSON.parse(text) as unknown} if ((req as unknown as Request).body) {return null} // a request without a stream (a double in a test, a body Payload already read) if (Number(req.headers.get('content-length') ?? 0) > MAX_BODY) {return null} const read = (req as { text?: () => Promise }).text if (typeof read !== 'function') {return (await req.json?.()) as unknown} const whole = await read.call(req) return whole.length <= MAX_BODY ? (JSON.parse(whole) as unknown) : null } catch { return null } } /** * `POST /api/iapl/mail-relay/confirm` — where the Intecion Notifications Webservice calls a site back * during an enrolment the SITE started. Public, and useless to anybody else: * * - it answers `404` and changes nothing unless the body carries a nonce this site made in the last * five minutes (kept as a hash, compared in constant time, single use); * - then it stores the delivered token BESIDE the one in use (store.ts) — a working token is never * replaced by one the service has not accepted — and answers `200` with exactly * `{ "confirmation": hex(SHA-256(nonce + "." + token)) }`, which only an endpoint that holds the * nonce and has read the token can compute; * - refused calls are rate-limited per address; a call that carries a nonce the site holds is never * turned away by the limit. * The path is fixed for this product by the service's contract; a project cannot move it (a site with * another API route asks Intecion to set its confirm address). */ export function relayConfirmEndpoint(options: Pick = {}): Endpoint { const max = options.confirmRateLimit?.max ?? RELAY_DEFAULTS.confirmRateLimit.max const windowMs = options.confirmRateLimit?.windowMs ?? RELAY_DEFAULTS.confirmRateLimit.windowMs return { handler: async (req: PayloadRequest) => { // Only calls that are REFUSED count against the limit, and the nonce is looked up first: the address the // service calls from is shared (every Cloudflare Worker reaches a site behind Cloudflare from the same // one), so a stranger who fills a per-address bucket must not keep the site's own enrolment out. const refuse = async () => { const limit = await consumeRateLimit({ key: clientIp(req.headers), max, scope: 'mail-relay-confirm', windowMs }) return limit.ok ? notFound() : tooManyRequests(limit.retryAfter, { error: 'Too many requests.' }) } const body = (await readBody(req)) as { nonce?: unknown; state?: unknown; token?: unknown } | null if (!body || typeof body !== 'object') {return refuse()} const { nonce, state, token } = body if (typeof nonce !== 'string' || !NONCE.test(nonce) || typeof token !== 'string' || !TOKEN.test(token) || typeof state !== 'string' || !STATES.has(state)) { return refuse() } try { // one read of the key-value store for a well-formed call; a wrong nonce is refused and counted const held = await takeNonce(req.payload, nonce) if (!held) {return refuse()} // the token is for the host that started this enrolment: stored beside THAT host's token await writeRelayCandidate(req.payload, { at: new Date().toISOString(), nonceHash: sha256Hex(nonce), state: state as 'active' | 'pending' | 'suspended', token }, held.host) } catch (err) { req.payload.logger.error(`[iapl] mail service: the confirm route could not use the store: ${err instanceof Error ? err.message.split('\n')[0] : String(err)}`) return notFound() } // Exactly this object and nothing else: the service reads at most 1024 bytes and checks the hash. return new Response(JSON.stringify({ confirmation: sha256Hex(`${nonce}.${token}`) }), { headers: { 'cache-control': 'no-store', 'content-type': 'application/json' }, status: 200, }) }, method: 'post', path: RELAY_CONFIRM_PATH, } }