Skip to content

Commit 85c7374

Browse files
fix(plugin-auth): a change-email request notifies the current address whatever way the caller is signed in (#30166)
Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:`POST /api/v1/auth/change-email` 被接受后发往账号当前邮箱的 `auth.email_change_notice`,收件人改为在全局 after-hook 里从端点自己解析出的会话读取;全局 before-hook 里那一段单独的会话读取删除。 - 为什么改:#8019 的裁决要求每个被接受的改邮箱请求都通知账号的当前邮箱,与调用方以何种方式登录无关;本 PR 让这条规则对每种登录方式都成立。 - 风险与回滚:风险低。通知的模板与文案不变;改邮箱流程本身(确认信发往新地址、点击前不改动)不变;被拒绝的请求仍然一封信都不发;通知失败仍不阻断流程。回滚即 revert 本 PR。 - 先看:`packages/plugins/plugin-auth/src/auth-manager-after-hook.ts`(`/change-email` 一段与 `changeEmailFrom`);`auth-manager-before-hook.ts`(删除的一段);`change-email-delete-user-wiring.test.ts` 新增的顶层 describe。 - 两分钟验证:`pnpm --filter @objectstack/plugin-auth exec vitest run --maxWorkers=2 src/change-email-delete-user-wiring.test.ts`,预期 20 个用例全部通过,其中新增 5 个。 - 需要你做的:无,席位落地。 ## What changes - **The rule** (the #8019 ruling, unchanged): every accepted `POST /api/v1/auth/change-email` request mails the account's current address the `auth.email_change_notice`, whatever way the caller is signed in. - `auth-manager-after-hook.ts`: the `/change-email` section takes the notice's recipient from the user of the session the endpoint itself acted on, `ctx.context.session.user`. better-auth's `sensitiveSessionMiddleware` records that session before the handler runs, and the handler does not write it, so it names the account the request changes, with the address it holds as the request arrives. A small helper, `changeEmailFrom`, shapes the recipient. The success gate, the failure-swallowing send and the refusal coding that follow are unchanged. - `auth-manager-before-hook.ts`: the `/change-email` capture is removed, since the after-hook now reads the address itself; the module header's list of moved sections no longer names it. - `auth-manager-auth-instance.ts`: one comment pointer that named the removed key now names `auth-manager-after-hook.ts`. - `identity-mail-sibling.test.ts`, `auth-email-locale.test.ts`: the three fixtures that drive the after-hook directly hand it `context.session.user` in place of the removed key; their assertions are unchanged. - Changeset `change-email-notice-every-sign-in.md`: `@objectstack/plugin-auth` patch. ## Tests A new top-level describe in `change-email-delete-user-wiring.test.ts`, the change-email harness, named for the rule: "a change-email request notifies the current address whatever way the caller is signed in". - For each way of signing in (the session cookie; a bearer token alone): an accepted request mails exactly one notice, to the current address, naming the requested address and the account id. The acceptance is asserted too (a 200 and one confirmation to the requested address), and the stored address has not moved. - For each way of signing in: a refused request (the account's own address, `400 VALIDATION_ERROR`) mails nothing at all. - A caller signed in as two accounts at once: the notice goes to the current address of the account the request changes (the one its confirmation is for), and to no other. ## Acceptance notes - Not stacked on any open PR. #30144 (open) also edits `auth-manager-before-hook.ts` and `auth-manager-auth-instance.ts`; neither PR depends on the other, their hunks are at least 50 lines apart, and `git merge-tree` of the two heads is clean, with no reference to the removed key left in the combined tree. - `main` was merged in before opening (seven commits, none under `packages/plugins/plugin-auth`); `@objectstack/spec` and `@objectstack/driver-sql`, which the merge touched, were rebuilt before the typecheck and the final test runs. The full plugin-auth suite ran on the pre-merge tree with the fix applied (below); per AGENTS.md §10 it was not re-run after a merge with no overlap. ## Verification <details> <summary>Tests and typecheck</summary> ```text plugin-auth full suite @ 5505e3e with the fix applied (e312a22 is that tree plus the two-account case; os-verify-lock held, closure built first) Test Files 220 passed (220) Tests 3819 passed | 10 skipped (3829) plugin-auth full suite exit=0 · VERDICT command-exit 0 pnpm --filter @objectstack/plugin-auth typecheck @ a014cda: exit 0 check:test-typecheck: OK — 10 file(s) / 88 error(s) / 23 pinned signature(s) held in test-typecheck-debt.json change-email-delete-user-wiring + identity-mail-sibling + auth-email-locale @ a014cda Test Files 3 passed (3) Tests 95 passed (95) targeted tests exit=0 · VERDICT command-exit 0 eslint --no-inline-config on the six changed .ts files @ a014cda: exit 0 ``` </details> <details> <summary>One-shot reverse verification</summary> ```text @ e503bab, one lock-held script with a restoring trap auth-manager-after-hook.ts and auth-manager-before-hook.ts restored to the base blobs (git hash-object == base blob: db93a8a, f1f1fec) change-email-delete-user-wiring.test.ts: exit 1 — the new describe goes red; every pre-existing case in the file stays green restored with git checkout HEAD (hash-object == HEAD blob: dd1e908, 5cb1f28; git diff HEAD empty; status clean; HEAD unmoved) change-email-delete-user-wiring.test.ts: exit 0, Tests 20 passed (20) The tests import src/ relatively, so there is no dist/ leg. The later commit a014cda changes only how one acceptance assertion reads the recipient (through the EmailAddress union); it was re-run green at a014cda above. ``` </details> <details> <summary>Gates</summary> ```text node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack (no paths: change set from the merge base) -> 60 commands @ a014cda: 59 of them re-run, each exit captured before any pipe: 59 x exit 0 (check:dual-build-cjs-loads included, measured over a full build: "116 published require entry point(s) across 71 package(s) load") @ e503bab: pnpm check:type-check-debt exit 0 "0 ledger entr(ies) re-measured ... none above its recorded number" (not re-run at a014cda: that commit touches three lines of one test file, which plugin-auth's own typecheck reads green at a014cda) node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack --ran FILE Run reconciliation — 60 derived, 60 run, 0 NOT-MEASURED, 0 UNRUN. all 60 accounted families carry an exit code Repo-wide scans (pnpm lint and the rest of Lint & Repo Gates) are CI's. ``` </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 76dfe0e commit 85c7374

7 files changed

Lines changed: 141 additions & 39 deletions
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@objectstack/plugin-auth': patch
3+
---
4+
5+
fix(plugin-auth): a change-email request notifies the current address whatever way the caller is signed in
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
- **The rule.** Every `POST /api/v1/auth/change-email` request that is accepted mails the account's current address the `auth.email_change_notice`, whatever way the caller is signed in. The notice goes to the account the request changes: its address is read from the session the endpoint itself acted on.
11+
- **Unchanged.** The notice's template and text; the confirmation mail to the requested address; a refused request still mails nothing; the notice still never blocks the change.

‎packages/plugins/plugin-auth/src/auth-email-locale.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ async function driveAllFive(locale: string | undefined, extra: Record<string, un
168168
path: '/change-email',
169169
body: { newEmail: 'new@example.com' },
170170
context: {
171-
__osChangeEmailFrom: { email: 'ada@example.com', name: 'Ada', id: 'u1' },
171+
session: { user: { email: 'ada@example.com', name: 'Ada', id: 'u1' } },
172172
returned: { status: true },
173173
},
174174
});
@@ -353,7 +353,7 @@ async function driveWithHeader(
353353
body: { newEmail: 'new@example.com' },
354354
request,
355355
context: {
356-
__osChangeEmailFrom: { email: 'ada@example.com', name: 'Ada', id: 'u1' },
356+
session: { user: { email: 'ada@example.com', name: 'Ada', id: 'u1' } },
357357
returned: { status: true },
358358
},
359359
});

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

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,21 @@ export interface AfterHookHost {
7373
stampPasswordChangedAt: AuthManager['stampPasswordChangedAt'];
7474
}
7575

