From c5552ab74420ddc564254c2c9a147527abeabd55 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 01:55:50 +0000 Subject: [PATCH 1/7] fix(auth): a credential change ends the user's other password-reset tokens WIP: the seam module and its adapter wiring; tests follow. Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../credential-change-ends-reset-tokens.ts | 188 ++++++++++++++++++ .../plugin-auth/src/objectql-adapter.ts | 22 ++ 2 files changed, 210 insertions(+) create mode 100644 packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.ts 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..7913dc04ed3 --- /dev/null +++ b/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.ts @@ -0,0 +1,188 @@ +// 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: the + * auth instance sets no `verification.storeIdentifier`. + * + * ## 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 the adapter calls + * {@link endResetTokensOnCredentialWrite} on each account write whose payload + * carries `password`, with the users that write targets. + * + * 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. + * + * ## Secondary storage + * + * With a host `secondaryStorage`, 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. `sys_verification.identifier` is `internal`, so the link + * tokens' identifiers are recovered through the privileged readback + * (`internal-field-readback.ts`), and only when a cache is configured. + */ + +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 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; +} + +/** + * 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. Answers how many were ended. + * Throws when a read or a delete fails, so the caller's write never lands + * beside a token that is still live. + */ +export async function endOutstandingResetTokens( + engine: ResetTokenEngine, + userId: string, + options: EndResetTokensOptions = {}, +): Promise { + const VERIFICATION = SystemObjectName.VERIFICATION; + const links = (await engine.find(VERIFICATION, { + where: { value: userId, identifier: { $startsWith: RESET_LINK_IDENTIFIER_PREFIX } }, + fields: ['id', 'identifier'], + })) as VerificationRow[]; + + 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 codes = codeIdentifier + ? ((await engine.find(VERIFICATION, { where: { identifier: codeIdentifier }, fields: ['id'] })) as VerificationRow[]) + : []; + + const rows = [...links, ...codes].filter((r) => typeof r?.id === 'string' || typeof r?.id === 'number'); + if (rows.length === 0) return 0; + + const cacheKeys = new Set(); + if (options.cache) { + if (links.length > 0 && options.internalFieldEngine) { + await reattachInternalFieldsOnRead(options.internalFieldEngine, VERIFICATION, links, ['identifier']); + } + for (const row of links) { + if (typeof row.identifier === 'string' && row.identifier.length > 0) cacheKeys.add(`${CACHE_KEY_PREFIX}${row.identifier}`); + } + if (codeIdentifier) cacheKeys.add(`${CACHE_KEY_PREFIX}${codeIdentifier}`); + } + + for (const row of rows) { + await engine.delete(VERIFICATION, { where: { id: row.id } }); + } + for (const key of cacheKeys) { + await options.cache!.delete(key); + } + return rows.length; +} + +/** + * The adapter's 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. + */ +export async function endResetTokensOnCredentialWrite( + engine: ResetTokenEngine, + objectName: string, + payload: unknown, + targets: readonly unknown[], + options: EndResetTokensOptions = {}, +): Promise { + if (!writesCredential(objectName, payload)) return; + const users = new Set(); + for (const target of targets) { + const id = accountUserId(target); + if (id) 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 74fcf83350d..7a432639566 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,15 @@ 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`, read off the options better-auth builds + // this adapter with (below): a credential write ends the reset tokens' + // cache entries with their rows (`credential-change-ends-reset-tokens.ts`). + let resetTokenCache: ResetTokenCache | undefined; + const endResetTokens = (objectName: string, payload: unknown, targets: readonly unknown[]) => + endResetTokensOnCredentialWrite(dataEngine as never, objectName, payload, targets, { + cache: resetTokenCache, + internalFieldEngine, + }); const engineWithTx = rawDataEngine as unknown as { transaction?( cb: (trxCtx: unknown, info: unknown) => Promise, @@ -953,6 +963,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 +1145,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 +1185,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. @@ -1286,6 +1306,8 @@ export function createObjectQLAdapterFactory( return (options: Parameters[0]) => { const adapter = readEverySsoProviderRowWhenUnbounded(factory(options)); wrappedAdapter = adapter; + const cache = (options as { secondaryStorage?: unknown } | undefined)?.secondaryStorage as ResetTokenCache | undefined; + resetTokenCache = cache && typeof cache.delete === 'function' ? cache : undefined; return adapter; }; } From 78564146ae323ac47291d79b1d2df22e0dd6cbdf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:08:38 +0000 Subject: [PATCH 2/7] test(auth): pin that a credential change ends the user's other reset tokens at every door WIP: door-level pins, changeset and the docs line. Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../credential-change-ends-reset-tokens.md | 15 + content/docs/permissions/authentication.mdx | 8 + ...redential-change-ends-reset-tokens.test.ts | 422 ++++++++++++++++++ 3 files changed, 445 insertions(+) create mode 100644 .changeset/credential-change-ends-reset-tokens.md create mode 100644 packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.test.ts diff --git a/.changeset/credential-change-ends-reset-tokens.md b/.changeset/credential-change-ends-reset-tokens.md new file mode 100644 index 00000000000..cc866179351 --- /dev/null +++ b/.changeset/credential-change-ends-reset-tokens.md @@ -0,0 +1,15 @@ +--- +'@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) — every door that sets a user's password 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: 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, by any door, every reset link (`/request-password-reset`) and texted reset code (`/phone-number/request-password-reset`) issued for that user beforehand is ended. 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`, its cached copy is removed too. A password write whose outstanding tokens cannot be ended does not land: the door answers an error and the old password stands. +- **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 92d4043c282..ec355e9e042 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/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..56c5127b6c5 --- /dev/null +++ b/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.test.ts @@ -0,0 +1,422 @@ +// 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); + * - with a `secondaryStorage` cache, an ended link answers what a link never + * issued answers from the cache's reads too; + * - a password write whose tokens cannot be ended does not land: the old + * password still signs in and the outstanding link is still live. + */ + +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 { 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) }; +} + +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); + // The account as an identity provider leaves one: no local credential. + 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); + + 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("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 link answers what a link never issued answers', () => { + it('at the landing and at the reset door, the cache read first', async () => { + const cache = new Map(); + const s = await stage({ + // The embedded OAuth provider refuses a cache-held session store; it is + // not what this case is about. + plugins: { oidcProvider: false }, + 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; + }, + }, + }); + const unknown = await neverIssued(s); + const earlier = await s.requestLink(); + expect(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(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); +}); + +describe('a password write whose reset tokens cannot be ended does not land', () => { + it('the old password still signs in and the outstanding link still 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); +}); From 5a448780c2b6f3e2a82d20a092db6a6e86b96a38 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 02:58:52 +0000 Subject: [PATCH 3/7] docs(tenant-audit): regenerate the census for the reset-token seam's write site Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../docs/permissions/tenant-audit-census.mdx | 32 +++++++++---------- ...08-tenant-audit-write-call-sites.counts.md | 15 +++++---- 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index 793cd0dfda7..6cbdbb143bf 100644 --- a/content/docs/permissions/tenant-audit-census.mdx +++ b/content/docs/permissions/tenant-audit-census.mdx @@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way. The same holds twice over for the context. An options argument spelled as a literal can be read; one spelled `options`, `{ ...opts }`, or handed through a -forwarding shim cannot, and **59 of the 321 sites are spelled that way**. A +forwarding shim cannot, and **59 of the 322 sites are spelled that way**. A context resolved from an inline literal or a local `const` can be tested for `isSystem`; one arriving from a helper call cannot. @@ -160,8 +160,8 @@ now **0**: nothing on this surface threads a context that provably lacks the fla **"No tenant context" counted sites it had not read.** An options argument the walker could not parse was folded into the same bucket as one it had read and -found empty. That published **71 sites "carrying no tenant context at all"** -when 12 said so and 59 were simply unread — an over-claim in the *alarming* +found empty. That published **72 sites "carrying no tenant context at all"** +when 13 said so and 59 were simply unread — an over-claim in the *alarming* direction, on the very figure this page tells other cards to cite. `carries` is now three-valued, and an unreadable argument can never contribute to the provable count. @@ -197,9 +197,9 @@ reproduce them. Where it disagrees, it disagrees on the page: | carried figure | where it survives | this census | | :--- | :--- | ---: | -| 175 write call sites | quoted in the merged changeset | **321** | +| 175 write call sites | quoted in the merged changeset | **322** | | 24 carrying no tenant context | quoted in the merged changeset | **3** provable and tenancy-enabled; **32** more whose options argument is unreadable | -| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **226 of 321** decidable, **95** undecidable | +| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **226 of 322** decidable, **96** undecidable | | 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 181 decidably elevated, 0 decidably not, 128 undecidable | | 141 and 132, two independent re-derivations | the card that filed this work | — | @@ -217,11 +217,11 @@ would report a smaller number and would not say so. The fourth row is the one worth flagging to anyone citing it. **The 135 / 77% figure has no surviving corroboration anywhere in the tree.** This census reads -181 of 321 (56%) as decidably elevated, with 128 more whose elevation is a +181 of 322 (56%) as decidably elevated, with 128 more whose elevation is a run-time fact — so the claim is neither confirmed nor refuted, and the honest answer is that a static reading cannot settle it. -⇒ **Cite `3 / 321`, and say what it is**: the sites whose options argument was +⇒ **Cite `3 / 322`, and say what it is**: the sites whose options argument was READ and holds no tenant context, against a decidably tenancy-enabled object. That is the control's provable yield surface. ⛔ Do not cite it as "the sites without tenant context" — **32 further sites** have an options argument this @@ -233,13 +233,13 @@ cannot read, and they are neither in nor out. | what | count | | :--- | ---: | -| write call sites on the application surface | **321** | +| write call sites on the application surface | **322** | | …whose object name is statically decidable | 226 | -| …whose object name is chosen at run time | 95 | +| …whose object name is chosen at run time | 96 | | …against an object with tenancy ENABLED | 219 | | …against an object that declares tenancy off | 7 | | threading a tenant context | 250 | -| PROVABLY carrying none (options read, no context key) | **12** | +| PROVABLY carrying none (options read, no context key) | **13** | | …of those, against a decidably tenancy-enabled object | **3** | | options argument UNREADABLE — may or may not carry one | 59 | | …of those, against a decidably tenancy-enabled object | 32 | @@ -249,7 +249,7 @@ cannot read, and they are neither in nor out. | how the instrument reached the site | count | | :--- | ---: | -| receiver carried a readable engine type | 255 | +| receiver carried a readable engine type | 256 | | receiver erased, placed by the object NAME | 56 | | receiver erased, placed by an `object: string` PARAMETER | 5 | | receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 | @@ -257,7 +257,7 @@ cannot read, and they are neither in nor out. | object name spelled inline | 140 | | object name spelled through a `const` | 86 | | object name is an `object: string` parameter | 10 | -| object name is some other run-time expression | 85 | +| object name is some other run-time expression | 86 | ### Subtractions the census could NOT defend — enforced @@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-15 at `2ab05f460`. +Measured on 2026-11-17 at `35f918fbf`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1176 | -| engine-shaped types recognised | 141 | +| tracked non-test sources scanned | 1186 | +| engine-shaped types recognised | 143 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 311 | +| same-named calls subtracted as non-engine | 325 | {/* END GENERATED: tenant-audit-census */} diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md index d9225ca889b..7df37facd84 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md @@ -33,13 +33,13 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution. | Measure | Value | |---|---:| -| Write call sites | 321 | +| Write call sites | 322 | | Object name statically decidable | 226 | -| Object name chosen at run time | 95 | +| Object name chosen at run time | 96 | | Against a tenancy-enabled object | 219 | | Against an object declaring tenancy off | 7 | | Threading a tenant context | 250 | -| Provably carrying none | 12 | +| Provably carrying none | 13 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 59 | | …and decidably tenancy-enabled | 32 | @@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-15 at `2ab05f460`. +Measured on 2026-11-17 at `35f918fbf`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1176 | -| engine-shaped types recognised | 141 | +| tracked non-test sources scanned | 1186 | +| engine-shaped types recognised | 143 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 311 | +| same-named calls subtracted as non-engine | 325 | ## Every site @@ -157,6 +157,7 @@ Measured on 2026-11-15 at `2ab05f460`. | `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 | 1 | | `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 | From 3692701c5c874b62c1fb2467616ac38771aed1f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:07:00 +0000 Subject: [PATCH 4/7] test(auth): state the fail-closed pin as the rule it holds Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../src/credential-change-ends-reset-tokens.test.ts | 4 ++-- .../plugin-auth/src/credential-change-ends-reset-tokens.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) 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 index 56c5127b6c5..2cc4659c4dc 100644 --- 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 @@ -26,7 +26,7 @@ * - with a `secondaryStorage` cache, an ended link answers what a link never * issued answers from the cache's reads too; * - a password write whose tokens cannot be ended does not land: the old - * password still signs in and the outstanding link is still live. + * password stands and the outstanding link resets. */ import { describe, it, expect, afterAll, afterEach, vi } from 'vitest'; @@ -401,7 +401,7 @@ describe('with a secondaryStorage cache, an ended link answers what a link never }); describe('a password write whose reset tokens cannot be ended does not land', () => { - it('the old password still signs in and the outstanding link still resets', async () => { + 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); 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 index 7913dc04ed3..b3008a0afe2 100644 --- a/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.ts +++ b/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.ts @@ -118,7 +118,7 @@ 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. Answers how many were ended. * Throws when a read or a delete fails, so the caller's write never lands - * beside a token that is still live. + * beside a live token. */ export async function endOutstandingResetTokens( engine: ResetTokenEngine, From 33cd9b8989f7dfcdb1395e8705a8401d7cc4734c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:27:04 +0000 Subject: [PATCH 5/7] fix(auth): a password write ends reset tokens on both storage adapters and refuses where it cannot find or name them WIP: predicate deletes where no cache is configured; pins for the composed identifier setting, the cache arm's refusal, the cached texted code, the administrator's door on a user with no local password and the raw adapter. Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- ...redential-change-ends-reset-tokens.test.ts | 204 +++++++++++++++--- .../credential-change-ends-reset-tokens.ts | 120 +++++++---- .../plugin-auth/src/objectql-adapter.ts | 32 ++- 3 files changed, 279 insertions(+), 77 deletions(-) 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 index 2cc4659c4dc..755dfef1fbd 100644 --- 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 @@ -23,10 +23,19 @@ * 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; + * 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. + * 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'; @@ -35,6 +44,11 @@ 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'; @@ -216,6 +230,39 @@ async function neverIssued(s: Awaited>) { 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(); @@ -294,14 +341,7 @@ describe('a password change ends every reset link outstanding before it', () => const unknown = await neverIssued(s); const earlier = await s.requestLink(); const { bearer } = await s.signIn(EMAIL, FIRST); - // The account as an identity provider leaves one: no local credential. - 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); + await dropLocalPassword(s); const set = await s.fire('/set-initial-password', { newPassword: SECOND }, bearer); expect(set.status, await set.clone().text()).toBe(200); @@ -310,6 +350,42 @@ describe('a password change ends every reset link outstanding before it', () => 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); @@ -364,40 +440,68 @@ describe('a password change ends the texted reset code outstanding before it', ( }, 60_000); }); -describe('with a secondaryStorage cache, an ended link answers what a link never issued answers', () => { - it('at the landing and at the reset door, the cache read first', async () => { - const cache = new Map(); - const s = await stage({ - // The embedded OAuth provider refuses a cache-held session store; it is - // not what this case is about. - plugins: { oidcProvider: false }, - 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('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(cache.has(`verification:reset-password:${earlier}`), 'the link is cached as it is issued').toBe(true); + 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(cache.has(`verification:reset-password:${earlier}`)).toBe(false); + 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', () => { @@ -420,3 +524,35 @@ describe('a password write whose reset tokens cannot be ended does not land', () 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 index b3008a0afe2..1f4568a97a6 100644 --- a/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.ts +++ b/packages/plugins/plugin-auth/src/credential-change-ends-reset-tokens.ts @@ -27,8 +27,12 @@ * `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: the - * auth instance sets no `verification.storeIdentifier`. + * 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 * @@ -40,9 +44,11 @@ * 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 the adapter calls - * {@link endResetTokensOnCredentialWrite} on each account write whose payload - * carries `password`, with the users that write targets. + * 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 @@ -52,15 +58,32 @@ * 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`, 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. `sys_verification.identifier` is `internal`, so the link - * tokens' identifiers are recovered through the privileged readback - * (`internal-field-readback.ts`), and only when a cache is configured. + * 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'; @@ -75,6 +98,12 @@ 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; @@ -92,6 +121,8 @@ export interface EndResetTokensOptions { 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; } /** @@ -116,20 +147,17 @@ 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. Answers how many were ended. - * Throws when a read or a delete fails, so the caller's write never lands - * beside a live token. + * 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 { +): Promise { const VERIFICATION = SystemObjectName.VERIFICATION; - const links = (await engine.find(VERIFICATION, { - where: { value: userId, identifier: { $startsWith: RESET_LINK_IDENTIFIER_PREFIX } }, - fields: ['id', 'identifier'], - })) as VerificationRow[]; + const linkPredicate = { value: userId, identifier: { $startsWith: RESET_LINK_IDENTIFIER_PREFIX } }; const user = (await engine.findOne(SystemObjectName.USER, { where: { id: userId }, @@ -137,37 +165,48 @@ export async function endOutstandingResetTokens( })) 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 codes = codeIdentifier - ? ((await engine.find(VERIFICATION, { where: { identifier: codeIdentifier }, fields: ['id'] })) as VerificationRow[]) - : []; - - const rows = [...links, ...codes].filter((r) => typeof r?.id === 'string' || typeof r?.id === 'number'); - if (rows.length === 0) return 0; - const cacheKeys = new Set(); + const cacheKeys: string[] = []; if (options.cache) { - if (links.length > 0 && options.internalFieldEngine) { + // 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) { - if (typeof row.identifier === 'string' && row.identifier.length > 0) cacheKeys.add(`${CACHE_KEY_PREFIX}${row.identifier}`); + await engine.delete(VERIFICATION, { where: { id: row.id } }); + cacheKeys.push(`${CACHE_KEY_PREFIX}${row.identifier as string}`); } - if (codeIdentifier) cacheKeys.add(`${CACHE_KEY_PREFIX}${codeIdentifier}`); + } else { + await engine.delete(VERIFICATION, { where: linkPredicate, multi: true }); } - for (const row of rows) { - await engine.delete(VERIFICATION, { where: { id: row.id } }); + 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); } - return rows.length; +} + +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 adapter's call: when `payload` sets a credential on `sys_account`, end + * 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. + * 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, @@ -177,10 +216,19 @@ export async function endResetTokensOnCredentialWrite( 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) users.add(id); + 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 49ae3798fcf..87837e9beb4 100644 --- a/packages/plugins/plugin-auth/src/objectql-adapter.ts +++ b/packages/plugins/plugin-auth/src/objectql-adapter.ts @@ -889,14 +889,18 @@ 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`, read off the options better-auth builds - // this adapter with (below): a credential write ends the reset tokens' - // cache entries with their rows (`credential-change-ends-reset-tokens.ts`). + // 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?( @@ -1310,8 +1314,10 @@ export function createObjectQLAdapterFactory( return (options: Parameters[0]) => { const adapter = readEverySsoProviderRowWhenUnbounded(factory(options)); wrappedAdapter = adapter; - const cache = (options as { secondaryStorage?: unknown } | undefined)?.secondaryStorage as ResetTokenCache | undefined; - resetTokenCache = cache && typeof cache.delete === 'function' ? cache : undefined; + 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; }; } @@ -1411,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; }, @@ -1444,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; @@ -1456,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 }); } From 88d2a24f5a839d2187a76fc9c85ad203a5e3262e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:39:17 +0000 Subject: [PATCH 6/7] docs(tenant-audit): regenerate the census for the reset-token seam's write sites Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../docs/permissions/tenant-audit-census.mdx | 30 +++++++++---------- ...08-tenant-audit-write-call-sites.counts.md | 14 ++++----- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index 88a5b1b4254..ff1c910fd4d 100644 --- a/content/docs/permissions/tenant-audit-census.mdx +++ b/content/docs/permissions/tenant-audit-census.mdx @@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way. The same holds twice over for the context. An options argument spelled as a literal can be read; one spelled `options`, `{ ...opts }`, or handed through a -forwarding shim cannot, and **59 of the 323 sites are spelled that way**. A +forwarding shim cannot, and **59 of the 325 sites are spelled that way**. A context resolved from an inline literal or a local `const` can be tested for `isSystem`; one arriving from a helper call cannot. @@ -160,8 +160,8 @@ now **0**: nothing on this surface threads a context that provably lacks the fla **"No tenant context" counted sites it had not read.** An options argument the walker could not parse was folded into the same bucket as one it had read and -found empty. That published **72 sites "carrying no tenant context at all"** -when 13 said so and 59 were simply unread — an over-claim in the *alarming* +found empty. That published **74 sites "carrying no tenant context at all"** +when 15 said so and 59 were simply unread — an over-claim in the *alarming* direction, on the very figure this page tells other cards to cite. `carries` is now three-valued, and an unreadable argument can never contribute to the provable count. @@ -197,9 +197,9 @@ reproduce them. Where it disagrees, it disagrees on the page: | carried figure | where it survives | this census | | :--- | :--- | ---: | -| 175 write call sites | quoted in the merged changeset | **323** | +| 175 write call sites | quoted in the merged changeset | **325** | | 24 carrying no tenant context | quoted in the merged changeset | **3** provable and tenancy-enabled; **32** more whose options argument is unreadable | -| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **227 of 323** decidable, **96** undecidable | +| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **227 of 325** decidable, **98** undecidable | | 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 181 decidably elevated, 0 decidably not, 129 undecidable | | 141 and 132, two independent re-derivations | the card that filed this work | — | @@ -217,11 +217,11 @@ would report a smaller number and would not say so. The fourth row is the one worth flagging to anyone citing it. **The 135 / 77% figure has no surviving corroboration anywhere in the tree.** This census reads -181 of 323 (56%) as decidably elevated, with 129 more whose elevation is a +181 of 325 (56%) as decidably elevated, with 129 more whose elevation is a run-time fact — so the claim is neither confirmed nor refuted, and the honest answer is that a static reading cannot settle it. -⇒ **Cite `3 / 323`, and say what it is**: the sites whose options argument was +⇒ **Cite `3 / 325`, and say what it is**: the sites whose options argument was READ and holds no tenant context, against a decidably tenancy-enabled object. That is the control's provable yield surface. ⛔ Do not cite it as "the sites without tenant context" — **32 further sites** have an options argument this @@ -233,13 +233,13 @@ cannot read, and they are neither in nor out. | what | count | | :--- | ---: | -| write call sites on the application surface | **323** | +| write call sites on the application surface | **325** | | …whose object name is statically decidable | 227 | -| …whose object name is chosen at run time | 96 | +| …whose object name is chosen at run time | 98 | | …against an object with tenancy ENABLED | 220 | | …against an object that declares tenancy off | 7 | | threading a tenant context | 251 | -| PROVABLY carrying none (options read, no context key) | **13** | +| PROVABLY carrying none (options read, no context key) | **15** | | …of those, against a decidably tenancy-enabled object | **3** | | options argument UNREADABLE — may or may not carry one | 59 | | …of those, against a decidably tenancy-enabled object | 32 | @@ -249,7 +249,7 @@ cannot read, and they are neither in nor out. | how the instrument reached the site | count | | :--- | ---: | -| receiver carried a readable engine type | 256 | +| receiver carried a readable engine type | 258 | | receiver erased, placed by the object NAME | 57 | | receiver erased, placed by an `object: string` PARAMETER | 5 | | receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 | @@ -257,7 +257,7 @@ cannot read, and they are neither in nor out. | object name spelled inline | 141 | | object name spelled through a `const` | 86 | | object name is an `object: string` parameter | 10 | -| object name is some other run-time expression | 86 | +| object name is some other run-time expression | 88 | ### Subtractions the census could NOT defend — enforced @@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-17 at `5a448780c`. +Measured on 2026-11-17 at `73ce021c1`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1189 | +| tracked non-test sources scanned | 1191 | | engine-shaped types recognised | 143 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 326 | +| same-named calls subtracted as non-engine | 328 | {/* END GENERATED: tenant-audit-census */} diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md index 9d1227a5794..df3551ba803 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md @@ -33,13 +33,13 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution. | Measure | Value | |---|---:| -| Write call sites | 323 | +| Write call sites | 325 | | Object name statically decidable | 227 | -| Object name chosen at run time | 96 | +| Object name chosen at run time | 98 | | Against a tenancy-enabled object | 220 | | Against an object declaring tenancy off | 7 | | Threading a tenant context | 251 | -| Provably carrying none | 13 | +| Provably carrying none | 15 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 59 | | …and decidably tenancy-enabled | 32 | @@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-17 at `5a448780c`. +Measured on 2026-11-17 at `73ce021c1`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1189 | +| tracked non-test sources scanned | 1191 | | engine-shaped types recognised | 143 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 326 | +| same-named calls subtracted as non-engine | 328 | ## Every site @@ -158,7 +158,7 @@ Measured on 2026-11-17 at `5a448780c`. | `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 | 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 | From 6aa9ab8204bb0acf4b213e66e34a7e6d67193a31 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:48:36 +0000 Subject: [PATCH 7/7] docs(changeset): scope the reset-token rule to the storage adapters that apply it Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .changeset/credential-change-ends-reset-tokens.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.changeset/credential-change-ends-reset-tokens.md b/.changeset/credential-change-ends-reset-tokens.md index cc866179351..8a4553bf883 100644 --- a/.changeset/credential-change-ends-reset-tokens.md +++ b/.changeset/credential-change-ends-reset-tokens.md @@ -4,12 +4,13 @@ fix(plugin-auth)!: a change to a user's credential ends every other outstanding password-reset token of that user -Clause-②: no (narrowing) — every door that sets a user's password 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: 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. +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, by any door, every reset link (`/request-password-reset`) and texted reset code (`/phone-number/request-password-reset`) issued for that user beforehand is ended. 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`, its cached copy is removed too. A password write whose outstanding tokens cannot be ended does not land: the door answers an error and the old password stands. +- **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.