Mail relay: the built-in client for the Intecion Notifications Webservice
Transport, enrolment with the confirm route, token and state in payload-kv, rotation, the panel's state block, doctor rules, the fake service and the copied contract 1.5.0. Tests against the contract's runner and the fake. Docs and HTTP tests follow. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
9efd86a06f
commit
ea9703f8e3
@@ -5,11 +5,15 @@ import { getSiteIntegrations } from '../payload/index.js'
|
||||
import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js'
|
||||
import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js'
|
||||
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
|
||||
import { relayAttachmentLimit, sendRelayWithPanel } from './relay/adapter.js'
|
||||
import { pluginMailOptions, type RelayOptions, resolveRelayOptions } from './relay/options.js'
|
||||
|
||||
type TransportIntegrations = {
|
||||
emailStatus?: IntegrationStatus | null
|
||||
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
|
||||
emailTransport?: 'graph' | 'smtp' | null
|
||||
smtpFromAddress?: null | string
|
||||
smtpFromName?: null | string
|
||||
smtpHost?: null | string
|
||||
smtpPassword?: null | string
|
||||
smtpUser?: null | string
|
||||
@@ -17,9 +21,33 @@ type TransportIntegrations = {
|
||||
|
||||
const smtpConfigured = (s: TransportIntegrations) => Boolean(s.smtpHost && s.smtpUser && s.smtpPassword)
|
||||
|
||||
/** Which transport a send takes. `none`: nothing is set up and the relay is switched off. */
|
||||
export type MailTransport = 'graph' | 'none' | 'relay' | 'smtp'
|
||||
|
||||
/**
|
||||
* The transport in effect for the present settings, decided on every send (no stored value):
|
||||
* 1. "Sending method" is Microsoft Graph and the GRAPH_* variables are complete → Graph, as before
|
||||
* (deprecated; removed in 2.0);
|
||||
* 2. the panel has an SMTP server (server, user name, password) → SMTP — on the client's request;
|
||||
* 3. the GRAPH_* variables are complete → Graph (deprecated), until they are removed;
|
||||
* 4. otherwise → the Intecion Notifications Webservice, unless it is switched off (`mail: { relay: false }`);
|
||||
* 5. otherwise nothing is configured.
|
||||
* A site with SMTP filled in never contacts the service.
|
||||
*/
|
||||
export function resolveMailTransport(settings: TransportIntegrations, state: { graphEnv: boolean; relay: boolean }): MailTransport {
|
||||
if ((settings.emailTransport ?? 'smtp') === 'graph' && state.graphEnv) {return 'graph'}
|
||||
if (smtpConfigured(settings)) {return 'smtp'}
|
||||
if (state.graphEnv) {return 'graph'}
|
||||
return state.relay ? 'relay' : 'none'
|
||||
}
|
||||
|
||||
/** Graph result codes that mean "Graph cannot carry an attachment this large" — SMTP may. */
|
||||
const GRAPH_TOO_LARGE = new Set(['graph-large-off', 'graph-permission'])
|
||||
|
||||
/** The one warning a site on Microsoft Graph gets per process (silence: `mail: { graphDeprecationWarning: false }`). */
|
||||
export const GRAPH_DEPRECATION_NOTICE =
|
||||
'[iapl] Microsoft Graph as the e-mail transport is deprecated and will be removed in 2.0. Remove the GRAPH_* variables to send through the Intecion Notifications Webservice, or fill in an SMTP server in Site integrations (docs/email.md, "Moving off Microsoft Graph").'
|
||||
|
||||
const STATUS_FIELD = 'emailStatus'
|
||||
/** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */
|
||||
const describe = (err: unknown) =>
|
||||
@@ -28,12 +56,27 @@ const describe = (err: unknown) =>
|
||||
export type MailAdapterArgs = {
|
||||
fallbackFromAddress?: string
|
||||
fallbackFromName?: string
|
||||
/** @deprecated Microsoft Graph is deprecated since 1.17.0 and removed in 2.0 (docs/email.md, "Moving off Microsoft Graph"). */
|
||||
graph?: GraphAdapterArgs
|
||||
/**
|
||||
* The Intecion Notifications Webservice — the transport of a site with no SMTP server in the panel.
|
||||
* `false` switches it off for this adapter; an object overrides `iapl({ mail: { relay } })`.
|
||||
*/
|
||||
relay?: false | RelayOptions
|
||||
smtp?: PanelSmtpAdapterArgs
|
||||
}
|
||||
|
||||
let warnedGraphDeprecated = false
|
||||
/** iapl() left its options in the config: it has already warned at start (plugin.ts, onInit). */
|
||||
const pluginWarnsAtStart = (payload: { config?: { custom?: unknown } }) => Boolean((payload.config?.custom as { iapl?: { mail?: unknown } } | undefined)?.iapl?.mail)
|
||||
|
||||
/** For tests. */
|
||||
export function resetGraphDeprecationWarning(): void {
|
||||
warnedGraphDeprecated = false
|
||||
}
|
||||
|
||||
/** True when the agency Graph credentials are present in the environment. */
|
||||
function graphAvailable(): boolean {
|
||||
export function graphAvailable(): boolean {
|
||||
return Boolean(
|
||||
process.env.GRAPH_TENANT_ID &&
|
||||
process.env.GRAPH_CLIENT_ID &&
|
||||
@@ -44,7 +87,9 @@ function graphAvailable(): boolean {
|
||||
|
||||
/**
|
||||
* Dispatcher email adapter: wired into the config ONCE, but picks the transport
|
||||
* (SMTP or Graph) per send by reading `emailTransport` from SiteIntegrations.
|
||||
* per send from Site integrations (resolveMailTransport): the panel's SMTP server
|
||||
* when one is filled in, Microsoft Graph while its variables last (deprecated),
|
||||
* otherwise the Intecion Notifications Webservice (relay/).
|
||||
* This is what makes the choice switchable in the panel — Payload builds the
|
||||
* email adapter at boot and can't swap it at runtime, so instead of choosing
|
||||
* between two adapters at boot we install one that delegates on every send.
|
||||
@@ -84,9 +129,15 @@ export const mailAdapter =
|
||||
* promises more than can be sent: on Graph without the large-file path and
|
||||
* without SMTP settings the ceiling is GRAPH_INLINE_MAX_BYTES.
|
||||
*/
|
||||
const relayOptions = () => resolveRelayOptions(payload, args.relay)
|
||||
const transportOf = (settings: TransportIntegrations) => resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(relayOptions()) })
|
||||
|
||||
const attachmentLimit = async (): Promise<null | number> => {
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
if ((settings.emailTransport ?? 'smtp') !== 'graph' || !graphAvailable()) {return null}
|
||||
const transport = transportOf(settings)
|
||||
// The service says what it carries for this site (10 MB unless Intecion set another number).
|
||||
if (transport === 'relay') {return relayAttachmentLimit(payload, relayOptions()!).catch(() => null)}
|
||||
if (transport !== 'graph') {return null}
|
||||
const support = await graphLargeAttachmentSupport(args.graph)
|
||||
if (support === 'ok' || support === 'unavailable' || smtpConfigured(settings)) {return null}
|
||||
return GRAPH_INLINE_MAX_BYTES - 1
|
||||
@@ -102,7 +153,13 @@ export const mailAdapter =
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
const choice = settings.emailTransport ?? 'smtp'
|
||||
const previous = settings[STATUS_FIELD]
|
||||
const useGraph = choice === 'graph' && graphAvailable()
|
||||
const chosen = transportOf(settings)
|
||||
|
||||
// No SMTP server in the panel and no Graph: the Intecion Notifications Webservice.
|
||||
if (chosen === 'relay') {return sendRelayWithPanel(payload, relayOptions()!, message, settings)}
|
||||
|
||||
const useGraph = chosen === 'graph'
|
||||
// "Graph" in the panel without its variables is reported only while SMTP carries the mail instead.
|
||||
const graphFallback = choice === 'graph' && !useGraph
|
||||
|
||||
if (graphFallback) {
|
||||
@@ -112,6 +169,11 @@ export const mailAdapter =
|
||||
'[iapl] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.',
|
||||
)
|
||||
}
|
||||
// A project that uses mailAdapter() without iapl()'s start warning still hears it once.
|
||||
if (useGraph && !warnedGraphDeprecated && !pluginWarnsAtStart(payload) && pluginMailOptions(payload).graphDeprecationWarning !== false) {
|
||||
warnedGraphDeprecated = true
|
||||
payload.logger.warn(GRAPH_DEPRECATION_NOTICE)
|
||||
}
|
||||
|
||||
// A large attachment Graph cannot carry (switched off, or the app lacks
|
||||
// Mail.ReadWrite) goes over SMTP when the panel has SMTP settings.
|
||||
@@ -168,7 +230,8 @@ export const mailAdapter =
|
||||
}
|
||||
: { state: 'ok' },
|
||||
)
|
||||
return result
|
||||
// which transport carried it — the test e-mail says so in the panel
|
||||
return result && typeof result === 'object' ? { ...result, transport: viaGraph ? 'graph' : 'smtp' } : result
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { CollectionConfig } from 'payload'
|
||||
|
||||
import { clientIp } from '../../shared/rateLimit.js'
|
||||
import { markNextMail } from './kinds.js'
|
||||
|
||||
const MARK = Symbol.for('iapl.accountMailMark')
|
||||
|
||||
/**
|
||||
* Payload composes and sends "forgot password" and "verify your e-mail" by itself, through
|
||||
* `payload.sendEmail`, with nothing on the message that says what it is. This hook on an auth
|
||||
* collection says it for the NEXT message of the request (kinds.ts): kind `account`, with the
|
||||
* visitor's address so the relay transport can limit what one visitor makes the site send
|
||||
* (`mail.relay.accountMail`). Other transports ignore the mark; nothing else changes.
|
||||
*
|
||||
* Marks `forgotPassword` always, and `create` only where the collection verifies e-mail addresses.
|
||||
*/
|
||||
export function withAccountMailMark(collection: CollectionConfig): CollectionConfig {
|
||||
const hooks = collection.hooks?.beforeOperation ?? []
|
||||
if (hooks.some((h) => (h as { [MARK]?: boolean })[MARK])) {return collection}
|
||||
const verifies = typeof collection.auth === 'object' && Boolean(collection.auth.verify)
|
||||
// NOT async: the mark has to be set in the operation's own synchronous run (markNextMail).
|
||||
const mark = ((args: { args?: { req?: { headers?: Headers } }; operation: string; req?: { headers?: Headers } }) => {
|
||||
if (args.operation === 'forgotPassword' || (verifies && args.operation === 'create')) {
|
||||
const headers = args.req?.headers ?? args.args?.req?.headers
|
||||
markNextMail('account', { visitor: headers ? clientIp(headers) || undefined : undefined })
|
||||
}
|
||||
return args.args
|
||||
}) as unknown as { [MARK]?: boolean } & NonNullable<NonNullable<CollectionConfig['hooks']>['beforeOperation']>[number]
|
||||
mark[MARK] = true
|
||||
return { ...collection, hooks: { ...collection.hooks, beforeOperation: [...hooks, mark] } }
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import type { BasePayload, PayloadEmailAdapter, SendEmailOptions } from 'payload'
|
||||
|
||||
import type { RelayOptions, ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { type IntegrationStatus, recordIntegrationStatus } from '../../integrations/status.js'
|
||||
import { getSiteIntegrations } from '../../payload/index.js'
|
||||
import { RELAY_DEFAULTS, RELAY_SERVICE_NAME } from './constants.js'
|
||||
import { resolveRelayOptions } from './options.js'
|
||||
import { type RelaySendResult, sendThroughRelay } from './send.js'
|
||||
import { refreshRelayStatus } from './session.js'
|
||||
import { readRelayStore } from './store.js'
|
||||
|
||||
/** The address mail leaves from until the service has been asked (`/v1/status` reports the real one). */
|
||||
export const RELAY_SENDER_ADDRESS = '[email protected]'
|
||||
|
||||
type PanelSender = { emailStatus?: IntegrationStatus | null; smtpFromAddress?: null | string; smtpFromName?: null | string }
|
||||
|
||||
const firstLine = (text: string) => text.split('\n')[0].slice(0, 200)
|
||||
|
||||
/** The site name from Site settings (default locale), or '' — the sender name when the panel field is empty. */
|
||||
async function siteName(payload: BasePayload): Promise<string> {
|
||||
try {
|
||||
if (!(payload.config.globals ?? []).some((g) => g.slug === 'site-settings')) {return ''}
|
||||
const doc = (await payload.findGlobal({ slug: 'site-settings' as never, depth: 0, overrideAccess: true })) as { siteName?: unknown }
|
||||
return typeof doc?.siteName === 'string' ? doc.siteName.trim() : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The display name of the site's mail: `relay.senderName`, else the panel's "Sender name", else the
|
||||
* site name from Site settings. Empty = the service uses the site's host.
|
||||
*/
|
||||
export async function relaySenderName(payload: BasePayload, options: Pick<RelayOptions, 'senderName'>, panelName?: null | string): Promise<string> {
|
||||
const own = typeof options.senderName === 'function' ? await options.senderName({ payload }) : options.senderName
|
||||
if (typeof own === 'string' && own.trim()) {return own.trim()}
|
||||
if (typeof panelName === 'string' && panelName.trim()) {return panelName.trim()}
|
||||
return siteName(payload)
|
||||
}
|
||||
|
||||
/** One send through the service with the panel's sender name and reply address, and `emailStatus` kept. */
|
||||
export async function sendRelayWithPanel(payload: BasePayload, options: ResolvedRelayOptions, message: SendEmailOptions, settings: PanelSender): Promise<RelaySendResult> {
|
||||
const result = await sendThroughRelay(payload, options, message, {
|
||||
replyTo: settings.smtpFromAddress,
|
||||
senderName: await relaySenderName(payload, options, settings.smtpFromName),
|
||||
})
|
||||
await recordIntegrationStatus(
|
||||
payload,
|
||||
'emailStatus',
|
||||
settings.emailStatus,
|
||||
result.sent ? { state: 'ok' } : { code: result.code, message: `${RELAY_SERVICE_NAME}: ${firstLine(result.detail)}`, state: 'degraded' },
|
||||
)
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* The largest total attachment size the service carries for this site, as it last reported
|
||||
* (`limits.maxAttachmentBytes` of `/v1/status`) — read again when older than an hour. `null` until
|
||||
* the site has enrolled: the plugin has no constant of its own for it.
|
||||
*/
|
||||
export async function relayAttachmentLimit(payload: BasePayload, options: ResolvedRelayOptions): Promise<null | number> {
|
||||
let stored = await readRelayStore(payload)
|
||||
const stale = !stored.service || Date.now() - Date.parse(stored.service.fetchedAt) > RELAY_DEFAULTS.statusTtlMs
|
||||
if (stale && (stored.token || options.token !== undefined) && !stored.disconnected) {
|
||||
stored = (await refreshRelayStatus(payload, options)).stored
|
||||
}
|
||||
const limit = stored.service?.limits?.maxAttachmentBytes
|
||||
return typeof limit === 'number' && limit >= 0 ? limit : null
|
||||
}
|
||||
|
||||
export type RelayAdapterArgs = {
|
||||
/** Payload wants a from-address at start; the service fixes the real one. */
|
||||
fallbackFromAddress?: string
|
||||
fallbackFromName?: string
|
||||
} & RelayOptions
|
||||
|
||||
/**
|
||||
* The Intecion Notifications Webservice as a Payload e-mail adapter of its own — for a project that
|
||||
* wants this transport and nothing else:
|
||||
* email: relayAdapter()
|
||||
* `mailAdapter()` already uses it when the panel has no SMTP server; most projects need only that.
|
||||
* Reads the sender name and the reply address from Site integrations when that global exists.
|
||||
*/
|
||||
export const relayAdapter =
|
||||
(args: RelayAdapterArgs = {}): PayloadEmailAdapter =>
|
||||
({ payload }) => {
|
||||
const { fallbackFromAddress, fallbackFromName, ...own } = args
|
||||
const options = () => resolveRelayOptions(payload, own) as ResolvedRelayOptions
|
||||
const panel = async (): Promise<PanelSender> =>
|
||||
(payload.config.globals ?? []).some((g) => g.slug === 'site-integrations') ? getSiteIntegrations<PanelSender>(payload) : {}
|
||||
return {
|
||||
name: 'iapl-relay',
|
||||
attachmentLimit: () => relayAttachmentLimit(payload, options()),
|
||||
defaultFromAddress: fallbackFromAddress ?? RELAY_SENDER_ADDRESS,
|
||||
defaultFromName: fallbackFromName ?? 'Website',
|
||||
sendEmail: async (message: SendEmailOptions) => sendRelayWithPanel(payload, options(), message, await panel()),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { PLUGIN_VERSION } from '../../../version.js'
|
||||
import { RELAY_DEFAULTS, RELAY_PRODUCT } from './constants.js'
|
||||
|
||||
/** A refusal of the service (contracts/mail-relay/schema.json, `Error`), or what stands in for one. */
|
||||
export type RelayRefusal = {
|
||||
code: string
|
||||
field?: string
|
||||
limit?: string
|
||||
message: string
|
||||
/** No usable answer came at all (time-out, connection lost): the request may have been carried out. */
|
||||
noAnswer: boolean
|
||||
ok: false
|
||||
reason?: string
|
||||
retryable: boolean
|
||||
/** Seconds. */
|
||||
retryAfter?: number
|
||||
status: number
|
||||
}
|
||||
|
||||
export type RelayAnswer<T = Record<string, unknown>> = { body: T; ok: true; status: number } | RelayRefusal
|
||||
|
||||
export type RelayCall = {
|
||||
/** The request body, already encoded. A send keeps these bytes for every retry. */
|
||||
body?: Uint8Array
|
||||
fetchImpl?: typeof fetch
|
||||
idempotencyKey?: string
|
||||
method: 'GET' | 'POST'
|
||||
/** Relative to the base address: `/v1/send`. */
|
||||
path: string
|
||||
timeoutMs?: number
|
||||
token?: string
|
||||
/** Base address, host and path prefix together; joined with `path` as text. */
|
||||
url: string
|
||||
}
|
||||
|
||||
const firstLine = (text: string) => text.split('\n')[0].slice(0, 300)
|
||||
|
||||
/**
|
||||
* One request to the service. Never throws. An answer that is not the contract's JSON — an error page
|
||||
* of the network in front, an empty or cut-off body, a redirect — is `503 unavailable`, retryable; a
|
||||
* request that got no answer at all is the same with `noAnswer: true`.
|
||||
*/
|
||||
export async function relayRequest<T = Record<string, unknown>>(call: RelayCall): Promise<RelayAnswer<T>> {
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), call.timeoutMs ?? RELAY_DEFAULTS.timeoutMs)
|
||||
let status = 0
|
||||
try {
|
||||
const response = await (call.fetchImpl ?? fetch)(`${call.url.replace(/\/+$/, '')}${call.path}`, {
|
||||
body: call.body as BodyInit | undefined,
|
||||
headers: {
|
||||
accept: 'application/json',
|
||||
'user-agent': `${RELAY_PRODUCT}/${PLUGIN_VERSION}`,
|
||||
...(call.body ? { 'content-type': 'application/json' } : {}),
|
||||
...(call.token ? { authorization: `Bearer ${call.token}` } : {}),
|
||||
...(call.idempotencyKey ? { 'idempotency-key': call.idempotencyKey } : {}),
|
||||
},
|
||||
method: call.method,
|
||||
// the token goes to the configured address and nowhere else
|
||||
redirect: 'manual',
|
||||
signal: controller.signal,
|
||||
})
|
||||
status = response.status
|
||||
const text = await response.text()
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
parsed = null
|
||||
}
|
||||
const body = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : null
|
||||
if (body?.ok === true && status === 200) {return { body: body as T, ok: true, status }}
|
||||
if (body?.ok === false && typeof body.code === 'string' && body.code) {
|
||||
return {
|
||||
code: body.code,
|
||||
message: typeof body.message === 'string' ? firstLine(body.message) : body.code,
|
||||
noAnswer: false,
|
||||
ok: false,
|
||||
retryable: body.retryable === true,
|
||||
status,
|
||||
...(typeof body.retryAfter === 'number' && body.retryAfter >= 0 ? { retryAfter: body.retryAfter } : {}),
|
||||
...(typeof body.field === 'string' ? { field: body.field } : {}),
|
||||
...(typeof body.limit === 'string' ? { limit: body.limit } : {}),
|
||||
...(typeof body.reason === 'string' ? { reason: body.reason } : {}),
|
||||
}
|
||||
}
|
||||
return { code: 'unavailable', message: `The mail service answered ${status} without a usable body.`, noAnswer: false, ok: false, retryable: true, status }
|
||||
} catch (err) {
|
||||
const aborted = controller.signal.aborted
|
||||
return {
|
||||
code: 'unavailable',
|
||||
message: aborted ? 'The mail service did not answer in time.' : `The mail service could not be reached: ${firstLine(err instanceof Error ? err.message : String(err))}`,
|
||||
// an attempt that timed out is "no answer"; a body that broke off by itself is an answer that is not JSON
|
||||
noAnswer: aborted || status === 0,
|
||||
ok: false,
|
||||
retryable: true,
|
||||
status,
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import type { RelayOptions } from './options.js'
|
||||
|
||||
import { clientIp, consumeRateLimit, tooManyRequests } from '../../shared/rateLimit.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<unknown> {
|
||||
const length = Number(req.headers.get('content-length') ?? 0)
|
||||
if (length > MAX_BODY) {return null}
|
||||
try {
|
||||
const read = (req as { text?: () => Promise<string> }).text
|
||||
if (typeof read !== 'function') {return (await req.json?.()) as unknown}
|
||||
const text = await read.call(req)
|
||||
return text.length <= MAX_BODY ? (JSON.parse(text) 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;
|
||||
* - it is rate-limited per address.
|
||||
* 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<RelayOptions, 'confirmRateLimit'> = {}): Endpoint {
|
||||
const max = options.confirmRateLimit?.max ?? RELAY_DEFAULTS.confirmRateLimit.max
|
||||
const windowMs = options.confirmRateLimit?.windowMs ?? RELAY_DEFAULTS.confirmRateLimit.windowMs
|
||||
return {
|
||||
handler: async (req: PayloadRequest) => {
|
||||
const limit = await consumeRateLimit({ key: clientIp(req.headers), max, scope: 'mail-relay-confirm', windowMs })
|
||||
if (!limit.ok) {return 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 notFound()}
|
||||
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 notFound()
|
||||
}
|
||||
try {
|
||||
if (!(await takeNonce(req.payload, nonce))) {return notFound()}
|
||||
await writeRelayCandidate(req.payload, { at: new Date().toISOString(), nonceHash: sha256Hex(nonce), state: state as 'active' | 'pending' | 'suspended', token })
|
||||
} 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,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* The Intecion Notifications Webservice, as the plugin knows it. No secret is here and none is in the
|
||||
* package: a site gets its own token by enrolling (enrol.ts). The wire contract these values come from
|
||||
* is copied in `contracts/mail-relay/` (test/mailRelayContract.test.ts fails on a hand-edited copy).
|
||||
*/
|
||||
|
||||
/** Base address: host and path together, joined with a path as text. Override: `mail: { relay: { url } }`. */
|
||||
export const RELAY_BASE_URL = 'https://webservices.intecion.net/mail'
|
||||
/** The version of the copied contract this client speaks (`contracts/mail-relay/VERSION`). */
|
||||
export const RELAY_CONTRACT_VERSION = '1.5.0'
|
||||
/** The `product` value of this plugin. */
|
||||
export const RELAY_PRODUCT = 'iapl'
|
||||
/** The service's name, for texts. */
|
||||
export const RELAY_SERVICE_NAME = 'Intecion Notifications Webservice'
|
||||
/** Where the service calls a site of this product back, under Payload's API route. Fixed by the contract. */
|
||||
export const RELAY_CONFIRM_PATH = '/iapl/mail-relay/confirm'
|
||||
/** Admin-only routes of the panel's status block. */
|
||||
export const RELAY_STATUS_PATH = '/iapl/mail-relay/status'
|
||||
export const RELAY_CONNECT_PATH = '/iapl/mail-relay/connect'
|
||||
export const RELAY_DISCONNECT_PATH = '/iapl/mail-relay/disconnect'
|
||||
/** Key of the site's token and state in `payload.kv`; the candidate token and the nonces hang off it. */
|
||||
export const RELAY_KV_KEY = 'iapl:mail-relay'
|
||||
|
||||
export const RELAY_DEFAULTS = {
|
||||
/** A visitor's lever: "forgot password" mail per address and per visitor in the window (accountMail option). */
|
||||
accountMail: { perAddress: 5, perVisitor: 10, windowMinutes: 60 },
|
||||
/** Requests for one message, the same key and bytes each time. */
|
||||
attempts: 3,
|
||||
/** One attempt, from sending the request to the end of the answer. */
|
||||
attemptTimeoutMs: 30_000,
|
||||
/** Calls to the confirm route per address a minute. */
|
||||
confirmRateLimit: { max: 10, windowMs: 60_000 },
|
||||
/** The enrolment call: the service's call-back has 8 seconds of it. */
|
||||
enrolTimeoutMs: 15_000,
|
||||
/** How long a site keeps the nonce of an enrolment it started. */
|
||||
nonceTtlMs: 5 * 60_000,
|
||||
/** After a refused enrolment the site does not ask again by itself for this long ("Connect again" does). */
|
||||
refusalCooldownMs: 15 * 60_000,
|
||||
/** How long the limits read from `/v1/status` are used before they are read again. */
|
||||
statusTtlMs: 60 * 60_000,
|
||||
/** Other calls (status, rotate, revoke). */
|
||||
timeoutMs: 10_000,
|
||||
/** Waiting between the attempts for one message, in all. Wins over `retryAfter`. */
|
||||
waitBudgetMs: 10_000,
|
||||
} as const
|
||||
|
||||
/**
|
||||
* What a send through the service can leave in `emailStatus.code` (Site integrations), each with a
|
||||
* text in the editor's language. `relay-name-replaced` is a warning shown in the status block: the
|
||||
* mail went out.
|
||||
*/
|
||||
export const RELAY_STATUS_CODES = [
|
||||
'relay-pending',
|
||||
'relay-suspended',
|
||||
'relay-refused',
|
||||
'relay-quota',
|
||||
'relay-too-large',
|
||||
'relay-attachment-refused',
|
||||
'relay-recipient-suppressed',
|
||||
'relay-unreachable',
|
||||
'relay-not-confirmed',
|
||||
'relay-disconnected',
|
||||
'relay-error',
|
||||
'relay-name-replaced',
|
||||
] as const
|
||||
export type RelayStatusCode = (typeof RELAY_STATUS_CODES)[number]
|
||||
|
||||
/** The site status for a code of the service (contract §1, "suggested site status"). */
|
||||
export function relayStatusFor(code: string, retryable: boolean): RelayStatusCode {
|
||||
switch (code) {
|
||||
case 'attachment-refused':
|
||||
return 'relay-attachment-refused'
|
||||
case 'callback-failed':
|
||||
case 'enrolment-closed':
|
||||
case 'host-not-allowed':
|
||||
return 'relay-refused'
|
||||
case 'quota-exceeded':
|
||||
case 'too-many-recipients':
|
||||
return 'relay-quota'
|
||||
case 'recipient-suppressed':
|
||||
return 'relay-recipient-suppressed'
|
||||
case 'site-pending':
|
||||
return 'relay-pending'
|
||||
case 'site-suspended':
|
||||
return 'relay-suspended'
|
||||
case 'too-large':
|
||||
return 'relay-too-large'
|
||||
default:
|
||||
// A code this client does not know is acted on by `retryable` (contract §1).
|
||||
return retryable ? 'relay-unreachable' : 'relay-error'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,586 @@
|
||||
import { createHash, randomBytes } from 'node:crypto'
|
||||
|
||||
import { RELAY_CONTRACT_VERSION, RELAY_SERVICE_NAME } from './constants.js'
|
||||
import { MAIL_KINDS, type MailKind } from './kinds.js'
|
||||
|
||||
/**
|
||||
* A stand-in for the Intecion Notifications Webservice, in memory, for tests — the plugin's own and
|
||||
* a project's. It speaks the wire contract (`contracts/mail-relay/`): every example there runs against
|
||||
* it (test/mailRelayContract.test.ts). Nothing is sent: accepted mail is recorded in `outbox`.
|
||||
*
|
||||
* const relay = createFakeRelay({ allow: ['example.com'] })
|
||||
* iapl({ mail: { relay: { url: relay.url, fetchImpl: relay.fetch } } })
|
||||
*
|
||||
* It is NOT the service: its sender-name guard and its limits are simplified (the real lists and
|
||||
* windows are the service's own), and it keeps no log. Use it to test what a site does with each
|
||||
* answer, not to learn what the service will accept.
|
||||
*/
|
||||
|
||||
export type FakeRelayMail = {
|
||||
attachments: { bytes: number; contentType: string; filename: string }[]
|
||||
bcc: string[]
|
||||
cc: string[]
|
||||
from: string
|
||||
fromName: string
|
||||
headers: Record<string, string>
|
||||
host: string
|
||||
html?: string
|
||||
kind: MailKind
|
||||
replyTo?: string
|
||||
subject: string
|
||||
text?: string
|
||||
to: string[]
|
||||
}
|
||||
|
||||
export type FakeRelayLimits = {
|
||||
maxAttachmentBytes: number
|
||||
maxAttachments: number
|
||||
maxBodyBytes: number
|
||||
messagesPerDay: number
|
||||
messagesPerHour: number
|
||||
newRecipientsPerDay: number
|
||||
perRecipientPerDay: number
|
||||
recipientsPerMessage: number
|
||||
securityAlertsPerDay: number
|
||||
serverAddresses: number
|
||||
}
|
||||
|
||||
type Site = {
|
||||
addresses: string[]
|
||||
alerts: number
|
||||
/** A token issued by hand binds to the first address that uses it. */
|
||||
bindOnUse: boolean
|
||||
callbackPath?: string
|
||||
confirmations: Map<string, number>
|
||||
dayAccount: number
|
||||
dayOther: number
|
||||
host: string
|
||||
hourAccount: number
|
||||
hourOther: number
|
||||
issuedAt: number
|
||||
keys: Map<string, { answer: Record<string, unknown>; hash: string }>
|
||||
lastSenderName?: string
|
||||
previous?: { token: string; until: number }
|
||||
product: string
|
||||
state: 'active' | 'pending' | 'suspended'
|
||||
token?: string
|
||||
}
|
||||
|
||||
export type FakeRelayOptions = {
|
||||
/** Where the service's own notices and every `security-alert` go. */
|
||||
alertRecipient?: string
|
||||
/** Hosts that are active as soon as they enrol; others wait for approval (`'*'` = every host). */
|
||||
allow?: string[]
|
||||
/** Also enrol hosts that are not public DNS names (`localhost:3000`), and call them back over http. For a site on this machine. */
|
||||
allowLocalHosts?: boolean
|
||||
/** How the service reaches a site's confirm route. Default: `fetch`, no redirect followed. */
|
||||
callSite?: (url: string, init: { body: string; headers: Record<string, string>; method: 'POST' }) => Promise<Response>
|
||||
/** The address requests come from when the request carries no `x-fake-client-address` header. */
|
||||
clientAddress?: string
|
||||
limits?: Partial<FakeRelayLimits>
|
||||
now?: () => number
|
||||
senderAddress?: string
|
||||
}
|
||||
|
||||
const DEFAULT_LIMITS: FakeRelayLimits = {
|
||||
maxAttachmentBytes: 10 * 1024 * 1024,
|
||||
maxAttachments: 20,
|
||||
maxBodyBytes: 512_000,
|
||||
messagesPerDay: 200,
|
||||
messagesPerHour: 30,
|
||||
newRecipientsPerDay: 50,
|
||||
perRecipientPerDay: 10,
|
||||
recipientsPerMessage: 10,
|
||||
securityAlertsPerDay: 20,
|
||||
serverAddresses: 8,
|
||||
}
|
||||
|
||||
const DAY = 24 * 60 * 60_000
|
||||
const HOST = /^(?=.{4,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/
|
||||
const LOCAL_HOST = /^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::\d{1,5})?$/
|
||||
const PRIVATE = ['localhost', 'local', 'localdomain', 'internal', 'intranet', 'private', 'lan', 'home', 'corp', 'test', 'invalid', 'example', 'onion', 'arpa']
|
||||
const ADDRESS = /^[\w!#$%&'*+/=?^`{|}~-]+(?:\.[\w!#$%&'*+/=?^`{|}~-]+)*@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z][A-Z0-9-]{0,61}[A-Z0-9]$/i
|
||||
const NONCE = /^[\w-]{32,128}$/
|
||||
const KEY = /^[\w-]{16,128}$/
|
||||
const VERSION = /^[0-9A-Z][\w.+-]*$/i
|
||||
const CONTENT_TYPE = /^[A-Z0-9][\w!#$&^.+-]*\/[A-Z0-9][\w!#$&^.+-]*$/i
|
||||
// three single code points on purpose (ZWNJ, ZWJ, soft hyphen), not a joined sequence
|
||||
// eslint-disable-next-line no-misleading-character-class
|
||||
const UNSAFE_SUBJECT = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}]|(?![\u200C\u200D\u00AD])\p{Cf}/u
|
||||
const UNSAFE_NAME = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}\p{Cf}]/u
|
||||
const EXECUTABLE = new Set(['apk', 'app', 'bat', 'cmd', 'com', 'cpl', 'dll', 'dmg', 'exe', 'hta', 'jar', 'js', 'jse', 'lnk', 'msi', 'ps1', 'scr', 'sh', 'vbs', 'wsf'])
|
||||
const SEND_FIELDS = new Set(['attachments', 'bcc', 'cc', 'html', 'kind', 'product', 'productVersion', 'replyTo', 'senderName', 'subject', 'text', 'to'])
|
||||
const NEVER_A_CLIENT = /\b(?:admin|administrator|amazon|apple|bank|gmail|google|intecion|microsoft|no-?reply|outlook|paypal|security|support)\b/i
|
||||
|
||||
const sha256 = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex')
|
||||
|
||||
class Refusal extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly code: string,
|
||||
message: string,
|
||||
readonly extra: { field?: string; limit?: string; reason?: string; retryable?: boolean; retryAfter?: number } = {},
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
const invalid = (field: string, message: string) => new Refusal(400, 'invalid-request', message, { field })
|
||||
|
||||
function isPublicHost(host: string): boolean {
|
||||
return HOST.test(host) && !PRIVATE.some((s) => host === s || host.endsWith(`.${s}`))
|
||||
}
|
||||
|
||||
/** The simplified sender-name guard: the name, or null when the mail leaves under the host instead. */
|
||||
function guardName(name: string, host: string): null | string {
|
||||
const clean = name.replace(/\s+/g, ' ').trim()
|
||||
if (!clean || [...clean].length > 64) {return null}
|
||||
if (/[@<>"\\]/.test(clean) || !/^[\p{L}\p{N} .,&'’()/-]+$/u.test(clean)) {return null}
|
||||
if (/\b[\w-]+\.[a-z]{2,}\b/i.test(clean) && !clean.toLowerCase().includes(host)) {return null}
|
||||
if (NEVER_A_CLIENT.test(clean)) {return null}
|
||||
const scripts = ['Latin', 'Cyrillic', 'Greek'].filter((s) => new RegExp(`\\p{Script=${s}}`, 'u').test(clean))
|
||||
return scripts.length > 1 ? null : clean
|
||||
}
|
||||
|
||||
export type FakeRelay = {
|
||||
/** Lists a host: it is active as soon as it enrols (and at once when it is waiting). */
|
||||
allow: (host: string) => void
|
||||
/** How the mail back end answers the next sends. */
|
||||
backend: 'failure' | 'ok' | 'recipient-suppressed'
|
||||
/** The address the next requests come from (a request's own `x-fake-client-address` header wins). */
|
||||
clientAddress: string
|
||||
/** `fetch` for requests under `url`; anything else goes to the real `fetch`. */
|
||||
fetch: typeof fetch
|
||||
/** One request to the service: `handle(new Request(`${url}/v1/send`, …))`. */
|
||||
handle: (request: Request) => Promise<Response>
|
||||
/**
|
||||
* Looked at before every request: return a `Response` to answer in the service's place, `'drop'` to
|
||||
* make the request fail like a lost connection, or nothing to let it through.
|
||||
*/
|
||||
intercept?: (request: Request) => 'drop' | Promise<'drop' | Response | undefined> | Response | undefined
|
||||
/** A token for a site the service cannot call back; it binds to the first address that uses it. */
|
||||
issueToken: (host: string, product?: string) => string
|
||||
limits: FakeRelayLimits
|
||||
/** Starts an HTTP server for the fake (a site in another process, an end-to-end test). */
|
||||
listen: (port?: number) => Promise<{ close: () => Promise<void>; url: string }>
|
||||
/** Every message the back end accepted, oldest first. */
|
||||
outbox: FakeRelayMail[]
|
||||
/** Every request that reached the service: method, path and the caller's address — never a token. */
|
||||
requests: { address: string; method: string; path: string }[]
|
||||
/** Forgets every site, message and counter. */
|
||||
reset: () => void
|
||||
/** Sets the confirm address of one host (a site that serves its API somewhere else). */
|
||||
setCallbackPath: (host: string, path: string) => void
|
||||
/** Puts a site into a state without an enrolment; returns its token. */
|
||||
setSite: (host: string, state: 'active' | 'pending' | 'suspended', options?: { product?: string }) => string
|
||||
/** For tests of limits: the counters of one site. */
|
||||
site: (host: string) => Site | undefined
|
||||
url: string
|
||||
}
|
||||
|
||||
export function createFakeRelay(options: FakeRelayOptions = {}): FakeRelay {
|
||||
const now = options.now ?? (() => Date.now())
|
||||
const senderAddress = options.senderAddress ?? '[email protected]'
|
||||
const alertRecipient = options.alertRecipient ?? '[email protected]'
|
||||
const listed = new Set(options.allow ?? [])
|
||||
const sites = new Map<string, Site>()
|
||||
const tokens = new Map<string, string>() // sha256(token) → host
|
||||
const url = 'https://fake-relay.invalid/mail'
|
||||
const seenRecipients = new Map<string, Set<string>>()
|
||||
|
||||
const isListed = (host: string) => listed.has('*') || listed.has(host)
|
||||
const newToken = () => `ims_${randomBytes(32).toString('base64url')}`
|
||||
const blank = (host: string, product: string): Site => ({
|
||||
addresses: [], alerts: 0, bindOnUse: false, confirmations: new Map(), dayAccount: 0, dayOther: 0, host, hourAccount: 0, hourOther: 0, issuedAt: now(), keys: new Map(), product, state: 'pending',
|
||||
})
|
||||
const giveToken = (site: Site): string => {
|
||||
const token = newToken()
|
||||
if (site.token) {site.previous = { token: site.token, until: now() + DAY }}
|
||||
site.token = token
|
||||
site.issuedAt = now()
|
||||
tokens.set(sha256(token), site.host)
|
||||
return token
|
||||
}
|
||||
|
||||
const relay: FakeRelay = {
|
||||
allow: (host) => {
|
||||
listed.add(host)
|
||||
const site = sites.get(host)
|
||||
if (site?.state === 'pending') {site.state = 'active'}
|
||||
},
|
||||
backend: 'ok',
|
||||
clientAddress: options.clientAddress ?? '203.0.113.10',
|
||||
fetch: ((input: Request | string | URL, init?: RequestInit) => {
|
||||
const target = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
|
||||
if (!target.startsWith(url)) {return fetch(input, init)}
|
||||
return relay.handle(new Request(input, init))
|
||||
}) as typeof fetch,
|
||||
handle: async (request) => {
|
||||
const held = await relay.intercept?.(request.clone())
|
||||
if (held === 'drop') {throw new TypeError('fetch failed')}
|
||||
if (held) {return held}
|
||||
return handle(request)
|
||||
},
|
||||
issueToken: (host, product = 'iapl') => {
|
||||
const site = sites.get(host) ?? blank(host, product)
|
||||
sites.set(host, site)
|
||||
site.state = site.state === 'suspended' ? 'suspended' : 'active'
|
||||
site.bindOnUse = true
|
||||
site.addresses = []
|
||||
return giveToken(site)
|
||||
},
|
||||
limits: { ...DEFAULT_LIMITS, ...options.limits },
|
||||
listen: async (port = 0) => {
|
||||
const { createServer } = await import('node:http')
|
||||
const server = createServer((req, res) => {
|
||||
const chunks: Buffer[] = []
|
||||
req.on('data', (c: Buffer) => chunks.push(c))
|
||||
req.on('end', () => {
|
||||
void (async () => {
|
||||
const headers = new Headers()
|
||||
for (const [k, v] of Object.entries(req.headers)) {
|
||||
if (typeof v === 'string') {headers.set(k, v)}
|
||||
}
|
||||
const method = (req.method ?? 'GET').toUpperCase()
|
||||
const prefix = new URL(url).pathname
|
||||
const path = (req.url ?? '/').startsWith(prefix) ? (req.url ?? '/').slice(prefix.length) : `/__outside${req.url ?? '/'}`
|
||||
try {
|
||||
const response = await relay.handle(new Request(`${url}${path}`, { body: method === 'GET' || method === 'HEAD' ? undefined : Buffer.concat(chunks), headers, method }))
|
||||
response.headers.forEach((value, key) => res.setHeader(key, value))
|
||||
res.statusCode = response.status
|
||||
res.end(Buffer.from(await response.arrayBuffer()))
|
||||
} catch {
|
||||
req.socket.destroy()
|
||||
}
|
||||
})()
|
||||
})
|
||||
})
|
||||
await new Promise<void>((resolve) => server.listen(port, '127.0.0.1', resolve))
|
||||
const address = server.address()
|
||||
const listening = typeof address === 'object' && address ? address.port : port
|
||||
return { close: () => new Promise<void>((resolve) => server.close(() => resolve())), url: `http://127.0.0.1:${listening}${new URL(url).pathname}` }
|
||||
},
|
||||
outbox: [],
|
||||
requests: [],
|
||||
reset: () => {
|
||||
sites.clear()
|
||||
tokens.clear()
|
||||
seenRecipients.clear()
|
||||
relay.outbox.length = 0
|
||||
relay.requests.length = 0
|
||||
relay.backend = 'ok'
|
||||
relay.intercept = undefined
|
||||
},
|
||||
setCallbackPath: (host, path) => {
|
||||
const site = sites.get(host) ?? blank(host, 'iapl')
|
||||
sites.set(host, site)
|
||||
site.callbackPath = path
|
||||
},
|
||||
setSite: (host, state, { product = 'iapl' } = {}) => {
|
||||
const site = sites.get(host) ?? blank(host, product)
|
||||
sites.set(host, site)
|
||||
site.state = state
|
||||
if (!site.addresses.includes(relay.clientAddress)) {site.addresses.push(relay.clientAddress)}
|
||||
return site.token ?? giveToken(site)
|
||||
},
|
||||
site: (host) => sites.get(host),
|
||||
url,
|
||||
}
|
||||
|
||||
const json = (status: number, body: Record<string, unknown>, headers: Record<string, string> = {}) =>
|
||||
new Response(JSON.stringify(body), { headers: { 'cache-control': 'no-store', 'content-type': 'application/json', ...headers }, status })
|
||||
|
||||
const refused = (r: Refusal) =>
|
||||
json(
|
||||
r.status,
|
||||
{ code: r.code, message: r.message, ok: false, retryable: r.extra.retryable ?? false, ...(r.extra.field ? { field: r.extra.field } : {}), ...(r.extra.limit ? { limit: r.extra.limit } : {}), ...(r.extra.reason ? { reason: r.extra.reason } : {}), ...(r.extra.retryAfter !== undefined ? { retryAfter: r.extra.retryAfter } : {}) },
|
||||
r.extra.retryAfter !== undefined ? { 'retry-after': String(r.extra.retryAfter) } : {},
|
||||
)
|
||||
|
||||
async function readJson(request: Request): Promise<{ bytes: Uint8Array; value: Record<string, unknown> }> {
|
||||
if (!(request.headers.get('content-type') ?? '').toLowerCase().startsWith('application/json')) {
|
||||
throw new Refusal(415, 'unsupported-media-type', 'The body must be application/json.')
|
||||
}
|
||||
const bytes = new Uint8Array(await request.arrayBuffer())
|
||||
let value: unknown
|
||||
try {
|
||||
value = JSON.parse(new TextDecoder().decode(bytes))
|
||||
} catch {
|
||||
throw invalid('body', 'The body is not JSON.')
|
||||
}
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {throw invalid('body', 'The body must be an object.')}
|
||||
return { bytes, value: value as Record<string, unknown> }
|
||||
}
|
||||
|
||||
function authenticate(request: Request, address: string): { current: boolean; site: Site } {
|
||||
const match = /^bearer (\S+)$/i.exec(request.headers.get('authorization') ?? '')
|
||||
const host = match ? tokens.get(sha256(match[1])) : undefined
|
||||
const site = host ? sites.get(host) : undefined
|
||||
const current = Boolean(site && match && site.token === match[1])
|
||||
const previous = Boolean(site && match && site.previous?.token === match[1] && site.previous.until > now())
|
||||
if (!site || (!current && !previous)) {throw new Refusal(401, 'invalid-token', 'No token, or one the service does not know.')}
|
||||
if (site.bindOnUse && site.addresses.length === 0) {site.addresses.push(address)}
|
||||
if (!site.addresses.includes(address)) {throw new Refusal(401, 'reverify', 'The token is good, but this server address is new for the site. Enrol again.')}
|
||||
// used most recently last: beyond the limit the address used longest ago is dropped
|
||||
site.addresses = [...site.addresses.filter((a) => a !== address), address]
|
||||
return { current, site }
|
||||
}
|
||||
|
||||
async function enrol(request: Request, address: string): Promise<Response> {
|
||||
const { value } = await readJson(request)
|
||||
for (const key of Object.keys(value)) {
|
||||
if (!['host', 'nonce', 'product', 'productVersion'].includes(key)) {throw invalid(key, `Unknown field "${key}".`)}
|
||||
}
|
||||
const { host, nonce, product, productVersion } = value
|
||||
if (typeof host !== 'string') {throw invalid('host', 'host is required.')}
|
||||
if (typeof nonce !== 'string' || !NONCE.test(nonce)) {throw invalid('nonce', 'nonce must be 32 to 128 characters of A-Z a-z 0-9 _ -.')}
|
||||
if (product !== 'iapl' && product !== 'iawl') {throw invalid('product', 'Unknown product.')}
|
||||
if (typeof productVersion !== 'string' || !VERSION.test(productVersion) || productVersion.length > 32) {throw invalid('productVersion', 'productVersion is required.')}
|
||||
const local = Boolean(options.allowLocalHosts) && LOCAL_HOST.test(host)
|
||||
if (!isPublicHost(host) && !local) {throw new Refusal(403, 'host-not-allowed', 'The host is not a public DNS name.')}
|
||||
|
||||
const existing = sites.get(host)
|
||||
if (existing?.state === 'suspended') {throw new Refusal(403, 'site-suspended', 'The site was stopped by Intecion.')}
|
||||
const site = existing ?? blank(host, product)
|
||||
const state = existing?.state === 'active' || isListed(host) ? 'active' : 'pending'
|
||||
const token = newToken()
|
||||
const path = site.callbackPath ?? (product === 'iawl' ? '/?rest_route=/iawl/v1/mail-relay/confirm' : '/api/iapl/mail-relay/confirm')
|
||||
const target = `${local && !isPublicHost(host) ? 'http' : 'https'}://${host}${path}`
|
||||
const body = JSON.stringify({ nonce, state, token })
|
||||
const fail = (reason: string) => new Refusal(422, 'callback-failed', `The site's confirm endpoint did not confirm (${reason}).`, { reason })
|
||||
let answer: Response
|
||||
try {
|
||||
const call = options.callSite ?? ((u, init) => fetch(u, { ...init, redirect: 'manual', signal: AbortSignal.timeout(8000) }))
|
||||
answer = await call(target, { body, headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
} catch (err) {
|
||||
throw fail(err instanceof Error && err.name === 'TimeoutError' ? 'timeout' : 'unreachable')
|
||||
}
|
||||
if (answer.status >= 300 && answer.status < 400) {throw fail('redirect')}
|
||||
if (answer.status !== 200) {throw fail('status')}
|
||||
let confirmation: unknown
|
||||
try {
|
||||
const text = await answer.text()
|
||||
confirmation = text.length <= 1024 ? (JSON.parse(text) as { confirmation?: unknown }).confirmation : undefined
|
||||
} catch {
|
||||
confirmation = undefined
|
||||
}
|
||||
if (confirmation !== sha256(`${nonce}.${token}`)) {throw fail('confirmation')}
|
||||
|
||||
sites.set(host, site)
|
||||
site.state = state
|
||||
site.product = product
|
||||
if (site.token) {site.previous = { token: site.token, until: now() + DAY }}
|
||||
site.token = token
|
||||
site.issuedAt = now()
|
||||
site.bindOnUse = false
|
||||
tokens.set(sha256(token), host)
|
||||
site.addresses = [...site.addresses.filter((a) => a !== address), address].slice(-relay.limits.serverAddresses)
|
||||
return json(200, { ok: true, state })
|
||||
}
|
||||
|
||||
function validateSend(value: Record<string, unknown>, site: Site) {
|
||||
for (const key of Object.keys(value)) {
|
||||
if (!SEND_FIELDS.has(key)) {throw invalid(key, `Unknown field "${key}".`)}
|
||||
}
|
||||
const kind = value.kind as MailKind
|
||||
if (value.product !== 'iapl' && value.product !== 'iawl') {throw invalid('product', 'Unknown product.')}
|
||||
if (typeof value.productVersion !== 'string' || !VERSION.test(value.productVersion)) {throw invalid('productVersion', 'productVersion is required.')}
|
||||
if (!(MAIL_KINDS as readonly string[]).includes(kind)) {throw invalid('kind', 'Unknown kind.')}
|
||||
const list = (field: 'bcc' | 'cc' | 'to'): string[] => {
|
||||
const raw = value[field]
|
||||
if (raw === undefined) {return []}
|
||||
if (!Array.isArray(raw) || raw.some((a) => typeof a !== 'string' || a.length > 254 || !ADDRESS.test(a))) {throw invalid(field, `${field} must be a list of bare addresses.`)}
|
||||
return raw as string[]
|
||||
}
|
||||
let to = list('to')
|
||||
let cc = list('cc')
|
||||
let bcc = list('bcc')
|
||||
if (kind === 'security-alert') {
|
||||
to = [alertRecipient]
|
||||
cc = []
|
||||
bcc = []
|
||||
} else if (to.length === 0) {throw invalid('to', 'At least one recipient.')}
|
||||
if (to.length + cc.length + bcc.length > relay.limits.recipientsPerMessage) {
|
||||
throw new Refusal(422, 'too-many-recipients', `At most ${relay.limits.recipientsPerMessage} recipients a message.`)
|
||||
}
|
||||
const replyTo = value.replyTo
|
||||
if (replyTo !== undefined && (typeof replyTo !== 'string' || !ADDRESS.test(replyTo))) {throw invalid('replyTo', 'replyTo must be one bare address.')}
|
||||
const senderName = value.senderName
|
||||
if (senderName !== undefined && (typeof senderName !== 'string' || [...senderName].length > 256)) {throw invalid('senderName', 'senderName must be at most 256 characters.')}
|
||||
const subject = value.subject
|
||||
if (typeof subject !== 'string' || subject.length === 0 || [...subject].length > 300) {throw invalid('subject', 'subject must be 1 to 300 characters.')}
|
||||
if (UNSAFE_SUBJECT.test(subject)) {throw invalid('subject', 'subject must not contain line breaks, control or invisible characters.')}
|
||||
if (subject.replace(/\s+/g, '').toLowerCase().startsWith(`[${RELAY_SERVICE_NAME.replace(/ /g, '').toLowerCase()}`)) {
|
||||
throw invalid('subject', 'The subject must not start with the name of the mail service in brackets.')
|
||||
}
|
||||
const { html, text } = value
|
||||
if (text !== undefined && (typeof text !== 'string' || !text)) {throw invalid('text', 'text must be a non-empty string.')}
|
||||
if (html !== undefined && (typeof html !== 'string' || !html)) {throw invalid('html', 'html must be a non-empty string.')}
|
||||
if (text === undefined && html === undefined) {throw invalid('text', 'text or html is required.')}
|
||||
if (Buffer.byteLength(`${(text) ?? ''}${(html) ?? ''}`) > relay.limits.maxBodyBytes) {
|
||||
throw new Refusal(413, 'too-large', 'The body is too large.', { limit: 'body' })
|
||||
}
|
||||
const attachments: FakeRelayMail['attachments'] = []
|
||||
if (value.attachments !== undefined) {
|
||||
if (!Array.isArray(value.attachments) || value.attachments.length > relay.limits.maxAttachments) {throw invalid('attachments', 'Too many attachments.')}
|
||||
let total = 0
|
||||
value.attachments.forEach((raw: unknown, index: number) => {
|
||||
const a = raw as { content?: unknown; contentType?: unknown; filename?: unknown }
|
||||
if (!a || typeof a !== 'object' || Object.keys(a).some((k) => !['content', 'contentType', 'filename'].includes(k))) {throw invalid('attachments', 'Unknown field in an attachment.')}
|
||||
if (typeof a.filename !== 'string' || !a.filename || a.filename.length > 255) {throw invalid('attachments', 'An attachment needs a filename.')}
|
||||
if (typeof a.contentType !== 'string' || !CONTENT_TYPE.test(a.contentType)) {throw invalid('attachments', 'An attachment needs a content type.')}
|
||||
if (typeof a.content !== 'string' || a.content.length < 4 || a.content.length % 4 !== 0 || !/^[A-Z0-9+/]+={0,2}$/i.test(a.content)) {throw invalid('attachments', 'content must be padded base64.')}
|
||||
const refusedFile = new Refusal(422, 'attachment-refused', 'A file the service never carries, or a bad file name.', { field: `attachments[${index}]` })
|
||||
if (UNSAFE_NAME.test(a.filename) || /[/\\"<>|:*?]/.test(a.filename) || a.filename.startsWith('.')) {throw refusedFile}
|
||||
if (a.filename.toLowerCase().split('.').slice(1).some((e) => EXECUTABLE.has(e))) {throw refusedFile}
|
||||
const bytes = (a.content.length * 3) / 4 - (a.content.endsWith('==') ? 2 : a.content.endsWith('=') ? 1 : 0)
|
||||
total += bytes
|
||||
attachments.push({ bytes, contentType: a.contentType, filename: a.filename })
|
||||
})
|
||||
if (total > relay.limits.maxAttachmentBytes) {throw new Refusal(413, 'too-large', 'The attachments are too large.', { limit: 'attachments' })}
|
||||
}
|
||||
const asked = typeof senderName === 'string' ? senderName : ''
|
||||
const accepted = asked ? guardName(asked, site.host) : null
|
||||
const marked = [...bcc, ...cc, ...to].includes(alertRecipient)
|
||||
return {
|
||||
attachments, bcc, cc, html, kind, replaced: Boolean(asked) && !accepted,
|
||||
replyTo, senderName: accepted ?? site.host, subject: marked ? `[${site.host}] ${subject}` : subject, text, to,
|
||||
}
|
||||
}
|
||||
|
||||
/** The limits of contract §3.3, counted simply (no sliding window: `reset()` or the site's counters start them again). */
|
||||
function checkQuota(site: Site, kind: MailKind, recipients: string[]): { apply: () => void; left: { day: number; hour: number } } {
|
||||
const { messagesPerDay: day, messagesPerHour: hour, newRecipientsPerDay, perRecipientPerDay, securityAlertsPerDay } = relay.limits
|
||||
const over = (limit: string) => new Refusal(429, 'quota-exceeded', `The site reached its limit (${limit}).`, { limit })
|
||||
if (kind === 'security-alert') {
|
||||
if (site.alerts >= securityAlertsPerDay) {throw over('alerts')}
|
||||
return { apply: () => void (site.alerts += 1), left: { day: securityAlertsPerDay - site.alerts - 1, hour: securityAlertsPerDay - site.alerts - 1 } }
|
||||
}
|
||||
const share = (limit: number) => (kind === 'account' || limit < 5 ? limit : Math.floor((limit * 4) / 5))
|
||||
const usedHour = kind === 'account' ? site.hourAccount + site.hourOther : site.hourOther
|
||||
const usedDay = kind === 'account' ? site.dayAccount + site.dayOther : site.dayOther
|
||||
if (usedHour >= share(hour) || site.hourAccount + site.hourOther >= hour) {throw over('hour')}
|
||||
if (usedDay >= share(day) || site.dayAccount + site.dayOther >= day) {throw over('day')}
|
||||
if (kind === 'form-confirmation' && recipients.some((r) => (site.confirmations.get(r.toLowerCase()) ?? 0) >= perRecipientPerDay)) {throw over('recipient')}
|
||||
const seen = seenRecipients.get(site.host) ?? new Set<string>()
|
||||
seenRecipients.set(site.host, seen)
|
||||
const fresh = kind === 'account' ? [] : recipients.filter((r) => !seen.has(r.toLowerCase()))
|
||||
const newToday = [...seen].filter((r) => r.startsWith('new:')).length
|
||||
const newLimit = kind === 'form-confirmation' && newRecipientsPerDay >= 5 ? Math.floor((newRecipientsPerDay * 4) / 5) : newRecipientsPerDay
|
||||
if (fresh.length && newToday + fresh.length > newLimit) {throw over('new-recipients')}
|
||||
return {
|
||||
apply: () => {
|
||||
if (kind === 'account') {
|
||||
site.hourAccount += 1
|
||||
site.dayAccount += 1
|
||||
} else {
|
||||
site.hourOther += 1
|
||||
site.dayOther += 1
|
||||
}
|
||||
if (kind === 'form-confirmation') {
|
||||
for (const r of recipients) {site.confirmations.set(r.toLowerCase(), (site.confirmations.get(r.toLowerCase()) ?? 0) + 1)}
|
||||
}
|
||||
for (const r of fresh) {
|
||||
seen.add(r.toLowerCase())
|
||||
seen.add(`new:${r.toLowerCase()}`)
|
||||
}
|
||||
},
|
||||
left: { day: Math.max(0, Math.min(share(day) - usedDay, day - site.dayAccount - site.dayOther) - 1), hour: Math.max(0, Math.min(share(hour) - usedHour, hour - site.hourAccount - site.hourOther) - 1) },
|
||||
}
|
||||
}
|
||||
|
||||
async function send(request: Request, address: string): Promise<Response> {
|
||||
const { site } = authenticate(request, address)
|
||||
if (site.state === 'pending') {throw new Refusal(403, 'site-pending', 'The site is waiting for approval by Intecion.')}
|
||||
if (site.state === 'suspended') {throw new Refusal(403, 'site-suspended', 'The site was stopped by Intecion.')}
|
||||
const key = request.headers.get('idempotency-key') ?? ''
|
||||
if (!KEY.test(key)) {throw invalid('Idempotency-Key', 'Idempotency-Key must be 16 to 128 characters of A-Z a-z 0-9 _ -.')}
|
||||
const { bytes, value } = await readJson(request)
|
||||
const hash = sha256(bytes)
|
||||
const known = site.keys.get(key)
|
||||
if (known) {
|
||||
if (known.hash !== hash) {throw new Refusal(409, 'idempotency-conflict', 'This Idempotency-Key was used for a different message.')}
|
||||
return json(200, { ...known.answer, replayed: true })
|
||||
}
|
||||
const mail = validateSend(value, site)
|
||||
const quota = checkQuota(site, mail.kind, [...mail.to, ...mail.cc, ...mail.bcc])
|
||||
if (relay.backend === 'failure') {throw new Refusal(502, 'backend-failed', 'The mail back end failed.', { retryable: true })}
|
||||
if (relay.backend === 'recipient-suppressed') {throw new Refusal(422, 'recipient-suppressed', 'The mail back end refuses one of the recipients. Nothing was sent.')}
|
||||
quota.apply()
|
||||
site.lastSenderName = mail.senderName
|
||||
relay.outbox.push({
|
||||
attachments: mail.attachments, bcc: mail.bcc, cc: mail.cc, from: senderAddress, fromName: mail.senderName,
|
||||
headers: { 'X-Intecion-Product': String(value.product), 'X-Intecion-Site': site.host }, host: site.host,
|
||||
...(mail.html ? { html: mail.html } : {}), kind: mail.kind, ...(mail.replyTo ? { replyTo: mail.replyTo } : {}), subject: mail.subject, ...(mail.text ? { text: mail.text } : {}), to: mail.to,
|
||||
})
|
||||
const { messagesPerDay, messagesPerHour } = relay.limits
|
||||
const answer = {
|
||||
id: `fake-${relay.outbox.length}`,
|
||||
messageId: `<fake-${relay.outbox.length}@${senderAddress.split('@')[1]}>`,
|
||||
ok: true,
|
||||
quota: { day: { limit: messagesPerDay, remaining: quota.left.day }, hour: { limit: messagesPerHour, remaining: quota.left.hour } },
|
||||
replayed: false,
|
||||
senderName: mail.senderName,
|
||||
warnings: mail.replaced ? ['sender-name-replaced'] : [],
|
||||
}
|
||||
site.keys.set(key, { answer, hash })
|
||||
return json(200, answer)
|
||||
}
|
||||
|
||||
function status(request: Request, address: string): Response {
|
||||
const { site } = authenticate(request, address)
|
||||
const { messagesPerDay, messagesPerHour } = relay.limits
|
||||
return json(200, {
|
||||
host: site.host,
|
||||
kinds: [...MAIL_KINDS],
|
||||
limits: relay.limits,
|
||||
ok: true,
|
||||
product: site.product,
|
||||
quota: { day: { limit: messagesPerDay, remaining: Math.max(0, messagesPerDay - site.dayAccount - site.dayOther) }, hour: { limit: messagesPerHour, remaining: Math.max(0, messagesPerHour - site.hourAccount - site.hourOther) } },
|
||||
sender: { address: senderAddress },
|
||||
...(site.lastSenderName ? { senderName: site.lastSenderName } : {}),
|
||||
service: { name: RELAY_SERVICE_NAME, contract: RELAY_CONTRACT_VERSION, version: '0.0.0-fake' },
|
||||
state: site.state,
|
||||
token: { issuedAt: new Date(site.issuedAt).toISOString(), rotateAfter: new Date(site.issuedAt + 90 * DAY).toISOString() },
|
||||
})
|
||||
}
|
||||
|
||||
async function handle(request: Request): Promise<Response> {
|
||||
const path = new URL(request.url).pathname.slice(new URL(url).pathname.length) || '/'
|
||||
const address = request.headers.get('x-fake-client-address') ?? relay.clientAddress
|
||||
relay.requests.push({ address, method: request.method, path })
|
||||
try {
|
||||
const fetchSite = request.headers.get('sec-fetch-site')
|
||||
if (request.headers.has('origin') || (fetchSite !== null && fetchSite !== 'none')) {throw new Refusal(403, 'browser-not-allowed', 'The service is for servers, not browsers.')}
|
||||
const routes: Record<string, [string, () => Promise<Response> | Response]> = {
|
||||
'/health': ['GET', () => json(200, { ok: true })],
|
||||
'/v1/enrol': ['POST', () => enrol(request, address)],
|
||||
'/v1/revoke': ['POST', () => {
|
||||
const { site } = authenticate(request, address)
|
||||
for (const [hash, host] of tokens) {
|
||||
if (host === site.host) {tokens.delete(hash)}
|
||||
}
|
||||
site.token = undefined
|
||||
site.previous = undefined
|
||||
return json(200, { ok: true })
|
||||
}],
|
||||
'/v1/rotate': ['POST', () => {
|
||||
const { current, site } = authenticate(request, address)
|
||||
if (!current) {throw new Refusal(409, 'already-rotated', 'Only the current token can rotate.')}
|
||||
const token = giveToken(site)
|
||||
return json(200, { ok: true, previousValidUntil: new Date(now() + DAY).toISOString(), token })
|
||||
}],
|
||||
'/v1/send': ['POST', () => send(request, address)],
|
||||
'/v1/status': ['GET', () => status(request, address)],
|
||||
}
|
||||
const route = routes[path]
|
||||
if (!route) {throw new Refusal(404, 'not-found', 'No such route.')}
|
||||
if (route[0] !== request.method) {throw new Refusal(405, 'method-not-allowed', 'Wrong method.')}
|
||||
return await route[1]()
|
||||
} catch (err) {
|
||||
if (err instanceof Refusal) {return refused(err)}
|
||||
return refused(new Refusal(500, 'internal', 'A fault in the fake service.', { retryable: true }))
|
||||
}
|
||||
}
|
||||
|
||||
return relay
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { type RelayOptions, resolveRelayOptions } from './options.js'
|
||||
import { disconnectRelay as disconnect, enrolRelay as enrol, type EnrolResult, type RelayStatus, rotateRelayToken as rotate, getRelayStatus as status } from './session.js'
|
||||
|
||||
export { RELAY_SENDER_ADDRESS, relayAdapter, relayAttachmentLimit, relaySenderName } from './adapter.js'
|
||||
export type { RelayAdapterArgs } from './adapter.js'
|
||||
export { relayRequest } from './client.js'
|
||||
export type { RelayAnswer, RelayCall, RelayRefusal } from './client.js'
|
||||
export { relayConfirmEndpoint } from './confirm.js'
|
||||
export {
|
||||
RELAY_BASE_URL,
|
||||
RELAY_CONFIRM_PATH,
|
||||
RELAY_CONTRACT_VERSION,
|
||||
RELAY_DEFAULTS,
|
||||
RELAY_KV_KEY,
|
||||
RELAY_PRODUCT,
|
||||
RELAY_SERVICE_NAME,
|
||||
RELAY_STATUS_CODES,
|
||||
relayStatusFor,
|
||||
} from './constants.js'
|
||||
export type { RelayStatusCode } from './constants.js'
|
||||
export { MAIL_KIND, MAIL_KINDS, mailKindOf, markNextMail, runWithMailKind, withMailKind } from './kinds.js'
|
||||
export type { MailKind } from './kinds.js'
|
||||
export { bareAddress, bareAddresses, buildRelayMessage, cleanSubject } from './message.js'
|
||||
export type { BuildRelayMessageArgs, BuiltRelayMessage, RelaySendRequest } from './message.js'
|
||||
export { isPublicHost, relayHost, resolveRelayOptions } from './options.js'
|
||||
export type { RelayOptions } from './options.js'
|
||||
export { sendThroughRelay } from './send.js'
|
||||
export type { RelaySendContext, RelaySendResult } from './send.js'
|
||||
export { setRelayToken } from './session.js'
|
||||
export type { EnrolResult, RelayStatus } from './session.js'
|
||||
|
||||
const DISABLED = 'The mail service is switched off for this project (mail: { relay: false }).'
|
||||
|
||||
function resolved(payload: BasePayload, options?: RelayOptions) {
|
||||
const out = resolveRelayOptions(payload, options)
|
||||
if (!out) {throw new Error(DISABLED)}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Enrols the site with the Intecion Notifications Webservice now (a deploy script, a "Connect" button
|
||||
* of your own). `mailAdapter()` does this by itself on the first send. `force` also after a refusal a
|
||||
* moment ago, or after "Disconnect".
|
||||
*/
|
||||
export const enrolRelay = (payload: BasePayload, options?: { force?: boolean } & RelayOptions): Promise<EnrolResult> => {
|
||||
const { force, ...own } = options ?? {}
|
||||
return enrol(payload, resolved(payload, Object.keys(own).length ? own : undefined), { force })
|
||||
}
|
||||
|
||||
/** The site's state with the service — never the token. `refresh: true` asks the service; otherwise the stored state. */
|
||||
export const getRelayStatus = (payload: BasePayload, options?: { refresh?: boolean } & RelayOptions): Promise<{ error?: string } & RelayStatus> => {
|
||||
const { refresh, ...own } = options ?? {}
|
||||
return status(payload, resolved(payload, Object.keys(own).length ? own : undefined), { refresh })
|
||||
}
|
||||
|
||||
/** Gives the site's token up on the service and forgets it; the site sends nothing through the service until it is connected again. */
|
||||
export const disconnectRelay = (payload: BasePayload, options?: RelayOptions): Promise<void> => disconnect(payload, resolved(payload, options))
|
||||
|
||||
/** Asks for a new token now (the adapter does it by itself when the service says the token is due). */
|
||||
export const rotateRelayToken = (payload: BasePayload, options?: RelayOptions) => rotate(payload, resolved(payload, options), { force: true })
|
||||
@@ -0,0 +1,58 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||
|
||||
/**
|
||||
* What a message is for. The Intecion Notifications Webservice applies different limits per kind, so
|
||||
* the kind has to be true: `account` only for mail to an account holder (password reset, invitation),
|
||||
* `form-confirmation` for mail to an address a visitor typed, `form-notification` for a form's mail to
|
||||
* the addresses written in the panel. Mail whose purpose is not known is `system`.
|
||||
*/
|
||||
export const MAIL_KINDS = ['form-notification', 'form-confirmation', 'account', 'security-alert', 'system', 'test'] as const
|
||||
export type MailKind = (typeof MAIL_KINDS)[number]
|
||||
|
||||
/** The key of the kind on a message. A symbol: no mail library reads it, JSON leaves it out, a spread keeps it. */
|
||||
export const MAIL_KIND = Symbol.for('iapl.mailKind')
|
||||
|
||||
const isKind = (value: unknown): value is MailKind => typeof value === 'string' && (MAIL_KINDS as readonly string[]).includes(value)
|
||||
|
||||
/**
|
||||
* Marks a message for `payload.sendEmail`:
|
||||
* await payload.sendEmail(withMailKind({ to, subject, html }, 'account'))
|
||||
* Other transports (SMTP, Graph, a project's own adapter) ignore the mark.
|
||||
*/
|
||||
export function withMailKind<T extends object>(message: T, kind: MailKind): T {
|
||||
return { ...message, [MAIL_KIND]: kind }
|
||||
}
|
||||
|
||||
/** The kind a message was marked with, if any. */
|
||||
export function mailKindOf(message: unknown): MailKind | undefined {
|
||||
const kind = message && typeof message === 'object' ? (message as Record<symbol, unknown>)[MAIL_KIND] : undefined
|
||||
return isKind(kind) ? kind : undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* For mail the plugin does not compose itself (Payload's "forgot password" and "verify your e-mail"):
|
||||
* the operation's hook says what the NEXT message of this request is, and the adapter takes it once.
|
||||
*/
|
||||
type MailContext = { kind: MailKind; sticky?: boolean; taken?: boolean; visitor?: string }
|
||||
const context = new AsyncLocalStorage<MailContext>()
|
||||
|
||||
/**
|
||||
* Says that the next message sent in this request is of `kind`. Call it synchronously at the start of
|
||||
* a hook (before the first `await`), so the operation that called the hook runs on in this context.
|
||||
*/
|
||||
export function markNextMail(kind: MailKind, extra: { visitor?: string } = {}): void {
|
||||
context.enterWith({ kind, ...extra })
|
||||
}
|
||||
|
||||
/** Runs `fn` with every message sent inside it marked as `kind` (a message's own mark still wins). */
|
||||
export function runWithMailKind<T>(kind: MailKind, fn: () => T): T {
|
||||
return context.run({ kind, sticky: true }, fn)
|
||||
}
|
||||
|
||||
/** The context of the message being sent now; a one-shot mark is used up by this call. */
|
||||
export function takeMailContext(): { kind: MailKind; visitor?: string } | undefined {
|
||||
const current = context.getStore()
|
||||
if (!current || current.taken) {return undefined}
|
||||
if (!current.sticky) {current.taken = true}
|
||||
return { kind: current.kind, visitor: current.visitor }
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import type { SendEmailOptions } from 'payload'
|
||||
|
||||
import { domainToASCII } from 'node:url'
|
||||
|
||||
import type { MailKind } from './kinds.js'
|
||||
|
||||
import { PLUGIN_VERSION } from '../../../version.js'
|
||||
import { toGraphAttachments } from '../graphAttachments.js'
|
||||
import { RELAY_PRODUCT, RELAY_SERVICE_NAME } from './constants.js'
|
||||
|
||||
/** The body of `POST /v1/send` (contracts/mail-relay/schema.json, `SendRequest`). Closed: no other field exists. */
|
||||
export type RelaySendRequest = {
|
||||
attachments?: { content: string; contentType: string; filename: string }[]
|
||||
bcc?: string[]
|
||||
cc?: string[]
|
||||
html?: string
|
||||
kind: MailKind
|
||||
product: string
|
||||
productVersion: string
|
||||
replyTo?: string
|
||||
senderName?: string
|
||||
subject: string
|
||||
text?: string
|
||||
to?: string[]
|
||||
}
|
||||
|
||||
const ADDRESS = /^[\w!#$%&'*+/=?^`{|}~-]+(?:\.[\w!#$%&'*+/=?^`{|}~-]+)*@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z][A-Z0-9-]{0,61}[A-Z0-9]$/i
|
||||
const CONTENT_TYPE = /^[A-Z0-9][\w!#$&^.+-]*\/[A-Z0-9][\w!#$&^.+-]*$/i
|
||||
/** What a subject may not contain (contract §3): control and invisible characters, except ZWJ, ZWNJ and the soft hyphen. */
|
||||
// three single code points on purpose (ZWNJ, ZWJ, soft hyphen), not a joined sequence
|
||||
// eslint-disable-next-line no-misleading-character-class
|
||||
const UNSAFE = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}]|(?![\u200C\u200D\u00AD])\p{Cf}/gu
|
||||
const UNSAFE_STRICT = /[\p{Cc}\p{Zl}\p{Zp}\p{Co}\p{Cs}\p{Cf}]/gu
|
||||
|
||||
/** One bare address (`name@domain`, ASCII; an international domain as punycode), or null. */
|
||||
export function bareAddress(value: unknown): null | string {
|
||||
const raw = typeof value === 'string' ? value : value && typeof value === 'object' ? (value as { address?: unknown }).address : ''
|
||||
if (typeof raw !== 'string') {return null}
|
||||
const text = (raw.match(/<([^<>]+)>\s*$/)?.[1] ?? raw).trim()
|
||||
const at = text.lastIndexOf('@')
|
||||
if (at < 1) {return null}
|
||||
const domain = /^[\x21-\x7e]+$/.test(text.slice(at + 1)) ? text.slice(at + 1) : domainToASCII(text.slice(at + 1))
|
||||
const address = `${text.slice(0, at)}@${domain}`
|
||||
return address.length >= 6 && address.length <= 254 && ADDRESS.test(address) ? address : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Every address of a To / CC / BCC value as nodemailer takes it — a string ("Anna <[email protected]>, [email protected]"),
|
||||
* an object, or a list of either — as bare addresses. `dropped` counts what was not an address.
|
||||
*/
|
||||
export function bareAddresses(value: unknown): { addresses: string[]; dropped: number } {
|
||||
const parts: unknown[] = []
|
||||
for (const item of Array.isArray(value) ? value : value === undefined || value === null || value === '' ? [] : [value]) {
|
||||
if (typeof item === 'string') {
|
||||
// commas and semicolons separate addresses, except inside a quoted display name
|
||||
parts.push(...(item.match(/(?:"[^"]*"|[^,;])+/g) ?? []).map((p) => p.trim()).filter(Boolean))
|
||||
} else {parts.push(item)}
|
||||
}
|
||||
const addresses: string[] = []
|
||||
let dropped = 0
|
||||
for (const part of parts) {
|
||||
const address = bareAddress(part)
|
||||
if (!address) {dropped += 1}
|
||||
else if (!addresses.some((a) => a.toLowerCase() === address.toLowerCase())) {addresses.push(address)}
|
||||
}
|
||||
return { addresses, dropped }
|
||||
}
|
||||
|
||||
const codePoints = (text: string, max: number) => {
|
||||
const points = [...text]
|
||||
return points.length > max ? points.slice(0, max).join('') : text
|
||||
}
|
||||
|
||||
/**
|
||||
* A subject the service accepts. It refuses, it does not repair — and a subject is often a visitor's
|
||||
* own words — so line breaks become spaces, control and invisible characters go, the length is cut to
|
||||
* 300 characters, and a subject that would start like the service's own notices loses its bracket.
|
||||
*/
|
||||
export function cleanSubject(subject: unknown): string {
|
||||
let text = typeof subject === 'string' ? subject : ''
|
||||
text = text.replace(/[\r\n\t\u2028\u2029]+/g, ' ').replace(UNSAFE, '').replace(/ {2,}/g, ' ').trim()
|
||||
if (text.replace(/\s+/g, '').toLowerCase().startsWith(`[${RELAY_SERVICE_NAME.replace(/ /g, '').toLowerCase()}`)) {text = text.replace(/^\s*\[\s*/, '')}
|
||||
return codePoints(text, 300) || '(no subject)'
|
||||
}
|
||||
|
||||
/** A file name the service accepts: no path, no quotes, nothing invisible. */
|
||||
export function cleanFilename(name: unknown): string {
|
||||
const base = (typeof name === 'string' ? name : '').split(/[/\\]/).pop() ?? ''
|
||||
const clean = base.replace(UNSAFE_STRICT, '').replace(/["<>|:*?]/g, '_').replace(/^\.+/, '').trim()
|
||||
return codePoints(clean, 255) || 'attachment'
|
||||
}
|
||||
|
||||
const bodyText = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' ? value || undefined : Buffer.isBuffer(value) ? value.toString('utf8') || undefined : undefined
|
||||
|
||||
export type BuildRelayMessageArgs = {
|
||||
/** What the message is for. Default `system`. */
|
||||
kind?: MailKind
|
||||
product?: string
|
||||
productVersion?: string
|
||||
/** Used when the message names no reply address of its own (the panel's "Sender address"). */
|
||||
replyTo?: null | string
|
||||
/** The display name (the panel's "Sender name", else the site name). Without one the mail leaves under the site's host. */
|
||||
senderName?: null | string
|
||||
}
|
||||
|
||||
export type BuiltRelayMessage =
|
||||
| { dropped: number; ok: true; request: RelaySendRequest }
|
||||
| { ok: false; problem: string }
|
||||
|
||||
/**
|
||||
* A Payload / nodemailer message as the request the service takes. `from` and free headers are left
|
||||
* out: the service fixes the sender address, and there is no field for either.
|
||||
*/
|
||||
export function buildRelayMessage(message: SendEmailOptions, args: BuildRelayMessageArgs = {}): BuiltRelayMessage {
|
||||
const m = message as Record<string, unknown>
|
||||
const kind = args.kind ?? 'system'
|
||||
const to = bareAddresses(m.to)
|
||||
const cc = bareAddresses(m.cc)
|
||||
const bcc = bareAddresses(m.bcc)
|
||||
if (kind !== 'security-alert' && to.addresses.length === 0) {return { ok: false, problem: 'The message has no valid recipient address.' }}
|
||||
|
||||
const text = bodyText(m.text)
|
||||
const html = bodyText(m.html)
|
||||
if (!text && !html) {return { ok: false, problem: 'The message has no text and no HTML body.' }}
|
||||
|
||||
const all = toGraphAttachments(message)
|
||||
if (all === null) {return { ok: false, problem: 'An attachment has content the mail service cannot carry (pass a Buffer or a string).' }}
|
||||
// an empty file cannot be written in the request (base64 of at least one byte) and carries nothing
|
||||
const files = all.filter((file) => file.content.length > 0)
|
||||
|
||||
const replyTo = bareAddresses(m.replyTo).addresses[0] ?? bareAddress(args.replyTo ?? '') ?? undefined
|
||||
const senderName = typeof args.senderName === 'string' ? codePoints(args.senderName.replace(UNSAFE_STRICT, ' ').replace(/ {2,}/g, ' ').trim(), 256) : ''
|
||||
|
||||
const request: RelaySendRequest = {
|
||||
kind,
|
||||
product: args.product ?? RELAY_PRODUCT,
|
||||
productVersion: args.productVersion ?? PLUGIN_VERSION,
|
||||
...(kind === 'security-alert' && !to.addresses.length ? {} : { to: to.addresses }),
|
||||
...(cc.addresses.length ? { cc: cc.addresses } : {}),
|
||||
...(bcc.addresses.length ? { bcc: bcc.addresses } : {}),
|
||||
...(replyTo ? { replyTo } : {}),
|
||||
...(senderName ? { senderName } : {}),
|
||||
subject: cleanSubject(m.subject),
|
||||
...(text ? { text } : {}),
|
||||
...(html ? { html } : {}),
|
||||
...(files.length
|
||||
? {
|
||||
attachments: files.map((file) => {
|
||||
const type = file.contentType.split(';')[0].trim()
|
||||
return {
|
||||
content: file.content.toString('base64'),
|
||||
contentType: CONTENT_TYPE.test(type) && type.length <= 127 ? type : 'application/octet-stream',
|
||||
filename: cleanFilename(file.name),
|
||||
}
|
||||
}),
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
return { dropped: to.dropped + cc.dropped + bcc.dropped, ok: true, request }
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { BasePayload, SendEmailOptions } from 'payload'
|
||||
|
||||
import type { MailKind } from './kinds.js'
|
||||
|
||||
import { RELAY_BASE_URL } from './constants.js'
|
||||
|
||||
/**
|
||||
* `iapl({ mail: { relay } })` and `mailAdapter({ relay })`. Every key is optional; `relay: false`
|
||||
* switches the transport, the enrolment and the confirm route off.
|
||||
*/
|
||||
export type RelayOptions = {
|
||||
/**
|
||||
* "Forgot password" is a visitor's lever like a form: the service lets `account` mail use the site's
|
||||
* whole hour. So the plugin limits it itself, per address and per visitor (the request's address).
|
||||
* Default 5 per address and 10 per visitor an hour; `false` = no limit of the plugin's.
|
||||
*/
|
||||
accountMail?: { perAddress?: number; perVisitor?: number; windowMinutes?: number } | false
|
||||
/** Calls to the public confirm route per address. Default 10 a minute. */
|
||||
confirmRateLimit?: { max?: number; windowMs?: number }
|
||||
/**
|
||||
* `'auto'` (default): the site enrols by itself on the first send without a token, and again after
|
||||
* the service asks for it. `'manual'`: only "Connect" in the panel or `enrolRelay()` enrols.
|
||||
* `false`: never — the token comes from `token` or `setRelayToken()`.
|
||||
*/
|
||||
enrol?: 'auto' | 'manual' | false
|
||||
/** For tests and special networks: the `fetch` the service is called with. */
|
||||
fetchImpl?: typeof fetch
|
||||
/**
|
||||
* The site's public host, as the service calls it back (`example.com`). Default: the host of
|
||||
* `serverURL`. Enrol the host the site really answers on (no redirect is followed).
|
||||
*/
|
||||
host?: string
|
||||
/** The kind of a message that carries no mark of its own; return undefined to keep the default (`system`). */
|
||||
kind?: (message: SendEmailOptions) => MailKind | undefined
|
||||
/**
|
||||
* The wait before the next attempt when the service names none, in ms, multiplied by the attempt's
|
||||
* number. Default 1000. The ten seconds of waiting in all are not changed by it. Mostly for tests.
|
||||
*/
|
||||
retryBackoffMs?: number
|
||||
/** The display name of outgoing mail. Default: the panel's "Sender name", else the site name. */
|
||||
senderName?: ((args: { payload: BasePayload }) => null | Promise<null | string | undefined> | string | undefined) | string
|
||||
/** One attempt of a send, in ms. Default 30 000 (a 10 MB attachment has to fit). */
|
||||
timeoutMs?: number
|
||||
/**
|
||||
* A token from elsewhere (a relay of your own, or a secret of your deployment). When set, the stored
|
||||
* token is not used and the site does not enrol.
|
||||
*/
|
||||
token?: (() => Promise<string | undefined> | string | undefined) | string
|
||||
/** Base address of the service. Default `https://webservices.intecion.net/mail`. A relay of your own speaks the same contract. */
|
||||
url?: string
|
||||
}
|
||||
|
||||
export type ResolvedRelayOptions = { ownUrl: boolean; url: string } & Omit<RelayOptions, 'url'>
|
||||
|
||||
type PluginMail = { graphDeprecationWarning?: boolean; relay?: false | RelayOptions }
|
||||
|
||||
/** What `iapl({ mail })` left in the config for the adapter (`config.custom.iapl.mail`). */
|
||||
export function pluginMailOptions(payload: Pick<BasePayload, 'config'>): PluginMail {
|
||||
return ((payload.config?.custom as { iapl?: { mail?: PluginMail } } | undefined)?.iapl?.mail ?? {})
|
||||
}
|
||||
|
||||
/**
|
||||
* The options in effect: the adapter's own `relay` argument over the plugin option. `null` = the relay
|
||||
* is switched off.
|
||||
*/
|
||||
export function resolveRelayOptions(payload: Pick<BasePayload, 'config'>, own?: false | RelayOptions): null | ResolvedRelayOptions {
|
||||
const fromPlugin = pluginMailOptions(payload).relay
|
||||
if (own === false || (own === undefined && fromPlugin === false)) {return null}
|
||||
const merged: RelayOptions = { ...(fromPlugin || {}), ...(own || {}) }
|
||||
const url = (merged.url ?? RELAY_BASE_URL).replace(/\/+$/, '')
|
||||
return { ...merged, ownUrl: url !== RELAY_BASE_URL, url }
|
||||
}
|
||||
|
||||
const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
|
||||
const PRIVATE_SUFFIXES = ['localhost', 'local', 'localdomain', 'internal', 'intranet', 'private', 'lan', 'home', 'corp', 'test', 'invalid', 'example', 'onion', 'arpa']
|
||||
|
||||
/** A public DNS name the service can call back: no address literal, no port, no single label, no private suffix. */
|
||||
export function isPublicHost(host: string): boolean {
|
||||
if (host.length < 4 || host.length > 253) {return false}
|
||||
const labels = host.split('.')
|
||||
if (labels.length < 2 || !labels.every((l) => LABEL.test(l)) || !/^[a-z]/.test(labels[labels.length - 1])) {return false}
|
||||
return !PRIVATE_SUFFIXES.some((s) => host === s || host.endsWith(`.${s}`))
|
||||
}
|
||||
|
||||
/**
|
||||
* The host this site enrols as: `relay.host`, else the host of `serverURL` — lowercase, punycode,
|
||||
* without scheme, path or the default port. Empty when neither is set.
|
||||
*/
|
||||
export function relayHost(payload: Pick<BasePayload, 'config'>, options: Pick<RelayOptions, 'host'>): string {
|
||||
const raw = (options.host ?? payload.config?.serverURL ?? '').trim()
|
||||
if (!raw) {return ''}
|
||||
try {
|
||||
return new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`).host.toLowerCase()
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import type { Endpoint, PayloadRequest } from 'payload'
|
||||
|
||||
import type { IntegrationStatus } from '../../integrations/status.js'
|
||||
import type { RelayOptions } from './options.js'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { serverText } from '../../integrations/texts.js'
|
||||
import { getSiteIntegrations } from '../../payload/index.js'
|
||||
import { graphAvailable, type MailTransport, resolveMailTransport } from '../mailAdapter.js'
|
||||
import { RELAY_SENDER_ADDRESS } from './adapter.js'
|
||||
import { RELAY_CONFIRM_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js'
|
||||
import { resolveRelayOptions } from './options.js'
|
||||
import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CODES, type RelayStatus, setRelayToken } from './session.js'
|
||||
|
||||
type Settings = {
|
||||
emailStatus?: IntegrationStatus | null
|
||||
emailTransport?: 'graph' | 'smtp' | null
|
||||
smtpFromAddress?: null | string
|
||||
smtpHost?: null | string
|
||||
smtpPassword?: null | string
|
||||
smtpUser?: null | string
|
||||
}
|
||||
|
||||
/** What the state block on the e-mail tab shows. Never a token, never a password. */
|
||||
export type MailPanelState = {
|
||||
/** The address the service calls this site back at. */
|
||||
confirmUrl?: string
|
||||
/** Enabled in the project (`mail.relay` is not `false`). */
|
||||
relay: ({ senderAddress: string } & RelayStatus) | null
|
||||
replyAddress: null | string
|
||||
transport: MailTransport
|
||||
}
|
||||
|
||||
type I18n = Parameters<typeof serverText>[0]
|
||||
|
||||
const json = (body: unknown, status = 200) => Response.json(body, { headers: { 'cache-control': 'no-store' }, status })
|
||||
|
||||
function refuse(req: PayloadRequest): null | Response {
|
||||
const i18n = req.i18n as I18n
|
||||
if (!req.user) {return json({ error: serverText(i18n, 'mailRelayLoggedOut'), ok: false }, 401)}
|
||||
if (!userMeetsRole(req, 'admin')) {return json({ error: serverText(i18n, 'mailRelayForbidden'), ok: false }, 403)}
|
||||
return null
|
||||
}
|
||||
|
||||
/** The transport in effect and the site's state with the service, for the panel and the doctor. */
|
||||
export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own: false | RelayOptions | undefined, { refresh = false }: { refresh?: boolean } = {}): Promise<MailPanelState> {
|
||||
const { payload } = req
|
||||
const settings = await getSiteIntegrations<Settings>(payload)
|
||||
const options = resolveRelayOptions(payload, own)
|
||||
const transport = resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(options) })
|
||||
const status = options ? await getRelayStatus(payload, options, { refresh: refresh && transport === 'relay' }) : null
|
||||
const api = payload.config.routes?.api ?? '/api'
|
||||
return {
|
||||
...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}),
|
||||
relay: status ? { ...status, senderAddress: status.senderAddress ?? RELAY_SENDER_ADDRESS } : null,
|
||||
replyAddress: typeof settings.smtpFromAddress === 'string' && settings.smtpFromAddress.trim() ? settings.smtpFromAddress.trim() : null,
|
||||
transport,
|
||||
}
|
||||
}
|
||||
|
||||
/** Why an enrolment was refused, in the admin's language. */
|
||||
export function enrolRefusalText(i18n: I18n, refusal: { code: string; message?: string; reason?: string }, state: Pick<MailPanelState, 'confirmUrl' | 'relay'>): string {
|
||||
switch (refusal.code) {
|
||||
case 'callback-failed':
|
||||
return serverText(i18n, 'mailRelayRefusedCallback', { reason: refusal.reason ?? '', url: state.confirmUrl ?? '' })
|
||||
case 'enrolment-closed':
|
||||
return serverText(i18n, 'mailRelayRefusedClosed')
|
||||
case 'host-not-allowed':
|
||||
return serverText(i18n, 'mailRelayRefusedHost', { host: state.relay?.host ?? '' })
|
||||
case LOCAL_CODES.noHost:
|
||||
return serverText(i18n, 'mailRelayRefusedNoHost')
|
||||
case 'site-suspended':
|
||||
return serverText(i18n, 'mailRelayStateSuspended')
|
||||
default:
|
||||
return serverText(i18n, 'mailRelayRefusedOther', { message: refusal.message ?? refusal.code })
|
||||
}
|
||||
}
|
||||
|
||||
async function answer(req: PayloadRequest, own: false | RelayOptions | undefined, extra: Record<string, unknown> = {}, refresh = false): Promise<Response> {
|
||||
const state = await mailPanelState(req, own, { refresh })
|
||||
const refusal = state.relay?.refusal
|
||||
return json({ ok: true, ...state, ...(refusal ? { refusalText: enrolRefusalText(req.i18n as I18n, refusal, state) } : {}), ...extra })
|
||||
}
|
||||
|
||||
/**
|
||||
* The three admin-only routes behind the state block on Site integrations → E-mail sending:
|
||||
* GET /api/iapl/mail-relay/status the transport in effect and the site's state (`?refresh=1` asks the service)
|
||||
* POST /api/iapl/mail-relay/connect enrol now — or, with `{ token }`, store a token Intecion issued by hand
|
||||
* POST /api/iapl/mail-relay/disconnect give the token up; nothing is sent through the service until "Connect again"
|
||||
* None of them ever answers with a token.
|
||||
*/
|
||||
export function relayPanelEndpoints(own?: false | RelayOptions): Endpoint[] {
|
||||
return [
|
||||
{
|
||||
handler: async (req) => {
|
||||
const refused = refuse(req)
|
||||
if (refused) {return refused}
|
||||
return answer(req, own, {}, new URL(req.url ?? 'http://x').searchParams.get('refresh') === '1')
|
||||
},
|
||||
method: 'get',
|
||||
path: RELAY_STATUS_PATH,
|
||||
},
|
||||
{
|
||||
handler: async (req) => {
|
||||
const refused = refuse(req)
|
||||
if (refused) {return refused}
|
||||
const i18n = req.i18n as I18n
|
||||
const options = resolveRelayOptions(req.payload, own)
|
||||
if (!options) {return json({ error: serverText(i18n, 'mailRelayOff'), ok: false }, 409)}
|
||||
let body: { token?: unknown } = {}
|
||||
try {
|
||||
body = ((await req.json?.()) ?? {}) as { token?: unknown }
|
||||
} catch {
|
||||
/* no body: plain "connect again" */
|
||||
}
|
||||
if (typeof body.token === 'string' && body.token.trim()) {
|
||||
try {
|
||||
await setRelayToken(req.payload, body.token.trim())
|
||||
} catch {
|
||||
return json({ error: serverText(i18n, 'mailRelayTokenInvalid'), ok: false }, 400)
|
||||
}
|
||||
return answer(req, own, { message: serverText(i18n, 'mailRelayConnected') }, true)
|
||||
}
|
||||
const result: EnrolResult = await enrolRelay(req.payload, options, { force: true })
|
||||
if (!result.ok) {
|
||||
const state = await mailPanelState(req, own)
|
||||
return json({ ...state, error: serverText(i18n, 'mailRelayConnectFailed', { reason: enrolRefusalText(i18n, result, state) }), ok: false }, 502)
|
||||
}
|
||||
return answer(req, own, { message: serverText(i18n, result.state === 'pending' ? 'mailRelayStatePending' : 'mailRelayConnected') }, true)
|
||||
},
|
||||
method: 'post',
|
||||
path: RELAY_CONNECT_PATH,
|
||||
},
|
||||
{
|
||||
handler: async (req) => {
|
||||
const refused = refuse(req)
|
||||
if (refused) {return refused}
|
||||
const options = resolveRelayOptions(req.payload, own)
|
||||
if (!options) {return json({ error: serverText(req.i18n as I18n, 'mailRelayOff'), ok: false }, 409)}
|
||||
await disconnectRelay(req.payload, options)
|
||||
return answer(req, own, { message: serverText(req.i18n as I18n, 'mailRelayDisconnected') })
|
||||
},
|
||||
method: 'post',
|
||||
path: RELAY_DISCONNECT_PATH,
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
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 { type MailKind, mailKindOf, takeMailContext } from './kinds.js'
|
||||
import { 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> {
|
||||
const marked = takeMailContext()
|
||||
const kind = mailKindOf(message) ?? marked?.kind ?? 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
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { randomBytes } from 'node:crypto'
|
||||
|
||||
import type { ResolvedRelayOptions } from './options.js'
|
||||
|
||||
import { PLUGIN_VERSION } from '../../../version.js'
|
||||
import { type RelayAnswer, type RelayRefusal, relayRequest } from './client.js'
|
||||
import { RELAY_DEFAULTS, RELAY_PRODUCT, type RelayStatusCode, relayStatusFor } from './constants.js'
|
||||
import { isPublicHost, relayHost } from './options.js'
|
||||
import {
|
||||
clearRelayStore,
|
||||
dropRelayCandidate,
|
||||
holdNonce,
|
||||
readRelayCandidate,
|
||||
readRelayStore,
|
||||
type RelaySiteState,
|
||||
type RelayStored,
|
||||
releaseNonce,
|
||||
sha256Hex,
|
||||
updateRelayStore,
|
||||
} from './store.js'
|
||||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
|
||||
const refusal = (code: string, message: string, extra: Partial<RelayRefusal> = {}): RelayRefusal => ({ code, message, noAnswer: false, ok: false, retryable: false, status: 0, ...extra })
|
||||
|
||||
/** Codes this client makes up for what never reached the service. */
|
||||
export const LOCAL_CODES = {
|
||||
disconnected: 'client-disconnected',
|
||||
noHost: 'client-no-host',
|
||||
noToken: 'client-no-token',
|
||||
} as const
|
||||
|
||||
export type EnrolResult =
|
||||
| { code: string; message: string; ok: false; reason?: string; retryable: boolean; status: RelayStatusCode }
|
||||
| { ok: true; state: RelaySiteState }
|
||||
|
||||
const enrolFailure = (answer: RelayRefusal): { ok: false } & EnrolResult => ({
|
||||
code: answer.code,
|
||||
message: answer.message,
|
||||
ok: false,
|
||||
...(answer.reason ? { reason: answer.reason } : {}),
|
||||
retryable: answer.retryable,
|
||||
status:
|
||||
answer.code === LOCAL_CODES.disconnected ? 'relay-disconnected'
|
||||
: answer.code === LOCAL_CODES.noHost || answer.code === LOCAL_CODES.noToken ? 'relay-refused'
|
||||
: relayStatusFor(answer.code, answer.retryable),
|
||||
})
|
||||
|
||||
const inFlight = new WeakMap<object, Promise<EnrolResult>>()
|
||||
|
||||
/**
|
||||
* Enrols this site with the service: makes a nonce, asks, and the service calls the site's confirm
|
||||
* route with the token before it answers (confirm.ts stores it beside the token in use). Only when the
|
||||
* service answers `200` does that token become the one in use. One enrolment at a time per process.
|
||||
*
|
||||
* `force`: also when an earlier enrolment was refused a moment ago, or the site was disconnected.
|
||||
*/
|
||||
export function enrolRelay(payload: BasePayload, options: ResolvedRelayOptions, { force = false }: { force?: boolean } = {}): Promise<EnrolResult> {
|
||||
const running = inFlight.get(payload)
|
||||
if (running) {return running}
|
||||
const run = enrolOnce(payload, options, force).finally(() => inFlight.delete(payload))
|
||||
inFlight.set(payload, run)
|
||||
return run
|
||||
}
|
||||
|
||||
async function enrolOnce(payload: BasePayload, options: ResolvedRelayOptions, force: boolean): Promise<EnrolResult> {
|
||||
const stored = await readRelayStore(payload)
|
||||
if (stored.disconnected && !force) {return enrolFailure(refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.'))}
|
||||
if (!force && stored.refusal && Date.parse(stored.refusal.until) > Date.now()) {
|
||||
return enrolFailure(refusal(stored.refusal.code, stored.refusal.message ?? stored.refusal.code, { reason: stored.refusal.reason }))
|
||||
}
|
||||
const host = relayHost(payload, options)
|
||||
if (!host) {
|
||||
return enrolFailure(refusal(LOCAL_CODES.noHost, 'The site does not know its public address: set serverURL in the Payload config, or mail.relay.host.'))
|
||||
}
|
||||
// Intecion's service calls back public DNS names only; a relay of one's own (or the local stand-in) decides itself.
|
||||
if (!options.ownUrl && !isPublicHost(host)) {
|
||||
return enrolFailure(refusal('host-not-allowed', `"${host}" is not a public host name, so the mail service cannot call this site back.`))
|
||||
}
|
||||
|
||||
let answer: RelayAnswer<{ state?: string }> | undefined
|
||||
let nonce = ''
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
nonce = randomBytes(32).toString('base64url')
|
||||
const nonceHash = await holdNonce(payload, nonce, RELAY_DEFAULTS.nonceTtlMs)
|
||||
answer = await relayRequest<{ state?: string }>({
|
||||
body: Buffer.from(JSON.stringify({ host, nonce, product: RELAY_PRODUCT, productVersion: PLUGIN_VERSION })),
|
||||
fetchImpl: options.fetchImpl,
|
||||
method: 'POST',
|
||||
path: '/v1/enrol',
|
||||
timeoutMs: RELAY_DEFAULTS.enrolTimeoutMs,
|
||||
url: options.url,
|
||||
})
|
||||
if (answer.ok) {
|
||||
const candidate = await readRelayCandidate(payload)
|
||||
if (!candidate || candidate.nonceHash !== nonceHash) {
|
||||
// The service says yes, but the token did not reach this store (another instance with a store of its own?).
|
||||
return enrolFailure(refusal('callback-failed', 'The mail service confirmed the enrolment, but its token did not reach this site\'s store.', { reason: 'store' }))
|
||||
}
|
||||
const state: RelaySiteState = answer.body.state === 'pending' || answer.body.state === 'suspended' ? answer.body.state : 'active'
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
...current,
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
host,
|
||||
refusal: null,
|
||||
source: 'enrolment',
|
||||
state,
|
||||
token: candidate.token,
|
||||
}))
|
||||
await dropRelayCandidate(payload)
|
||||
return { ok: true, state }
|
||||
}
|
||||
// Used or not, this nonce is over. A token the call-back did deliver stays beside the one in use.
|
||||
await releaseNonce(payload, nonce)
|
||||
if (answer.code !== 'enrolment-in-progress' || attempt > 0) {break}
|
||||
// Another process of this site is enrolling: wait, then look whether the token is here by now.
|
||||
await sleep(Math.min((answer.retryAfter ?? 2) * 1000, 5000))
|
||||
const now = await readRelayStore(payload)
|
||||
if ((now.token && now.token !== stored.token) || (await readRelayCandidate(payload))) {return { ok: true, state: now.state ?? 'active' }}
|
||||
}
|
||||
|
||||
const failed = answer as RelayRefusal
|
||||
if (!failed.retryable) {
|
||||
// Asking again at once would give the same answer (and a call-back that times out costs 8 seconds a time).
|
||||
const now = Date.now()
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
...current,
|
||||
refusal: { at: new Date(now).toISOString(), code: failed.code, message: failed.message, ...(failed.reason ? { reason: failed.reason } : {}), until: new Date(now + RELAY_DEFAULTS.refusalCooldownMs).toISOString() },
|
||||
...(failed.code === 'site-suspended' ? { state: 'suspended' as const } : {}),
|
||||
}))
|
||||
}
|
||||
return enrolFailure(failed)
|
||||
}
|
||||
|
||||
/** A token from the `token` option (a relay of one's own, a deployment secret), when the project set one. */
|
||||
async function optionToken(options: ResolvedRelayOptions): Promise<string | undefined> {
|
||||
if (options.token === undefined) {return undefined}
|
||||
const value = typeof options.token === 'function' ? await options.token() : options.token
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : undefined
|
||||
}
|
||||
|
||||
/** Kept across the retries of one message: a site enrols at most once per message. */
|
||||
export type TokenUse = { enrolled?: boolean; enrolment?: EnrolResult }
|
||||
|
||||
/**
|
||||
* Runs `call` with the site's token and deals with what the answer says about the token:
|
||||
* - no token yet → enrol first (when `enrol` is `'auto'`), then call;
|
||||
* - a token the call-back delivered but `/v1/enrol` never confirmed is tried first; on
|
||||
* `401 invalid-token` it is dropped and the earlier token is used again;
|
||||
* - `401 invalid-token` or `401 reverify` → enrol again once, then call again.
|
||||
* Any answer but `invalid-token` proves the token: a candidate then becomes the token in use.
|
||||
*/
|
||||
export async function withRelayToken<T>(
|
||||
payload: BasePayload,
|
||||
options: ResolvedRelayOptions,
|
||||
call: (token: string) => Promise<RelayAnswer<T>>,
|
||||
use: TokenUse = {},
|
||||
{ enrol = options.enrol !== 'manual' && options.enrol !== false, first = true }: { enrol?: boolean; first?: boolean } = {},
|
||||
): Promise<RelayAnswer<T>> {
|
||||
const fixed = await optionToken(options)
|
||||
if (fixed) {return call(fixed)}
|
||||
if (options.token !== undefined) {return refusal(LOCAL_CODES.noToken, 'mail.relay.token returned no token.')}
|
||||
|
||||
for (let round = 0; round < 4; round++) {
|
||||
const stored = await readRelayStore(payload)
|
||||
if (stored.disconnected) {return refusal(LOCAL_CODES.disconnected, 'The site was disconnected from the mail service in the panel.')}
|
||||
const candidate = await readRelayCandidate(payload)
|
||||
const token = candidate?.token ?? stored.token
|
||||
|
||||
const enrolNow = async (): Promise<null | RelayRefusal> => {
|
||||
if (!enrol || use.enrolled) {return refusal(LOCAL_CODES.noToken, 'The site is not connected to the mail service.')}
|
||||
use.enrolled = true
|
||||
use.enrolment = await enrolRelay(payload, options)
|
||||
return use.enrolment.ok ? null : refusal(use.enrolment.code, use.enrolment.message, { reason: use.enrolment.reason, retryable: use.enrolment.retryable })
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
// `first: false` (a status read): a site that never enrolled does not start because somebody looked.
|
||||
if (!first) {return refusal(LOCAL_CODES.noToken, 'The site is not connected to the mail service.')}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return failed}
|
||||
continue
|
||||
}
|
||||
const answer = await call(token)
|
||||
if (!answer.ok && answer.code === 'invalid-token') {
|
||||
if (candidate) {
|
||||
// The service never made this token valid: back to the earlier one.
|
||||
await dropRelayCandidate(payload)
|
||||
continue
|
||||
}
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment ? failed : answer}
|
||||
continue
|
||||
}
|
||||
if (candidate) {
|
||||
// Seen accepted: this is the token now.
|
||||
await updateRelayStore(payload, (current) => ({ ...current, enrolledAt: candidate.at, host: relayHost(payload, options) || current.host, source: 'enrolment', state: candidate.state, token: candidate.token }))
|
||||
await dropRelayCandidate(payload)
|
||||
}
|
||||
if (!answer.ok && answer.code === 'reverify') {
|
||||
const failed = await enrolNow()
|
||||
if (failed) {return use.enrolment ? failed : answer}
|
||||
continue
|
||||
}
|
||||
return answer
|
||||
}
|
||||
return refusal('invalid-token', 'The mail service keeps refusing this site\'s token.')
|
||||
}
|
||||
|
||||
type StatusBody = {
|
||||
limits?: NonNullable<RelayStored['service']>['limits']
|
||||
quota?: NonNullable<RelayStored['service']>['quota']
|
||||
sender?: { address?: string }
|
||||
service?: { contract?: string; name?: string }
|
||||
state?: RelaySiteState
|
||||
token?: { rotateAfter?: string }
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads `/v1/status` and keeps what it says (limits, quota, the sender address, when to rotate).
|
||||
* A site without a token is not enrolled by this; a site whose server address is new to the service
|
||||
* (`401 reverify`) enrols again, as on a send. Returns the stored entry as it is afterwards; `error`
|
||||
* when the service could not be asked.
|
||||
*/
|
||||
export async function refreshRelayStatus(payload: BasePayload, options: ResolvedRelayOptions): Promise<{ error?: RelayRefusal; stored: RelayStored }> {
|
||||
const answer = await withRelayToken<StatusBody>(
|
||||
payload,
|
||||
options,
|
||||
(token) => relayRequest<StatusBody>({ fetchImpl: options.fetchImpl, method: 'GET', path: '/v1/status', token, url: options.url }),
|
||||
{},
|
||||
{ first: false },
|
||||
)
|
||||
if (!answer.ok) {return { error: answer, stored: await readRelayStore(payload) }}
|
||||
const body = answer.body
|
||||
const stored = await updateRelayStore(payload, (current) => ({
|
||||
...current,
|
||||
service: {
|
||||
name: body.service?.name,
|
||||
contract: body.service?.contract,
|
||||
fetchedAt: new Date().toISOString(),
|
||||
limits: body.limits,
|
||||
quota: body.quota,
|
||||
rotateAfter: body.token?.rotateAfter,
|
||||
senderAddress: body.sender?.address,
|
||||
},
|
||||
...(body.state ? { state: body.state } : {}),
|
||||
}))
|
||||
return { stored }
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks for a new token when the service said the present one is due (`token.rotateAfter`, 90 days).
|
||||
* The new token is stored at once; the previous one works for 24 hours more, so other processes of
|
||||
* the site read the store again in time. `409 already-rotated` = another process won: nothing to do
|
||||
* when the store already holds a newer token, else the site enrols again on its next send.
|
||||
*/
|
||||
export async function rotateRelayToken(payload: BasePayload, options: ResolvedRelayOptions, { force = false }: { force?: boolean } = {}): Promise<'failed' | 'not-due' | 'rotated'> {
|
||||
const stored = await readRelayStore(payload)
|
||||
if (!stored.token || options.token !== undefined) {return 'not-due'}
|
||||
const due = stored.service?.rotateAfter ? Date.parse(stored.service.rotateAfter) : Number.NaN
|
||||
if (!force && !(due <= Date.now())) {return 'not-due'}
|
||||
const used = stored.token
|
||||
const answer = await relayRequest<{ token?: string }>({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/rotate', token: used, url: options.url })
|
||||
if (answer.ok && typeof answer.body.token === 'string' && answer.body.token) {
|
||||
const fresh = answer.body.token
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
...current,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
service: current.service ? { ...current.service, rotateAfter: undefined } : current.service,
|
||||
source: 'rotation',
|
||||
token: fresh,
|
||||
}))
|
||||
return 'rotated'
|
||||
}
|
||||
if (!answer.ok && answer.code === 'already-rotated') {
|
||||
const now = await readRelayStore(payload)
|
||||
// No newer token here: this one is on its way out. Forget it, so the next send enrols at once.
|
||||
if (now.token === used) {await updateRelayStore(payload, (current) => ({ ...current, service: null, token: undefined }))}
|
||||
return 'failed'
|
||||
}
|
||||
// Asked once; not again before the status has been read anew.
|
||||
await updateRelayStore(payload, (current) => ({ ...current, service: current.service ? { ...current.service, rotateAfter: undefined } : current.service }))
|
||||
return 'failed'
|
||||
}
|
||||
|
||||
/** Gives the token up on the service (every token of the site stops working) and forgets it here. */
|
||||
export async function disconnectRelay(payload: BasePayload, options: ResolvedRelayOptions): Promise<void> {
|
||||
const stored = await readRelayStore(payload)
|
||||
if (stored.token && options.token === undefined) {
|
||||
await relayRequest({ fetchImpl: options.fetchImpl, method: 'POST', path: '/v1/revoke', token: stored.token, url: options.url })
|
||||
}
|
||||
await clearRelayStore(payload, { disconnected: true })
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores a token Intecion issued by hand (a site the service cannot call back: behind a firewall, on
|
||||
* a private address). It is bound to the first server address that uses it.
|
||||
*/
|
||||
export async function setRelayToken(payload: BasePayload, token: string, options: { host?: string } = {}): Promise<void> {
|
||||
if (!/^ims_[\w-]{43}$/.test(token)) {throw new Error('Not a token of the mail service (ims_ and 43 characters).')}
|
||||
await dropRelayCandidate(payload)
|
||||
await updateRelayStore(payload, (current) => ({
|
||||
...current,
|
||||
disconnected: false,
|
||||
enrolledAt: new Date().toISOString(),
|
||||
...(options.host ? { host: options.host } : {}),
|
||||
refusal: null,
|
||||
service: null,
|
||||
source: 'manual',
|
||||
state: current.state ?? 'active',
|
||||
token,
|
||||
}))
|
||||
}
|
||||
|
||||
/** What the panel and the doctor may know: never the token. */
|
||||
export type RelayStatus = {
|
||||
connected: boolean
|
||||
disconnected: boolean
|
||||
host: string
|
||||
limits?: NonNullable<RelayStored['service']>['limits']
|
||||
nameReplaced?: { asked: string; at: string; used: string }
|
||||
quota?: NonNullable<RelayStored['service']>['quota']
|
||||
refusal?: { at: string; code: string; message?: string; reason?: string }
|
||||
senderAddress?: string
|
||||
serviceName?: string
|
||||
state?: RelaySiteState
|
||||
tokenSource?: 'enrolment' | 'manual' | 'option' | 'rotation'
|
||||
}
|
||||
|
||||
export function describeRelayStore(payload: BasePayload, options: ResolvedRelayOptions, stored: RelayStored): RelayStatus {
|
||||
const fromOption = options.token !== undefined
|
||||
return {
|
||||
connected: fromOption || Boolean(stored.token),
|
||||
disconnected: Boolean(stored.disconnected),
|
||||
host: relayHost(payload, options) || stored.host || '',
|
||||
...(stored.service?.limits ? { limits: stored.service.limits } : {}),
|
||||
...(stored.nameReplaced ? { nameReplaced: stored.nameReplaced } : {}),
|
||||
...(stored.service?.quota ? { quota: stored.service.quota } : {}),
|
||||
...(stored.refusal ? { refusal: { at: stored.refusal.at, code: stored.refusal.code, message: stored.refusal.message, reason: stored.refusal.reason } } : {}),
|
||||
...(stored.service?.senderAddress ? { senderAddress: stored.service.senderAddress } : {}),
|
||||
...(stored.service?.name ? { serviceName: stored.service.name } : {}),
|
||||
...(stored.state ? { state: stored.state } : {}),
|
||||
...(fromOption ? { tokenSource: 'option' as const } : stored.source ? { tokenSource: stored.source } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The site's state with the service, for a panel or a script. `refresh: true` asks the service
|
||||
* (`/v1/status`); otherwise what was last stored is returned and nothing leaves the server.
|
||||
*/
|
||||
export async function getRelayStatus(payload: BasePayload, options: ResolvedRelayOptions, { refresh = false }: { refresh?: boolean } = {}): Promise<{ error?: string } & RelayStatus> {
|
||||
if (!refresh) {return describeRelayStore(payload, options, await readRelayStore(payload))}
|
||||
const { error, stored } = await refreshRelayStatus(payload, options)
|
||||
return { ...describeRelayStore(payload, options, stored), ...(error && error.code !== LOCAL_CODES.noToken ? { error: error.code } : {}) }
|
||||
}
|
||||
|
||||
export { sha256Hex }
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { createHash, timingSafeEqual } from 'node:crypto'
|
||||
|
||||
import { RELAY_KV_KEY } from './constants.js'
|
||||
|
||||
/**
|
||||
* Where the site keeps its token: Payload's key-value store (`payload.kv`, the `payload-kv` collection
|
||||
* Payload itself adds — no field, no column, no migration of ours). That collection refuses every
|
||||
* operation through access control and is hidden in the panel, so the token cannot be read over REST
|
||||
* or GraphQL (test/mailRelayHttp.test.ts proves it). The token is never logged and never sent to a browser.
|
||||
*
|
||||
* Three entries:
|
||||
* - `iapl:mail-relay` the token in use, the site's state, what the service last reported;
|
||||
* - `iapl:mail-relay:candidate` a token the service delivered that has not been seen accepted yet;
|
||||
* - `iapl:mail-relay:nonce:<hash>` an enrolment this site started (5 minutes, single use).
|
||||
* The confirm route writes only the candidate and deletes only its nonce, so it can never overwrite a
|
||||
* working token.
|
||||
*/
|
||||
|
||||
export type RelaySiteState = 'active' | 'pending' | 'suspended'
|
||||
|
||||
export type RelayLimits = {
|
||||
maxAttachmentBytes?: number
|
||||
maxAttachments?: number
|
||||
maxBodyBytes?: number
|
||||
messagesPerDay?: number
|
||||
messagesPerHour?: number
|
||||
recipientsPerMessage?: number
|
||||
}
|
||||
|
||||
export type RelayStored = {
|
||||
/** An admin pressed "Disconnect": no send and no enrolment until "Connect again". */
|
||||
disconnected?: boolean
|
||||
enrolledAt?: string
|
||||
/** The host the token was issued for. */
|
||||
host?: string
|
||||
/** The last warning about the sender name: the name the mail left under instead. */
|
||||
nameReplaced?: { asked: string; at: string; used: string } | null
|
||||
/** The last refusal of an enrolment; no new enrolment by itself before `until`. */
|
||||
refusal?: { at: string; code: string; message?: string; reason?: string; until: string } | null
|
||||
/** What `/v1/status` last said. */
|
||||
service?: {
|
||||
contract?: string
|
||||
fetchedAt: string
|
||||
limits?: RelayLimits
|
||||
name?: string
|
||||
quota?: { day?: { limit: number; remaining: number }; hour?: { limit: number; remaining: number } }
|
||||
rotateAfter?: string
|
||||
senderAddress?: string
|
||||
} | null
|
||||
/** `enrolment`: by the call-back. `manual`: issued by Intecion and stored by hand. `rotation`: from /v1/rotate. */
|
||||
source?: 'enrolment' | 'manual' | 'rotation'
|
||||
state?: RelaySiteState
|
||||
token?: string
|
||||
v: 1
|
||||
}
|
||||
|
||||
export type RelayCandidate = { at: string; nonceHash: string; state: RelaySiteState; token: string }
|
||||
|
||||
type KV = { delete: (key: string) => Promise<void>; get: (key: string) => Promise<unknown>; set: (key: string, value: object) => Promise<void> }
|
||||
|
||||
/** Without `payload.kv` (a Payload older than the store, or a test double): this process only. */
|
||||
const memory = new WeakMap<object, Map<string, unknown>>()
|
||||
let warnedNoStore = false
|
||||
|
||||
function kvOf(payload: BasePayload): KV {
|
||||
const kv = (payload as { kv?: Partial<KV> }).kv
|
||||
if (typeof kv?.get === 'function' && typeof kv?.set === 'function' && typeof kv?.delete === 'function') {return kv as KV}
|
||||
if (!warnedNoStore) {
|
||||
warnedNoStore = true
|
||||
payload.logger?.warn?.('[iapl] mail service: this Payload has no key-value store (payload.kv); the token is kept in memory and is lost on restart.')
|
||||
}
|
||||
let map = memory.get(payload)
|
||||
if (!map) {
|
||||
map = new Map()
|
||||
memory.set(payload, map)
|
||||
}
|
||||
const held = map
|
||||
return {
|
||||
delete: (key) => Promise.resolve(void held.delete(key)),
|
||||
get: (key) => Promise.resolve(held.get(key) ?? null),
|
||||
set: (key, value) => Promise.resolve(void held.set(key, structuredClone(value))),
|
||||
}
|
||||
}
|
||||
|
||||
export const sha256Hex = (text: string) => createHash('sha256').update(text, 'utf8').digest('hex')
|
||||
|
||||
const CANDIDATE_KEY = `${RELAY_KV_KEY}:candidate`
|
||||
const nonceKey = (nonceHash: string) => `${RELAY_KV_KEY}:nonce:${nonceHash}`
|
||||
|
||||
export async function readRelayStore(payload: BasePayload): Promise<RelayStored> {
|
||||
const value = (await kvOf(payload).get(RELAY_KV_KEY)) as null | RelayStored
|
||||
return value && typeof value === 'object' ? { ...value, v: 1 } : { v: 1 }
|
||||
}
|
||||
|
||||
/** Reads the entry again, applies `change` and writes it: the smallest window for two writers. */
|
||||
export async function updateRelayStore(payload: BasePayload, change: (current: RelayStored) => RelayStored): Promise<RelayStored> {
|
||||
const next = change(await readRelayStore(payload))
|
||||
await kvOf(payload).set(RELAY_KV_KEY, next)
|
||||
return next
|
||||
}
|
||||
|
||||
/** Forgets the token and everything known about the service (keeps nothing). */
|
||||
export async function clearRelayStore(payload: BasePayload, keep: Pick<RelayStored, 'disconnected'> = {}): Promise<void> {
|
||||
const kv = kvOf(payload)
|
||||
await kv.delete(CANDIDATE_KEY)
|
||||
if (keep.disconnected) {await kv.set(RELAY_KV_KEY, { disconnected: true, v: 1 } satisfies RelayStored)}
|
||||
else {await kv.delete(RELAY_KV_KEY)}
|
||||
}
|
||||
|
||||
export async function readRelayCandidate(payload: BasePayload): Promise<null | RelayCandidate> {
|
||||
const value = (await kvOf(payload).get(CANDIDATE_KEY)) as null | RelayCandidate
|
||||
return value && typeof value.token === 'string' ? value : null
|
||||
}
|
||||
|
||||
export const writeRelayCandidate = (payload: BasePayload, candidate: RelayCandidate) => kvOf(payload).set(CANDIDATE_KEY, candidate)
|
||||
export const dropRelayCandidate = (payload: BasePayload) => kvOf(payload).delete(CANDIDATE_KEY)
|
||||
|
||||
/** Remembers that this site started an enrolment with `nonce`. Only its hash is stored. */
|
||||
export async function holdNonce(payload: BasePayload, nonce: string, ttlMs: number): Promise<string> {
|
||||
const nonceHash = sha256Hex(nonce)
|
||||
await kvOf(payload).set(nonceKey(nonceHash), { expiresAt: Date.now() + ttlMs, hash: nonceHash })
|
||||
return nonceHash
|
||||
}
|
||||
|
||||
/** True when this site holds `nonce` and it has not expired. Single use: the entry is gone afterwards. */
|
||||
export async function takeNonce(payload: BasePayload, nonce: string): Promise<boolean> {
|
||||
const kv = kvOf(payload)
|
||||
const nonceHash = sha256Hex(nonce)
|
||||
const key = nonceKey(nonceHash)
|
||||
// Found by the hash of the nonce (a look-up tells nothing about the nonce itself), then compared in constant time.
|
||||
const held = (await kv.get(key)) as { expiresAt?: number; hash?: string } | null
|
||||
if (!held || typeof held.hash !== 'string' || held.hash.length !== nonceHash.length) {return false}
|
||||
if (!timingSafeEqual(Buffer.from(held.hash), Buffer.from(nonceHash))) {return false}
|
||||
await kv.delete(key)
|
||||
return typeof held.expiresAt === 'number' && held.expiresAt > Date.now()
|
||||
}
|
||||
|
||||
export const releaseNonce = (payload: BasePayload, nonce: string) => kvOf(payload).delete(nonceKey(sha256Hex(nonce)))
|
||||
@@ -3,7 +3,8 @@ import type { Endpoint, PayloadRequest } from 'payload'
|
||||
import { addDataAndFileToRequest } from 'payload'
|
||||
|
||||
import { userMeetsRole } from '../../access/predicates.js'
|
||||
import { serverText } from '../../integrations/texts.js'
|
||||
import { serverText, STATUS_CODE_TEXTS } from '../../integrations/texts.js'
|
||||
import { withMailKind } from '../relay/kinds.js'
|
||||
|
||||
/**
|
||||
* Custom endpoint: send a test email to a given address through whatever
|
||||
@@ -64,7 +65,7 @@ export const testEmailEndpoint: Endpoint = {
|
||||
const text = site ? serverText(i18n, 'testEmailBody', { site }) : serverText(i18n, 'testEmailBodyGeneric')
|
||||
|
||||
try {
|
||||
const info = await req.payload.sendEmail({
|
||||
const info = await req.payload.sendEmail(withMailKind({
|
||||
...(attachmentMB
|
||||
? { attachments: [{ content: Buffer.alloc(attachmentMB * 1024 * 1024, 'IAPL test file\n'), contentType: 'text/plain', filename: `test-${attachmentMB}MB.txt` }] }
|
||||
: {}),
|
||||
@@ -72,7 +73,7 @@ export const testEmailEndpoint: Endpoint = {
|
||||
subject,
|
||||
text,
|
||||
to,
|
||||
})
|
||||
}, 'test'))
|
||||
|
||||
// Payload's sendEmail resolves with the adapter's result. Our adapters
|
||||
// return { sent: boolean, error?: string, code?: string }; nodemailer
|
||||
@@ -83,16 +84,28 @@ export const testEmailEndpoint: Endpoint = {
|
||||
: true
|
||||
|
||||
if (!sent) {
|
||||
const failed = info as { code?: string; detail?: string; error?: string }
|
||||
const failed = info as { code?: string; confirmed?: boolean; detail?: string; error?: string }
|
||||
req.payload.logger.error(`[iapl] Test email not sent: ${failed?.detail ?? failed?.error ?? 'unknown reason'}`)
|
||||
const relayText = failed?.code ? STATUS_CODE_TEXTS[failed.code] : undefined
|
||||
const error =
|
||||
failed?.code === 'not-configured'
|
||||
? serverText(i18n, 'testEmailNotConfigured')
|
||||
: serverText(i18n, 'testEmailFailed')
|
||||
return Response.json({ error, ok: false }, { status: 502 })
|
||||
: failed?.confirmed === false
|
||||
? serverText(i18n, 'testEmailNotConfirmed')
|
||||
// the mail service's refusal in the admin's language (waiting for approval, a limit, too large …)
|
||||
: failed?.code?.startsWith('relay-') && relayText
|
||||
? serverText(i18n, relayText)
|
||||
: serverText(i18n, 'testEmailFailed')
|
||||
return Response.json({ code: failed?.code, error, ok: false }, { status: 502 })
|
||||
}
|
||||
|
||||
return Response.json({ message: serverText(i18n, 'testEmailSent', { to }), ok: true })
|
||||
// The answer names the transport that carried it.
|
||||
const sentBy = info as { senderName?: string; transport?: string } | null
|
||||
const message =
|
||||
sentBy?.transport === 'relay' ? serverText(i18n, 'testEmailSentRelay', { name: sentBy.senderName ?? '', to })
|
||||
: sentBy?.transport === 'smtp' ? serverText(i18n, 'testEmailSentSmtp', { to })
|
||||
: serverText(i18n, 'testEmailSent', { to })
|
||||
return Response.json({ message, ok: true, ...(sentBy?.transport ? { transport: sentBy.transport } : {}) })
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err)
|
||||
req.payload.logger.error(`[iapl] Test email failed: ${message}`)
|
||||
|
||||
Reference in New Issue
Block a user