Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/password-reset-revocation-trail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@objectstack/plugin-auth': patch
'@objectstack/platform-objects': patch
---

fix(plugin-auth): a session a password reset ends leaves a revocation trail

Clause-②: no
Metadata-protocol: none

- **A session a password reset ends leaves a revocation trail.** When a completed self-service password reset ends the account's sessions — the emailed link (`POST /api/v1/auth/reset-password`), and the phone OTP reset (`POST /api/v1/auth/phone-number/reset-password`); better-auth's email-OTP reset door, which the platform does not mount, is covered on its own path too — each `sys_session` row is now kept and stamped, `revoked_at` with `revoke_reason: password_reset`, the same kind of trail an interactive revoke leaves, instead of being deleted. The session is still refused (`401`).
- **The value says who ended the session.** `password_reset` is distinct from `user_revoked` (the owner revoking their own sessions) and from `admin_password_reset`, which an administrator's forced reset keeps writing.
- **`sys_session.revoke_reason`'s published vocabulary names `password_reset`** (`@objectstack/platform-objects`, the field's description and its translated help).
- **Unchanged.** Which sessions a reset ends; sign-out, which still deletes its row; the account's API keys, which a self-service reset does not revoke; and the audit log, which records no `logout` row for a reset.
2 changes: 1 addition & 1 deletion docs/HARDENING.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ ObjectStack uses [better-auth](https://www.better-auth.com/) via
| Session TTL | 7 days | `session.expiresIn` (seconds) |
| Access token TTL | inherited from session | configure in better-auth |
| Refresh | better-auth `/auth/get-session` rolls TTL | `session.updateAge` (seconds) |
| Revocation | DELETE on `session` row; a completed password reset ends every session of the account | — always on (`revokeSessionsOnPasswordReset: false` is refused at boot) |
| Revocation | Sign-out deletes the `session` row. A revoke, and a completed password reset (which ends every session of the account), keep the row stamped `revoked_at` / `revoke_reason` (`password_reset` for the reset) and refuse it | — always on (`revokeSessionsOnPasswordReset: false` is refused at boot) |
| Idle / absolute / concurrent caps | Off (opt-in) | `session_idle_timeout_minutes` / `session_absolute_max_hours` / `max_concurrent_sessions_per_user` (Setup → Authentication) |
| Email verify TTL | 1 hour | `emailVerification.expiresIn` |

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ export const enObjects: NonNullable<TranslationData['objects']> = {
},
revoke_reason: {
label: "Revoke Reason",
help: "Why the session was revoked (idle_timeout, absolute_max, concurrent_cap, user_revoked, admin, organization_membership_ended, admin_password_reset, …)."
help: "Why the session was revoked (idle_timeout, absolute_max, concurrent_cap, user_revoked, admin, organization_membership_ended, admin_password_reset, password_reset, …)."
},
active_organization_id: {
label: "Active Organization"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ export const esESObjects: NonNullable<TranslationData['objects']> = {
},
revoke_reason: {
label: "Motivo de la revocación",
help: "Por qué se revocó la sesión (idle_timeout, absolute_max, concurrent_cap, user_revoked, admin, organization_membership_ended, admin_password_reset, …)."
help: "Por qué se revocó la sesión (idle_timeout, absolute_max, concurrent_cap, user_revoked, admin, organization_membership_ended, admin_password_reset, password_reset, …)."
},
active_organization_id: {
label: "Organización activa"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ export const jaJPObjects: NonNullable<TranslationData['objects']> = {
},
revoke_reason: {
label: "失効理由",
help: "セッションが失効した理由(idle_timeout、absolute_max、concurrent_cap、user_revoked、admin、organization_membership_ended、admin_password_reset など)。"
help: "セッションが失効した理由(idle_timeout、absolute_max、concurrent_cap、user_revoked、admin、organization_membership_ended、admin_password_reset、password_reset など)。"
},
active_organization_id: {
label: "アクティブ組織"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ export const zhCNObjects: NonNullable<TranslationData['objects']> = {
},
revoke_reason: {
label: "撤销原因",
help: "会话被撤销的原因(idle_timeout、absolute_max、concurrent_cap、user_revoked、admin、organization_membership_ended、admin_password_reset 等)。"
help: "会话被撤销的原因(idle_timeout、absolute_max、concurrent_cap、user_revoked、admin、organization_membership_ended、admin_password_reset、password_reset 等)。"
},
active_organization_id: {
label: "当前组织"
Expand Down
5 changes: 4 additions & 1 deletion packages/platform-objects/src/identity/sys-session.object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,9 +240,12 @@ export const SysSession = ObjectSchema.create({
// `admin_password_reset` is the second authorization-event cause: an
// administrator's forced password reset revoked the session
// (`plugin-auth/forced-reset-revocation.ts`, `FORCED_RESET_REVOKE_REASON`).
// `password_reset` is its self-service counterpart: a completed password
// reset ended the session (the reset doors in `INTERACTIVE_REVOKE_REASON`,
// `plugin-auth/session-tombstone.ts`).
description:
'Why the session was revoked (idle_timeout, absolute_max, concurrent_cap, user_revoked, '
+ 'admin, organization_membership_ended, admin_password_reset, …).',
+ 'admin, organization_membership_ended, admin_password_reset, password_reset, …).',
}),

// ── Active context (multi-org/team) ──────────────────────────
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest';
import { SysApiKey, SysSession } from '@objectstack/platform-objects/identity';
import { FORCED_RESET_REVOKE_REASON } from './forced-reset-revocation';
import { INTERACTIVE_REVOKE_REASON } from './session-tombstone';
import { managedExtensionEditableFields, managedExtensionFields } from './managed-extension-fields';

// `sys_session.revoke_reason` is free text; its description is the only
Expand All @@ -11,6 +12,15 @@ describe('sys_session.revoke_reason vocabulary', () => {
const description = String((SysSession.fields as any).revoke_reason.description);
expect(description).toContain(FORCED_RESET_REVOKE_REASON);
});

it('names every value the interactive-revoke ledger writes, the password-reset doors\' included', () => {
const description = String((SysSession.fields as any).revoke_reason.description);
const written = [...new Set(Object.values(INTERACTIVE_REVOKE_REASON))].sort();
expect(written).toEqual(['admin', 'password_reset', 'user_revoked']);
for (const value of written) {
expect({ value, named: new RegExp(`\\b${value}\\b`).test(description) }).toEqual({ value, named: true });
}
});
});

// `sys_api_key.revoked_reason` is a closed select: the forced reset is its one
Expand Down
118 changes: 117 additions & 1 deletion packages/plugins/plugin-auth/src/password-reset-ends-sessions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,19 @@
* sessions on every reset door;
* - an explicit `revokeSessionsOnPasswordReset: false` is refused at
* construction and on a configuration patch, where the standing
* configuration keeps ruling; `true` is accepted.
* configuration keeps ruling; `true` is accepted;
* - a session a password reset ends leaves a revocation trail: on each reset
* door every session the account held is still a `sys_session` row
* afterwards, stamped `revoked_at` and `revoke_reason: password_reset`, and
* it still answers 401; the control, an administrator's forced reset over
* the same engine, stamps `admin_password_reset` instead.
*/

import { describe, it, expect, afterAll, afterEach, vi } from 'vitest';
import { ObjectQL } from '@objectstack/objectql';
import { SqlDriver } from '@objectstack/driver-sql';
import { AuthManager } from './auth-manager.js';
import { runAdminSetUserPassword, type AdminUserEndpointDeps } from './admin-user-endpoints.js';
import { authIdentityObjects } from './manifest.js';
import { assertPasswordResetEndsSessions } from './password-reset-ends-sessions.js';
import { memoizeScrypt } from './__tests__/scrypt-memo.testkit';
Expand Down Expand Up @@ -209,6 +215,116 @@ describe("a completed phone OTP reset ends the account's other sessions", () =>
}, 60_000);
});

