diff --git a/packages/dms-mailing/docs/1.introduction.md b/packages/dms-mailing/docs/1.introduction.md index 14531239..64a41b5b 100644 --- a/packages/dms-mailing/docs/1.introduction.md +++ b/packages/dms-mailing/docs/1.introduction.md @@ -43,7 +43,7 @@ A test send uses the draft by default and adds `[TEST]` to the subject. It appea The module stores templates and sends per workspace (tenant), in its own tables. E-mails render through the DMS html-render chain, so they share the DMS e-mail branding. If that renderer fails, the module falls back to its own HTML renderer. E-mails go out through the module that implements `@antelopejs/interface-email`, for example `@antelopejs/nodemailer`. -Other modules call the module through `@antelopejs/interface-dms-mailing`. They send with `SendTemplate` and report provider events with `RecordEmailEvent`. When a workspace is provisioned, they can also ship templates, categories, the sender and the webhook secret as code (`DeclareTemplate`, `DeclareTemplateCategory`, `DeclareSender`, `DeclareWebhookSecret`) and import past sends (`ImportSends`). +Other modules call the module through `@antelopejs/interface-dms-mailing`. They send with `SendTemplate`, attached files included, and report provider events with `RecordEmailEvent`. When a workspace is provisioned, they can also ship templates, categories, the sender and the webhook secret as code (`DeclareTemplate`, `DeclareTemplateCategory`, `DeclareSender`, `DeclareWebhookSecret`) and import past sends (`ImportSends`). ## Where it lives in the dashboard diff --git a/packages/dms-mailing/docs/5.extending.md b/packages/dms-mailing/docs/5.extending.md index 79cae385..27efd21e 100644 --- a/packages/dms-mailing/docs/5.extending.md +++ b/packages/dms-mailing/docs/5.extending.md @@ -37,6 +37,25 @@ Read `result.results` before you retry a recipient. For several recipients, the `content` sends an alternate body for an existing template without saving or publishing it. `isTest: true` marks a test send. Its subject starts with `[TEST] `, it uses the template's draft when there is one, and production figures leave it out. +### Attach files + +`attachments` sends files with the e-mail, such as the PDF of an invoice. Pass the bytes you already hold: + +```typescript fragment +const pdf = await readInvoicePdf(invoiceId); // a Buffer + +await SendTemplate("invoice-sent", { + tenantId, + to: "sofie@example.com", + variables: { invoice: { number: "2026-001" } }, + attachments: [{ filename: "invoice-2026-001.pdf", contentType: "application/pdf", content: pdf }], +}); +``` + +- Every recipient of the call gets the same files. A file name keeps its last path segment, without line breaks. +- A send carries at most 10 files, adding up to at most 10 MiB. Over that, the call rejects with `code` `attachments_too_large` before anything is sent or logged. +- **Mailing › Sends** lists each file's name and size, and keeps its SHA-256, never its bytes. A send with files cannot be sent again from the dashboard: send it again from your code. + ### Amounts and dates Pass an amount or a date as a value, and the e-mail writes it in the locale of the send. diff --git a/packages/dms-mailing/frontend-vue/app/components/SendDrawer.vue b/packages/dms-mailing/frontend-vue/app/components/SendDrawer.vue index 2851f3ba..600bea83 100644 --- a/packages/dms-mailing/frontend-vue/app/components/SendDrawer.vue +++ b/packages/dms-mailing/frontend-vue/app/components/SendDrawer.vue @@ -19,6 +19,7 @@ import { type SendActionId, } from '../utils/send-actions' import { renderingTitleKey } from '../utils/rendering-title' +import { formatFileSize, sentAttachments } from '../utils/attachments' import { formatLatency, isSlowLatency } from '../utils/send-stats' import { isSuppressedStatus, @@ -211,6 +212,10 @@ const stats = computed(() => { ] }) +const attachments = computed(() => + sentAttachments(send.value?.json_attachments), +) + const originTitle = computed(() => { const template = detail.value?.template const name = template?.name ?? send.value?.templateSlug ?? '' @@ -600,6 +605,19 @@ onMounted(() => { /> + + + {{ file.filename }} + + diff --git a/packages/dms-mailing/frontend-vue/app/types/mailing.ts b/packages/dms-mailing/frontend-vue/app/types/mailing.ts index 0a523f90..3d1cc96c 100644 --- a/packages/dms-mailing/frontend-vue/app/types/mailing.ts +++ b/packages/dms-mailing/frontend-vue/app/types/mailing.ts @@ -465,6 +465,8 @@ export interface SendRow { error?: string source?: string json_variables: string + /** The files it carried (`SentAttachment[]` as JSON); absent for most sends. */ + json_attachments?: string opens: number clicks: number createdAt: string diff --git a/packages/dms-mailing/frontend-vue/app/utils/attachments.ts b/packages/dms-mailing/frontend-vue/app/utils/attachments.ts new file mode 100644 index 00000000..e425f2e5 --- /dev/null +++ b/packages/dms-mailing/frontend-vue/app/utils/attachments.ts @@ -0,0 +1,35 @@ +/** A file a send carried, as the send log keeps it: never its bytes. */ +export interface SentAttachment { + filename: string + size: number +} + +const KILOBYTE = 1024 + +const isSentAttachment = (value: unknown): value is SentAttachment => + typeof value === 'object' && + value !== null && + 'filename' in value && + typeof value.filename === 'string' && + 'size' in value && + typeof value.size === 'number' + +/** The files of a send's `json_attachments`; none when absent or unreadable. */ +export function sentAttachments(json: string | undefined): SentAttachment[] { + if (!json) return [] + try { + const parsed: unknown = JSON.parse(json) + return Array.isArray(parsed) ? parsed.filter(isSentAttachment) : [] + } catch { + return [] + } +} + +/** `size` in kilobytes, at least one: "120 kB", "2,048 kB". */ +export const formatFileSize = (size: number, locale: string): string => + new Intl.NumberFormat(locale, { + style: 'unit', + unit: 'kilobyte', + unitDisplay: 'short', + maximumFractionDigits: 0, + }).format(Math.max(1, Math.round(size / KILOBYTE))) diff --git a/packages/dms-mailing/frontend-vue/app/utils/send-actions.ts b/packages/dms-mailing/frontend-vue/app/utils/send-actions.ts index 399cff6a..26557fe1 100644 --- a/packages/dms-mailing/frontend-vue/app/utils/send-actions.ts +++ b/packages/dms-mailing/frontend-vue/app/utils/send-actions.ts @@ -31,7 +31,7 @@ export interface DrawerSend extends SendRow { /** What decides a drawer's footer. */ export interface FooterSend extends Pick< DrawerSend, - 'status' | 'isSoftBounce' | 'replayedBy' + 'status' | 'isSoftBounce' | 'replayedBy' | 'json_attachments' > { /** * Whether the recipient is on the suppression list today; unknown until @@ -99,12 +99,14 @@ const ACTIONS_BY_STATUS: Partial> = { } /** - * Footers that win over the status: a send someone already sent again offers + * Footers that win over the status: a send that carried attachments cannot be + * repeated since the log keeps no file, a send someone already sent again offers * no second one, a temporary bounce (a full mailbox) may go to the same * address later, and so may a suppressed send once its address is * reactivated. */ const FOOTER_RULES: FooterRule[] = [ + { matches: (send) => !!send.json_attachments, actions: LOOK_ONLY }, { matches: (send) => !!send.replayedBy, actions: LOOK_ONLY }, { matches: (send) => send.status === 'bounced' && !!send.isSoftBounce, diff --git a/packages/dms-mailing/frontend-vue/i18n/locales/mailing-en-GB.json b/packages/dms-mailing/frontend-vue/i18n/locales/mailing-en-GB.json index 3e7cf437..3374ce9c 100644 --- a/packages/dms-mailing/frontend-vue/i18n/locales/mailing-en-GB.json +++ b/packages/dms-mailing/frontend-vue/i18n/locales/mailing-en-GB.json @@ -411,6 +411,7 @@ "no_replay_after_spam": "The recipient reported this e-mail as spam: it is not sent again.", "nothing_to_publish": "This template has no content to publish yet.", "replay_needs_new_address": "This address bounced. Send to a corrected address instead.", + "no_replay_with_attachments": "This e-mail carried attachments, which the send log does not keep. Send it again from the application that sent it.", "starter_not_found": "This starter template does not exist.", "template_in_use": "Only an archived template that was never sent can be deleted. Archive it instead.", "invalid_template": "The template name or slug is invalid.", diff --git a/packages/dms-mailing/frontend-vue/i18n/locales/mailing-fr-FR.json b/packages/dms-mailing/frontend-vue/i18n/locales/mailing-fr-FR.json index d17406e5..01ca6842 100644 --- a/packages/dms-mailing/frontend-vue/i18n/locales/mailing-fr-FR.json +++ b/packages/dms-mailing/frontend-vue/i18n/locales/mailing-fr-FR.json @@ -411,6 +411,7 @@ "no_replay_after_spam": "Le destinataire a signalé cet e-mail comme spam : il n’est pas renvoyé.", "nothing_to_publish": "Ce modèle n’a pas encore de contenu à publier.", "replay_needs_new_address": "Cette adresse a rebondi. Envoyez plutôt à une adresse corrigée.", + "no_replay_with_attachments": "Cet e-mail portait des pièces jointes, que le journal des envois ne garde pas. Renvoyez-le depuis l’application qui l’a envoyé.", "starter_not_found": "Ce modèle de départ n’existe pas.", "template_in_use": "Seul un modèle archivé et jamais envoyé peut être supprimé. Archivez-le plutôt.", "invalid_template": "Le nom ou le slug du modèle est invalide.", diff --git a/packages/dms-mailing/frontend-vue/tests/attachments.test.ts b/packages/dms-mailing/frontend-vue/tests/attachments.test.ts new file mode 100644 index 00000000..c810e0a9 --- /dev/null +++ b/packages/dms-mailing/frontend-vue/tests/attachments.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest' +import { formatFileSize, sentAttachments } from '../app/utils/attachments' + +const FILE = { filename: 'invoice.pdf', size: 120 } + +describe('sentAttachments', () => { + it('reads the files the send log kept', () => { + expect(sentAttachments(JSON.stringify([FILE]))).toEqual([FILE]) + }) + + it('reads nothing from an absent, broken or foreign value', () => { + expect(sentAttachments(undefined)).toEqual([]) + expect(sentAttachments('{not json')).toEqual([]) + expect(sentAttachments('{"filename":"a"}')).toEqual([]) + expect(sentAttachments('[{"filename":"a"}]')).toEqual([]) + }) +}) + +describe('formatFileSize', () => { + it('writes kilobytes, never zero', () => { + expect(formatFileSize(120, 'en')).toBe('1 kB') + expect(formatFileSize(2048, 'en')).toBe('2 kB') + }) +}) diff --git a/packages/dms-mailing/frontend-vue/tests/send-actions.test.ts b/packages/dms-mailing/frontend-vue/tests/send-actions.test.ts index 004a29ec..6dd41c94 100644 --- a/packages/dms-mailing/frontend-vue/tests/send-actions.test.ts +++ b/packages/dms-mailing/frontend-vue/tests/send-actions.test.ts @@ -64,6 +64,18 @@ describe('sendFooterActions', () => { expect(actions.map((action) => action.id)).not.toContain('fix_address') }) + it('offers no send again of a send whose files the log does not keep', () => { + const json = + '[{"filename":"a.pdf","contentType":"application/pdf","size":3,"sha256":"ab"}]' + for (const status of ['failed', 'bounced', 'sent'] as const) { + const actions = sendFooterActions({ status, json_attachments: json }) + expect(actions.map((action) => action.id)).toEqual([ + 'rendering', + 'copy_address', + ]) + } + }) + it('always offers the rendering', () => { for (const status of SEND_STATUSES) expect(ids(status)).toContain('rendering') diff --git a/packages/dms-mailing/frontend-vue/tests/send-drawer.test.ts b/packages/dms-mailing/frontend-vue/tests/send-drawer.test.ts index a8fa76e4..c2e70caf 100644 --- a/packages/dms-mailing/frontend-vue/tests/send-drawer.test.ts +++ b/packages/dms-mailing/frontend-vue/tests/send-drawer.test.ts @@ -42,8 +42,8 @@ const STUBS = Object.fromEntries( STUB_NAMES.map((name) => [name, slotStub(name)]), ) -async function render(): Promise { - const { host } = mount(SendDrawer, { rowData: SEND }, STUBS) +async function render(row: SendRow = SEND): Promise { + const { host } = mount(SendDrawer, { rowData: row }, STUBS) await flush() return host } @@ -116,4 +116,30 @@ describe('send drawer layout', () => { expect(row?.getAttribute('meta')).toContain('source') expect(row?.textContent).toContain(SEND.source) }) + + it('lists the files a send carried', async () => { + const row: SendRow = { + ...SEND, + json_attachments: JSON.stringify([ + { + filename: 'invoice-001.pdf', + contentType: 'application/pdf', + size: 2048, + sha256: 'a'.repeat(64), + }, + ]), + } + stubApiData().respond( + mailingReads({ send: () => ({ send: row, events: [] }) }), + ) + const host = await render(row) + const listed = host.querySelector('[data-send-attachment]') + expect(listed?.textContent).toContain('invoice-001.pdf') + expect(listed?.getAttribute('meta')).toContain('2 kB') + }) + + it('shows no attachment section for a send without files', async () => { + const host = await render() + expect(host.querySelector('[data-send-attachment]')).toBeNull() + }) }) diff --git a/packages/dms-mailing/skills/dms-mailing/SKILL.md b/packages/dms-mailing/skills/dms-mailing/SKILL.md index e7d97ba7..4acfb498 100644 --- a/packages/dms-mailing/skills/dms-mailing/SKILL.md +++ b/packages/dms-mailing/skills/dms-mailing/SKILL.md @@ -51,6 +51,9 @@ const result = await SendTemplate("order-confirmed", { the template; pass every required one. - Don't pre-format amounts and dates per locale: pass `{ value: 987420, currency: "EUR" }` (minor units) or a `Date`, or an ISO string at a `date` path; the send locale formats them. Plain strings print as given. +- Files: `attachments: [{ filename, contentType?, content: Buffer }]`, the same for every recipient; at most 10 files + and 10 MiB, else `error.code` = `attachments_too_large` before anything is sent. The log keeps name, type, size and + SHA-256, never the bytes, so the dashboard cannot send it again (409 `no_replay_with_attachments`): resend from code. - In-process events: `RecordEmailEvent(tenantId, { provider, messageId, type, details })`. HTTP: `POST /api/mailing/events//` with header `x-mailing-webhook-secret`. - Automation (if `interface-dms-automation` is loaded): action `mailing.send-template`, trigger `mailing.email-event`. diff --git a/packages/dms-mailing/src/db/tables/sends.table.ts b/packages/dms-mailing/src/db/tables/sends.table.ts index aef29f53..ea24e580 100644 --- a/packages/dms-mailing/src/db/tables/sends.table.ts +++ b/packages/dms-mailing/src/db/tables/sends.table.ts @@ -76,6 +76,10 @@ export class MailingSend extends Table { @Field("string") declare json_variables: string; + /** JSON list of the name, type, size and SHA-256 of each file the e-mail carried; absent for most sends. */ + @Field("string") + declare json_attachments?: string; + @Field("number") declare opens: number; diff --git a/packages/dms-mailing/src/routes/sends.ts b/packages/dms-mailing/src/routes/sends.ts index 319445b0..96771844 100644 --- a/packages/dms-mailing/src/routes/sends.ts +++ b/packages/dms-mailing/src/routes/sends.ts @@ -45,7 +45,8 @@ import { type CheckedSendParams, sendUnlessSuppressed, } from "../services/checked-send"; -import { MANUAL_SEND_SOURCE, SendError, subjectFor } from "../services/send"; +import { MANUAL_SEND_SOURCE, subjectFor } from "../services/send"; +import { SendError } from "../services/send-error"; import { buildSendStats, isTransportFailure, @@ -87,6 +88,8 @@ const REPLAY_SKIPPED = "$dms_mailing.sends.banner.replay_skipped"; const RECIPIENT_FIELD = "to"; const NEEDS_NEW_ADDRESS = "$dms_mailing.errors.replay_needs_new_address"; const NO_REPLAY_AFTER_SPAM = "$dms_mailing.errors.no_replay_after_spam"; +const NO_REPLAY_WITH_ATTACHMENTS = + "$dms_mailing.errors.no_replay_with_attachments"; const TEST_SEND_SOURCE = "dms-mailing:test-send"; const REPLAY_SOURCE = "dms-mailing:replay"; const FIX_ADDRESS_SOURCE = "dms-mailing:fix-address"; @@ -522,6 +525,7 @@ export class SendsController extends Controller(API_BASE_PATH) { to: string | undefined, source: string, ): Promise { + assert(!send.json_attachments, HTTP_CONFLICT, NO_REPLAY_WITH_ATTACHMENTS); const template = await requireTemplate(this.templates, send.templateId); const version = send.templateVersion; const content = diff --git a/packages/dms-mailing/src/services/attachments.ts b/packages/dms-mailing/src/services/attachments.ts new file mode 100644 index 00000000..5ce35b2f --- /dev/null +++ b/packages/dms-mailing/src/services/attachments.ts @@ -0,0 +1,53 @@ +import { createHash } from "node:crypto"; +import type { BufferAttachment } from "@antelopejs/interface-email"; +import type { SendAttachment } from "@antelopejs/interface-dms-mailing"; +import { SendError } from "./send-error"; + +/** Most files one send carries. */ +export const MAX_ATTACHMENTS = 10; +/** Most bytes the files of one send add up to: base64 grows them by a third, under the 20 MB most mail servers accept. */ +export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024; + +const PATH_SEPARATORS = /[\\/]/; +const LINE_BREAKS = /[\r\n]/g; + +/** + * The files as the email interface takes them, each name cut to its last path + * segment without line breaks; absent for a send without any. Over + * {@link MAX_ATTACHMENTS} or {@link MAX_ATTACHMENT_BYTES}, it throws + * `attachments_too_large`. + */ +export function checkAttachments( + input: readonly SendAttachment[] | undefined, +): BufferAttachment[] | undefined { + if (!input?.length) return undefined; + const total = input.reduce((sum, file) => sum + file.content.byteLength, 0); + if (input.length > MAX_ATTACHMENTS || total > MAX_ATTACHMENT_BYTES) + throw new SendError( + "attachments_too_large", + `${input.length} files of ${total} bytes, at most ${MAX_ATTACHMENTS} files of ${MAX_ATTACHMENT_BYTES} bytes`, + ); + return input.map(({ filename, contentType, content }) => ({ + filename: (filename.split(PATH_SEPARATORS).pop() ?? "").replace( + LINE_BREAKS, + "", + ), + contentType, + content: Buffer.from(content), + })); +} + +/** What the send log keeps of the files: name, type, size and SHA-256, never the bytes. */ +export function attachmentsLog( + files: readonly BufferAttachment[] | undefined, +): string | undefined { + if (!files) return undefined; + return JSON.stringify( + files.map(({ filename, contentType, content }) => ({ + filename, + contentType, + size: content.byteLength, + sha256: createHash("sha256").update(content).digest("hex"), + })), + ); +} diff --git a/packages/dms-mailing/src/services/send-error.ts b/packages/dms-mailing/src/services/send-error.ts new file mode 100644 index 00000000..c68c0003 --- /dev/null +++ b/packages/dms-mailing/src/services/send-error.ts @@ -0,0 +1,9 @@ +/** Why a send was refused before anything left: `code` names the rule. */ +export class SendError extends Error { + constructor( + public readonly code: string, + message: string, + ) { + super(message); + } +} diff --git a/packages/dms-mailing/src/services/send.ts b/packages/dms-mailing/src/services/send.ts index 23b2b1db..d9af6824 100644 --- a/packages/dms-mailing/src/services/send.ts +++ b/packages/dms-mailing/src/services/send.ts @@ -2,6 +2,7 @@ import { type BatchEmailMessageResponse, type BatchEmailParams, type BatchEmailResponse, + type BufferAttachment, type EmailAddress, type EmailParams, type EmailResponse, @@ -38,7 +39,9 @@ import { type TemplateContent, } from "../types"; import { publishSendCreated } from "../realtime"; +import { attachmentsLog, checkAttachments } from "./attachments"; import { renderEmailHtml } from "./render"; +import { SendError } from "./send-error"; import { getSettings } from "./settings"; import { toSendStatus } from "./status"; import { refreshAttentionIfFlagged } from "./template-attention"; @@ -54,15 +57,6 @@ import { } from "./templates"; import { isText } from "../validation/guards"; -export class SendError extends Error { - constructor( - public readonly code: string, - message: string, - ) { - super(message); - } -} - export interface PreparedSend { content: TemplateContent; locale: string; @@ -79,6 +73,8 @@ export interface PreparedSend { category: string; /** Why the template needed a look when the send started. */ attention: string; + /** The files every recipient gets; absent for most sends. */ + attachments?: BufferAttachment[]; } /** @@ -273,6 +269,7 @@ export async function prepare( if (missing.length) { throw new SendError("missing_variables", missing.join(", ")); } + const attachments = checkAttachments(params.attachments); const { content, version, variables } = resolveContent(template, params); const settings = await getSettings(tenantId); const locale = pickLocale(content, params.locale, settings.fallbackLocale); @@ -287,6 +284,7 @@ export async function prepare( tenantId, category: template.category ?? "", attention: template.attention, + attachments, }; } @@ -315,6 +313,7 @@ export function messageFor( templateSlug: prepared.slug, }, tracking: { opens: true, clicks: true }, + attachments: prepared.attachments, }; } @@ -460,6 +459,7 @@ async function record( error: outcome.error, source: params.source, json_variables: JSON.stringify(params.variables ?? {}), + json_attachments: attachmentsLog(prepared.attachments), opens: 0, clicks: 0, isTest: Boolean(params.isTest), diff --git a/packages/dms-mailing/src/test/integration/send-attachments.test.ts b/packages/dms-mailing/src/test/integration/send-attachments.test.ts new file mode 100644 index 00000000..4fcde1a8 --- /dev/null +++ b/packages/dms-mailing/src/test/integration/send-attachments.test.ts @@ -0,0 +1,154 @@ +import { createHash } from "node:crypto"; +import { expect } from "chai"; +import { z } from "zod"; +import { DEFAULT_TENANT_ID } from "@antelopejs/interface-dms/constants"; +import { GetModel } from "@antelopejs/interface-database-decorators"; +import { SendModel } from "../../db"; +import { suppressAddress } from "../../services/suppressions"; +import { declaration, mailing } from "../helpers/declarations"; +import { authorizedClient } from "../helpers/http"; +import { ensureOwnerSession } from "../helpers/owner"; +import { MAX_ATTACHMENT_BYTES } from "../../services/attachments"; +import { capturedMail, rawMail } from "../helpers/mail-store"; + +const HTTP_CONFLICT = 409; +const stamp = Date.now(); +const slug = `attachments-${stamp}`; +const VARIABLES = { customer: { firstName: "Sofie" } }; +/** Unique bytes, so the test finds its own message among the fixture's. */ +const PDF = Buffer.from(`%PDF-1.7 invoice ${stamp}`); +const SHA256 = createHash("sha256").update(PDF).digest("hex"); + +const summarySchema = z.array( + z.object({ + filename: z.string(), + contentType: z.string(), + size: z.number(), + sha256: z.string(), + }), +); + +const invoice = { + filename: "../archive/invoice-001.pdf\r\nX-Injected: yes", + contentType: "application/pdf", + content: PDF, +}; + +async function loggedAttachments(sendId: string) { + const send = await GetModel(SendModel, DEFAULT_TENANT_ID).get(sendId); + return summarySchema.parse(JSON.parse(send?.json_attachments ?? "null")); +} + +const EXPECTED_SUMMARY = [ + { + filename: "invoice-001.pdfX-Injected: yes", + contentType: "application/pdf", + size: PDF.byteLength, + sha256: SHA256, + }, +]; + +describe("[integration] sends with attachments", () => { + before(async () => { + const { DeclareTemplate } = await mailing(); + await DeclareTemplate(declaration(slug)); + }); + + it("delivers the file over SMTP and logs its name, size and hash only", async () => { + const { SendTemplate } = await mailing(); + const result = await SendTemplate(slug, { + tenantId: DEFAULT_TENANT_ID, + to: [`first-${stamp}@example.test`, `second-${stamp}@example.test`], + variables: VARIABLES, + attachments: [invoice], + }); + + const results = result.results ?? []; + expect(results.map((entry) => entry.status)).to.deep.equal([ + "sent", + "sent", + ]); + for (const entry of results) + expect(await loggedAttachments(entry.sendId)).to.deep.equal( + EXPECTED_SUMMARY, + ); + const send = await GetModel(SendModel, DEFAULT_TENANT_ID).get( + result.sendId, + ); + expect(send?.json_attachments).to.not.contain(PDF.toString("base64")); + + const mine = capturedMail() + .map(rawMail) + .filter((message) => message.includes(PDF.toString("base64"))); + expect(mine).to.have.length(2); + expect(mine[0]).to.match(/Content-Type: application\/pdf/i); + expect(mine[0]).to.contain("invoice-001.pdf"); + expect(mine[0]).to.not.contain("archive"); + expect(mine[0]).to.not.match(/^X-Injected:/m); + }); + + it("logs the files of a suppressed recipient without sending them", async () => { + const { SendTemplate } = await mailing(); + const address = `suppressed-${stamp}@example.test`; + await suppressAddress(DEFAULT_TENANT_ID, { + email: address, + reason: "manual", + }); + const result = await SendTemplate(slug, { + tenantId: DEFAULT_TENANT_ID, + to: address, + variables: VARIABLES, + attachments: [invoice], + }); + + expect(result.status).to.equal("suppressed"); + expect(await loggedAttachments(result.sendId)).to.deep.equal( + EXPECTED_SUMMARY, + ); + }); + + it("refuses a file over the ceiling before anything is logged", async () => { + const { SendTemplate } = await mailing(); + const address = `too-large-${stamp}@example.test`; + const refusal = await SendTemplate(slug, { + tenantId: DEFAULT_TENANT_ID, + to: address, + variables: VARIABLES, + attachments: [ + { + filename: "huge.bin", + content: Buffer.alloc(MAX_ATTACHMENT_BYTES + 1), + }, + ], + }).catch((error: unknown) => error); + + expect(refusal).to.have.property("code", "attachments_too_large"); + const logged = await GetModel(SendModel, DEFAULT_TENANT_ID).getBy( + "recipientEmail", + address, + ); + expect(logged).to.have.length(0); + }); + + it("refuses to send again a send whose files the log does not keep", async () => { + const { SendTemplate } = await mailing(); + const sent = await SendTemplate(slug, { + tenantId: DEFAULT_TENANT_ID, + to: `replay-${stamp}@example.test`, + variables: VARIABLES, + attachments: [invoice], + }); + const session = await ensureOwnerSession(); + const client = authorizedClient(session.accessToken); + + const replay = await client.post( + `/api/mailing/sends/${sent.sendId}/replay`, + {}, + ); + + expect(replay.status, JSON.stringify(replay.data)).to.equal(HTTP_CONFLICT); + expect(JSON.stringify(replay.data)).to.contain( + "$dms_mailing.errors.no_replay_with_attachments", + ); + }); +}); diff --git a/packages/interface-dms-mailing/docs/1.index.md b/packages/interface-dms-mailing/docs/1.index.md index 0ee1b7d4..0ce98dee 100644 --- a/packages/interface-dms-mailing/docs/1.index.md +++ b/packages/interface-dms-mailing/docs/1.index.md @@ -46,6 +46,13 @@ interface SendTemplateParams { content?: TemplateContent; source?: string; isTest?: boolean; + attachments?: SendAttachment[]; +} + +interface SendAttachment { + filename: string; + contentType?: string; + content: Uint8Array; // a Buffer is one } interface SendTemplateResult { @@ -79,10 +86,12 @@ A suppressed address gets no e-mail. Its result has `status: "suppressed"` and a Provider failures become `failed` recipient results. If recording a send fails, its result has `sendId: ""`, `status: "failed"` and an error, and can still carry a provider `messageId`, because delivery may have happened. A `failed` result does not prove that no e-mail left, and retrying the whole call can deliver twice. -Validation failures reject the promise instead of returning recipient results. The runtime's errors carry one of these codes: `no_recipient`, `template_not_found`, `template_not_live`, `invalid_content` or `missing_variables`. The interface does not export the error class. The workspace's **Missing variables** setting decides whether missing variables refuse a send. Marketing footer URLs are required system variables when the template uses them, never for test sends. Storage or notification failures can reject after side effects started, so the call is neither transactional nor idempotent. +Validation failures reject the promise instead of returning recipient results. The runtime's errors carry one of these codes: `no_recipient`, `template_not_found`, `template_not_live`, `invalid_content`, `missing_variables` or `attachments_too_large`. The interface does not export the error class. The workspace's **Missing variables** setting decides whether missing variables refuse a send. Marketing footer URLs are required system variables when the template uses them, never for test sends. Storage or notification failures can reject after side effects started, so the call is neither transactional nor idempotent. `variables` is `TemplateVariables`, a record of strings, numbers, booleans, `null`, `Date` values, money values (`{ value: 987420, currency: "EUR" }`, in the currency's minor unit), and lists and records of the same. Dates and money are written in the send's locale. A class instance or a function does not compile, and a template path reads only the keys a record owns. +`attachments` sends files with the e-mail, the same for every recipient of the call. `content` holds the bytes the caller already read. The module keeps the last path segment of `filename`, without line breaks, and passes the files to the `@antelopejs/interface-email` provider. A call carries at most 10 files adding up to at most 10 MiB, or it rejects with `attachments_too_large` before anything is sent or logged. The send log keeps each file's name, type, size and SHA-256 (`json_attachments`), never its bytes, so the dashboard refuses to send it again (`409`, `no_replay_with_attachments`): the caller, which holds the files, sends it again. + ## `RecordEmailEvent` ```ts [Contract] diff --git a/packages/interface-dms-mailing/src/index.ts b/packages/interface-dms-mailing/src/index.ts index e2a51d69..4e2a8a86 100644 --- a/packages/interface-dms-mailing/src/index.ts +++ b/packages/interface-dms-mailing/src/index.ts @@ -171,6 +171,22 @@ export interface VariableDefinition { required: boolean; } +/** + * A file a send carries, as bytes the caller already holds. Every recipient of + * the call gets the same files. + */ +export interface SendAttachment { + /** + * The name the recipient sees: the module keeps its last path segment, + * without line breaks. + */ + filename: string; + /** The MIME type (`application/pdf`); the provider guesses it when absent. */ + contentType?: string; + /** The file's bytes; a `Buffer` is one. */ + content: Uint8Array; +} + /** Parameters of a template send triggered from application code. */ export interface SendTemplateParams { tenantId: string; @@ -180,6 +196,13 @@ export interface SendTemplateParams { content?: TemplateContent; source?: string; isTest?: boolean; + /** + * Files the e-mail carries: at most 10, adding up to at most 10 MiB, or the + * send rejects with `code` `attachments_too_large`. The send log keeps their + * names, types, sizes and SHA-256 hashes, never their bytes, so a send with + * attachments cannot be sent again from the dashboard. + */ + attachments?: SendAttachment[]; } /**