Mail relay: docs, agent guide, skills, changelog draft; test against the real service code; starter offers the mail service
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
533f571d4d
commit
dd3792cbc7
+5
-4
@@ -30,7 +30,7 @@ export const nextHeadersMock = {
|
||||
|
||||
export type TestServer = { close: () => Promise<void>; url: string }
|
||||
|
||||
export async function startPayloadServer(config: Promise<SanitizedConfig>): Promise<TestServer> {
|
||||
export async function startPayloadServer(config: Promise<SanitizedConfig>, port = 0): Promise<TestServer> {
|
||||
const rest = { DELETE: REST_DELETE(config), GET: REST_GET(config), PATCH: REST_PATCH(config), POST: REST_POST(config) }
|
||||
const graphql = GRAPHQL_POST(config)
|
||||
|
||||
@@ -76,12 +76,13 @@ export async function startPayloadServer(config: Promise<SanitizedConfig>): Prom
|
||||
})()
|
||||
})
|
||||
})
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
// a fixed port listens on every local address: `localhost` may be ::1 for whoever calls back
|
||||
await new Promise<void>((resolve) => (port ? server.listen(port, resolve) : server.listen(0, '127.0.0.1', resolve)))
|
||||
const address = server.address()
|
||||
const port = typeof address === 'object' && address ? address.port : 0
|
||||
const listening = typeof address === 'object' && address ? address.port : 0
|
||||
return {
|
||||
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
|
||||
url: `http://127.0.0.1:${port}`,
|
||||
url: `http://127.0.0.1:${listening}`,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* - each mail says what it is: the test e-mail, a form's two e-mails, Payload's "forgot password";
|
||||
* - the state routes are for admins; `relay: false` leaves no route and no block; no stored field changed.
|
||||
*/
|
||||
import type { Config, Field, Payload } from 'payload'
|
||||
import type { Field, Payload, SanitizedConfig } from 'payload'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
@@ -275,7 +275,7 @@ describe('each mail says what it is', () => {
|
||||
})
|
||||
|
||||
describe('switched off, and what did not change', () => {
|
||||
const endpoints = (config: Config) => (config.endpoints ?? []).map((e) => `${e.method} ${e.path}`)
|
||||
const endpoints = (config: SanitizedConfig) => (config.endpoints ?? []).map((e) => `${e.method} ${e.path}`)
|
||||
const stored = (fields: Field[]): string[] =>
|
||||
fields.flatMap((f) => {
|
||||
if (f.type === 'ui') {return []}
|
||||
@@ -283,7 +283,7 @@ describe('switched off, and what did not change', () => {
|
||||
const own = 'name' in f && f.name ? [`${f.name}:${f.type}${f.type === 'select' ? `(${(f.options as { value: string }[]).map((o) => (typeof o === 'string' ? o : o.value)).join('|')})` : ''}`] : []
|
||||
return 'fields' in f && Array.isArray(f.fields) ? [...own, ...stored(f.fields).map((n) => ('name' in f && f.name ? `${f.name}.${n}` : n))] : own
|
||||
})
|
||||
const emailTab = (config: Config) => JSON.stringify(config.globals?.find((g) => g.slug === 'site-integrations')?.fields)
|
||||
const emailTab = (config: SanitizedConfig) => JSON.stringify(config.globals?.find((g) => g.slug === 'site-integrations')?.fields)
|
||||
|
||||
test('mail: { relay: false } leaves no route, no state block and no mark on the auth collection', async () => {
|
||||
const off = await makeConfig({ relay: false }, 'relayoff')
|
||||
@@ -294,12 +294,12 @@ describe('switched off, and what did not change', () => {
|
||||
expect(emailTab(off)).not.toContain('MailRelayStatus')
|
||||
expect(emailTab(off)).not.toContain('Intecion')
|
||||
expect((off.custom as { iapl: { mail: { relay: unknown } } }).iapl.mail.relay).toBe(false)
|
||||
const hooks = (config: Config) => config.collections?.find((c) => c.slug === 'users')?.hooks?.beforeOperation?.length ?? 0
|
||||
const hooks = (config: SanitizedConfig) => config.collections?.find((c) => c.slug === 'users')?.hooks?.beforeOperation?.length ?? 0
|
||||
expect(hooks(on) - hooks(off)).toBe(1)
|
||||
})
|
||||
|
||||
test('no stored field differs: the same names, types and select values with the service on, off, and as in 1.16', async () => {
|
||||
const names = (config: Config) => stored(config.globals?.find((g) => g.slug === 'site-integrations')?.fields ?? []).filter((n) => /^(?:email|smtp)/.test(n))
|
||||
const names = (config: SanitizedConfig) => stored((config.globals?.find((g) => g.slug === 'site-integrations')?.fields ?? [])).filter((n) => /^(?:email|smtp)/.test(n))
|
||||
const on = names(await makeConfig(undefined, 'fieldson'))
|
||||
expect(on).toEqual(names(await makeConfig({ relay: false }, 'fieldsoff')))
|
||||
expect(on).toEqual([
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* The plugin's client against the REAL service code of the Intecion Notifications Webservice, run on
|
||||
* this machine (the IWDL repository's local stand-in: the same Worker under the local Workers runtime,
|
||||
* with mail recorded instead of sent and the call-back allowed to reach `localhost`).
|
||||
*
|
||||
* Skipped unless the stand-in is named — nothing here can reach the deployed service:
|
||||
* cd <IWDL>/services/mail-relay
|
||||
* npm run dev:migrate && npm run ims -- allow localhost:3987 && npm run dev
|
||||
* npm run ims -- limits localhost:3987 --hour 2000 --day 20000 # after the first run: a run sends about ten messages,
|
||||
* # and the default hour (24 for mail that is not account mail) lasts three runs
|
||||
* IAPL_TEST_RELAY_URL=http://127.0.0.1:8787/mail pnpm vitest run test/mailRelayService.test.ts
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { ResolvedRelayOptions } from '../src/modules/email/relay/options.js'
|
||||
|
||||
import { mailAttachmentLimit } from '../src/modules/email/attachmentLimit.js'
|
||||
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
|
||||
import { relayRequest } from '../src/modules/email/relay/client.js'
|
||||
import { RELAY_CONTRACT_VERSION } from '../src/modules/email/relay/constants.js'
|
||||
import { withMailKind } from '../src/modules/email/relay/kinds.js'
|
||||
import { resolveRelayOptions } from '../src/modules/email/relay/options.js'
|
||||
import { sendThroughRelay } from '../src/modules/email/relay/send.js'
|
||||
import { disconnectRelay, enrolRelay, getRelayStatus, rotateRelayToken } from '../src/modules/email/relay/session.js'
|
||||
import { readRelayStore } from '../src/modules/email/relay/store.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { startPayloadServer, type TestServer } from './http/server.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const SERVICE = (process.env.IAPL_TEST_RELAY_URL ?? '').replace(/\/+$/, '')
|
||||
const PORT = Number(process.env.IAPL_TEST_SITE_PORT ?? 3987)
|
||||
const HOST = `localhost:${PORT}`
|
||||
const local = /^http:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?\//.test(`${SERVICE}/`)
|
||||
|
||||
type Recorded = { from?: { email?: string; name?: string }; headers?: Record<string, string>; replyTo?: string; subject?: string; to?: string[] }
|
||||
|
||||
describe.skipIf(!SERVICE || !local)('against the real service code, run locally', () => {
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
let options: ResolvedRelayOptions
|
||||
const origin = SERVICE.replace(/\/mail$/, '')
|
||||
const outbox = async () => ((await (await fetch(`${origin}/__dev/outbox`)).json()) as { mails: Recorded[] }).mails
|
||||
const MESSAGE = { html: '<p>Hello.</p>', subject: 'New enquiry', to: '[email protected]' }
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-relay-service-media') } }],
|
||||
db: testDatabase('relayservice'),
|
||||
editor: lexicalEditor(),
|
||||
email: mailAdapter(),
|
||||
plugins: [iapl({ i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail: { relay: { retryBackoffMs: 50, url: SERVICE } }, twoFactor: false })],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
serverURL: `http://${HOST}`,
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config, PORT)
|
||||
options = resolveRelayOptions(payload, undefined)!
|
||||
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromAddress: '[email protected]', smtpFromName: 'Kancelaria Example' } as never })
|
||||
await fetch(`${origin}/__dev/outbox`, { method: 'DELETE' })
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
test('the service is up and speaks the contract this client was written for', async () => {
|
||||
expect(await (await fetch(`${SERVICE}/health`)).json()).toEqual({ ok: true })
|
||||
})
|
||||
|
||||
test('the first e-mail: the service calls the site\'s confirm route over HTTP, then takes the message', async () => {
|
||||
const result = (await payload.sendEmail(withMailKind(MESSAGE, 'form-notification'))) as Record<string, unknown>
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ replayed: false, senderName: 'Kancelaria Example', sent: true, transport: 'relay', warnings: [] })
|
||||
const stored = await readRelayStore(payload)
|
||||
expect(stored).toMatchObject({ host: HOST, source: 'enrolment', state: 'active' })
|
||||
expect(stored.token).toMatch(/^ims_[\w-]{43}$/)
|
||||
const mails = await outbox()
|
||||
expect(mails).toHaveLength(1)
|
||||
expect(JSON.stringify(mails[0])).toContain('Kancelaria Example')
|
||||
expect(JSON.stringify(mails[0])).toContain('[email protected]')
|
||||
expect(JSON.stringify(mails[0])).toContain(HOST)
|
||||
})
|
||||
|
||||
test('/v1/status: the state, the limits and the contract version', async () => {
|
||||
const status = await getRelayStatus(payload, options, { refresh: true })
|
||||
expect(status, JSON.stringify(status)).toMatchObject({ connected: true, host: HOST, state: 'active', tokenSource: 'enrolment' })
|
||||
expect(status.error).toBeUndefined()
|
||||
expect(status.senderAddress).toMatch(/^[^@\s]+@[^@\s]+$/)
|
||||
expect(status.limits?.maxAttachmentBytes).toBeGreaterThan(0)
|
||||
expect(status.quota?.hour?.remaining).toBeLessThan(status.quota?.hour?.limit ?? 0)
|
||||
const stored = await readRelayStore(payload)
|
||||
expect(stored.service?.contract).toBe(RELAY_CONTRACT_VERSION)
|
||||
expect(await mailAttachmentLimit(payload)).toBe(status.limits?.maxAttachmentBytes)
|
||||
})
|
||||
|
||||
test('a visitor\'s words in the subject, display names in the recipients, an international domain: accepted as the client cleans them', async () => {
|
||||
const before = (await outbox()).length
|
||||
const result = await sendThroughRelay(payload, options, {
|
||||
cc: '"Kowalski, Jan" <[email protected]>',
|
||||
html: '<p>x</p>',
|
||||
subject: 'Pytanie\r\nBcc: [email protected] \u{1F469}\u{1F4BB}',
|
||||
text: 'x',
|
||||
to: ['Biuro <[email protected]>', 'info@żółw.pl'],
|
||||
})
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ sent: true })
|
||||
const mail = (await outbox())[before]
|
||||
expect(mail.subject).toBe('Pytanie Bcc: [email protected] \u{1F469}\u{1F4BB}')
|
||||
expect(JSON.stringify(mail)).toContain('[email protected]')
|
||||
})
|
||||
|
||||
test('a sender name the service does not accept: sent under the host, with the warning', async () => {
|
||||
const result = await sendThroughRelay(payload, options, MESSAGE, { senderName: 'PayPal <[email protected]>' })
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ senderName: HOST, sent: true, warnings: ['sender-name-replaced'] })
|
||||
expect((await getRelayStatus(payload, options)).nameReplaced).toMatchObject({ used: HOST })
|
||||
})
|
||||
|
||||
test('refusals map to the site statuses: a program as attachment, too many recipients, a file over the limit', async () => {
|
||||
const exe = await sendThroughRelay(payload, options, { ...MESSAGE, attachments: [{ content: Buffer.from('MZ'), filename: 'invoice.pdf.exe' }] })
|
||||
expect(exe).toMatchObject({ cause: 'attachment-refused', code: 'relay-attachment-refused', sent: false })
|
||||
const many = await sendThroughRelay(payload, options, { ...MESSAGE, to: Array.from({ length: 60 }, (_, i) => `a${i}@example.org`) })
|
||||
expect(many).toMatchObject({ code: 'relay-quota', sent: false })
|
||||
const limit = (await getRelayStatus(payload, options)).limits?.maxAttachmentBytes ?? 0
|
||||
const big = await sendThroughRelay(payload, options, { ...MESSAGE, attachments: [{ content: Buffer.alloc(limit + 1), filename: 'big.bin' }] })
|
||||
expect(big).toMatchObject({ code: 'relay-too-large', sent: false })
|
||||
})
|
||||
|
||||
test('the answer to a send is lost: the retry carries the same key and bytes, and no second mail goes out', async () => {
|
||||
let lost = 0
|
||||
const keys: (null | string)[] = []
|
||||
const lossy = (async (input: string, init?: RequestInit) => {
|
||||
const response = await fetch(input, init)
|
||||
if (String(input).endsWith('/v1/send')) {
|
||||
keys.push(new Headers(init?.headers).get('idempotency-key'))
|
||||
if (lost++ === 0) {throw new TypeError('fetch failed')} // the service did its part; the answer never arrives
|
||||
}
|
||||
return response
|
||||
}) as typeof fetch
|
||||
const result = await sendThroughRelay(payload, { ...options, fetchImpl: lossy }, { ...MESSAGE, subject: 'Once only' })
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ replayed: true, sent: true })
|
||||
expect(keys).toHaveLength(2)
|
||||
expect(keys[0]).toBe(keys[1])
|
||||
// (the outbox also records the service's own notices to Intecion, so this message is counted by its subject)
|
||||
expect((await outbox()).filter((m) => m.subject === 'Once only')).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('requests from a new server address: 401 reverify, one enrolment, the message goes out', async () => {
|
||||
const paths: string[] = []
|
||||
// an address this site has not used in an earlier run against the same local database
|
||||
const elsewhere = `198.51.100.${1 + Math.floor(Math.random() * 250)}`
|
||||
const moved = (async (input: string, init?: RequestInit) => {
|
||||
paths.push(String(input).slice(SERVICE.length))
|
||||
return fetch(input, { ...init, headers: { ...(init?.headers as Record<string, string>), 'x-dev-client-address': elsewhere } })
|
||||
}) as typeof fetch
|
||||
const result = await sendThroughRelay(payload, { ...options, fetchImpl: moved }, { ...MESSAGE, subject: 'Moved' })
|
||||
expect(result, JSON.stringify(result)).toMatchObject({ sent: true })
|
||||
expect(paths).toEqual(['/v1/send', '/v1/enrol', '/v1/send'])
|
||||
})
|
||||
|
||||
test('rotation: the new token is stored at once and works; the previous one cannot rotate again', async () => {
|
||||
const old = (await readRelayStore(payload)).token!
|
||||
expect(await rotateRelayToken(payload, options, { force: true })).toBe('rotated')
|
||||
const fresh = (await readRelayStore(payload)).token!
|
||||
expect(fresh).not.toBe(old)
|
||||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'After rotation' })).sent).toBe(true)
|
||||
const again = await relayRequest({ method: 'POST', path: '/v1/rotate', token: old, url: SERVICE })
|
||||
expect(again).toMatchObject({ code: 'already-rotated', ok: false, retryable: false })
|
||||
})
|
||||
|
||||
test('"Disconnect" revokes: the token stops working at once; "Connect again" enrols anew', async () => {
|
||||
const token = (await readRelayStore(payload)).token!
|
||||
await disconnectRelay(payload, options)
|
||||
expect(await relayRequest({ method: 'GET', path: '/v1/status', token, url: SERVICE })).toMatchObject({ code: 'invalid-token', ok: false })
|
||||
expect(await sendThroughRelay(payload, options, MESSAGE)).toMatchObject({ code: 'relay-disconnected', sent: false })
|
||||
expect(await enrolRelay(payload, options, { force: true })).toEqual({ ok: true, state: 'active' })
|
||||
expect((await sendThroughRelay(payload, options, { ...MESSAGE, subject: 'Back' })).sent).toBe(true)
|
||||
})
|
||||
|
||||
test('nothing in the service\'s outbox carries a token, and the site never logged one', async () => {
|
||||
expect(JSON.stringify(await outbox())).not.toContain('ims_')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user