From 72cc0d7f814c0502a901dd426c0808ce88cc65f9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 09:16:56 +0000 Subject: [PATCH 1/2] fix(plugin-email): refuse a malformed recipient address as VALIDATION_FAILED A malformed caller-supplied address in to / cc / bcc / replyTo threw a plain `Invalid email address` error from normalizeMessage, which the REST send door maps to 500 EMAIL_SEND_FAILED. It now throws `VALIDATION_FAILED: invalid recipient address in FIELD: ADDRESS`, the prefix the door already answers with 400. The configured sender keeps the plain throw: an unsendable `from` is a server fault, not the caller's. Claude-Session: https://claude.ai/code/session_01ADHkmRW6HXmiYEciBx61dj Co-authored-by: Claude --- .../29152-email-recipient-validation-400.md | 13 ++++ .../plugin-email/src/email-service.test.ts | 63 +++++++++++++++++++ .../plugins/plugin-email/src/email-service.ts | 49 ++++++++++++--- .../rest/src/email-send-door-bounds.test.ts | 56 +++++++++++++++++ 4 files changed, 174 insertions(+), 7 deletions(-) create mode 100644 .changeset/29152-email-recipient-validation-400.md diff --git a/.changeset/29152-email-recipient-validation-400.md b/.changeset/29152-email-recipient-validation-400.md new file mode 100644 index 00000000000..1dec30921c0 --- /dev/null +++ b/.changeset/29152-email-recipient-validation-400.md @@ -0,0 +1,13 @@ +--- +'@objectstack/plugin-email': patch +--- + +fix(plugin-email): a malformed recipient address is the caller's `400 VALIDATION_FAILED`, not a `500` (#29152) + +Clause-②: no +Metadata-protocol: none + +- A malformed address in `to`, `cc`, `bcc` or `replyTo` (an empty `to` string and one bad member of a list included) is now refused by `normalizeMessage` as `VALIDATION_FAILED: invalid recipient address in FIELD: ADDRESS` (`invalid reply-to address` for `replyTo`). `POST /api/v1/email/send` already answers that prefix with `400 { code: 'VALIDATION_FAILED' }`, so a caller-correctable input no longer answers `500 EMAIL_SEND_FAILED`. +- An unsendable configured sender (`OS_EMAIL_FROM`, Settings → Mail → From address) keeps its plain `Invalid email address` error and stays a server-side fault: it is not the caller's to fix. +- Unchanged: the refused send still writes its `sys_email` row at `failed`, and internal senders (template sends, auth mail, messaging) still see the send reject. +- Nothing to do: no metadata, protocol or configuration changes. diff --git a/packages/plugins/plugin-email/src/email-service.test.ts b/packages/plugins/plugin-email/src/email-service.test.ts index 00e9184e193..06dde490543 100644 --- a/packages/plugins/plugin-email/src/email-service.test.ts +++ b/packages/plugins/plugin-email/src/email-service.test.ts @@ -53,6 +53,69 @@ describe('normalizeMessage', () => { }); }); +describe('normalizeMessage — a malformed CALLER address is the caller\'s VALIDATION_FAILED', () => { + const FROM = 'no-reply@example.test'; + const base = { subject: 'Hi', text: 'x' }; + const refusal = (input: Record) => { + try { + normalizeMessage({ ...base, ...input } as any, FROM); + } catch (err) { + return String((err as Error).message); + } + throw new Error('expected normalizeMessage to refuse the input'); + }; + + it.each([ + ['a malformed `to`', { to: 'not-an-email' }, 'invalid recipient address in `to`: not-an-email'], + ['an empty `to` string', { to: '' }, 'invalid recipient address in `to`: (empty)'], + ['one bad member of a `to` list', { to: ['a@b.com', 'nope'] }, 'invalid recipient address in `to`: nope'], + ['an object `to` with a bad address', { to: { name: 'A', address: 'a@localhost' } }, 'invalid recipient address in `to`: a@localhost'], + ['a malformed `cc`', { to: 'a@b.com', cc: 'bad cc' }, 'invalid recipient address in `cc`: bad cc'], + ['a malformed `bcc`', { to: 'a@b.com', bcc: ['c@d.com', 'x@'] }, 'invalid recipient address in `bcc`: x@'], + ['a malformed `replyTo`', { to: 'a@b.com', replyTo: 'reply' }, 'invalid reply-to address in `replyTo`: reply'], + ])('%s is refused VALIDATION_FAILED, naming the field', (_label, input, reason) => { + expect(refusal(input)).toBe(`VALIDATION_FAILED: ${reason}`); + }); + + it('a malformed CONFIGURED sender is NOT a VALIDATION_FAILED — it is the server\'s fault, not the caller\'s', () => { + let message = ''; + try { + normalizeMessage({ to: 'a@b.com', ...base }, { name: 'ObjectOS Local', address: 'noreply@localhost' }); + } catch (err) { + message = String((err as Error).message); + } + expect(message).toBe('Invalid email address: noreply@localhost'); + expect(message.startsWith('VALIDATION_FAILED')).toBe(false); + }); + + it('well-formed caller addresses in every field still normalize', () => { + const msg = normalizeMessage( + { ...base, to: ['a@b.com'], cc: 'c@d.com', bcc: { name: 'B', address: 'b@c.com' }, replyTo: 'r@s.com' }, + FROM, + ); + expect(msg).toMatchObject({ to: ['a@b.com'], cc: ['c@d.com'], bcc: ['B '], replyTo: 'r@s.com' }); + }); + + it('EmailService.send rejects the same way, delivers nothing, and still records the rejection row', async () => { + const rows: Array> = []; + const persistence: EmailPersistence = { + async insert(row) { rows.push({ ...row }); return { id: row.id }; }, + async update() { /* no-op */ }, + }; + const transport = { send: vi.fn(async () => ({ messageId: '' })) }; + const svc = new EmailService({ transport, defaultFrom: FROM, persistence }); + + await expect(svc.send({ to: ['a@b.com', 'nope'], ...base })) + .rejects.toThrow(/^VALIDATION_FAILED: invalid recipient address in `to`: nope$/); + expect(transport.send).not.toHaveBeenCalled(); + // Unchanged by the reclassification: a pre-delivery refusal is still an + // audit row at `failed`, never a re-deliverable `queued` one. + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ status: 'failed', attempt_count: 0 }); + expect(String(rows[0].error)).toContain('invalid recipient address in `to`: nope'); + }); +}); + describe('LogTransport', () => { it('returns a synthetic Message-ID and logs', async () => { const logger = { info: vi.fn() }; diff --git a/packages/plugins/plugin-email/src/email-service.ts b/packages/plugins/plugin-email/src/email-service.ts index 96e7d9e8efb..305c5dc3743 100644 --- a/packages/plugins/plugin-email/src/email-service.ts +++ b/packages/plugins/plugin-email/src/email-service.ts @@ -296,15 +296,50 @@ export function formatAddress(addr: EmailAddress): string { return `${quoted} <${address}>`; } -function listToArray(v: EmailAddress | EmailAddress[] | undefined): string[] | undefined { +/** + * The message fields whose addresses the CALLER supplies — every one of them + * is the caller's to correct, so a malformed address in any of them is the + * caller's `VALIDATION_FAILED`, never a server fault. + */ +type CallerAddressField = 'to' | 'cc' | 'bcc' | 'replyTo'; + +/** + * {@link formatAddress} for an address the CALLER supplied: the same + * acceptance ({@link isSendableAddress}, one spelling of "valid enough to + * send"), refused as `VALIDATION_FAILED: invalid recipient address …` naming + * the field, so the REST send door answers 400 — the caller can fix it — + * instead of 500 `EMAIL_SEND_FAILED`. + * + * The SENDER deliberately stays on {@link formatAddress}'s plain + * `Invalid email address` throw: `from` is the deployment's configured sender + * (`OS_EMAIL_FROM`, the `mail` settings, or a caller `from` the REST door has + * already bound to that same configured value), so an unsendable one is a + * server-side fault that a 400 would wrongly pin on the caller. + */ +function formatCallerAddress(addr: EmailAddress, field: CallerAddressField): string { + if (!isSendableAddress(addr)) { + const what = field === 'replyTo' ? 'reply-to address' : 'recipient address'; + const shown = addr == null ? '' : addressPart(addr); + throw new Error(`VALIDATION_FAILED: invalid ${what} in \`${field}\`: ${shown || '(empty)'}`); + } + return formatAddress(addr); +} + +function listToArray( + v: EmailAddress | EmailAddress[] | undefined, + field: Exclude, +): string[] | undefined { if (v === undefined) return undefined; const arr = Array.isArray(v) ? v : [v]; - return arr.map(formatAddress); + return arr.map((addr) => formatCallerAddress(addr, field)); } /** * Validate input + apply default-from + canonicalize recipients. - * Throws Error('VALIDATION_FAILED: ') for malformed payloads. + * Throws Error('VALIDATION_FAILED: REASON') for malformed payloads — a + * malformed caller-supplied address (`to` / `cc` / `bcc` / `replyTo`) + * included. An unsendable `from` is the one malformed address that is NOT a + * `VALIDATION_FAILED`: see {@link formatCallerAddress}. */ export function normalizeMessage( input: SendEmailInput, @@ -318,7 +353,7 @@ export function normalizeMessage( if (!input.text && !input.html) { throw new Error('VALIDATION_FAILED: at least one of text or html is required'); } - const toArr = listToArray(input.to); + const toArr = listToArray(input.to, 'to'); if (!toArr || toArr.length === 0) { throw new Error('VALIDATION_FAILED: at least one recipient (to) is required'); } @@ -335,11 +370,11 @@ export function normalizeMessage( ...(input.text !== undefined ? { text: input.text } : {}), ...(input.html !== undefined ? { html: input.html } : {}), }; - const cc = listToArray(input.cc); + const cc = listToArray(input.cc, 'cc'); if (cc && cc.length > 0) msg.cc = cc; - const bcc = listToArray(input.bcc); + const bcc = listToArray(input.bcc, 'bcc'); if (bcc && bcc.length > 0) msg.bcc = bcc; - if (input.replyTo) msg.replyTo = formatAddress(input.replyTo); + if (input.replyTo) msg.replyTo = formatCallerAddress(input.replyTo, 'replyTo'); if (input.attachments && input.attachments.length > 0) msg.attachments = input.attachments; if (input.headers && Object.keys(input.headers).length > 0) msg.headers = input.headers; return msg; diff --git a/packages/rest/src/email-send-door-bounds.test.ts b/packages/rest/src/email-send-door-bounds.test.ts index 688cb57e431..6ca65d0c02f 100644 --- a/packages/rest/src/email-send-door-bounds.test.ts +++ b/packages/rest/src/email-send-door-bounds.test.ts @@ -143,6 +143,62 @@ describe('POST /api/v1/email/send — the capability', () => { }); }); +describe('POST /api/v1/email/send — a malformed recipient is the caller\'s 400, never a 500', () => { + /** + * A service whose `send` refuses the way `@objectstack/plugin-email`'s + * `normalizeMessage` does: a malformed caller-supplied address is a + * `VALIDATION_FAILED: invalid recipient address in FIELD: ADDRESS` throw + * (that producer's own suite pins the exact text per field), and a + * malformed CONFIGURED sender is the plain `Invalid email address` throw — + * a server fault. This file pins the door half: what each answers on the wire. + */ + function refusingDouble(refusal?: string) { + const send = vi.fn(async (_input: SendEmailInput) => { + if (refusal !== undefined) throw new Error(refusal); + return { id: 'eml_1', status: 'sent' as const, messageId: 'm1' }; + }); + const service: Partial = { send, getDefaultFrom: () => CONFIGURED }; + return { service, send }; + } + + it.each([ + ['a malformed `to`', { to: 'not-an-email' }, 'invalid recipient address in `to`: not-an-email'], + ['an empty `to`', { to: '' }, 'invalid recipient address in `to`: (empty)'], + ['a `to` list with one bad member', { to: ['ok@example.org', 'nope'] }, 'invalid recipient address in `to`: nope'], + ['a malformed `cc`', { cc: 'bad cc' }, 'invalid recipient address in `cc`: bad cc'], + ])('%s answers 400 VALIDATION_FAILED naming the address', async (_label, fields, reason) => { + const { service, send } = refusingDouble(`VALIDATION_FAILED: ${reason}`); + const { post } = boot({ service, ctx: ADMIN }); + const out = await post({ ...MESSAGE, ...fields }); + + expect(out.status).toBe(400); + expect(out.body.code).toBe('VALIDATION_FAILED'); + expect(out.body.error).toBe(reason); + // The door forwarded the caller's addresses untouched — the refusal is the service's verdict on them. + expect(send).toHaveBeenCalledTimes(1); + expect(send.mock.calls[0][0]).toMatchObject(fields); + }); + + it('a well-formed send through the same service still answers 200', async () => { + const { service, send } = refusingDouble(); + const { post } = boot({ service, ctx: ADMIN }); + const out = await post({ ...MESSAGE, cc: ['cc@example.org'] }); + + expect(out.status).toBe(200); + expect(out.body).toMatchObject({ status: 'sent', id: 'eml_1' }); + expect(send).toHaveBeenCalledTimes(1); + }); + + it('a malformed CONFIGURED sender stays a server fault: 500 EMAIL_SEND_FAILED, not a 400 that blames the caller', async () => { + const { service } = refusingDouble('Invalid email address: noreply@localhost'); + const { post } = boot({ service, ctx: ADMIN }); + const out = await post(MESSAGE); + + expect(out.status).toBe(500); + expect(out.body.code).toBe('EMAIL_SEND_FAILED'); + }); +}); + describe('POST /api/v1/email/send — `sentBy` is the authenticated caller', () => { it('a body naming another user as `sentBy` is refused 403, and nothing is sent', async () => { const { service, send } = emailDouble(); From a53fb69fa6d6541877866ffa1cab9eae7b8902a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 09:56:12 +0000 Subject: [PATCH 2/2] fix(plugin-email): refuse a non-string display name on a caller address A JSON body can put any value in a recipient's `name`; a non-string one failed inside formatAddress as a TypeError, which the REST send door answers 500. It is now the same VALIDATION_FAILED refusal as a malformed recipient address. Claude-Session: https://claude.ai/code/session_01ADHkmRW6HXmiYEciBx61dj Co-authored-by: Claude --- .changeset/29152-email-recipient-validation-400.md | 1 + .../plugins/plugin-email/src/email-service.test.ts | 5 +++++ packages/plugins/plugin-email/src/email-service.ts | 11 ++++++++++- 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/.changeset/29152-email-recipient-validation-400.md b/.changeset/29152-email-recipient-validation-400.md index 1dec30921c0..a6d0b936c1f 100644 --- a/.changeset/29152-email-recipient-validation-400.md +++ b/.changeset/29152-email-recipient-validation-400.md @@ -9,5 +9,6 @@ Metadata-protocol: none - A malformed address in `to`, `cc`, `bcc` or `replyTo` (an empty `to` string and one bad member of a list included) is now refused by `normalizeMessage` as `VALIDATION_FAILED: invalid recipient address in FIELD: ADDRESS` (`invalid reply-to address` for `replyTo`). `POST /api/v1/email/send` already answers that prefix with `400 { code: 'VALIDATION_FAILED' }`, so a caller-correctable input no longer answers `500 EMAIL_SEND_FAILED`. - An unsendable configured sender (`OS_EMAIL_FROM`, Settings → Mail → From address) keeps its plain `Invalid email address` error and stays a server-side fault: it is not the caller's to fix. +- A display name that is not a string (a JSON body can carry any value there) is refused the same way instead of failing as a `TypeError` (500). - Unchanged: the refused send still writes its `sys_email` row at `failed`, and internal senders (template sends, auth mail, messaging) still see the send reject. - Nothing to do: no metadata, protocol or configuration changes. diff --git a/packages/plugins/plugin-email/src/email-service.test.ts b/packages/plugins/plugin-email/src/email-service.test.ts index 06dde490543..9870d1eebc1 100644 --- a/packages/plugins/plugin-email/src/email-service.test.ts +++ b/packages/plugins/plugin-email/src/email-service.test.ts @@ -73,6 +73,11 @@ describe('normalizeMessage — a malformed CALLER address is the caller\'s VALID ['a malformed `cc`', { to: 'a@b.com', cc: 'bad cc' }, 'invalid recipient address in `cc`: bad cc'], ['a malformed `bcc`', { to: 'a@b.com', bcc: ['c@d.com', 'x@'] }, 'invalid recipient address in `bcc`: x@'], ['a malformed `replyTo`', { to: 'a@b.com', replyTo: 'reply' }, 'invalid reply-to address in `replyTo`: reply'], + [ + 'a non-string display name', + { to: 'a@b.com', cc: { name: 5, address: 'c@d.com' } }, + 'invalid recipient address in `cc`: the display name of c@d.com must be a string', + ], ])('%s is refused VALIDATION_FAILED, naming the field', (_label, input, reason) => { expect(refusal(input)).toBe(`VALIDATION_FAILED: ${reason}`); }); diff --git a/packages/plugins/plugin-email/src/email-service.ts b/packages/plugins/plugin-email/src/email-service.ts index 305c5dc3743..dd5cbbc4d50 100644 --- a/packages/plugins/plugin-email/src/email-service.ts +++ b/packages/plugins/plugin-email/src/email-service.ts @@ -317,11 +317,20 @@ type CallerAddressField = 'to' | 'cc' | 'bcc' | 'replyTo'; * server-side fault that a 400 would wrongly pin on the caller. */ function formatCallerAddress(addr: EmailAddress, field: CallerAddressField): string { + const what = field === 'replyTo' ? 'reply-to address' : 'recipient address'; if (!isSendableAddress(addr)) { - const what = field === 'replyTo' ? 'reply-to address' : 'recipient address'; const shown = addr == null ? '' : addressPart(addr); throw new Error(`VALIDATION_FAILED: invalid ${what} in \`${field}\`: ${shown || '(empty)'}`); } + // A JSON body can carry any value as the display name; a non-string one + // would otherwise fail inside `formatAddress` as a TypeError — a 500 for + // input the caller wrote. + const name: unknown = typeof addr === 'object' ? addr.name : undefined; + if (name !== undefined && name !== null && typeof name !== 'string') { + throw new Error( + `VALIDATION_FAILED: invalid ${what} in \`${field}\`: the display name of ${addressPart(addr)} must be a string`, + ); + } return formatAddress(addr); }