diff --git a/.changeset/credential-change-ends-reset-tokens.md b/.changeset/credential-change-ends-reset-tokens.md new file mode 100644 index 00000000000..8a4553bf883 --- /dev/null +++ b/.changeset/credential-change-ends-reset-tokens.md @@ -0,0 +1,16 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth)!: a change to a user's credential ends every other outstanding password-reset token of that user + +Clause-②: no (narrowing) — a password write through either of this plugin's storage adapters (the factory `AuthManager` composes, and the exported raw `createObjectQLAdapter`) ends every other password-reset link and texted reset code still outstanding for that user, in the same request and before the new password is written. In the `AuthManager` composition that is every door that sets a password: a completed reset (`POST /reset-password`, `POST /phone-number/reset-password`), the user's own `POST /change-password`, an administrator's `POST /admin/set-user-password`, and a first password (`POST /set-initial-password`). No request, response or metadata shape is added, removed or re-shaped; a link or code requested after the change resets as usual. +Metadata-protocol: none + + + +**BREAKING** password-reset narrowing (`@objectstack/plugin-auth`): a change to a user's credential ends every other outstanding password-reset token of that user. + +- **Now.** When a user's password is set through either storage adapter, every reset link (`/request-password-reset`) and texted reset code (`/phone-number/request-password-reset`) issued for that user beforehand is ended. In the `AuthManager` composition an ended link or code answers exactly what one never issued answers: `400 INVALID_TOKEN` at `POST /reset-password`, the `INVALID_TOKEN` redirect at the link's landing (`GET /reset-password/:token`), and the never-sent answer at `POST /phone-number/reset-password`; with a host `secondaryStorage` there, its cached copy is removed too. A password write whose outstanding tokens cannot be ended, or whose cached copies cannot be named, does not land: the door answers an error and the old password stands. So does every password write when `verification.storeIdentifier` is set to anything but `plain`, because the tokens cannot be found under it; the `AuthManager` composition never sets it. +- **The raw `createObjectQLAdapter`.** It is handed none of better-auth's options, so through it the rule covers the token rows only. A host that pairs it with a `secondaryStorage` or a `verification.storeIdentifier` setting is outside the rule; compose the factory, `createObjectQLAdapterFactory`, as `AuthManager` does. +- **Who moves.** A person holding a reset link or code issued before their password changed requests a new one. Nothing else changes: another user's links and codes, and a link or code requested after the change, reset as before. diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 255c4228308..1df1c0239c5 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -314,6 +314,14 @@ the user signs in again with the new password. It is not a setting: the former configuration that still carries it, at any value, is refused at boot — delete the key. +Any change to a user's password ends every other reset link and texted reset +code still outstanding for that user: a completed reset, the user's own +`POST /api/v1/auth/change-password`, an administrator's +`POST /api/v1/auth/admin/set-user-password` and a first password set through +`POST /api/v1/auth/set-initial-password`. An ended link or code answers exactly +what one that was never issued answers (`400 INVALID_TOKEN` at +`reset-password`); a link or code requested after the change works as usual. + #### Setting a first local password `POST /api/v1/auth/set-initial-password` sets an **initial** local password for a diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md index 288ee34d6a4..f0ba430bd55 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 95 | +| Write call sites | 98 | | Object name statically decidable | 58 | -| Object name chosen at run time | 37 | +| Object name chosen at run time | 40 | | Object name spelled inline | 47 | | Object name spelled through a `const` | 11 | | Object name is an `object: string` parameter | 2 | -| Object name is some other run-time expression | 35 | +| Object name is some other run-time expression | 38 | | Against a tenancy-enabled object | 56 | | Against an object declaring tenancy off | 2 | | Threading a tenant context | 55 | -| Provably carrying none (options read, no context key) | 12 | +| Provably carrying none (options read, no context key) | 15 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 28 | | …and decidably tenancy-enabled | 16 | | Threading a decidably elevated (`isSystem`) context | 38 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 45 | -| Receiver carried a readable engine type | 69 | +| Receiver carried a readable engine type | 72 | | Receiver erased, placed by the object NAME | 24 | | Receiver erased, placed by an `object: string` PARAMETER | 1 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 1 | @@ -69,6 +69,7 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-auth/src/auth-plugin.ts` | `update` | `sys_oauth_application` | enabled | PROVABLY NONE | 1 | | `packages/plugins/plugin-auth/src/auth-plugin.ts` | `update` | `sys_user` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/auth-plugin.ts` | `update` | `SystemObjectName.USER` | undecidable | elevated | 1 | +| `packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.ts` | `delete` | `VERIFICATION` | undecidable | PROVABLY NONE | 3 | | `packages/plugins/plugin-auth/src/default-organization-invariant.ts` | `insert` | `sys_organization` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/demo-staff.ts` | `update` | `sys_user` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/demo-staff.ts` | `insert` | `sys_user_permission_set` | enabled | elevated | 1 | diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.test.ts b/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.test.ts new file mode 100644 index 00000000000..755dfef1fbd --- /dev/null +++ b/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.test.ts @@ -0,0 +1,558 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A change to a user's credential ends every other outstanding password-reset + * token of that user (`credential-change-ends-reset-tokens.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 — the administrator's + * `/admin/set-user-password` included, which that mount serves itself. + * + * Pinned: + * - after a completed emailed-link reset, the user's other link answers what + * a link never issued answers, whichever of the two was spent first, and + * the password is the one the spent link set; + * - after the user's own `/change-password` and after an administrator's + * `/admin/set-user-password`, every link outstanding before the change + * answers what a link never issued answers — at the reset door and at the + * link's landing (`GET /reset-password/:token`) — and a link requested + * after the change resets (the control); the same after a first password + * set through `/set-initial-password`; + * - a texted reset code outstanding before a password change answers what a + * code never sent answers, and a code requested after it resets; a + * completed texted-code reset ends the user's outstanding links; + * - another user's links are untouched by this user's change (the control); + * - the same for an administrator setting a password for a user with no + * local one, and for a password write through the exported raw + * `createObjectQLAdapter`; + * - with a `secondaryStorage` cache, an ended link answers what a link never + * issued answers from the cache's reads too, and an ended texted code's + * cached copy is gone with it; + * - a password write whose tokens cannot be ended does not land: the old + * password stands and the outstanding link resets — when a delete fails, + * and when a cached link's key cannot be named; + * - the reset tokens are found only where identifiers are stored as issued: + * the composed verification store carries no identifier-storage setting + * (a closed key set), and a password write under one other than plain is + * refused, as is one whose target names no user. + */ + +import { describe, it, expect, afterAll, afterEach, vi } from 'vitest'; +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 { createObjectQLAdapter } from './objectql-adapter.js'; +import { + endResetTokensOnCredentialWrite, + RESET_TOKEN_IDENTIFIER_REFUSAL, +} from './credential-change-ends-reset-tokens.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'; + +const ORIGIN = 'http://localhost:3000'; +const BASE = '/api/v1/auth'; +const SECRET = 'test-secret-at-least-32-chars-long-reset-tokens-end'; +const ADMIN_EMAIL = 'reset-tokens-admin@example.com'; +const EMAIL = 'reset-tokens-user@example.com'; +const OTHER_EMAIL = 'reset-tokens-other@example.com'; +const PHONE = '+15550177'; +const FIRST = 'F1rst!Password-Tokens'; +const SECOND = 'S3cond!Password-Tokens'; +const THIRD = 'Th1rd!Password-Tokens'; +const FOURTH = 'F0urth!Password-Tokens'; +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.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 } : {}) }; +} + +/** + * 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. + */ +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; 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, bearer?: string) => + app.request(`${ORIGIN}${BASE}${path}`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + origin: ORIGIN, + ...(bearer ? { authorization: `Bearer ${bearer}` } : {}), + }, + body: JSON.stringify(body), + }); + + 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); + + /** The bearer a password sign-in mints, or the refusal's status. */ + const signIn = async (email: string, password: string) => { + const res = await fire('/sign-in/email', { email, password }); + return { status: res.status, bearer: res.headers.get('set-auth-token') ?? undefined }; + }; + + /** The token the reset mail carries, read the way its recipient reads it. */ + const requestLink = async (email = EMAIL): Promise => { + const before = mail.filter((m) => m.template === 'auth.password_reset').length; + const res = await fire('/request-password-reset', { 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 (token: string, newPassword: string) => + answer(await fire('/reset-password', { token, newPassword })); + + /** The `error` the link's landing redirects with (`null` = it hands the token on). */ + const landing = async (token: string) => { + const res = await app.request( + `${ORIGIN}${BASE}/reset-password/${token}?callbackURL=${encodeURIComponent(`${ORIGIN}/reset`)}`, + { method: 'GET', headers: { origin: ORIGIN } }, + ); + const location = res.headers.get('location'); + expect(location, `the landing redirects: ${res.status}`).toBeTruthy(); + return new URL(location!).searchParams.get('error'); + }; + + /** The code the reset text carries. */ + const requestCode = async (): Promise => { + const before = texts.length; + const res = await fire('/phone-number/request-password-reset', { phoneNumber: PHONE }); + expect(res.status, await res.clone().text()).toBe(200); + await vi.waitFor(() => expect(texts.length).toBe(before + 1)); + const code = String(texts[before].templateParams?.code ?? ''); + expect(code, 'the reset text carries its code').not.toBe(''); + return code; + }; + + const userId = await idOf(EMAIL); + const admin = await signIn(ADMIN_EMAIL, FIRST); + expect(admin.bearer, 'the administrator signs in on the bearer lane').toBeTruthy(); + + return { engine, manager, fire, signUp, signIn, requestLink, reset, landing, requestCode, userId, adminBearer: admin.bearer! }; +} + +/** What a link that was never issued answers, at the reset door and at its landing. */ +async function neverIssued(s: Awaited>) { + const token = 'a-reset-link-never-issued-0000'; + return { reset: await s.reset(token, FOURTH), landing: await s.landing(token) }; +} + +/** The account as an identity provider leaves one: no local credential. */ +async function dropLocalPassword(s: Awaited>) { + const credentials = (await s.engine.find( + 'sys_account', + { where: { user_id: s.userId, provider_id: 'credential' } }, + SYS, + )) as Array<{ id: string }>; + expect(credentials).toHaveLength(1); + await s.engine.delete('sys_account', { where: { id: credentials[0].id }, context: { isSystem: true } } as never); +} + +/** A host `secondaryStorage` over a Map the case can read. */ +function cacheStorage() { + const cache = new Map(); + return { + cache, + secondaryStorage: { + get: async (key: string) => cache.get(key) ?? null, + set: async (key: string, value: string) => { + cache.set(key, value); + }, + delete: async (key: string) => { + cache.delete(key); + }, + increment: async (key: string) => { + const next = Number(cache.get(key) ?? 0) + 1; + cache.set(key, String(next)); + return next; + }, + }, + }; +} + +describe("a completed reset ends the user's other reset links", () => { + it('the earlier link answers what a link never issued answers, and the password is the one the spent link set', async () => { + const s = await stage(); + const unknown = await neverIssued(s); + expect(unknown.reset).toEqual({ status: 400, code: 'INVALID_TOKEN' }); + const earlier = await s.requestLink(); + const later = await s.requestLink(); + + expect(await s.reset(later, SECOND)).toEqual({ status: 200 }); + + expect(await s.landing(earlier)).toBe(unknown.landing); + expect(await s.reset(earlier, THIRD)).toEqual(unknown.reset); + expect((await s.signIn(EMAIL, SECOND)).status).toBe(200); + expect((await s.signIn(EMAIL, THIRD)).status).not.toBe(200); + }, 60_000); + + it('the later link answers what a link never issued answers once the earlier one is spent', async () => { + const s = await stage(); + const unknown = await neverIssued(s); + const earlier = await s.requestLink(); + const later = await s.requestLink(); + + expect(await s.reset(earlier, SECOND)).toEqual({ status: 200 }); + + expect(await s.landing(later)).toBe(unknown.landing); + expect(await s.reset(later, THIRD)).toEqual(unknown.reset); + expect((await s.signIn(EMAIL, SECOND)).status).toBe(200); + }, 60_000); +}); + +describe('a password change ends every reset link outstanding before it', () => { + it("the user's own /change-password: an earlier link answers what a link never issued answers; a link requested after it resets", async () => { + const s = await stage(); + const unknown = await neverIssued(s); + const earlier = await s.requestLink(); + const { bearer } = await s.signIn(EMAIL, FIRST); + + const changed = await s.fire('/change-password', { currentPassword: FIRST, newPassword: SECOND, revokeOtherSessions: true }, bearer); + expect(changed.status, await changed.clone().text()).toBe(200); + + expect(await s.landing(earlier)).toBe(unknown.landing); + expect(await s.reset(earlier, THIRD)).toEqual(unknown.reset); + expect((await s.signIn(EMAIL, SECOND)).status).toBe(200); + + // The control: a link requested after the change resets. + const fresh = await s.requestLink(); + expect(await s.landing(fresh)).toBeNull(); + expect(await s.reset(fresh, THIRD)).toEqual({ status: 200 }); + expect((await s.signIn(EMAIL, THIRD)).status).toBe(200); + }, 60_000); + + it("an administrator's /admin/set-user-password: an earlier link answers what a link never issued answers; a link requested after it resets", async () => { + const s = await stage(); + const unknown = await neverIssued(s); + const earlier = await s.requestLink(); + + const set = await s.fire( + '/admin/set-user-password', + { userId: s.userId, newPassword: SECOND, mustChangePassword: false }, + s.adminBearer, + ); + expect(set.status, await set.clone().text()).toBe(200); + + expect(await s.landing(earlier)).toBe(unknown.landing); + expect(await s.reset(earlier, THIRD)).toEqual(unknown.reset); + expect((await s.signIn(EMAIL, SECOND)).status).toBe(200); + + // The control: a link requested after the change resets. + const fresh = await s.requestLink(); + expect(await s.reset(fresh, THIRD)).toEqual({ status: 200 }); + expect((await s.signIn(EMAIL, THIRD)).status).toBe(200); + }, 60_000); + + it('a first password set through /set-initial-password: an earlier link answers what a link never issued answers', async () => { + const s = await stage(); + const unknown = await neverIssued(s); + const earlier = await s.requestLink(); + const { bearer } = await s.signIn(EMAIL, FIRST); + await dropLocalPassword(s); + + const set = await s.fire('/set-initial-password', { newPassword: SECOND }, bearer); + expect(set.status, await set.clone().text()).toBe(200); + + expect(await s.reset(earlier, THIRD)).toEqual(unknown.reset); + expect((await s.signIn(EMAIL, SECOND)).status).toBe(200); + }, 60_000); + + it("an administrator's /admin/set-user-password for a user with no local password: an earlier link answers what a link never issued answers", async () => { + const s = await stage(); + const unknown = await neverIssued(s); + const earlier = await s.requestLink(); + await dropLocalPassword(s); + + const set = await s.fire( + '/admin/set-user-password', + { userId: s.userId, newPassword: SECOND, mustChangePassword: false }, + s.adminBearer, + ); + expect(set.status, await set.clone().text()).toBe(200); + + expect(await s.reset(earlier, THIRD)).toEqual(unknown.reset); + expect((await s.signIn(EMAIL, SECOND)).status).toBe(200); + }, 60_000); + + it("the exported createObjectQLAdapter: a password write through it ends the holder's earlier link", async () => { + const s = await stage(); + const unknown = await neverIssued(s); + const earlier = await s.requestLink(); + const adapter = createObjectQLAdapter(s.engine as never); + + const written = await adapter.updateMany({ + model: 'account', + where: [ + { field: 'user_id', operator: 'eq', value: s.userId, connector: 'AND' }, + { field: 'provider_id', operator: 'eq', value: 'credential', connector: 'AND' }, + ] as never, + update: { password: 'a-hash-the-raw-adapter-writes' }, + }); + expect(written).toBe(1); + + expect(await s.reset(earlier, THIRD)).toEqual(unknown.reset); + }, 60_000); + + it("another user's links are untouched by this user's password change", async () => { + const s = await stage(); + await s.signUp(OTHER_EMAIL, true); + const others = await s.requestLink(OTHER_EMAIL); + const mine = await s.requestLink(); + + expect(await s.reset(mine, SECOND)).toEqual({ status: 200 }); + + expect(await s.reset(others, THIRD)).toEqual({ status: 200 }); + expect((await s.signIn(OTHER_EMAIL, THIRD)).status).toBe(200); + }, 60_000); +}); + +describe('a password change ends the texted reset code outstanding before it', () => { + const phoneStage = 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); + return s; + }; + const resetByCode = async (s: Awaited>, otp: string, newPassword: string) => + answer(await s.fire('/phone-number/reset-password', { phoneNumber: PHONE, otp, newPassword })); + + it("the user's own /change-password: an earlier code answers what a code never sent answers; a code requested after it resets", async () => { + const s = await phoneStage(); + const neverSent = await resetByCode(s, '000000', FOURTH); + expect(neverSent.status).toBe(400); + const earlier = await s.requestCode(); + const { bearer } = await s.signIn(EMAIL, FIRST); + + const changed = await s.fire('/change-password', { currentPassword: FIRST, newPassword: SECOND }, bearer); + expect(changed.status, await changed.clone().text()).toBe(200); + + expect(await resetByCode(s, earlier, THIRD)).toEqual(neverSent); + expect((await s.signIn(EMAIL, SECOND)).status).toBe(200); + + // The control: a code requested after the change resets. + const fresh = await s.requestCode(); + expect(await resetByCode(s, fresh, THIRD)).toEqual({ status: 200 }); + expect((await s.signIn(EMAIL, THIRD)).status).toBe(200); + }, 60_000); + + it('a completed texted-code reset ends the reset links outstanding before it', async () => { + const s = await phoneStage(); + const unknown = await neverIssued(s); + const link = await s.requestLink(); + const code = await s.requestCode(); + + expect(await resetByCode(s, code, SECOND)).toEqual({ status: 200 }); + + expect(await s.reset(link, THIRD)).toEqual(unknown.reset); + expect((await s.signIn(EMAIL, SECOND)).status).toBe(200); + }, 60_000); +}); + +describe('with a secondaryStorage cache, an ended token answers what a token never issued answers', () => { + // The embedded OAuth provider refuses a cache-held session store; it is not + // what these cases are about. + const cachedStage = (extra: Record = {}) => { + const storage = cacheStorage(); + return stage({ ...extra, plugins: { oidcProvider: false, ...((extra.plugins as Record) ?? {}) }, secondaryStorage: storage.secondaryStorage }) + .then((s) => ({ ...s, cache: storage.cache })); + }; + + it('a link: at the landing and at the reset door, the cache read first', async () => { + const s = await cachedStage(); + const unknown = await neverIssued(s); + const earlier = await s.requestLink(); + expect(s.cache.has(`verification:reset-password:${earlier}`), 'the link is cached as it is issued').toBe(true); + const { bearer } = await s.signIn(EMAIL, FIRST); + + const changed = await s.fire('/change-password', { currentPassword: FIRST, newPassword: SECOND }, bearer); + expect(changed.status, await changed.clone().text()).toBe(200); + + expect(s.cache.has(`verification:reset-password:${earlier}`)).toBe(false); + expect(await s.landing(earlier)).toBe(unknown.landing); + expect(await s.reset(earlier, THIRD)).toEqual(unknown.reset); + }, 60_000); + + it('a texted code: its cached copy is ended with it', async () => { + const s = await cachedStage({ plugins: { phoneNumber: true }, phoneOtp: { cooldownSeconds: 0 } }); + await s.engine.update('sys_user', { id: s.userId, phone_number: PHONE, phone_number_verified: true }, SYS); + const resetByCode = async (otp: string) => + answer(await s.fire('/phone-number/reset-password', { phoneNumber: PHONE, otp, newPassword: THIRD })); + const neverSent = await resetByCode('000000'); + const earlier = await s.requestCode(); + expect(s.cache.has(`verification:${PHONE}-request-password-reset`), 'the code is cached as it is sent').toBe(true); + const { bearer } = await s.signIn(EMAIL, FIRST); + + const changed = await s.fire('/change-password', { currentPassword: FIRST, newPassword: SECOND }, bearer); + expect(changed.status, await changed.clone().text()).toBe(200); + + expect(s.cache.has(`verification:${PHONE}-request-password-reset`)).toBe(false); + expect(await resetByCode(earlier)).toEqual(neverSent); + }, 60_000); + + it("a password write whose links' cached copies cannot be named does not land", async () => { + const s = await cachedStage(); + const earlier = await s.requestLink(); + const { bearer } = await s.signIn(EMAIL, FIRST); + + const engine = s.engine as unknown as { + resolveInternalField(object: string, ids: readonly string[], field: string): Promise>; + }; + const resolve = engine.resolveInternalField.bind(engine); + const unnamed = vi.spyOn(engine, 'resolveInternalField').mockImplementation(async (object, ids, field) => + object === 'sys_verification' && field === 'identifier' ? new Map() : resolve(object, ids, field), + ); + const changed = await s.fire('/change-password', { currentPassword: FIRST, newPassword: SECOND }, bearer); + expect(changed.status).toBeGreaterThanOrEqual(400); + unnamed.mockRestore(); + + expect((await s.signIn(EMAIL, FIRST)).status).toBe(200); + expect((await s.signIn(EMAIL, SECOND)).status).not.toBe(200); + expect(s.cache.has(`verification:reset-password:${earlier}`)).toBe(true); + expect(await s.reset(earlier, THIRD)).toEqual({ status: 200 }); + }, 60_000); +}); + +describe('a password write whose reset tokens cannot be ended does not land', () => { + it('the old password stands and the outstanding link resets', async () => { + const s = await stage(); + const earlier = await s.requestLink(); + const { bearer } = await s.signIn(EMAIL, FIRST); + + const remove = s.engine.delete.bind(s.engine); + const refuse = vi.spyOn(s.engine, 'delete').mockImplementation((async (object: string, ...rest: unknown[]) => { + if (object === 'sys_verification') throw new Error('store unavailable'); + return (remove as (...a: unknown[]) => unknown)(object, ...rest); + }) as never); + const changed = await s.fire('/change-password', { currentPassword: FIRST, newPassword: SECOND }, bearer); + expect(changed.status).toBeGreaterThanOrEqual(400); + refuse.mockRestore(); + + expect((await s.signIn(EMAIL, FIRST)).status).toBe(200); + expect((await s.signIn(EMAIL, SECOND)).status).not.toBe(200); + expect(await s.reset(earlier, THIRD)).toEqual({ status: 200 }); + }, 60_000); +}); + +describe('the reset tokens are found only where identifiers are stored as issued', () => { + it('the composed verification store carries no identifier-storage setting, with or without a cache', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + for (const extra of [{}, { plugins: { oidcProvider: false }, secondaryStorage: cacheStorage().secondaryStorage }]) { + const engine = await engines.take(); + const manager = new AuthManager({ secret: SECRET, baseUrl: ORIGIN, dataEngine: engine as never, ...extra } as never); + const auth = (await manager.getAuthInstance()) as unknown as { options: { verification?: Record } }; + const verification = auth.options.verification ?? {}; + // A closed set: a key added here is a decision this rule's matching must be re-read against. + expect(Object.keys(verification).sort()).toEqual( + 'secondaryStorage' in extra ? ['fields', 'modelName', 'storeInDatabase'] : ['fields', 'modelName'], + ); + expect(verification.storeIdentifier).toBeUndefined(); + } + }); + + it('a password write under an identifier-storage setting other than plain is refused before any read', async () => { + const untouched = {} as never; + for (const identifierStorage of ['hashed', { default: 'hashed' }, { default: 'plain', overrides: { 'reset-password:': 'hashed' } }]) { + await expect( + endResetTokensOnCredentialWrite(untouched, 'sys_account', { password: 'h' }, [{ user_id: 'u1' }], { identifierStorage }), + ).rejects.toThrow(RESET_TOKEN_IDENTIFIER_REFUSAL); + } + }); + + it('a password write whose target names no user is refused before any read', async () => { + await expect( + endResetTokensOnCredentialWrite({} as never, 'sys_account', { password: 'h' }, [{ id: 'acc_1' }]), + ).rejects.toThrow(/names no user/); + }); +}); diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.ts b/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.ts new file mode 100644 index 00000000000..1f4568a97a6 --- /dev/null +++ b/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.ts @@ -0,0 +1,236 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A change to a user's credential ends every other outstanding password-reset + * token of that user. + * + * ## The rule + * + * Whenever a user's password is set — a completed reset (the emailed link or + * the texted code), the user's own `/change-password`, an administrator's + * `/admin/set-user-password`, a first password (`/set-initial-password`) — every + * password-reset token still outstanding for that user is ended in the same + * request, before the new password is written. The token a reset door spends + * to make the change is spent by that door; every other one is deleted here. + * A token issued after the change is untouched and resets as usual. + * + * An ended token answers exactly what a token that was never issued answers: + * its `sys_verification` row is gone, so every door that reads it — the reset + * itself, the emailed link's landing (`GET /reset-password/:token`) and the + * reset doors' own checks ahead of the vendor handler — finds nothing. + * + * Two token shapes are a user's (better-auth 1.7.12): + * + * - the emailed link, `/request-password-reset`: a row keyed + * `reset-password:TOKEN` whose value is the user's id; + * - the texted code, `/phone-number/request-password-reset`: the row keyed + * `PHONE-request-password-reset` for the phone number the user holds — the + * reset door finds its user by that number. + * + * Both are matched as the vendor stores them, with a plain identifier. A + * `verification.storeIdentifier` other than `'plain'` would store them under a + * digest no prefix or key here could name, so the rule would match nothing; a + * credential write under such a setting is REFUSED instead + * ({@link RESET_TOKEN_IDENTIFIER_REFUSAL}). The auth instance sets none, and + * `credential-change-ends-reset-tokens.test.ts` pins the composed setting. + * + * ## Where it is wired, and why there + * + * Every door that sets a password writes the credential account + * (`sys_account`) through better-auth's storage adapter + * (`objectql-adapter.ts`): `internalAdapter.updatePassword` (both reset doors + * and the administrator's door), `updateAccount` (`/change-password`, + * `/set-initial-password`) and `createAccount` / `linkAccount` (a password set + * for a user who holds no local one yet). The adapter is the one seam all of + * them cross with the user in hand: a database hook's `update.before` is given + * the patch without the rows it targets, and the administrator's door calls + * the internal adapter outside any endpoint context. So both adapters in that + * file — the factory `AuthManager` composes and the exported raw + * `createObjectQLAdapter` — call {@link endResetTokensOnCredentialWrite} on each + * account write whose payload carries `password`, with the rows that write + * targets. A targeted row that names no user is refused, never skipped. + * + * Before the write, never after it. better-auth runs its own flows on this + * adapter without a database transaction (the adapter's `transaction` is + * native only inside a SCIM request), so the order is what keeps the rule: a + * token that cannot be ended aborts the write, the old password stands and + * the door answers an error. A write that fails after its tokens were ended + * costs the user a new reset request, never a live token beside a new + * password. + * + * ## How the rows are deleted + * + * With no cache, each token shape is ended by ONE predicate delete + * (`multi: true`): the user's links by `value` and the identifier prefix, the + * texted code by its exact identifier. The engine pushes each down to the + * store, and a link issued while the request runs is matched as long as it + * lands before the delete. + * + * ## Secondary storage + * + * With a host `secondaryStorage` (handed to the factory adapter in the + * `AuthManager` composition; the raw adapter is handed none), better-auth also + * caches every verification value under `verification:IDENTIFIER`, and the + * auth instance sets `verification.storeInDatabase`, so the row stays the + * record. The cache entry of every ended token is deleted too, so a read the + * cache answers first finds nothing either. + * + * A link's cache entry is keyed by its token, which only a read of its row can + * name, and `sys_verification.identifier` is `internal`, so the link rows are + * read first and their identifiers recovered through the privileged readback + * (`internal-field-readback.ts`). That arm then deletes exactly the rows it + * read, by id, so every row it ends loses its cache entry with it; a predicate + * delete there could end a row whose cache entry it never named. A link row + * whose identifier cannot be recovered is REFUSED, never skipped: its cache + * entry would otherwise outlive it. The texted code's key is known without a + * read, so its row is ended by the predicate delete in both arms. + */ + +import { SystemObjectName } from '@objectstack/spec/system'; +import { reattachInternalFieldsOnRead, type InternalFieldResolvingEngine } from './internal-field-readback.js'; + +/** The identifier prefix of an emailed reset link's row (better-auth `/request-password-reset`). */ +export const RESET_LINK_IDENTIFIER_PREFIX = 'reset-password:'; + +/** The identifier suffix of a texted reset code's row, after the phone number. */ +export const RESET_CODE_IDENTIFIER_SUFFIX = '-request-password-reset'; + +/** better-auth's cache key prefix for a verification value in `secondaryStorage`. */ +const CACHE_KEY_PREFIX = 'verification:'; + +/** The refusal a credential write meets when the verification store does not keep identifiers plain. */ +export const RESET_TOKEN_IDENTIFIER_REFUSAL = + "[auth] a password was not set: this deployment's verification store keeps identifiers other than plain " + + '(`verification.storeIdentifier`), so the outstanding password-reset tokens of the user cannot be found and ' + + 'ended. A password change must end them. Remove `verification.storeIdentifier`, or keep it `plain`.'; + +/** The engine verbs this seam uses, under the adapter's system context. */ +export interface ResetTokenEngine { + find(object: string, query: Record): Promise; + findOne(object: string, query: Record): Promise; + delete(object: string, query: Record): Promise; +} + +/** The one verb of better-auth's `secondaryStorage` this seam uses. */ +export interface ResetTokenCache { + delete(key: string): unknown; +} + +export interface EndResetTokensOptions { + /** The host's `secondaryStorage`, when one is configured. */ + readonly cache?: ResetTokenCache; + /** The RAW engine, holder of the privileged `resolveInternalField`. */ + readonly internalFieldEngine?: InternalFieldResolvingEngine; + /** better-auth's `verification.storeIdentifier`, as the adapter was built with it. */ + readonly identifierStorage?: unknown; +} + +/** + * Whether an adapter write sets a credential: a `sys_account` row whose + * payload carries `password` (any value, a cleared one included). + */ +export function writesCredential(objectName: string, payload: unknown): boolean { + if (objectName !== SystemObjectName.ACCOUNT) return false; + if (!payload || typeof payload !== 'object') return false; + return (payload as Record).password !== undefined; +} + +/** The user id an account row (or create payload) names, in either spelling. */ +export function accountUserId(row: unknown): string | undefined { + if (!row || typeof row !== 'object') return undefined; + const r = row as Record; + const id = r.user_id ?? r.userId; + return typeof id === 'string' && id.length > 0 ? id : undefined; +} + +type VerificationRow = { id?: unknown; identifier?: unknown }; + +/** + * End every outstanding password-reset token of `userId`: delete its rows, and + * its cache entries when a cache is configured. Throws when a read or a delete + * fails, or when a cached link's key cannot be named, so the caller's write + * never lands beside a live token. + */ +export async function endOutstandingResetTokens( + engine: ResetTokenEngine, + userId: string, + options: EndResetTokensOptions = {}, +): Promise { + const VERIFICATION = SystemObjectName.VERIFICATION; + const linkPredicate = { value: userId, identifier: { $startsWith: RESET_LINK_IDENTIFIER_PREFIX } }; + + const user = (await engine.findOne(SystemObjectName.USER, { + where: { id: userId }, + fields: ['id', 'phone_number'], + })) as { phone_number?: unknown } | null; + const phone = typeof user?.phone_number === 'string' && user.phone_number.length > 0 ? user.phone_number : undefined; + const codeIdentifier = phone ? `${phone}${RESET_CODE_IDENTIFIER_SUFFIX}` : undefined; + + const cacheKeys: string[] = []; + if (options.cache) { + // The cache arm: name each link's key from its row, then end exactly those rows (header). + if (typeof options.cache.delete !== 'function') throw new Error(cacheKeyRefusal('every')); + const links = (await engine.find(VERIFICATION, { where: linkPredicate, fields: ['id', 'identifier'] })) as VerificationRow[]; + if (links.length > 0) { + if (!options.internalFieldEngine) throw new Error(cacheKeyRefusal(links.length)); + await reattachInternalFieldsOnRead(options.internalFieldEngine, VERIFICATION, links, ['identifier']); + } + const unnamed = links.filter((row) => typeof row.identifier !== 'string' || row.identifier.length === 0); + if (unnamed.length > 0) throw new Error(cacheKeyRefusal(unnamed.length)); + for (const row of links) { + await engine.delete(VERIFICATION, { where: { id: row.id } }); + cacheKeys.push(`${CACHE_KEY_PREFIX}${row.identifier as string}`); + } + } else { + await engine.delete(VERIFICATION, { where: linkPredicate, multi: true }); + } + + if (codeIdentifier) { + await engine.delete(VERIFICATION, { where: { identifier: codeIdentifier }, multi: true }); + if (options.cache) cacheKeys.push(`${CACHE_KEY_PREFIX}${codeIdentifier}`); + } + + for (const key of cacheKeys) { + await options.cache!.delete(key); + } +} + +function cacheKeyRefusal(count: number | 'every'): string { + return `[auth] a password was not set: ${count} outstanding password-reset link(s) of the user could not be ` + + 'ended in the secondary storage with their rows. A password change must end them. Check that the auth store ' + + '(sys_verification) is readable through the privileged readback and that the secondary storage offers `delete`, ' + + 'then retry.'; +} + +/** + * The adapters' call: when `payload` sets a credential on `sys_account`, end + * the outstanding reset tokens of every user the write targets, before it + * lands. Inert for every other write. Refused when the verification store + * does not keep identifiers plain, and when a targeted row names no user. + */ +export async function endResetTokensOnCredentialWrite( + engine: ResetTokenEngine, + objectName: string, + payload: unknown, + targets: readonly unknown[], + options: EndResetTokensOptions = {}, +): Promise { + if (!writesCredential(objectName, payload)) return; + if (options.identifierStorage !== undefined && options.identifierStorage !== 'plain') { + throw new Error(RESET_TOKEN_IDENTIFIER_REFUSAL); + } + const users = new Set(); + for (const target of targets) { + const id = accountUserId(target); + if (!id) { + throw new Error( + '[auth] a password was not set: the account row it targets names no user, so the outstanding ' + + 'password-reset tokens of its holder cannot be found and ended.', + ); + } + users.add(id); + } + for (const userId of users) { + await endOutstandingResetTokens(engine, userId, options); + } +} diff --git a/packages/plugins/plugin-auth/src/objectql-adapter.ts b/packages/plugins/plugin-auth/src/objectql-adapter.ts index 6902c52d619..87837e9beb4 100644 --- a/packages/plugins/plugin-auth/src/objectql-adapter.ts +++ b/packages/plugins/plugin-auth/src/objectql-adapter.ts @@ -31,6 +31,7 @@ import { type InternalFieldResolvingEngine, } from './internal-field-readback.js'; import { decodeOrganizationMetadataOnRead } from './organization-metadata-decode.js'; +import { endResetTokensOnCredentialWrite, type ResetTokenCache } from './credential-change-ends-reset-tokens.js'; /** * Mapping from better-auth model names to ObjectStack protocol object names. @@ -888,6 +889,19 @@ export function createObjectQLAdapterFactory( // the callback directly, and a driver without `beginTransaction` follows // the engine's ADR-0119 D1 warn-once degrade. let wrappedAdapter: unknown = null; + // The host's `secondaryStorage` and the verification store's identifier + // setting, read off the options better-auth builds this adapter with + // (below): a credential write ends the reset tokens' cache entries with + // their rows, and is refused where identifiers are not kept plain + // (`credential-change-ends-reset-tokens.ts`). + let resetTokenCache: ResetTokenCache | undefined; + let resetTokenIdentifierStorage: unknown; + const endResetTokens = (objectName: string, payload: unknown, targets: readonly unknown[]) => + endResetTokensOnCredentialWrite(dataEngine as never, objectName, payload, targets, { + cache: resetTokenCache, + internalFieldEngine, + identifierStorage: resetTokenIdentifierStorage, + }); const engineWithTx = rawDataEngine as unknown as { transaction?( cb: (trxCtx: unknown, info: unknown) => Promise, @@ -953,6 +967,9 @@ export function createObjectQLAdapterFactory( // other object, unidentifiable pair, no existing row — and then this is a // plain insert, byte for byte as before. See `adopt-membership.ts` for // why the seam is here and what adoption does to the role. + // A password set on an account the user did not hold ends the user's + // other reset tokens first (`credential-change-ends-reset-tokens.ts`). + await endResetTokens(objectName, row, [row]); const adopted = await adoptExistingMembership(dataEngine as any, objectName, row); const result = adopted ?? (await dataEngine.insert(objectName, row)); if (factoryOptions.onRecordCreated && result && typeof result === 'object') { @@ -1132,6 +1149,9 @@ export function createObjectQLAdapterFactory( record as Record, patch as Record, ); + // A password change ends the account holder's other reset tokens + // before it lands (`credential-change-ends-reset-tokens.ts`). + await endResetTokens(objectName, patch, [record]); const result = await dataEngine.update(objectName, { ...patch, id: record.id }); // [#16231] The payload carries the resolved `id` and no `where`, so // the engine dispatches `by-id` and answers the record or `null`. The @@ -1169,6 +1189,10 @@ export function createObjectQLAdapterFactory( liftClientSecretForWrite(objectName, patch); stripIdpInitiatedFromOidcConfigOnWrite(objectName, patch); restoreUserInfoEndpointOnWrite(objectName, patch); + // `internalAdapter.updatePassword` is this door: the password change + // ends each targeted holder's other reset tokens before any row lands + // (`credential-change-ends-reset-tokens.ts`). + await endResetTokens(objectName, patch, records); for (const record of records) { // [#17440] Same rule on the bulk door — a re-point smuggled through // `updateMany` is the same re-point. @@ -1290,6 +1314,10 @@ export function createObjectQLAdapterFactory( return (options: Parameters[0]) => { const adapter = readEverySsoProviderRowWhenUnbounded(factory(options)); wrappedAdapter = adapter; + const built = options as { secondaryStorage?: unknown; verification?: { storeIdentifier?: unknown } } | undefined; + const cache = built?.secondaryStorage as ResetTokenCache | undefined; + resetTokenCache = cache ?? undefined; + resetTokenIdentifierStorage = built?.verification?.storeIdentifier; return adapter; }; } @@ -1389,10 +1417,19 @@ function readEverySsoProviderRowWhenUnbounded + endResetTokensOnCredentialWrite(dataEngine as never, objectName, payload, targets, { + internalFieldEngine: rawDataEngine as unknown as InternalFieldResolvingEngine, + }); return { create: async >({ model, data, select: _select }: { model: string; data: T; select?: string[] }): Promise => { const objectName = resolveProtocolName(model); - const result = await dataEngine.insert(objectName, normaliseIdentifierWrite(model, data)); + const payload = normaliseIdentifierWrite(model, data); + await endResetTokens(objectName, payload, [payload]); + const result = await dataEngine.insert(objectName, payload); return result as T; }, @@ -1422,8 +1459,10 @@ export function createObjectQLAdapter(rawDataEngine: IDataEngine) { const filter = convertWhere(model, where); const record = await dataEngine.findOne(objectName, { where: filter }); if (!record) return null; + const patch = normaliseIdentifierWrite(model, update); + await endResetTokens(objectName, patch, [record]); const result = await dataEngine.update(objectName, { - ...normaliseIdentifierWrite(model, update), + ...patch, id: record.id, }); return result ? result as T : null; @@ -1434,6 +1473,7 @@ export function createObjectQLAdapter(rawDataEngine: IDataEngine) { const filter = convertWhere(model, where); const records = await dataEngine.find(objectName, { where: filter }); const patch = normaliseIdentifierWrite(model, update); + await endResetTokens(objectName, patch, records); for (const record of records) { await dataEngine.update(objectName, { ...patch, id: record.id }); }