/** * Attachments through both e-mail paths. SMTP: the real nodemailer against a * small local SMTP server. Microsoft Graph: a mocked Graph (no tenant, no * credentials) that records every call — the inline path, the upload session, * and the clean-up of the mailbox copy. */ import type { BasePayload, PayloadEmailAdapter } from 'payload' import { createServer, type Server } from 'node:net' import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest' import { clearGraphTokenCache, graphAdapter, graphLargeAttachmentSupport } from '../src/modules/email/graphAdapter.js' import { GRAPH_INLINE_MAX_BYTES } from '../src/modules/email/graphAttachments.js' import { mailAdapter } from '../src/modules/email/mailAdapter.js' import { panelSmtpAdapter } from '../src/modules/email/panelSmtpAdapter.js' import { fakePayload } from './helpers.js' vi.mock('server-only', () => ({})) const MB = 1024 * 1024 const bytes = (size: number) => Buffer.from(Array.from({ length: size }, (_, i) => i % 251)) const attachment = (size: number, filename = 'cv.pdf') => ({ content: bytes(size), contentDisposition: 'attachment' as const, contentType: 'application/pdf', filename }) // ---- SMTP ------------------------------------------------------------------------------------- type Received = { data: string; to: string[] } /** `refuseOver`: answer DATA with 552 when the message is larger (a server with a size limit). */ function startSmtp(received: Received[], limits: { refuseOver?: number } = {}): Promise<{ port: number; server: Server }> { const server = createServer((socket) => { const mail: Received = { data: '', to: [] } let inData = false let buffer = '' const reply = (line: string) => socket.write(`${line}\r\n`) reply('220 localhost ESMTP test') socket.on('data', (chunk) => { buffer += chunk.toString('latin1') let index: number while ((index = buffer.indexOf('\r\n')) >= 0) { const line = buffer.slice(0, index) buffer = buffer.slice(index + 2) if (inData) { if (line === '.') { inData = false if (limits.refuseOver && mail.data.length > limits.refuseOver) { reply('552 5.3.4 Message size exceeds fixed limit') } else { received.push(mail) reply('250 2.0.0 Ok: queued') } } else { mail.data += `${line}\n` } continue } const command = line.toUpperCase() if (command.startsWith('EHLO')) {socket.write('250-localhost\r\n250-AUTH PLAIN LOGIN\r\n250 8BITMIME\r\n')} else if (command.startsWith('AUTH PLAIN')) {reply('235 2.7.0 Authentication successful')} else if (command.startsWith('MAIL FROM:')) {reply('250 2.1.0 Ok')} else if (command.startsWith('RCPT TO:')) { mail.to.push(line.slice(8).trim()) reply('250 2.1.5 Ok') } else if (command === 'DATA') { inData = true reply('354 End data with .') } else if (command === 'QUIT') { reply('221 2.0.0 Bye') socket.end() } else {reply('502 5.5.2 Command not recognized')} } }) }) return new Promise((resolve) => { server.listen(0, '127.0.0.1', () => { const address = server.address() resolve({ port: typeof address === 'object' && address ? address.port : 0, server }) }) }) } const build = (adapter: PayloadEmailAdapter, payload: BasePayload) => adapter({ payload } as Parameters[0]) /** The base64 body of the first attachment in a raw message, decoded. */ function attachedBytes(raw: string): Buffer { const start = raw.indexOf('Content-Disposition: attachment') const body = raw.slice(raw.indexOf('\n\n', start) + 2) return Buffer.from(body.slice(0, body.indexOf('\n--')).replace(/\s+/g, ''), 'base64') } // ---- a mocked Microsoft Graph ------------------------------------------------------------------ type Call = { body?: unknown; headers: Record; method: string; url: string } const jwt = (roles: string[]) => `x.${Buffer.from(JSON.stringify({ roles })).toString('base64url')}.y` function mockGraph({ fail, roles = ['Mail.Send', 'Mail.ReadWrite'], sentAfterLooks = 1 }: { fail?: (call: Call) => number | undefined; roles?: string[]; sentAfterLooks?: number } = {}) { const calls: Call[] = [] const uploaded: Buffer[] = [] let looks = 0 const fetchImpl = (async (input: string | URL, init: RequestInit = {}) => { const url = String(input) const method = init.method ?? 'GET' const headers = (init.headers ?? {}) as Record if (url.includes('login.microsoftonline.com')) {return Response.json({ access_token: jwt(roles), expires_in: 3600 })} const call: Call = { body: typeof init.body === 'string' ? (JSON.parse(init.body) as unknown) : init.body, headers, method, url } calls.push(call) const failure = fail?.(call) if (failure) {return new Response('{"error":{"code":"Failed"}}', { status: failure })} if (url.endsWith('/sendMail')) {return new Response(null, { status: 202 })} if (method === 'POST' && url.endsWith('/messages')) {return Response.json({ id: 'draft-1' }, { status: 201 })} if (url.endsWith('/attachments/createUploadSession')) {return Response.json({ uploadUrl: 'https://outlook.office.com/upload/session-1' }, { status: 201 })} if (url.endsWith('/attachments')) {return Response.json({ id: 'att' }, { status: 201 })} if (method === 'PUT' && url.startsWith('https://outlook.office.com/upload/')) { uploaded.push(Buffer.from(init.body as Uint8Array)) const [, end, total] = /bytes \d+-(\d+)\/(\d+)/.exec(headers['Content-Range']) ?? [] return Response.json({}, { status: Number(end) + 1 === Number(total) ? 201 : 200 }) } if (url.endsWith('/send')) {return new Response(null, { status: 202 })} if (method === 'GET' && url.includes('/messages/draft-1')) {return Response.json({ isDraft: ++looks < sentAfterLooks })} if (url.endsWith('/permanentDelete')) {return new Response(null, { status: 204 })} if (method === 'DELETE') {return new Response(null, { status: 204 })} return new Response('unexpected', { status: 500 }) }) as unknown as typeof fetch const names = () => calls.map((c) => `${c.method} ${c.url.replace('https://graph.microsoft.com/v1.0/users/forms%40example.com', '').replace(/\?.*$/, '')}`) return { calls, fetchImpl, names, uploaded } } const graphEnv = () => { vi.stubEnv('GRAPH_TENANT_ID', 'tenant') vi.stubEnv('GRAPH_CLIENT_ID', 'client') vi.stubEnv('GRAPH_CLIENT_SECRET', 'secret') vi.stubEnv('GRAPH_SENDER', 'forms@example.com') } describe('attachments', () => { const received: Received[] = [] const limited: Received[] = [] let port = 0 let limitedPort = 0 let servers: Server[] = [] beforeAll(async () => { const open = await startSmtp(received) const small = await startSmtp(limited, { refuseOver: 200_000 }) port = open.port limitedPort = small.port servers = [open.server, small.server] }) afterAll(async () => { await Promise.all(servers.map((s) => new Promise((resolve) => s.close(resolve)))) }) afterEach(() => { received.length = 0 limited.length = 0 clearGraphTokenCache() vi.unstubAllEnvs() }) const smtp = (p = port) => ({ smtpFromAddress: 'office@example.com', smtpHost: '127.0.0.1', smtpPassword: 'pw', smtpPort: p, smtpUser: 'mailer' }) const message = (size: number) => ({ attachments: [attachment(size)], html: '

