diff --git a/.changeset/35184-dev-seed-retire-at-boot.md b/.changeset/35184-dev-seed-retire-at-boot.md new file mode 100644 index 00000000000..571e1b5aeaa --- /dev/null +++ b/.changeset/35184-dev-seed-retire-at-boot.md @@ -0,0 +1,19 @@ +--- +'@objectstack/plugin-auth': patch +--- + +fix(auth)!: a boot outside development mode retires what the development seed issued + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**BREAKING** for a deployment that serves a database `os dev` seeded. At every boot outside development mode (`NODE_ENV` is not `development`), before the server serves a request, the platform retires what each account the development seed created (its admin and the stack's `demoStaff`) was issued, while that account still has the password it was seeded with: its sessions, its API keys, the apps authorized to it and its device sign-ins, its outstanding password-reset links, any sign-in account linked to it, the OAuth applications it registered (disabled) and the SCIM credentials it minted (revoked). It is the revocation `os user set-password` performs, without setting a password, and with a host `secondaryStorage` it also ends the sessions held there. + +- FROM: a session, an API key or an authorized app the seed's admin or a demo account was issued under `os dev` kept working on a server outside development mode, until an operator ran `os user set-password` on that account. +- TO: the boot retires them. A retired session's next request is unauthenticated, a retired key is refused `403 API_KEY_REVOKED`, and both carry the reason `admin_password_reset`, so only a platform administrator restores such a key. The log names each account and what was retired. When the retirement cannot complete, the boot fails with an error naming the accounts. + +**Not moved.** A boot in development mode retires nothing. An account the seed did not create is never read. An account whose password was set since the seed (by `os user set-password`, by an administrator or by its own reset) holds a credential the seed did not issue and is untouched, and so is every credential it was issued after that. A database with no account the seed created costs one indexed read per boot. + +The fix: set each seeded account's password with `os user set-password ` before serving the database outside development mode (the refusals added in the previous release already require it to sign in), then sign in and issue new keys. diff --git a/.changeset/dev-seed-credential-production-refusal.md b/.changeset/dev-seed-credential-production-refusal.md index 40ea0b858f3..9dc02094718 100644 --- a/.changeset/dev-seed-credential-production-refusal.md +++ b/.changeset/dev-seed-credential-production-refusal.md @@ -24,4 +24,4 @@ Metadata-protocol: none **Not detected:** a database seeded before this release with a custom seed password carries no mark and no well-known password. Set a new password with `os user set-password` on each account it seeded before serving it outside development mode. -**Not ended at boot:** this release refuses the development seed password and every new session for a seeded account still on it. Sessions and API keys a seeded account was issued before the server left development mode are ended by `os user set-password`; run it on each seeded account before serving the database. Ending them at boot is follow-up #35184. +**Ended by `os user set-password`, and at boot:** this release refuses the development seed password and every new session for a seeded account still on it. Sessions and API keys a seeded account was issued before the server left development mode are ended by `os user set-password`; run it on each seeded account before serving the database. In the same release, a boot outside development mode also retires them: see the note "a boot outside development mode retires what the development seed issued" (#36311). diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index 1264c0a94d3..5c5e586661d 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -625,14 +625,27 @@ serve a database `os dev` wrote, set each seeded account's password on the server with [`os user set-password`](/docs/deployment/cli#os-user-set-password) first; the refusal names that command. -What this release refuses is the seed password and every new session for a -seeded account still on it. Sessions and API keys a seeded account was issued -before the server left development mode are ended by `os user set-password` -(with any sign-in account linked to it and any app authorized to it; the -OAuth applications it registered are disabled and the SCIM credentials it -minted are revoked), so -run it on each seeded account before serving the database; ending them at boot -is follow-up #35184. +Nothing the development seed issued keeps acting once the deployment leaves +development mode. At every boot outside development mode, before the server +serves a request, it retires what each seeded account still on its seed +password was issued: its sessions, its API keys, the apps authorized to it and +its device sign-ins, its outstanding password-reset links, any sign-in account +linked to it, the OAuth applications it registered (disabled) and the SCIM +credentials it minted (revoked). A retired session or key answers exactly as a +revoked one does, and the log names each account and what was retired. When +the host supplies a `secondaryStorage` that holds the sessions, the server ends +them there too, which `os user set-password` cannot reach. An +account whose password was set since the seed (by `os user set-password`, by +an administrator, or by its own reset) holds a credential the seed did not +issue and is untouched, as is every account the seed did not create. A boot in +development mode retires nothing. There is no switch. + +If the retirement cannot complete (the database refuses a read or a write), +the server does not start, and the error names the accounts; fix the database +access, or run `os user set-password` on each of them, and start it again. +`os user set-password` itself ends the same credentials when it sets the +password, so running it on each seeded account before serving the database +leaves nothing for the boot to retire. ### A seeded directory opens no bootstrap window diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md index 3633d0e5466..fa0c44ad759 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md @@ -14,26 +14,26 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 106 | +| Write call sites | 107 | | Object name statically decidable | 58 | -| Object name chosen at run time | 48 | +| Object name chosen at run time | 49 | | Object name spelled inline | 47 | | Object name spelled through a `const` | 11 | -| Object name is an `object: string` parameter | 3 | +| Object name is an `object: string` parameter | 4 | | Object name is some other run-time expression | 45 | | Against a tenancy-enabled object | 56 | | Against an object declaring tenancy off | 2 | -| Threading a tenant context | 62 | +| Threading a tenant context | 63 | | Provably carrying none (options read, no context key) | 15 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 29 | | …and decidably tenancy-enabled | 16 | -| Threading a decidably elevated (`isSystem`) context | 44 | +| Threading a decidably elevated (`isSystem`) context | 45 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 47 | | Receiver carried a readable engine type | 80 | | Receiver erased, placed by the object NAME | 24 | -| Receiver erased, placed by an `object: string` PARAMETER | 1 | +| Receiver erased, placed by an `object: string` PARAMETER | 2 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 1 | ## Subtractions the census could NOT defend — enforced @@ -74,6 +74,7 @@ a row or a number here — fix the code, or the census, and regenerate. | `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 | | `packages/plugins/plugin-auth/src/demo-staff.ts` | `insert` | `sys_user_position` | enabled | elevated | 1 | +| `packages/plugins/plugin-auth/src/dev-seed-credential-retirement.ts` | `delete` | `object` | undecidable | elevated | 1 | | `packages/plugins/plugin-auth/src/dev-seed-credential.ts` | `update` | `SystemObjectName.USER` | undecidable | elevated | 1 | | `packages/plugins/plugin-auth/src/ensure-default-organization.ts` | `insert` | `object` | undecidable | elevated | 1 | | `packages/plugins/plugin-auth/src/ensure-default-organization.ts` | `update` | `sys_member` | enabled | elevated | 1 | diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 37a71ed71b9..2bbc3138c73 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -128,6 +128,7 @@ import { resolveKernelCache } from './kernel-cache.js'; import { authIdentityManifest } from './manifest.js'; import { scheduleLegacySsoSecretMigration } from './sso-client-secret.js'; import { reportSsoProvidersWithNonBareDomainEntries } from './sso-stored-domain-entries.js'; +import { retireDevSeedCredentials, type DevSeedRetirementEngine } from './dev-seed-credential-retirement.js'; import { directSignInNetworkRefusal, isDirectSignInDoorNavigation, @@ -1795,6 +1796,23 @@ export class AuthPlugin implements Plugin { } }); + // Outside development mode: retire what the development seed issued to + // every stamped account still on its seed password, on `kernel:ready`, so + // it has settled before `kernel:listening` opens the socket. Registered + // independently of `registerRoutes`: a retired session or key must not act + // through any door. A retirement that does not complete THROWS and fails + // the boot (`dev-seed-credential-retirement.ts`). + ctx.hook('kernel:ready', async () => { + let ql: DevSeedRetirementEngine | undefined; + try { ql = ctx.getService('objectql'); } catch { ql = undefined; } + const authManager = this.authManager; + await retireDevSeedCredentials({ + engine: ql, + authContext: async () => (authManager ? await authManager.getAuthContext() : undefined), + logger: ctx.logger, + }); + }); + // Dev-only: provision a known, loginable platform admin on an empty DB. // Registered as its own kernel:ready hook (independent of registerRoutes) // so it runs whenever the runtime boots in development. diff --git a/packages/plugins/plugin-auth/src/dev-seed-credential-retirement.test.ts b/packages/plugins/plugin-auth/src/dev-seed-credential-retirement.test.ts new file mode 100644 index 00000000000..56bb203dc15 --- /dev/null +++ b/packages/plugins/plugin-auth/src/dev-seed-credential-retirement.test.ts @@ -0,0 +1,372 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Leaving development mode retires what the development seed issued — pinned + * across two real boots over one database. + * + * ## The composition + * + * A real `ObjectKernel`, a real ObjectQL engine on a SQLite FILE, the real + * `AuthPlugin` (the development admin seed, one `demoStaff` account and the + * admin plugin) and the real `SecurityPlugin`. The first boot runs with + * `NODE_ENV=development`, as `os dev` boots: it seeds, and the seed's admin, a + * demo account and an account an administrator creates (no seed stamp) are + * each issued a session, an API key and a password-reset link. The server + * stops, and boots again over the same file, as `os start` serves the database + * `os dev` wrote. + * + * ## What each case reads + * + * What each credential answers on the second boot: the session through + * `/get-session` (a retired one resolves no user, as a revoked one does), the + * key through the key-admission seam (`API_KEY_REVOKED`, as a revoked one + * does), and the reset links left in `sys_verification`. + */ + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { ObjectKernel, hashApiKey, resolveApiKeyAdmission, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SecurityPlugin } from '@objectstack/plugin-security'; +import { AuthPlugin } from './auth-plugin.js'; +import type { AuthManager } from './auth-manager.js'; +import { DEV_SEED_CREDENTIAL_FIELD } from './dev-seed-credential.js'; +import { retireDevSeedCredentials } from './dev-seed-credential-retirement.js'; +import { setOperatorPassword } from './operator-password-reset.js'; +// Vendor modules paid at module load, never inside a clocked case. +import 'better-auth'; +import 'better-auth/api'; +import 'better-auth/crypto'; +import 'better-auth/plugins'; +import 'better-auth/plugins/bearer'; +import 'better-auth/plugins/custom-session'; +import 'better-auth/plugins/organization'; +import 'better-auth/plugins/admin'; +import '@better-auth/core/context'; +import '@better-auth/core/error'; +import '@objectstack/core/egress'; + +const SYS = { isSystem: true } as const; +const ORIGIN = 'http://localhost:3000'; +const AUTH = `${ORIGIN}/api/v1/auth`; +const SECRET = 'test-secret-at-least-32-chars-long-devseed'; +const SEED_EMAIL = 'admin@objectos.ai'; +const SEED_PASSWORD = 'admin123'; +const STAFF_EMAIL = 'staff1@demo.example'; +const CONTROL_EMAIL = 'colleague@company.example'; +const CONTROL_PASSWORD = 'Admin-Chosen-Pass-29'; +const OPERATOR_PASSWORD = 'Operator!Chosen-Passw0rd-7'; +const PRODUCTION = 'production'; + +const ENV_KEYS = [ + 'NODE_ENV', + 'OS_SEED_ADMIN', + 'OS_SEED_ADMIN_EMAIL', + 'OS_SEED_ADMIN_PASSWORD', + 'OS_SEED_ADMIN_NAME', + 'OS_MIGRATE_AND_EXIT', + 'OS_TENANCY_POSTURE', + 'OS_MULTI_ORG_ENABLED', + 'OS_PLATFORM_OWNER_EMAIL', +] as const; + +type Who = 'admin' | 'staff' | 'control'; +type SecondaryStorage = { + get(key: string): Promise; + set(key: string, value: string, ttl?: number): Promise; + delete(key: string): Promise; +}; + +const savedEnv: Partial> = {}; +let kernel: ObjectKernel | undefined; +let dir: string | undefined; + +beforeEach(() => { + for (const key of ENV_KEYS) { + savedEnv[key] = process.env[key]; + delete process.env[key]; + } + dir = mkdtempSync(join(tmpdir(), 'os-dev-seed-retire-')); +}); + +afterEach(async () => { + try { + await kernel?.shutdown(); + } catch { + /* already down */ + } + kernel = undefined; + if (dir) rmSync(dir, { recursive: true, force: true }); + dir = undefined; + for (const key of ENV_KEYS) { + if (savedEnv[key] === undefined) delete process.env[key]; + else process.env[key] = savedEnv[key]; + } +}); + +/** A store shared by both boots, as a host's Redis outlives a restart. */ +function sharedSecondaryStorage(): SecondaryStorage & { keys(): string[] } { + const map = new Map(); + return { + async get(key) { + return map.get(key) ?? null; + }, + async set(key, value) { + map.set(key, value); + }, + async delete(key) { + map.delete(key); + }, + keys: () => [...map.keys()], + }; +} + +function sqliteFilePlugin(filename: string): Plugin { + return { + name: 'test.driver.sqlite-file', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService( + 'driver.default', + new SqlDriver({ client: 'better-sqlite3', connection: { filename }, useNullAsDefault: true }), + ); + }, + }; +} + +/** A response's Set-Cookie values as one request Cookie header (expired ones dropped). */ +const cookieHeader = (res: Response): string => + (res.headers.getSetCookie?.() ?? []) + .filter((c) => !/max-age=0/i.test(c)) + .map((c) => c.split(';')[0]) + .join('; '); + +/** One boot of the real composition over the test's database file, in `nodeEnv`. */ +async function boot(nodeEnv: string, options: { secondaryStorage?: SecondaryStorage; also?: Plugin } = {}) { + process.env.NODE_ENV = nodeEnv; + kernel = new ObjectKernel({ logger: { level: 'silent' } }); + await kernel.use(sqliteFilePlugin(join(dir!, 'app.sqlite'))); + await kernel.use(new ObjectQLPlugin()); + await kernel.use( + new AuthPlugin({ + secret: SECRET, + baseUrl: ORIGIN, + demoStaff: [{ name: 'Demo Staff 1', email: STAFF_EMAIL }] as never, + // The OIDC provider refuses a `secondaryStorage` that holds the sessions + // (`session-of-record.test.ts`), so a host that supplies one turns it off. + plugins: { admin: true, ...(options.secondaryStorage ? { oidcProvider: false } : {}) }, + ...(options.secondaryStorage ? { secondaryStorage: options.secondaryStorage } : {}), + } as never), + ); + await kernel.use(new SecurityPlugin()); + if (options.also) await kernel.use(options.also); + await kernel.bootstrap(); + const ql = kernel.getService('objectql'); + const manager = kernel.getService('auth'); + const rows = async (object: string, where: Record = {}) => + (await ql.find(object, { where, limit: 200, context: SYS })) as Array>; + const post = (path: string, body: unknown) => + manager.handleRequest( + new Request(`${AUTH}${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN }, + body: JSON.stringify(body ?? {}), + }), + ); + /** The user a session cookie resolves to, or `null`. */ + const sessionUser = async (cookie: string): Promise => { + const res = await manager.handleRequest(new Request(`${AUTH}/get-session`, { method: 'GET', headers: { origin: ORIGIN, cookie } })); + const body = (await res.json().catch(() => null)) as { user?: { id?: string } } | null; + return body?.user?.id ?? null; + }; + /** The key-admission seam's verdict for a raw key: `admitted`, or the refusal's code. */ + const keyAnswer = async (raw: string): Promise => { + const admission = await resolveApiKeyAdmission(ql, { 'x-api-key': raw }, Date.now(), undefined, undefined, undefined); + return admission.outcome === 'lifecycle' ? admission.refusal.code : admission.outcome; + }; + /** Mint a key the way `POST /api/v1/keys` writes the row (system context, hash only); answers the raw key. */ + const mintKey = async (userId: string, name: string): Promise => { + const raw = `osk_${name}_${'x'.repeat(24)}`; + await ql.insert( + 'sys_api_key', + { id: `key_${name}`, name, key: hashApiKey(raw), prefix: raw.slice(0, 12), user_id: userId, revoked: false }, + { context: SYS } as never, + ); + return raw; + }; + const idOf = async (email: string) => (await rows('sys_user', { email }))[0]?.id as string; + const signIn = async (email: string, password: string): Promise => { + const res = await post('/sign-in/email', { email, password }); + expect(res.status, `${email}: ${await res.clone().text()}`).toBe(200); + return cookieHeader(res); + }; + return { ql, manager, rows, post, sessionUser, keyAnswer, mintKey, idOf, signIn }; +} + +type Server = Awaited>; + +async function stop(): Promise { + await kernel?.shutdown(); + kernel = undefined; +} + +/** Whether `userId` carries the seed stamp, matched by the server, as the column is never served. */ +async function isStamped(server: Server, userId: string): Promise { + const found = await server.ql.find( + 'sys_user', + { where: { id: userId, [DEV_SEED_CREDENTIAL_FIELD]: { $null: false } }, fields: ['id'], limit: 1, context: SYS } as never, + ); + return Array.isArray(found) && found.length === 1; +} + +/** + * The development boot: the seed, an administrator-created control account, + * and a session, an API key and a reset link issued to each of the three. + * `beforeStop` runs on the development database before the server stops. + */ +async function seedInDevelopment(options: { secondaryStorage?: SecondaryStorage; beforeStop?: (dev: Server, ids: Record) => Promise } = {}) { + const dev = await boot('development', options); + const api: any = await dev.manager.getApi(); + // The administrator's create-user, as the `/admin/create-user` route drives it. + await api.createUser({ body: { email: CONTROL_EMAIL, name: 'Admin Created', password: CONTROL_PASSWORD } }); + const ids: Record = { admin: await dev.idOf(SEED_EMAIL), staff: await dev.idOf(STAFF_EMAIL), control: await dev.idOf(CONTROL_EMAIL) }; + expect({ admin: await isStamped(dev, ids.admin), staff: await isStamped(dev, ids.staff), control: await isStamped(dev, ids.control) }) + .toEqual({ admin: true, staff: true, control: false }); + + const cookies: Record = { + admin: await dev.signIn(SEED_EMAIL, SEED_PASSWORD), + staff: await dev.signIn(STAFF_EMAIL, SEED_PASSWORD), + control: await dev.signIn(CONTROL_EMAIL, CONTROL_PASSWORD), + }; + const keys: Record = { + admin: await dev.mintKey(ids.admin, 'admin'), + staff: await dev.mintKey(ids.staff, 'staff'), + control: await dev.mintKey(ids.control, 'control'), + }; + const expiresAt = new Date(Date.now() + 3_600_000); + for (const who of ['admin', 'staff', 'control'] as const) { + await dev.ql.insert('sys_verification', { identifier: `reset-password:tok_${who}`, value: ids[who], expires_at: expiresAt }, { context: SYS } as never); + } + await options.beforeStop?.(dev, ids); + await stop(); + return { ids, cookies, keys }; +} + +type Issued = Awaited>; + +/** What `who`'s development credentials answer on `server`. */ +async function answers(server: Server, issued: Issued, who: Who) { + return { + session: await server.sessionUser(issued.cookies[who]), + key: await server.keyAnswer(issued.keys[who]), + resetLinks: (await server.rows('sys_verification', { value: issued.ids[who] })).length, + }; +} + +const RETIRED = { session: null, key: 'API_KEY_REVOKED', resetLinks: 0 }; + +describe('leaving development mode retires what the development seed issued', () => { + it('a boot outside development mode retires the seed accounts\' sessions, API keys and reset links, each answering as revoked; an administrator-created account is untouched', async () => { + const issued = await seedInDevelopment(); + const server = await boot(PRODUCTION); + for (const who of ['admin', 'staff'] as const) { + expect({ who, ...(await answers(server, issued, who)) }).toEqual({ who, ...RETIRED }); + const sessions = await server.rows('sys_session', { user_id: issued.ids[who] }); + expect(sessions.length, `${who} had a session row`).toBeGreaterThan(0); + for (const session of sessions) { + expect({ who, reason: session.revoke_reason, revoked: Boolean(session.revoked_at) }).toEqual({ who, reason: 'admin_password_reset', revoked: true }); + } + } + expect(await answers(server, issued, 'control')).toEqual({ session: issued.ids.control, key: 'admitted', resetLinks: 1 }); + // The stamp stays: the account opens no session until an operator sets a password. + expect(await isStamped(server, issued.ids.admin)).toBe(true); + }); + + it('a boot in development mode retires nothing', async () => { + const issued = await seedInDevelopment(); + const server = await boot('development'); + for (const who of ['admin', 'staff', 'control'] as const) { + expect({ who, ...(await answers(server, issued, who)) }).toEqual({ who, session: issued.ids[who], key: 'admitted', resetLinks: 1 }); + } + }); + + it('an account whose password was set since the seed is untouched: by the operator\'s reset, or by an administrator', async () => { + let afterOperatorReset = ''; + const issued = await seedInDevelopment({ + async beforeStop(dev, ids) { + // The operator's reset clears the stamp and ends what the account held; a key minted after it is the operator era's. + expect(await setOperatorPassword(dev.ql as never, { email: SEED_EMAIL, password: OPERATOR_PASSWORD })).toMatchObject({ outcome: 'set' }); + afterOperatorReset = await dev.mintKey(ids.admin, 'after_operator_reset'); + // The write `/admin/set-user-password` makes, with its revocation switch off: the stamp stays and stops + // matching. The write itself ends the account's reset links, as every password write does. + const context: any = await dev.manager.getAuthContext(); + await context.internalAdapter.updatePassword(ids.staff, await context.password.hash(CONTROL_PASSWORD)); + }, + }); + const server = await boot(PRODUCTION); + expect(await server.keyAnswer(afterOperatorReset)).toBe('admitted'); + expect(await server.sessionUser(await server.signIn(SEED_EMAIL, OPERATOR_PASSWORD))).toBe(issued.ids.admin); + expect(await isStamped(server, issued.ids.staff)).toBe(true); + expect(await answers(server, issued, 'staff')).toEqual({ session: issued.ids.staff, key: 'admitted', resetLinks: 0 }); + }); + + it('a second boot outside development mode is a no-op', async () => { + const issued = await seedInDevelopment(); + const first = await boot(PRODUCTION); + const tombstones = async (server: Server) => + (await server.rows('sys_session', { user_id: issued.ids.admin })).map((row) => [row.id, String(row.revoked_at)]); + const afterFirst = await tombstones(first); + await stop(); + const second = await boot(PRODUCTION); + expect(await tombstones(second)).toEqual(afterFirst); + // The same retirement, run once more, finds the two seed accounts and ends nothing. + const outcome = await retireDevSeedCredentials({ engine: second.ql as never, authContext: () => second.manager.getAuthContext() }); + expect(outcome).toMatchObject({ mode: 'production', stampedAccounts: 2 }); + const retired = outcome.mode === 'production' ? outcome.retired : []; + expect(retired.map((r) => r.userId).sort()).toEqual([issued.ids.admin, issued.ids.staff].sort()); + for (const account of retired) { + expect(account).toMatchObject({ sessions: 0, cachedSessions: 0, apiKeys: 0, signInAccounts: 0, authorizedApps: 0, ownedApps: 0, scimCredentials: 0 }); + } + expect(await answers(second, issued, 'control')).toEqual({ session: issued.ids.control, key: 'admitted', resetLinks: 1 }); + }); + + it('a retirement that cannot complete fails the boot, naming the account and the remedy', async () => { + const issued = await seedInDevelopment(); + // The database refuses every write to `sys_api_key`, from the server's start on. + const refuseKeyWrites: Plugin = { + name: 'test.refuse-api-key-writes', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + async init() {}, + async start(ctx: PluginContext) { + ctx.getService('objectql').registerHook( + 'beforeUpdate', + async () => { + throw new Error('sys_api_key is read-only on this database'); + }, + { object: 'sys_api_key', packageId: 'test.refuse-api-key-writes' } as never, + ); + }, + }; + const refused = await boot(PRODUCTION, { also: refuseKeyWrites }).then(() => undefined, (e: unknown) => e as Error); + expect(refused, 'the boot failed').toBeInstanceOf(Error); + expect(refused!.message).toContain(`user ${issued.ids.admin}`); + expect(refused!.message).toContain('os user set-password'); + }); + + it('with a host secondaryStorage holding the sessions, the boot ends them there', async () => { + const storage = sharedSecondaryStorage(); + const issued = await seedInDevelopment({ secondaryStorage: storage }); + // No `sys_session` row is written: the store is the session of record. + expect(storage.keys().filter((k) => k === `active-sessions-${issued.ids.admin}`)).toHaveLength(1); + const server = await boot(PRODUCTION, { secondaryStorage: storage }); + expect(await server.sessionUser(issued.cookies.admin)).toBeNull(); + expect(await server.sessionUser(issued.cookies.staff)).toBeNull(); + expect(await server.sessionUser(issued.cookies.control)).toBe(issued.ids.control); + }); +}); diff --git a/packages/plugins/plugin-auth/src/dev-seed-credential-retirement.ts b/packages/plugins/plugin-auth/src/dev-seed-credential-retirement.ts new file mode 100644 index 00000000000..a5d1b6aed31 --- /dev/null +++ b/packages/plugins/plugin-auth/src/dev-seed-credential-retirement.ts @@ -0,0 +1,306 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Leaving development mode retires what the development seed issued. + * + * ## The rule + * + * When a deployment leaves development mode, nothing the development seed + * issued keeps acting for an account that carries the development seed stamp. + * At every boot outside development mode, before the server serves a request, + * the platform retires those accounts' sessions, API keys and tokens. A + * retired credential answers exactly as a revoked one does, and an + * operator-set credential is untouched. There is no switch: development mode + * is `NODE_ENV=development` ({@link isDevelopmentMode}), the clause the seed + * and the refusals in `dev-seed-credential.ts` are gated on. + * + * The refusals there stop the seed's accounts from opening anything new + * outside development mode. This is the other half: what such an account was + * issued while the server was in development mode (a session, an API key it + * minted, an app it authorized) would otherwise keep working. + * + * ## Which accounts + * + * A stamped account whose seed credential is still in force: its stored + * password hash is still the one the seed stored ({@link + * isDevSeedCredentialInForce}). An account whose password was set since then + * holds a credential the seed did not issue and is not touched: the + * operator's reset (`os user set-password`, which also clears the stamp), an + * administrator's set-user-password and the account's own reset or change + * each write a new salted hash, and the stamp stops matching. An account the + * seed never stamped is never read. + * + * ## What is retired, per account + * + * The revocation the operator's reset performs, without setting a password + * (`forced-reset-revocation.ts` {@link revokeSessionsAndApiKeys}): + * + * - every live session: tombstoned in place (`revoked_at`, `revoke_reason`, a + * past `expires_at`, ADR-0069 D4), so its next request is unauthenticated, + * as after any other revocation; + * - every API key the key-admission seam would admit: `revoked: true`, so its + * next call is refused `API_KEY_REVOKED`. Both carry the reason the + * operator's reset records (`admin_password_reset`), so a retired key is + * restored only by a platform administrator; + * - every app authorized to the account (consents, refresh and stored access + * tokens) and every device sign-in approved for it, where those plugins are + * mounted, read through better-auth's own adapter as the administrator's + * forced reset reads them; + * - every sign-in account linked to it other than its password, every OAuth + * application it registered (disabled) and every SCIM credential it minted + * (revoked); + * - every outstanding password-reset token of the account + * (`credential-change-ends-reset-tokens.ts` {@link + * endOutstandingResetTokens}), rows and cache entries; + * - with a host `secondaryStorage` holding the sessions of record (no + * `sys_session` row is written then), the account's sessions there, through + * better-auth's own `deleteUserSessions`, and read back to prove it. + * + * ## What is left + * + * - The password credential and the stamp. The refusals keep answering for + * them, and the way out stays the operator's reset. + * - A sign-in link or one-time code (`sys_verification`): it only opens a + * session, which `session.create.before` refuses for such an account. + * - A one-time token: it hands over a session, which is retired above. + * - The single sign-on providers it registered and its second factor, which + * every reset keeps. + * + * ## When, and how it fails + * + * On `kernel:ready`, which settles before `kernel:listening` opens the socket. + * A database with no stamped account costs one indexed read. It is idempotent: + * an account retired at one boot cannot open a new session or mint a key + * before the next, so the next finds nothing to end. + * + * It fails closed, as the refusals do (a read that fails answers `503` there): + * a read or a write that did not land throws, and the boot fails with a + * sentence naming the accounts and the remedy, rather than serving while a + * development seed credential may still act. Only an engine with no read + * surface (mock mode) or a user table that was never created holds no stamped + * account, and reads as none. + */ + +import { SystemObjectName } from '@objectstack/spec/system'; +import { isMissingTableError } from '@objectstack/types'; +import { + DEV_SEED_CREDENTIAL_FIELD, + OPERATOR_PASSWORD_RESET_COMMAND, + isDevSeedCredentialInForce, + isDevelopmentMode, +} from './dev-seed-credential.js'; +import { revokeSessionsAndApiKeys, type ForcedResetRevocationOutcome } from './forced-reset-revocation.js'; +import { endOutstandingResetTokens } from './credential-change-ends-reset-tokens.js'; +import type { MountedOAuthGrants } from './password-reset-ends-added-access.js'; +import type { InternalFieldResolvingEngine } from './internal-field-readback.js'; + +/** The slice of the data engine the retirement reads and writes through. */ +export interface DevSeedRetirementEngine { + find(object: string, query?: unknown, opts?: unknown): Promise; + findOne?(object: string, query?: unknown, opts?: unknown): Promise; + update(object: string, doc: Record, opts?: unknown): Promise; + delete?(object: string, options?: unknown): Promise; + insert?(object: string, data: Record, opts?: unknown): Promise; + getSchema?(object: string): unknown; +} + +/** The slice of better-auth's context the retirement uses. */ +export interface DevSeedRetirementAuthContext { + adapter?: unknown; + getPlugin?(pluginId: string): unknown; + secondaryStorage?: { delete(key: string): unknown } | null; + options?: { session?: { storeSessionInDatabase?: boolean } }; + internalAdapter?: { + listSessions(userId: string): Promise; + deleteUserSessions(userId: string): Promise; + }; +} + +/** What the retirement ended for one account. */ +export interface RetiredDevSeedAccount { + userId: string; + sessions: number; + /** Sessions ended in a host `secondaryStorage` that holds them. */ + cachedSessions: number; + apiKeys: number; + signInAccounts: number; + authorizedApps: number; + ownedApps: number; + scimCredentials: number; +} + +/** What one boot's retirement did. */ +export type DevSeedRetirementOutcome = + | { mode: 'development' } + | { mode: 'production'; stampedAccounts: number; retired: RetiredDevSeedAccount[] }; + +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const; + +/** How many stamped accounts one read considers. */ +const STAMPED_PAGE = 200; + +function rowsOf(result: unknown): Array> { + if (Array.isArray(result)) return result as Array>; + const value = (result as { value?: unknown } | null)?.value; + return Array.isArray(value) ? (value as Array>) : []; +} + +/** The ids of every stamped account: one indexed read per page. */ +async function stampedAccountIds(engine: DevSeedRetirementEngine): Promise { + const ids: string[] = []; + for (let offset = 0; ; offset += STAMPED_PAGE) { + let page: Array>; + try { + page = rowsOf( + await engine.find( + SystemObjectName.USER, + { + where: { [DEV_SEED_CREDENTIAL_FIELD]: { $null: false } }, + fields: ['id'], + orderBy: [{ field: 'id', order: 'asc' }], + limit: STAMPED_PAGE, + offset, + }, + { context: SYSTEM_CTX }, + ), + ); + } catch (error) { + if (isMissingTableError(error, SystemObjectName.USER)) return ids; + throw error; + } + for (const row of page) { + if (typeof row?.id === 'string' && row.id) ids.push(row.id); + } + if (page.length < STAMPED_PAGE) return ids; + } +} + +/** + * Sessions of record a host `secondaryStorage` holds for `userId`, ended + * through better-auth's own `deleteUserSessions` and read back. With no such + * store, or with sessions kept in `sys_session` (retired there), none. + */ +async function retireCachedSessions(authContext: DevSeedRetirementAuthContext | undefined, userId: string): Promise { + if (!authContext?.secondaryStorage || authContext.options?.session?.storeSessionInDatabase) return 0; + const internal = authContext.internalAdapter; + if (!internal || typeof internal.listSessions !== 'function' || typeof internal.deleteUserSessions !== 'function') { + throw new Error('the secondary storage holds the sessions, and better-auth offers no way to end them'); + } + const live = (await internal.listSessions(userId)).length; + if (live === 0) return 0; + await internal.deleteUserSessions(userId); + // The vendor logs, and does not throw, a cache delete that fails. + const left = (await internal.listSessions(userId)).length; + if (left > 0) throw new Error(`${left} session(s) in the secondary storage could not be ended`); + return live; +} + +function incompleteRevocation(outcome: ForcedResetRevocationOutcome): string { + return `${outcome.failed} write(s) did not land, or a read did not finish ` + + `(${outcome.sessions} session(s), ${outcome.apiKeys} API key(s) ended so far)`; +} + +/** + * Retire what the development seed issued to every stamped account still on + * its seed password, on a server that is not in development mode. Throws when + * any of it could not be retired (the module header says why). + */ +export async function retireDevSeedCredentials(host: { + engine: DevSeedRetirementEngine | undefined; + /** better-auth's context; read only when a stamped account is found. */ + authContext: () => Promise; + logger?: { warn(message: string): void }; +}): Promise { + if (isDevelopmentMode()) return { mode: 'development' }; + const engine = host.engine; + if (!engine || typeof engine.find !== 'function' || typeof engine.update !== 'function') { + return { mode: 'production', stampedAccounts: 0, retired: [] }; + } + + const stamped = await stampedAccountIds(engine); + if (stamped.length === 0) return { mode: 'production', stampedAccounts: 0, retired: [] }; + + const authContext = await host.authContext(); + const oauth: MountedOAuthGrants = { + store: authContext?.adapter as MountedOAuthGrants['store'], + mounted: (pluginId) => typeof authContext?.getPlugin === 'function' && Boolean(authContext.getPlugin(pluginId)), + }; + const resetTokenEngine = { + find: async (object: string, query: Record) => + rowsOf(await engine.find(object, { ...query, context: SYSTEM_CTX })), + findOne: async (object: string, query: Record) => + engine.findOne + ? engine.findOne(object, { ...query, context: SYSTEM_CTX }) + : (rowsOf(await engine.find(object, { ...query, limit: 1, context: SYSTEM_CTX }))[0] ?? null), + delete: async (object: string, query: Record) => { + if (typeof engine.delete !== 'function') throw new Error('the data engine cannot delete'); + return engine.delete(object, { ...query, context: SYSTEM_CTX }); + }, + }; + + const retired: RetiredDevSeedAccount[] = []; + const failures: string[] = []; + for (const userId of stamped) { + try { + if (!(await isDevSeedCredentialInForce(engine, userId))) continue; + } catch (error) { + failures.push(`user ${userId}: the account could not be read (${(error as Error)?.message ?? error})`); + continue; + } + const reasons: string[] = []; + const revocation = await revokeSessionsAndApiKeys(engine, userId, { oauth }); + if (!revocation.complete) reasons.push(incompleteRevocation(revocation)); + try { + await endOutstandingResetTokens(resetTokenEngine, userId, { + ...(authContext?.secondaryStorage ? { cache: authContext.secondaryStorage } : {}), + internalFieldEngine: engine as unknown as InternalFieldResolvingEngine, + }); + } catch (error) { + reasons.push(`its password-reset tokens could not be ended (${(error as Error)?.message ?? error})`); + } + let cachedSessions = 0; + try { + cachedSessions = await retireCachedSessions(authContext, userId); + } catch (error) { + reasons.push(`${(error as Error)?.message ?? error}`); + } + if (reasons.length > 0) { + failures.push(`user ${userId}: ${reasons.join('; ')}`); + continue; + } + const account: RetiredDevSeedAccount = { + userId, + sessions: revocation.sessions, + cachedSessions, + apiKeys: revocation.apiKeys, + signInAccounts: revocation.signInAccounts, + authorizedApps: revocation.authorizedApps, + ownedApps: revocation.ownedApps, + scimCredentials: revocation.scimCredentials, + }; + retired.push(account); + const ended = + account.sessions + account.cachedSessions + account.apiKeys + account.signInAccounts + + account.authorizedApps + account.ownedApps + account.scimCredentials; + if (ended > 0) { + host.logger?.warn( + `[auth] user ${userId} was created by the development seed and still has its seed password, so this server, ` + + `which is not in development mode, retired what it was issued: ${account.sessions + account.cachedSessions} ` + + `session(s), ${account.apiKeys} API key(s), ${account.signInAccounts} linked sign-in account(s), ` + + `${account.authorizedApps} authorized app(s), ${account.ownedApps} registered OAuth application(s) and ` + + `${account.scimCredentials} SCIM credential(s), with its password-reset tokens. The account signs in again ` + + `once an operator sets a new password with \`${OPERATOR_PASSWORD_RESET_COMMAND} \`.`, + ); + } + } + + if (failures.length > 0) { + throw new Error( + '[auth] the server did not start: it is not in development mode, and what the development seed issued to ' + + `${failures.length} account(s) still on the seed password could not all be retired, so it could keep ` + + `acting. ${failures.join('. ')}. Remedy: fix the database access the error names and start the server ` + + `again, or set a new password for each account with \`${OPERATOR_PASSWORD_RESET_COMMAND} \` first.`, + ); + } + return { mode: 'production', stampedAccounts: stamped.length, retired }; +}