Mail relay: HTTP tests on a running Payload, account mail marked by recipient, panel wording, doctor rules tested

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 20:40:17 +01:00
co-authored by Claude Fable 5.2
parent ea9703f8e3
commit 533f571d4d
12 changed files with 532 additions and 111 deletions
+1 -2
View File
@@ -230,8 +230,7 @@ export const mailAdapter =
}
: { state: 'ok' },
)
// which transport carried it — the test e-mail says so in the panel
return result && typeof result === 'object' ? { ...result, transport: viaGraph ? 'graph' : 'smtp' } : result
return result
},
}
}
+16 -8
View File
@@ -1,31 +1,39 @@
import type { CollectionConfig } from 'payload'
import { clientIp } from '../../shared/rateLimit.js'
import { markNextMail } from './kinds.js'
import { dropExpectedMail, expectMailTo } 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.
* collection says it for the message about to go to that address (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 it; nothing else changes.
*
* Marks `forgotPassword` always, and `create` only where the collection verifies e-mail addresses.
* A collection that logs in by user name alone names no address in the request: its mail is `system`.
*/
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 } }) => {
const mark = ((args: { args?: { data?: { email?: unknown }; req?: { headers?: Headers } }; operation: string; req?: { headers?: Headers } }) => {
if (args.operation === 'forgotPassword' || (verifies && args.operation === 'create')) {
const email = args.args?.data?.email
const headers = args.req?.headers ?? args.args?.req?.headers
markNextMail('account', { visitor: headers ? clientIp(headers) || undefined : undefined })
if (typeof email === 'string' && email.trim()) {expectMailTo(email, '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] } }
// The operation ended without a mail to that address (no such account, Payload's own interval between
// requests): what was expected must not stick to the next, unrelated message to it.
const done = ((args: { args?: { data?: { email?: unknown } }; operation: string; result?: unknown }) => {
const email = args.args?.data?.email
if (typeof email === 'string' && (args.operation === 'forgotPassword' || (verifies && args.operation === 'create'))) {dropExpectedMail(email)}
return args.result
}) as unknown as NonNullable<NonNullable<CollectionConfig['hooks']>['afterOperation']>[number]
return { ...collection, hooks: { ...collection.hooks, afterOperation: [...(collection.hooks?.afterOperation ?? []), done], beforeOperation: [...hooks, mark] } }
}
+2 -2
View File
@@ -4,7 +4,7 @@ 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 { RELAY_DEFAULTS } from './constants.js'
import { resolveRelayOptions } from './options.js'
import { type RelaySendResult, sendThroughRelay } from './send.js'
import { refreshRelayStatus } from './session.js'
@@ -49,7 +49,7 @@ export async function sendRelayWithPanel(payload: BasePayload, options: Resolved
payload,
'emailStatus',
settings.emailStatus,
result.sent ? { state: 'ok' } : { code: result.code, message: `${RELAY_SERVICE_NAME}: ${firstLine(result.detail)}`, state: 'degraded' },
result.sent ? { state: 'ok' } : { code: result.code, message: `Mail service: ${firstLine(result.detail)}`, state: 'degraded' },
)
return result
}
+1 -1
View File
@@ -20,7 +20,7 @@ export {
relayStatusFor,
} from './constants.js'
export type { RelayStatusCode } from './constants.js'
export { MAIL_KIND, MAIL_KINDS, mailKindOf, markNextMail, runWithMailKind, withMailKind } from './kinds.js'
export { expectMailTo, MAIL_KIND, MAIL_KINDS, mailKindOf, 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'
+46 -15
View File
@@ -31,28 +31,59 @@ export function mailKindOf(message: unknown): MailKind | 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.
* the operation's hook says that a message to this address is about to be sent and what it is, and the
* transport takes that once. By address, not by async context: Payload awaits other hooks before and
* after ours, and a context set inside one of them does not reach the code that sends the mail.
*/
type MailContext = { kind: MailKind; sticky?: boolean; taken?: boolean; visitor?: string }
const context = new AsyncLocalStorage<MailContext>()
type Expected = { kind: MailKind; until: number; visitor?: string }
const expected = new Map<string, Expected>()
// The mail follows its operation's hook within the same request. Short, because Payload can end the
// operation without sending (its own interval between two requests for one account) and without
// running the hook that would take the expectation back.
const EXPECTED_TTL_MS = 10_000
/**
* 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.
* Says that the next message to `address` (within ten seconds, in this process) is of `kind`.
* `visitor`: the address of whoever asked for it, for the limit on account mail (`mail.relay.accountMail`).
*/
export function markNextMail(kind: MailKind, extra: { visitor?: string } = {}): void {
context.enterWith({ kind, ...extra })
export function expectMailTo(address: string, kind: MailKind, extra: { visitor?: string } = {}): void {
const key = address.trim().toLowerCase()
if (!key || !isKind(kind)) {return}
const now = Date.now()
if (expected.size > 1000) {
for (const [k, entry] of expected) {
if (entry.until <= now) {expected.delete(k)}
}
}
expected.set(key, { kind, until: now + EXPECTED_TTL_MS, ...(extra.visitor ? { visitor: extra.visitor } : {}) })
}
/** Runs `fn` with every message sent inside it marked as `kind` (a message's own mark still wins). */
/** What was said about a message to exactly this one recipient; used up by this call. */
export function takeExpectedMail(recipients: string[]): { kind: MailKind; visitor?: string } | undefined {
if (recipients.length !== 1) {return undefined}
const key = recipients[0].toLowerCase()
const entry = expected.get(key)
if (!entry) {return undefined}
expected.delete(key)
return entry.until > Date.now() ? { kind: entry.kind, visitor: entry.visitor } : undefined
}
/** The operation is over and sent nothing to `address`: nothing is expected any more. */
export function dropExpectedMail(address: string): void {
expected.delete(address.trim().toLowerCase())
}
const context = new AsyncLocalStorage<{ kind: MailKind }>()
/**
* Runs `fn` with every message sent inside it marked as `kind` (a message's own mark still wins):
* await runWithMailKind('account', () => payload.sendEmail({ to, subject, html }))
*/
export function runWithMailKind<T>(kind: MailKind, fn: () => T): T {
return context.run({ kind, sticky: true }, fn)
return context.run({ kind }, 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 }
/** The kind of the surrounding `runWithMailKind`, if any. */
export function currentMailKind(): MailKind | undefined {
return context.getStore()?.kind
}
+7 -4
View File
@@ -7,8 +7,8 @@ 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 { currentMailKind, type MailKind, mailKindOf, takeExpectedMail } from './kinds.js'
import { bareAddresses, buildRelayMessage, type RelaySendRequest } from './message.js'
import { LOCAL_CODES, refreshRelayStatus, rotateRelayToken, type TokenUse, withRelayToken } from './session.js'
import { readRelayStore, sha256Hex, updateRelayStore } from './store.js'
@@ -113,8 +113,11 @@ export type RelaySendContext = {
* `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'
// What the message is: its own mark; else what an auth operation said about a message to this address
// (Payload's own account mail); else the surrounding runWithMailKind; else the project's rule; else unknown.
const own = mailKindOf(message)
const marked = own ? undefined : takeExpectedMail(bareAddresses((message as { to?: unknown }).to).addresses)
const kind = own ?? marked?.kind ?? currentMailKind() ?? options.kind?.(message) ?? 'system'
const built = buildRelayMessage(message, { kind, replyTo: context.replyTo, senderName: context.senderName })
if (!built.ok) {return failure('relay-error', 'client-invalid-message', built.problem)}
+7 -3
View File
@@ -5,6 +5,7 @@ import { addDataAndFileToRequest } from 'payload'
import { userMeetsRole } from '../../access/predicates.js'
import { serverText, STATUS_CODE_TEXTS } from '../../integrations/texts.js'
import { withMailKind } from '../relay/kinds.js'
import { mailPanelState } from '../relay/panel.js'
/**
* Custom endpoint: send a test email to a given address through whatever
@@ -64,6 +65,7 @@ export const testEmailEndpoint: Endpoint = {
const subject = site ? serverText(i18n, 'testEmailSubject', { site }) : serverText(i18n, 'testEmailSubjectGeneric')
const text = site ? serverText(i18n, 'testEmailBody', { site }) : serverText(i18n, 'testEmailBodyGeneric')
const transportBefore = await mailPanelState(req, undefined).then((state) => state.transport).catch(() => null)
try {
const info = await req.payload.sendEmail(withMailKind({
...(attachmentMB
@@ -99,13 +101,15 @@ export const testEmailEndpoint: Endpoint = {
return Response.json({ code: failed?.code, error, ok: false }, { status: 502 })
}
// The answer names the transport that carried it.
// The answer names the transport that carried it: the mail service says so itself; SMTP is told by the
// settings (the dispatcher's results for SMTP and Graph are what they were before 1.17.0).
const sentBy = info as { senderName?: string; transport?: string } | null
const smtp = !sentBy?.transport && req.payload.email?.name === 'ipal-mail-dispatcher' && transportBefore === 'smtp'
const message =
sentBy?.transport === 'relay' ? serverText(i18n, 'testEmailSentRelay', { name: sentBy.senderName ?? '', to })
: sentBy?.transport === 'smtp' ? serverText(i18n, 'testEmailSentSmtp', { to })
: smtp ? serverText(i18n, 'testEmailSentSmtp', { to })
: serverText(i18n, 'testEmailSent', { to })
return Response.json({ message, ok: true, ...(sentBy?.transport ? { transport: sentBy.transport } : {}) })
return Response.json({ message, ok: true, ...(sentBy?.transport === 'relay' ? { transport: 'relay' } : smtp ? { transport: 'smtp' } : {}) })
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[iapl] Test email failed: ${message}`)