Skip to content

Commit 4522c3e

Browse files
fix(plugin-auth): the uncoded refusals on /change-email and /update-user carry an ADR-0112 code (#29282)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9AeLjhsRgNzegLA69SC8sCc)_ Fixes #29163 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:`/change-email` 改成自己当前邮箱、未配置邮件服务时改邮箱、`/update-user` 没有可改字段,这三种拒绝原来只有英文 message 没有 code,现在都带上台账里已有的 code(`VALIDATION_ERROR` / `EMAIL_SERVICE_REQUIRED`)。 - 为什么改:同一个入口的其它拒绝都带 code,客户端只能靠匹配英文文案区分这三种,无法按 ADR-0112 的 code 分支和做本地化。 - 风险与回滚:只在 after hook 里给这三句厂商原话补 code,状态码、文案、拒绝与否都不变,不改 better-auth;回滚即 revert 本 PR。 - 先看:`packages/plugins/plugin-auth/src/account-self-service-refusal-code.ts`(识别条件)、`auth-manager-after-hook.ts`(两处调用)、`change-email-delete-user-wiring.test.ts` 末尾新 describe。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run src/account-self-service-refusal-code.test.ts src/change-email-delete-user-wiring.test.ts`,预期 17/17 通过。 - 需要你做的:无,席位落地。 ## What changes - New `account-self-service-refusal-code.ts`: in the global `after` hook, a 400 `APIError` with no `code` on `/change-email` or `/update-user` whose message is exactly one of the vendor's listed sentences is re-thrown with the same status and message plus a ledgered code. Anything else passes through untouched, including a future vendor release that codes these itself. Same seam and recognition shape as the invite-member `ROLE_NOT_FOUND` stamp. | Door | Vendor sentence | Code added | |:--|:--|:--| | `POST /change-email` | `Email is the same` (own address, any letter case) | `VALIDATION_ERROR` (standard catalog; the code this door already answers for a malformed address) | | `POST /change-email` | `Verification email isn't enabled` (no email transport) | `EMAIL_SERVICE_REQUIRED` (`@objectstack/plugin-auth` ledger; the code the invite import answers for the same deployment condition) | | `POST /update-user` | `No fields to update` | `VALIDATION_ERROR` | - `auth-manager-after-hook.ts`: calls the stamp last in the `/change-email` section (after the old-address notice logic, which only acts on success) and right after the invite-member stamp for `/update-user`. - No new error code, no `packages/spec` edit, no better-auth change, no change to which requests are refused. ## Tests - `change-email-delete-user-wiring.test.ts` (existing file, new `describe` at the end, reusing its harness): the three refusals on the wire, each asserting status + full body `{ message, code }`, that nothing was mailed or changed on the own-address refusal, and a preservation case that the vendor's already-coded siblings (`VALIDATION_ERROR` for a malformed address, `EMAIL_CAN_NOT_BE_UPDATED`, anonymous `UNAUTHORIZED`) answer byte-for-byte as before. - `account-self-service-refusal-code.test.ts` (new): every listed sentence is stamped on its own door; seven answers are left alone (listed sentence on the other door, uncovered path, unlisted sentence, vendor-coded body, non-400, success, inherited object key as path). - No existing test needed an edit. ## Acceptance notes - **Body shape.** The card delta asked for `{ success:false, error:{ code, message } }` "like the door's other refusals". Measured, the door's other refusals answer the vendor's flat `{ message, code }` (table in Verification), so the stamp keeps that shape: re-shaping only these three would make one door answer in two dialects. The flat shape is what every vendor-served auth route answers today. - **Sibling measurement** (also in Verification): an address already taken answers `200 {"status":true}` by design (vendor anti-enumeration), so it is not a refusal to code. ## Verification Base `0c0d3b68` (origin/main at branch point) vs head (see report), plugin-auth `AuthManager.handleRequest` harness, better-auth 1.7.12: <details><summary>Premise and sibling refusals, measured on base</summary> | Request | Base answer | |:--|:--| | change-email, own address | 400 `{"message":"Email is the same"}` | | change-email, own address upper-cased | 400 `{"message":"Email is the same"}` | | change-email, no email transport | 400 `{"message":"Verification email isn't enabled"}` | | change-email, malformed address | 400 `{"message":"[body.newEmail] Invalid email address","code":"VALIDATION_ERROR"}` | | change-email, missing newEmail | 400 `{"message":"[body.newEmail] Invalid input: expected string, received undefined","code":"VALIDATION_ERROR"}` | | change-email, address already taken | 200 `{"status":true}` | | change-email, anonymous | 401 `{"message":"Unauthorized","code":"UNAUTHORIZED"}` | | update-user, `email` key | 400 `{"message":"Email can not be updated","code":"EMAIL_CAN_NOT_BE_UPDATED"}` | | update-user, `{}` or only undeclared keys | 400 `{"message":"No fields to update"}` | | update-user, array body | 400 `{"message":"[body] Invalid input: expected record, received array","code":"VALIDATION_ERROR"}` | Head: the three uncoded rows answer the same status and message plus the code in the table above; every other row is unchanged (pinned). Clause-②: same requests refused on base and head (400 / 400 for all three), only `code` added: `no`. </details> <details><summary>Ablation (each mutation through scripts/ablation-replace.mjs, restored to the HEAD blob, git diff HEAD empty)</summary> - A1 throw replaced by `return` → 4 failed (the three wire cases + the stamp unit case). - A2 sentence check dropped → 1 failed: `leaves every other answer alone` (`/update-user: expected APIError: Email is the same … to be undefined`). - A3 already-coded guard dropped → 1 failed: `leaves every other answer alone` (`/change-email: expected APIError … to be undefined`). - After each: `ok restored: blob == HEAD (017cbf0) and git diff HEAD is empty`. </details> <details><summary>Local runs on head a80478e</summary> - `pnpm --filter @objectstack/plugin-auth test`: Test Files 209 passed (209), Tests 3616 passed, 10 skipped. - `pnpm --filter @objectstack/plugin-auth typecheck`: lock VERDICT command-exit 0 (src, examples, test layer held in test-typecheck-debt.json). - `eslint --no-inline-config` on the four touched `.ts` files: exit 0 (plugin-auth has no own `lint` script; the repo-wide `pnpm lint` is CI's). - Dogfood auth tests after the `@objectstack/dogfood^...` closure build (exit 0): `admin-platform-admin-standing`, `admin-route-nonadmin-refusal`, `mcp-oauth-api-action-forward`, `auth-session-audit-trail`, `discovery-auth-families`, `bearer-lane-password-change`, `admin-credential-lifecycle`, `account-oauth-tokens-not-serialized`: Test Files 8 passed (8), Tests 63 passed (63). - `dispatch-gates --ran`: 61 derived, 61 run, 0 NOT-MEASURED, 0 UNRUN, every line with its exit code, all 0. Three first exited non-zero for setup reasons and were re-run green: `check-plugin-teardown-shape --self-test` (exit 3 until its pinned fixture commit was fetched into the shallow clone), `check:dts-closure` and `check:dual-build-cjs-loads` (exit 1 / 3 while a closure build was rewriting `dist/`; green after it finished). - Full dogfood not run: no `!` in the title and no `(narrowing)` arm. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmPd6RTyjWJ8rUy8F5r)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 2771575 commit 4522c3e

5 files changed

Lines changed: 246 additions & 0 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): the uncoded refusals on `POST /change-email` and `POST /update-user` now carry an ADR-0112 code
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
Three refusals on the account self-service doors answered a 400 with a message and no `code`, while every other refusal on the same doors carried one, so a client could only tell them apart by matching English text. Each now answers the same 400 with the same message, plus a code that is already in the ledger:
11+
12+
- `POST /change-email` to the caller's own address (`Email is the same`, any letter case) → `code: "VALIDATION_ERROR"`, the code this door already answers for a malformed address.
13+
- `POST /change-email` on a deployment with no email transport (`Verification email isn't enabled`) → `code: "EMAIL_SERVICE_REQUIRED"`.
14+
- `POST /update-user` with nothing it can update (`No fields to update`) → `code: "VALIDATION_ERROR"`.
15+
16+
Which requests are refused is unchanged, and the body keeps the doors' flat `{ "message", "code" }` shape. A client that branched on the message text keeps working; it can now branch on `code` instead.
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #29163 — recognition is narrow: only a listed sentence, on its own door, as
5+
* an uncoded 400 `APIError`, is re-thrown with a code. The wire behaviour is
6+
* pinned in `change-email-delete-user-wiring.test.ts`; this file holds the
7+
* answers the stamp must leave alone.
8+
*/
9+
10+
import { describe, it, expect } from 'vitest';
11+
import { APIError } from 'better-auth/api';
12+
import { codeSelfServiceRefusal, SELF_SERVICE_UNCODED_REFUSALS } from './account-self-service-refusal-code.js';
13+
14+
const ctxFor = (path: string, returned: unknown) => ({ path, context: { returned } });
15+
16+
const thrownBy = async (ctx: unknown): Promise<unknown> => {
17+
try {
18+
await codeSelfServiceRefusal(ctx);
19+
return undefined;
20+
} catch (e) {
21+
return e;
22+
}
23+
};
24+
25+
describe('codeSelfServiceRefusal (#29163)', () => {
26+
it('stamps each listed sentence on its own door, keeping status and message', async () => {
27+
for (const [path, sentences] of Object.entries(SELF_SERVICE_UNCODED_REFUSALS)) {
28+
for (const [message, code] of Object.entries(sentences)) {
29+
const thrown = await thrownBy(ctxFor(path, APIError.fromStatus('BAD_REQUEST', { message })));
30+
expect(thrown, `${path}: ${message}`).toBeInstanceOf(APIError);
31+
expect((thrown as APIError).statusCode).toBe(400);
32+
expect((thrown as APIError).body).toEqual({ code, message });
33+
}
34+
}
35+
});
36+
37+
it('leaves every other answer alone', async () => {
38+
const untouched: Array<[string, unknown]> = [
39+
// a listed sentence on the OTHER door
40+
['/update-user', APIError.fromStatus('BAD_REQUEST', { message: 'Email is the same' })],
41+
// a path the module does not cover
42+
['/sign-up/email', APIError.fromStatus('BAD_REQUEST', { message: 'Email is the same' })],
43+
// an unlisted sentence
44+
['/change-email', APIError.fromStatus('BAD_REQUEST', { message: 'Something else' })],
45+
// already coded by the vendor
46+
['/change-email', new APIError('BAD_REQUEST', { message: 'Email is the same', code: 'VENDOR_CODE' })],
47+
// not a 400
48+
['/change-email', APIError.fromStatus('FORBIDDEN', { message: 'Email is the same' })],
49+
// a success
50+
['/change-email', { status: true }],
51+
// an inherited key is not a door
52+
['toString', APIError.fromStatus('BAD_REQUEST', { message: 'Email is the same' })],
53+
];
54+
for (const [path, returned] of untouched) {
55+
expect(await thrownBy(ctxFor(path, returned)), path).toBeUndefined();
56+
}
57+
});
58+
});
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #29163 — the uncoded refusals on the account self-service doors,
5+
* `POST /change-email` and `POST /update-user`, answered with a code.
6+
*
7+
* ## The defect, at the seam
8+
*
9+
* better-auth (`dist/api/routes/update-user.mjs`, measured against the
10+
* installed `1.7.12`) refuses three conditions on these two doors with
11+
* `APIError.fromStatus("BAD_REQUEST", { message })` — a message and no `code`:
12+
*
13+
* POST /change-email {"newEmail": <the caller's own address>}
14+
* -> 400 {"message":"Email is the same"}
15+
* POST /change-email (no email transport on the deployment)
16+
* -> 400 {"message":"Verification email isn't enabled"}
17+
* POST /update-user {} (or only keys the user schema does not declare)
18+
* -> 400 {"message":"No fields to update"}
19+
*
20+
* Every other refusal on the same doors carries one: a malformed `newEmail`
21+
* answers `{"message":…,"code":"VALIDATION_ERROR"}`, an `email` key on
22+
* `/update-user` answers `EMAIL_CAN_NOT_BE_UPDATED`, an anonymous caller
23+
* `UNAUTHORIZED`. An ADR-0112 client branches on `code`, never on prose, so
24+
* these three could only be told apart by string-matching the vendor's English.
25+
*
26+
* ## What this does
27+
*
28+
* Runs in the `after` hook, where better-auth hands the thrown `APIError` over
29+
* on `ctx.context.returned`, and re-throws exactly these refusals as
30+
* `APIError('BAD_REQUEST', { code, message })` with the vendor's own message.
31+
* better-auth's hook runner replaces the returned value with an `APIError` an
32+
* after hook throws, so the status, the message and the moment of the refusal
33+
* (before anything is written or mailed) stay the vendor's; only the missing
34+
* `code` is added. The body keeps the door's own flat `{ message, code }` shape,
35+
* the shape its coded siblings already answer in.
36+
*
37+
* Each code is one the ledger already holds (ADR-0112), none new:
38+
*
39+
* - `VALIDATION_ERROR` (standard catalog) for the two request-content
40+
* refusals — the code this door already answers for a malformed address;
41+
* - `EMAIL_SERVICE_REQUIRED` (`@objectstack/plugin-auth`) for the missing
42+
* transport — the code plugin-auth's own invite import answers for the same
43+
* deployment condition (`admin-import-users.ts`).
44+
*
45+
* Recognition is deliberately narrow: one of the two paths, a 400 `APIError`,
46+
* no `code` of its own, and a message that IS one of the vendor's sentences
47+
* listed for that path. Every other answer — including a future vendor release
48+
* that codes these itself — passes through untouched, and the vendored library
49+
* is not patched.
50+
*/
51+
52+
import type { RegisteredErrorCode, StandardErrorCode } from '@objectstack/spec/api';
53+
54+
/** The standard-catalog code for the two request-content refusals. */
55+
const VALIDATION_ERROR_CODE: StandardErrorCode = 'VALIDATION_ERROR';
56+
57+
/** plugin-auth's ledgered code for a deployment with no email transport. */
58+
const EMAIL_SERVICE_REQUIRED_CODE: RegisteredErrorCode = 'EMAIL_SERVICE_REQUIRED';
59+
60+
/** The ledgered codes this module stamps (see the module header for each). */
61+
type SelfServiceRefusalCode = StandardErrorCode | RegisteredErrorCode;
62+
63+
/**
64+
* Per door, the vendor's uncoded sentence and the code it answers with. Keyed
65+
* on better-auth's own `ctx.path` spelling.
66+
*/
67+
export const SELF_SERVICE_UNCODED_REFUSALS: Readonly<Record<string, Readonly<Record<string, SelfServiceRefusalCode>>>> = {
68+
'/change-email': {
69+
'Email is the same': VALIDATION_ERROR_CODE,
70+
"Verification email isn't enabled": EMAIL_SERVICE_REQUIRED_CODE,
71+
},
72+
'/update-user': {
73+
'No fields to update': VALIDATION_ERROR_CODE,
74+
},
75+
};
76+
77+
/**
78+
* Re-throw a listed uncoded refusal on `/change-email` or `/update-user` with
79+
* its code. A no-op on every other path and every other answer. Call it LAST
80+
* in the hook section that handles the path: the throw ends the hook.
81+
*/
82+
export async function codeSelfServiceRefusal(ctx: any): Promise<void> {
83+
const path = ctx?.path;
84+
if (typeof path !== 'string' || !Object.prototype.hasOwnProperty.call(SELF_SERVICE_UNCODED_REFUSALS, path)) return;
85+
const sentences = SELF_SERVICE_UNCODED_REFUSALS[path];
86+
const returned = ctx?.context?.returned;
87+
const { APIError, isAPIError } = await import('better-auth/api');
88+
if (!isAPIError(returned)) return;
89+
if (returned.statusCode !== 400) return;
90+
const body = returned.body as { code?: unknown; message?: unknown } | undefined;
91+
if (body?.code !== undefined) return;
92+
const message = body?.message;
93+
if (typeof message !== 'string' || !Object.prototype.hasOwnProperty.call(sentences, message)) return;
94+
throw new APIError('BAD_REQUEST', { code: sentences[message], message });
95+
}

‎packages/plugins/plugin-auth/src/auth-manager-after-hook.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
* Nothing re-exports this module, so the published surface does not move.
4141
*/
4242

43+
import { codeSelfServiceRefusal } from './account-self-service-refusal-code.js';
4344
import type { AuthManager } from './auth-manager.js';
4445
import { SIGN_IN_EMAIL_PATH } from './auth-session-audit.js';
4546
import { narrowDirectoryForExternalCaller } from './external-directory-door.js';
@@ -219,6 +220,10 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) {
219220
// caller here, so the request rung applies.
220221
await this.sendChangeEmailNotice(from, newEmail, ctx);
221222
}
223+
// #29163 — the vendor's uncoded refusals here carry a ledgered code
224+
// (see `account-self-service-refusal-code.ts`). It throws on a match,
225+
// so it stays last in this section.
226+
await codeSelfServiceRefusal(ctx);
222227
return;
223228
}
224229