describe('a session a password reset ends leaves a revocation trail', () => {
type SessionRow = { id: string; expires_at?: unknown; revoked_at?: unknown; revoke_reason?: unknown };

/** The account's `sys_session` rows, read off the table the way an auditor reads them. */
async function sessionRowsOf(engine: ObjectQL): Promise<SessionRow[]> {
const [user] = (await engine.find('sys_user', { where: { email: EMAIL }, limit: 1 }, SYS)) as Array<{ id: string }>;
return (await engine.find('sys_session', { where: { user_id: user.id } }, SYS)) as SessionRow[];
}

/** The sessions the account holds before the reset: at least one, none of them ended. */
async function liveSessionsBefore(a: Account): Promise<SessionRow[]> {
const before = await sessionRowsOf(a.engine);
expect(before.length).toBeGreaterThan(0);
expect(before.map((row) => row.revoked_at ?? null)).toEqual(before.map(() => null));
return before;
}

/**
* Every session in `before` is still a row, stamped with when and why it
* ended, and the session signed in before the reset is refused.
*/
async function expectTrail(a: Account, before: SessionRow[], reason: string, startedAt: number): Promise<void> {
const after = new Map((await sessionRowsOf(a.engine)).map((row) => [row.id, row]));
for (const { id } of before) {
const row = after.get(id);
expect({ id, kept: row !== undefined }).toEqual({ id, kept: true });
expect(row!.revoke_reason).toBe(reason);
const revokedAt = new Date(row!.revoked_at as string).getTime();
expect(Number.isFinite(revokedAt)).toBe(true);
// Whole-second storage may round the stamp down, never ahead of now.
expect(revokedAt).toBeGreaterThanOrEqual(startedAt - 1000);
expect(revokedAt).toBeLessThanOrEqual(Date.now());
expect(new Date(row!.expires_at as string).getTime()).toBeLessThan(Date.now());
}
expect(await answer(await getSession(a.manager, a.earlier))).toEqual({ status: 401, code: 'UNAUTHENTICATED' });
}

it('the emailed-link reset (/reset-password) stamps every earlier session password_reset, and the session still answers 401', async () => {
const a = await signedInAccount();
const token = await requestResetToken(a);
const before = await liveSessionsBefore(a);
const startedAt = Date.now();

const reset = await post(a.manager, '/reset-password', { token, newPassword: SECOND });
expect(reset.status, await reset.clone().text()).toBe(200);

await expectTrail(a, before, 'password_reset', startedAt);
}, 60_000);

it('the phone OTP reset (/phone-number/reset-password) stamps every earlier session password_reset, and the session still answers 401', async () => {
const PHONE = '+15550143';
const a = await signedInAccount({ plugins: { phoneNumber: true } });
const texts: Array<{ to: string; templateParams?: { code?: string } }> = [];
a.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 [user] = (await a.engine.find('sys_user', { where: { email: EMAIL }, limit: 1 }, SYS)) as Array<{ id: string }>;
await a.engine.update('sys_user', { id: user.id, phone_number: PHONE, phone_number_verified: true }, SYS);
const requested = await post(a.manager, '/phone-number/request-password-reset', { phoneNumber: PHONE });
expect(requested.status, await requested.clone().text()).toBe(200);
await vi.waitFor(() => expect(texts.map((t) => t.to)).toEqual([PHONE]));
const otp = String(texts[0].templateParams?.code ?? '');
expect(otp, 'the reset text carries its code').not.toBe('');
const before = await liveSessionsBefore(a);
const startedAt = Date.now();

const reset = await post(a.manager, '/phone-number/reset-password', { phoneNumber: PHONE, otp, newPassword: SECOND });
expect(reset.status, await reset.clone().text()).toBe(200);

await expectTrail(a, before, 'password_reset', startedAt);
}, 60_000);

it("the control: an administrator's forced reset still stamps admin_password_reset, so the value says who ended the session", async () => {
const a = await signedInAccount();
const before = await liveSessionsBefore(a);
const [user] = (await a.engine.find('sys_user', { where: { email: EMAIL }, limit: 1 }, SYS)) as Array<{ id: string }>;
const m = a.manager;
const quiet = { warn() {}, info() {}, error() {}, debug() {} };
// The deps `auth-plugin.ts` hands the forced-reset door, built from the same manager.
const deps = {
getAuthApi: () => m.getApi(),
getAuthContext: () => m.getAuthContext(),
getDataEngine: () => m.getDataEngine(),
assertPasswordComplexity: (pw: string) => m.checkPasswordComplexity(pw),
noteMustChangePasswordIssued: () => m.noteMustChangePasswordIssued(),
phoneNumberEnabled: () => m.isPhoneNumberEnabled(),
getMembershipPolicy: () => m.getMembershipPolicy(),
logger: quiet,
} as unknown as AdminUserEndpointDeps;
const startedAt = Date.now();

const forced = await runAdminSetUserPassword(
deps,
new Request(`${AUTH}/admin/set-user-password`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', origin: BASE },
body: JSON.stringify({ userId: user.id, newPassword: SECOND }),
}),
{ id: 'admin-control', email: 'admin-control@example.com' },
);
expect(forced.status, JSON.stringify(forced.body)).toBe(200);

await expectTrail(a, before, 'admin_password_reset', startedAt);
}, 60_000);
});

