diff --git a/.changeset/credential-change-ends-prior-access.md b/.changeset/credential-change-ends-prior-access.md new file mode 100644 index 00000000000..6e17d42bf92 --- /dev/null +++ b/.changeset/credential-change-ends-prior-access.md @@ -0,0 +1,21 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(plugin-auth)!: a credential change ends access issued before it + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +Once an account's password changes, the following, issued for that account before the change, no longer grant access after it: + +- An email-change link (any link the email-change flow begun at `POST /api/v1/auth/change-email` mails, at either of its steps and to either address: the confirmation sent to the current address, and the link sent to the new one) minted before the change answers at `GET /api/v1/auth/verify-email` exactly what a link that was never issued answers: `401 INVALID_TOKEN`, or the `error=INVALID_TOKEN` redirect to its callback. Its owner requests a new one. A link's issue time is whole seconds, so one minted in the same second as the change is refused too. +- A second-factor challenge opened by a password sign-in before the change answers what a challenge that was never opened answers. The person signs in again with the new password. +- A door that ends the account's sessions when it sets the password ends every session opened before its password write: both reset doors, `POST /api/v1/auth/change-password` with `revokeOtherSessions: true` (the session it installs is kept), and the one-step invitation acceptance (ahead of the session it opens). +- A password sign-in during which the account's password changes is refused with what a wrong password answers at that door, and leaves no session. + +The moment of the change is the last time the account's local password was written over, so every door that replaces a password counts, an administrator's `POST /api/v1/auth/admin/set-user-password` included. An account's first password is not a change. A check that cannot read the record refuses. Access issued after the change, and an account that never changed its local password, are untouched. No request, response or metadata shape changes. + +**BREAKING** for a client that opens an email-change link, completes a second-factor challenge, or finishes a password sign-in after the account's password changed underneath it: each is now refused as above, with the code a never-issued link, a never-opened challenge or a wrong password already answers, so a client that handles those answers needs no change. The fix for a person: request a new email-change link, or sign in again with the new password. diff --git a/content/docs/permissions/authentication.mdx b/content/docs/permissions/authentication.mdx index 9413b44b9a9..a6cb88b506f 100644 --- a/content/docs/permissions/authentication.mdx +++ b/content/docs/permissions/authentication.mdx @@ -326,6 +326,22 @@ code still outstanding for that user: a completed reset, the user's own what one that was never issued answers (`400 INVALID_TOKEN` at `reset-password`); a link or code requested after the change works as usual. +A change to a user's password also ends the following, issued before it. An +email-change link minted before the change answers what a link that was never +issued answers at `GET /api/v1/auth/verify-email` (`401 INVALID_TOKEN`, or the +`error=INVALID_TOKEN` redirect to its callback), and a second-factor challenge +opened by a password sign-in before the change answers what a challenge that +was never opened answers; the person asks again. A door that ends the +account's sessions — a completed reset, `change-password` with +`revokeOtherSessions: true` (the session it installs is kept) and the one-step +invitation acceptance — ends every session opened before its password write, +and a password sign-in during which the password changes is refused with what +a wrong password answers. The change's moment is the last time the account's +local password was written over, so an administrator's `set-user-password` +counts too, and an account's first password is not a change; an email-change +link carries its issue time in whole seconds, so one minted in the same second +as the change is refused as well. + #### Setting a first local password `POST /api/v1/auth/set-initial-password` sets an **initial** local password for a diff --git a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts index 91c1dc4fcee..c288b225059 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-after-hook.ts @@ -45,6 +45,12 @@ import { BANNED_USER_CODE, causeBannedUserRefusal } from './banned-user-refusal- import type { AuthManager } from './auth-manager.js'; import { refusalCodeOf } from './auth-session-audit.js'; import { passwordSignInDoorOf } from './auth-manager-sign-in-lockout.js'; +import { + endSessionsAfterCredentialWrite, + refuseSignInAcrossCredentialChange, + RESET_DOOR_PATHS, + RESET_DOOR_SUBJECT, +} from './credential-change-ends-prior-access.js'; import { narrowDirectoryForExternalCaller } from './external-directory-door.js'; import { SESSION_SCOPING_REFUSAL } from './organization-access-policy.js'; import { refuseIntrospectionForBannedSubject } from './oauth-token-read-ban-refusal.js'; @@ -165,8 +171,74 @@ async function refusedAfterTheCredential(returned: unknown): Promise { return after.includes(code); } +/** + * What a wrong password answers at `door`: better-auth's own refusal there + * (1.7.12), its code read off the vendor's own tables — `BASE_ERROR_CODES` for + * the email door, the phone-number plugin's `$ERROR_CODES` for the phone door — + * so no code is minted here. + */ +async function wrongPasswordAt(ctx: any, door: 'email' | 'phone'): Promise { + const { APIError } = await import('better-auth/api'); + const { BASE_ERROR_CODES } = await import('@better-auth/core/error'); + const phoneCodes = door === 'phone' ? ctx?.context?.getPlugin?.('phone-number')?.$ERROR_CODES : undefined; + const phoneRefusal = phoneCodes?.INVALID_PHONE_NUMBER_OR_PASSWORD; + return APIError.from('UNAUTHORIZED', phoneRefusal ?? BASE_ERROR_CODES.INVALID_EMAIL_OR_PASSWORD); +} + +/** Whether the endpoint answered a success (no `APIError` on `returned`). */ +async function endpointSucceeded(ctx: any): Promise { + try { + const { isAPIError } = await import('better-auth/api'); + return !isAPIError(ctx?.context?.returned); + } catch { + return !(ctx?.context?.returned instanceof Error); + } +} + +/** + * A door that ends the account's sessions when it sets the password ends them + * again now that the password is written (`credential-change-ends-prior- + * access.ts`): both reset doors, and `/change-password` asked to end the other + * sessions, which keeps the session it installed. + */ +async function endSessionsOnceThePasswordIsWritten(this: Pick, ctx: any): Promise { + const resetDoor = RESET_DOOR_PATHS.has(ctx?.path); + const changeDoor = ctx?.path === '/change-password' && ctx?.body?.revokeOtherSessions === true; + if (!resetDoor && !changeDoor) return; + if (!(await endpointSucceeded(ctx))) return; + const internal = ctx?.context?.internalAdapter; + const subject: unknown = resetDoor ? ctx?.context?.[RESET_DOOR_SUBJECT] : actingUserIdOf(ctx); + const installed: unknown = ctx?.context?.returned?.token; + if (typeof subject !== 'string' || !subject || !internal || (changeDoor && (typeof installed !== 'string' || !installed))) { + this.logDurabilityDegradation( + 'AuthManager: a password was set by a door that ends the account\'s sessions, but the sessions were NOT ' + + 'ended again once the password was written: the account it set could not be named. The door ended ' + + 'them before the write, as it always has. Remedy: none per request; report it, the next such door ' + + 'ends them again.', + new Error('the account of a session-ending password door could not be named'), + { object: 'sys_session', path: String(ctx?.path) }, + ); + return; + } + await endSessionsAfterCredentialWrite(internal, subject, changeDoor ? (installed as string) : undefined); +} + /** The body of `createAuthInstance`'s `hooks.after` arrow; the comments there and in it are its contract. */ export async function globalAfterHook(this: AfterHookHost, ctx: any) { + // ── A credential change ends access issued before it ────────────── + // FIRST: a password sign-in during which the account's password changed + // is refused, its session ended and the response left without one, ahead + // of every after-hook that reads the new session — the second-factor + // plugin's among them, which then opens no challenge. Its refusal is what + // a wrong password answers at that door; the lockout settlement below + // reads it as one, and it is thrown once that settlement has run. + // `credential-change-ends-prior-access.ts` states the rule. + const signInDoor = passwordSignInDoorOf(ctx); + const signInAcrossChange = signInDoor + ? await refuseSignInAcrossCredentialChange(ctx, () => wrongPasswordAt(ctx, signInDoor.door)) + : undefined; + if (signInAcrossChange) ctx.context.returned = signInAcrossChange; + // ── #8243: impersonation must actually take effect for a bearer ── // FIRST among the after-hooks that touch the response, because the // bearer plugin's own after-hook runs behind this one and must see @@ -310,12 +382,17 @@ export async function globalAfterHook(this: AfterHookHost, ctx: any) { // on a match, so it stays after the settlement and the refusal's // `login_failed` row above. The phone door goes on to the hooks below, // as before. + if (signInAcrossChange) throw signInAcrossChange; if (door === 'email') { await causeBannedUserRefusal(ctx); return; } } + // ── A credential change ends access issued before it ────────────── + // Ahead of the password-change after-effects below, which return. + await endSessionsOnceThePasswordIsWritten.call(this, ctx); + // ── ADR-0069 D1: on a successful change/reset — stamp // password_changed_at (expiry) and commit password history. // diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts index 990a149fe2d..c454cffb0ce 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts @@ -66,6 +66,12 @@ import { setAuthActorResolver } from './auth-actor-attribution.js'; import { AuthManager } from './auth-manager.js'; import { passwordSignInDoorOf, recordLockoutRequest } from './auth-manager-sign-in-lockout.js'; import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.js'; +import { + endEmailChangeTokenIssuedBeforeCredentialChange, + endTwoFactorChallengeIssuedBeforeCredentialChange, + noteSignInCredential, + RESET_DOOR_SUBJECT, +} from './credential-change-ends-prior-access.js'; import { isLastLocalCredentialHolder, LAST_LOCAL_CREDENTIAL_CODE, @@ -196,7 +202,12 @@ export async function globalBeforeHook( this: BeforeHookHost, ctx: any, setShouldSkipSessionRefresh: typeof import('better-auth/api').setShouldSkipSessionRefresh, -): Promise | Response | void> { +): Promise< + | ReturnType + | Awaited> + | Response + | void +> { // ── #4586: hand the attribution scope its actor resolver ───── // FIRST, and unconditionally: this global before-hook is the one // seam every better-auth endpoint passes through (`matcher: () => @@ -251,6 +262,15 @@ export async function globalBeforeHook( // see `auth-manager-sign-in-lockout.ts`. await recordLockoutRequest.call(this, ctx); + // ── A credential change ends access issued before it ────────── + // An email-change link minted before the account's last credential + // change answers what a link never issued answers, and a second-factor + // challenge opened before it is ended. `credential-change-ends-prior- + // access.ts` states the rule and its one predicate. + const endedEmailChange = await endEmailChangeTokenIssuedBeforeCredentialChange(ctx); + if (endedEmailChange) return endedEmailChange; + await endTwoFactorChallengeIssuedBeforeCredentialChange(ctx); + // ── [#33203] Cloud-managed: no reset door sets a local password ── // A hosted environment sets no local password for anyone, a platform // administrator included (ruling 10 of cloud#4465, `cloud-managed.ts`). @@ -314,6 +334,10 @@ export async function globalBeforeHook( const resetSubject = resetDoor ? await resolveResetDoorUserId(ctx, this.config.phoneOtp?.allowedAttempts ?? 3) : undefined; + // The account a reset door sets the password of, for the after-hook, which + // ends its sessions again once the password is written + // (`credential-change-ends-prior-access.ts`). + if (resetSubject?.ok && resetSubject.userId && ctx?.context) ctx.context[RESET_DOOR_SUBJECT] = resetSubject.userId; if (resetSubject?.ok && resetSubject.userId) { const source = await readUserSource(this.getDataEngine(), resetSubject.userId); if (source.ok && isPendingSsoSource(source.value)) { @@ -942,6 +966,20 @@ export async function globalBeforeHook( const passwordDoor = passwordSignInDoorOf(ctx); if (passwordDoor) { if (passwordDoor.identifier) await this.admitSignInAttempt(passwordDoor.identifier, ctx, passwordDoor.door); + // A sign-in during which the account's password changes is refused: the + // first of its two readings (`credential-change-ends-prior-access.ts`). + // Each door's account is the one the vendor's own lookup at that door + // names, read through the vendor's adapter, so the reading needs no data + // engine. + const { door, identifier } = passwordDoor; + await noteSignInCredential(ctx, async () => { + if (!identifier) return undefined; + const id: unknown = + door === 'phone' + ? (await ctx.context.adapter.findOne({ model: 'user', where: [{ field: 'phoneNumber', value: identifier }] }))?.id + : (await ctx.context.internalAdapter.findUserByEmail(identifier.toLowerCase()))?.user?.id; + return typeof id === 'string' && id.length > 0 ? id : undefined; + }); return; } diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts new file mode 100644 index 00000000000..ca14e15d513 --- /dev/null +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.test.ts @@ -0,0 +1,695 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A credential change ends access issued before it + * (`credential-change-ends-prior-access.ts`). + * + * Every door is driven through the real routes: a real `AuthManager` over a + * real `ObjectQL` engine (better-sqlite3, this plugin's own manifest), behind + * `AuthPlugin.registerAuthRoutes` mounted on a Hono app. + * + * Pinned: + * - an email-change link minted before a completed reset, a `/change-password` + * or an administrator's `/admin/set-user-password` answers what a link + * never issued answers (with and without a callback), the address does not + * move and no session is opened; a link minted after the change verifies; + * - a second-factor challenge opened before a reset answers what a challenge + * never opened answers; one opened after it completes; + * - a session a sign-in opens between a door's session revocation and its + * password write is ended by the door — the emailed reset, the texted + * reset, and `/change-password` asked to end the other sessions (the + * session it installs stands); + * - a password sign-in during which the account's password changes is + * refused with what a wrong password answers at that door (email and + * phone), and leaves no session; + * - the predicate and the clock: nothing is before a change that never + * happened, and the clock is the last write over the credential row. + */ + +import { describe, it, expect, afterAll, afterEach, vi } from 'vitest'; +import { createHmac } from 'node:crypto'; +import { Hono } from 'hono'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { AuthManager } from './auth-manager.js'; +import { AuthPlugin } from './auth-plugin.js'; +import { issuedBeforeCredentialChange, readCredentialChangedAt } from './credential-change-ends-prior-access.js'; +import { authIdentityObjects } from './manifest.js'; +import { inviteForAudienceGate } from './audience-gate-test-support'; +import { memoizeScrypt } from './__tests__/scrypt-memo.testkit'; +import { sqliteEnginePool } from './__tests__/sqlite-engine-pool.testkit'; +// better-auth's first module load is paid here, at module load, not inside the +// first case (AGENTS.md, Build & Test: clocked windows measure behaviour). +import 'better-auth'; +import 'better-auth/api'; +import 'better-auth/plugins'; +import 'better-auth/plugins/two-factor'; + +const ORIGIN = 'http://localhost:3000'; +const BASE = '/api/v1/auth'; +const SECRET = 'test-secret-at-least-32-chars-long-prior-access-ends'; +const ADMIN_EMAIL = 'prior-access-admin@example.com'; +const EMAIL = 'prior-access-user@example.com'; +const NEW_ADDRESS = 'prior-access-moved@example.com'; +const PHONE = '+15550188'; +const FIRST = 'F1rst!Password-Prior'; +const SECOND = 'S3cond!Password-Prior'; +const SYS = { context: { isSystem: true } } as never; + +const engines = sqliteEnginePool(async () => { + const engine = new ObjectQL(); + const driver = new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }); + engine.registerDriver(driver, true); + await engine.init(); + for (const object of authIdentityObjects) { + engine.registry.registerObject(object as never, '@objectstack/plugin-auth'); + } + await engine.syncSchemas(); + return { engine, driver }; +}); +afterEach(engines.release); +afterAll(engines.destroy); + +const scrypt = memoizeScrypt(); +afterAll(scrypt.restore); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +const mockCtx = () => + ({ + registerService: vi.fn(), + getService: vi.fn((name: string) => (name === 'manifest' ? { register: vi.fn() } : undefined)), + getServices: vi.fn(() => new Map()), + hook: vi.fn(), + trigger: vi.fn(), + logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }, + getKernel: vi.fn(), + }) as any; + +/** Status and the error code, in either envelope the auth doors answer with. */ +async function answer(res: Response): Promise<{ status: number; code?: string }> { + const body = (await res.clone().json().catch(() => null)) as { code?: unknown; error?: { code?: unknown } } | null; + const code = body?.error?.code ?? body?.code; + return { status: res.status, ...(typeof code === 'string' ? { code } : {}) }; +} + +const cookieOf = (res: Response): string => + (res.headers.getSetCookie?.() ?? []).map((c) => c.split(';')[0]).filter(Boolean).join('; '); + +/** + * Whether a response hands its caller a session in its headers: a + * `set-auth-token` header, or a session cookie set to a value (a cookie + * cleared to empty hands out none). + */ +const handsOutSession = (res: Response): boolean => + res.headers.get('set-auth-token') !== null + || (res.headers.getSetCookie?.() ?? []).some((c) => /session_(token|data)=[^;]+/.test(c.split(';')[0])); + +// RFC 6238 TOTP, hand-rolled as `two-factor-reenrollment-verified-reset.test.ts` does. +function base32Decode(input: string): Buffer { + const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + let bits = 0; + let value = 0; + const out: number[] = []; + for (const char of input.replace(/=+$/, '').toUpperCase()) { + value = (value << 5) | ALPHABET.indexOf(char); + bits += 5; + if (bits >= 8) { + out.push((value >>> (bits - 8)) & 0xff); + bits -= 8; + } + } + return Buffer.from(out); +} +function totp(secret: Buffer): string { + const buf = Buffer.alloc(8); + buf.writeBigUInt64BE(BigInt(Math.floor(Date.now() / 30_000))); + const digest = createHmac('sha1', secret).update(buf).digest(); + const offset = digest[digest.length - 1] & 0x0f; + const code = + ((digest[offset] & 0x7f) << 24) | ((digest[offset + 1] & 0xff) << 16) | ((digest[offset + 2] & 0xff) << 8) | (digest[offset + 3] & 0xff); + return String(code % 1_000_000).padStart(6, '0'); +} + +/** + * One deployment: an administrator (the first account) and the user under test + * (signed up through an invitation, as `invite_only` admits a second account), + * behind the real route mount, with mail and texts captured. + */ +async function stage(config: Record = {}) { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'info').mockImplementation(() => {}); + const engine = await engines.take(); + const manager = new AuthManager({ + secret: SECRET, + baseUrl: ORIGIN, + dataEngine: engine as never, + ...config, + plugins: { admin: true, ...((config.plugins as Record) ?? {}) }, + } as never); + const mail: Array<{ template: string; to?: { address?: string }; data: Record }> = []; + manager.setEmailService({ + sendTemplate: async (input: any) => { + mail.push(input); + return { status: 'sent' }; + }, + } as never); + const texts: Array<{ to: string; templateParams?: { code?: string } }> = []; + manager.setSmsService({ + async send(input: { to: string; templateParams?: { code?: string } }) { + texts.push(input); + return { id: `sms${texts.length}`, status: 'sent' }; + }, + isConfigured: () => true, + } as never); + + const app = new Hono(); + const ctx = mockCtx(); + const plugin = new AuthPlugin({ secret: SECRET }); + await plugin.init(ctx); + (plugin as any).authManager = manager; + (plugin as any).registerAuthRoutes({ getRawApp: () => app, getPort: () => 0 }, ctx); + + const fire = (path: string, body: unknown, headers: Record = {}) => + app.request(`${ORIGIN}${BASE}${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN, ...headers }, + body: JSON.stringify(body), + }); + const bearer = (token: string) => ({ authorization: `Bearer ${token}` }); + + const signUp = async (email: string, invited: boolean) => { + const invitationId = invited ? await inviteForAudienceGate(engine, email) : undefined; + const res = await fire('/sign-up/email', { email, password: FIRST, name: email, ...(invitationId ? { invitationId } : {}) }); + expect(res.status, `sign-up ${email}: ${await res.clone().text()}`).toBe(200); + }; + await signUp(ADMIN_EMAIL, false); + await signUp(EMAIL, true); + + const idOf = async (email: string) => + String(((await engine.find('sys_user', { where: { email }, limit: 1 }, SYS)) as Array<{ id: string }>)[0].id); + await engine.update('sys_user', { id: await idOf(ADMIN_EMAIL), role: 'admin' }, SYS); + const userId = await idOf(EMAIL); + + /** The bearer a password sign-in mints, the refusal's answer, and the challenge cookie when one is asked. */ + const signIn = async (email: string, password: string) => { + const res = await fire('/sign-in/email', { email, password }); + const body = (await res.clone().json().catch(() => null)) as { twoFactorRedirect?: boolean } | null; + return { + ...(await answer(res)), + bearer: res.headers.get('set-auth-token') ?? undefined, + handsOutSession: handsOutSession(res), + challenge: body?.twoFactorRedirect === true ? cookieOf(res) : undefined, + }; + }; + + /** The account a bearer signs in as now, or `null`. */ + const whoIs = async (token: string): Promise => { + const res = await app.request(`${ORIGIN}${BASE}/get-session`, { headers: { origin: ORIGIN, ...bearer(token) } }); + const body = (await res.json().catch(() => null)) as { user?: { id?: string } } | null; + return body?.user?.id ?? null; + }; + + /** The sessions of the user that better-auth would still honour. */ + const liveSessions = async () => { + const auth: any = await manager.getAuthContext(); + return (await auth.internalAdapter.listSessions(userId)) as Array<{ token: string }>; + }; + + const requestLink = async (): Promise => { + const before = mail.filter((m) => m.template === 'auth.password_reset').length; + const res = await fire('/request-password-reset', { email: EMAIL, redirectTo: `${ORIGIN}/reset` }); + expect(res.status, await res.clone().text()).toBe(200); + await vi.waitFor(() => expect(mail.filter((m) => m.template === 'auth.password_reset').length).toBe(before + 1)); + return String(mail.filter((m) => m.template === 'auth.password_reset')[before].data.token); + }; + const reset = async (newPassword: string) => { + const token = await requestLink(); + return answer(await fire('/reset-password', { token, newPassword })); + }; + + /** The email-change link `/change-email` mails to the new address. */ + const requestEmailChange = async (token: string, newEmail = NEW_ADDRESS): Promise => { + const toNew = () => mail.filter((m) => m.template === 'auth.verify_email' && m.to?.address === newEmail).length; + const before = toNew(); + const res = await fire('/change-email', { newEmail, callbackURL: '/' }, bearer(token)); + expect(res.status, `change-email: ${await res.clone().text()}`).toBe(200); + await vi.waitFor(() => expect(toNew()).toBe(before + 1)); + return String(mail.filter((m) => m.template === 'auth.verify_email' && m.to?.address === newEmail)[before].data.token); + }; + + /** What `GET /verify-email` answers a token: status, code, the redirect's error, and whether it opened a session. */ + const verifyEmail = async (token: string, callbackURL?: string) => { + const query = `token=${encodeURIComponent(token)}${callbackURL ? `&callbackURL=${encodeURIComponent(callbackURL)}` : ''}`; + const res = await app.request(`${ORIGIN}${BASE}/verify-email?${query}`, { method: 'GET', headers: { origin: ORIGIN } }); + const location = res.headers.get('location'); + return { + ...(await answer(res)), + redirectError: location ? new URL(location, ORIGIN).searchParams.get('error') : undefined, + opensSession: /session_token=[^;]+/.test(res.headers.getSetCookie?.().join('\n') ?? ''), + }; + }; + + const emailOf = async () => + String(((await engine.findOne('sys_user', { where: { id: userId }, fields: ['email'], context: { isSystem: true } } as never)) as { email: string }).email); + + const admin = await signIn(ADMIN_EMAIL, FIRST); + expect(admin.bearer, 'the administrator signs in on the bearer lane').toBeTruthy(); + + return { + engine, manager, fire, bearer, signIn, whoIs, liveSessions, requestLink, reset, requestEmailChange, + verifyEmail, emailOf, userId, texts, adminBearer: admin.bearer!, + }; +} + +/** + * Move the wall clock two seconds on: past the window in which a credential + * row's write is still its creation, and past the whole second a token minted + * next carries as its `iat`. + */ +function advanceTheClock() { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(Date.now() + 2_000); +} + +/** Turn on a TOTP second factor for the account `bearer` signs in as, and answer its secret. */ +async function enrolTotp(s: Awaited>, bearer: string): Promise { + const enabled = await s.fire('/two-factor/enable', { password: FIRST }, s.bearer(bearer)); + expect(enabled.status, await enabled.clone().text()).toBe(200); + const { totpURI } = (await enabled.json()) as { totpURI: string }; + const secret = base32Decode(String(new URL(totpURI.replace('otpauth://', 'https://')).searchParams.get('secret'))); + const confirmed = await s.fire('/two-factor/verify-totp', { code: totp(secret) }, s.bearer(bearer)); + expect(confirmed.status, await confirmed.clone().text()).toBe(200); + return secret; +} + +describe('an email-change link issued before a credential change answers what a link never issued answers', () => { + it('after a completed reset: no session, the address stays; a link minted after the reset verifies', async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + const before = await s.requestEmailChange(user.bearer!); + const neverIssued = await s.verifyEmail('a-token-never-issued'); + expect(neverIssued).toMatchObject({ status: 401, code: 'INVALID_TOKEN', opensSession: false }); + + advanceTheClock(); + expect(await s.reset(SECOND)).toEqual({ status: 200 }); + + expect(await s.verifyEmail(before)).toEqual(neverIssued); + expect(await s.emailOf()).toBe(EMAIL); + expect(await s.liveSessions()).toEqual([]); + + // The control: a link minted after the reset verifies and moves the address. + advanceTheClock(); + const again = await s.signIn(EMAIL, SECOND); + const after = await s.requestEmailChange(again.bearer!); + expect(await s.verifyEmail(after)).toMatchObject({ status: 200 }); + expect(await s.emailOf()).toBe(NEW_ADDRESS); + }, 60_000); + + it('with a callback, it redirects with the error a link never issued redirects with', async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + const before = await s.requestEmailChange(user.bearer!); + const neverIssued = await s.verifyEmail('a-token-never-issued', '/settings'); + expect(neverIssued.redirectError).toBe('INVALID_TOKEN'); + + advanceTheClock(); + expect(await s.reset(SECOND)).toEqual({ status: 200 }); + + expect(await s.verifyEmail(before, '/settings')).toEqual(neverIssued); + expect(await s.emailOf()).toBe(EMAIL); + }, 60_000); + + it("after the user's own /change-password, sessions kept", async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + const before = await s.requestEmailChange(user.bearer!); + const neverIssued = await s.verifyEmail('a-token-never-issued'); + + advanceTheClock(); + const changed = await s.fire('/change-password', { currentPassword: FIRST, newPassword: SECOND }, s.bearer(user.bearer!)); + expect(changed.status, await changed.clone().text()).toBe(200); + + expect(await s.verifyEmail(before)).toEqual(neverIssued); + expect(await s.emailOf()).toBe(EMAIL); + }, 60_000); + + it("after an administrator's /admin/set-user-password", async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + const before = await s.requestEmailChange(user.bearer!); + const neverIssued = await s.verifyEmail('a-token-never-issued'); + + advanceTheClock(); + const set = await s.fire( + '/admin/set-user-password', + { userId: s.userId, newPassword: SECOND, mustChangePassword: false }, + s.bearer(s.adminBearer), + ); + expect(set.status, await set.clone().text()).toBe(200); + + expect(await s.verifyEmail(before)).toEqual(neverIssued); + expect(await s.emailOf()).toBe(EMAIL); + }, 60_000); +}); + +describe('a second-factor challenge opened before a credential change answers what a challenge never opened answers', () => { + it('after a completed reset; a challenge opened after it completes', async () => { + const s = await stage({ plugins: { twoFactor: true } }); + const user = await s.signIn(EMAIL, FIRST); + const enabled = await s.fire('/two-factor/enable', { password: FIRST }, s.bearer(user.bearer!)); + expect(enabled.status, await enabled.clone().text()).toBe(200); + const { totpURI } = (await enabled.json()) as { totpURI: string }; + const secret = base32Decode(String(new URL(totpURI.replace('otpauth://', 'https://')).searchParams.get('secret'))); + const confirmed = await s.fire('/two-factor/verify-totp', { code: totp(secret) }, s.bearer(user.bearer!)); + expect(confirmed.status, await confirmed.clone().text()).toBe(200); + + const opened = await s.signIn(EMAIL, FIRST); + expect(opened.challenge, 'the password sign-in stops at the challenge').toBeTruthy(); + const neverOpened = await answer(await s.fire('/two-factor/verify-totp', { code: totp(secret) })); + + advanceTheClock(); + expect(await s.reset(SECOND)).toEqual({ status: 200 }); + + expect(await answer(await s.fire('/two-factor/verify-totp', { code: totp(secret) }, { cookie: opened.challenge! }))).toEqual(neverOpened); + expect(await s.liveSessions()).toEqual([]); + + // The control: a challenge opened after the reset completes. + const fresh = await s.signIn(EMAIL, SECOND); + expect(fresh.challenge).toBeTruthy(); + const completed = await s.fire('/two-factor/verify-totp', { code: totp(secret) }, { cookie: fresh.challenge! }); + expect(completed.status, await completed.clone().text()).toBe(200); + }, 60_000); +}); + +describe('a door that ends the sessions ends the ones opened before its password write lands', () => { + /** Run `during` once, just before the next password write of the user reaches the store. */ + async function beforeThePasswordWrite(s: Awaited>, verb: 'updatePassword' | 'updateAccount', during: () => Promise) { + const internal = (await s.manager.getAuthContext()).internalAdapter; + const original = internal[verb].bind(internal); + let ran = false; + vi.spyOn(internal, verb).mockImplementation(async (...args: unknown[]) => { + if (!ran) { + ran = true; + await during(); + } + return original(...args); + }); + } + + it('the emailed reset', async () => { + const s = await stage(); + let opened: string | undefined; + await beforeThePasswordWrite(s, 'updatePassword', async () => { + opened = (await s.signIn(EMAIL, FIRST)).bearer; + }); + + expect(await s.reset(SECOND)).toEqual({ status: 200 }); + + expect(opened, 'a sign-in ran before the password write').toBeTruthy(); + expect(await s.whoIs(opened!)).toBeNull(); + expect(await s.liveSessions()).toEqual([]); + }, 60_000); + + it('the texted reset', async () => { + const s = await stage({ plugins: { phoneNumber: true }, phoneOtp: { cooldownSeconds: 0 } }); + await s.engine.update('sys_user', { id: s.userId, phone_number: PHONE, phone_number_verified: true }, SYS); + const sent = await s.fire('/phone-number/request-password-reset', { phoneNumber: PHONE }); + expect(sent.status, await sent.clone().text()).toBe(200); + await vi.waitFor(() => expect(s.texts.length).toBe(1)); + const otp = String(s.texts[0].templateParams?.code ?? ''); + let opened: string | undefined; + await beforeThePasswordWrite(s, 'updatePassword', async () => { + opened = (await s.signIn(EMAIL, FIRST)).bearer; + }); + + expect(await answer(await s.fire('/phone-number/reset-password', { phoneNumber: PHONE, otp, newPassword: SECOND }))).toEqual({ status: 200 }); + + expect(opened, 'a sign-in ran before the password write').toBeTruthy(); + expect(await s.whoIs(opened!)).toBeNull(); + expect(await s.liveSessions()).toEqual([]); + }, 60_000); + + it('/change-password asked to end the other sessions; the session it installs stands', async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + let opened: string | undefined; + await beforeThePasswordWrite(s, 'updateAccount', async () => { + opened = (await s.signIn(EMAIL, FIRST)).bearer; + }); + + const changed = await s.fire( + '/change-password', + { currentPassword: FIRST, newPassword: SECOND, revokeOtherSessions: true }, + s.bearer(user.bearer!), + ); + expect(changed.status, await changed.clone().text()).toBe(200); + const installed = String(((await changed.json()) as { token?: string }).token); + + expect(opened, 'a sign-in ran before the password write').toBeTruthy(); + expect(await s.whoIs(opened!)).toBeNull(); + expect(await s.whoIs(installed)).toBe(s.userId); + expect((await s.liveSessions()).map((row) => row.token)).toEqual([installed]); + }, 60_000); +}); + +describe('a password sign-in during which the password changes is refused', () => { + it('it answers what a wrong password answers and leaves no session', async () => { + const s = await stage(); + const wrong = await s.signIn(EMAIL, 'Not!The-Password-1'); + expect(wrong.status).toBe(401); + const link = await s.requestLink(); + const internal = (await s.manager.getAuthContext()).internalAdapter; + const original = internal.createSession.bind(internal); + let changed: { status: number; code?: string } | undefined; + vi.spyOn(internal, 'createSession').mockImplementation(async (...args: unknown[]) => { + if (!changed) changed = await answer(await s.fire('/reset-password', { token: link, newPassword: SECOND })); + return original(...args); + }); + + const raced = await s.signIn(EMAIL, FIRST); + + expect(changed).toEqual({ status: 200 }); + expect({ status: raced.status, code: raced.code }).toEqual({ status: wrong.status, code: wrong.code }); + expect(wrong.handsOutSession, 'a wrong password hands out no session').toBe(false); + expect(raced.handsOutSession, 'the refused sign-in hands out no session token in its headers').toBe(false); + expect(await s.liveSessions()).toEqual([]); + }, 60_000); + + it('the phone door: it answers what a wrong password answers there and leaves no session', async () => { + const s = await stage({ plugins: { phoneNumber: true }, phoneOtp: { cooldownSeconds: 0 } }); + await s.engine.update('sys_user', { id: s.userId, phone_number: PHONE, phone_number_verified: true }, SYS); + const phoneSignIn = async (password: string) => { + const res = await s.fire('/sign-in/phone-number', { phoneNumber: PHONE, password }); + return { ...(await answer(res)), handsOutSession: handsOutSession(res) }; + }; + const wrong = await phoneSignIn('Not!The-Password-1'); + expect(wrong).toMatchObject({ status: 401, code: 'INVALID_PHONE_NUMBER_OR_PASSWORD' }); + const fine = await phoneSignIn(FIRST); + expect(fine, 'the control: the phone door hands out a session to the right password').toMatchObject({ status: 200, handsOutSession: true }); + const link = await s.requestLink(); + const internal = (await s.manager.getAuthContext()).internalAdapter; + const original = internal.createSession.bind(internal); + let changed: { status: number; code?: string } | undefined; + vi.spyOn(internal, 'createSession').mockImplementation(async (...args: unknown[]) => { + if (!changed) changed = await answer(await s.fire('/reset-password', { token: link, newPassword: SECOND })); + return original(...args); + }); + + const raced = await phoneSignIn(FIRST); + + expect(changed).toEqual({ status: 200 }); + expect({ status: raced.status, code: raced.code }).toEqual({ status: wrong.status, code: wrong.code }); + expect(wrong.handsOutSession, 'a wrong password hands out no session').toBe(false); + expect(raced.handsOutSession, 'the refused sign-in hands out no session token in its headers').toBe(false); + expect(await s.liveSessions()).toEqual([]); + }, 60_000); + + it('a sign-in the password does not change during stands (the control)', async () => { + const s = await stage(); + const fine = await s.signIn(EMAIL, FIRST); + expect(fine.status).toBe(200); + expect(fine.handsOutSession).toBe(true); + expect(await s.whoIs(fine.bearer!)).toBe(s.userId); + }, 60_000); +}); + +describe('a check that cannot read its record refuses', () => { + /** The account's credential row cannot be read through the vendor's adapter, until the spy is restored. */ + async function unreadableCredential(s: Awaited>) { + const internal = (await s.manager.getAuthContext()).internalAdapter; + return vi.spyOn(internal, 'findCredentialAccount').mockRejectedValue(new Error('the credential row cannot be read')); + } + + it('an email-change link whose clock cannot be read answers what a link never issued answers; read again, it verifies', async () => { + const s = await stage(); + const user = await s.signIn(EMAIL, FIRST); + const link = await s.requestEmailChange(user.bearer!); + const neverIssued = await s.verifyEmail('a-token-never-issued'); + + const unreadable = await unreadableCredential(s); + expect(await s.verifyEmail(link)).toEqual(neverIssued); + expect(unreadable).toHaveBeenCalled(); + expect(await s.emailOf()).toBe(EMAIL); + + // The control: the account never changed its password, so the same link verifies once the clock reads. + unreadable.mockRestore(); + expect(await s.verifyEmail(link)).toMatchObject({ status: 200 }); + expect(await s.emailOf()).toBe(NEW_ADDRESS); + }, 60_000); + + it('a second-factor challenge whose clock cannot be read answers what a challenge never opened answers', async () => { + const s = await stage({ plugins: { twoFactor: true } }); + const secret = await enrolTotp(s, (await s.signIn(EMAIL, FIRST)).bearer!); + const opened = await s.signIn(EMAIL, FIRST); + expect(opened.challenge, 'the password sign-in stops at the challenge').toBeTruthy(); + const neverOpened = await answer(await s.fire('/two-factor/verify-totp', { code: totp(secret) })); + + const unreadable = await unreadableCredential(s); + expect(await answer(await s.fire('/two-factor/verify-totp', { code: totp(secret) }, { cookie: opened.challenge! }))).toEqual(neverOpened); + expect(unreadable).toHaveBeenCalled(); + unreadable.mockRestore(); + + // The control: a challenge verified while the clock reads completes. + const fresh = await s.signIn(EMAIL, FIRST); + const completed = await s.fire('/two-factor/verify-totp', { code: totp(secret) }, { cookie: fresh.challenge! }); + expect(completed.status, await completed.clone().text()).toBe(200); + }, 60_000); + + it('a password sign-in whose first reading cannot be taken answers what a wrong password answers and leaves no session', async () => { + const s = await stage(); + const wrong = await s.signIn(EMAIL, 'Not!The-Password-1'); + const internal = (await s.manager.getAuthContext()).internalAdapter; + const original = internal.findCredentialAccount.bind(internal); + let refusedReads = 0; + vi.spyOn(internal, 'findCredentialAccount').mockImplementation(async (...args: unknown[]) => { + if (refusedReads === 0) { + refusedReads += 1; + throw new Error('the credential row cannot be read'); + } + return (original as (...a: unknown[]) => Promise)(...args); + }); + + // The session sign-up opened stands throughout; the refused sign-in adds none to it. + const tokens = async () => (await s.liveSessions()).map((row) => row.token).sort(); + const sessionsBefore = await tokens(); + const refused = await s.signIn(EMAIL, FIRST); + + expect(refusedReads, 'the first reading was the one that failed').toBe(1); + expect({ status: refused.status, code: refused.code }).toEqual({ status: wrong.status, code: wrong.code }); + expect(refused.handsOutSession).toBe(false); + expect(await tokens()).toEqual(sessionsBefore); + + // The control: with both readings taken, the same sign-in stands and adds its session. + const fine = await s.signIn(EMAIL, FIRST); + expect(fine).toMatchObject({ status: 200, handsOutSession: true }); + expect(await s.whoIs(fine.bearer!)).toBe(s.userId); + expect((await tokens()).length).toBe(sessionsBefore.length + 1); + }, 60_000); +}); + +describe('the clock and the sign-in readings need no data engine', () => { + it('on the vendor in-memory adapter: a link of an account that never changed its password verifies; one minted before a change does not; both password doors sign in', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.spyOn(console, 'info').mockImplementation(() => {}); + // No `dataEngine`: the manager runs on better-auth's own in-memory adapter. + const manager = new AuthManager({ secret: SECRET, baseUrl: ORIGIN, plugins: { admin: true, phoneNumber: true } } as never); + const mail: Array<{ template: string; to?: { address?: string }; data: Record }> = []; + manager.setEmailService({ + sendTemplate: async (input: any) => { + mail.push(input); + return { status: 'sent' }; + }, + } as never); + manager.setSmsService({ send: async () => ({ id: 'sms', status: 'sent' }), isConfigured: () => true } as never); + const app = new Hono(); + const ctx = mockCtx(); + const plugin = new AuthPlugin({ secret: SECRET }); + await plugin.init(ctx); + (plugin as any).authManager = manager; + (plugin as any).registerAuthRoutes({ getRawApp: () => app, getPort: () => 0 }, ctx); + const fire = (path: string, body: unknown, headers: Record = {}) => + app.request(`${ORIGIN}${BASE}${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN, ...headers }, + body: JSON.stringify(body), + }); + const verify = async (token: string) => + answer(await app.request(`${ORIGIN}${BASE}/verify-email?token=${encodeURIComponent(token)}`, { headers: { origin: ORIGIN } })); + const linkTo = async (bearer: string, newEmail: string): Promise => { + const sent = () => mail.filter((m) => m.template === 'auth.verify_email' && m.to?.address === newEmail); + const before = sent().length; + const res = await fire('/change-email', { newEmail, callbackURL: '/' }, { authorization: `Bearer ${bearer}` }); + expect(res.status, `change-email: ${await res.clone().text()}`).toBe(200); + await vi.waitFor(() => expect(sent().length).toBe(before + 1)); + return String(sent()[before].data.token); + }; + + // Without a data engine no sign-up door admits an account (no posture can + // prove a first run or resolve a grant there): the account is created the + // operator's way, by the administrator's create-user called in-process. + const api: any = await manager.getApi(); + await api.createUser({ body: { email: EMAIL, name: EMAIL, password: FIRST } }); + const auth: any = await manager.getAuthContext(); + const internal = auth.internalAdapter; + const userId = String((await internal.findUserByEmail(EMAIL))?.user?.id); + await auth.adapter.update({ model: 'user', where: [{ field: 'id', value: userId }], update: { phoneNumber: PHONE, phoneNumberVerified: true } }); + + const signedIn = await fire('/sign-in/email', { email: EMAIL, password: FIRST }); + expect(signedIn.status, await signedIn.clone().text()).toBe(200); + expect(handsOutSession(signedIn), 'the email door hands out a session').toBe(true); + const bearer = String(signedIn.headers.get('set-auth-token')); + const addressNow = async () => ((await internal.findUserByEmail(NEW_ADDRESS)) ? NEW_ADDRESS : 'unchanged'); + const neverIssued = await verify('a-token-never-issued'); + + // Never changed: the link verifies. + expect(await verify(await linkTo(bearer, 'prior-access-first-move@example.com'))).toMatchObject({ status: 200 }); + + // Minted before a change: it answers what a link never issued answers. + const before = await linkTo(bearer, NEW_ADDRESS); + advanceTheClock(); + const changed = await fire('/change-password', { currentPassword: FIRST, newPassword: SECOND }, { authorization: `Bearer ${bearer}` }); + expect(changed.status, await changed.clone().text()).toBe(200); + expect(await verify(before)).toEqual(neverIssued); + expect(await addressNow()).toBe('unchanged'); + + // The phone door's first reading names its account through the vendor's adapter too. + const byPhone = await fire('/sign-in/phone-number', { phoneNumber: PHONE, password: SECOND }); + expect(byPhone.status, await byPhone.clone().text()).toBe(200); + expect(handsOutSession(byPhone), 'the phone door hands out a session').toBe(true); + }, 60_000); +}); + +describe('the predicate and its clock', () => { + it('nothing is before a change that never happened; an unreadable issue time is before one that did', () => { + expect(issuedBeforeCredentialChange(1_000, undefined)).toBe(false); + expect(issuedBeforeCredentialChange(999, 1_000)).toBe(true); + expect(issuedBeforeCredentialChange(1_000, 1_000)).toBe(false); + expect(issuedBeforeCredentialChange(Number.NaN, 1_000)).toBe(true); + }); + + it('the clock is the last write over the credential row; its creation and no row are no change', async () => { + const reader = (account: unknown) => ({ findCredentialAccount: async () => account }) as never; + const created = '2026-01-01T00:00:00.000Z'; + expect(await readCredentialChangedAt(reader(null), 'u')).toBeUndefined(); + expect(await readCredentialChangedAt(reader({ createdAt: created, updatedAt: created }), 'u')).toBeUndefined(); + expect(await readCredentialChangedAt(reader({ createdAt: created, updatedAt: '2026-01-01T00:00:00.900Z' }), 'u')).toBeUndefined(); + expect(await readCredentialChangedAt(reader({ createdAt: created, updatedAt: '2026-02-01T00:00:00.000Z' }), 'u')).toBe( + Date.parse('2026-02-01T00:00:00.000Z'), + ); + // The adapter answers `Date` values. + expect(await readCredentialChangedAt(reader({ createdAt: new Date(created), updatedAt: new Date('2026-02-01T00:00:00.000Z') }), 'u')).toBe( + Date.parse('2026-02-01T00:00:00.000Z'), + ); + await expect( + readCredentialChangedAt({ findCredentialAccount: async () => { throw new Error('down'); } } as never, 'u'), + ).rejects.toThrow('down'); + }); +}); diff --git a/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts new file mode 100644 index 00000000000..7e638e09268 --- /dev/null +++ b/packages/plugins/plugin-auth/src/credential-change-ends-prior-access.ts @@ -0,0 +1,307 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A credential change ends access issued before it. + * + * ## The rule + * + * Once an account's password changes, the following, issued for that account + * before the change, no longer grant access after it — this list is the whole + * of what the rule covers: + * + * - an email-change link — the token `POST /change-email` mails (better-auth + * 1.7.12, `routes/update-user.mjs`), any token carrying `updateTo` — minted + * before the change answers at `GET /verify-email` exactly what a token + * that was never issued answers; + * - a second-factor challenge a password sign-in opened before the change is + * ended at its verify door, which then answers what a challenge that does + * not exist answers; + * - a door that ends the account's sessions when it sets the password ends + * them again once the password is written: both reset doors, the user's + * own `/change-password` asked to end the other sessions (the session it + * installs is kept), and the one-step invitation door + * (`invitation-mailbox-proof.ts`, ahead of the session it opens); + * - a password sign-in is refused when the account's password changed while + * it ran: the session it opened is ended and it answers what a wrong + * password answers at that door. + * + * Access issued after the change is untouched. + * + * ## The one predicate, and the clock it reads + * + * {@link issuedBeforeCredentialChange} is the only comparison: something + * issued strictly before the account's credential change is refused. The + * change's moment is {@link readCredentialChangedAt}: the last time the + * account's local credential row (`sys_account`, provider `credential`) was + * written over, its `updated_at`. It is read through better-auth's internal + * adapter (`findCredentialAccount`), the same row and the same seam the + * vendor reads to check a password, so the clock needs no data engine: a + * manager on the vendor's in-memory adapter reads it as well. Every door that + * replaces a password writes that row — both reset doors, `/change-password`, + * an administrator's `/admin/set-user-password`, the one-step invitation door + * — whether or not it also stamps `sys_user.password_changed_at`. The row's + * creation is the account's first password, not a change: a row written over + * within {@link FIRST_CREDENTIAL_WINDOW_MS} of its creation reads as never + * written over, and an account with no local credential has never changed + * one. In either case nothing is refused. + * + * A token's issue time is the `iat` the vendor signs into it, whole seconds: + * a token minted in the same second as the change, after it, is refused too. + * Its owner asks for a new one. + * + * Each check fails closed: a clock or a record that cannot be read refuses + * what it was asked to admit. + * + * ## Where it is wired + * + * - `/verify-email`, the second-factor verify doors, and the password + * sign-in doors' first reading: the global before-hook + * (`auth-manager-before-hook.ts`). + * - The sessions a reset door or `/change-password` ends again, and the + * sign-in's second reading: the global after-hook + * (`auth-manager-after-hook.ts`), which runs ahead of every plugin's own + * after-hook, so a refused sign-in opens no second-factor challenge. + * - The one-step invitation door: in the door, before the session it opens. + * + * Each session ended here is ended through better-auth's internal adapter, so + * every session-delete hook runs, and a reset door's records the reason a + * reset records (`session-tombstone.ts`). + */ + +/** The path of better-auth's email verification door. */ +export const VERIFY_EMAIL_PATH = '/verify-email'; + +/** better-auth's second-factor verify doors (1.7.12 `plugins/two-factor`). */ +export const TWO_FACTOR_VERIFY_PATHS: ReadonlySet = new Set([ + '/two-factor/verify-totp', + '/two-factor/verify-otp', + '/two-factor/verify-backup-code', +]); + +/** The name better-auth gives the second-factor challenge cookie. */ +const TWO_FACTOR_COOKIE = 'two_factor'; + +/** The prefix of a challenge's attempt counter row, after which comes the challenge's identifier. */ +const TWO_FACTOR_ATTEMPTS_PREFIX = '2fa-attempts-'; + +/** + * The token the verify door is handed in place of an ended one: a value no + * signer issued, so the vendor answers it as it answers any token it cannot + * verify, through its own path. + */ +export const ENDED_EMAIL_CHANGE_TOKEN = 'ended-by-a-credential-change'; + +/** The context keys the before-hook leaves for the after-hook. */ +const SIGN_IN_READING = '__osSignInCredentialReading'; + +/** The context key under which the before-hook leaves the account a reset door sets the password of. */ +export const RESET_DOOR_SUBJECT = '__osResetDoorUserId'; + +/** better-auth's two reset doors (`resetCredentialPassword`), which end the sessions before the write. */ +export const RESET_DOOR_PATHS: ReadonlySet = new Set(['/reset-password', '/phone-number/reset-password']); + +/** + * The one comparison: `issuedAtMs` falls before the account's credential + * change. Nothing is before a change that never happened; an issue time that + * cannot be read is treated as before one that did. + */ +export function issuedBeforeCredentialChange(issuedAtMs: number, changedAtMs: number | undefined): boolean { + if (changedAtMs === undefined) return false; + if (!Number.isFinite(issuedAtMs)) return true; + return issuedAtMs < changedAtMs; +} + +function toMs(value: unknown): number | undefined { + if (value === null || value === undefined || value === '') return undefined; + const ms = value instanceof Date ? value.getTime() : new Date(value as string | number).getTime(); + return Number.isFinite(ms) ? ms : undefined; +} + +/** + * The seam the clock reads through: better-auth's internal adapter, whose + * `findCredentialAccount` answers the account's local credential row (provider + * `credential`, `accountId` the user's id) with its `createdAt` / `updatedAt`. + */ +export interface CredentialClockReader { + findCredentialAccount(userId: string): Promise<{ createdAt?: unknown; updatedAt?: unknown } | null | undefined>; +} + +/** + * How long after its creation a credential row's own write still counts as + * its creation: the row is written with a creation and an update stamp taken + * separately, and the first password is not a change. + */ +export const FIRST_CREDENTIAL_WINDOW_MS = 1_000; + +/** + * The moment of the account's last credential change, in epoch ms, or + * `undefined` when it has never had one. Throws when the record cannot be + * read, so a caller refuses. + */ +export async function readCredentialChangedAt(reader: CredentialClockReader, userId: string): Promise { + const account = await reader.findCredentialAccount(userId); + const created = toMs(account?.createdAt); + const updated = toMs(account?.updatedAt); + if (updated === undefined) return undefined; + if (created !== undefined && updated - created <= FIRST_CREDENTIAL_WINDOW_MS) return undefined; + return updated; +} + +/** + * Whether `issuedAt` falls before `userId`'s credential change, read through + * the request's own internal adapter; a clock that cannot be read answers yes. + */ +async function issuedBeforeChangeOf(ctx: any, userId: string, issuedAtMs: number): Promise { + const reader: CredentialClockReader | undefined = ctx?.context?.internalAdapter; + if (typeof reader?.findCredentialAccount !== 'function') return true; + try { + return issuedBeforeCredentialChange(issuedAtMs, await readCredentialChangedAt(reader, userId)); + } catch { + return true; + } +} + +/** + * `GET /verify-email`: an email-change token issued before the account's + * credential change is replaced by {@link ENDED_EMAIL_CHANGE_TOKEN}, so the + * door answers it what it answers a token never issued, its callback check + * included. Answers the before-hook context that does so, or `undefined` to + * leave the request as it came. A token that does not decode, or carries no + * `updateTo`, is the vendor's to judge. + */ +export async function endEmailChangeTokenIssuedBeforeCredentialChange( + ctx: any, +): Promise<{ context: { query: Record } } | undefined> { + if (ctx?.path !== VERIFY_EMAIL_PATH) return undefined; + const token: unknown = ctx?.query?.token; + if (typeof token !== 'string' || token.length === 0) return undefined; + let claims: Record; + try { + const { decodeJwt } = await import('jose'); + claims = decodeJwt(token) as Record; + } catch { + return undefined; + } + if (typeof claims.updateTo !== 'string' || typeof claims.email !== 'string') return undefined; + const ended = { context: { query: { ...(ctx.query ?? {}), token: ENDED_EMAIL_CHANGE_TOKEN } } }; + let userId: string | undefined; + try { + const found = await ctx.context.internalAdapter.findUserByEmail(claims.email.toLowerCase()); + const id: unknown = found?.user?.id; + userId = typeof id === 'string' && id.length > 0 ? id : undefined; + } catch { + return ended; + } + // No account at the address: the vendor's own refusal answers it. + if (!userId) return undefined; + const issuedAtMs = typeof claims.iat === 'number' ? claims.iat * 1000 : Number.NaN; + return (await issuedBeforeChangeOf(ctx, userId, issuedAtMs)) ? ended : undefined; +} + +/** + * A second-factor verify door: the challenge the request's cookie names is + * ended — its row and its attempt counter deleted — when it was opened before + * the account's credential change, so the vendor's own check finds no + * challenge. Throws when the challenge cannot be ended. + */ +export async function endTwoFactorChallengeIssuedBeforeCredentialChange(ctx: any): Promise { + if (!TWO_FACTOR_VERIFY_PATHS.has(ctx?.path)) return; + const cookie = ctx?.context?.createAuthCookie?.(TWO_FACTOR_COOKIE); + if (!cookie?.name || typeof ctx?.getSignedCookie !== 'function') return; + const identifier: unknown = await ctx.getSignedCookie(cookie.name, ctx.context.secret); + if (typeof identifier !== 'string' || identifier.length === 0) return; + const internal = ctx.context.internalAdapter; + const challenge = await internal.findVerificationValue(identifier); + if (!challenge) return; + const userId = typeof challenge.value === 'string' ? challenge.value : ''; + const issuedAtMs = toMs(challenge.createdAt) ?? Number.NaN; + if (userId && !(await issuedBeforeChangeOf(ctx, userId, issuedAtMs))) return; + await internal.deleteVerificationByIdentifier(identifier); + await internal.deleteVerificationByIdentifier(`${TWO_FACTOR_ATTEMPTS_PREFIX}${identifier}`); +} + +/** The local credential an account holds now, as better-auth reads it to check a password. */ +async function readCredential(ctx: any, userId: string): Promise { + const account = await ctx.context.internalAdapter.findCredentialAccount(userId); + const password: unknown = account?.password; + return typeof password === 'string' && password.length > 0 ? password : undefined; +} + +/** + * A password sign-in's first reading, before the vendor checks the password: + * the account the request names and the credential it holds now, left on the + * request for {@link refuseSignInAcrossCredentialChange}. `findAccountId` + * answers the account the door's identifier names. A reading that cannot be + * taken leaves none, which the second reading refuses. + */ +export async function noteSignInCredential( + ctx: any, + findAccountId: () => Promise, +): Promise { + if (!ctx?.context) return; + delete ctx.context[SIGN_IN_READING]; + try { + const userId = await findAccountId(); + if (!userId) return; + ctx.context[SIGN_IN_READING] = { userId, credential: await readCredential(ctx, userId) }; + } catch { + // No reading: a sign-in it would have judged is refused after the fact. + } +} + +/** + * A password sign-in's second reading, after the vendor opened its session: + * when the account's credential is not the one the first reading saw (or + * either reading is missing), the session is ended, the response carries no + * session, and the refusal `refusal` builds is answered. Answers that refusal + * for the caller to throw, or `undefined` when the sign-in stands. Inert for + * a request that opened no session. + */ +export async function refuseSignInAcrossCredentialChange( + ctx: any, + refusal: () => Promise, +): Promise { + const opened = ctx?.context?.newSession; + const reading = ctx?.context?.[SIGN_IN_READING] as { userId: string; credential?: string } | undefined; + if (ctx?.context) delete ctx.context[SIGN_IN_READING]; + const userId: unknown = opened?.user?.id; + const token: unknown = opened?.session?.token; + if (typeof userId !== 'string' || typeof token !== 'string') return undefined; + let stands = false; + if (reading && reading.userId === userId && reading.credential !== undefined) { + try { + stands = (await readCredential(ctx, userId)) === reading.credential; + } catch { + stands = false; + } + } + if (stands) return undefined; + await ctx.context.internalAdapter.deleteSession(token); + ctx.context.setNewSession?.(null); + const { deleteSessionCookie } = await import('better-auth/cookies'); + deleteSessionCookie(ctx, true); + return refusal(); +} + +/** + * End every session `userId` holds, except the one whose token is `keep`, + * through better-auth's internal adapter (so every session-delete hook runs, + * and the door's path decides what the ended row records). + */ +export async function endSessionsAfterCredentialWrite( + internal: { + listSessions(userId: string): Promise>; + deleteSession(token: string): Promise; + deleteUserSessions(userId: string): Promise; + }, + userId: string, + keep?: string, +): Promise { + if (!keep) { + await internal.deleteUserSessions(userId); + return; + } + for (const session of await internal.listSessions(userId)) { + if (typeof session?.token === 'string' && session.token !== keep) await internal.deleteSession(session.token); + } +} diff --git a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts index 0c669336e80..0c8743b1291 100644 --- a/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts +++ b/packages/plugins/plugin-auth/src/invitation-mailbox-proof.ts @@ -117,6 +117,7 @@ */ import { isCloudManaged } from '@objectstack/core'; +import { endSessionsAfterCredentialWrite } from './credential-change-ends-prior-access.js'; import { isMissingTableError } from '@objectstack/types'; import { CLOUD_MANAGED_REFUSAL_CODE, CLOUD_MANAGED_REFUSAL_MESSAGES } from './cloud-managed.js'; import { incrementFixedWindow, InProcessCounterStore, type CounterStore } from './rate-limit-storage.js'; @@ -746,6 +747,10 @@ export async function buildInvitationProofDoorPlugin(host: InvitationProofDoorHo } // ADR-0069 D1: the password-age stamp and the forced-change clear. await host.stampPasswordChangedAt(String(user.id)); + // A credential change ends access issued before it: the account's + // sessions are ended again now that the password is written, ahead of + // the one this door opens (`credential-change-ends-prior-access.ts`). + if (existing) await endSessionsAfterCredentialWrite(internal, String(user.id)); const session = await internal.createSession(user.id, false); if (!session) throw new APIError('INTERNAL_SERVER_ERROR', { code: 'INTERNAL_ERROR', message: 'Failed to create a session.' }); diff --git a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts index 7331e6ab8e8..3c73e83313b 100644 --- a/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-one-step-acceptance-34257.test.ts @@ -1236,6 +1236,33 @@ describe('#34257 — a password the door sets starts the password-age clock and }); }); +describe('a credential change ends access issued before it — the one-step door', () => { + quietConsole(); + + it('a session opened before the door writes the password is ended, and the session the door opens stands', async () => { + const { engine, manager, invite } = await boot(); + const { invitation, proof } = await invite('raced@example.com'); + await signUp(manager, engine, 'raced@example.com'); + const internal = (await manager.getAuthContext()).internalAdapter; + const original = internal.updatePassword.bind(internal); + let opened: string | undefined; + vi.spyOn(internal, 'updatePassword').mockImplementation(async (...args: unknown[]) => { + if (opened === undefined) { + const res = await post(manager, '/sign-in/email', { email: 'raced@example.com', password: PASSWORD }); + opened = res.status === 200 ? cookieFrom(res) : ''; + } + return (original as (...a: unknown[]) => Promise)(...args); + }); + + const res = await door(manager, { invitationId: invitation.id, proof, name: 'R', password: NEW_PASSWORD }); + await expectAccepted(res); + + expect(opened, 'a sign-in ran before the password write').toBeTruthy(); + expect(await sessionUser(manager, opened!)).toBeNull(); + expect(await sessionUser(manager, cookieFrom(res))).toMatchObject({ email: 'raced@example.com' }); + }); +}); + // #35107 — a host that calls the organization plugin's `sendInvitationEmail` // from its own code (no better-auth endpoint around the call) gets the same // mail: the proof is minted through the manager's own auth context.