Skip to content

Commit 5cdaf9a

Browse files
fix(plugin-email): a malformed recipient address answers 400 VALIDATION_FAILED, not 500 (#29250)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9RaqxGhqh8FisCVMZz6zHXb)_ Fixes #29152 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:发邮件接口收到格式错误的收件人地址(`to` / `cc` / `bcc` / `replyTo`,含空 `to`、列表里一个坏地址、显示名不是字符串)时,现在回 400 `VALIDATION_FAILED` 并点名哪个字段哪个地址,不再回 500 `EMAIL_SEND_FAILED`。 - 为什么改:调用方自己能改正的输入不该报 500(18.3.0 发版清单 email-template-render 验收第 7 条);500 会让集成方和自动化作者以为是服务器坏了。 - 风险与回滚:只改 plugin-email 的收件人校验报错分类,接受哪些地址的判据一字未改;配置错误的发件人(`OS_EMAIL_FROM` / 邮件设置)仍按服务端故障回 500;被拒的发送照旧写一条 `failed` 的 sys_email 记录。回滚即 revert 本 PR。 - 先看:`packages/plugins/plugin-email/src/email-service.ts` 的 `formatCallerAddress`(新增的拒收分类);`packages/rest/src/email-send-door-bounds.test.ts` 新的一组线上钉子。 - 两分钟验证:`pnpm --filter @objectstack/plugin-email exec vitest run src/email-service.test.ts` 与 `pnpm --filter @objectstack/rest exec vitest run src/email-send-door-bounds.test.ts`,预期全绿。 - 需要你做的:无,席位落地。 ## What changes - `normalizeMessage` (`@objectstack/plugin-email`) judges every CALLER-supplied address (`to`, `cc`, `bcc`, `replyTo`) through a new `formatCallerAddress`. Same acceptance as before (`isSendableAddress`, which shares `EMAIL_REGEX` with `formatAddress`); a refusal is now `VALIDATION_FAILED: invalid recipient address in FIELD: ADDRESS` (`invalid reply-to address` for `replyTo`). That is the spelling the REST send door already reads for its existing 400 (`message.startsWith('VALIDATION_FAILED')` in `email-routes.ts`, the same branch that answers `subject: ""` today), so the door needed no source change. - A non-string display name on a caller address (a JSON body can carry any value there) failed inside `formatAddress` as a `TypeError` ("obj.name?.trim is not a function"), which the door answers 500. It is now the same `VALIDATION_FAILED` refusal. This is an in-place fix of the same defect class in the same file, named here per the bounded-fix rule; evidence is the ablation below. - The SENDER keeps `formatAddress`'s plain `Invalid email address` throw. `from` is the deployment's configured sender (`OS_EMAIL_FROM`, Settings → Mail): the REST door already refuses a body `from` that is not the configured address with 403 and otherwise forwards the configured value, so an unsendable `from` is never the caller's input and stays a 500. - Changeset: patch for `@objectstack/plugin-email` only (`@objectstack/rest` source is unchanged). ## Tests New, no existing test edited: - `packages/plugins/plugin-email/src/email-service.test.ts`: eight refusal cases (malformed `to`, empty `to` string, one bad member of a `to` list, object `to`, `cc`, `bcc`, `replyTo`, non-string display name) each asserting the exact `VALIDATION_FAILED: …` text; a configured sender at `noreply@localhost` asserting the plain `Invalid email address` text and NOT the prefix; well-formed addresses in every field still normalize; `EmailService.send` rejects with the prefix, never calls the transport, and still writes one `failed` row. - `packages/rest/src/email-send-door-bounds.test.ts`: bad `to`, empty `to`, a `to` list with one bad member, bad `cc` → 400 with `code: 'VALIDATION_FAILED'` and the `error` text asserted, the caller's addresses forwarded untouched; a well-formed send through the same service → 200; a configured-sender fault → 500 `EMAIL_SEND_FAILED`, not a 400. The service here is a double that throws the producer's text; the producer's own suite pins that text per field (see Acceptance notes). ## Acceptance notes - `sys_email` row: kept as today. A 400-refused send still writes its `failed` rejection row: `sendInternal` catches the `normalizeMessage` throw, calls `recordRejectedMessage`, and rethrows; that method's docblock states the rule (the row is the only durable evidence when a caller swallows the error). Pinned in the new `EmailService.send` case. - Other callers of `normalizeMessage`: it has one call site, `EmailService.sendInternal`, reached by `send()` / `sendInline()` / `sendTemplate()`. Every internal sender still sees a rejection: template sends and auth mail (plugin-auth `sendTemplate` callers) receive the throw as before; the mail settings "Send test email" action returns `{ ok: false, severity: 'error', message }` from its catch; the messaging email channel returns `{ ok: false, error }` and its `classifyError` matches neither the old nor the new text, so it grades `retryable` exactly as before. The only reader of the `VALIDATION_FAILED` prefix on this path is the REST send door. No caller turns the failure into a success. - The rest pins drive the real `HonoHttpServer` door with a service double, because `@objectstack/rest` does not depend on `@objectstack/plugin-email`; the two suites together pin both halves (producer text, door mapping), and each half was ablated on its own. - Observation, not filed: the messaging email channel grades a malformed recipient `retryable`, so a bad address burns the retry ladder before going dead. Unchanged by this PR. ## Verification Head `a53fb69fa` (after `git merge origin/main` at `5a194b41`). <details><summary>Tests and typecheck (both packages, under os-verify-lock)</summary> - `@objectstack/plugin-email` test: Test Files 47 passed (47), Tests 775 passed (775); typecheck `tsc --noEmit` + check:test-typecheck OK. VERDICT command-exit 0. - `@objectstack/rest` test: Test Files 367 passed (367), Tests 6969 passed, 332 skipped (7301); typecheck + check:test-typecheck OK. VERDICT command-exit 0 (run on `72cc0d7f`; rest source and tests are byte-identical at the final head). - After the merge: the four touched/neighbouring files re-run, plugin-email 57/57, rest 258/258. - `eslint --no-inline-config` on `packages/plugins/plugin-email/src` and `packages/rest/src`: exit 0, no output. </details> <details><summary>Ablations (each landed on disk via scripts/ablation-replace.mjs, restored to the HEAD blob)</summary> Both suites import the subject from `src/` by relative path, so no build sits between mutation and run. - A1, recipients back on the plain throw (`if (false && !isSendableAddress(addr))`): plugin-email 8 failed / 33 passed. Expected "VALIDATION_FAILED: invalid recipient address in to: not-an-email", received "Invalid email address: not-an-email". - A2, configured sender judged as a caller address: 1 failed. expected "Invalid email address: noreply@localhost", received "VALIDATION_FAILED: invalid recipient address in to: noreply@localhost". - A3, door prefix branch removed (`if (false && message.startsWith('VALIDATION_FAILED'))`): rest 4 failed / 38 passed, `expected 500 to be 400`. - A4, door answers every send throw 400 (`if (true || …)`): rest 1 failed, `expected 400 to be 500` on the configured-sender case. - A5, display-name guard disabled: 1 failed. expected "VALIDATION_FAILED: invalid recipient address in cc: the display name of c@d.com must be a string", received "obj.name?.trim is not a function". </details> <details><summary>Gates (dispatch-gates --commands, derived at the final head)</summary> - Derived at a53fb69: 61 families. All 61 run on that head, every one exit 0. Reconciliation: "dispatch-gates --ran: 61 derived famil(ies) accounted for — 61 run, 0 NOT-MEASURED (a DERIVED zero — all 61 recorded an exit code and none of them is 3)." - Two families first answered exit 3 (prerequisite, not a verdict) on the earlier head: check-plugin-teardown-shape --self-test needed a pinned fixture commit the shallow clone lacked (fetched it), and check:dual-build-cjs-loads needs every package's dist (ran a full pnpm build under the lock, exit 0). Both exit 0 in the final run. - Lint family is not derived: eslint on both packages, exit 0 (above). </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmRW6HXmiYEciBx61dj)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent c347d22 commit 5cdaf9a

4 files changed

Lines changed: 189 additions & 7 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/plugin-email': patch
3+
---
4+
5+
fix(plugin-email): a malformed recipient address is the caller's `400 VALIDATION_FAILED`, not a `500` (#29152)
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
- 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`.
11+
- 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.
12+
- 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).
13+
- 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.
14+
- Nothing to do: no metadata, protocol or configuration changes.

‎packages/plugins/plugin-email/src/email-service.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,74 @@ describe('normalizeMessage', () => {
5353
});
5454
});
5555

56+
describe('normalizeMessage — a malformed CALLER address is the caller\'s VALIDATION_FAILED', () => {
57+
const FROM = 'no-reply@example.test';
58+
const base = { subject: 'Hi', text: 'x' };
59+
const refusal = (input: Record<string, unknown>) => {
60+
try {
61+
normalizeMessage({ ...base, ...input } as any, FROM);
62+
} catch (err) {
63+
return String((err as Error).message);
64+
}
65+
throw new Error('expected normalizeMessage to refuse the input');
66+
};
67+
68+
it.each([
69+
['a malformed `to`', { to: 'not-an-email' }, 'invalid recipient address in `to`: not-an-email'],
70+
['an empty `to` string', { to: '' }, 'invalid recipient address in `to`: (empty)'],
71+
['one bad member of a `to` list', { to: ['a@b.com', 'nope'] }, 'invalid recipient address in `to`: nope'],
72+
['an object `to` with a bad address', { to: { name: 'A', address: 'a@localhost' } }, 'invalid recipient address in `to`: a@localhost'],
73+
['a malformed `cc`', { to: 'a@b.com', cc: 'bad cc' }, 'invalid recipient address in `cc`: bad cc'],
74+
['a malformed `bcc`', { to: 'a@b.com', bcc: ['c@d.com', 'x@'] }, 'invalid recipient address in `bcc`: x@'],
75+
['a malformed `replyTo`', { to: 'a@b.com', replyTo: 'reply' }, 'invalid reply-to address in `replyTo`: reply'],
76+
[
77+
'a non-string display name',
78+
{ to: 'a@b.com', cc: { name: 5, address: 'c@d.com' } },
79+
'invalid recipient address in `cc`: the display name of c@d.com must be a string',
80+
],
81+
])('%s is refused VALIDATION_FAILED, naming the field', (_label, input, reason) => {
82+
expect(refusal(input)).toBe(`VALIDATION_FAILED: ${reason}`);
83+
});
84+
85+
it('a malformed CONFIGURED sender is NOT a VALIDATION_FAILED — it is the server\'s fault, not the caller\'s', () => {
86+
let message = '';
87+
try {
88+
normalizeMessage({ to: 'a@b.com', ...base }, { name: 'ObjectOS Local', address: 'noreply@localhost' });
89+
} catch (err) {
90+
message = String((err as Error).message);
91+
}
92+
expect(message).toBe('Invalid email address: noreply@localhost');
93+
expect(message.startsWith('VALIDATION_FAILED')).toBe(false);
94+
});
95+
96+
it('well-formed caller addresses in every field still normalize', () => {
97+
const msg = normalizeMessage(
98+
{ ...base, to: ['a@b.com'], cc: 'c@d.com', bcc: { name: 'B', address: 'b@c.com' }, replyTo: 'r@s.com' },
99+
FROM,
100+
);
101+
expect(msg).toMatchObject({ to: ['a@b.com'], cc: ['c@d.com'], bcc: ['B <b@c.com>'], replyTo: 'r@s.com' });
102+
});
103+
104+
it('EmailService.send rejects the same way, delivers nothing, and still records the rejection row', async () => {
105+
const rows: Array<Record<string, any>> = [];
106+
const persistence: EmailPersistence = {
107+
async insert(row) { rows.push({ ...row }); return { id: row.id }; },
108+
async update() { /* no-op */ },
109+
};
110+
const transport = { send: vi.fn(async () => ({ messageId: '<m@x>' })) };
111+
const svc = new EmailService({ transport, defaultFrom: FROM, persistence });
112+
113+
await expect(svc.send({ to: ['a@b.com', 'nope'], ...base }))
114+
.rejects.toThrow(/^VALIDATION_FAILED: invalid recipient address in `to`: nope$/);
115+
expect(transport.send).not.toHaveBeenCalled();
116+
// Unchanged by the reclassification: a pre-delivery refusal is still an
117+
// audit row at `failed`, never a re-deliverable `queued` one.
118+
expect(rows).toHaveLength(1);
119+
expect(rows[0]).toMatchObject({ status: 'failed', attempt_count: 0 });
120+
expect(String(rows[0].error)).toContain('invalid recipient address in `to`: nope');
121+
});
122+
});
123+
56124
describe('LogTransport', () => {
57125
it('returns a synthetic Message-ID and logs', async () => {
58126
const logger = { info: vi.fn() };

‎packages/plugins/plugin-email/src/email-service.ts‎

Lines changed: 51 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -296,15 +296,59 @@ export function formatAddress(addr: EmailAddress): string {
296296
return `${quoted} <${address}>`;
297297
}
298298

299-
function listToArray(v: EmailAddress | EmailAddress[] | undefined): string[] | undefined {
299+
/**
300+
* The message fields whose addresses the CALLER supplies — every one of them
301+
* is the caller's to correct, so a malformed address in any of them is the
302+
* caller's `VALIDATION_FAILED`, never a server fault.
303+
*/
304+
type CallerAddressField = 'to' | 'cc' | 'bcc' | 'replyTo';
305+
306+
/**
307+
* {@link formatAddress} for an address the CALLER supplied: the same
308+
* acceptance ({@link isSendableAddress}, one spelling of "valid enough to
309+
* send"), refused as `VALIDATION_FAILED: invalid recipient address …` naming
310+
* the field, so the REST send door answers 400 — the caller can fix it —
311+
* instead of 500 `EMAIL_SEND_FAILED`.
312+
*
313+
* The SENDER deliberately stays on {@link formatAddress}'s plain
314+
* `Invalid email address` throw: `from` is the deployment's configured sender
315+
* (`OS_EMAIL_FROM`, the `mail` settings, or a caller `from` the REST door has
316+
* already bound to that same configured value), so an unsendable one is a
317+
* server-side fault that a 400 would wrongly pin on the caller.
318+
*/
319+
function formatCallerAddress(addr: EmailAddress, field: CallerAddressField): string {
320+
const what = field === 'replyTo' ? 'reply-to address' : 'recipient address';
321+
if (!isSendableAddress(addr)) {
322+
const shown = addr == null ? '' : addressPart(addr);
323+
throw new Error(`VALIDATION_FAILED: invalid ${what} in \`${field}\`: ${shown || '(empty)'}`);
324+
}
325+
// A JSON body can carry any value as the display name; a non-string one
326+
// would otherwise fail inside `formatAddress` as a TypeError — a 500 for
327+
// input the caller wrote.
328+
const name: unknown = typeof addr === 'object' ? addr.name : undefined;
329+
if (name !== undefined && name !== null && typeof name !== 'string') {
330+
throw new Error(
331+
`VALIDATION_FAILED: invalid ${what} in \`${field}\`: the display name of ${addressPart(addr)} must be a string`,
332+
);
333+
}
334+
return formatAddress(addr);
335+
}
336+
337+
function listToArray(
338+
v: EmailAddress | EmailAddress[] | undefined,
339+
field: Exclude<CallerAddressField, 'replyTo'>,
340+
): string[] | undefined {
300341
if (v === undefined) return undefined;
301342
const arr = Array.isArray(v) ? v : [v];
302-
return arr.map(formatAddress);
343+
return arr.map((addr) => formatCallerAddress(addr, field));
303344
}
304345

