Account mail after commit: matched by its token, not by the address (P-4)

holdAccountMailFor bound the next message to an address to whichever
request held it: two resets for one account at once could lose the first
one's mail on the second's rollback, and a form's mail to that address was
deferred to the reset's transaction.

Payload calls generateEmailSubject({ req, token, user }) right before it
sends the reset or verify mail, and the mail carries that token. The plugin
now wraps that function on every auth collection (a project's own one is
kept, Payload's subject otherwise) and holds the token for the request's
transaction; mailAdapter defers only a message to that account alone whose
body contains a held token. An AsyncLocalStorage mark set in a
beforeOperation hook was not used: Payload awaits the hook, and a mark set
inside it does not reach the send (relay/kinds.ts says the same).

Building blocks renamed with it: holdAccountMail(token, address, req),
releaseAccountMail(token). Both review rows are tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 01:36:17 +01:00
co-authored by Claude Opus 5.5
parent 4efadb21d5
commit 919953e65e
8 changed files with 151 additions and 67 deletions
+1 -1
View File
@@ -209,7 +209,7 @@ export type { SearchResult } from './modules/content/index.js'
// Postgres: connections kept free of transactions, work run after a commit (docs/deployment.md "Postgres: the connection pool").
export { afterCommit, defaultConnectionReserve, inWatchedTransaction, poolSize, RESERVE_ESCAPE_MS, reserveConnections, transactionsBusy, transactionWatchState, watchTransactions } from './modules/database/transactions.js'
// Files on panel forms (forms.attachments): checked, e-mailed, never stored.
export { holdAccountMailFor, releaseAccountMailFor, sendAccountMailAfterCommit, withAccountMailAfterCommit } from './modules/email/accountMailAfterCommit.js'
export { holdAccountMail, releaseAccountMail, sendAccountMailAfterCommit, withAccountMailAfterCommit } from './modules/email/accountMailAfterCommit.js'
export { mailAttachmentLimit } from './modules/email/attachmentLimit.js'
export { graphAdapter } from './modules/email/graphAdapter.js'
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
+69 -56
View File
@@ -10,84 +10,97 @@ import { bareAddresses } from './relay/message.js'
* many such requests at once every place for a transaction is taken by requests that only wait for mail
* (docs/deployment.md §4.3a).
*
* This hook on an auth collection says, when such an operation starts inside a watched transaction, that the
* next message to that address belongs to it; `mailAdapter()` then sends that message right AFTER the
* transaction commits — still inside the same request, so the request ends when the mail is out, as before —
* and drops it when the transaction is rolled back (no token was stored, the link would not work).
* By address, like the account-mail mark (relay/kinds.ts): Payload passes nothing else to the adapter.
* Without a transaction (MongoDB without a replica set, SQLite) nothing changes.
* Payload calls the collection's `generateEmailSubject({ req, token, user })` right before it sends that mail,
* and the mail carries the same token (in its link). The wrapper below holds the token for the transaction of
* that `req`; `mailAdapter()` sends the message whose body contains a held token right AFTER that transaction
* commits — still inside the same request, so the request ends when the mail is out, as before — and drops it
* when the transaction is rolled back (the token was not stored, the link would not work).
* Matched by the token (and the account's address as a second check), never by the address alone: two
* requests for one account at once, or a form's mail to the same address, are each their own message.
* A project's own `generateEmailSubject` is kept and called; without one the subject is Payload's own.
* Without a transaction (MongoDB without a replica set, SQLite) nothing changes; a message without a held
* token (a project's own e-mail template that leaves the token out) is sent at once, as before.
* `iapl({ mail: { accountMailAfterCommit: false } })` = inside the transaction, as before.
*/
const MARK = Symbol.for('iapl.accountMailAfterCommit')
type Pending = { req: PayloadRequest; until: number }
const pending = new Map<string, Pending>()
// The mail follows its operation's hook within the same request.
type Held = { address: string; req: PayloadRequest; until: number }
const held = new Map<string, Held>()
// Payload sends the mail right after it composed the subject, within the same request.
const TTL_MS = 30_000
// Payload's tokens are 40 hexadecimal characters; a shorter one could be found in an unrelated message.
const MIN_TOKEN = 16
const keyOf = (address: string) => address.trim().toLowerCase()
/** The message to `address` belongs to the transaction of `req` (when there is one to wait for). */
export function holdAccountMailFor(address: string, req: PayloadRequest): void {
const key = keyOf(address)
if (!key || !inWatchedTransaction(req)) {return}
/** The message that carries `token` (to `address`) belongs to the transaction of `req`, when there is one to wait for. */
export function holdAccountMail(token: string, address: string, req: PayloadRequest): void {
if (typeof token !== 'string' || token.length < MIN_TOKEN || !inWatchedTransaction(req)) {return}
const now = Date.now()
if (pending.size > 1000) {
for (const [k, entry] of pending) {
if (entry.until <= now) {pending.delete(k)}
}
for (const [k, entry] of held) {
if (entry.until <= now) {held.delete(k)}
}
pending.set(key, { req, until: now + TTL_MS })
held.set(token, { address: keyOf(address), req, until: now + TTL_MS })
}
/** The operation ended without a mail to `address`: nothing is held for it any more. */
export function releaseAccountMailFor(address: string): void {
pending.delete(keyOf(address))
/** Nothing is held for `token` any more. */
export function releaseAccountMail(token: string): void {
held.delete(token)
}
const bodyOf = (message: { html?: unknown; text?: unknown }) => `${typeof message.html === 'string' ? message.html : ''}\n${typeof message.text === 'string' ? message.text : ''}`
/**
* For a transport: when this message is the account mail of an operation whose transaction is still open,
* schedules `send` for right after its commit and returns true (the caller sends nothing now). The kind the
* relay transport was told for the address (`account`, with the visitor) is carried over to that send.
* For a transport: when this message carries the token of an account operation whose transaction is still
* open, and goes to that account's address alone, schedules `send` for right after the commit and returns
* true (the caller sends nothing now). The kind the relay transport was told for the address (`account`, with
* the visitor) is carried over to that send.
*/
export function sendAccountMailAfterCommit(message: { to?: unknown }, send: () => Promise<unknown>): boolean {
export function sendAccountMailAfterCommit(message: { html?: unknown; text?: unknown; to?: unknown }, send: () => Promise<unknown>): boolean {
if (!held.size) {return false}
const { addresses } = bareAddresses(message.to)
if (addresses.length !== 1) {return false}
const key = keyOf(addresses[0])
const entry = pending.get(key)
if (!entry) {return false}
pending.delete(key)
if (entry.until <= Date.now()) {return false}
const expected = takeExpectedMail(addresses)
return afterCommit(entry.req, async () => {
if (expected) {expectMailTo(addresses[0], expected.kind, { visitor: expected.visitor })}
await send()
})
const body = bodyOf(message)
const now = Date.now()
for (const [token, entry] of held) {
if (entry.until <= now || entry.address !== keyOf(addresses[0]) || !body.includes(token)) {continue}
held.delete(token)
const expected = takeExpectedMail(addresses)
return afterCommit(entry.req, async () => {
if (expected) {expectMailTo(addresses[0], expected.kind, { visitor: expected.visitor })}
await send()
})
}
return false
}
type OperationArgs = { args?: { data?: { email?: unknown }; req?: PayloadRequest }; operation: string; req?: PayloadRequest; result?: unknown }
type SubjectArgs = { req: PayloadRequest; token: string; user: { email?: unknown } }
type SubjectFn = ((args: SubjectArgs) => Promise<string> | string) & { [MARK]?: boolean }
function holdingSubject(own: SubjectFn | undefined, fallback: string): SubjectFn {
if (own?.[MARK]) {return own}
const fn: SubjectFn = async (args) => {
const subject = own ? await own(args) : args.req.t(fallback as never)
if (typeof args.user?.email === 'string') {holdAccountMail(args.token, args.user.email, args.req)}
return subject
}
fn[MARK] = true
return fn
}
/**
* Adds the hook to an auth collection (idempotent): `forgotPassword` always, `create` where the collection
* verifies e-mail addresses.
* Wraps an auth collection's `forgotPassword.generateEmailSubject`, and `verify.generateEmailSubject` where it
* verifies e-mail addresses (idempotent). Payload's own subjects stay when the collection has none.
*/
export function withAccountMailAfterCommit(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)
const applies = (operation: string) => operation === 'forgotPassword' || (verifies && operation === 'create')
const hold = ((args: OperationArgs) => {
const email = args.args?.data?.email
const req = args.req ?? args.args?.req
if (applies(args.operation) && typeof email === 'string' && req) {holdAccountMailFor(email, req)}
return args.args
}) as unknown as { [MARK]?: boolean } & NonNullable<NonNullable<CollectionConfig['hooks']>['beforeOperation']>[number]
hold[MARK] = true
// Ran without a mail (no such account, Payload's interval between two requests): forget the address.
const done = ((args: OperationArgs) => {
const email = args.args?.data?.email
if (applies(args.operation) && typeof email === 'string') {releaseAccountMailFor(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, hold] } }
const auth = collection.auth
if (!auth) {return collection}
const own = typeof auth === 'object' ? auth : {}
if (own.disableLocalStrategy === true) {return collection}
const forgotPassword = { ...own.forgotPassword, generateEmailSubject: holdingSubject(own.forgotPassword?.generateEmailSubject as SubjectFn | undefined, 'authentication:resetYourPassword') }
const verify =
own.verify === true || (own.verify && typeof own.verify === 'object')
? { ...(typeof own.verify === 'object' ? own.verify : {}), generateEmailSubject: holdingSubject((typeof own.verify === 'object' ? own.verify.generateEmailSubject : undefined) as SubjectFn | undefined, 'authentication:verifyYourEmail') }
: own.verify
return { ...collection, auth: { ...own, forgotPassword: forgotPassword as never, ...(verify !== undefined ? { verify: verify as never } : {}) } }
}