diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index fb3df2b..ec963e4 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -146,10 +146,11 @@ once there are more than 20. `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState`, `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` ([deployment.md](./deployment.md) §4.3a, with the measured table). - **Payload's "forgot password" and "verify your e-mail" go out after their transaction commits** when sent through - `mailAdapter()` (`mail.accountMailAfterCommit`, default on; same request, nothing sent on a rollback). With the mail + `mailAdapter()` (`mail.accountMailAfterCommit`, default on; same request, nothing sent on a rollback). The message is + matched to its request by its token (Payload's `generateEmailSubject` is wrapped; a project's own one is kept). With the mail service hanging, 30 resets and 30 submissions at once finish in about one send budget (11 s) instead of 43.5 s. - Building blocks `withAccountMailAfterCommit`, `sendAccountMailAfterCommit`, `holdAccountMailFor`, - `releaseAccountMailFor`. + Building blocks `withAccountMailAfterCommit`, `sendAccountMailAfterCommit`, `holdAccountMail`, + `releaseAccountMail`. - **Form e-mails go out after the submission's transaction commits** — same request, same answer to the visitor (a file that could not be sent is still reported). A submission rolled back by a later hook now sends nothing; a send that fails after the commit leaves the submission stored (as a failed e-mail always did). Sites without diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index 5ea1e04..fdd3883 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -1247,7 +1247,7 @@ add missing hosts with flags / `extra`; (3) change `mode` to `'enforce'` in both | Every message says what it is (form notification, form confirmation, account, test, system) | — (other transports ignore the mark) | `withMailKind`, `runWithMailKind`, `expectMailTo`, `mail.relay.kind`, `buildFormMailKindHook` | | Microsoft Graph as transport: deprecated, one warning per start, removed in 2.0 | `mail: { graphDeprecationWarning: false }` (the warning only) | move off it: email.md "Moving off Microsoft Graph" | | Postgres: a fifth of the pool (at least 2) stays free of transactions — at most `pool size − reserve` open at once, the next waits; a transaction begun inside another one (a hook without `req`) takes no place and goes at once, but never the last connection. Without it ten form submissions or "forgot password" requests at once stopped the site | `connectionReserve: false` | `connectionReserve: `; `reserveConnections(payload, n)` in your own `onInit` (without `iapl()`); `watchTransactions`, `afterCommit`, `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (`{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS` (deployment.md §4.3a) | -| Payload's "forgot password" / "verify your e-mail" through `mailAdapter()` go out right after their transaction commits (same request); a rolled-back operation sends nothing | `mail: { accountMailAfterCommit: false }` | your own adapter: `sendAccountMailAfterCommit(message, send)`; `withAccountMailAfterCommit(collection)`, `holdAccountMailFor`, `releaseAccountMailFor` (email.md "Payload system mail") | +| Payload's "forgot password" / "verify your e-mail" through `mailAdapter()` go out right after their transaction commits (same request); a rolled-back operation sends nothing | `mail: { accountMailAfterCommit: false }` | your own adapter: `sendAccountMailAfterCommit(message, send)`; `withAccountMailAfterCommit(collection)`, `holdAccountMail`, `releaseAccountMail` (email.md "Payload system mail") | | Form e-mails go out right after the submission's transaction commits (same request, same answer); a rolled-back submission sends nothing; a send that fails after the commit leaves the submission stored. No transactions (MongoDB without a replica set, SQLite): at once, as before | `forms: { emailsInTransaction: true }` | `sendAfterCommit(prepare, deliver)`, `sendFormEmails(req, emails)`, `afterCommit(req, fn)` (forms.md "When e-mails go out") | | SMTP time-outs: 10 s to connect, 30 s greeting, 60 s silence | — | `mailAdapter({ smtp: { timeouts: { connectionMs, greetingMs, socketMs } } })`, `panelSmtpAdapter({ timeouts })`; `SMTP_TIMEOUT_DEFAULTS`, type `SmtpTimeouts` (email.md "SMTP") | diff --git a/docs/deployment.md b/docs/deployment.md index 4fdff7e..378f7e1 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -398,9 +398,10 @@ Without `iapl()` (building blocks only): `onInit: (payload) => { reserveConnecti Building blocks: `reserveConnections`, `watchTransactions`, `afterCommit` (run work right after a transaction commits), `inWatchedTransaction`, `transactionsBusy`, `transactionWatchState` (for a health or debug route: `{ active, nested, waiting, reserve }`), `poolSize`, `defaultConnectionReserve`, `RESERVE_ESCAPE_MS`; for account mail -`withAccountMailAfterCommit(collection)` (the hook the plugin puts on every auth collection), -`sendAccountMailAfterCommit(message, send)` (what an e-mail adapter of your own calls first), `holdAccountMailFor`, -`releaseAccountMailFor`. Still true: a hook that writes without `req` is a transaction of its own — it is not rolled +`withAccountMailAfterCommit(collection)` (what the plugin does to every auth collection: wraps its +`generateEmailSubject`, which Payload calls with the request and the token right before the send), +`sendAccountMailAfterCommit(message, send)` (what an e-mail adapter of your own calls first), `holdAccountMail`, +`releaseAccountMail`. Still true: a hook that writes without `req` is a transaction of its own — it is not rolled back with its caller's. Pass `req`. **Check** (staging, Postgres): send 30 submissions of a form at once (or 30 "forgot password" requests for different diff --git a/docs/email.md b/docs/email.md index 3cc2885..fcf7b3c 100644 --- a/docs/email.md +++ b/docs/email.md @@ -498,7 +498,10 @@ Password reset and e-mail verification go through Payload's built-in mechanism ( account mail ("What a message is"). Payload sends them inside the operation's database transaction; `mailAdapter()` sends them right **after** it commits instead (still in the same request; nothing when it is rolled back), so a slow mail server holds no database connection — `mail: { accountMailAfterCommit: false }` keeps them inside -([deployment.md](./deployment.md) §4.3a). An e-mail adapter of your own does the same by calling +([deployment.md](./deployment.md) §4.3a). The message is matched to its request by the token it carries (and the +account's address), never by the address alone: a form's mail to the same address goes out as usual. A project's own +`forgotPassword.generateEmailSubject` / `verify.generateEmailSubject` is kept; an own `generateEmailHTML` must put the +token in the body (any working reset link does), or that mail is sent inside the transaction as before. An e-mail adapter of your own does the same by calling `sendAccountMailAfterCommit(message, () => send(message))` first. ## Masking secrets in the panel (MaskedField) diff --git a/src/index.ts b/src/index.ts index 79e6df4..d786451 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/modules/email/accountMailAfterCommit.ts b/src/modules/email/accountMailAfterCommit.ts index 75d68b5..6c77a49 100644 --- a/src/modules/email/accountMailAfterCommit.ts +++ b/src/modules/email/accountMailAfterCommit.ts @@ -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() -// The mail follows its operation's hook within the same request. +type Held = { address: string; req: PayloadRequest; until: number } +const held = new Map() +// 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): boolean { +export function sendAccountMailAfterCommit(message: { html?: unknown; text?: unknown; to?: unknown }, send: () => Promise): 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) & { [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['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['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 } : {}) } } } diff --git a/test/plugin.test.ts b/test/plugin.test.ts index d62d1fa..1b8c5dc 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -72,7 +72,8 @@ describe('iapl — auth collection', () => { secret: 'x', } as unknown as Config) const users = config.collections?.find((c) => c.slug === 'users') - expect(users?.auth).toBe(true) + // an auth collection with Payload's defaults; the plugin only wraps the reset mail's subject (mail.accountMailAfterCommit) + expect(users?.auth).toEqual({ forgotPassword: { generateEmailSubject: expect.any(Function) } }) expect(users?.fields.some((f) => 'name' in f && f.name === 'roles')).toBe(true) }) diff --git a/test/transactionPool.test.ts b/test/transactionPool.test.ts index 0782a76..0e72750 100644 --- a/test/transactionPool.test.ts +++ b/test/transactionPool.test.ts @@ -10,12 +10,13 @@ * docker run -d --rm -p 127.0.0.1:55432:5432 -e POSTGRES_PASSWORD=test postgres:17 * IPAL_TEST_POSTGRES_URI=postgres://postgres:test@127.0.0.1:55432/postgres pnpm vitest run test/transactionPool.test.ts */ -import type { BasePayload, Payload } from 'payload' +import type { BasePayload, Payload, PayloadRequest } from 'payload' import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { afterCommit, defaultConnectionReserve, inWatchedTransaction, transactionWatchState, watchTransactions } from '../src/modules/database/transactions.js' +import { holdAccountMail, releaseAccountMail, sendAccountMailAfterCommit, withAccountMailAfterCommit } from '../src/modules/email/accountMailAfterCommit.js' import { submitForm } from '../src/modules/forms/submitForm.js' import { startPayloadServer, type TestServer } from './http/server.js' import { silentServer, site } from './transactionPoolSite.js' @@ -136,6 +137,70 @@ describe('the watch (fake adapter)', () => { expect(transactionWatchState(payload)).toMatchObject({ active: 4, waiting: 2 }) }, 15_000) + describe('account mail after commit (matched by its token, never by the address alone)', () => { + const TOKEN_A = 'a'.repeat(40) + const TOKEN_B = 'b'.repeat(40) + const reqOf = async (payload: BasePayload, db: FakeDb) => ({ payload, transactionID: (await db.beginTransaction())! }) as unknown as PayloadRequest + const resetMail = (token: string, to = 'victim@client.example') => ({ html: `reset`, to }) + + test('two "forgot password" for one address at once, the second rolled back: the first one\'s mail goes out at its commit', async () => { + const { db, payload } = fakePayload({ max: 10 }) + watchTransactions(payload) + const sent: string[] = [] + const a = await reqOf(payload, db) + const b = await reqOf(payload, db) + holdAccountMail(TOKEN_A, 'victim@client.example', a) + holdAccountMail(TOKEN_B, 'Victim@Client.example', b) + expect(sendAccountMailAfterCommit(resetMail(TOKEN_A), async () => void sent.push('A'))).toBe(true) + expect(sendAccountMailAfterCommit(resetMail(TOKEN_B), async () => void sent.push('B'))).toBe(true) + await db.commitTransaction(a.transactionID as string) + expect(sent).toEqual(['A']) + await db.rollbackTransaction(b.transactionID as string) + expect(sent).toEqual(['A']) + }) + + test('a form\'s mail to an address whose "forgot password" is in flight is sent at once; the reset mail waits for its commit', async () => { + const { db, payload } = fakePayload({ max: 10 }) + watchTransactions(payload) + const sent: string[] = [] + const reset = await reqOf(payload, db) + holdAccountMail(TOKEN_A, 'office@client.example', reset) + expect(sendAccountMailAfterCommit({ html: '

New message from the contact form

', to: 'office@client.example' }, async () => void sent.push('form'))).toBe(false) + // the same token to another address, or to several, is not the account's mail either + expect(sendAccountMailAfterCommit(resetMail(TOKEN_A, 'other@client.example'), async () => {})).toBe(false) + expect(sendAccountMailAfterCommit({ ...resetMail(TOKEN_A), to: ['office@client.example', 'x@client.example'] }, async () => {})).toBe(false) + expect(sendAccountMailAfterCommit(resetMail(TOKEN_A, 'office@client.example'), async () => void sent.push('reset'))).toBe(true) + await db.rollbackTransaction(reset.transactionID as string) + expect(sent).toEqual([]) // the form mail was the caller's to send; the reset of a rolled-back request is dropped + releaseAccountMail(TOKEN_A) + }) + + test('nothing held without a watched transaction, or for a short token', async () => { + const { db, payload } = fakePayload({ max: 10 }) + watchTransactions(payload) + holdAccountMail(TOKEN_A, 'x@client.example', { payload, transactionID: undefined } as unknown as PayloadRequest) + holdAccountMail('short', 'x@client.example', await reqOf(payload, db)) + expect(sendAccountMailAfterCommit(resetMail(TOKEN_A, 'x@client.example'), async () => {})).toBe(false) + expect(sendAccountMailAfterCommit({ html: 'short', to: 'x@client.example' }, async () => {})).toBe(false) + }) + + test('the collection: Payload\'s own subjects, a project\'s own one kept; collections without a password left alone', async () => { + const t = (key: string) => `t:${key}` + const plain = withAccountMailAfterCommit({ slug: 'users', auth: true, fields: [] }) + const auth = plain.auth as { forgotPassword: { generateEmailSubject: (a: unknown) => Promise }; verify?: unknown } + expect(await auth.forgotPassword.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: 'u@x.example' } })).toBe('t:authentication:resetYourPassword') + expect(auth.verify).toBeUndefined() + const own = withAccountMailAfterCommit({ slug: 'members', auth: { forgotPassword: { generateEmailSubject: () => 'Reset' }, verify: true }, fields: [] }) + const ownAuth = own.auth as { forgotPassword: { generateEmailSubject: (a: unknown) => Promise }; verify: { generateEmailSubject: (a: unknown) => Promise } } + expect(await ownAuth.forgotPassword.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: 'u@x.example' } })).toBe('Reset') + expect(await ownAuth.verify.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: 'u@x.example' } })).toBe('t:authentication:verifyYourEmail') + expect(withAccountMailAfterCommit(own)).toEqual(own) // idempotent + const keyOnly = { slug: 'keys', auth: { disableLocalStrategy: true as const }, fields: [] } + expect(withAccountMailAfterCommit(keyOnly)).toBe(keyOnly) + expect(withAccountMailAfterCommit({ slug: 'pages', fields: [] })).toEqual({ slug: 'pages', fields: [] }) + }) + }) + test('afterCommit runs after the commit and before it returns; dropped on rollback; an error is logged', async () => { const { db, events, logger, payload } = fakePayload() watchTransactions(payload)