76+
/**
77+
* #8019 — who the change-email notice goes to: the user of the session the
78+
* endpoint acted on. `undefined` when that user carries no address, and then
79+
* no notice is sent.
80+
*/
81+
function changeEmailFrom(user: unknown): { email: string; name?: string; id?: string } | undefined {
82+
const u = (user ?? {}) as { email?: unknown; name?: unknown; id?: unknown };
83+
if (typeof u.email !== 'string' || !u.email) return undefined;
84+
return {
85+
email: u.email,
86+
...(typeof u.name === 'string' && u.name ? { name: u.name } : {}),
87+
...(typeof u.id === 'string' && u.id ? { id: u.id } : {}),
88+
};
89+
}
90+
7691
/** The body of `createAuthInstance`'s `hooks.after` arrow; the comments there and in it are its contract. */
7792
export async function globalAfterHook(this: AfterHookHost, ctx: any) {
7893
// ── #8243: impersonation must actually take effect for a bearer ──
@@ -204,9 +219,17 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) {
204219
// does not carry the old address, and better-auth mints a fresh
205220
// session there when the link is opened without one, so an
206221
// apply-time notice would silently miss that path.
222+
//
223+
// The address the notice goes to is the one the account holds as the
224+
// request arrives, read from the session the endpoint itself acted on:
225+
// better-auth's `sensitiveSessionMiddleware` resolves the caller before
226+
// the handler runs and records that session on `ctx.context.session`,
227+
// whatever credential carried it, and the handler never writes that object.
228+
// So it names the account the request changes, with the address as it
229+
// stood. No before-hook can read it: the endpoint resolves its caller only
230+
// after every before-hook has run.
207231
if (ctx?.path === '/change-email') {
208-
const from = ctx?.context?.__osChangeEmailFrom;
209-
delete ctx.context.__osChangeEmailFrom;
232+
const from = changeEmailFrom(ctx?.context?.session?.user);
210233
let succeeded: boolean;
211234
try {
212235
const { isAPIError } = await import('better-auth/api');

‎packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ export async function createAuthInstance(this: AuthInstanceHost): Promise<Auth<a
274274
// approval gate the ruling refuses, not a way to notify.
275275
//
276276
// The notice is consequently sent by the framework, from the global
277-
// `after` hook on `/change-email` (search `__osChangeEmailFrom`), using
277+
// `after` hook on `/change-email` (`auth-manager-after-hook.ts`), using
278278
// the `auth.email_change_notice` template. It is failure-isolated by
279279
// construction: it runs after better-auth has already produced the
280280
// response, and its own errors are swallowed, so a dead mailbox cannot

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

Lines changed: 1 addition & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
* it stood, re-indented four levels and otherwise unedited: the same actor
1313
* resolver handed to the attribution scope, the same refresh skip for a minted
1414
* principal session, the same per-number OTP send guard, the same password
15-
* complexity and reuse checks, the same change-email capture, the same
15+
* complexity and reuse checks, the same
1616
* remove-member, organization-delete and no-record revoke refusals, the same
1717
* held-caller refusal on the admin plugin's role-scalar actions, the same
1818
* no-record admin revoke refusal, the same held-caller refusal on rewriting or
@@ -206,38 +206,6 @@ export async function globalBeforeHook(
206206
// fall through to the path's own handling below
207207
}
208208

209-
// ── #8019: capture the address a change-email would move AWAY from ──
210-
// The notice goes out from the after-hook, but the OLD address only
211-
// exists BEFORE the endpoint runs — and `ctx.context.session` is not
212-
// it: better-auth's own `sensitiveSessionMiddleware` populates that,
213-
// and endpoint middleware runs AFTER this global before-hook, so the
214-
// field is still empty here. Resolve the session explicitly, the same
215-
// hook-order-independent way `/oauth2/authorize` below has to.
216-
//
217-
// Stashed, never sent from here: at this point the request has not
218-
// been accepted yet (it can still fail on `newEmail` equal to the
219-
// current address, on rate limiting, or on a missing transport), and
220-
// a notice for a request better-auth then refuses would be a false
221-
// alarm about an identity move that never happened.
222-
if (ctx?.path === '/change-email') {
223-
try {
224-
const { getSessionFromCtx } = await import('better-auth/api');
225-
const s: any = await getSessionFromCtx(ctx as any).catch(() => null);
226-
const from = s?.user?.email;
227-
if (typeof from === 'string' && from) {
228-
ctx.context.__osChangeEmailFrom = {
229-
email: from,
230-
...(typeof s?.user?.name === 'string' && s.user.name ? { name: s.user.name } : {}),
231-
...(typeof s?.user?.id === 'string' && s.user.id ? { id: s.user.id } : {}),
232-
};
233-
}
234-
} catch {
235-
// Unresolvable session → no stash → no notice. better-auth's own
236-
// session middleware still rejects the request with 401, so this
237-
// never silently drops a notice for a change that proceeds.
238-
}
239-
}
240-
241209
// ── #8289: remove-member answers its PERMISSION denial itself ──
242210
// better-auth's `removeMember` orders "only an owner may remove an
243211
// owner" AHEAD of its real permission check and reports it with the

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

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -530,6 +530,106 @@ describe('#8019 — change-email notifies the previous address without gating on
530530
});
531531
});
532532