305346
/**
306347
* Validate input + apply default-from + canonicalize recipients.
307-
* Throws Error('VALIDATION_FAILED: <reason>') for malformed payloads.
348+
* Throws Error('VALIDATION_FAILED: REASON') for malformed payloads — a
349+
* malformed caller-supplied address (`to` / `cc` / `bcc` / `replyTo`)
350+
* included. An unsendable `from` is the one malformed address that is NOT a
351+
* `VALIDATION_FAILED`: see {@link formatCallerAddress}.
308352
*/
309353
export function normalizeMessage(
310354
input: SendEmailInput,
@@ -318,7 +362,7 @@ export function normalizeMessage(
318362
if (!input.text && !input.html) {
319363
throw new Error('VALIDATION_FAILED: at least one of text or html is required');
320364
}
321-
const toArr = listToArray(input.to);
365+
const toArr = listToArray(input.to, 'to');
322366
if (!toArr || toArr.length === 0) {
323367
throw new Error('VALIDATION_FAILED: at least one recipient (to) is required');
324368
}
@@ -335,11 +379,11 @@ export function normalizeMessage(
335379
...(input.text !== undefined ? { text: input.text } : {}),
336380
...(input.html !== undefined ? { html: input.html } : {}),
337381
};
338-
const cc = listToArray(input.cc);
382+
const cc = listToArray(input.cc, 'cc');
339383
if (cc && cc.length > 0) msg.cc = cc;
340-
const bcc = listToArray(input.bcc);
384+
const bcc = listToArray(input.bcc, 'bcc');
341385
if (bcc && bcc.length > 0) msg.bcc = bcc;
342-
if (input.replyTo) msg.replyTo = formatAddress(input.replyTo);
386+
if (input.replyTo) msg.replyTo = formatCallerAddress(input.replyTo, 'replyTo');
343387
if (input.attachments && input.attachments.length > 0) msg.attachments = input.attachments;
344388
if (input.headers && Object.keys(input.headers).length > 0) msg.headers = input.headers;
345389
return msg;

‎packages/rest/src/email-send-door-bounds.test.ts‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,62 @@ describe('POST /api/v1/email/send — the capability', () => {
143143
});
144144
});
145145

