import type { BasePayload, SendEmailOptions } from 'payload' import { createHash, randomBytes } from 'node:crypto' import type { ResolvedRelayOptions } from './options.js' import { consumeRateLimit, ipRateKey } from '../../shared/rateLimit.js' import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js' import { RELAY_DEFAULTS, type RelayStatusCode, relayStatusFor } from './constants.js' import { currentMailKind, type MailKind, mailKindOf, takeExpectedMail } from './kinds.js' import { bareAddresses, buildRelayMessage, type RelaySendRequest } from './message.js' import { relayHost } from './options.js' import { LOCAL_CODES, readSiteStore, refreshRelayStatus, rotateRelayToken, type TokenUse, updateSiteStore, withRelayToken } from './session.js' import { sha256Hex } from './store.js' export type RelaySendResult = | { /** The service's code, or one of this client's (`client-…`). */ cause: string /** A status code for `emailStatus` (RELAY_STATUS_CODES). */ code: RelayStatusCode /** * `false`: the message MAY have been sent — the service gave no answer, or cannot say yet. Send * the same message again and this client uses the same key and bytes, so no second mail can go out. */ confirmed: boolean /** For the panel status and the log. English; never shown to a visitor. */ detail: string error: string sent: false transport: 'relay' } | { /** The service's id of the message in its log. */ id: string kind: MailKind messageId?: string /** true: this message had been sent before (same key and bytes); no second mail went out. */ replayed: boolean /** The name the mail left under. */ senderName: string sent: true transport: 'relay' warnings: string[] } type SendBody = { id?: string; messageId?: string; replayed?: boolean; senderName?: string; warnings?: unknown } const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) /** * Messages the service gave no final answer for (no answer at all, a retryable failure, an error page * of the network in front), by the hash of their bytes: sent again within 24 hours they go out under * the SAME key, so the service answers with what happened to the first attempt instead of sending a * second mail. Per process (there is no stored outbox): after a restart, or from another instance of * the site, the same message gets a new key. A message of a new content always gets a new key. */ const unconfirmed = new Map() const DAY = 24 * 60 * 60_000 function keyFor(hash: string): string { const now = Date.now() for (const [h, entry] of unconfirmed) { if (now - entry.at > DAY) {unconfirmed.delete(h)} } return unconfirmed.get(hash)?.key ?? randomBytes(24).toString('base64url') } /** For tests. */ export function clearUnconfirmedRelayMessages(): void { unconfirmed.clear() } const failure = (code: RelayStatusCode, cause: string, detail: string, confirmed = true): { sent: false } & RelaySendResult => ({ cause, code, confirmed, detail, error: confirmed ? 'The e-mail was not sent.' : 'The e-mail may not have been sent: the mail service did not confirm it.', sent: false, transport: 'relay', }) function describeRefusal(answer: RelayRefusal): { sent: false } & RelaySendResult { const extra = [answer.limit ? `limit: ${answer.limit}` : '', answer.reason ? `reason: ${answer.reason}` : '', answer.field ? `field: ${answer.field}` : ''].filter(Boolean).join(', ') const said = `${answer.code}${extra ? ` (${extra})` : ''}: ${answer.message}` if (answer.code === LOCAL_CODES.disconnected) {return failure('relay-disconnected', answer.code, answer.message)} if (([LOCAL_CODES.foreignToken, LOCAL_CODES.noHost, LOCAL_CODES.noRoute, LOCAL_CODES.noToken, LOCAL_CODES.otherHost] as string[]).includes(answer.code)) {return failure('relay-refused', answer.code, answer.message)} // No answer at all, or a send the service cannot report on yet: it may be out. if (answer.noAnswer || answer.code === 'in-progress') {return failure('relay-not-confirmed', answer.code, `Not confirmed — the message may have been sent. ${said}`, false)} if (answer.code === 'callback-failed' && answer.reason === 'status') { return failure('relay-refused', answer.code, `${said} If the site serves its API at another path, ask Intecion to set this site's confirm address.`) } if (answer.code === 'invalid-token' || answer.code === 'reverify' || answer.code === 'host-mismatch') {return failure('relay-refused', answer.code, said)} const status = relayStatusFor(answer.code, answer.retryable) // The mail back end failed without saying whether the message can still go out. if (status === 'relay-unreachable' && !['enrolment-in-progress', 'rate-limited', 'unavailable'].includes(answer.code)) { return failure(status, answer.code, `Probably not sent. ${said}`) } return failure(status, answer.code, said) } export type RelaySendContext = { /** The panel's "Sender address": where replies go when the message names no reply address. */ replyTo?: null | string /** The panel's "Sender name", else the site name. */ senderName?: null | string } /** * One message through the service. Never throws. * * The message is encoded ONCE and exactly those bytes go out on every attempt, under one * `Idempotency-Key`: at most three attempts, 30 seconds each, at most ten seconds of waiting between * them in all (which win over the service's `retryAfter`), and only after an answer that says * `retryable` or after no answer. An enrolment made on the way is not one of the three. * * All of it shares one budget (`totalTimeoutMs`: 10 seconds, 30 with files): the request that sends the * mail has somebody waiting. An attempt cut off by it counts as no answer — "not confirmed". */ export async function sendThroughRelay(payload: BasePayload, options: ResolvedRelayOptions, message: SendEmailOptions, context: RelaySendContext = {}): Promise { // What the message is: its own mark; else what an auth operation said about a message to this address // (Payload's own account mail); else the surrounding runWithMailKind; else the project's rule; else unknown. const own = mailKindOf(message) const marked = own ? undefined : takeExpectedMail(bareAddresses((message as { to?: unknown }).to).addresses) const kind = own ?? marked?.kind ?? currentMailKind() ?? options.kind?.(message) ?? 'system' const built = buildRelayMessage(message, { kind, replyTo: context.replyTo, senderName: context.senderName }) if (!built.ok) {return failure('relay-error', 'client-invalid-message', built.problem)} const request: RelaySendRequest = built.request if (built.dropped) {payload.logger.warn(`[iapl] mail service: ${built.dropped} recipient value(s) were not e-mail addresses and were left out.`)} // A visitor can ask for account mail as often as they like; the service does not limit it per address. if (kind === 'account' && options.accountMail !== false) { const own = options.accountMail ?? {} const windowMs = (own.windowMinutes ?? RELAY_DEFAULTS.accountMail.windowMinutes) * 60_000 const perAddress = own.perAddress ?? RELAY_DEFAULTS.accountMail.perAddress const checks = [ ...(marked?.visitor ? [{ key: `visitor:${ipRateKey(marked.visitor)}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []), // 1.18.0: one visitor (IP) gets `perAddress` mails to an address; the address gets `perAddressTotal` from everybody — // a stranger who fills an address's count from one IP no longer stops its owner's own reset mail (IAWL idea 16). ...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].flatMap((address) => { const to = `to:${sha256Hex(address.toLowerCase())}` return [ // no visitor known (server code, no IP header): all such requests are one visitor { key: marked?.visitor ? ipRateKey(marked.visitor) : 'no-visitor', max: perAddress, scope: `mail-relay-account:${to}` }, { key: to, max: own.perAddressTotal ?? RELAY_DEFAULTS.accountMail.perAddressTotal }, ] }), ] for (const check of checks) { const { ok } = await consumeRateLimit({ scope: 'mail-relay-account', ...check, windowMs }) if (!ok) { payload.logger.warn(`[iapl] mail service: an account e-mail was held back (more than ${check.max} ${check.key.startsWith('visitor:') ? 'from one visitor' : 'scope' in check ? 'to one address from one visitor' : 'to one address'} in the window; mail.relay.accountMail).`) return failure('relay-quota', 'client-account-mail-limit', 'Too many account e-mails to one address or from one visitor; held back by the site (mail.relay.accountMail).') } } } const stored = await readSiteStore(payload, options) const limits = stored.service && Date.now() - Date.parse(stored.service.fetchedAt) < RELAY_DEFAULTS.statusTtlMs ? stored.service.limits : undefined if (limits) { // What the service said within the last hour: no need to upload 10 MB to hear it again. const bytes = (request.attachments ?? []).reduce((sum, a) => sum + Math.floor((a.content.length * 3) / 4) - (a.content.endsWith('==') ? 2 : a.content.endsWith('=') ? 1 : 0), 0) if (typeof limits.maxAttachmentBytes === 'number' && bytes > limits.maxAttachmentBytes) { return failure('relay-too-large', 'too-large', `too-large (limit: attachments): the files are ${bytes} bytes, the mail service carries ${limits.maxAttachmentBytes}.`) } const recipients = (request.to?.length ?? 0) + (request.cc?.length ?? 0) + (request.bcc?.length ?? 0) if (typeof limits.recipientsPerMessage === 'number' && recipients > limits.recipientsPerMessage) { return failure('relay-quota', 'too-many-recipients', `too-many-recipients: ${recipients} recipients, the mail service allows ${limits.recipientsPerMessage} a message.`) } } // Somebody waits for this request (a form's visitor): everything from here on — a check, an enrolment, the // attempts and the waits between them — shares one budget. A service that hangs costs that much, not the // sum of the attempts' time-outs. const total = options.totalTimeoutMs const hasFiles = Boolean(request.attachments?.length) const budgetMs = typeof total === 'number' ? total : hasFiles ? (total?.files ?? RELAY_DEFAULTS.totalTimeoutWithFilesMs) : (total?.plain ?? RELAY_DEFAULTS.totalTimeoutMs) const deadline = Date.now() + Math.max(1, budgetMs) const left = () => deadline - Date.now() // A token stored by hand is used only once the service has said that it is this host's (a token of another // site, pasted in or copied, must not send as that site). if (stored.token && stored.manual && !stored.hostChecked && options.token === undefined) { const checked = await refreshRelayStatus(payload, options, { timeoutMs: Math.max(1, left()) }) if (checked.error && checked.error.code !== 'reverify' && checked.error.code !== 'invalid-token') { // nothing was sent: the check itself did not get through, or the token is another site's return checked.error.code === LOCAL_CODES.foreignToken ? failure('relay-refused', checked.error.code, checked.error.message) : failure('relay-unreachable', checked.error.code, `The token stored by hand could not be checked with the mail service, so nothing was sent. ${checked.error.message}`) } } if (stored.service?.rotateAfter && Date.parse(stored.service.rotateAfter) <= Date.now()) { await rotateRelayToken(payload, options, { timeoutMs: Math.max(1, left()) }).catch(() => undefined) } const body = Buffer.from(JSON.stringify(request), 'utf8') const hash = createHash('sha256').update(body).digest('hex') const idempotencyKey = keyFor(hash) const use: TokenUse = { deadline } const site = relayHost(payload, options) const budget = RELAY_DEFAULTS.waitBudgetMs let attempts = 0 let waited = 0 let answer: RelayAnswer = { code: 'unavailable', message: 'not tried', noAnswer: false, ok: false, retryable: false, status: 0 } while (attempts < RELAY_DEFAULTS.attempts) { if (left() <= 0) {break} // the time is up: report what the last attempt said answer = await withRelayToken( payload, options, (token) => { attempts += 1 return relayRequest({ body, fetchImpl: options.fetchImpl, idempotencyKey, method: 'POST', path: '/v1/send', site, timeoutMs: Math.max(1, Math.min(options.timeoutMs ?? RELAY_DEFAULTS.attemptTimeoutMs, left())), token, url: options.url }) }, use, ) if (answer.ok || !answer.retryable || attempts >= RELAY_DEFAULTS.attempts) {break} // The site could not enrol: the message was never handed over, and asking again would not change that. if (use.enrolment && !use.enrolment.ok) {break} const wait = answer.retryAfter !== undefined ? answer.retryAfter * 1000 : attempts * (options.retryBackoffMs ?? 1000) // The ten seconds win over retryAfter: stop at once and report. if (waited + wait > budget || wait >= left()) {break} await sleep(wait) waited += wait } if (answer.ok) { unconfirmed.delete(hash) const warnings = Array.isArray(answer.body.warnings) ? answer.body.warnings.filter((w): w is string => typeof w === 'string') : [] const used = typeof answer.body.senderName === 'string' ? answer.body.senderName : '' const replaced = warnings.includes('sender-name-replaced') try { const now = await readSiteStore(payload, options) const known = now.nameReplaced const nameChanged = replaced ? known?.used !== used || known?.asked !== (request.senderName ?? '') : Boolean(known) if (nameChanged || now.state !== 'active' || now.refusal) { await updateSiteStore(payload, options, (current) => ({ ...current, nameReplaced: replaced ? { asked: request.senderName ?? '', at: new Date().toISOString(), used } : null, refusal: null, state: 'active', })) } if (replaced && nameChanged) { payload.logger.warn(`[iapl] mail service: the sender name was not accepted; the e-mail left under "${used}". Choose another name in Site integrations → E-mail sending.`) } // Limits, quota and the day to rotate: read again once they are an hour old. Awaited (one short GET an // hour): a write to the store that lands after the request has ended could undo a "Disconnect" or a rotation. if (!now.service || Date.now() - Date.parse(now.service.fetchedAt) > RELAY_DEFAULTS.statusTtlMs) { await refreshRelayStatus(payload, options, { timeoutMs: Math.max(2000, left()) }) } } catch { /* bookkeeping must not turn a sent mail into a failed one */ } return { id: typeof answer.body.id === 'string' ? answer.body.id : '', kind, ...(typeof answer.body.messageId === 'string' ? { messageId: answer.body.messageId } : {}), replayed: answer.body.replayed === true, senderName: used, sent: true, transport: 'relay', warnings, } } const result = describeRefusal(answer) // Whenever the service did not give a final "no" (no answer, a failure it calls retryable, an answer that was // not its own): the same key if this message is tried again. Reusing a key is always safe — the service either // answers with what happened to the first attempt or sends the message now; a new key could send it twice. if (answer.noAnswer || answer.retryable) {unconfirmed.set(hash, { at: Date.now(), key: idempotencyKey })} else {unconfirmed.delete(hash)} if (answer.code === 'site-pending' || answer.code === 'site-suspended') { const state = answer.code === 'site-pending' ? 'pending' : 'suspended' if (stored.state !== state) {await updateSiteStore(payload, options, (current) => ({ ...current, state })).catch(() => undefined)} } // The panel's status is the LAST send's; a later good mail must not hide this one: kept with its time // (written when the code changes, or every ten minutes while it lasts). Not for a refusal of the site's own // making that never reached the service (a local host, a copied database): such a process writes nothing. if (!answer.code.startsWith('client-') && !(answer.code === 'host-not-allowed' && answer.status === 0)) {try { const now = await readSiteStore(payload, options) const last = now.lastFailure if (!last || last.code !== result.code || Date.now() - Date.parse(last.at) > 10 * 60_000) { await updateSiteStore(payload, options, (current) => ({ ...current, lastFailure: { at: new Date().toISOString(), code: result.code, kind } })) } } catch { /* bookkeeping only */ }} payload.logger.error(`[iapl] mail service: e-mail ${result.confirmed ? 'not sent' : 'not confirmed'} (${result.code}; ${answer.code}${answer.limit ? `, ${answer.limit}` : ''}${answer.reason ? `, ${answer.reason}` : ''}).`) return result }