Files
ipal-kit/src/modules/email/relay/send.ts
T

241 lines
13 KiB
TypeScript

import type { BasePayload, SendEmailOptions } from 'payload'
import { createHash, randomBytes } from 'node:crypto'
import type { ResolvedRelayOptions } from './options.js'
import { consumeRateLimit } 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 { LOCAL_CODES, refreshRelayStatus, rotateRelayToken, type TokenUse, withRelayToken } from './session.js'
import { readRelayStore, sha256Hex, updateRelayStore } 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<void>((resolve) => setTimeout(resolve, ms))
/**
* Messages whose outcome the service never confirmed, 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; a message of a new content always gets a new key.
*/
const unconfirmed = new Map<string, { at: number; key: string }>()
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 (answer.code === LOCAL_CODES.noToken || answer.code === LOCAL_CODES.noHost) {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') {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.
*/
export async function sendThroughRelay(payload: BasePayload, options: ResolvedRelayOptions, message: SendEmailOptions, context: RelaySendContext = {}): Promise<RelaySendResult> {
// 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:${marked.visitor}`, max: own.perVisitor ?? RELAY_DEFAULTS.accountMail.perVisitor }] : []),
...[...(request.to ?? []), ...(request.cc ?? []), ...(request.bcc ?? [])].map((address) => ({ key: `to:${sha256Hex(address.toLowerCase())}`, max: perAddress })),
]
for (const check of checks) {
const { ok } = await consumeRateLimit({ ...check, scope: 'mail-relay-account', 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' : '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 readRelayStore(payload)
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.`)
}
}
if (stored.service?.rotateAfter && Date.parse(stored.service.rotateAfter) <= Date.now()) {
await rotateRelayToken(payload, options).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 = {}
const budget = RELAY_DEFAULTS.waitBudgetMs
let attempts = 0
let waited = 0
let answer: RelayAnswer<SendBody> = { code: 'unavailable', message: 'not tried', noAnswer: false, ok: false, retryable: false, status: 0 }
while (attempts < RELAY_DEFAULTS.attempts) {
answer = await withRelayToken<SendBody>(
payload,
options,
(token) => {
attempts += 1
return relayRequest<SendBody>({ body, fetchImpl: options.fetchImpl, idempotencyKey, method: 'POST', path: '/v1/send', timeoutMs: options.timeoutMs ?? RELAY_DEFAULTS.attemptTimeoutMs, token, url: options.url })
},
use,
)
if (answer.ok || !answer.retryable || attempts >= RELAY_DEFAULTS.attempts) {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) {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 readRelayStore(payload)
const known = now.nameReplaced
const nameChanged = replaced ? known?.used !== used || known?.asked !== (request.senderName ?? '') : Boolean(known)
if (nameChanged || now.state !== 'active' || now.refusal) {
await updateRelayStore(payload, (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)
}
} 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)
// Not confirmed, or failed in a way the back end does not explain: the same key if this message is tried again.
if (!result.confirmed || result.detail.startsWith('Probably not sent')) {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 updateRelayStore(payload, (current) => ({ ...current, state })).catch(() => undefined)}
}
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
}