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:
co-authored by
Claude Opus 5.5
parent
4efadb21d5
commit
919953e65e
+2
-1
@@ -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)
|
||||
})
|
||||
|
||||
|
||||
@@ -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:[email protected]: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 = '[email protected]') => ({ html: `<a href="https://site.example/admin/reset/${token}">reset</a>`, 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, '[email protected]', a)
|
||||
holdAccountMail(TOKEN_B, '[email protected]', 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, '[email protected]', reset)
|
||||
expect(sendAccountMailAfterCommit({ html: '<p>New message from the contact form</p>', to: '[email protected]' }, 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, '[email protected]'), async () => {})).toBe(false)
|
||||
expect(sendAccountMailAfterCommit({ ...resetMail(TOKEN_A), to: ['[email protected]', '[email protected]'] }, async () => {})).toBe(false)
|
||||
expect(sendAccountMailAfterCommit(resetMail(TOKEN_A, '[email protected]'), 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, '[email protected]', { payload, transactionID: undefined } as unknown as PayloadRequest)
|
||||
holdAccountMail('short', '[email protected]', await reqOf(payload, db))
|
||||
expect(sendAccountMailAfterCommit(resetMail(TOKEN_A, '[email protected]'), async () => {})).toBe(false)
|
||||
expect(sendAccountMailAfterCommit({ html: 'short', to: '[email protected]' }, 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<string> }; verify?: unknown }
|
||||
expect(await auth.forgotPassword.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: '[email protected]' } })).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<string> }; verify: { generateEmailSubject: (a: unknown) => Promise<string> } }
|
||||
expect(await ownAuth.forgotPassword.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: '[email protected]' } })).toBe('Reset')
|
||||
expect(await ownAuth.verify.generateEmailSubject({ req: { t }, token: TOKEN_A, user: { email: '[email protected]' } })).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)
|
||||
|
||||
Reference in New Issue
Block a user