From 4b4710692c73aaa0d990408883724d9d4f94a121 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 13:52:36 +0000 Subject: [PATCH 1/8] =?UTF-8?q?wip(plugin-auth):=20a=20credential=20change?= =?UTF-8?q?=20ends=20access=20issued=20before=20it=20=E2=80=94=20rule=20mo?= =?UTF-8?q?dule=20and=20its=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_012MmDsQg43GaB78K8X6U1sL Co-authored-by: Claude --- ...redential-change-ends-prior-access.test.ts | 485 ++++++++++++++++++ .../credential-change-ends-prior-access.ts | 294 +++++++++++ 2 files changed, 779 insertions(+) create mode 100644 packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts create mode 100644 packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts new file mode 100644 index 00000000000..7b8c64fae98 --- /dev/null +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts @@ -0,0 +1,485 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A credential change ends access issued before it + * (`credential-change-ends-prior-access.ts`). + * + * Every door is driven through the real routes: a real `AuthManager` over a + * real `ObjectQL` engine (better-sqlite3, this plugin's own manifest), behind + * `AuthPlugin.registerAuthRoutes` mounted on a Hono app. + * + * Pinned: + * - an email-change link minted before a completed reset, a `/change-password` + * or an administrator's `/admin/set-user-password` answers what a link + * never issued answers (with and without a callback), the address does not + * move and no session is opened; a link minted after the change verifies; + * - a second-factor challenge opened before a reset answers what a challenge + * never opened answers; one opened after it completes; + * - a session a sign-in opens between a door's session revocation and its + * password write is ended by the door — the emailed reset, the texted + * reset, and `/change-password` asked to end the other sessions (the + * session it installs stands); + * - a password sign-in during which the account's password changes is + * refused with what a wrong password answers, and leaves no session; + * - the predicate and the clock: nothing is before a change that never + * happened, and the clock is the later of the two records. + */ + +import { describe, it, expect, afterAll, afterEach, vi } from 'vitest'; +import { createHmac } from 'node:crypto'; +import { Hono } from 'hono'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AuthManager } from './auth-manager.js'; +import { AuthPlugin } from './auth-plugin.js'; +import { issuedBeforeCredentialChange, readCredentialChangedAt } from './credential-change-ends-prior-access.js'; +import { authIdentityObjects } from './manifest.js'; +import { inviteForAudienceGate } from './audience-gate-test-support'; +import { memoizeScrypt } from './__tests__/scrypt-memo.testkit'; +import { sqliteEnginePool } from './__tests__/sqlite-engine-pool.testkit'; +// better-auth's first module load is paid here, at module load, not inside the +// first case (AGENTS.md, Build & Test: clocked windows measure behaviour). +import 'better-auth'; +import 'better-auth/api'; +import 'better-auth/plugins'; +import 'better-auth/plugins/two-factor'; + +const ORIGIN = 'http://localhost:3000'; +const BASE = '/api/v1/auth'; +const SECRET = 'test-secret-at-least-32-chars-long-prior-access-ends'; +const ADMIN_EMAIL = 'prior-access-admin@example.com'; +const EMAIL = 'prior-access-user@example.com'; +const NEW_ADDRESS = 'prior-access-moved@example.com'; +const PHONE = '+15550188'; +const FIRST = 'F1rst!Password-Prior'; +const SECOND = 'S3cond!Password-Prior'; +const SYS = { context: { isSystem: true } } as never; + +const engines = sqliteEnginePool(async () => { + const engine = new ObjectQL(); + const driver = new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }); + engine.registerDriver(driver, true); + await engine.init(); + for (const object of authIdentityObjects) { + engine.registry.registerObject(object as never, '@objectstack/plugin-auth'); + } + await engine.syncSchemas(); + return { engine, driver }; +}); +afterEach(engines.release); +afterAll(engines.destroy); + +const scrypt = memoizeScrypt(); +afterAll(scrypt.restore); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +const mockCtx = () => + ({ + registerService: vi.fn(), + getService: vi.fn((name: string) => (name === 'manifest' ? { register: vi.fn() } : undefined)), + getServices: vi.fn(() => new Map()), + hook: vi.fn(), + trigger: vi.fn(), + logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }, + getKernel: vi.fn(), + }) as any; + +/** Status and the error code, in either envelope the auth doors answer with. */ +async function answer(res: Response): Promise<{ status: number; code?: string }> { + const body = (await res.clone().json().catch(() => null)) as { code?: unknown; error?: { code?: unknown } } | null; + const code = body?.error?.code ?? body?.code; + return { status: res.status, ...(typeof code === 'string' ? { code } : {}) }; +} + +const cookieOf = (res: Response): string => + (res.headers.getSetCookie?.() ?? []).map((c) => c.split(';')[0]).filter(Boolean).join('; '); + +// RFC 6238 TOTP, hand-rolled as `two-factor-reenrollment-verified-reset.test.ts` does. +function base32Decode(input: string): Buffer { + const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + let bits = 0; + let value = 0; + const out: number[] = []; + for (const char of input.replace(/=+$/, '').toUpperCase()) { + value = (value << 5) | ALPHABET.indexOf(char); + bits += 5; + if (bits >= 8) { + out.push((value >>> (bits - 8)) & 0xff); + bits -= 8; + } + } + return Buffer.from(out); +} +function totp(secret: Buffer): string { + const buf = Buffer.alloc(8); + buf.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 30_000))); + const digest = createHmac('sha1', secret).update(buf).digest(); + const offset = digest[digest.length - 1] & 0x0f; + const code = + ((digest[offset] & 0x7f) << 24) | ((digest[offset + 1] & 0xff) << 16) | ((digest[offset + 2] & 0xff) << 8) | (digest[offset + 3] & 0xff); + return String(code % 1_000_000).padStart(6, '0'); +} + +/** + * One deployment: an administrator (the first account) and the user under test + * (signed up through an invitation, as `invite_only` admits a second account), + * behind the real route mount, with mail and texts captured. + */ +async function stage(config: Record = {}) { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'info').mockImplementation(() => {}); + const engine = await engines.take(); + const manager = new AuthManager({ + secret: SECRET, + baseUrl: ORIGIN, + dataEngine: engine as never, + ...config, + plugins: { admin: true, ...((config.plugins as Record) ?? {}) }, + } as never); + const mail: Array<{ template: string; to?: { address?: string }; data: Record }> = []; + manager.setEmailService({ + sendTemplate: async (input: any) => { + mail.push(input); + return { status: 'sent' }; + }, + } as never); + const texts: Array<{ to: string; templateParams?: { code?: string } }> = []; + manager.setSmsService({ + async send(input: { to: string; templateParams?: { code?: string } }) { + texts.push(input); + return { id: `sms${texts.length}`, status: 'sent' }; + }, + isConfigured: () => true, + } as never); + + const app = new Hono(); + const ctx = mockCtx(); + const plugin = new AuthPlugin({ secret: SECRET }); + await plugin.init(ctx); + (plugin as any).authManager = manager; + (plugin as any).registerAuthRoutes({ getRawApp: () => app, getPort: () => 0 }, ctx); + + const fire = (path: string, body: unknown, headers: Record = {}) => + app.request(`${ORIGIN}${BASE}${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN, ...headers }, + body: JSON.stringify(body), + }); + const bearer = (token: string) => ({ authorization: `Bearer ${token}` }); + + const signUp = async (email: string, invited: boolean) => { + const invitationId = invited ? await inviteForAudienceGate(engine, email) : undefined; + const res = await fire('/sign-up/email', { email, password: FIRST, name: email, ...(invitationId ? { invitationId } : {}) }); + expect(res.status, `sign-up ${email}: ${await res.clone().text()}`).toBe(200); + }; + await signUp(ADMIN_EMAIL, false); + await signUp(EMAIL, true); + + const idOf = async (email: string) => + String(((await engine.find('sys_user', { where: { email }, limit: 1 }, SYS)) as Array<{ id: string }>)[0].id); + await engine.update('sys_user', { id: await idOf(ADMIN_EMAIL), role: 'admin' }, SYS); + const userId = await idOf(EMAIL); + + /** The bearer a password sign-in mints, the refusal's answer, and the challenge cookie when one is asked. */ + const signIn = async (email: string, password: string) => { + const res = await fire('/sign-in/email', { email, password }); + const body = (await res.clone().json().catch(() => null)) as { twoFactorRedirect?: boolean } | null; + return { + ...(await answer(res)), + bearer: res.headers.get('set-auth-token') ?? undefined, + challenge: body?.twoFactorRedirect === true ? cookieOf(res) : undefined, + }; + }; + + /** The account a bearer signs in as now, or `null`. */ + const whoIs = async (token: string): Promise => { + const res = await app.request(`${ORIGIN}${BASE}/get-session`, { headers: { origin: ORIGIN, ...bearer(token) } }); + const body = (await res.json().catch(() => null)) as { user?: { id?: string } } | null; + return body?.user?.id ?? null; + }; + + /** The sessions of the user that better-auth would still honour. */ + const liveSessions = async () => { + const auth: any = await manager.getAuthContext(); + return (await auth.internalAdapter.listSessions(userId)) as Array<{ token: string }>; + }; + + const requestLink = async (): Promise => { + const before = mail.filter((m) => m.template === 'auth.password_reset').length; + const res = await fire('/request-password-reset', { email: EMAIL, redirectTo: `${ORIGIN}/reset` }); + expect(res.status, await res.clone().text()).toBe(200); + await vi.waitFor(() => expect(mail.filter((m) => m.template === 'auth.password_reset').length).toBe(before + 1)); + return String(mail.filter((m) => m.template === 'auth.password_reset')[before].data.token); + }; + const reset = async (newPassword: string) => { + const token = await requestLink(); + return answer(await fire('/reset-password', { token, newPassword })); + }; + + /** The email-change link `/change-email` mails to the new address. */ + const requestEmailChange = async (token: string, newEmail = NEW_ADDRESS): Promise => { + const toNew = () => mail.filter((m) => m.template === 'auth.verify_email' && m.to?.address === newEmail).length; + const before = toNew(); + const res = await fire('/change-email', { newEmail, callbackURL: '/' }, bearer(token)); + expect(res.status, `change-email: ${await res.clone().text()}`).toBe(200); + await vi.waitFor(() => expect(toNew()).toBe(before + 1)); + return String(mail.filter((m) => m.template === 'auth.verify_email' && m.to?.address === newEmail)[before].data.token); + }; + + /** What `GET /verify-email` answers a token: status, code, the redirect's error, and whether it opened a session. */ + const verifyEmail = async (token: string, callbackURL?: string) => { + const query = `token=${encodeURIComponent(token)}${callbackURL ? `&callbackURL=${encodeURIComponent(callbackURL)}` : ''}`; + const res = await app.request(`${ORIGIN}${BASE}/verify-email?${query}`, { method: 'GET', headers: { origin: ORIGIN } }); + const location = res.headers.get('location'); + return { + ...(await answer(res)), + redirectError: location ? new URL(location, ORIGIN).searchParams.get('error') : undefined, + opensSession: /session_token=[^;]+/.test(res.headers.getSetCookie?.().join('\n') ?? ''), + }; + }; + + const emailOf = async () => + String(((await engine.findOne('sys_user', { where: { id: userId }, fields: ['email'], context: { isSystem: true } } as never)) as { email: string }).email); + + const admin = await signIn(ADMIN_EMAIL, FIRST); + expect(admin.bearer, 'the administrator signs in on the bearer lane').toBeTruthy(); + + return { + engine, manager, fire, bearer, signIn, whoIs, liveSessions, requestLink, reset, requestEmailChange, + verifyEmail, emailOf, userId, texts, adminBearer: admin.bearer!, + }; +} + +/** Move the wall clock past the next whole second, so a token minted next carries a later `iat` than the change. */ +function stepPastTheSecond() { + vi.useFakeTimers({ toFake: ['Date'], now: Date.now() + 2_000 }); +} + +describe('an email-change link issued before a credential change answers what a link never issued answers', () => { + it('after a completed reset: no session, the address stays; a link minted after the reset verifies', async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + const before = await s.requestEmailChange(user.bearer!); + const neverIssued = await s.verifyEmail('a-token-never-issued'); + expect(neverIssued).toMatchObject({ status: 401, code: 'INVALID_TOKEN', opensSession: false }); + + expect(await s.reset(SECOND)).toEqual({ status: 200 }); + + expect(await s.verifyEmail(before)).toEqual(neverIssued); + expect(await s.emailOf()).toBe(EMAIL); + expect(await s.liveSessions()).toEqual([]); + + // The control: a link minted after the reset verifies and moves the address. + stepPastTheSecond(); + const again = await s.signIn(EMAIL, SECOND); + const after = await s.requestEmailChange(again.bearer!); + expect(await s.verifyEmail(after)).toMatchObject({ status: 200 }); + expect(await s.emailOf()).toBe(NEW_ADDRESS); + }, 60_000); + + it('with a callback, it redirects with the error a link never issued redirects with', async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + const before = await s.requestEmailChange(user.bearer!); + const neverIssued = await s.verifyEmail('a-token-never-issued', '/settings'); + expect(neverIssued.redirectError).toBe('INVALID_TOKEN'); + + expect(await s.reset(SECOND)).toEqual({ status: 200 }); + + expect(await s.verifyEmail(before, '/settings')).toEqual(neverIssued); + expect(await s.emailOf()).toBe(EMAIL); + }, 60_000); + + it("after the user's own /change-password, sessions kept", async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + const before = await s.requestEmailChange(user.bearer!); + const neverIssued = await s.verifyEmail('a-token-never-issued'); + + const changed = await s.fire('/change-password', { currentPassword: FIRST, newPassword: SECOND }, s.bearer(user.bearer!)); + expect(changed.status, await changed.clone().text()).toBe(200); + + expect(await s.verifyEmail(before)).toEqual(neverIssued); + expect(await s.emailOf()).toBe(EMAIL); + }, 60_000); + + it("after an administrator's /admin/set-user-password", async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + const before = await s.requestEmailChange(user.bearer!); + const neverIssued = await s.verifyEmail('a-token-never-issued'); + + const set = await s.fire( + '/admin/set-user-password', + { userId: s.userId, newPassword: SECOND, mustChangePassword: false }, + s.bearer(s.adminBearer), + ); + expect(set.status, await set.clone().text()).toBe(200); + + expect(await s.verifyEmail(before)).toEqual(neverIssued); + expect(await s.emailOf()).toBe(EMAIL); + }, 60_000); +}); + +describe('a second-factor challenge opened before a credential change answers what a challenge never opened answers', () => { + it('after a completed reset; a challenge opened after it completes', async () => { + const s = await stage({ plugins: { twoFactor: true } }); + const user = await s.signIn(EMAIL, FIRST); + const enabled = await s.fire('/two-factor/enable', { password: FIRST }, s.bearer(user.bearer!)); + expect(enabled.status, await enabled.clone().text()).toBe(200); + const { totpURI } = (await enabled.json()) as { totpURI: string }; + const secret = base32Decode(String(new URL(totpURI.replace('otpauth://', 'https://')).searchParams.get('secret'))); + const confirmed = await s.fire('/two-factor/verify-totp', { code: totp(secret) }, s.bearer(user.bearer!)); + expect(confirmed.status, await confirmed.clone().text()).toBe(200); + + const opened = await s.signIn(EMAIL, FIRST); + expect(opened.challenge, 'the password sign-in stops at the challenge').toBeTruthy(); + const neverOpened = await answer(await s.fire('/two-factor/verify-totp', { code: totp(secret) })); + + expect(await s.reset(SECOND)).toEqual({ status: 200 }); + + expect(await answer(await s.fire('/two-factor/verify-totp', { code: totp(secret) }, { cookie: opened.challenge! }))).toEqual(neverOpened); + expect(await s.liveSessions()).toEqual([]); + + // The control: a challenge opened after the reset completes. + const fresh = await s.signIn(EMAIL, SECOND); + expect(fresh.challenge).toBeTruthy(); + const completed = await s.fire('/two-factor/verify-totp', { code: totp(secret) }, { cookie: fresh.challenge! }); + expect(completed.status, await completed.clone().text()).toBe(200); + }, 60_000); +}); + +describe('a door that ends the sessions ends the ones opened before its password write lands', () => { + /** Run `during` once, just before the next password write of the user reaches the store. */ + async function beforeThePasswordWrite(s: Awaited>, verb: 'updatePassword' | 'updateAccount', during: () => Promise) { + const internal = (await s.manager.getAuthContext()).internalAdapter; + const original = internal[verb].bind(internal); + let ran = false; + vi.spyOn(internal, verb).mockImplementation(async (...args: unknown[]) => { + if (!ran) { + ran = true; + await during(); + } + return original(...args); + }); + } + + it('the emailed reset', async () => { + const s = await stage(); + let opened: string | undefined; + await beforeThePasswordWrite(s, 'updatePassword', async () => { + opened = (await s.signIn(EMAIL, FIRST)).bearer; + }); + + expect(await s.reset(SECOND)).toEqual({ status: 200 }); + + expect(opened, 'a sign-in ran before the password write').toBeTruthy(); + expect(await s.whoIs(opened!)).toBeNull(); + expect(await s.liveSessions()).toEqual([]); + }, 60_000); + + it('the texted reset', async () => { + const s = await stage({ plugins: { phoneNumber: true }, phoneOtp: { cooldownSeconds: 0 } }); + await s.engine.update('sys_user', { id: s.userId, phone_number: PHONE, phone_number_verified: true }, SYS); + const sent = await s.fire('/phone-number/request-password-reset', { phoneNumber: PHONE }); + expect(sent.status, await sent.clone().text()).toBe(200); + await vi.waitFor(() => expect(s.texts.length).toBe(1)); + const otp = String(s.texts[0].templateParams?.code ?? ''); + let opened: string | undefined; + await beforeThePasswordWrite(s, 'updatePassword', async () => { + opened = (await s.signIn(EMAIL, FIRST)).bearer; + }); + + expect(await answer(await s.fire('/phone-number/reset-password', { phoneNumber: PHONE, otp, newPassword: SECOND }))).toEqual({ status: 200 }); + + expect(opened, 'a sign-in ran before the password write').toBeTruthy(); + expect(await s.whoIs(opened!)).toBeNull(); + expect(await s.liveSessions()).toEqual([]); + }, 60_000); + + it('/change-password asked to end the other sessions; the session it installs stands', async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + let opened: string | undefined; + await beforeThePasswordWrite(s, 'updateAccount', async () => { + opened = (await s.signIn(EMAIL, FIRST)).bearer; + }); + + const changed = await s.fire( + '/change-password', + { currentPassword: FIRST, newPassword: SECOND, revokeOtherSessions: true }, + s.bearer(user.bearer!), + ); + expect(changed.status, await changed.clone().text()).toBe(200); + const installed = String(((await changed.json()) as { token?: string }).token); + + expect(opened, 'a sign-in ran before the password write').toBeTruthy(); + expect(await s.whoIs(opened!)).toBeNull(); + expect(await s.whoIs(installed)).toBe(s.userId); + expect((await s.liveSessions()).map((row) => row.token)).toEqual([installed]); + }, 60_000); +}); + +describe('a password sign-in during which the password changes is refused', () => { + it('it answers what a wrong password answers and leaves no session', async () => { + const s = await stage(); + const wrong = await s.signIn(EMAIL, 'Not!The-Password-1'); + expect(wrong.status).toBe(401); + const link = await s.requestLink(); + const internal = (await s.manager.getAuthContext()).internalAdapter; + const original = internal.createSession.bind(internal); + let changed: { status: number; code?: string } | undefined; + vi.spyOn(internal, 'createSession').mockImplementation(async (...args: unknown[]) => { + if (!changed) changed = await answer(await s.fire('/reset-password', { token: link, newPassword: SECOND })); + return original(...args); + }); + + const raced = await s.signIn(EMAIL, FIRST); + + expect(changed).toEqual({ status: 200 }); + expect({ status: raced.status, code: raced.code }).toEqual({ status: wrong.status, code: wrong.code }); + if (raced.bearer) expect(await s.whoIs(raced.bearer)).toBeNull(); + expect(await s.liveSessions()).toEqual([]); + }, 60_000); + + it('a sign-in the password does not change during stands (the control)', async () => { + const s = await stage(); + const fine = await s.signIn(EMAIL, FIRST); + expect(fine.status).toBe(200); + expect(await s.whoIs(fine.bearer!)).toBe(s.userId); + }, 60_000); +}); + +describe('the predicate and its clock', () => { + it('nothing is before a change that never happened; an unreadable issue time is before one that did', () => { + expect(issuedBeforeCredentialChange(1_000, undefined)).toBe(false); + expect(issuedBeforeCredentialChange(999, 1_000)).toBe(true); + expect(issuedBeforeCredentialChange(1_000, 1_000)).toBe(false); + expect(issuedBeforeCredentialChange(Number.NaN, 1_000)).toBe(true); + }); + + it('the clock is the later of password_changed_at and the credential row, and none without either', async () => { + const at = (iso?: string) => (iso ? { password_changed_at: iso, updated_at: iso } : null); + const engine = (user: unknown, account: unknown) => ({ + findOne: async (object: string) => (object === 'sys_user' ? user : account), + }); + expect(await readCredentialChangedAt(engine(null, null) as never, 'u')).toBeUndefined(); + expect( + await readCredentialChangedAt(engine(at('2026-01-01T00:00:00Z'), { updated_at: '2026-02-01T00:00:00Z' }) as never, 'u'), + ).toBe(Date.parse('2026-02-01T00:00:00Z')); + expect( + await readCredentialChangedAt(engine(at('2026-03-01T00:00:00Z'), { updated_at: '2026-02-01T00:00:00Z' }) as never, 'u'), + ).toBe(Date.parse('2026-03-01T00:00:00Z')); + await expect( + readCredentialChangedAt({ findOne: async () => { throw new Error('down'); } } as never, 'u'), + ).rejects.toThrow('down'); + }); +}); diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts new file mode 100644 index 00000000000..8af21f0753d --- /dev/null +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts @@ -0,0 +1,294 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A credential change ends access issued before it. + * + * ## The rule + * + * Once an account's password is set, nothing issued for that account before + * the change grants access after it: + * + * - an email-change link — the token `POST /change-email` mails (better-auth + * 1.7.12, `routes/update-user.mjs`), any token carrying `updateTo` — minted + * before the change answers at `GET /verify-email` exactly what a token + * that was never issued answers; + * - a second-factor challenge a password sign-in opened before the change is + * ended at its verify door, which then answers what a challenge that does + * not exist answers; + * - a door that ends the account's sessions when it sets the password ends + * them again once the password is written: both reset doors, the user's + * own `/change-password` asked to end the other sessions (the session it + * installs is kept), and the one-step invitation door + * (`invitation-mailbox-proof.ts`, ahead of the session it opens); + * - a password sign-in is refused when the account's password changed while + * it ran: the session it opened is ended and it answers what a wrong + * password answers at that door. + * + * Access issued after the change is untouched. + * + * ## The one predicate, and the clock it reads + * + * {@link issuedBeforeCredentialChange} is the only comparison: something + * issued strictly before the account's credential change is refused. The + * change's moment is {@link readCredentialChangedAt}: the later of + * `sys_user.password_changed_at` (ADR-0069 D1) and the `updated_at` of the + * account's local credential row (`sys_account`, provider `credential`). Every + * door that writes the password writes that row, those that do not stamp + * `password_changed_at` included (an administrator's + * `/admin/set-user-password`, the texted-code reset, a first password). An + * account with neither has never changed a local password, and nothing is + * refused. + * + * A token's issue time is the `iat` the vendor signs into it, whole seconds: + * a token minted in the same second as the change, after it, is refused too. + * Its owner asks for a new one. + * + * Each check fails closed: a clock or a record that cannot be read refuses + * what it was asked to admit. + * + * ## Where it is wired + * + * - `/verify-email`, the second-factor verify doors, and the password + * sign-in doors' first reading: the global before-hook + * (`auth-manager-before-hook.ts`). + * - The sessions a reset door or `/change-password` ends again, and the + * sign-in's second reading: the global after-hook + * (`auth-manager-after-hook.ts`), which runs ahead of every plugin's own + * after-hook, so a refused sign-in opens no second-factor challenge. + * - The one-step invitation door: in the door, before the session it opens. + * + * Each session ended here is ended through better-auth's internal adapter, so + * every session-delete hook runs, and a reset door's records the reason a + * reset records (`session-tombstone.ts`). + */ + +import type { IDataEngine } from '@objectstack/core'; +import { SystemObjectName } from '@objectstack/spec/system'; + +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] }; + +/** The path of better-auth's email verification door. */ +export const VERIFY_EMAIL_PATH = '/verify-email'; + +/** better-auth's second-factor verify doors (1.7.12 `plugins/two-factor`). */ +export const TWO_FACTOR_VERIFY_PATHS: ReadonlySet = new Set([ + '/two-factor/verify-totp', + '/two-factor/verify-otp', + '/two-factor/verify-backup-code', +]); + +/** The name better-auth gives the second-factor challenge cookie. */ +const TWO_FACTOR_COOKIE = 'two_factor'; + +/** The prefix of a challenge's attempt counter row, after which comes the challenge's identifier. */ +const TWO_FACTOR_ATTEMPTS_PREFIX = '2fa-attempts-'; + +/** + * The token the verify door is handed in place of an ended one: a value no + * signer issued, so the vendor answers it as it answers any token it cannot + * verify, through its own path. + */ +export const ENDED_EMAIL_CHANGE_TOKEN = 'ended-by-a-credential-change'; + +/** The context keys the before-hook leaves for the after-hook. */ +const SIGN_IN_READING = '__osSignInCredentialReading'; + +/** + * The one comparison: `issuedAtMs` falls before the account's credential + * change. Nothing is before a change that never happened; an issue time that + * cannot be read is treated as before one that did. + */ +export function issuedBeforeCredentialChange(issuedAtMs: number, changedAtMs: number | undefined): boolean { + if (changedAtMs === undefined) return false; + if (!Number.isFinite(issuedAtMs)) return true; + return issuedAtMs < changedAtMs; +} + +function toMs(value: unknown): number | undefined { + if (value === null || value === undefined || value === '') return undefined; + const ms = value instanceof Date ? value.getTime() : new Date(value as string | number).getTime(); + return Number.isFinite(ms) ? ms : undefined; +} + +type ClockEngine = Pick; + +/** + * The moment of the account's last credential change, in epoch ms, or + * `undefined` when it has never had one. Throws when either record cannot be + * read, so a caller refuses. + */ +export async function readCredentialChangedAt(engine: ClockEngine, userId: string): Promise { + const user = (await engine.findOne(SystemObjectName.USER, { + where: { id: userId }, + fields: ['id', 'password_changed_at'], + context: SYSTEM_CTX, + } as never)) as { password_changed_at?: unknown } | null; + const account = (await engine.findOne(SystemObjectName.ACCOUNT, { + where: { user_id: userId, provider_id: 'credential' }, + fields: ['id', 'updated_at'], + context: SYSTEM_CTX, + } as never)) as { updated_at?: unknown } | null; + const moments = [toMs(user?.password_changed_at), toMs(account?.updated_at)].filter( + (ms): ms is number => ms !== undefined, + ); + return moments.length > 0 ? Math.max(...moments) : undefined; +} + +/** Whether `issuedAt` falls before `userId`'s credential change; a clock that cannot be read answers yes. */ +async function issuedBeforeChangeOf(engine: ClockEngine | undefined, userId: string, issuedAtMs: number): Promise { + if (!engine) return true; + try { + return issuedBeforeCredentialChange(issuedAtMs, await readCredentialChangedAt(engine, userId)); + } catch { + return true; + } +} + +/** + * `GET /verify-email`: an email-change token issued before the account's + * credential change is replaced by {@link ENDED_EMAIL_CHANGE_TOKEN}, so the + * door answers it what it answers a token never issued, its callback check + * included. Answers the before-hook context that does so, or `undefined` to + * leave the request as it came. A token that does not decode, or carries no + * `updateTo`, is the vendor's to judge. + */ +export async function endEmailChangeTokenIssuedBeforeCredentialChange( + ctx: any, + engine: ClockEngine | undefined, +): Promise<{ context: { query: Record } } | undefined> { + if (ctx?.path !== VERIFY_EMAIL_PATH) return undefined; + const token: unknown = ctx?.query?.token; + if (typeof token !== 'string' || token.length === 0) return undefined; + let claims: Record; + try { + const { decodeJwt } = await import('jose'); + claims = decodeJwt(token) as Record; + } catch { + return undefined; + } + if (typeof claims.updateTo !== 'string' || typeof claims.email !== 'string') return undefined; + const ended = { context: { query: { ...(ctx.query ?? {}), token: ENDED_EMAIL_CHANGE_TOKEN } } }; + let userId: string | undefined; + try { + const found = await ctx.context.internalAdapter.findUserByEmail(claims.email.toLowerCase()); + const id: unknown = found?.user?.id; + userId = typeof id === 'string' && id.length > 0 ? id : undefined; + } catch { + return ended; + } + // No account at the address: the vendor's own refusal answers it. + if (!userId) return undefined; + const issuedAtMs = typeof claims.iat === 'number' ? claims.iat * 1000 : Number.NaN; + return (await issuedBeforeChangeOf(engine, userId, issuedAtMs)) ? ended : undefined; +} + +/** + * A second-factor verify door: the challenge the request's cookie names is + * ended — its row and its attempt counter deleted — when it was opened before + * the account's credential change, so the vendor's own check finds no + * challenge. Throws when the challenge cannot be ended. + */ +export async function endTwoFactorChallengeIssuedBeforeCredentialChange( + ctx: any, + engine: ClockEngine | undefined, +): Promise { + if (!TWO_FACTOR_VERIFY_PATHS.has(ctx?.path)) return; + const cookie = ctx?.context?.createAuthCookie?.(TWO_FACTOR_COOKIE); + if (!cookie?.name || typeof ctx?.getSignedCookie !== 'function') return; + const identifier: unknown = await ctx.getSignedCookie(cookie.name, ctx.context.secret); + if (typeof identifier !== 'string' || identifier.length === 0) return; + const internal = ctx.context.internalAdapter; + const challenge = await internal.findVerificationValue(identifier); + if (!challenge) return; + const userId = typeof challenge.value === 'string' ? challenge.value : ''; + const issuedAtMs = toMs(challenge.createdAt) ?? Number.NaN; + if (userId && !(await issuedBeforeChangeOf(engine, userId, issuedAtMs))) return; + await internal.deleteVerificationByIdentifier(identifier); + await internal.deleteVerificationByIdentifier(`${TWO_FACTOR_ATTEMPTS_PREFIX}${identifier}`); +} + +/** The local credential an account holds now, as better-auth reads it to check a password. */ +async function readCredential(ctx: any, userId: string): Promise { + const account = await ctx.context.internalAdapter.findCredentialAccount(userId); + const password: unknown = account?.password; + return typeof password === 'string' && password.length > 0 ? password : undefined; +} + +/** + * A password sign-in's first reading, before the vendor checks the password: + * the account the request names and the credential it holds now, left on the + * request for {@link refuseSignInAcrossCredentialChange}. `findAccountId` + * answers the account the door's identifier names. A reading that cannot be + * taken leaves none, which the second reading refuses. + */ +export async function noteSignInCredential( + ctx: any, + findAccountId: () => Promise, +): Promise { + if (!ctx?.context) return; + delete ctx.context[SIGN_IN_READING]; + try { + const userId = await findAccountId(); + if (!userId) return; + ctx.context[SIGN_IN_READING] = { userId, credential: await readCredential(ctx, userId) }; + } catch { + // No reading: a sign-in it would have judged is refused after the fact. + } +} + +/** + * A password sign-in's second reading, after the vendor opened its session: + * when the account's credential is not the one the first reading saw (or + * either reading is missing), the session is ended, the response carries no + * session, and the refusal `refusal` builds is answered. Answers that refusal + * for the caller to throw, or `undefined` when the sign-in stands. Inert for + * a request that opened no session. + */ +export async function refuseSignInAcrossCredentialChange( + ctx: any, + refusal: () => Promise, +): Promise { + const opened = ctx?.context?.newSession; + const reading = ctx?.context?.[SIGN_IN_READING] as { userId: string; credential?: string } | undefined; + if (ctx?.context) delete ctx.context[SIGN_IN_READING]; + const userId: unknown = opened?.user?.id; + const token: unknown = opened?.session?.token; + if (typeof userId !== 'string' || typeof token !== 'string') return undefined; + let stands = false; + if (reading && reading.userId === userId && reading.credential !== undefined) { + try { + stands = (await readCredential(ctx, userId)) === reading.credential; + } catch { + stands = false; + } + } + if (stands) return undefined; + await ctx.context.internalAdapter.deleteSession(token); + ctx.context.setNewSession?.(null); + const { deleteSessionCookie } = await import('better-auth/cookies'); + deleteSessionCookie(ctx, true); + return refusal(); +} + +/** + * End every session `userId` holds, except the one whose token is `keep`, + * through better-auth's internal adapter (so every session-delete hook runs, + * and the door's path decides what the ended row records). + */ +export async function endSessionsAfterCredentialWrite( + internal: { + listSessions(userId: string): Promise>; + deleteSession(token: string): Promise; + deleteUserSessions(userId: string): Promise; + }, + userId: string, + keep?: string, +): Promise { + if (!keep) { + await internal.deleteUserSessions(userId); + return; + } + for (const session of await internal.listSessions(userId)) { + if (typeof session?.token === 'string' && session.token !== keep) await internal.deleteSession(session.token); + } +} From 29102d8052d4a034c9c452120c2314b8ccdd132f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:01:05 +0000 Subject: [PATCH 2/8] fix(plugin-auth): a credential change ends access issued before it Claude-Session: https://claude.ai/code/session_012MmDsQg43GaB78K8X6U1sL Co-authored-by: Claude --- .../src/auth-manager-after-hook.ts | 76 +++++++++++++++++++ .../src/auth-manager-before-hook.ts | 41 +++++++++- .../credential-change-ends-prior-access.ts | 6 ++ .../src/invitation-mailbox-proof.ts | 5 ++ ...vitation-one-step-acceptance-34257.test.ts | 27 +++++++ 5 files changed, 153 insertions(+), 2 deletions(-) diff --git a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts index 91c1dc4fcee..0c3780df173 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts @@ -45,6 +45,12 @@ import { BANNED_USER_CODE, causeBannedUserRefusal } from './banned-user-refusal- import type { AuthManager } from './auth-manager.js'; import { refusalCodeOf } from './auth-session-audit.js'; import { passwordSignInDoorOf } from './auth-manager-sign-in-lockout.js'; +import { + endSessionsAfterCredentialWrite, + refuseSignInAcrossCredentialChange, + RESET_DOOR_PATHS, + RESET_DOOR_SUBJECT, +} from './credential-change-ends-prior-access.js'; import { narrowDirectoryForExternalCaller } from './external-directory-door.js'; import { SESSION_SCOPING_REFUSAL } from './organization-access-policy.js'; import { refuseIntrospectionForBannedSubject } from './oauth-token-read-ban-refusal.js'; @@ -166,7 +172,72 @@ async function refusedAfterTheCredential(returned: unknown): Promise { } /** The body of `createAuthInstance`'s `hooks.after` arrow; the comments there and in it are its contract. */ +/** What a wrong password answers at `door`: better-auth's own refusal there (1.7.12). */ +async function wrongPasswordAt(door: 'email' | 'phone'): Promise { + const { APIError } = await import('better-auth/api'); + if (door === 'phone') { + return new APIError('UNAUTHORIZED', { + code: 'INVALID_PHONE_NUMBER_OR_PASSWORD', + message: 'Invalid phone number or password', + }); + } + const { BASE_ERROR_CODES } = await import('@better-auth/core/error'); + return APIError.from('UNAUTHORIZED', BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); +} + +/** Whether the endpoint answered a success (no `APIError` on `returned`). */ +async function endpointSucceeded(ctx: any): Promise { + try { + const { isAPIError } = await import('better-auth/api'); + return !isAPIError(ctx?.context?.returned); + } catch { + return !(ctx?.context?.returned instanceof Error); + } +} + +/** + * A door that ends the account's sessions when it sets the password ends them + * again now that the password is written (`credential-change-ends-prior- + * access.ts`): both reset doors, and `/change-password` asked to end the other + * sessions, which keeps the session it installed. + */ +async function endSessionsOnceThePasswordIsWritten(this: Pick, ctx: any): Promise { + const resetDoor = RESET_DOOR_PATHS.has(ctx?.path); + const changeDoor = ctx?.path === '/change-password' && ctx?.body?.revokeOtherSessions === true; + if (!resetDoor && !changeDoor) return; + if (!(await endpointSucceeded(ctx))) return; + const internal = ctx?.context?.internalAdapter; + const subject: unknown = resetDoor ? ctx?.context?.[RESET_DOOR_SUBJECT] : actingUserIdOf(ctx); + const installed: unknown = ctx?.context?.returned?.token; + if (typeof subject !== 'string' || !subject || !internal || (changeDoor && (typeof installed !== 'string' || !installed))) { + this.logDurabilityDegradation( + 'AuthManager: a password was set by a door that ends the account\'s sessions, but the sessions were NOT ' + + 'ended again once the password was written: the account it set could not be named. The door ended ' + + 'them before the write, as it always has. Remedy: none per request; report it, the next such door ' + + 'ends them again.', + new Error('the account of a session-ending password door could not be named'), + { object: 'sys_session', path: String(ctx?.path) }, + ); + return; + } + await endSessionsAfterCredentialWrite(internal, subject, changeDoor ? (installed as string) : undefined); +} + export async function globalAfterHook(this: AfterHookHost, ctx: any) { + // ── A credential change ends access issued before it ────────────── + // FIRST: a password sign-in during which the account's password changed + // is refused, its session ended and the response left without one, ahead + // of every after-hook that reads the new session — the second-factor + // plugin's among them, which then opens no challenge. Its refusal is what + // a wrong password answers at that door; the lockout settlement below + // reads it as one, and it is thrown once that settlement has run. + // `credential-change-ends-prior-access.ts` states the rule. + const signInDoor = passwordSignInDoorOf(ctx); + const signInAcrossChange = signInDoor + ? await refuseSignInAcrossCredentialChange(ctx, () => wrongPasswordAt(signInDoor.door)) + : undefined; + if (signInAcrossChange) ctx.context.returned = signInAcrossChange; + // ── #8243: impersonation must actually take effect for a bearer ── // FIRST among the after-hooks that touch the response, because the // bearer plugin's own after-hook runs behind this one and must see @@ -310,6 +381,7 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) { // on a match, so it stays after the settlement and the refusal's // `login_failed` row above. The phone door goes on to the hooks below, // as before. + if (signInAcrossChange) throw signInAcrossChange; if (door === 'email') { await causeBannedUserRefusal(ctx); return; @@ -327,6 +399,10 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) { // only when the before-hook's reuse and forced-change checks ran for that // same account. The history entry is the old hash those checks read, so it // is appended only to the account it was read from. + // ── A credential change ends access issued before it ────────────── + // Ahead of the password-change after-effects, which return. + await endSessionsOnceThePasswordIsWritten.call(this, ctx); + if (ctx?.path === '/change-password' || ctx?.path === '/reset-password') { let succeeded: boolean; try { diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts index 990a149fe2d..3e30a2aab0d 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -64,8 +64,14 @@ import { isCloudManaged } from '@objectstack/core'; import { VENDOR_ROLE_SCALAR_ADMIN_PATHS } from './admin-impersonate-endpoint.js'; import { setAuthActorResolver } from './auth-actor-attribution.js'; import { AuthManager } from './auth-manager.js'; -import { passwordSignInDoorOf, recordLockoutRequest } from './auth-manager-sign-in-lockout.js'; +import { findPhoneSignInAccount, passwordSignInDoorOf, recordLockoutRequest } from './auth-manager-sign-in-lockout.js'; import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.js'; +import { + endEmailChangeTokenIssuedBeforeCredentialChange, + endTwoFactorChallengeIssuedBeforeCredentialChange, + noteSignInCredential, + RESET_DOOR_SUBJECT, +} from './credential-change-ends-prior-access.js'; import { isLastLocalCredentialHolder, LAST_LOCAL_CREDENTIAL_CODE, @@ -196,7 +202,12 @@ export async function globalBeforeHook( this: BeforeHookHost, ctx: any, setShouldSkipSessionRefresh: typeof import('better-auth/api').setShouldSkipSessionRefresh, -): Promise | Response | void> { +): Promise< + | ReturnType + | Awaited> + | Response + | void +> { // ── #4586: hand the attribution scope its actor resolver ───── // FIRST, and unconditionally: this global before-hook is the one // seam every better-auth endpoint passes through (`matcher: () => @@ -251,6 +262,15 @@ export async function globalBeforeHook( // see `auth-manager-sign-in-lockout.ts`. await recordLockoutRequest.call(this, ctx); + // ── A credential change ends access issued before it ────────── + // An email-change link minted before the account's last credential + // change answers what a link never issued answers, and a second-factor + // challenge opened before it is ended. `credential-change-ends-prior- + // access.ts` states the rule and its one predicate. + const endedEmailChange = await endEmailChangeTokenIssuedBeforeCredentialChange(ctx, this.getDataEngine()); + if (endedEmailChange) return endedEmailChange; + await endTwoFactorChallengeIssuedBeforeCredentialChange(ctx, this.getDataEngine()); + // ── [#33203] Cloud-managed: no reset door sets a local password ── // A hosted environment sets no local password for anyone, a platform // administrator included (ruling 10 of cloud#4465, `cloud-managed.ts`). @@ -314,6 +334,10 @@ export async function globalBeforeHook( const resetSubject = resetDoor ? await resolveResetDoorUserId(ctx, this.config.phoneOtp?.allowedAttempts ?? 3) : undefined; + // The account a reset door sets the password of, for the after-hook, which + // ends its sessions again once the password is written + // (`credential-change-ends-prior-access.ts`). + if (resetSubject?.ok && resetSubject.userId && ctx?.context) ctx.context[RESET_DOOR_SUBJECT] = resetSubject.userId; if (resetSubject?.ok && resetSubject.userId) { const source = await readUserSource(this.getDataEngine(), resetSubject.userId); if (source.ok && isPendingSsoSource(source.value)) { @@ -942,6 +966,19 @@ export async function globalBeforeHook( const passwordDoor = passwordSignInDoorOf(ctx); if (passwordDoor) { if (passwordDoor.identifier) await this.admitSignInAttempt(passwordDoor.identifier, ctx, passwordDoor.door); + // A sign-in during which the account's password changes is refused: the + // first of its two readings (`credential-change-ends-prior-access.ts`). + const { door, identifier } = passwordDoor; + await noteSignInCredential(ctx, async () => { + if (!identifier) return undefined; + if (door === 'phone') { + const engine = this.getDataEngine(); + return engine ? (await findPhoneSignInAccount(engine, identifier, []))?.id : undefined; + } + const found = await ctx.context.internalAdapter.findUserByEmail(identifier.toLowerCase()); + const id: unknown = found?.user?.id; + return typeof id === 'string' && id.length > 0 ? id : undefined; + }); return; } diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts index 8af21f0753d..7c3e03a5e47 100644 --- a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts @@ -93,6 +93,12 @@ export const ENDED_EMAIL_CHANGE_TOKEN = 'ended-by-a-credential-change'; /** The context keys the before-hook leaves for the after-hook. */ const SIGN_IN_READING = '__osSignInCredentialReading'; +/** The context key under which the before-hook leaves the account a reset door sets the password of. */ +export const RESET_DOOR_SUBJECT = '__osResetDoorUserId'; + +/** better-auth's two reset doors (`resetCredentialPassword`), which end the sessions before the write. */ +export const RESET_DOOR_PATHS: ReadonlySet = new Set(['/reset-password', '/phone-number/reset-password']); + /** * The one comparison: `issuedAtMs` falls before the account's credential * change. Nothing is before a change that never happened; an issue time that diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index 0c669336e80..0c8743b1291 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -117,6 +117,7 @@ */ import { isCloudManaged } from '@objectstack/core'; +import { endSessionsAfterCredentialWrite } from './credential-change-ends-prior-access.js'; import { isMissingTableError } from '@objectstack/types'; import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.js'; import { incrementFixedWindow, InProcessCounterStore, type CounterStore } from './rate-limit-storage.js'; @@ -746,6 +747,10 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo } // ADR-0069 D1: the password-age stamp and the forced-change clear. await host.stampPasswordChangedAt(String(user.id)); + // A credential change ends access issued before it: the account's + // sessions are ended again now that the password is written, ahead of + // the one this door opens (`credential-change-ends-prior-access.ts`). + if (existing) await endSessionsAfterCredentialWrite(internal, String(user.id)); const session = await internal.createSession(user.id, false); if (!session) throw new APIError('INTERNAL_SERVER_ERROR', { code: 'INTERNAL_ERROR', message: 'Failed to create a session.' }); diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index eed2e028e33..e232278b83f 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -1235,3 +1235,30 @@ describe('#34257 — a password the door sets starts the password-age clock and expect(INTERACTIVE_REVOKE_REASON[ACCEPT_INVITATION_ONE_STEP_PATH]).toBe('password_reset'); }); }); + +describe('a credential change ends access issued before it — the one-step door', () => { + quietConsole(); + + it('a session opened before the door writes the password is ended, and the session the door opens stands', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('raced@example.com'); + await signUp(manager, engine, 'raced@example.com'); + const internal = (await manager.getAuthContext()).internalAdapter; + const original = internal.updatePassword.bind(internal); + let opened: string | undefined; + vi.spyOn(internal, 'updatePassword').mockImplementation(async (...args: unknown[]) => { + if (opened === undefined) { + const res = await post(manager, '/sign-in/email', { email: 'raced@example.com', password: PASSWORD }); + opened = res.status === 200 ? cookieFrom(res) : ''; + } + return (original as (...a: unknown[]) => Promise)(...args); + }); + + const res = await door(manager, { invitationId: invitation.id, proof, name: 'R', password: NEW_PASSWORD }); + await expectAccepted(res); + + expect(opened, 'a sign-in ran before the password write').toBeTruthy(); + expect(await sessionUser(manager, opened!)).toBeNull(); + expect(await sessionUser(manager, cookieFrom(res))).toMatchObject({ email: 'raced@example.com' }); + }); +}); From 26c4f6ca6795a79b8bf32ddc43352041429bed4e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:15:49 +0000 Subject: [PATCH 3/8] fix(plugin-auth): the credential change is the last write over the local password; changeset and docs Claude-Session: https://claude.ai/code/session_012MmDsQg43GaB78K8X6U1sL Co-authored-by: Claude --- .../credential-change-ends-prior-access.md | 17 +++++++ content/docs/permissions/authentication.mdx | 16 +++++++ ...redential-change-ends-prior-access.test.ts | 39 +++++++++------- .../credential-change-ends-prior-access.ts | 45 ++++++++++--------- 4 files changed, 82 insertions(+), 35 deletions(-) create mode 100644 .changeset/credential-change-ends-prior-access.md diff --git a/.changeset/credential-change-ends-prior-access.md b/.changeset/credential-change-ends-prior-access.md new file mode 100644 index 00000000000..20b3cc24b33 --- /dev/null +++ b/.changeset/credential-change-ends-prior-access.md @@ -0,0 +1,17 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth): a credential change ends access issued before it + +Clause-②: no +Metadata-protocol: none + +Once an account's password is set, nothing issued for that account before the change grants access after it: + +- An email-change link (the one `POST /api/v1/auth/change-email` mails to the new address) minted before the change answers at `GET /api/v1/auth/verify-email` exactly what a link that was never issued answers: `401 INVALID_TOKEN`, or the `error=INVALID_TOKEN` redirect to its callback. Its owner requests a new one. A link's issue time is whole seconds, so one minted in the same second as the change is refused too. +- A second-factor challenge opened by a password sign-in before the change answers what a challenge that was never opened answers. The person signs in again with the new password. +- A door that ends the account's sessions when it sets the password ends every session opened before its password write: both reset doors, `POST /api/v1/auth/change-password` with `revokeOtherSessions: true` (the session it installs is kept), and the one-step invitation acceptance (ahead of the session it opens). +- A password sign-in during which the account's password changes is refused with what a wrong password answers at that door, and leaves no session. + +The moment of the change is the last time the account's local password was written over, so every door that replaces a password counts, an administrator's `POST /api/v1/auth/admin/set-user-password` included. An account's first password is not a change. A check that cannot read the record refuses. Access issued after the change, and an account that never changed its local password, are untouched. No request, response or metadata shape changes. diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 40e5b0bf763..300dee56076 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -322,6 +322,22 @@ code still outstanding for that user: a completed reset, the user's own what one that was never issued answers (`400 INVALID_TOKEN` at `reset-password`); a link or code requested after the change works as usual. +A change to a user's password also ends the access issued before it. An +email-change link minted before the change answers what a link that was never +issued answers at `GET /api/v1/auth/verify-email` (`401 INVALID_TOKEN`, or the +`error=INVALID_TOKEN` redirect to its callback), and a second-factor challenge +opened by a password sign-in before the change answers what a challenge that +was never opened answers; the person asks again. A door that ends the +account's sessions — a completed reset, `change-password` with +`revokeOtherSessions: true` (the session it installs is kept) and the one-step +invitation acceptance — ends every session opened before its password write, +and a password sign-in during which the password changes is refused with what +a wrong password answers. The change's moment is the last time the account's +local password was written over, so an administrator's `set-user-password` +counts too, and an account's first password is not a change; an email-change +link carries its issue time in whole seconds, so one minted in the same second +as the change is refused as well. + #### Setting a first local password `POST /api/v1/auth/set-initial-password` sets an **initial** local password for a diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts index 7b8c64fae98..38f6ba570cd 100644 --- a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts @@ -22,7 +22,7 @@ * - a password sign-in during which the account's password changes is * refused with what a wrong password answers, and leaves no session; * - the predicate and the clock: nothing is before a change that never - * happened, and the clock is the later of the two records. + * happened, and the clock is the last write over the credential row. */ import { describe, it, expect, afterAll, afterEach, vi } from 'vitest'; @@ -258,9 +258,14 @@ async function stage(config: Record = {}) { }; } -/** Move the wall clock past the next whole second, so a token minted next carries a later `iat` than the change. */ -function stepPastTheSecond() { - vi.useFakeTimers({ toFake: ['Date'], now: Date.now() + 2_000 }); +/** + * Move the wall clock two seconds on: past the window in which a credential + * row's write is still its creation, and past the whole second a token minted + * next carries as its `iat`. + */ +function advanceTheClock() { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() + 2_000); } describe('an email-change link issued before a credential change answers what a link never issued answers', () => { @@ -271,6 +276,7 @@ describe('an email-change link issued before a credential change answers what a const neverIssued = await s.verifyEmail('a-token-never-issued'); expect(neverIssued).toMatchObject({ status: 401, code: 'INVALID_TOKEN', opensSession: false }); + advanceTheClock(); expect(await s.reset(SECOND)).toEqual({ status: 200 }); expect(await s.verifyEmail(before)).toEqual(neverIssued); @@ -278,7 +284,7 @@ describe('an email-change link issued before a credential change answers what a expect(await s.liveSessions()).toEqual([]); // The control: a link minted after the reset verifies and moves the address. - stepPastTheSecond(); + advanceTheClock(); const again = await s.signIn(EMAIL, SECOND); const after = await s.requestEmailChange(again.bearer!); expect(await s.verifyEmail(after)).toMatchObject({ status: 200 }); @@ -292,6 +298,7 @@ describe('an email-change link issued before a credential change answers what a const neverIssued = await s.verifyEmail('a-token-never-issued', '/settings'); expect(neverIssued.redirectError).toBe('INVALID_TOKEN'); + advanceTheClock(); expect(await s.reset(SECOND)).toEqual({ status: 200 }); expect(await s.verifyEmail(before, '/settings')).toEqual(neverIssued); @@ -304,6 +311,7 @@ describe('an email-change link issued before a credential change answers what a const before = await s.requestEmailChange(user.bearer!); const neverIssued = await s.verifyEmail('a-token-never-issued'); + advanceTheClock(); const changed = await s.fire('/change-password', { currentPassword: FIRST, newPassword: SECOND }, s.bearer(user.bearer!)); expect(changed.status, await changed.clone().text()).toBe(200); @@ -317,6 +325,7 @@ describe('an email-change link issued before a credential change answers what a const before = await s.requestEmailChange(user.bearer!); const neverIssued = await s.verifyEmail('a-token-never-issued'); + advanceTheClock(); const set = await s.fire( '/admin/set-user-password', { userId: s.userId, newPassword: SECOND, mustChangePassword: false }, @@ -344,6 +353,7 @@ describe('a second-factor challenge opened before a credential change answers wh expect(opened.challenge, 'the password sign-in stops at the challenge').toBeTruthy(); const neverOpened = await answer(await s.fire('/two-factor/verify-totp', { code: totp(secret) })); + advanceTheClock(); expect(await s.reset(SECOND)).toEqual({ status: 200 }); expect(await answer(await s.fire('/two-factor/verify-totp', { code: totp(secret) }, { cookie: opened.challenge! }))).toEqual(neverOpened); @@ -466,18 +476,17 @@ describe('the predicate and its clock', () => { expect(issuedBeforeCredentialChange(Number.NaN, 1_000)).toBe(true); }); - it('the clock is the later of password_changed_at and the credential row, and none without either', async () => { - const at = (iso?: string) => (iso ? { password_changed_at: iso, updated_at: iso } : null); - const engine = (user: unknown, account: unknown) => ({ - findOne: async (object: string) => (object === 'sys_user' ? user : account), - }); - expect(await readCredentialChangedAt(engine(null, null) as never, 'u')).toBeUndefined(); + it('the clock is the last write over the credential row; its creation and no row are no change', async () => { + const engine = (account: unknown) => ({ findOne: async () => account }); + const created = '2026-01-01T00:00:00.000Z'; + expect(await readCredentialChangedAt(engine(null) as never, 'u')).toBeUndefined(); + expect(await readCredentialChangedAt(engine({ created_at: created, updated_at: created }) as never, 'u')).toBeUndefined(); expect( - await readCredentialChangedAt(engine(at('2026-01-01T00:00:00Z'), { updated_at: '2026-02-01T00:00:00Z' }) as never, 'u'), - ).toBe(Date.parse('2026-02-01T00:00:00Z')); + await readCredentialChangedAt(engine({ created_at: created, updated_at: '2026-01-01T00:00:00.900Z' }) as never, 'u'), + ).toBeUndefined(); expect( - await readCredentialChangedAt(engine(at('2026-03-01T00:00:00Z'), { updated_at: '2026-02-01T00:00:00Z' }) as never, 'u'), - ).toBe(Date.parse('2026-03-01T00:00:00Z')); + await readCredentialChangedAt(engine({ created_at: created, updated_at: '2026-02-01T00:00:00.000Z' }) as never, 'u'), + ).toBe(Date.parse('2026-02-01T00:00:00.000Z')); await expect( readCredentialChangedAt({ findOne: async () => { throw new Error('down'); } } as never, 'u'), ).rejects.toThrow('down'); diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts index 7c3e03a5e47..73f7e48e910 100644 --- a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts @@ -30,14 +30,16 @@ * * {@link issuedBeforeCredentialChange} is the only comparison: something * issued strictly before the account's credential change is refused. The - * change's moment is {@link readCredentialChangedAt}: the later of - * `sys_user.password_changed_at` (ADR-0069 D1) and the `updated_at` of the - * account's local credential row (`sys_account`, provider `credential`). Every - * door that writes the password writes that row, those that do not stamp - * `password_changed_at` included (an administrator's - * `/admin/set-user-password`, the texted-code reset, a first password). An - * account with neither has never changed a local password, and nothing is - * refused. + * change's moment is {@link readCredentialChangedAt}: the last time the + * account's local credential row (`sys_account`, provider `credential`) was + * written over, its `updated_at`. Every door that replaces a password writes + * that row — both reset doors, `/change-password`, an administrator's + * `/admin/set-user-password`, the one-step invitation door — whether or not it + * also stamps `sys_user.password_changed_at`. The row's creation is the + * account's first password, not a change: a row written over within + * {@link FIRST_CREDENTIAL_WINDOW_MS} of its creation reads as never written + * over, and an account with no local credential has never changed one. In + * either case nothing is refused. * * A token's issue time is the `iat` the vendor signs into it, whole seconds: * a token minted in the same second as the change, after it, is refused too. @@ -118,26 +120,29 @@ function toMs(value: unknown): number | undefined { type ClockEngine = Pick; +/** + * How long after its creation a credential row's own write still counts as + * its creation: the row is written with a creation and an update stamp taken + * separately, and the first password is not a change. + */ +export const FIRST_CREDENTIAL_WINDOW_MS = 1_000; + /** * The moment of the account's last credential change, in epoch ms, or - * `undefined` when it has never had one. Throws when either record cannot be + * `undefined` when it has never had one. Throws when the record cannot be * read, so a caller refuses. */ export async function readCredentialChangedAt(engine: ClockEngine, userId: string): Promise { - const user = (await engine.findOne(SystemObjectName.USER, { - where: { id: userId }, - fields: ['id', 'password_changed_at'], - context: SYSTEM_CTX, - } as never)) as { password_changed_at?: unknown } | null; const account = (await engine.findOne(SystemObjectName.ACCOUNT, { where: { user_id: userId, provider_id: 'credential' }, - fields: ['id', 'updated_at'], + fields: ['id', 'created_at', 'updated_at'], context: SYSTEM_CTX, - } as never)) as { updated_at?: unknown } | null; - const moments = [toMs(user?.password_changed_at), toMs(account?.updated_at)].filter( - (ms): ms is number => ms !== undefined, - ); - return moments.length > 0 ? Math.max(...moments) : undefined; + } as never)) as { created_at?: unknown; updated_at?: unknown } | null; + const created = toMs(account?.created_at); + const updated = toMs(account?.updated_at); + if (updated === undefined) return undefined; + if (created !== undefined && updated - created <= FIRST_CREDENTIAL_WINDOW_MS) return undefined; + return updated; } /** Whether `issuedAt` falls before `userId`'s credential change; a clock that cannot be read answers yes. */ From e26ce0a7234f12ab1cb5b45a0e272a0fa858862f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:43:21 +0000 Subject: [PATCH 4/8] fix(plugin-auth): the phone door's sign-in refusal reads the vendor's own code; its race case Claude-Session: https://claude.ai/code/session_012MmDsQg43GaB78K8X6U1sL Co-authored-by: Claude --- .../src/auth-manager-after-hook.ts | 21 +++++++------- ...redential-change-ends-prior-access.test.ts | 29 ++++++++++++++++++- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts index 0c3780df173..61c443ba24c 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts @@ -172,17 +172,18 @@ async function refusedAfterTheCredential(returned: unknown): Promise { } /** The body of `createAuthInstance`'s `hooks.after` arrow; the comments there and in it are its contract. */ -/** What a wrong password answers at `door`: better-auth's own refusal there (1.7.12). */ -async function wrongPasswordAt(door: 'email' | 'phone'): Promise { +/** + * What a wrong password answers at `door`: better-auth's own refusal there + * (1.7.12), its code read off the vendor's own tables — `BASE_ERROR_CODES` for + * the email door, the phone-number plugin's `$ERROR_CODES` for the phone door — + * so no code is minted here. + */ +async function wrongPasswordAt(ctx: any, door: 'email' | 'phone'): Promise { const { APIError } = await import('better-auth/api'); - if (door === 'phone') { - return new APIError('UNAUTHORIZED', { - code: 'INVALID_PHONE_NUMBER_OR_PASSWORD', - message: 'Invalid phone number or password', - }); - } const { BASE_ERROR_CODES } = await import('@better-auth/core/error'); - return APIError.from('UNAUTHORIZED', BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); + const phoneCodes = door === 'phone' ? ctx?.context?.getPlugin?.('phone-number')?.$ERROR_CODES : undefined; + const phoneRefusal = phoneCodes?.INVALID_PHONE_NUMBER_OR_PASSWORD; + return APIError.from('UNAUTHORIZED', phoneRefusal ?? BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); } /** Whether the endpoint answered a success (no `APIError` on `returned`). */ @@ -234,7 +235,7 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) { // `credential-change-ends-prior-access.ts` states the rule. const signInDoor = passwordSignInDoorOf(ctx); const signInAcrossChange = signInDoor - ? await refuseSignInAcrossCredentialChange(ctx, () => wrongPasswordAt(signInDoor.door)) + ? await refuseSignInAcrossCredentialChange(ctx, () => wrongPasswordAt(ctx, signInDoor.door)) : undefined; if (signInAcrossChange) ctx.context.returned = signInAcrossChange; diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts index 38f6ba570cd..4adfe58d03d 100644 --- a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts @@ -20,7 +20,8 @@ * reset, and `/change-password` asked to end the other sessions (the * session it installs stands); * - a password sign-in during which the account's password changes is - * refused with what a wrong password answers, and leaves no session; + * refused with what a wrong password answers at that door (email and + * phone), and leaves no session; * - the predicate and the clock: nothing is before a change that never * happened, and the clock is the last write over the credential row. */ @@ -460,6 +461,32 @@ describe('a password sign-in during which the password changes is refused', () = expect(await s.liveSessions()).toEqual([]); }, 60_000); + it('the phone door: it answers what a wrong password answers there and leaves no session', async () => { + const s = await stage({ plugins: { phoneNumber: true }, phoneOtp: { cooldownSeconds: 0 } }); + await s.engine.update('sys_user', { id: s.userId, phone_number: PHONE, phone_number_verified: true }, SYS); + const phoneSignIn = async (password: string) => { + const res = await s.fire('/sign-in/phone-number', { phoneNumber: PHONE, password }); + return { ...(await answer(res)), bearer: res.headers.get('set-auth-token') ?? undefined }; + }; + const wrong = await phoneSignIn('Not!The-Password-1'); + expect(wrong).toMatchObject({ status: 401, code: 'INVALID_PHONE_NUMBER_OR_PASSWORD' }); + const link = await s.requestLink(); + const internal = (await s.manager.getAuthContext()).internalAdapter; + const original = internal.createSession.bind(internal); + let changed: { status: number; code?: string } | undefined; + vi.spyOn(internal, 'createSession').mockImplementation(async (...args: unknown[]) => { + if (!changed) changed = await answer(await s.fire('/reset-password', { token: link, newPassword: SECOND })); + return original(...args); + }); + + const raced = await phoneSignIn(FIRST); + + expect(changed).toEqual({ status: 200 }); + expect({ status: raced.status, code: raced.code }).toEqual({ status: wrong.status, code: wrong.code }); + if (raced.bearer) expect(await s.whoIs(raced.bearer)).toBeNull(); + expect(await s.liveSessions()).toEqual([]); + }, 60_000); + it('a sign-in the password does not change during stands (the control)', async () => { const s = await stage(); const fine = await s.signIn(EMAIL, FIRST); From 4cb593b8cc030ec5f5e3acd319ef02a60f754f60 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 21:12:24 +0000 Subject: [PATCH 5/8] =?UTF-8?q?fix(plugin-auth)!:=20a=20credential=20chang?= =?UTF-8?q?e=20ends=20access=20issued=20before=20it=20=E2=80=94=20the=20na?= =?UTF-8?q?rrowing=20is=20declared=20and=20the=20claim=20is=20as=20wide=20?= =?UTF-8?q?as=20the=20rule?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The changeset declares Clause-② no (narrowing) with its ADR-0087 disposition and BREAKING note; the changeset, the docs and the rule module name what the rule covers instead of claiming everything issued before the change; the after-hook's own docblock sits on the after-hook again, and the session re-end sits above the ADR-0069 D1 block. Claude-Session: https://claude.ai/code/session_016WV4czt69hUUaG5XcgFNYL Co-authored-by: Claude --- .changeset/credential-change-ends-prior-access.md | 10 +++++++--- content/docs/permissions/authentication.mdx | 2 +- .../plugins/plugin-auth/src/auth-manager-after-hook.ts | 10 +++++----- .../src/credential-change-ends-prior-access.ts | 5 +++-- 4 files changed, 16 insertions(+), 11 deletions(-) diff --git a/.changeset/credential-change-ends-prior-access.md b/.changeset/credential-change-ends-prior-access.md index 20b3cc24b33..b587a0b4ede 100644 --- a/.changeset/credential-change-ends-prior-access.md +++ b/.changeset/credential-change-ends-prior-access.md @@ -2,12 +2,14 @@ '@objectstack/plugin-auth': patch --- -fix(plugin-auth): a credential change ends access issued before it +fix(plugin-auth)!: a credential change ends access issued before it -Clause-②: no +Clause-②: no (narrowing) Metadata-protocol: none -Once an account's password is set, nothing issued for that account before the change grants access after it: + + +Once an account's password changes, the following, issued for that account before the change, no longer grant access after it: - An email-change link (the one `POST /api/v1/auth/change-email` mails to the new address) minted before the change answers at `GET /api/v1/auth/verify-email` exactly what a link that was never issued answers: `401 INVALID_TOKEN`, or the `error=INVALID_TOKEN` redirect to its callback. Its owner requests a new one. A link's issue time is whole seconds, so one minted in the same second as the change is refused too. - A second-factor challenge opened by a password sign-in before the change answers what a challenge that was never opened answers. The person signs in again with the new password. @@ -15,3 +17,5 @@ Once an account's password is set, nothing issued for that account before the ch - A password sign-in during which the account's password changes is refused with what a wrong password answers at that door, and leaves no session. The moment of the change is the last time the account's local password was written over, so every door that replaces a password counts, an administrator's `POST /api/v1/auth/admin/set-user-password` included. An account's first password is not a change. A check that cannot read the record refuses. Access issued after the change, and an account that never changed its local password, are untouched. No request, response or metadata shape changes. + +**BREAKING** for a client that opens an email-change link, completes a second-factor challenge, or finishes a password sign-in after the account's password changed underneath it: each is now refused as above, with the code a never-issued link, a never-opened challenge or a wrong password already answers, so a client that handles those answers needs no change. The fix for a person: request a new email-change link, or sign in again with the new password. diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 15457d81efc..a6cb88b506f 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -326,7 +326,7 @@ code still outstanding for that user: a completed reset, the user's own what one that was never issued answers (`400 INVALID_TOKEN` at `reset-password`); a link or code requested after the change works as usual. -A change to a user's password also ends the access issued before it. An +A change to a user's password also ends the following, issued before it. An email-change link minted before the change answers what a link that was never issued answers at `GET /api/v1/auth/verify-email` (`401 INVALID_TOKEN`, or the `error=INVALID_TOKEN` redirect to its callback), and a second-factor challenge diff --git a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts index 61c443ba24c..c288b225059 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts @@ -171,7 +171,6 @@ async function refusedAfterTheCredential(returned: unknown): Promise { return after.includes(code); } -/** The body of `createAuthInstance`'s `hooks.after` arrow; the comments there and in it are its contract. */ /** * What a wrong password answers at `door`: better-auth's own refusal there * (1.7.12), its code read off the vendor's own tables — `BASE_ERROR_CODES` for @@ -224,6 +223,7 @@ async function endSessionsOnceThePasswordIsWritten(this: Pick Date: Thu, 19 Nov 2026 23:21:29 +0000 Subject: [PATCH 6/8] fix(plugin-auth): the credential clock reads through the vendor's adapter; refusals that cannot read their record are pinned The clock behind "a credential change ends access issued before it" reads the account's credential row through better-auth's internal adapter, the seam its own password check reads, so a manager with no data engine judges links and challenges instead of refusing them all. New cases pin that a refused sign-in hands out no session token in its headers, that a link, a challenge and a sign-in whose record cannot be read are refused, and that the clock works on the vendor's in-memory adapter. The changeset names every email-change link the rule judges. Claude-Session: https://claude.ai/code/session_016WV4czt69hUUaG5XcgFNYL Co-authored-by: Claude --- .../credential-change-ends-prior-access.md | 2 +- .../src/auth-manager-before-hook.ts | 4 +- ...redential-change-ends-prior-access.test.ts | 176 ++++++++++++++++-- .../credential-change-ends-prior-access.ts | 55 +++--- 4 files changed, 194 insertions(+), 43 deletions(-) diff --git a/.changeset/credential-change-ends-prior-access.md b/.changeset/credential-change-ends-prior-access.md index b587a0b4ede..b26867b4ed5 100644 --- a/.changeset/credential-change-ends-prior-access.md +++ b/.changeset/credential-change-ends-prior-access.md @@ -11,7 +11,7 @@ Metadata-protocol: none Once an account's password changes, the following, issued for that account before the change, no longer grant access after it: -- An email-change link (the one `POST /api/v1/auth/change-email` mails to the new address) minted before the change answers at `GET /api/v1/auth/verify-email` exactly what a link that was never issued answers: `401 INVALID_TOKEN`, or the `error=INVALID_TOKEN` redirect to its callback. Its owner requests a new one. A link's issue time is whole seconds, so one minted in the same second as the change is refused too. +- An email-change link (any link `POST /api/v1/auth/change-email` mints for the account, whichever address it is mailed to) minted before the change answers at `GET /api/v1/auth/verify-email` exactly what a link that was never issued answers: `401 INVALID_TOKEN`, or the `error=INVALID_TOKEN` redirect to its callback. Its owner requests a new one. A link's issue time is whole seconds, so one minted in the same second as the change is refused too. - A second-factor challenge opened by a password sign-in before the change answers what a challenge that was never opened answers. The person signs in again with the new password. - A door that ends the account's sessions when it sets the password ends every session opened before its password write: both reset doors, `POST /api/v1/auth/change-password` with `revokeOtherSessions: true` (the session it installs is kept), and the one-step invitation acceptance (ahead of the session it opens). - A password sign-in during which the account's password changes is refused with what a wrong password answers at that door, and leaves no session. diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts index 3e30a2aab0d..cbde0f9df4f 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -267,9 +267,9 @@ export async function globalBeforeHook( // change answers what a link never issued answers, and a second-factor // challenge opened before it is ended. `credential-change-ends-prior- // access.ts` states the rule and its one predicate. - const endedEmailChange = await endEmailChangeTokenIssuedBeforeCredentialChange(ctx, this.getDataEngine()); + const endedEmailChange = await endEmailChangeTokenIssuedBeforeCredentialChange(ctx); if (endedEmailChange) return endedEmailChange; - await endTwoFactorChallengeIssuedBeforeCredentialChange(ctx, this.getDataEngine()); + await endTwoFactorChallengeIssuedBeforeCredentialChange(ctx); // ── [#33203] Cloud-managed: no reset door sets a local password ── // A hosted environment sets no local password for anyone, a platform diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts index 4adfe58d03d..ed55c71f6a7 100644 --- a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts @@ -103,6 +103,15 @@ async function answer(res: Response): Promise<{ status: number; code?: string }> const cookieOf = (res: Response): string => (res.headers.getSetCookie?.() ?? []).map((c) => c.split(';')[0]).filter(Boolean).join('; '); +/** + * Whether a response hands its caller a session in its headers: a + * `set-auth-token` header, or a session cookie set to a value (a cookie + * cleared to empty hands out none). + */ +const handsOutSession = (res: Response): boolean => + res.headers.get('set-auth-token') !== null + || (res.headers.getSetCookie?.() ?? []).some((c) => /session_(token|data)=[^;]+/.test(c.split(';')[0])); + // RFC 6238 TOTP, hand-rolled as `two-factor-reenrollment-verified-reset.test.ts` does. function base32Decode(input: string): Buffer { const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; @@ -196,6 +205,7 @@ async function stage(config: Record = {}) { return { ...(await answer(res)), bearer: res.headers.get('set-auth-token') ?? undefined, + handsOutSession: handsOutSession(res), challenge: body?.twoFactorRedirect === true ? cookieOf(res) : undefined, }; }; @@ -269,6 +279,17 @@ function advanceTheClock() { vi.setSystemTime(Date.now() + 2_000); } +/** Turn on a TOTP second factor for the account `bearer` signs in as, and answer its secret. */ +async function enrolTotp(s: Awaited>, bearer: string): Promise { + const enabled = await s.fire('/two-factor/enable', { password: FIRST }, s.bearer(bearer)); + expect(enabled.status, await enabled.clone().text()).toBe(200); + const { totpURI } = (await enabled.json()) as { totpURI: string }; + const secret = base32Decode(String(new URL(totpURI.replace('otpauth://', 'https://')).searchParams.get('secret'))); + const confirmed = await s.fire('/two-factor/verify-totp', { code: totp(secret) }, s.bearer(bearer)); + expect(confirmed.status, await confirmed.clone().text()).toBe(200); + return secret; +} + describe('an email-change link issued before a credential change answers what a link never issued answers', () => { it('after a completed reset: no session, the address stays; a link minted after the reset verifies', async () => { const s = await stage(); @@ -457,7 +478,8 @@ describe('a password sign-in during which the password changes is refused', () = expect(changed).toEqual({ status: 200 }); expect({ status: raced.status, code: raced.code }).toEqual({ status: wrong.status, code: wrong.code }); - if (raced.bearer) expect(await s.whoIs(raced.bearer)).toBeNull(); + expect(wrong.handsOutSession, 'a wrong password hands out no session').toBe(false); + expect(raced.handsOutSession, 'the refused sign-in hands out no session token in its headers').toBe(false); expect(await s.liveSessions()).toEqual([]); }, 60_000); @@ -466,10 +488,12 @@ describe('a password sign-in during which the password changes is refused', () = await s.engine.update('sys_user', { id: s.userId, phone_number: PHONE, phone_number_verified: true }, SYS); const phoneSignIn = async (password: string) => { const res = await s.fire('/sign-in/phone-number', { phoneNumber: PHONE, password }); - return { ...(await answer(res)), bearer: res.headers.get('set-auth-token') ?? undefined }; + return { ...(await answer(res)), handsOutSession: handsOutSession(res) }; }; const wrong = await phoneSignIn('Not!The-Password-1'); expect(wrong).toMatchObject({ status: 401, code: 'INVALID_PHONE_NUMBER_OR_PASSWORD' }); + const fine = await phoneSignIn(FIRST); + expect(fine, 'the control: the phone door hands out a session to the right password').toMatchObject({ status: 200, handsOutSession: true }); const link = await s.requestLink(); const internal = (await s.manager.getAuthContext()).internalAdapter; const original = internal.createSession.bind(internal); @@ -483,7 +507,8 @@ describe('a password sign-in during which the password changes is refused', () = expect(changed).toEqual({ status: 200 }); expect({ status: raced.status, code: raced.code }).toEqual({ status: wrong.status, code: wrong.code }); - if (raced.bearer) expect(await s.whoIs(raced.bearer)).toBeNull(); + expect(wrong.handsOutSession, 'a wrong password hands out no session').toBe(false); + expect(raced.handsOutSession, 'the refused sign-in hands out no session token in its headers').toBe(false); expect(await s.liveSessions()).toEqual([]); }, 60_000); @@ -491,10 +516,133 @@ describe('a password sign-in during which the password changes is refused', () = const s = await stage(); const fine = await s.signIn(EMAIL, FIRST); expect(fine.status).toBe(200); + expect(fine.handsOutSession).toBe(true); expect(await s.whoIs(fine.bearer!)).toBe(s.userId); }, 60_000); }); +describe('a check that cannot read its record refuses', () => { + /** The account's credential row cannot be read through the vendor's adapter, until the spy is restored. */ + async function unreadableCredential(s: Awaited>) { + const internal = (await s.manager.getAuthContext()).internalAdapter; + return vi.spyOn(internal, 'findCredentialAccount').mockRejectedValue(new Error('the credential row cannot be read')); + } + + it('an email-change link whose clock cannot be read answers what a link never issued answers; read again, it verifies', async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + const link = await s.requestEmailChange(user.bearer!); + const neverIssued = await s.verifyEmail('a-token-never-issued'); + + const unreadable = await unreadableCredential(s); + expect(await s.verifyEmail(link)).toEqual(neverIssued); + expect(unreadable).toHaveBeenCalled(); + expect(await s.emailOf()).toBe(EMAIL); + + // The control: the account never changed its password, so the same link verifies once the clock reads. + unreadable.mockRestore(); + expect(await s.verifyEmail(link)).toMatchObject({ status: 200 }); + expect(await s.emailOf()).toBe(NEW_ADDRESS); + }, 60_000); + + it('a second-factor challenge whose clock cannot be read answers what a challenge never opened answers', async () => { + const s = await stage({ plugins: { twoFactor: true } }); + const secret = await enrolTotp(s, (await s.signIn(EMAIL, FIRST)).bearer!); + const opened = await s.signIn(EMAIL, FIRST); + expect(opened.challenge, 'the password sign-in stops at the challenge').toBeTruthy(); + const neverOpened = await answer(await s.fire('/two-factor/verify-totp', { code: totp(secret) })); + + const unreadable = await unreadableCredential(s); + expect(await answer(await s.fire('/two-factor/verify-totp', { code: totp(secret) }, { cookie: opened.challenge! }))).toEqual(neverOpened); + expect(unreadable).toHaveBeenCalled(); + unreadable.mockRestore(); + + // The control: a challenge verified while the clock reads completes. + const fresh = await s.signIn(EMAIL, FIRST); + const completed = await s.fire('/two-factor/verify-totp', { code: totp(secret) }, { cookie: fresh.challenge! }); + expect(completed.status, await completed.clone().text()).toBe(200); + }, 60_000); + + it('a password sign-in whose first reading cannot be taken answers what a wrong password answers and leaves no session', async () => { + const s = await stage(); + const wrong = await s.signIn(EMAIL, 'Not!The-Password-1'); + const internal = (await s.manager.getAuthContext()).internalAdapter; + const original = internal.findCredentialAccount.bind(internal); + let refusedReads = 0; + vi.spyOn(internal, 'findCredentialAccount').mockImplementation(async (...args: unknown[]) => { + if (refusedReads === 0) { + refusedReads += 1; + throw new Error('the credential row cannot be read'); + } + return (original as (...a: unknown[]) => Promise)(...args); + }); + + const refused = await s.signIn(EMAIL, FIRST); + + expect(refusedReads, 'the first reading was the one that failed').toBe(1); + expect({ status: refused.status, code: refused.code }).toEqual({ status: wrong.status, code: wrong.code }); + expect(refused.handsOutSession).toBe(false); + expect(await s.liveSessions()).toEqual([]); + }, 60_000); +}); + +describe('the clock needs no data engine', () => { + it('on the vendor in-memory adapter: a link of an account that never changed its password verifies; one minted before a change does not', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'info').mockImplementation(() => {}); + // No `dataEngine`: the manager runs on better-auth's own in-memory adapter. + const manager = new AuthManager({ secret: SECRET, baseUrl: ORIGIN } as never); + const mail: Array<{ template: string; to?: { address?: string }; data: Record }> = []; + manager.setEmailService({ + sendTemplate: async (input: any) => { + mail.push(input); + return { status: 'sent' }; + }, + } as never); + const app = new Hono(); + const ctx = mockCtx(); + const plugin = new AuthPlugin({ secret: SECRET }); + await plugin.init(ctx); + (plugin as any).authManager = manager; + (plugin as any).registerAuthRoutes({ getRawApp: () => app, getPort: () => 0 }, ctx); + const fire = (path: string, body: unknown, headers: Record = {}) => + app.request(`${ORIGIN}${BASE}${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN, ...headers }, + body: JSON.stringify(body), + }); + const verify = async (token: string) => + answer(await app.request(`${ORIGIN}${BASE}/verify-email?token=${encodeURIComponent(token)}`, { headers: { origin: ORIGIN } })); + const linkTo = async (bearer: string, newEmail: string): Promise => { + const sent = () => mail.filter((m) => m.template === 'auth.verify_email' && m.to?.address === newEmail); + const before = sent().length; + const res = await fire('/change-email', { newEmail, callbackURL: '/' }, { authorization: `Bearer ${bearer}` }); + expect(res.status, `change-email: ${await res.clone().text()}`).toBe(200); + await vi.waitFor(() => expect(sent().length).toBe(before + 1)); + return String(sent()[before].data.token); + }; + const signedUp = await fire('/sign-up/email', { email: EMAIL, password: FIRST, name: EMAIL }); + expect(signedUp.status, await signedUp.clone().text()).toBe(200); + const signedIn = await fire('/sign-in/email', { email: EMAIL, password: FIRST }); + expect(signedIn.status, await signedIn.clone().text()).toBe(200); + const bearer = String(signedIn.headers.get('set-auth-token')); + const internal = (await manager.getAuthContext()).internalAdapter; + const addressNow = async () => (await internal.findUserByEmail(NEW_ADDRESS)) ? NEW_ADDRESS : 'unchanged'; + const neverIssued = await verify('a-token-never-issued'); + + // Never changed: the link verifies. + expect(await verify(await linkTo(bearer, 'prior-access-first-move@example.com'))).toMatchObject({ status: 200 }); + + // Minted before a change: it answers what a link never issued answers. + const before = await linkTo(bearer, NEW_ADDRESS); + advanceTheClock(); + const changed = await fire('/change-password', { currentPassword: FIRST, newPassword: SECOND }, { authorization: `Bearer ${bearer}` }); + expect(changed.status, await changed.clone().text()).toBe(200); + expect(await verify(before)).toEqual(neverIssued); + expect(await addressNow()).toBe('unchanged'); + }, 60_000); +}); + describe('the predicate and its clock', () => { it('nothing is before a change that never happened; an unreadable issue time is before one that did', () => { expect(issuedBeforeCredentialChange(1_000, undefined)).toBe(false); @@ -504,18 +652,20 @@ describe('the predicate and its clock', () => { }); it('the clock is the last write over the credential row; its creation and no row are no change', async () => { - const engine = (account: unknown) => ({ findOne: async () => account }); + const reader = (account: unknown) => ({ findCredentialAccount: async () => account }) as never; const created = '2026-01-01T00:00:00.000Z'; - expect(await readCredentialChangedAt(engine(null) as never, 'u')).toBeUndefined(); - expect(await readCredentialChangedAt(engine({ created_at: created, updated_at: created }) as never, 'u')).toBeUndefined(); - expect( - await readCredentialChangedAt(engine({ created_at: created, updated_at: '2026-01-01T00:00:00.900Z' }) as never, 'u'), - ).toBeUndefined(); - expect( - await readCredentialChangedAt(engine({ created_at: created, updated_at: '2026-02-01T00:00:00.000Z' }) as never, 'u'), - ).toBe(Date.parse('2026-02-01T00:00:00.000Z')); + expect(await readCredentialChangedAt(reader(null), 'u')).toBeUndefined(); + expect(await readCredentialChangedAt(reader({ createdAt: created, updatedAt: created }), 'u')).toBeUndefined(); + expect(await readCredentialChangedAt(reader({ createdAt: created, updatedAt: '2026-01-01T00:00:00.900Z' }), 'u')).toBeUndefined(); + expect(await readCredentialChangedAt(reader({ createdAt: created, updatedAt: '2026-02-01T00:00:00.000Z' }), 'u')).toBe( + Date.parse('2026-02-01T00:00:00.000Z'), + ); + // The adapter answers `Date` values. + expect(await readCredentialChangedAt(reader({ createdAt: new Date(created), updatedAt: new Date('2026-02-01T00:00:00.000Z') }), 'u')).toBe( + Date.parse('2026-02-01T00:00:00.000Z'), + ); await expect( - readCredentialChangedAt({ findOne: async () => { throw new Error('down'); } } as never, 'u'), + readCredentialChangedAt({ findCredentialAccount: async () => { throw new Error('down'); } } as never, 'u'), ).rejects.toThrow('down'); }); }); diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts index b2b03001c05..3598560f527 100644 --- a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts @@ -33,8 +33,11 @@ * issued strictly before the account's credential change is refused. The * change's moment is {@link readCredentialChangedAt}: the last time the * account's local credential row (`sys_account`, provider `credential`) was - * written over, its `updated_at`. Every door that replaces a password writes - * that row — both reset doors, `/change-password`, an administrator's + * written over, its `updated_at`. It is read through better-auth's internal + * adapter (`findCredentialAccount`), the same row and the same seam the + * vendor reads to check a password, so the clock needs no data engine: a + * manager on the vendor's in-memory adapter reads it as well. Every door that + * replaces a password writes that row — both reset doors, `/change-password`, an administrator's * `/admin/set-user-password`, the one-step invitation door — whether or not it * also stamps `sys_user.password_changed_at`. The row's creation is the * account's first password, not a change: a row written over within @@ -65,11 +68,6 @@ * reset records (`session-tombstone.ts`). */ -import type { IDataEngine } from '@objectstack/core'; -import { SystemObjectName } from '@objectstack/spec/system'; - -const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] }; - /** The path of better-auth's email verification door. */ export const VERIFY_EMAIL_PATH = '/verify-email'; @@ -119,7 +117,14 @@ function toMs(value: unknown): number | undefined { return Number.isFinite(ms) ? ms : undefined; } -type ClockEngine = Pick; +/** + * The seam the clock reads through: better-auth's internal adapter, whose + * `findCredentialAccount` answers the account's local credential row (provider + * `credential`, `accountId` the user's id) with its `createdAt` / `updatedAt`. + */ +export interface CredentialClockReader { + findCredentialAccount(userId: string): Promise<{ createdAt?: unknown; updatedAt?: unknown } | null | undefined>; +} /** * How long after its creation a credential row's own write still counts as @@ -133,24 +138,24 @@ export const FIRST_CREDENTIAL_WINDOW_MS = 1_000; * `undefined` when it has never had one. Throws when the record cannot be * read, so a caller refuses. */ -export async function readCredentialChangedAt(engine: ClockEngine, userId: string): Promise { - const account = (await engine.findOne(SystemObjectName.ACCOUNT, { - where: { user_id: userId, provider_id: 'credential' }, - fields: ['id', 'created_at', 'updated_at'], - context: SYSTEM_CTX, - } as never)) as { created_at?: unknown; updated_at?: unknown } | null; - const created = toMs(account?.created_at); - const updated = toMs(account?.updated_at); +export async function readCredentialChangedAt(reader: CredentialClockReader, userId: string): Promise { + const account = await reader.findCredentialAccount(userId); + const created = toMs(account?.createdAt); + const updated = toMs(account?.updatedAt); if (updated === undefined) return undefined; if (created !== undefined && updated - created <= FIRST_CREDENTIAL_WINDOW_MS) return undefined; return updated; } -/** Whether `issuedAt` falls before `userId`'s credential change; a clock that cannot be read answers yes. */ -async function issuedBeforeChangeOf(engine: ClockEngine | undefined, userId: string, issuedAtMs: number): Promise { - if (!engine) return true; +/** + * Whether `issuedAt` falls before `userId`'s credential change, read through + * the request's own internal adapter; a clock that cannot be read answers yes. + */ +async function issuedBeforeChangeOf(ctx: any, userId: string, issuedAtMs: number): Promise { + const reader: CredentialClockReader | undefined = ctx?.context?.internalAdapter; + if (typeof reader?.findCredentialAccount !== 'function') return true; try { - return issuedBeforeCredentialChange(issuedAtMs, await readCredentialChangedAt(engine, userId)); + return issuedBeforeCredentialChange(issuedAtMs, await readCredentialChangedAt(reader, userId)); } catch { return true; } @@ -166,7 +171,6 @@ async function issuedBeforeChangeOf(engine: ClockEngine | undefined, userId: str */ export async function endEmailChangeTokenIssuedBeforeCredentialChange( ctx: any, - engine: ClockEngine | undefined, ): Promise<{ context: { query: Record } } | undefined> { if (ctx?.path !== VERIFY_EMAIL_PATH) return undefined; const token: unknown = ctx?.query?.token; @@ -191,7 +195,7 @@ export async function endEmailChangeTokenIssuedBeforeCredentialChange( // No account at the address: the vendor's own refusal answers it. if (!userId) return undefined; const issuedAtMs = typeof claims.iat === 'number' ? claims.iat * 1000 : Number.NaN; - return (await issuedBeforeChangeOf(engine, userId, issuedAtMs)) ? ended : undefined; + return (await issuedBeforeChangeOf(ctx, userId, issuedAtMs)) ? ended : undefined; } /** @@ -200,10 +204,7 @@ export async function endEmailChangeTokenIssuedBeforeCredentialChange( * the account's credential change, so the vendor's own check finds no * challenge. Throws when the challenge cannot be ended. */ -export async function endTwoFactorChallengeIssuedBeforeCredentialChange( - ctx: any, - engine: ClockEngine | undefined, -): Promise { +export async function endTwoFactorChallengeIssuedBeforeCredentialChange(ctx: any): Promise { if (!TWO_FACTOR_VERIFY_PATHS.has(ctx?.path)) return; const cookie = ctx?.context?.createAuthCookie?.(TWO_FACTOR_COOKIE); if (!cookie?.name || typeof ctx?.getSignedCookie !== 'function') return; @@ -214,7 +215,7 @@ export async function endTwoFactorChallengeIssuedBeforeCredentialChange( if (!challenge) return; const userId = typeof challenge.value === 'string' ? challenge.value : ''; const issuedAtMs = toMs(challenge.createdAt) ?? Number.NaN; - if (userId && !(await issuedBeforeChangeOf(engine, userId, issuedAtMs))) return; + if (userId && !(await issuedBeforeChangeOf(ctx, userId, issuedAtMs))) return; await internal.deleteVerificationByIdentifier(identifier); await internal.deleteVerificationByIdentifier(`${TWO_FACTOR_ATTEMPTS_PREFIX}${identifier}`); } From b6285e3a27a9384d79ea95a21454e46c4c66cb31 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 23:45:28 +0000 Subject: [PATCH 7/8] fix(plugin-auth): the phone sign-in's first reading names its account through the vendor's adapter; the refusal cases pin what they claim The first reading of `/sign-in/phone-number` named its account through the data engine, so a manager without one took no reading and refused every phone sign-in. It now names the account with the lookup the vendor's phone door makes, through the vendor's adapter, as the email door already does. The case for a sign-in whose first reading cannot be taken compares the account's sessions before and after the refused sign-in (the session sign-up opened stands throughout), and a control sign-in afterwards adds one. The case for a manager without a data engine creates its account with the administrator's create-user called in-process, since no sign-up door admits an account without a data engine, and signs in at both password doors. Claude-Session: https://claude.ai/code/session_016WV4czt69hUUaG5XcgFNYL Co-authored-by: Claude --- .../src/auth-manager-before-hook.ts | 15 +++---- ...redential-change-ends-prior-access.test.ts | 40 +++++++++++++++---- 2 files changed, 40 insertions(+), 15 deletions(-) diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts index cbde0f9df4f..c454cffb0ce 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -64,7 +64,7 @@ import { isCloudManaged } from '@objectstack/core'; import { VENDOR_ROLE_SCALAR_ADMIN_PATHS } from './admin-impersonate-endpoint.js'; import { setAuthActorResolver } from './auth-actor-attribution.js'; import { AuthManager } from './auth-manager.js'; -import { findPhoneSignInAccount, passwordSignInDoorOf, recordLockoutRequest } from './auth-manager-sign-in-lockout.js'; +import { passwordSignInDoorOf, recordLockoutRequest } from './auth-manager-sign-in-lockout.js'; import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.js'; import { endEmailChangeTokenIssuedBeforeCredentialChange, @@ -968,15 +968,16 @@ export async function globalBeforeHook( if (passwordDoor.identifier) await this.admitSignInAttempt(passwordDoor.identifier, ctx, passwordDoor.door); // A sign-in during which the account's password changes is refused: the // first of its two readings (`credential-change-ends-prior-access.ts`). + // Each door's account is the one the vendor's own lookup at that door + // names, read through the vendor's adapter, so the reading needs no data + // engine. const { door, identifier } = passwordDoor; await noteSignInCredential(ctx, async () => { if (!identifier) return undefined; - if (door === 'phone') { - const engine = this.getDataEngine(); - return engine ? (await findPhoneSignInAccount(engine, identifier, []))?.id : undefined; - } - const found = await ctx.context.internalAdapter.findUserByEmail(identifier.toLowerCase()); - const id: unknown = found?.user?.id; + const id: unknown = + door === 'phone' + ? (await ctx.context.adapter.findOne({ model: 'user', where: [{ field: 'phoneNumber', value: identifier }] }))?.id + : (await ctx.context.internalAdapter.findUserByEmail(identifier.toLowerCase()))?.user?.id; return typeof id === 'string' && id.length > 0 ? id : undefined; }); return; diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts index ed55c71f6a7..ca14e15d513 100644 --- a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts @@ -577,21 +577,30 @@ describe('a check that cannot read its record refuses', () => { return (original as (...a: unknown[]) => Promise)(...args); }); + // The session sign-up opened stands throughout; the refused sign-in adds none to it. + const tokens = async () => (await s.liveSessions()).map((row) => row.token).sort(); + const sessionsBefore = await tokens(); const refused = await s.signIn(EMAIL, FIRST); expect(refusedReads, 'the first reading was the one that failed').toBe(1); expect({ status: refused.status, code: refused.code }).toEqual({ status: wrong.status, code: wrong.code }); expect(refused.handsOutSession).toBe(false); - expect(await s.liveSessions()).toEqual([]); + expect(await tokens()).toEqual(sessionsBefore); + + // The control: with both readings taken, the same sign-in stands and adds its session. + const fine = await s.signIn(EMAIL, FIRST); + expect(fine).toMatchObject({ status: 200, handsOutSession: true }); + expect(await s.whoIs(fine.bearer!)).toBe(s.userId); + expect((await tokens()).length).toBe(sessionsBefore.length + 1); }, 60_000); }); -describe('the clock needs no data engine', () => { - it('on the vendor in-memory adapter: a link of an account that never changed its password verifies; one minted before a change does not', async () => { +describe('the clock and the sign-in readings need no data engine', () => { + it('on the vendor in-memory adapter: a link of an account that never changed its password verifies; one minted before a change does not; both password doors sign in', async () => { vi.spyOn(console, 'warn').mockImplementation(() => {}); vi.spyOn(console, 'info').mockImplementation(() => {}); // No `dataEngine`: the manager runs on better-auth's own in-memory adapter. - const manager = new AuthManager({ secret: SECRET, baseUrl: ORIGIN } as never); + const manager = new AuthManager({ secret: SECRET, baseUrl: ORIGIN, plugins: { admin: true, phoneNumber: true } } as never); const mail: Array<{ template: string; to?: { address?: string }; data: Record }> = []; manager.setEmailService({ sendTemplate: async (input: any) => { @@ -599,6 +608,7 @@ describe('the clock needs no data engine', () => { return { status: 'sent' }; }, } as never); + manager.setSmsService({ send: async () => ({ id: 'sms', status: 'sent' }), isConfigured: () => true } as never); const app = new Hono(); const ctx = mockCtx(); const plugin = new AuthPlugin({ secret: SECRET }); @@ -621,13 +631,22 @@ describe('the clock needs no data engine', () => { await vi.waitFor(() => expect(sent().length).toBe(before + 1)); return String(sent()[before].data.token); }; - const signedUp = await fire('/sign-up/email', { email: EMAIL, password: FIRST, name: EMAIL }); - expect(signedUp.status, await signedUp.clone().text()).toBe(200); + + // Without a data engine no sign-up door admits an account (no posture can + // prove a first run or resolve a grant there): the account is created the + // operator's way, by the administrator's create-user called in-process. + const api: any = await manager.getApi(); + await api.createUser({ body: { email: EMAIL, name: EMAIL, password: FIRST } }); + const auth: any = await manager.getAuthContext(); + const internal = auth.internalAdapter; + const userId = String((await internal.findUserByEmail(EMAIL))?.user?.id); + await auth.adapter.update({ model: 'user', where: [{ field: 'id', value: userId }], update: { phoneNumber: PHONE, phoneNumberVerified: true } }); + const signedIn = await fire('/sign-in/email', { email: EMAIL, password: FIRST }); expect(signedIn.status, await signedIn.clone().text()).toBe(200); + expect(handsOutSession(signedIn), 'the email door hands out a session').toBe(true); const bearer = String(signedIn.headers.get('set-auth-token')); - const internal = (await manager.getAuthContext()).internalAdapter; - const addressNow = async () => (await internal.findUserByEmail(NEW_ADDRESS)) ? NEW_ADDRESS : 'unchanged'; + const addressNow = async () => ((await internal.findUserByEmail(NEW_ADDRESS)) ? NEW_ADDRESS : 'unchanged'); const neverIssued = await verify('a-token-never-issued'); // Never changed: the link verifies. @@ -640,6 +659,11 @@ describe('the clock needs no data engine', () => { expect(changed.status, await changed.clone().text()).toBe(200); expect(await verify(before)).toEqual(neverIssued); expect(await addressNow()).toBe('unchanged'); + + // The phone door's first reading names its account through the vendor's adapter too. + const byPhone = await fire('/sign-in/phone-number', { phoneNumber: PHONE, password: SECOND }); + expect(byPhone.status, await byPhone.clone().text()).toBe(200); + expect(handsOutSession(byPhone), 'the phone door hands out a session').toBe(true); }, 60_000); }); From b5cbc6ad19fe850a64cb98c4bf553cbbb3d5a128 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:23:04 +0000 Subject: [PATCH 8/8] docs(plugin-auth): the changeset names every email-change link the rule judges, at either step of the flow An email-change link is judged whichever step of the flow mailed it: the confirmation `POST /change-email` sends the current address, and the link to the new address, whether `/change-email` mails it directly or the confirmation step does. The changeset's parenthesis now says so. The predicate module's docblock paragraph on the clock is re-wrapped; no code moves. Claude-Session: https://claude.ai/code/session_016WV4czt69hUUaG5XcgFNYL Co-authored-by: Claude --- .changeset/credential-change-ends-prior-access.md | 2 +- .../src/credential-change-ends-prior-access.ts | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.changeset/credential-change-ends-prior-access.md b/.changeset/credential-change-ends-prior-access.md index b26867b4ed5..6e17d42bf92 100644 --- a/.changeset/credential-change-ends-prior-access.md +++ b/.changeset/credential-change-ends-prior-access.md @@ -11,7 +11,7 @@ Metadata-protocol: none Once an account's password changes, the following, issued for that account before the change, no longer grant access after it: -- An email-change link (any link `POST /api/v1/auth/change-email` mints for the account, whichever address it is mailed to) minted before the change answers at `GET /api/v1/auth/verify-email` exactly what a link that was never issued answers: `401 INVALID_TOKEN`, or the `error=INVALID_TOKEN` redirect to its callback. Its owner requests a new one. A link's issue time is whole seconds, so one minted in the same second as the change is refused too. +- An email-change link (any link the email-change flow begun at `POST /api/v1/auth/change-email` mails, at either of its steps and to either address: the confirmation sent to the current address, and the link sent to the new one) minted before the change answers at `GET /api/v1/auth/verify-email` exactly what a link that was never issued answers: `401 INVALID_TOKEN`, or the `error=INVALID_TOKEN` redirect to its callback. Its owner requests a new one. A link's issue time is whole seconds, so one minted in the same second as the change is refused too. - A second-factor challenge opened by a password sign-in before the change answers what a challenge that was never opened answers. The person signs in again with the new password. - A door that ends the account's sessions when it sets the password ends every session opened before its password write: both reset doors, `POST /api/v1/auth/change-password` with `revokeOtherSessions: true` (the session it installs is kept), and the one-step invitation acceptance (ahead of the session it opens). - A password sign-in during which the account's password changes is refused with what a wrong password answers at that door, and leaves no session. diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts index 3598560f527..7e638e09268 100644 --- a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts @@ -37,13 +37,13 @@ * adapter (`findCredentialAccount`), the same row and the same seam the * vendor reads to check a password, so the clock needs no data engine: a * manager on the vendor's in-memory adapter reads it as well. Every door that - * replaces a password writes that row — both reset doors, `/change-password`, an administrator's - * `/admin/set-user-password`, the one-step invitation door — whether or not it - * also stamps `sys_user.password_changed_at`. The row's creation is the - * account's first password, not a change: a row written over within - * {@link FIRST_CREDENTIAL_WINDOW_MS} of its creation reads as never written - * over, and an account with no local credential has never changed one. In - * either case nothing is refused. + * replaces a password writes that row — both reset doors, `/change-password`, + * an administrator's `/admin/set-user-password`, the one-step invitation door + * — whether or not it also stamps `sys_user.password_changed_at`. The row's + * creation is the account's first password, not a change: a row written over + * within {@link FIRST_CREDENTIAL_WINDOW_MS} of its creation reads as never + * written over, and an account with no local credential has never changed + * one. In either case nothing is refused. * * A token's issue time is the `iat` the vendor signs into it, whole seconds: * a token minted in the same second as the change, after it, is refused too.