@@ -256,6 +261,10 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) {
256261
// on a match, so it stays after every section above.
257262
await codeInviteRoleNotFound(ctx);
258263

264+
// ── #29163: update-user's uncoded refusal carries its code ──
265+
// Same seam as the change-email section above; throws on a match.
266+
await codeSelfServiceRefusal(ctx);
267+
259268
if (ctx?.path !== '/sign-up/email') return;
260269
// ADR-0069 D1 — stamp password_changed_at for a newly-created local
261270
// user (expiry clock starts at sign-up). Best-effort.

‎packages/plugins/plugin-auth/src/change-email-delete-user-wiring.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,3 +529,71 @@ describe('#8019 — change-email notifies the previous address without gating on
529529
expect(changeEmail?.updateEmailWithoutVerification).toBeUndefined();
530530
});
531531
});
532+
533+
// ───────────────────────────────────────────────────────────────────────────
534+
describe('#29163 — the uncoded refusals on /change-email and /update-user carry a ledgered code', () => {
535+
/**
536+
* Each refusal is asserted on its envelope (ADR-0112): the status, the
537+
* `code`, and the vendor's own sentence, which the stamp keeps byte-for-byte.
538+
* The body stays the door's flat `{ message, code }` — the shape its coded
539+
* siblings (pinned in the last case) already answer in.
540+
*/
541+
it('the caller\'s own address: 400 VALIDATION_ERROR, nothing mailed and nothing changed', async () => {
542+
const engine = createMemoryEngine();
543+
const email = createRecordingEmailService();
544+
const manager = makeManager(engine, email.service);
545+
const cookie = cookieFrom(await signUp(manager, 'own@example.com'));
546+
email.sent.length = 0;
547+
548+
for (const newEmail of ['own@example.com', 'OWN@example.com']) {
549+
const response = await post(manager, '/change-email', cookie, { newEmail });
550+
expect(response.status).toBe(400);
551+
expect(await errorBody(response)).toEqual({ message: 'Email is the same', code: 'VALIDATION_ERROR' });
552+
}
553+
expect(email.sent).toHaveLength(0);
554+
expect(userRows(engine).map((u) => u.email)).toEqual(['own@example.com']);
555+
});
556+
557+
it('no email transport: 400 EMAIL_SERVICE_REQUIRED', async () => {
558+
const engine = createMemoryEngine();
559+
const manager = makeManager(engine);
560+
const cookie = cookieFrom(await signUp(manager, 'nomail-29163@example.com'));
561+
562+
const response = await post(manager, '/change-email', cookie, { newEmail: 'elsewhere@example.com' });
563+
expect(response.status).toBe(400);
564+
expect(await errorBody(response)).toEqual({ message: "Verification email isn't enabled", code: 'EMAIL_SERVICE_REQUIRED' });
565+
});
566+
567+
it('/update-user with nothing it can update: 400 VALIDATION_ERROR, and a real update still succeeds', async () => {
568+
const engine = createMemoryEngine();
569+
const manager = makeManager(engine, createRecordingEmailService().service);
570+
const cookie = cookieFrom(await signUp(manager, 'update-29163@example.com'));
571+
572+
for (const body of [{}, { undeclared_key: 'x' }]) {
573+
const response = await post(manager, '/update-user', cookie, body);
574+
expect(response.status).toBe(400);
575+
expect(await errorBody(response)).toEqual({ message: 'No fields to update', code: 'VALIDATION_ERROR' });
576+
}
577+
const ok = await post(manager, '/update-user', cookie, { name: 'Renamed' });
578+
expect(ok.status).toBe(200);
579+
expect(await ok.json()).toEqual({ status: true });
580+
});
581+
582+
it('refusals the vendor already codes on these doors pass through unchanged', async () => {
583+
const engine = createMemoryEngine();
584+
const manager = makeManager(engine, createRecordingEmailService().service);
585+
const cookie = cookieFrom(await signUp(manager, 'coded-29163@example.com'));
586+
587+
const invalid = await post(manager, '/change-email', cookie, { newEmail: 'not-an-email' });
588+
expect(invalid.status).toBe(400);
589+
expect(await errorBody(invalid)).toEqual({ message: '[body.newEmail] Invalid email address', code: 'VALIDATION_ERROR' });
590+
591+
const emailKey = await post(manager, '/update-user', cookie, { email: 'x@example.com' });
592+
expect(emailKey.status).toBe(400);
593+
expect(await errorBody(emailKey)).toEqual({ message: 'Email can not be updated', code: 'EMAIL_CAN_NOT_BE_UPDATED' });
594+
595+
const anonymous = await post(manager, '/change-email', '', { newEmail: 'x@example.com' });
596+
expect(anonymous.status).toBe(401);
597+
expect(await errorBody(anonymous)).toEqual({ message: 'Unauthorized', code: 'UNAUTHORIZED' });
598+
});
599+
});

0 commit comments

Comments
 (0)