describe('revokeSessionsOnPasswordReset: false is refused, never silently overridden', () => {
it('is refused at construction', () => {
expect(
Expand Down
20 changes: 13 additions & 7 deletions packages/plugins/plugin-auth/src/password-reset-ends-sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,19 @@
* (`auth-manager-auth-instance.ts`), and every door that sets a password from a
* reset token or code inherits the rule without a door of its own.
*
* What an ended session leaves behind is not what the forced reset leaves. The
* reset paths are in neither the interactive-revoke ledger nor the erasure
* paths (`session-tombstone.ts`), so the session rows are deleted, not
* stamped: no `revoked_at` / `revoke_reason` trail is written. No `logout`
* audit row is written either — `logoutEventFor` (`auth-session-audit.ts`)
* records a `/sign-out` alone. And the account's API keys are untouched; the
* forced reset's key revocation is its own switch.
* A session a password reset ends leaves a revocation trail. Every reset door
* — the two above, and the email-OTP door, unmounted, on its own path — is in
* the interactive-revoke ledger (`session-tombstone.ts`,
* `INTERACTIVE_REVOKE_REASON`) with the value `password_reset`, and is not an
* erasure path. better-auth's bulk delete reaches the adapter's per-row
* reconcile, so each session row is stamped in place rather than deleted —
* `expires_at` a second in the past, `revoked_at`, `revoke_reason:
* password_reset` — and is hidden from better-auth's session reads, so the
* session answers 401. The value is not the forced reset's
* `admin_password_reset`: the row says who ended the session. No `logout`
* audit row is written — `logoutEventFor` (`auth-session-audit.ts`) records a
* `/sign-out` alone. And the account's API keys are untouched; the forced
* reset's key revocation is its own switch.
*
* ## The declared key
*
Expand Down
Loading
Loading