533+
// ───────────────────────────────────────────────────────────────────────────
534+
/**
535+
* #8019, whatever way the caller is signed in. The notice is owed for every
536+
* accepted request, so it must reach the account's current address on the
537+
* session-cookie lane and on the bearer-token lane alike. Every accepted case
538+
* also asserts the acceptance itself (a 200, and one confirmation to the
539+
* requested address), so no case can pass on a request better-auth refused;
540+
* and every refused case asserts that nothing at all was mailed.
541+
*/
542+
describe('#8019 — a change-email request notifies the current address whatever way the caller is signed in', () => {
543+
const bearerFrom = (response: Response): string => response.headers.get('set-auth-token') ?? '';
544+
545+
const changeEmailAs = (manager: AuthManager, credentials: { cookie?: string; bearer?: string }, newEmail: string) =>
546+
manager.handleRequest(
547+
new Request(`${AUTH}/change-email`, {
548+
method: 'POST',
549+
headers: {
550+
'content-type': 'application/json',
551+
origin: ORIGIN,
552+
...(credentials.cookie ? { cookie: credentials.cookie } : {}),
553+
...(credentials.bearer ? { authorization: `Bearer ${credentials.bearer}` } : {}),
554+
},
555+
body: JSON.stringify({ newEmail }),
556+
}),
557+
);
558+
559+
const confirmationsTo = (sent: SendTemplateInput[]): unknown[] =>
560+
sent.filter((s) => s.template === 'auth.verify_email').map((s) => s.to);
561+
562+
const TRANSPORTS: ReadonlyArray<readonly [string, (signedUp: Response) => { cookie?: string; bearer?: string }]> = [
563+
['the session cookie', (signedUp) => ({ cookie: cookieFrom(signedUp) })],
564+
['a bearer token alone', (signedUp) => ({ bearer: bearerFrom(signedUp) })],
565+
];
566+
567+
for (const [transport, credentialsOf] of TRANSPORTS) {
568+
it(`signed in by ${transport}: an accepted request mails the notice to the current address`, async () => {
569+
const engine = createMemoryEngine();
570+
const email = createRecordingEmailService();
571+
const manager = makeManager(engine, email.service);
572+
const credentials = credentialsOf(await signUp(manager, 'current@example.com'));
573+
expect(Object.values(credentials).join(''), 'sign-up must hand out the credential').not.toBe('');
574+
email.sent.length = 0;
575+
576+
const response = await changeEmailAs(manager, credentials, 'requested@example.com');
577+
expect(response.status, await response.clone().text()).toBe(200);
578+
expect(await response.json()).toEqual({ status: true });
579+
expect(confirmationsTo(email.sent), 'the request was accepted').toEqual([
580+
expect.objectContaining({ address: 'requested@example.com' }),
581+
]);
582+
583+
expect(notices(email.sent), 'exactly one notice, to the address being left').toHaveLength(1);
584+
const [notice] = notices(email.sent);
585+
expect(notice.to).toMatchObject({ address: 'current@example.com' });
586+
expect(notice.data).toMatchObject({
587+
newEmail: 'requested@example.com',
588+
user: { email: 'current@example.com', id: userRows(engine)[0]!.id },
589+
});
590+
// Nothing has moved yet: the notice names the address the account holds now.
591+
expect(userRows(engine).map((r) => r.email)).toEqual(['current@example.com']);
592+
});
593+
594+
it(`signed in by ${transport}: a refused request mails nothing`, async () => {
595+
const engine = createMemoryEngine();
596+
const email = createRecordingEmailService();
597+
const manager = makeManager(engine, email.service);
598+
const credentials = credentialsOf(await signUp(manager, 'current@example.com'));
599+
email.sent.length = 0;
600+
601+
// better-auth refuses the account's own address before it mints anything.
602+
const response = await changeEmailAs(manager, credentials, 'current@example.com');
603+
expect(response.status).toBe(400);
604+
expect(await errorBody(response)).toMatchObject({ code: 'VALIDATION_ERROR' });
605+
expect(email.sent).toEqual([]);
606+
});
607+
}
608+
609+
it('signed in as two accounts at once: the notice goes to the current address of the account the request changes', async () => {
610+
const engine = createMemoryEngine();
611+
const email = createRecordingEmailService();
612+
const manager = makeManager(engine, email.service);
613+
const cookie = cookieFrom(await signUp(manager, 'cookie-holder@example.com'));
614+
const bearer = bearerFrom(await signUp(manager, 'token-holder@example.com'));
615+
const tokenHolderId = userRows(engine).find((r) => r.email === 'token-holder@example.com')!.id;
616+
email.sent.length = 0;
617+
618+
const response = await changeEmailAs(manager, { cookie, bearer }, 'requested@example.com');
619+
expect(response.status, await response.clone().text()).toBe(200);
620+
621+
// The account the request changes is the one its confirmation is for.
622+
const confirmations = email.sent.filter((s) => s.template === 'auth.verify_email');
623+
expect(confirmations).toHaveLength(1);
624+
expect(confirmations[0].to).toMatchObject({ address: 'requested@example.com' });
625+
expect((confirmations[0].data as { user?: { id?: string } }).user?.id).toBe(tokenHolderId);
626+
627+
// …and the notice goes to that account's current address, and to no other.
628+
expect(notices(email.sent).map((s) => s.to)).toEqual([expect.objectContaining({ address: 'token-holder@example.com' })]);
629+
expect((notices(email.sent)[0].data as { user?: { id?: string } }).user?.id).toBe(tokenHolderId);
630+
});
631+
});
632+
533633
// ───────────────────────────────────────────────────────────────────────────
534634
describe('#29163 — the uncoded refusals on /change-email and /update-user carry a ledgered code', () => {
535635
/**

‎packages/plugins/plugin-auth/src/identity-mail-sibling.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ async function driveAuthMail(tenancy: Tenancy) {
8888
await config.hooks.after({
8989
path: '/change-email',
9090
body: { newEmail: 'new@example.com' },
91-
context: { __osChangeEmailFrom: { email: USER.email, name: USER.name, id: USER.id }, returned: { status: true } },
91+
context: { session: { user: { email: USER.email, name: USER.name, id: USER.id } }, returned: { status: true } },
9292
});
9393
await config.plugins.find((p: any) => p.id === 'organization')._opts.sendInvitationEmail({
9494
email: 'invitee@example.com',

0 commit comments

Comments
 (0)