146+
describe('POST /api/v1/email/send — a malformed recipient is the caller\'s 400, never a 500', () => {
147+
/**
148+
* A service whose `send` refuses the way `@objectstack/plugin-email`'s
149+
* `normalizeMessage` does: a malformed caller-supplied address is a
150+
* `VALIDATION_FAILED: invalid recipient address in FIELD: ADDRESS` throw
151+
* (that producer's own suite pins the exact text per field), and a
152+
* malformed CONFIGURED sender is the plain `Invalid email address` throw —
153+
* a server fault. This file pins the door half: what each answers on the wire.
154+
*/
155+
function refusingDouble(refusal?: string) {
156+
const send = vi.fn(async (_input: SendEmailInput) => {
157+
if (refusal !== undefined) throw new Error(refusal);
158+
return { id: 'eml_1', status: 'sent' as const, messageId: 'm1' };
159+
});
160+
const service: Partial<IEmailService> = { send, getDefaultFrom: () => CONFIGURED };
161+
return { service, send };
162+
}
163+
164+
it.each([
165+
['a malformed `to`', { to: 'not-an-email' }, 'invalid recipient address in `to`: not-an-email'],
166+
['an empty `to`', { to: '' }, 'invalid recipient address in `to`: (empty)'],
167+
['a `to` list with one bad member', { to: ['ok@example.org', 'nope'] }, 'invalid recipient address in `to`: nope'],
168+
['a malformed `cc`', { cc: 'bad cc' }, 'invalid recipient address in `cc`: bad cc'],
169+
])('%s answers 400 VALIDATION_FAILED naming the address', async (_label, fields, reason) => {
170+
const { service, send } = refusingDouble(`VALIDATION_FAILED: ${reason}`);
171+
const { post } = boot({ service, ctx: ADMIN });
172+
const out = await post({ ...MESSAGE, ...fields });
173+
174+
expect(out.status).toBe(400);
175+
expect(out.body.code).toBe('VALIDATION_FAILED');
176+
expect(out.body.error).toBe(reason);
177+
// The door forwarded the caller's addresses untouched — the refusal is the service's verdict on them.
178+
expect(send).toHaveBeenCalledTimes(1);
179+
expect(send.mock.calls[0][0]).toMatchObject(fields);
180+
});
181+
182+
it('a well-formed send through the same service still answers 200', async () => {
183+
const { service, send } = refusingDouble();
184+
const { post } = boot({ service, ctx: ADMIN });
185+
const out = await post({ ...MESSAGE, cc: ['cc@example.org'] });
186+
187+
expect(out.status).toBe(200);
188+
expect(out.body).toMatchObject({ status: 'sent', id: 'eml_1' });
189+
expect(send).toHaveBeenCalledTimes(1);
190+
});
191+
192+
it('a malformed CONFIGURED sender stays a server fault: 500 EMAIL_SEND_FAILED, not a 400 that blames the caller', async () => {
193+
const { service } = refusingDouble('Invalid email address: noreply@localhost');
194+
const { post } = boot({ service, ctx: ADMIN });
195+
const out = await post(MESSAGE);
196+
197+
expect(out.status).toBe(500);
198+
expect(out.body.code).toBe('EMAIL_SEND_FAILED');
199+
});
200+
});
201+
146202
describe('POST /api/v1/email/send — `sentBy` is the authenticated caller', () => {
147203
it('a body naming another user as `sentBy` is refused 403, and nothing is sent', async () => {
148204
const { service, send } = emailDouble();

0 commit comments

Comments
 (0)