New application

', subject: 'Application', to: 'jobs@example.com' }) describe('SMTP', () => { test('a 10 MB file goes out as an attachment and arrives byte for byte', async () => { const { payload } = fakePayload({ integrations: smtp() }) const result = await build(panelSmtpAdapter(), payload).sendEmail(message(10 * MB)) expect(result).toMatchObject({ sent: true }) expect(received).toHaveLength(1) expect(received[0].data).toContain('filename=cv.pdf') expect(received[0].data.length).toBeGreaterThan(13.3 * MB) // base64: about 13.7 MB on the wire expect(Buffer.compare(attachedBytes(received[0].data), bytes(10 * MB))).toBe(0) expect(await (build(panelSmtpAdapter(), payload) as { attachmentLimit?: unknown }).attachmentLimit).toBeUndefined() }, 60_000) test('a server that refuses the size: reported as not sent, with the server\'s reason', async () => { const { payload } = fakePayload({ integrations: smtp(limitedPort) }) const result = (await build(panelSmtpAdapter(), payload).sendEmail(message(MB))) as { detail?: string; sent: boolean } expect(result.sent).toBe(false) expect(result.detail).toContain('552') expect(limited).toHaveLength(0) }) }) describe('Microsoft Graph (mocked)', () => { test('under 3 MB: one sendMail call with the file inline, nothing kept in the mailbox', async () => { graphEnv() const graph = mockGraph({ roles: ['Mail.Send'] }) const { payload } = fakePayload() const result = await build(graphAdapter({ fetchImpl: graph.fetchImpl }), payload).sendEmail(message(2 * MB)) expect(result).toEqual({ sent: true }) expect(graph.names()).toEqual(['POST /sendMail']) const body = graph.calls[0].body as { message: { attachments: { contentBytes: string; name: string }[] }; saveToSentItems: boolean } expect(body.saveToSentItems).toBe(false) expect(body.message.attachments[0].name).toBe('cv.pdf') expect(Buffer.compare(Buffer.from(body.message.attachments[0].contentBytes, 'base64'), bytes(2 * MB))).toBe(0) }) test('10 MB: draft → upload session in order → send → the mailbox copy is deleted', async () => { graphEnv() const graph = mockGraph({ sentAfterLooks: 2 }) const { payload } = fakePayload() const result = (await build(graphAdapter({ cleanupDelaysMs: [0, 0, 0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(10 * MB))) as { cleanup: Promise; sent: boolean } expect(result.sent).toBe(true) expect(await result.cleanup).toBe('deleted') expect(graph.names()).toEqual([ 'POST /messages', 'POST /messages/draft-1/attachments/createUploadSession', 'PUT https://outlook.office.com/upload/session-1', 'PUT https://outlook.office.com/upload/session-1', 'PUT https://outlook.office.com/upload/session-1', 'PUT https://outlook.office.com/upload/session-1', 'POST /messages/draft-1/send', 'GET /messages/draft-1', // still a draft: not deleted yet (deleting now could cancel the send) 'GET /messages/draft-1', // sent 'POST /messages/draft-1/permanentDelete', ]) // The draft is addressed and labelled like any message, and asks for an id that survives the move to Sent Items. expect(graph.calls[0].body).toMatchObject({ subject: 'Application', toRecipients: [{ emailAddress: { address: 'jobs@example.com' } }] }) // every call on the draft carries the immutable-id preference (the pre-authenticated upload URL takes no headers of ours) const onGraph = graph.calls.filter((c) => c.url.startsWith('https://graph.microsoft.com/')) expect(onGraph.length).toBeGreaterThanOrEqual(6) expect(onGraph.every((c) => c.headers.Prefer === 'IdType="ImmutableId"')).toBe(true) expect((graph.calls[1].body as { AttachmentItem: unknown }).AttachmentItem).toMatchObject({ name: 'cv.pdf', attachmentType: 'file', size: 10 * MB }) // Every byte, in order, in pieces under 4 MB, without the bearer token on the pre-authenticated URL. expect(Buffer.compare(Buffer.concat(graph.uploaded), bytes(10 * MB))).toBe(0) expect(graph.uploaded.every((part) => part.length < 4 * MB)).toBe(true) const puts = graph.calls.filter((c) => c.method === 'PUT') expect(puts.every((c) => !('Authorization' in c.headers))).toBe(true) expect(puts.map((c) => c.headers['Content-Range'])[0]).toBe(`bytes 0-${10 * 320 * 1024 - 1}/${10 * MB}`) }) test('several files: small ones are added directly, large ones through a session', async () => { graphEnv() const graph = mockGraph() const { payload } = fakePayload() const result = (await build(graphAdapter({ cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl }), payload).sendEmail({ ...message(MB), attachments: [attachment(MB, 'letter.pdf'), attachment(4 * MB, 'cv.pdf')], })) as { cleanup: Promise; sent: boolean } expect(result.sent).toBe(true) await result.cleanup expect(graph.names().slice(0, 6)).toEqual([ 'POST /messages', 'POST /messages/draft-1/attachments', 'POST /messages/draft-1/attachments/createUploadSession', 'PUT https://outlook.office.com/upload/session-1', 'PUT https://outlook.office.com/upload/session-1', 'POST /messages/draft-1/send', ]) }) test.each([ ['the upload fails', (c: Call) => (c.method === 'PUT' ? 503 : undefined)], ['the send fails', (c: Call) => (c.url.endsWith('/send') ? 500 : undefined)], ['the upload session cannot be created', (c: Call) => (c.url.endsWith('createUploadSession') ? 400 : undefined)], ])('%s: not sent, and the draft with the file is deleted from the mailbox', async (_name, fail) => { graphEnv() const graph = mockGraph({ fail }) const { payload } = fakePayload() const result = (await build(graphAdapter({ cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { code?: string; sent: boolean } expect(result).toMatchObject({ code: 'graph-error', sent: false }) expect(graph.names().at(-1)).toBe('POST /messages/draft-1/permanentDelete') expect(graph.names()).not.toContain('GET /messages/draft-1') }) test('permanentDelete unavailable: falls back to a plain delete', async () => { graphEnv() const graph = mockGraph({ fail: (c) => (c.url.endsWith('/permanentDelete') ? 404 : undefined) }) const { payload } = fakePayload() const result = (await build(graphAdapter({ cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { cleanup: Promise } expect(await result.cleanup).toBe('deleted') expect(graph.names().slice(-2)).toEqual(['POST /messages/draft-1/permanentDelete', 'DELETE /messages/draft-1']) }) test('the sent copy cannot be removed: the send still counts, and the log says to delete it by hand', async () => { graphEnv() const graph = mockGraph({ fail: (c) => (c.url.endsWith('/permanentDelete') || c.method === 'DELETE' ? 500 : undefined) }) const { payload } = fakePayload() const result = (await build(graphAdapter({ cleanupDelaysMs: [0, 0], fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { cleanup: Promise; sent: boolean } expect(result.sent).toBe(true) expect(await result.cleanup).toBe('left') expect(payload.logger.warn).toHaveBeenCalledWith(expect.stringContaining('delete it by hand')) }) test('without Mail.ReadWrite: a clear refusal that names the permission, and nothing is created', async () => { graphEnv() const graph = mockGraph({ roles: ['Mail.Send'] }) const { payload } = fakePayload() const adapter = build(graphAdapter({ fetchImpl: graph.fetchImpl }), payload) const result = (await adapter.sendEmail(message(5 * MB))) as { code?: string; detail?: string; sent: boolean } expect(result).toMatchObject({ code: 'graph-permission', sent: false }) expect(result.detail).toContain('Mail.ReadWrite') expect(payload.logger.error).toHaveBeenCalledWith(expect.stringContaining('Mail.ReadWrite')) expect(graph.calls).toEqual([]) expect(await graphLargeAttachmentSupport({ fetchImpl: graph.fetchImpl })).toBe('no-permission') expect(await (adapter as unknown as { attachmentLimit: () => Promise }).attachmentLimit()).toBe(GRAPH_INLINE_MAX_BYTES - 1) }) test('Graph answers 403 to the draft (a token that hides its roles): the same refusal', async () => { graphEnv() const graph = mockGraph({ fail: (c) => (c.method === 'POST' && c.url.endsWith('/messages') ? 403 : undefined) }) const { payload } = fakePayload() const result = (await build(graphAdapter({ fetchImpl: graph.fetchImpl }), payload).sendEmail(message(5 * MB))) as { code?: string; detail?: string } expect(result.code).toBe('graph-permission') expect(result.detail).toContain('Mail.ReadWrite') }) test('largeAttachments: false — Graph keeps to small attachments', async () => { graphEnv() const graph = mockGraph() const { payload } = fakePayload() const adapter = build(graphAdapter({ fetchImpl: graph.fetchImpl, largeAttachments: false }), payload) expect(await adapter.sendEmail(message(5 * MB))).toMatchObject({ code: 'graph-large-off', sent: false }) expect(graph.calls).toEqual([]) expect(await adapter.sendEmail(message(MB))).toEqual({ sent: true }) }) }) describe('mailAdapter: Graph selected in the panel', () => { const limitOf = (adapter: unknown) => (adapter as { attachmentLimit: () => Promise }).attachmentLimit() test('permission present: large files go over Graph, no ceiling', async () => { graphEnv() const graph = mockGraph() const { payload } = fakePayload({ integrations: { ...smtp(), emailTransport: 'graph' } }) const adapter = build(mailAdapter({ graph: { cleanupDelaysMs: [0], fetchImpl: graph.fetchImpl } }), payload) expect(await limitOf(adapter)).toBeNull() expect(await adapter.sendEmail(message(5 * MB))).toMatchObject({ sent: true }) expect(graph.names()).toContain('POST /messages/draft-1/send') expect(received).toHaveLength(0) }) test('permission missing, SMTP filled in: the large message goes over SMTP; small ones stay on Graph', async () => { graphEnv() const graph = mockGraph({ roles: ['Mail.Send'] }) const { payload } = fakePayload({ integrations: { ...smtp(), emailTransport: 'graph' } }) const adapter = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl } }), payload) expect(await limitOf(adapter)).toBeNull() expect(await adapter.sendEmail(message(5 * MB))).toMatchObject({ sent: true }) expect(received).toHaveLength(1) expect(Buffer.compare(attachedBytes(received[0].data), bytes(5 * MB))).toBe(0) expect(graph.calls).toEqual([]) expect(await adapter.sendEmail(message(MB))).toEqual({ sent: true }) expect(graph.names()).toEqual(['POST /sendMail']) expect(received).toHaveLength(1) }) test('permission missing, no SMTP: the ceiling is just under 3 MB, and a larger send fails clearly', async () => { graphEnv() const graph = mockGraph({ roles: ['Mail.Send'] }) const { payload } = fakePayload({ integrations: { emailTransport: 'graph' } }) const adapter = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl } }), payload) expect(await limitOf(adapter)).toBe(GRAPH_INLINE_MAX_BYTES - 1) const result = (await adapter.sendEmail(message(5 * MB))) as { code?: string; detail?: string; sent: boolean } expect(result).toMatchObject({ code: 'graph-permission', sent: false }) expect(result.detail).toContain('Mail.ReadWrite') }) test('switched off by the project (largeAttachments: false): SMTP carries large files when filled in', async () => { graphEnv() const graph = mockGraph() const withSmtp = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl, largeAttachments: false } }), fakePayload({ integrations: { ...smtp(), emailTransport: 'graph' } }).payload) expect(await limitOf(withSmtp)).toBeNull() expect(await withSmtp.sendEmail(message(5 * MB))).toMatchObject({ sent: true }) expect(received).toHaveLength(1) const without = build(mailAdapter({ graph: { fetchImpl: graph.fetchImpl, largeAttachments: false } }), fakePayload({ integrations: { emailTransport: 'graph' } }).payload) expect(await limitOf(without)).toBe(GRAPH_INLINE_MAX_BYTES - 1) }) test('SMTP selected: no ceiling from the plugin', async () => { const adapter = build(mailAdapter(), fakePayload({ integrations: smtp() }).payload) expect(await limitOf(adapter)).toBeNull() }) }) })