From 547be616bf2f1ff9b3a74b1273ef759b503fc118 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 04:28:41 +0000 Subject: [PATCH 01/12] wip(auth): a production-mode server refuses a development seed credential Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- content/docs/deployment/cli.mdx | 33 ++ packages/cli/package.json | 3 + .../cli/src/commands/user/set-password.ts | 160 ++++++++ ...igrate.one-shot-family.integration.test.ts | 10 + .../src/identity/sys-user.object.ts | 25 ++ .../src/auth-manager-auth-instance.ts | 14 +- .../src/auth-manager-database-hooks.ts | 8 + .../src/auth-manager-membership-admission.ts | 7 + .../plugin-auth/src/dev-seed-credential.ts | 374 ++++++++++++++++++ packages/plugins/plugin-auth/src/index.ts | 14 + .../src/managed-extension-fields.ts | 6 + .../src/operator-password-reset.ts | 171 ++++++++ 12 files changed, 823 insertions(+), 2 deletions(-) create mode 100644 packages/cli/src/commands/user/set-password.ts create mode 100644 packages/plugins/plugin-auth/src/dev-seed-credential.ts create mode 100644 packages/plugins/plugin-auth/src/operator-password-reset.ts diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index c005050575d..80ad4b226fe 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -854,6 +854,39 @@ for its own keys. - A bundle proves what its checkpoints hold. Rows of a sealed window that no checkpoint lists (`late` and unsealed) are carried as the writing run found them. +#### `os user set-password` + +Sets a user's password in the project database, on the server. A server that is not in +development mode never accepts a development seed credential: a sign-in with the +development seed password (`admin123`, or the `OS_SEED_ADMIN_PASSWORD` value) is refused +on every account, and an account `os dev` seeded (its admin and the stack's `demoStaff`) +opens no session while it still has the password it was seeded with, a custom +`--admin-password` included. No session is offered to change it in, because whoever signed +in first could. This command is the way out, and the refusal names it. + +```bash +os user set-password admin@example.com # asks twice, unechoed +printf %s "$NEW_PASSWORD" | os user set-password admin@example.com --password-stdin +os user set-password admin@example.com --database-url "postgres://user:pass@host:5432/mydb" +``` + +**Options:** +- `--password-stdin` — read the new password from standard input instead of asking for it +- `--database-url ` — the database to write (defaults to `$OS_DATABASE_URL` / the project database) + +What one run does: + +- **The password never goes on the command line.** It is asked for on a terminal, or read + from standard input. +- **It refuses a password a server would refuse:** a development seed password, or one + shorter than 8 or longer than 128 characters. An address no account holds, and an + account with no password sign-in, are refused too. A refusal writes nothing. +- **It sets the password with the hash every server verifies**, clears the account's + development seed mark and a sign-in lock, and records the change time. +- **It ends every session and revokes every API key of the account**, as an + administrator's forced reset does: credentials issued under the old password do not + outlive it. It asks for no password change at the next sign-in. + ### Build & Validate | Command | Description | diff --git a/packages/cli/package.json b/packages/cli/package.json index b2ae84b5c83..b168d6db231 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -98,6 +98,9 @@ }, "storage": { "description": "Inspect stored files: report orphaned attachments" + }, + "user": { + "description": "Maintain user accounts on the server: set a password" } } }, diff --git a/packages/cli/src/commands/user/set-password.ts b/packages/cli/src/commands/user/set-password.ts new file mode 100644 index 00000000000..935a9d33e33 --- /dev/null +++ b/packages/cli/src/commands/user/set-password.ts @@ -0,0 +1,160 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { Args, Command, Flags } from '@oclif/core'; +import { createInterface } from 'node:readline'; +import { Writable } from 'node:stream'; +import { + printHeader, + printSuccess, + printWarning, + printError, + printInfo, + printStep, + isExitSignal, +} from '../../utils/format.js'; +import { bootSchemaStack } from '../../utils/schema-migrate.js'; +import { composeProviderForDeclarations } from '../../utils/schema-migration-plugins.js'; + +/** + * `os user set-password ` — the operator's password reset, run on the + * server against the project database. + * + * A server outside development mode refuses a development seed credential + * (`@objectstack/plugin-auth`, `dev-seed-credential.ts`) and opens no session + * in which it could be changed: whoever signed in first could change it. Its + * refusal names this command. The reset itself is plugin-auth's + * `setOperatorPassword`: it writes the account's password credential with + * better-auth's own hash, clears the development seed stamp and a sign-in + * lock, and ends every session and API key of the account. + * + * - **The password never travels on the command line**, where a shell history + * and the process table keep it: it is asked for twice, unechoed, on a + * terminal, or read from standard input with `--password-stdin`. + * - **The account is resolved first**, so an address no account holds is + * refused before any password is asked for. + * - **Operator-only.** No HTTP surface: it runs where the database is. + */ +export default class UserSetPassword extends Command { + static override description = + 'Set a user\'s password in the project database, ending the account\'s sessions and API keys. ' + + 'The reset a server outside development mode names when it refuses a development seed credential.'; + + static override examples = [ + '<%= config.bin %> user set-password admin@example.com', + 'printf %s "$NEW_PASSWORD" | <%= config.bin %> user set-password admin@example.com --password-stdin', + ]; + + static override args = { + email: Args.string({ description: 'The email address of the account', required: true }), + }; + + static override flags = { + 'password-stdin': Flags.boolean({ + description: 'Read the new password from standard input instead of asking for it', + default: false, + }), + 'database-url': Flags.string({ + description: 'Database URL (defaults to $OS_DATABASE_URL / the project DB)', + env: 'OS_DATABASE_URL', + }), + }; + + async run(): Promise { + const { args, flags } = await this.parse(UserSetPassword); + printHeader('User · set password'); + printStep('Booting…'); + + const { createIdentityObjectsPlugin, findAccountByEmail, operatorPasswordRefusal, setOperatorPassword } = + await import('@objectstack/plugin-auth'); + + let stack; + try { + stack = await bootSchemaStack({ + jsonOutput: false, + databaseUrl: flags['database-url'], + // The identity objects (`sys_user`, `sys_account`, `sys_session`, + // `sys_api_key`) for their declarations only: no auth manager, no + // authentication, nothing started. + extraPlugins: [composeProviderForDeclarations(createIdentityObjectsPlugin())], + }); + } catch (error) { + if (isExitSignal(error)) throw error; + printError(error instanceof Error ? error.message : String(error)); + this.exit(1); + return; + } + + let failure: string | undefined; + try { + const engine = stack.kernel.getService('objectql'); + if (!engine) { + failure = 'No ObjectQL engine on this runtime, so no account can be read.'; + } else if (!(await findAccountByEmail(engine, args.email))) { + failure = `No account has the email address ${args.email.trim()}.`; + } else { + const given = flags['password-stdin'] ? await readStdin() : await askTwice(); + const refusal = 'refused' in given ? given.refused : operatorPasswordRefusal(given.password)?.message; + if ('refused' in given || refusal !== undefined) { + failure = refusal; + } else { + const outcome = await setOperatorPassword(engine, { email: args.email, password: given.password }, { + logger: { warn: (message: string) => printWarning(message) }, + }); + if (outcome.outcome === 'refused') { + failure = outcome.message; + } else { + printSuccess(`The password of ${args.email.trim()} is set.`); + printInfo( + `${outcome.sessionsEnded} session(s) ended and ${outcome.apiKeysRevoked} API key(s) revoked; ` + + 'the account signs in with the new password.', + ); + if (!outcome.revocationComplete) { + printWarning('Not every session or API key could be revoked: revoke the rest by hand.'); + } + } + } + } + } finally { + await stack.shutdown(); + } + if (failure !== undefined) { + printError(failure); + this.exit(1); + } + } +} + +/** A password the operator gave, or why none was taken. */ +type GivenPassword = { password: string } | { refused: string }; + +/** The whole of standard input, without one trailing line break. */ +async function readStdin(): Promise { + const chunks: Buffer[] = []; + for await (const chunk of process.stdin) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))); + const text = Buffer.concat(chunks).toString('utf8').replace(/\r?\n$/, ''); + return text === '' ? { refused: 'Standard input held no password.' } : { password: text }; +} + +/** Ask for the password twice on a terminal, without echoing it. */ +async function askTwice(): Promise { + if (!process.stdin.isTTY) { + return { refused: 'Standard input is not a terminal, so no password can be asked for: pass --password-stdin.' }; + } + const first = await askUnechoed('New password: '); + const second = await askUnechoed('Repeat it: '); + if (first !== second) return { refused: 'The two passwords differ, so none was set.' }; + return first === '' ? { refused: 'No password was given.' } : { password: first }; +} + +function askUnechoed(question: string): Promise { + process.stdout.write(question); + const silent = new Writable({ write: (_chunk, _encoding, done) => done() }); + const rl = createInterface({ input: process.stdin, output: silent, terminal: true }); + return new Promise((resolve) => { + rl.question('', (answer) => { + rl.close(); + process.stdout.write('\n'); + resolve(answer); + }); + }); +} diff --git a/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts b/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts index f5569d71590..b57308c616a 100644 --- a/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts +++ b/packages/cli/src/utils/schema-migrate.one-shot-family.integration.test.ts @@ -110,6 +110,7 @@ import PluginTrustRevoke from '../commands/plugin/trust/revoke.js'; import SecretOrphans from '../commands/secret/orphans.js'; import SecretRewrap from '../commands/secret/rewrap.js'; import StorageOrphans from '../commands/storage/orphans.js'; +import UserSetPassword from '../commands/user/set-password.js'; // [#10126] Pay the first transform of these dist-resolved workspace deps at // MODULE LOAD: the commands reach them through dynamic `import()`s inside @@ -464,6 +465,15 @@ const CALLERS: Record = { write: [], note: 'report-only: it has no writing mode', }, + 'commands/user/set-password.ts': { + run: invoke(UserSetPassword), + noWrite: [], + // No account holds this address: the boot happens and the command then + // refuses the address, before it asks for a password. The boot is what + // this case is about. + write: [{ label: 'user set-password', argv: ['osf-absent@example.com', '--database-url', '@DB@'] }], + note: 'every run of it is the write: it has no preview mode', + }, // [#27123] The trusted-key read `os plugin install` and `os serve`'s // boot-time loader share: a utility, so its boot runs through the command // that reaches it from oclif. (`os serve` reaches it too, before its own diff --git a/packages/platform-objects/src/identity/sys-user.object.ts b/packages/platform-objects/src/identity/sys-user.object.ts index 1c836e0edfb..cf7c06486c6 100644 --- a/packages/platform-objects/src/identity/sys-user.object.ts +++ b/packages/platform-objects/src/identity/sys-user.object.ts @@ -1343,6 +1343,27 @@ export const SysUser = ObjectSchema.create({ 'Turned on when an administrator creates or imports the account, or resets its password; system-managed.', }), + // The development seed's stamp (`plugin-auth` `dev-seed-credential.ts`): + // written on an account `os dev`'s admin seed or a stack's `demoStaff` + // creates, as a one-way digest of the password hash the seed stored. A + // production-mode server refuses that account's sign-in and every new + // session while its stored hash still has this digest; `os user + // set-password` sets a new password and clears it. A digest of a salted + // hash, so `internal`: never served on the generic data path, matched by + // the server alone. Owned by objectql (better-auth is oblivious to this + // column — like `ai_access`). + dev_seed_credential: Field.text({ + label: 'Development Seed Credential', + required: false, + readonly: true, + internal: true, + group: 'System', + description: + 'Set on an account the development seed created. While its password is still the seed password, a ' + + 'production server refuses its sign-in and every new session; os user set-password sets a new password ' + + 'and clears it. System-managed; never returned on reads.', + }), + // ADR-0069 D3 — when enforced MFA first applied to this user; starts the // grace clock. Stamped lazily at session validation; system-managed. mfa_required_at: Field.datetime({ @@ -1569,6 +1590,10 @@ export const SysUser = ObjectSchema.create({ // #2766 V1.5 — phone sign-in identifier; unique when present (null for // email-only accounts), also the upsert match key for identity import. { fields: ['phone_number'], unique: 'global' }, + // The development seed's stamp, matched by the password verifier on a + // server that is not in development mode (`plugin-auth` + // `dev-seed-credential.ts`). Null on every account the seed never created. + { fields: ['dev_seed_credential'], unique: false }, ], enable: { diff --git a/packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts b/packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts index 5d25f2a4ea6..8bf31726a2c 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-auth-instance.ts @@ -57,6 +57,7 @@ import { audiencePermitsSelfRegistration } from '@objectstack/spec/system'; import { readEnvWithDeprecation } from '@objectstack/types'; import { readAccountInvitation, settleImportResetDelivery } from './account-invitation-marker.js'; import { withLockoutRefusal } from './sign-in-lockout-refusal.js'; +import { refuseDevSeedPasswordSignIn, withDevSeedPasswordRefusal } from './dev-seed-credential.js'; import { resolveEmailVerificationRequirement } from './audience-posture.js'; import { globalAfterHook, type AfterHookHost } from './auth-manager-after-hook.js'; import { globalBeforeHook, type BeforeHookHost } from './auth-manager-before-hook.js'; @@ -456,7 +457,12 @@ export async function createAuthInstance(this: AuthInstanceHost): Promise this.config.dataEngine as never, + logger: () => this.config.logger, + }), ...(effectiveDisableSignUp != null ? { disableSignUp: effectiveDisableSignUp } : {}), // [#11739] Invariant: a posture that permits self-registration @@ -833,7 +839,11 @@ export async function createAuthInstance(this: AuthInstanceHost): Promise { + before: createAuthMiddleware(async (ctx: any) => { + // A password sign-in that submits the development seed password is + // refused outside development mode, before any account is read + // (`dev-seed-credential.ts`). + await refuseDevSeedPasswordSignIn(ctx); const readConfig = () => this.config; const host: BeforeHookHost = { admitSignInAttempt: (...a) => this.admitSignInAttempt(...a), diff --git a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts index 3dc563d6cf0..b0309251173 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts @@ -65,6 +65,7 @@ import { SESSION_SCOPING_REFUSAL } from './organization-access-policy.js'; import { readSessionUserRow, refuseAgentAccountCredential } from './service-account-identity.js'; import { refuseInactiveUserSession, SESSION_ADMISSION_ROW_FIELDS } from './user-session-admission.js'; import { LOCKED_ACCOUNT_ROW_FIELDS, refuseLockedAccountSession } from './auth-manager-sign-in-lockout.js'; +import { refuseDevSeedCredentialSession, stampDevSeedCredential } from './dev-seed-credential.js'; import { PLATFORM_IDP_PROVIDER_ID } from './implicit-account-linking.js'; import { PENDING_SSO_SOURCE } from './pending-sso-marker.js'; @@ -120,6 +121,9 @@ export function composeDatabaseHooks( const stamp = async (account: any, ctx: any) => { await clearUnlink(account, ctx); await this.stampIdentitySource(account, ctx); + // The development seed's stamp, on the password credential of an account + // the seed creates (`dev-seed-credential.ts`). Never throws. + await stampDevSeedCredential(this.config.dataEngine as never, account, this.config.logger); }; // [ADR-0151 D2] An AI service account holds no password and no sign-in // provider link. Asked FIRST, before the host's own `create.before`, for @@ -379,6 +383,10 @@ export function composeDatabaseHooks( // session for that account, with the answer password sign-in gives. See // auth-manager-sign-in-lockout.ts. await refuseLockedAccountSession.call(this, session, ctx, userRow); + // A server outside development mode opens no session for an account the + // development seed created while it still has its seed password, on any + // door (`dev-seed-credential.ts`). + await refuseDevSeedCredentialSession(this.config.dataEngine as never, session); const captured = await captureSessionAddress(session); const result = sessionActiveOrgBefore ? await sessionActiveOrgBefore(captured, ctx) : undefined; if (result === false) return false; diff --git a/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts b/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts index 97171743e03..7ca3de5fd2c 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts @@ -68,6 +68,7 @@ import { withSystemReadContext } from './objectql-adapter.js'; import { reconcileMembership, type ReconcileOutcome } from './reconcile-membership.js'; import { isSsoProviderSource, readSsoProviderSignInOptions, ssoProviderIdOfSource } from './sso-sign-in-options.js'; import { shouldStampOwnerVerifiedAtCreation } from './walled-owner-operator-stamp.js'; +import { stageDevSeedCredential } from './dev-seed-credential.js'; /** * The `AuthManager` members the functions below read — every one of them, and @@ -231,6 +232,12 @@ export async function validateAudienceAdmission( ) { this.stageOwnerVerifiedStamp(email); } + // An operator-class creation is the development seed's own (`os dev`'s + // admin, a stack's `demoStaff`): only its provisioning ticket earns the + // class. Its seed stamp is staged here, where the ticket is proven, and + // written when the creation's password credential lands + // (`dev-seed-credential.ts`). + if (email && creationClass === 'operator') await stageDevSeedCredential(email); if (verdict.grantPermissionSet) { const setName = audience.selfRegistrationPermissionSet; if (!setName) { diff --git a/packages/plugins/plugin-auth/src/dev-seed-credential.ts b/packages/plugins/plugin-auth/src/dev-seed-credential.ts new file mode 100644 index 00000000000..a399f97538d --- /dev/null +++ b/packages/plugins/plugin-auth/src/dev-seed-credential.ts @@ -0,0 +1,374 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A production-mode server never accepts a development seed credential. + * + * `os dev` seeds a well-known admin (`AuthPlugin.maybeSeedDevAdmin`) and a + * stack's `demoStaff` (`demo-staff.ts`), all on the development seed password + * (`devSeedAdminPassword()`: `OS_SEED_ADMIN_PASSWORD`, else `admin123`). Those + * credentials belong to the development database. A server that is not in + * development mode refuses them, whoever serves the database — `os start`, + * `os serve`, the image or a custom host — because the refusal lives here, in + * the auth plugin, and not in any one command. + * + * "Production mode" is every `NODE_ENV` but `development`: the one clause the + * seed itself is gated on (`isDevAdminSeedArmed`), read when each check runs. + * + * ## The rules + * + * 1. **The seed password is refused at sign-in, on any account.** A password + * sign-in that submits the development seed password — `admin123`, and the + * value `OS_SEED_ADMIN_PASSWORD` names when it is set — is refused with + * `403 PERMISSION_DENIED` and a sentence naming the operator reset command + * ({@link refuseDevSeedPasswordSignIn}). It is decided on the submitted + * password alone, before any account is read, so the answer is the same + * for every address, one that exists or not: it tells a caller nothing + * about any account. This covers the seeded accounts, any other account on + * that password, and databases seeded before the stamp below existed. + * 2. **The verifier never accepts a seed credential** ({@link + * withDevSeedPasswordRefusal}). Every door that checks a password — + * the sign-in doors, and a password confirmation such as change-password's + * current password — gets "no match" for the seed password, and for the + * password a stamped account still holds from the seed. Those doors then + * answer exactly what a wrong password answers, so a correct seed password + * is never confirmed to a caller. + * 3. **A stamped account opens no new session** ({@link + * refuseDevSeedCredentialSession}). The accounts the seed creates are + * stamped (below). While a stamped account's stored password hash is still + * the one the seed stored, `session.create.before` refuses every session + * for it — password, magic link, one-time code, passkey, social or SSO + * sign-in, impersonation, a minted session — with `403 PERMISSION_DENIED` + * naming the reset command. A custom seed password (`os dev + * --admin-password`, `OS_SEED_ADMIN_PASSWORD`) is caught this way too, + * without the server ever knowing it. + * 4. **No forced change at sign-in.** None of the refusals opens a session in + * which the password could be changed: whoever signed in first could + * perform it. The one way out is the operator's reset on the server, + * `os user set-password` (`operator-password-reset.ts`). + * + * ## The stamp + * + * `sys_user.dev_seed_credential` holds a one-way digest (SHA-256) of the + * password hash the seed stored, never the password: a digest of a salted + * hash opens nothing, and the column is `internal`, so it is never served on + * the generic data path and is only matched by the server. "Still on the seed + * password" is "the stored hash still has this digest": any password change, + * through any door, writes a new salted hash and the stamp stops matching. + * + * It is written once, when the seed creates the account, in development: the + * audience gate (`validateAudienceAdmission`) stages it for an operator-class + * creation, the class only the seed's own provisioning ticket earns + * ({@link stageDevSeedCredential}), and `account.create.after` writes it when + * that creation's password credential lands ({@link stampDevSeedCredential}). + * + * ## What it does not detect + * + * A database seeded before the stamp existed, on a custom seed password, + * carries no stamp and no well-known password, so nothing marks it. Rule 1 + * covers such a database on the default seed password. + */ + +import { defineRequestState } from '@better-auth/core/context'; +import { SystemObjectName } from '@objectstack/spec/system'; +import { devSeedAdminPassword } from './walled-owner-verification-path.js'; +import { recoverInternalFieldsForSystemRead } from './internal-field-readback.js'; +import type { PasswordHasher } from './sign-in-lockout-refusal.js'; + +/** The `sys_user` column the seed stamps. */ +export const DEV_SEED_CREDENTIAL_FIELD = 'dev_seed_credential'; + +/** The development seed password when `OS_SEED_ADMIN_PASSWORD` is unset. */ +export const DEFAULT_DEV_SEED_PASSWORD = 'admin123'; + +/** The command an operator runs on the server to set a new password. */ +export const OPERATOR_PASSWORD_RESET_COMMAND = 'os user set-password'; + +/** + * The refusal a password sign-in meets when it submits the development seed + * password, on a server that is not in development mode. + */ +export const DEV_SEED_PASSWORD_REFUSAL = Object.freeze({ + code: 'PERMISSION_DENIED', + message: + 'This password is the development seed password, and a server that is not in development mode does not ' + + `accept it. An operator sets a new password on the server with \`${OPERATOR_PASSWORD_RESET_COMMAND} \`.`, +}); + +/** + * The refusal a session meets for an account the development seed created + * while its password is still the seed password. + */ +export const DEV_SEED_CREDENTIAL_SESSION_REFUSAL = Object.freeze({ + code: 'PERMISSION_DENIED', + message: + 'This account was created by the development seed and still has its seed password, so a server that is not in ' + + 'development mode opens no session for it. An operator sets a new password on the server with ' + + `\`${OPERATOR_PASSWORD_RESET_COMMAND} \`.`, +}); + +/** + * The better-auth endpoints that sign in with a submitted `password`. The + * verifier (rule 2) covers a door missing here; this list is where the + * refusal names the reset command. + */ +export const PASSWORD_SIGN_IN_PATHS: ReadonlySet = new Set([ + '/sign-in/email', + '/sign-in/username', + '/sign-in/phone-number', +]); + +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const; + +const env = (): Record => + ((globalThis as { process?: { env?: Record } })?.process?.env ?? {}); + +/** + * Whether this process is in development mode: `NODE_ENV === 'development'`, + * the clause the development seed is gated on, read on every call. + */ +export function isDevelopmentMode(): boolean { + return env().NODE_ENV === 'development'; +} + +/** + * Whether `password` is a development seed password: `admin123`, or the value + * `OS_SEED_ADMIN_PASSWORD` sets for this process. + */ +export function isDevSeedPassword(password: unknown): boolean { + if (typeof password !== 'string' || password === '') return false; + return password === DEFAULT_DEV_SEED_PASSWORD || password === devSeedAdminPassword(); +} + +/** The digest a stamp holds for a stored password hash: SHA-256, base64url. */ +export async function devSeedCredentialDigest(storedHash: string): Promise { + const digest = await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(storedHash)); + return Buffer.from(new Uint8Array(digest)).toString('base64url'); +} + +/** The slice of the data engine this module reads and writes through. */ +export interface DevSeedCredentialEngine { + find(object: string, query?: unknown, opts?: unknown): Promise; + update?(object: string, doc: Record, opts?: unknown): Promise; +} + +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>) : []; +} + +// ── Rule 1: the submitted seed password, before any account is read ───────── + +/** + * Refuse a password sign-in that submits a development seed password, on a + * server that is not in development mode. Runs ahead of every other hook, so + * it reads no account and counts toward no lock. Throws the refusal; returns + * otherwise. + */ +export async function refuseDevSeedPasswordSignIn(ctx: { path?: unknown; body?: unknown } | undefined): Promise { + if (isDevelopmentMode()) return; + if (typeof ctx?.path !== 'string' || !PASSWORD_SIGN_IN_PATHS.has(ctx.path)) return; + if (!isDevSeedPassword((ctx.body as { password?: unknown } | undefined)?.password)) return; + const { APIError } = await import('better-auth/api'); + throw new APIError('FORBIDDEN', { code: DEV_SEED_PASSWORD_REFUSAL.code, message: DEV_SEED_PASSWORD_REFUSAL.message }); +} + +// ── Rule 2: the verifier ───────────────────────────────────────────────────── + +/** + * Whether a stamped account still holds `storedHash`, the password hash the + * seed stored for it. Answers the account's id, or `undefined`. + */ +async function stampedHolderOf(engine: DevSeedCredentialEngine, storedHash: string): Promise { + const rows = rowsOf( + await engine.find( + SystemObjectName.USER, + { + where: { [DEV_SEED_CREDENTIAL_FIELD]: await devSeedCredentialDigest(storedHash) }, + fields: ['id'], + limit: 1, + }, + { context: SYSTEM_CTX }, + ), + ); + const id = rows[0]?.id; + return typeof id === 'string' && id ? id : undefined; +} + +/** + * The password pair handed to better-auth, with one change on a server that is + * not in development mode: after the real verification (run in full, so a + * refusal costs what a wrong password costs), a match is answered "no match" + * when the password is a development seed password, or when the hash is the + * one a stamped account still holds from the seed. A read that fails answers + * "no match": a credential that cannot be cleared is not accepted. + */ +export function withDevSeedPasswordRefusal( + hasher: PasswordHasher, + deps: { + engine: () => DevSeedCredentialEngine | undefined; + logger?: () => { warn?(message: string): void } | undefined; + }, +): PasswordHasher { + return { + hash: (password) => hasher.hash(password), + verify: async (args) => { + const verified = await hasher.verify(args); + if (!verified || isDevelopmentMode()) return verified; + if (isDevSeedPassword(args.password)) return false; + const engine = deps.engine(); + if (!engine || typeof engine.find !== 'function') return true; + try { + const holder = await stampedHolderOf(engine, args.hash); + if (!holder) return true; + deps.logger?.()?.warn?.( + `[auth] a password for user ${holder} was refused: the account was created by the development seed and ` + + 'still has its seed password, which a server that is not in development mode does not accept. ' + + `Remedy: set a new password on the server with \`${OPERATOR_PASSWORD_RESET_COMMAND} \`.`, + ); + return false; + } catch { + return false; + } + }, + }; +} + +// ── Rule 3: no session for a stamped account still on its seed password ───── + +/** + * Whether `userId` is a stamped account whose stored password hash is still the + * one the seed stored. One read for an account the seed never stamped (the + * common case); a stamped one adds its credential read. A read that fails + * throws. + */ +export async function isDevSeedCredentialInForce( + engine: DevSeedCredentialEngine, + userId: string, +): Promise { + const stamped = rowsOf( + await engine.find( + SystemObjectName.USER, + { where: { id: userId, [DEV_SEED_CREDENTIAL_FIELD]: { $null: false } }, fields: ['id'], limit: 1 }, + { context: SYSTEM_CTX }, + ), + ); + if (stamped.length === 0) return false; + const accounts = rowsOf( + await engine.find( + SystemObjectName.ACCOUNT, + { where: { user_id: userId, provider_id: 'credential' }, fields: ['id', 'password'], limit: 1 }, + { context: SYSTEM_CTX }, + ), + ); + await recoverInternalFieldsForSystemRead(engine as never, SystemObjectName.ACCOUNT, accounts, ['password']); + const hash = accounts[0]?.password; + if (typeof hash !== 'string' || hash === '') return false; + return (await stampedHolderOf(engine, hash)) === userId; +} + +/** + * `session.create.before`: refuse every session for a stamped account still on + * its seed password, on a server that is not in development mode. A read that + * fails refuses the session `503`, as the other session refusals do. + */ +export async function refuseDevSeedCredentialSession( + engine: DevSeedCredentialEngine | undefined, + session: unknown, +): Promise { + if (isDevelopmentMode()) return; + const userId = (session as { userId?: unknown } | null | undefined)?.userId; + if (typeof userId !== 'string' || !userId || !engine || typeof engine.find !== 'function') return; + let held: boolean; + try { + held = await isDevSeedCredentialInForce(engine, userId); + } catch (cause) { + const { APIError } = await import('better-auth/api'); + const err = new APIError('SERVICE_UNAVAILABLE', { + code: 'SERVICE_UNAVAILABLE', + message: 'The account could not be read to open a session. Try again.', + }); + (err as { cause?: unknown }).cause = cause; + throw err; + } + if (!held) return; + const { APIError } = await import('better-auth/api'); + throw new APIError('FORBIDDEN', { + code: DEV_SEED_CREDENTIAL_SESSION_REFUSAL.code, + message: DEV_SEED_CREDENTIAL_SESSION_REFUSAL.message, + }); +} + +// ── The stamp, written when the seed creates an account ───────────────────── + +/** The address of the creation the audience gate admitted as the seed's own. */ +const stagedSeedCreation = defineRequestState<{ email: string } | undefined>(() => undefined); + +/** + * Stage the stamp for the creation running in this request: called by the + * audience gate for an operator-class creation, the class only the + * development seed's provisioning ticket earns. Nothing is staged outside + * development mode. Never throws. + */ +export async function stageDevSeedCredential(email: string): Promise { + if (!isDevelopmentMode() || typeof email !== 'string' || email.trim() === '') return; + try { + await stagedSeedCreation.set({ email: email.trim().toLowerCase() }); + } catch { + /* no request state is open: nothing is staged */ + } +} + +/** + * `account.create.after`: when this request staged the seed's creation and the + * account that landed is its password credential, write the stamp on the + * account's user. Never throws: the account exists either way, and a stamp + * that did not land is reported at `error`, naming what it costs. + */ +export async function stampDevSeedCredential( + engine: DevSeedCredentialEngine | undefined, + account: unknown, + logger?: { error?(message: string, meta?: unknown): void }, +): Promise { + let staged: { email: string } | undefined; + try { + staged = await stagedSeedCreation.get(); + } catch { + return; + } + if (!staged || !isDevelopmentMode()) return; + const row = account as Record | null | undefined; + const providerId = row?.providerId ?? row?.provider_id; + const userId = row?.userId ?? row?.user_id; + if (providerId !== 'credential' || typeof userId !== 'string' || !userId) return; + if (!engine || typeof engine.find !== 'function' || typeof engine.update !== 'function') return; + try { + const users = rowsOf( + await engine.find(SystemObjectName.USER, { where: { id: userId }, fields: ['id', 'email'], limit: 1 }, { context: SYSTEM_CTX }), + ); + if (String(users[0]?.email ?? '').toLowerCase() !== staged.email) return; + let hash = row?.password; + if ((typeof hash !== 'string' || hash === '') && typeof row?.id === 'string') { + const accounts = [{ id: row.id } as Record]; + await recoverInternalFieldsForSystemRead(engine as never, SystemObjectName.ACCOUNT, accounts, ['password']); + hash = accounts[0].password; + } + if (typeof hash !== 'string' || hash === '') { + throw new Error('the credential row carries no password hash'); + } + await engine.update( + SystemObjectName.USER, + { id: userId, [DEV_SEED_CREDENTIAL_FIELD]: await devSeedCredentialDigest(hash) }, + { context: SYSTEM_CTX }, + ); + await stagedSeedCreation.set(undefined); + } catch (e) { + logger?.error?.( + `[auth] the development seed created user ${userId} but its seed stamp was NOT written: the account works, ` + + 'and on a server that is not in development mode it is refused only while its password is the default ' + + `seed password, not a custom one. Remedy: set a new password with \`${OPERATOR_PASSWORD_RESET_COMMAND} \` ` + + 'before serving this database outside development, or delete the database and seed it again.', + { error: (e as Error)?.message }, + ); + } +} diff --git a/packages/plugins/plugin-auth/src/index.ts b/packages/plugins/plugin-auth/src/index.ts index 3e2688922d5..83dc57e4ded 100644 --- a/packages/plugins/plugin-auth/src/index.ts +++ b/packages/plugins/plugin-auth/src/index.ts @@ -86,6 +86,20 @@ export * from './default-org-bootstrap-once.js'; // has to run the probe on its own schedule. export * from './account-identity-preflight.js'; export * from './set-initial-password.js'; +// The operator's password reset on the server (`os user set-password`): a +// server outside development mode refuses a development seed credential and +// opens no session to change it in, so the CLI sets the new password against +// the project database through this one function. +export { + setOperatorPassword, + findAccountByEmail, + operatorPasswordRefusal, + OPERATOR_PASSWORD_MIN_LENGTH, + OPERATOR_PASSWORD_MAX_LENGTH, + type OperatorPasswordResetEngine, + type OperatorPasswordResetOutcome, + type OperatorPasswordResetRefusalReason, +} from './operator-password-reset.js'; export * from './admin-user-endpoints.js'; export * from './admin-ban-endpoints.js'; export * from './platform-admin-gate.js'; diff --git a/packages/plugins/plugin-auth/src/managed-extension-fields.ts b/packages/plugins/plugin-auth/src/managed-extension-fields.ts index da4fc10c37b..20234489691 100644 --- a/packages/plugins/plugin-auth/src/managed-extension-fields.ts +++ b/packages/plugins/plugin-auth/src/managed-extension-fields.ts @@ -91,6 +91,12 @@ export const MANAGED_EXTENSION_FIELDS: Readonly` (`@objectstack/cli`). + * + * A server that is not in development mode refuses a development seed + * credential (`dev-seed-credential.ts`) and opens no session in which it could + * be changed, because whoever signed in first could change it. This is the way + * out: the operator, who holds the server, sets a new password directly. + * + * ## What one reset does + * + * - **Refuses a password a server would refuse.** A development seed password + * is never set, and the length is held to better-auth's bounds (8 to 128). + * - **Writes the account's password credential** (`sys_account`, provider + * `credential`) with better-auth's own hash, the one every server verifies. + * An account with no password credential is refused: this sets a password, + * it does not add a way to sign in that the account did not have. + * - **Clears the seed stamp** (`sys_user.dev_seed_credential`), stamps + * `password_changed_at`, and clears a sign-in lock, so the new password + * signs in at once. + * - **Ends every session and revokes every API key** of the account, as an + * administrator's forced reset with revocation does + * (`forced-reset-revocation.ts`, `admin_password_reset`): credentials minted + * under the old password do not outlive it. + * + * It asks for no password change at the next sign-in: the operator chose the + * password. + */ + +import { SystemObjectName } from '@objectstack/spec/system'; +import { DEV_SEED_CREDENTIAL_FIELD, isDevSeedPassword } from './dev-seed-credential.js'; +import { revokeSessionsAndApiKeys } from './forced-reset-revocation.js'; + +/** better-auth's default bounds for a password (`emailAndPassword.minPasswordLength` / `maxPasswordLength`). */ +export const OPERATOR_PASSWORD_MIN_LENGTH = 8; +export const OPERATOR_PASSWORD_MAX_LENGTH = 128; + +/** The slice of the data engine the reset reads and writes through. */ +export interface OperatorPasswordResetEngine { + find(object: string, query?: unknown, opts?: unknown): Promise; + update(object: string, doc: Record, opts?: unknown): Promise; +} + +/** Why a reset was refused. Nothing was written. */ +export type OperatorPasswordResetRefusalReason = + | 'password_too_short' + | 'password_too_long' + | 'dev_seed_password' + | 'no_user' + | 'no_local_password'; + +/** What one reset did. */ +export type OperatorPasswordResetOutcome = + | { + outcome: 'set'; + userId: string; + /** Sessions ended and API keys revoked. */ + sessionsEnded: number; + apiKeysRevoked: number; + /** `false` when a session or key could not be read or revoked; the password is set either way. */ + revocationComplete: boolean; + } + | { outcome: 'refused'; reason: OperatorPasswordResetRefusalReason; message: string }; + +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const; + +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>) : []; +} + +/** Why `password` cannot be set, or `undefined` when it can. */ +export function operatorPasswordRefusal( + password: string, +): { reason: OperatorPasswordResetRefusalReason; message: string } | undefined { + if (password.length < OPERATOR_PASSWORD_MIN_LENGTH) { + return { + reason: 'password_too_short', + message: `The password must be at least ${OPERATOR_PASSWORD_MIN_LENGTH} characters.`, + }; + } + if (password.length > OPERATOR_PASSWORD_MAX_LENGTH) { + return { + reason: 'password_too_long', + message: `The password must be at most ${OPERATOR_PASSWORD_MAX_LENGTH} characters.`, + }; + } + if (isDevSeedPassword(password)) { + return { + reason: 'dev_seed_password', + message: 'That is the development seed password, which a server outside development mode refuses. Choose another.', + }; + } + return undefined; +} + +/** The account `email` names, by its stored (lower-case) address. */ +export async function findAccountByEmail( + engine: OperatorPasswordResetEngine, + email: string, +): Promise<{ id: string; email: string } | undefined> { + const address = email.trim().toLowerCase(); + if (!address) return undefined; + const rows = rowsOf( + await engine.find(SystemObjectName.USER, { where: { email: address }, fields: ['id', 'email'], limit: 1 }, { context: SYSTEM_CTX }), + ); + const row = rows[0]; + return typeof row?.id === 'string' && row.id ? { id: row.id, email: String(row.email ?? address) } : undefined; +} + +/** + * Set `password` on the account `email` names. Refusals write nothing; a set + * password is reported with what the revocation did. + */ +export async function setOperatorPassword( + engine: OperatorPasswordResetEngine, + input: { email: string; password: string }, + opts: { logger?: { warn(message: string): void }; now?: () => Date } = {}, +): Promise { + const refusal = operatorPasswordRefusal(input.password); + if (refusal) return { outcome: 'refused', ...refusal }; + + const user = await findAccountByEmail(engine, input.email); + if (!user) { + return { outcome: 'refused', reason: 'no_user', message: `No account has the email address ${input.email.trim()}.` }; + } + const credential = rowsOf( + await engine.find( + SystemObjectName.ACCOUNT, + { where: { user_id: user.id, provider_id: 'credential' }, fields: ['id'], limit: 1 }, + { context: SYSTEM_CTX }, + ), + )[0]; + if (typeof credential?.id !== 'string' || !credential.id) { + return { + outcome: 'refused', + reason: 'no_local_password', + message: `The account ${user.email} has no password sign-in (it signs in another way), so no password was set.`, + }; + } + + const { hashPassword } = await import('better-auth/crypto'); + const now = (opts.now ?? (() => new Date()))(); + await engine.update( + SystemObjectName.ACCOUNT, + { id: credential.id, password: await hashPassword(input.password), updated_at: now }, + { context: SYSTEM_CTX }, + ); + await engine.update( + SystemObjectName.USER, + { + id: user.id, + [DEV_SEED_CREDENTIAL_FIELD]: null, + password_changed_at: now, + failed_login_count: 0, + locked_until: null, + }, + { context: SYSTEM_CTX }, + ); + const revocation = await revokeSessionsAndApiKeys(engine, user.id, { logger: opts.logger }); + return { + outcome: 'set', + userId: user.id, + sessionsEnded: revocation.sessions, + apiKeysRevoked: revocation.apiKeys, + revocationComplete: revocation.complete, + }; +} From 29409bbdd160faa927200c0a6620ccdefd56ad96 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:03:25 +0000 Subject: [PATCH 02/12] wip(auth): door pins, CLI test, changeset and docs for the development seed credential refusal Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../dev-seed-credential-production-refusal.md | 25 ++ content/docs/deployment/self-hosting.mdx | 8 + .../user/set-password.integration.test.ts | 208 ++++++++++ .../dev-seed-credential-production.test.ts | 372 ++++++++++++++++++ .../src/dev-seed-credential.test.ts | 119 ++++++ 5 files changed, 732 insertions(+) create mode 100644 .changeset/dev-seed-credential-production-refusal.md create mode 100644 packages/cli/src/commands/user/set-password.integration.test.ts create mode 100644 packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts create mode 100644 packages/plugins/plugin-auth/src/dev-seed-credential.test.ts diff --git a/.changeset/dev-seed-credential-production-refusal.md b/.changeset/dev-seed-credential-production-refusal.md new file mode 100644 index 00000000000..5506af28870 --- /dev/null +++ b/.changeset/dev-seed-credential-production-refusal.md @@ -0,0 +1,25 @@ +--- +'@objectstack/plugin-auth': patch +'@objectstack/platform-objects': patch +'@objectstack/cli': patch +--- + +fix(auth)!: a server outside development mode refuses a development seed credential, and `os user set-password` sets a new one on the server + +Clause-②: yes (narrowing) — narrowed: on a server whose `NODE_ENV` is not `development`, a password sign-in that submits the development seed password (`admin123`, or the value `OS_SEED_ADMIN_PASSWORD` sets) is refused on every account, and an account the development seed created opens no session while its stored password is still the one it was seeded with. Widened: the `os user set-password` command, the `sys_user.dev_seed_credential` column, and new `@objectstack/plugin-auth` exports `setOperatorPassword`, `findAccountByEmail`, `operatorPasswordRefusal`, `OPERATOR_PASSWORD_MIN_LENGTH`, `OPERATOR_PASSWORD_MAX_LENGTH` and the types `OperatorPasswordResetEngine`, `OperatorPasswordResetOutcome`, `OperatorPasswordResetRefusalReason`. +Metadata-protocol: none + + + +**BREAKING** for a deployment that serves, outside development mode, a database `os dev` seeded, or any account whose password is the development seed password. Such a sign-in is refused. Set a new password on the server with `os user set-password `; the refusal names the command. A server in development mode (`os dev`) is unchanged. + +**The rule: a server outside development mode never accepts a development seed credential.** Development mode is `NODE_ENV=development`, the condition the development seed itself runs under. The rule lives in the auth plugin, so `os start`, `os serve`, the image and a custom host all apply it. + +- **The seed password is refused at sign-in, on any account.** A password sign-in with the development seed password answers `403 PERMISSION_DENIED`, and its message names `os user set-password`. It is decided on the submitted password alone, before any account is read, so every address gets the same answer. This covers the seeded admin, the stack's `demoStaff`, any other account on that password, and a database seeded by an earlier release. +- **The accounts the development seed creates are marked.** `os dev`'s admin and each `demoStaff` account carry `sys_user.dev_seed_credential`: a one-way digest of the password hash the seed stored, never the password. The column is never returned on reads, and any password change stops it matching. +- **A marked account still on its seed password opens no session**, on any sign-in door (password, emailed link, one-time code, passkey, social or SSO, impersonation), whatever password it was seeded with, `os dev --admin-password` included. A password check never confirms that seed password: a password sign-in answers it as a wrong password. +- **No password change is offered at sign-in.** Whoever signed in first could perform it. The way out is the operator's reset on the server. + +**`os user set-password `** sets the account's password in the project database. It reads the new password from a terminal prompt (twice, not echoed) or from standard input with `--password-stdin`, never from the command line, and takes `--database-url` like the other one-shot commands. It refuses a development seed password and a password outside 8 to 128 characters, and writes nothing on a refusal. It clears the account's development seed mark and any sign-in lock, records the change time, and ends every session and revokes every API key of the account, as an administrator's forced reset does. It asks for no password change at the next sign-in. + +**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. diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index 305af41567a..198fc8b2ecd 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -617,6 +617,14 @@ on empty development databases. That seed is hard-gated to `NODE_ENV=development`: it is a development convenience, never a production recovery path. +Nor does a server outside development mode **accept** a development seed +credential. A sign-in with the development seed password is refused on every +account, and an account `os dev` seeded (its admin and the stack's `demoStaff`) +opens no session while it still has the password it was seeded with. If you +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. + ### A seeded directory opens no bootstrap window Both paths above assume the deployment's **first login** is still ahead of it. diff --git a/packages/cli/src/commands/user/set-password.integration.test.ts b/packages/cli/src/commands/user/set-password.integration.test.ts new file mode 100644 index 00000000000..0e50d89d98f --- /dev/null +++ b/packages/cli/src/commands/user/set-password.integration.test.ts @@ -0,0 +1,208 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `os user set-password` — the operator's reset, run through oclif against a + * real SQLite file, as an operator runs it on the server. + * + * The fixture is a project database holding one account with a password + * credential, one live session and one API key, written through the same + * declaration boot the command takes. Each case runs the command in process + * and reads the file back on a boot of its own: the stored hash is checked + * against the stored-hash format a server verifies, the session and the key by the columns + * that end and revoke them. + */ + +import { afterAll, beforeAll, beforeEach, afterEach, describe, expect, it, vi } from 'vitest'; +import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { Readable } from 'node:stream'; +import { fileURLToPath } from 'node:url'; +import { randomBytes, scrypt } from 'node:crypto'; +import { createIdentityObjectsPlugin } from '@objectstack/plugin-auth'; +import { isExitSignal } from '../../utils/format.js'; +import { bootSchemaStack } from '../../utils/schema-migrate.js'; +import { composeProviderForDeclarations } from '../../utils/schema-migration-plugins.js'; +import UserSetPassword from './set-password.js'; + +// Pay the first load of what `bootSchemaStack` and the command reach through +// dynamic `import()`s at MODULE LOAD, outside any clocked case. +import '@objectstack/service-datasource'; +import '@objectstack/runtime'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const CLI_ROOT = resolve(HERE, '..', '..', '..'); +const CASE_TIMEOUT_MS = 120_000; +const OVERRIDING_ENV = ['OS_DATABASE_URL', 'DATABASE_URL', 'TURSO_DATABASE_URL', 'OS_DATABASE_DRIVER', 'OS_HOME'] as const; +const SYSTEM = { context: { isSystem: true } }; +const EMAIL = 'admin@example.com'; +const OLD_PASSWORD = 'Old!Passw0rd-seeded'; +const NEW_PASSWORD = 'New!Passw0rd-operator'; + +/** + * The stored-hash format every server verifies (better-auth's `hashPassword`: + * `{saltHex}:{keyHex}`, scrypt N=16384 r=16 p=1, 64-byte key over the + * NFKC-normalised password), spelled out with node's own scrypt so this file + * checks the command against the format, not against the library it calls. + */ +const SCRYPT = { N: 16384, r: 16, p: 1, maxmem: 128 * 16384 * 16 * 2 } as const; +const scryptKey = (password: string, saltHex: string): Promise => + new Promise((resolveKey, reject) => + scrypt(password.normalize('NFKC'), saltHex, 64, SCRYPT, (err, key) => (err ? reject(err) : resolveKey(key.toString('hex')))), + ); +const hashPassword = async (password: string): Promise => { + const salt = randomBytes(16).toString('hex'); + return `${salt}:${await scryptKey(password, salt)}`; +}; +const verifyPassword = async ({ hash, password }: { hash: string; password: string }): Promise => { + const [salt, key] = hash.split(':'); + return Boolean(salt && key) && (await scryptKey(password, salt)) === key; +}; + +let dir: string; +let templateDb: string; +const savedEnv: Record = {}; +const savedCwd = process.cwd(); + +async function bootIdentity(dbFile: string) { + return bootSchemaStack({ + jsonOutput: false, + databaseUrl: `file:${dbFile}`, + projectRoot: dir, + extraPlugins: [composeProviderForDeclarations(createIdentityObjectsPlugin())], + }); +} + +/** What the file holds for the account, read on a boot of its own. */ +async function readAccount(dbFile: string) { + const stack = await bootIdentity(dbFile); + try { + const ql = stack.kernel.getService('objectql'); + const [user] = await ql.find('sys_user', { where: { email: EMAIL } }, SYSTEM); + const [account] = await ql.find('sys_account', { where: { user_id: user.id, provider_id: 'credential' } }, SYSTEM); + const values = await ql.resolveInternalField('sys_account', [account.id], 'password'); + const [session] = await ql.find('sys_session', { where: { user_id: user.id } }, SYSTEM); + const [key] = await ql.find('sys_api_key', { where: { user_id: user.id } }, SYSTEM); + return { + hash: String(values.get(account.id)), + sessionRevoked: Boolean(session?.revoked_at), + keyRevoked: key?.revoked === true || key?.revoked === 1, + }; + } finally { + await stack.shutdown(); + } +} + +/** Run the command in process with `stdin` as standard input; its exit status and what it printed. */ +async function run(argv: string[], stdin?: string): Promise<{ exitCode: number; out: string }> { + const savedStdin = Object.getOwnPropertyDescriptor(process, 'stdin'); + if (stdin !== undefined) { + Object.defineProperty(process, 'stdin', { value: Readable.from([Buffer.from(stdin)]), configurable: true }); + } + const printed: string[] = []; + const capture = ((chunk: unknown, ...rest: unknown[]) => { + printed.push(String(chunk)); + const cb = rest.find((a) => typeof a === 'function') as (() => void) | undefined; + if (cb) cb(); + return true; + }) as typeof process.stdout.write; + const spies = [ + vi.spyOn(process.stdout, 'write').mockImplementation(capture), + vi.spyOn(process.stderr, 'write').mockImplementation(capture), + vi.spyOn(console, 'log').mockImplementation((...a: unknown[]) => { printed.push(a.join(' ')); }), + vi.spyOn(console, 'warn').mockImplementation((...a: unknown[]) => { printed.push(a.join(' ')); }), + vi.spyOn(console, 'error').mockImplementation((...a: unknown[]) => { printed.push(a.join(' ')); }), + ]; + let exitCode = 0; + try { + await UserSetPassword.run(argv, { root: CLI_ROOT }); + } catch (error) { + if (!isExitSignal(error)) throw error; + exitCode = (error as { oclif?: { exit?: number } }).oclif?.exit ?? 1; + } finally { + for (const spy of spies) spy.mockRestore(); + if (savedStdin) Object.defineProperty(process, 'stdin', savedStdin); + } + return { exitCode, out: printed.join('') }; +} + +let caseSeq = 0; +function prepareCase(): string { + caseSeq += 1; + const dbFile = join(dir, `case-${caseSeq}.db`); + copyFileSync(templateDb, dbFile); + return dbFile; +} + +beforeAll(async () => { + for (const key of [...OVERRIDING_ENV, 'NODE_ENV', 'OS_SEED_ADMIN_PASSWORD'] as const) savedEnv[key] = process.env[key]; + for (const key of [...OVERRIDING_ENV, 'OS_SEED_ADMIN_PASSWORD'] as const) delete process.env[key]; + process.env.NODE_ENV = 'production'; + dir = mkdtempSync(join(tmpdir(), 'os-user-set-password-')); + mkdirSync(join(dir, 'data'), { recursive: true }); + templateDb = join(dir, 'data', 'template.db'); + process.chdir(dir); + const stack = await bootIdentity(templateDb); + try { + const ql = stack.kernel.getService('objectql'); + const user = await ql.insert('sys_user', { name: 'Admin', email: EMAIL, email_verified: true }, SYSTEM); + await ql.insert( + 'sys_account', + { user_id: user.id, provider_id: 'credential', account_id: user.id, password: await hashPassword(OLD_PASSWORD) }, + SYSTEM, + ); + await ql.insert( + 'sys_session', + { user_id: user.id, token: 'tok_live_session', expires_at: new Date(Date.now() + 86_400_000) }, + SYSTEM, + ); + await ql.insert('sys_api_key', { name: 'automation', key: 'k'.repeat(64), prefix: 'osk_test', user_id: user.id }, SYSTEM); + } finally { + await stack.shutdown(); + } +}, CASE_TIMEOUT_MS); + +afterAll(() => { + process.chdir(savedCwd); + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + rmSync(dir, { recursive: true, force: true }); +}); + +beforeEach(() => { + process.exitCode = undefined; +}); +afterEach(() => { + process.exitCode = undefined; +}); + +describe('os user set-password', () => { + it('sets the password from standard input with the hash a server verifies, and ends the account\'s sessions and API keys', async () => { + const dbFile = prepareCase(); + const result = await run([EMAIL, '--password-stdin', '--database-url', `file:${dbFile}`], `${NEW_PASSWORD}\n`); + expect(result.exitCode, result.out).toBe(0); + const after = await readAccount(dbFile); + expect(await verifyPassword({ hash: after.hash, password: NEW_PASSWORD })).toBe(true); + expect(await verifyPassword({ hash: after.hash, password: OLD_PASSWORD })).toBe(false); + expect({ sessionRevoked: after.sessionRevoked, keyRevoked: after.keyRevoked }).toEqual({ sessionRevoked: true, keyRevoked: true }); + }, CASE_TIMEOUT_MS); + + it('refuses the development seed password and writes nothing', async () => { + const dbFile = prepareCase(); + const before = await readAccount(dbFile); + const result = await run([EMAIL, '--password-stdin', '--database-url', `file:${dbFile}`], 'admin123\n'); + expect(result.exitCode).toBe(1); + expect(await readAccount(dbFile)).toEqual(before); + }, CASE_TIMEOUT_MS); + + it('refuses an address no account holds before it asks for a password', async () => { + const dbFile = prepareCase(); + const before = await readAccount(dbFile); + const result = await run(['nobody@nowhere.example', '--database-url', `file:${dbFile}`]); + expect(result.exitCode).toBe(1); + expect(result.out).toContain('nobody@nowhere.example'); + expect(await readAccount(dbFile)).toEqual(before); + }, CASE_TIMEOUT_MS); +}); diff --git a/packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts b/packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts new file mode 100644 index 00000000000..ce3d976458e --- /dev/null +++ b/packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts @@ -0,0 +1,372 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A server that is not in development mode never accepts a development seed + * credential — pinned at the doors, over a database the development boot + * seeded. + * + * ## The composition + * + * The development boot `demo-staff-provisioning.test.ts` pins: a real + * `ObjectKernel`, a real ObjectQL engine on in-memory SQLite, the real + * `AuthPlugin` (the development admin seed and one `demoStaff` account) and + * the real `SecurityPlugin`, booted with `NODE_ENV=development` as `os dev` + * boots. `NODE_ENV` then leaves development and a second `AuthManager` is + * built over the same engine: the database a production server serves, as + * `os start` would serve the file `os dev` wrote. + * + * ## What each case reads + * + * The answer the door gives (status, code, sentence) and the `sys_session` + * rows it left. A refusal is asserted by its ADR-0112 `code` and `status`, by + * the operator reset command its sentence names (the one sentence a client + * reads to act), and by the session it did not create. + */ + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ObjectKernel, 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 { AuthManager } from './auth-manager.js'; +import { recoverInternalFieldsForSystemRead } from './internal-field-readback.js'; +import { DEV_SEED_CREDENTIAL_FIELD, devSeedCredentialDigest } from './dev-seed-credential.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/magic-link'; +import '@better-auth/core/context'; +import '@better-auth/core/error'; + +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 CUSTOM_SEED_PASSWORD = 'Custom!Seed-Passw0rd-42'; +const NEW_PASSWORD = 'Operator!Chosen-Passw0rd-7'; +const STAFF_EMAIL = 'staff1@demo.example'; +const RESET_COMMAND = 'os user set-password'; + +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; + +function sqliteDriverPlugin(): Plugin { + return { + name: 'test.driver.sqlite', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService( + 'driver.default', + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, 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('; '); + +/** The refusal's envelope: status, machine code and sentence. */ +const answerOf = async (res: Response) => { + const text = await res.clone().text(); + let body: { code?: unknown; message?: unknown } = {}; + try { + body = JSON.parse(text); + } catch { + /* not JSON */ + } + return { status: res.status, code: body.code, message: typeof body.message === 'string' ? body.message : undefined }; +}; + +const savedEnv: Partial> = {}; +let kernel: ObjectKernel | undefined; + +beforeEach(() => { + for (const key of ENV_KEYS) { + savedEnv[key] = process.env[key]; + delete process.env[key]; + } +}); + +afterEach(async () => { + try { + await kernel?.shutdown(); + } catch { + /* already down */ + } + kernel = undefined; + for (const key of ENV_KEYS) { + if (savedEnv[key] === undefined) delete process.env[key]; + else process.env[key] = savedEnv[key]; + } +}); + +/** A manager's doors, driven as `Request`s through `handleRequest`. */ +function doorsOf(manager: AuthManager) { + const post = (path: string, body: unknown, headers: Record = {}) => + manager.handleRequest( + new Request(`${AUTH}${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json', origin: ORIGIN, ...headers }, + body: JSON.stringify(body ?? {}), + }), + ); + const get = (url: string, headers: Record = {}) => + manager.handleRequest(new Request(url.startsWith('http') ? url : `${AUTH}${url}`, { method: 'GET', headers: { origin: ORIGIN, ...headers } })); + const signIn = (email: string, password: string) => post('/sign-in/email', { email, password }); + /** The session a cookie resolves to: its user id, or `null`. */ + const sessionUser = async (cookie: string): Promise => { + const res = await get('/get-session', { cookie }); + const body = (await res.json().catch(() => null)) as { user?: { id?: string } } | null; + return body?.user?.id ?? null; + }; + return { post, get, signIn, sessionUser }; +} + +/** + * The development boot: `os dev` seeding the admin and one demo account into a + * fresh database. `adminPassword` is `os dev --admin-password`. + */ +async function bootDevelopment(options: { adminPassword?: string } = {}) { + process.env.NODE_ENV = 'development'; + if (options.adminPassword) process.env.OS_SEED_ADMIN_PASSWORD = options.adminPassword; + kernel = new ObjectKernel({ logger: { level: 'silent' } }); + await kernel.use(sqliteDriverPlugin()); + await kernel.use(new ObjectQLPlugin()); + await kernel.use( + new AuthPlugin({ secret: SECRET, baseUrl: ORIGIN, demoStaff: [{ name: 'Demo Staff 1', email: STAFF_EMAIL }] as never }), + ); + await kernel.use(new SecurityPlugin()); + 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 userId = async (email: string) => (await rows('sys_user', { email }))[0]?.id as string; + return { ql, manager, rows, userId, doors: doorsOf(manager) }; +} + +type Seeded = Awaited>; + +/** + * Leave development: the server that serves the database next. The seed's env + * is not passed on, as `os start` does not pass it. + */ +function productionServer(seeded: Seeded, options: { mails?: any[] } = {}) { + process.env.NODE_ENV = 'production'; + delete process.env.OS_SEED_ADMIN_PASSWORD; + const manager = new AuthManager({ + secret: SECRET, + baseUrl: ORIGIN, + dataEngine: seeded.ql as never, + ...(options.mails + ? { + plugins: { magicLink: true }, + emailService: { + async sendTemplate(input: any) { + options.mails!.push(input); + return { id: 'mail_test', status: 'sent' }; + }, + async send(input: any) { + options.mails!.push(input); + return { id: 'mail_test', status: 'sent' }; + }, + isConfigured: () => true, + }, + } + : {}), + } as never); + return { manager, doors: doorsOf(manager) }; +} + +/** Whether `userId` carries the seed stamp: matched by the server, as the column is never served. */ +async function isStamped(seeded: Seeded, userId: string): Promise { + const found = await seeded.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 stored password hash of `userId`'s password credential. */ +async function storedHash(seeded: Seeded, userId: string): Promise { + const accounts = await seeded.rows('sys_account', { user_id: userId, provider_id: 'credential' }); + await recoverInternalFieldsForSystemRead(seeded.ql as never, 'sys_account', accounts, ['password']); + return String(accounts[0]?.password); +} + +async function sessionCount(seeded: Seeded, userId: string): Promise { + return (await seeded.rows('sys_session', { user_id: userId })).length; +} + +const expectSeedPasswordRefusal = (answer: { status: number; code: unknown; message?: string }) => { + expect({ status: answer.status, code: answer.code }).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + expect(answer.message).toContain(RESET_COMMAND); +}; + +describe('a server outside development mode refuses a development seed credential', () => { + it('development mode is unchanged: the seed admin and a demo account sign in with the seed password, and each carries the seed stamp', async () => { + const seeded = await bootDevelopment(); + const adminId = await seeded.userId(SEED_EMAIL); + const staffId = await seeded.userId(STAFF_EMAIL); + expect(await isStamped(seeded, adminId)).toBe(true); + expect(await isStamped(seeded, staffId)).toBe(true); + for (const email of [SEED_EMAIL, STAFF_EMAIL]) { + const res = await seeded.doors.signIn(email, SEED_PASSWORD); + expect(res.status, `${email}: ${await res.clone().text()}`).toBe(200); + } + }); + + it('the seed stamp is a digest of the stored password hash, never the password', async () => { + const seeded = await bootDevelopment(); + const adminId = await seeded.userId(SEED_EMAIL); + const byDigest = await seeded.ql.find( + 'sys_user', + { where: { [DEV_SEED_CREDENTIAL_FIELD]: await devSeedCredentialDigest(await storedHash(seeded, adminId)) }, fields: ['id'], context: SYS } as never, + ); + expect((byDigest as any[]).map((r) => r.id)).toEqual([adminId]); + const byPassword = await seeded.ql.find( + 'sys_user', + { where: { [DEV_SEED_CREDENTIAL_FIELD]: SEED_PASSWORD }, fields: ['id'], context: SYS } as never, + ); + expect(byPassword).toEqual([]); + // Never served on a read. + const [row] = await seeded.rows('sys_user', { id: adminId }); + expect(DEV_SEED_CREDENTIAL_FIELD in row).toBe(false); + }); + + it('refuses a sign-in that submits the seed password to the seed admin, naming the operator reset command, and opens no session', async () => { + const seeded = await bootDevelopment(); + const adminId = await seeded.userId(SEED_EMAIL); + const before = await sessionCount(seeded, adminId); + const server = productionServer(seeded); + expectSeedPasswordRefusal(await answerOf(await server.doors.signIn(SEED_EMAIL, SEED_PASSWORD))); + expect(await sessionCount(seeded, adminId)).toBe(before); + }); + + it('refuses a sign-in that submits the seed password to a demo account', async () => { + const seeded = await bootDevelopment(); + const staffId = await seeded.userId(STAFF_EMAIL); + const before = await sessionCount(seeded, staffId); + const server = productionServer(seeded); + expectSeedPasswordRefusal(await answerOf(await server.doors.signIn(STAFF_EMAIL, SEED_PASSWORD))); + expect(await sessionCount(seeded, staffId)).toBe(before); + }); + + it('answers the seed password the same for an address no account holds: it is decided on the password alone', async () => { + const seeded = await bootDevelopment(); + const server = productionServer(seeded); + const known = await answerOf(await server.doors.signIn(SEED_EMAIL, SEED_PASSWORD)); + const unknown = await answerOf(await server.doors.signIn('nobody@nowhere.example', SEED_PASSWORD)); + expect(unknown).toEqual(known); + }); + + it('refuses the seed password on an account that carries no seed stamp, as a database seeded before the stamp does', async () => { + const seeded = await bootDevelopment(); + const adminId = await seeded.userId(SEED_EMAIL); + await seeded.ql.update('sys_user', { id: adminId, [DEV_SEED_CREDENTIAL_FIELD]: null }, { context: SYS } as never); + expect(await isStamped(seeded, adminId)).toBe(false); + const server = productionServer(seeded); + expectSeedPasswordRefusal(await answerOf(await server.doors.signIn(SEED_EMAIL, SEED_PASSWORD))); + }); + + it('refuses a stamped account on a custom seed password exactly as a wrong password, and opens no session', async () => { + const seeded = await bootDevelopment({ adminPassword: CUSTOM_SEED_PASSWORD }); + const adminId = await seeded.userId(SEED_EMAIL); + // Development: the custom seed password signs in. + expect((await seeded.doors.signIn(SEED_EMAIL, CUSTOM_SEED_PASSWORD)).status).toBe(200); + const before = await sessionCount(seeded, adminId); + const server = productionServer(seeded); + const refused = await answerOf(await server.doors.signIn(SEED_EMAIL, CUSTOM_SEED_PASSWORD)); + const wrong = await answerOf(await server.doors.signIn(SEED_EMAIL, 'Wr0ng!Guess-Zebra-7731')); + expect(refused).toEqual(wrong); + expect(refused.status).toBe(401); + expect(await sessionCount(seeded, adminId)).toBe(before); + }); + + it('opens no session for a stamped account still on its seed password on a door that takes no password (the emailed sign-in link)', async () => { + const seeded = await bootDevelopment({ adminPassword: CUSTOM_SEED_PASSWORD }); + const adminId = await seeded.userId(SEED_EMAIL); + const before = await sessionCount(seeded, adminId); + const mails: any[] = []; + const server = productionServer(seeded, { mails }); + const sent = await server.doors.post('/sign-in/magic-link', { email: SEED_EMAIL }); + expect(sent.status, `sign-in/magic-link: ${await sent.clone().text()}`).toBe(200); + const mail = mails.find((m) => m?.data?.magicLinkUrl); + expect(mail, 'the sign-in link was mailed').toBeDefined(); + const url = new URL(String(mail.data.magicLinkUrl)); + url.searchParams.delete('callbackURL'); + const answer = await answerOf(await server.doors.get(url.toString())); + expectSeedPasswordRefusalOnSession(answer); + expect(await sessionCount(seeded, adminId)).toBe(before); + }); + + it('after `os user set-password`, the new password signs in, the seed stamp is gone, and the development session is ended', async () => { + const seeded = await bootDevelopment({ adminPassword: CUSTOM_SEED_PASSWORD }); + const adminId = await seeded.userId(SEED_EMAIL); + const devSignIn = await seeded.doors.signIn(SEED_EMAIL, CUSTOM_SEED_PASSWORD); + expect(devSignIn.status).toBe(200); + const devCookie = cookieHeader(devSignIn); + const server = productionServer(seeded); + + const outcome = await setOperatorPassword(seeded.ql as never, { email: SEED_EMAIL, password: NEW_PASSWORD }); + expect(outcome).toMatchObject({ outcome: 'set', userId: adminId, revocationComplete: true }); + expect(await isStamped(seeded, adminId)).toBe(false); + + const res = await server.doors.signIn(SEED_EMAIL, NEW_PASSWORD); + expect(res.status, await res.clone().text()).toBe(200); + expect(await server.doors.sessionUser(cookieHeader(res))).toBe(adminId); + expect(await server.doors.sessionUser(devCookie)).toBeNull(); + // The old seed password stays refused. + expect((await server.doors.signIn(SEED_EMAIL, CUSTOM_SEED_PASSWORD)).status).toBe(401); + }); + + it('the operator reset refuses a password a server would refuse, and an address no account holds, and writes nothing', async () => { + const seeded = await bootDevelopment(); + const adminId = await seeded.userId(SEED_EMAIL); + process.env.NODE_ENV = 'production'; + const hash = await storedHash(seeded, adminId); + const refusals = await Promise.all([ + setOperatorPassword(seeded.ql as never, { email: SEED_EMAIL, password: SEED_PASSWORD }), + setOperatorPassword(seeded.ql as never, { email: SEED_EMAIL, password: 'short1!' }), + setOperatorPassword(seeded.ql as never, { email: SEED_EMAIL, password: 'x'.repeat(129) }), + setOperatorPassword(seeded.ql as never, { email: 'nobody@nowhere.example', password: NEW_PASSWORD }), + ]); + expect(refusals.map((r) => (r.outcome === 'refused' ? r.reason : r.outcome))).toEqual([ + 'dev_seed_password', + 'password_too_short', + 'password_too_long', + 'no_user', + ]); + expect(await storedHash(seeded, adminId)).toBe(hash); + expect(await isStamped(seeded, adminId)).toBe(true); + }); +}); + +function expectSeedPasswordRefusalOnSession(answer: { status: number; code: unknown; message?: string }) { + expect({ status: answer.status, code: answer.code }).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + expect(answer.message).toContain(RESET_COMMAND); +} diff --git a/packages/plugins/plugin-auth/src/dev-seed-credential.test.ts b/packages/plugins/plugin-auth/src/dev-seed-credential.test.ts new file mode 100644 index 00000000000..c2059612e78 --- /dev/null +++ b/packages/plugins/plugin-auth/src/dev-seed-credential.test.ts @@ -0,0 +1,119 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The development seed credential rules, unit by unit: which passwords are + * seed passwords, which doors the pre-lookup refusal reads, and what the + * verifier answers. The door-level pins are in + * `dev-seed-credential-production.test.ts`. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + DEV_SEED_CREDENTIAL_FIELD, + devSeedCredentialDigest, + isDevSeedPassword, + refuseDevSeedPasswordSignIn, + withDevSeedPasswordRefusal, +} from './dev-seed-credential.js'; + +const ENV_KEYS = ['NODE_ENV', 'OS_SEED_ADMIN_PASSWORD'] as const; +const saved: Partial> = {}; + +beforeEach(() => { + for (const key of ENV_KEYS) { + saved[key] = process.env[key]; + delete process.env[key]; + } + process.env.NODE_ENV = 'production'; +}); + +afterEach(() => { + for (const key of ENV_KEYS) { + if (saved[key] === undefined) delete process.env[key]; + else process.env[key] = saved[key]; + } +}); + +/** A pair that verifies `password === hash`, counting its calls. */ +const plainHasher = () => { + const verify = vi.fn(async ({ hash, password }: { hash: string; password: string }) => hash === password); + return { hash: async (password: string) => password, verify }; +}; + +/** An engine whose `sys_user` holds the given stamps. */ +const engineWithStamps = (stamps: Record) => ({ + find: vi.fn(async (_object: string, query: any) => { + const wanted = query?.where?.[DEV_SEED_CREDENTIAL_FIELD]; + return Object.entries(stamps) + .filter(([, stamp]) => stamp === wanted) + .map(([id]) => ({ id })); + }), +}); + +describe('the development seed password', () => { + it('is admin123, and the value OS_SEED_ADMIN_PASSWORD names when it is set', () => { + expect(isDevSeedPassword('admin123')).toBe(true); + expect(isDevSeedPassword('Custom!Seed-1')).toBe(false); + process.env.OS_SEED_ADMIN_PASSWORD = 'Custom!Seed-1'; + expect(isDevSeedPassword('Custom!Seed-1')).toBe(true); + expect(isDevSeedPassword('admin123')).toBe(true); + expect(isDevSeedPassword('')).toBe(false); + expect(isDevSeedPassword(undefined)).toBe(false); + }); +}); + +describe('a password sign-in that submits the seed password is refused before any account is read', () => { + const refusal = (path: string, password: unknown) => + refuseDevSeedPasswordSignIn({ path, body: { email: 'a@b.example', password } }).then( + () => undefined, + (e: any) => ({ status: e?.statusCode, code: e?.body?.code }), + ); + + it('on every password sign-in door, with 403 PERMISSION_DENIED', async () => { + for (const path of ['/sign-in/email', '/sign-in/username', '/sign-in/phone-number']) { + expect(await refusal(path, 'admin123')).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + } + }); + + it('not on another password, another door, or in development mode', async () => { + expect(await refusal('/sign-in/email', 'S3cure!Passw0rd')).toBeUndefined(); + expect(await refusal('/sign-up/email', 'admin123')).toBeUndefined(); + process.env.NODE_ENV = 'development'; + expect(await refusal('/sign-in/email', 'admin123')).toBeUndefined(); + }); +}); + +describe('the verifier never accepts a seed credential outside development mode', () => { + it('answers no match for the seed password after running the real verification', async () => { + const base = plainHasher(); + const verifier = withDevSeedPasswordRefusal(base, { engine: () => engineWithStamps({}) }); + expect(await verifier.verify({ hash: 'admin123', password: 'admin123' })).toBe(false); + expect(base.verify).toHaveBeenCalledTimes(1); + }); + + it('answers no match for the hash a stamped account still holds from the seed', async () => { + const engine = engineWithStamps({ usr_seeded: await devSeedCredentialDigest('Custom!Seed-1') }); + const warn = vi.fn(); + const verifier = withDevSeedPasswordRefusal(plainHasher(), { engine: () => engine, logger: () => ({ warn }) }); + expect(await verifier.verify({ hash: 'Custom!Seed-1', password: 'Custom!Seed-1' })).toBe(false); + expect(warn.mock.calls[0]?.[0]).toContain('os user set-password'); + }); + + it('answers a match for any other password, and no match when the stamp cannot be read', async () => { + const verifier = withDevSeedPasswordRefusal(plainHasher(), { engine: () => engineWithStamps({}) }); + expect(await verifier.verify({ hash: 'S3cure!Passw0rd', password: 'S3cure!Passw0rd' })).toBe(true); + expect(await verifier.verify({ hash: 'S3cure!Passw0rd', password: 'other' })).toBe(false); + const failing = withDevSeedPasswordRefusal(plainHasher(), { + engine: () => ({ find: async () => { throw new Error('store down'); } }), + }); + expect(await failing.verify({ hash: 'S3cure!Passw0rd', password: 'S3cure!Passw0rd' })).toBe(false); + }); + + it('answers what the underlying verifier answers in development mode', async () => { + process.env.NODE_ENV = 'development'; + const engine = engineWithStamps({ usr_seeded: await devSeedCredentialDigest('admin123') }); + const verifier = withDevSeedPasswordRefusal(plainHasher(), { engine: () => engine }); + expect(await verifier.verify({ hash: 'admin123', password: 'admin123' })).toBe(true); + expect(engine.find).not.toHaveBeenCalled(); + }); +}); From b5ba8cb2037e902a898a19310758e67eaa6afd7c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:21:30 +0000 Subject: [PATCH 03/12] wip(platform-objects): translate the development seed credential column Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../src/apps/translations/ar.objects.generated.ts | 4 ++++ .../src/apps/translations/de.objects.generated.ts | 4 ++++ .../src/apps/translations/en.objects.generated.ts | 4 ++++ .../src/apps/translations/es-ES.objects.generated.ts | 4 ++++ .../src/apps/translations/fr.objects.generated.ts | 4 ++++ .../src/apps/translations/ja-JP.objects.generated.ts | 4 ++++ .../src/apps/translations/ko.objects.generated.ts | 4 ++++ .../src/apps/translations/pt-BR.objects.generated.ts | 4 ++++ .../src/apps/translations/ru.objects.generated.ts | 4 ++++ .../src/apps/translations/zh-CN.objects.generated.ts | 4 ++++ .../src/apps/translations/zh-Hant.objects.generated.ts | 4 ++++ 11 files changed, 44 insertions(+) diff --git a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts index 55e6d0fcdcf..d43c3baa859 100644 --- a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts @@ -72,6 +72,10 @@ export const arObjects: NonNullable = { label: "يجب تغيير كلمة المرور", help: "عند التفعيل، يجب على المستخدم تغيير كلمة المرور قبل أن يتمكن من المتابعة. يُفعَّل عندما ينشئ المسؤول الحساب أو يستورده أو يعيد تعيين كلمة مروره؛ يديره النظام." }, + dev_seed_credential: { + label: "بيانات اعتماد البذرة التطويرية", + help: "يُعيَّن على حساب أنشأته البذرة التطويرية. ما دامت كلمة مروره هي كلمة مرور البذرة، يرفض خادم الإنتاج تسجيل دخوله وأي جلسة جديدة؛ يعيّن os user set-password كلمة مرور جديدة ويمسحه. يُديره النظام؛ ولا يُعاد عند القراءة أبدًا." + }, mfa_required_at: { label: "تاريخ فرض المصادقة متعددة العوامل", help: "وقت تطبيق المصادقة متعددة العوامل الإلزامية على هذا المستخدم لأول مرة (بداية مهلة السماح). يستند إليه mfa_required؛ يديره النظام." diff --git a/packages/platform-objects/src/apps/translations/de.objects.generated.ts b/packages/platform-objects/src/apps/translations/de.objects.generated.ts index ff148fd61b1..a4735bf9d40 100644 --- a/packages/platform-objects/src/apps/translations/de.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.objects.generated.ts @@ -72,6 +72,10 @@ export const deObjects: NonNullable = { label: "Passwortänderung erforderlich", help: "Wenn aktiviert, muss der Benutzer sein Passwort ändern, bevor er fortfahren kann. Wird aktiviert, wenn ein Administrator das Konto anlegt oder importiert oder sein Passwort zurücksetzt; vom System verwaltet." }, + dev_seed_credential: { + label: "Entwicklungs-Seed-Zugangsdaten", + help: "Wird bei einem Konto gesetzt, das der Entwicklungs-Seed angelegt hat. Solange sein Passwort noch das Seed-Passwort ist, verweigert ein Produktionsserver seine Anmeldung und jede neue Sitzung; os user set-password setzt ein neues Passwort und löscht den Wert. Vom System verwaltet; wird beim Lesen nie zurückgegeben." + }, mfa_required_at: { label: "MFA erforderlich seit", help: "Wann die erzwungene MFA erstmals für diesen Benutzer galt (Uhr für die Übergangsfrist). Grundlage für mfa_required; vom System verwaltet." diff --git a/packages/platform-objects/src/apps/translations/en.objects.generated.ts b/packages/platform-objects/src/apps/translations/en.objects.generated.ts index 01dacfa65d8..3fd9a0a8ada 100644 --- a/packages/platform-objects/src/apps/translations/en.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.objects.generated.ts @@ -72,6 +72,10 @@ export const enObjects: NonNullable = { label: "Must Change Password", help: "When on, the user must change their password before they can continue. Turned on when an administrator creates or imports the account, or resets its password; system-managed." }, + dev_seed_credential: { + label: "Development Seed Credential", + help: "Set on an account the development seed created. While its password is still the seed password, a production server refuses its sign-in and every new session; os user set-password sets a new password and clears it. System-managed; never returned on reads." + }, mfa_required_at: { label: "MFA Required At", help: "When enforced MFA first applied to this user (grace-period clock). Backs mfa_required; system-managed." diff --git a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts index d3aaa149e99..f7dbba19879 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts @@ -72,6 +72,10 @@ export const esESObjects: NonNullable = { label: "Debe cambiar la contraseña", help: "Si es true, el usuario queda bloqueado (403 PASSWORD_RESET_REQUIRED) hasta que cambie su contraseña. Lo establecen las rutas de administración de usuarios; gestionado por el sistema." }, + dev_seed_credential: { + label: "Credencial de semilla de desarrollo", + help: "Se establece en una cuenta que creó la semilla de desarrollo. Mientras su contraseña siga siendo la contraseña de la semilla, un servidor de producción rechaza su inicio de sesión y toda nueva sesión; os user set-password establece una contraseña nueva y lo borra. Gestionado por el sistema; nunca se devuelve en las lecturas." + }, mfa_required_at: { label: "MFA exigido desde", help: "Cuándo se aplicó por primera vez el MFA obligatorio a este usuario (inicio del período de gracia). Sirve de base a mfa_required; gestionado por el sistema." diff --git a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts index 06778c96beb..55c348b10ef 100644 --- a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts @@ -72,6 +72,10 @@ export const frObjects: NonNullable = { label: "Doit changer de mot de passe", help: "Lorsque cette option est activée, l’utilisateur doit changer son mot de passe avant de pouvoir continuer. Activée lorsqu’un administrateur crée ou importe le compte, ou en réinitialise le mot de passe ; gérée par le système." }, + dev_seed_credential: { + label: "Identifiant d'amorçage de développement", + help: "Défini sur un compte créé par l'amorçage de développement. Tant que son mot de passe est encore celui de l'amorçage, un serveur de production refuse sa connexion et toute nouvelle session ; os user set-password définit un nouveau mot de passe et l'efface. Géré par le système ; jamais renvoyé en lecture." + }, mfa_required_at: { label: "MFA exigée le", help: "Date à laquelle la MFA obligatoire s’est appliquée pour la première fois à cet utilisateur (point de départ du délai de grâce). Sert de base à mfa_required ; géré par le système." diff --git a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts index bc466437933..0ad1d04b257 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts @@ -72,6 +72,10 @@ export const jaJPObjects: NonNullable = { label: "パスワード変更必須", help: "true の場合、パスワードを変更するまでユーザーはブロックされます(403 PASSWORD_RESET_REQUIRED)。管理者のユーザー管理ルートが設定します。システム管理。" }, + dev_seed_credential: { + label: "開発シード資格情報", + help: "開発シードが作成したアカウントに設定されます。パスワードがシードのパスワードのままである間、本番サーバーはそのサインインと新しいセッションをすべて拒否します。os user set-password で新しいパスワードを設定すると消去されます。システム管理。読み取りでは返されません。" + }, mfa_required_at: { label: "MFA 強制適用日時", help: "強制 MFA がこのユーザーに最初に適用された日時(猶予期間の起点)。mfa_required の基準になります。システム管理。" diff --git a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts index 44d1c702a5f..46878310abe 100644 --- a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts @@ -72,6 +72,10 @@ export const koObjects: NonNullable = { label: "비밀번호 변경 필요", help: "켜져 있으면 사용자가 계속하기 전에 비밀번호를 변경해야 합니다. 관리자가 계정을 만들거나 가져오거나 비밀번호를 재설정하면 켜집니다. 시스템이 관리합니다." }, + dev_seed_credential: { + label: "개발 시드 자격 증명", + help: "개발 시드가 만든 계정에 설정됩니다. 비밀번호가 아직 시드 비밀번호인 동안 프로덕션 서버는 해당 계정의 로그인과 모든 새 세션을 거부합니다. os user set-password로 새 비밀번호를 설정하면 지워집니다. 시스템에서 관리하며 읽기 결과로 반환되지 않습니다." + }, mfa_required_at: { label: "MFA 필수 적용 시각", help: "이 사용자에게 MFA 강제가 처음 적용된 시각(유예 기간 기준)입니다. mfa_required의 기준이 되며 시스템이 관리합니다." diff --git a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts index 954330ca772..4e657547d59 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts @@ -72,6 +72,10 @@ export const ptBRObjects: NonNullable = { label: "Deve alterar a senha", help: "Quando ativado, o usuário precisa alterar a senha antes de continuar. É ativado quando um administrador cria ou importa a conta, ou redefine a senha dela; gerenciado pelo sistema." }, + dev_seed_credential: { + label: "Credencial de seed de desenvolvimento", + help: "Definido em uma conta criada pelo seed de desenvolvimento. Enquanto a senha ainda for a senha do seed, um servidor de produção recusa o login e toda nova sessão; os user set-password define uma nova senha e o limpa. Gerenciado pelo sistema; nunca retornado em leituras." + }, mfa_required_at: { label: "MFA exigida desde", help: "Quando a MFA obrigatória passou a valer para este usuário (relógio do período de carência). Base de mfa_required; gerenciado pelo sistema." diff --git a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts index 95f841a0f57..aa4c939af66 100644 --- a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts @@ -72,6 +72,10 @@ export const ruObjects: NonNullable = { label: "Требуется смена пароля", help: "Если включено, пользователь должен сменить пароль, прежде чем продолжить. Включается, когда администратор создаёт или импортирует учётную запись либо сбрасывает её пароль; управляется системой." }, + dev_seed_credential: { + label: "Учётные данные начального заполнения для разработки", + help: "Устанавливается для учётной записи, созданной начальным заполнением для разработки. Пока её пароль остаётся паролем заполнения, рабочий сервер отклоняет её вход и любой новый сеанс; os user set-password задаёт новый пароль и очищает значение. Управляется системой; никогда не возвращается при чтении." + }, mfa_required_at: { label: "MFA требуется с", help: "Когда к этому пользователю впервые применили обязательную MFA (отсчёт льготного периода). Используется для mfa_required; управляется системой." diff --git a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts index 713e40bab25..fa2516d654b 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts @@ -72,6 +72,10 @@ export const zhCNObjects: NonNullable = { label: "须修改密码", help: "开启后,用户必须先修改密码才能继续使用。管理员创建账号、导入用户或重置密码时会自动开启;系统维护。" }, + dev_seed_credential: { + label: "开发种子凭据", + help: "开发种子创建的账号会带上此标记。只要其密码仍是种子密码,生产服务器就拒绝其登录和任何新会话;使用 os user set-password 设置新密码后会清除。系统维护;读取时从不返回。" + }, mfa_required_at: { label: "MFA 强制生效时间", help: "强制 MFA 首次对该用户生效的时间(宽限期计时起点)。支撑 mfa_required;系统维护。" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts index b1b707dea97..ed6a2ac8ae8 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts @@ -72,6 +72,10 @@ export const zhHantObjects: NonNullable = { label: "須修改密碼", help: "開啟後,使用者必須先修改密碼才能繼續使用。管理員建立帳號、匯入使用者或重設密碼時會自動開啟;系統維護。" }, + dev_seed_credential: { + label: "開發種子憑證", + help: "開發種子建立的帳號會帶上此標記。只要其密碼仍是種子密碼,正式環境伺服器就拒絕其登入及任何新工作階段;使用 os user set-password 設定新密碼後會清除。系統維護;讀取時從不傳回。" + }, mfa_required_at: { label: "MFA 強制生效時間", help: "強制 MFA 首次對該使用者生效的時間(寬限期計時起點)。支撐 mfa_required;系統維護。" From 94a0d2d44082ccc1647a866ccf6a8fb543997d0f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 05:56:43 +0000 Subject: [PATCH 04/12] fix(auth): the seed stamp logs through the error channel, its column is bounded, and the session read-count pin names the stamp read Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../cli/src/commands/user/set-password.ts | 2 +- .../src/identity/sys-user.object.ts | 1 + .../src/auth-manager-database-hooks.ts | 4 +++- .../first-session-membership-ordering.test.ts | 20 +++++++++++++++---- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/commands/user/set-password.ts b/packages/cli/src/commands/user/set-password.ts index 935a9d33e33..96851931c9b 100644 --- a/packages/cli/src/commands/user/set-password.ts +++ b/packages/cli/src/commands/user/set-password.ts @@ -41,7 +41,7 @@ export default class UserSetPassword extends Command { static override examples = [ '<%= config.bin %> user set-password admin@example.com', - 'printf %s "$NEW_PASSWORD" | <%= config.bin %> user set-password admin@example.com --password-stdin', + '<%= config.bin %> user set-password admin@example.com --password-stdin', ]; static override args = { diff --git a/packages/platform-objects/src/identity/sys-user.object.ts b/packages/platform-objects/src/identity/sys-user.object.ts index cf7c06486c6..c3f2daf09ad 100644 --- a/packages/platform-objects/src/identity/sys-user.object.ts +++ b/packages/platform-objects/src/identity/sys-user.object.ts @@ -1355,6 +1355,7 @@ export const SysUser = ObjectSchema.create({ dev_seed_credential: Field.text({ label: 'Development Seed Credential', required: false, + maxLength: 64, // a SHA-256 digest in base64url is 43 characters; keyed by the index below readonly: true, internal: true, group: 'System', diff --git a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts index b0309251173..1671bb477bd 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts @@ -123,7 +123,9 @@ export function composeDatabaseHooks( await this.stampIdentitySource(account, ctx); // The development seed's stamp, on the password credential of an account // the seed creates (`dev-seed-credential.ts`). Never throws. - await stampDevSeedCredential(this.config.dataEngine as never, account, this.config.logger); + await stampDevSeedCredential(this.config.dataEngine as never, account, { + error: (message, meta) => this.audienceLogError(message, meta as Record | undefined), + }); }; // [ADR-0151 D2] An AI service account holds no password and no sign-in // provider link. Asked FIRST, before the host's own `create.before`, for diff --git a/packages/plugins/plugin-auth/src/first-session-membership-ordering.test.ts b/packages/plugins/plugin-auth/src/first-session-membership-ordering.test.ts index 7425d5c15f3..fb66e61bb42 100644 --- a/packages/plugins/plugin-auth/src/first-session-membership-ordering.test.ts +++ b/packages/plugins/plugin-auth/src/first-session-membership-ordering.test.ts @@ -57,6 +57,17 @@ const DEFAULT_ORG = 'org_default'; /** The AI service account check `session.create.before` runs first (ADR-0151 D2). */ const PRINCIPAL_KIND_READ = ['sys_user', expect.objectContaining({ where: { id: USER }, limit: 1 })]; +/** + * The development seed credential check on the same user's row + * (`dev-seed-credential.ts`), which a server outside development mode runs + * before any membership logic: this suite runs under `NODE_ENV=test`. + */ +const DEV_SEED_STAMP_READ = [ + 'sys_user', + expect.objectContaining({ where: { id: USER, dev_seed_credential: { $null: false } }, limit: 1 }), + expect.anything(), +]; + interface MemberRow { id: string; organization_id: string; @@ -227,9 +238,10 @@ describe("[#8247 rule 2] a user's FIRST session settles the membership before re // is refused by the reconciler before it touches the store, and the // re-read never runs because nothing was bound. expect(engine.findOne).toHaveBeenCalledTimes(2); - // The one `find` is the AI service account check on the user's own row - // (ADR-0151 D2), which runs before any membership logic. - expect(engine.find.mock.calls).toEqual([PRINCIPAL_KIND_READ]); + // The two `find`s are the AI service account check on the user's own row + // (ADR-0151 D2) and the development seed credential check, both before + // any membership logic. + expect(engine.find.mock.calls).toEqual([PRINCIPAL_KIND_READ, DEV_SEED_STAMP_READ]); }); }); @@ -331,7 +343,7 @@ describe("[#8247 rule 2] a user's FIRST session settles the membership before re const hooks = hooksFor({ engine, defaultOrgId: DEFAULT_ORG }); await hooks.session.create.before({ userId: USER }, {}); expect(engine.findOne).toHaveBeenCalledTimes(2); - expect(engine.find.mock.calls).toEqual([PRINCIPAL_KIND_READ]); + expect(engine.find.mock.calls).toEqual([PRINCIPAL_KIND_READ, DEV_SEED_STAMP_READ]); }); it('a creation staged in ANOTHER request does not reach this sign-in', async () => { From f3eb2cf0e70cc2640d48b3eaae233f647392492f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:00:25 +0000 Subject: [PATCH 05/12] fix(auth): the seed stamp's sink keeps a warn fallback, the set-password suite pays its loads at module top, and the tenant audit census counts the new writes Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../docs/permissions/tenant-audit-census.mdx | 32 +++++++++---------- ...08-tenant-audit-write-call-sites.counts.md | 19 ++++++----- .../user/set-password.integration.test.ts | 5 +++ .../src/auth-manager-database-hooks.ts | 3 +- .../plugin-auth/src/dev-seed-credential.ts | 11 ++++--- 5 files changed, 40 insertions(+), 30 deletions(-) diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index 26ca0364604..4fc48c8a443 100644 --- a/content/docs/permissions/tenant-audit-census.mdx +++ b/content/docs/permissions/tenant-audit-census.mdx @@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way. The same holds twice over for the context. An options argument spelled as a literal can be read; one spelled `options`, `{ ...opts }`, or handed through a -forwarding shim cannot, and **59 of the 322 sites are spelled that way**. A +forwarding shim cannot, and **59 of the 325 sites are spelled that way**. A context resolved from an inline literal or a local `const` can be tested for `isSystem`; one arriving from a helper call cannot. @@ -197,10 +197,10 @@ reproduce them. Where it disagrees, it disagrees on the page: | carried figure | where it survives | this census | | :--- | :--- | ---: | -| 175 write call sites | quoted in the merged changeset | **322** | +| 175 write call sites | quoted in the merged changeset | **325** | | 24 carrying no tenant context | quoted in the merged changeset | **3** provable and tenancy-enabled; **32** more whose options argument is unreadable | -| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **227 of 322** decidable, **95** undecidable | -| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 181 decidably elevated, 0 decidably not, 129 undecidable | +| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **227 of 325** decidable, **98** undecidable | +| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 184 decidably elevated, 0 decidably not, 129 undecidable | | 141 and 132, two independent re-derivations | the card that filed this work | — | **The differences are not reconciled, and deliberately so.** The old census's @@ -217,11 +217,11 @@ would report a smaller number and would not say so. The fourth row is the one worth flagging to anyone citing it. **The 135 / 77% figure has no surviving corroboration anywhere in the tree.** This census reads -181 of 322 (56%) as decidably elevated, with 129 more whose elevation is a +184 of 325 (57%) as decidably elevated, with 129 more whose elevation is a run-time fact — so the claim is neither confirmed nor refuted, and the honest answer is that a static reading cannot settle it. -⇒ **Cite `3 / 322`, and say what it is**: the sites whose options argument was +⇒ **Cite `3 / 325`, and say what it is**: the sites whose options argument was READ and holds no tenant context, against a decidably tenancy-enabled object. That is the control's provable yield surface. ⛔ Do not cite it as "the sites without tenant context" — **32 further sites** have an options argument this @@ -233,23 +233,23 @@ cannot read, and they are neither in nor out. | what | count | | :--- | ---: | -| write call sites on the application surface | **322** | +| write call sites on the application surface | **325** | | …whose object name is statically decidable | 227 | -| …whose object name is chosen at run time | 95 | +| …whose object name is chosen at run time | 98 | | …against an object with tenancy ENABLED | 220 | | …against an object that declares tenancy off | 7 | -| threading a tenant context | 251 | +| threading a tenant context | 254 | | PROVABLY carrying none (options read, no context key) | **12** | | …of those, against a decidably tenancy-enabled object | **3** | | options argument UNREADABLE — may or may not carry one | 59 | | …of those, against a decidably tenancy-enabled object | 32 | -| threading a decidably ELEVATED (`isSystem`) context | 181 | +| threading a decidably ELEVATED (`isSystem`) context | 184 | | threading a context that is decidably NOT elevated | 0 | | threading a context whose elevation is a run-time fact | 129 | | how the instrument reached the site | count | | :--- | ---: | -| receiver carried a readable engine type | 255 | +| receiver carried a readable engine type | 258 | | receiver erased, placed by the object NAME | 57 | | receiver erased, placed by an `object: string` PARAMETER | 5 | | receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 | @@ -257,7 +257,7 @@ cannot read, and they are neither in nor out. | object name spelled inline | 141 | | object name spelled through a `const` | 86 | | object name is an `object: string` parameter | 10 | -| object name is some other run-time expression | 85 | +| object name is some other run-time expression | 88 | ### Subtractions the census could NOT defend — enforced @@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-16 at `94cb58c3d`. +Measured on 2026-11-17 at `94a0d2d44`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1186 | -| engine-shaped types recognised | 142 | +| tracked non-test sources scanned | 1192 | +| engine-shaped types recognised | 144 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 323 | +| same-named calls subtracted as non-engine | 327 | {/* END GENERATED: tenant-audit-census */} diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md index f70dc7b1180..d6194c1e85e 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md @@ -33,17 +33,17 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution. | Measure | Value | |---|---:| -| Write call sites | 322 | +| Write call sites | 325 | | Object name statically decidable | 227 | -| Object name chosen at run time | 95 | +| Object name chosen at run time | 98 | | Against a tenancy-enabled object | 220 | | Against an object declaring tenancy off | 7 | -| Threading a tenant context | 251 | +| Threading a tenant context | 254 | | Provably carrying none | 12 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 59 | | …and decidably tenancy-enabled | 32 | -| Threading a decidably elevated context | 181 | +| Threading a decidably elevated context | 184 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 129 | @@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-16 at `94cb58c3d`. +Measured on 2026-11-17 at `94a0d2d44`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1186 | -| engine-shaped types recognised | 142 | +| tracked non-test sources scanned | 1192 | +| engine-shaped types recognised | 144 | | declared objects in the registry | 137 | -| same-named calls subtracted as non-engine | 323 | +| same-named calls subtracted as non-engine | 327 | ## Every site @@ -162,6 +162,7 @@ Measured on 2026-11-16 at `94cb58c3d`. | `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.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 | | `packages/plugins/plugin-auth/src/forced-reset-revocation.ts` | `update` | `SystemObjectName.API_KEY` | undecidable | elevated | 1 | @@ -182,6 +183,8 @@ Measured on 2026-11-16 at `94cb58c3d`. | `packages/plugins/plugin-auth/src/objectql-adapter.ts` | `delete` | `objectName` | undecidable | PROVABLY NONE | 5 | | `packages/plugins/plugin-auth/src/objectql-adapter.ts` | `insert` | `objectName` | undecidable | options unreadable | 2 | | `packages/plugins/plugin-auth/src/objectql-adapter.ts` | `update` | `objectName` | undecidable | options unreadable | 5 | +| `packages/plugins/plugin-auth/src/operator-password-reset.ts` | `update` | `SystemObjectName.ACCOUNT` | undecidable | elevated | 1 | +| `packages/plugins/plugin-auth/src/operator-password-reset.ts` | `update` | `SystemObjectName.USER` | undecidable | elevated | 1 | | `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_team` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_team_member` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_user_permission_set` | enabled | elevated | 1 | diff --git a/packages/cli/src/commands/user/set-password.integration.test.ts b/packages/cli/src/commands/user/set-password.integration.test.ts index 0e50d89d98f..b1358561122 100644 --- a/packages/cli/src/commands/user/set-password.integration.test.ts +++ b/packages/cli/src/commands/user/set-password.integration.test.ts @@ -28,7 +28,12 @@ import UserSetPassword from './set-password.js'; // Pay the first load of what `bootSchemaStack` and the command reach through // dynamic `import()`s at MODULE LOAD, outside any clocked case. import '@objectstack/service-datasource'; +import '@objectstack/driver-sql'; +import '@objectstack/driver-turso'; import '@objectstack/runtime'; +import '@objectstack/platform-objects/plugin'; +import '@objectstack/plugin-security'; +import '@objectstack/rest'; const HERE = dirname(fileURLToPath(import.meta.url)); const CLI_ROOT = resolve(HERE, '..', '..', '..'); diff --git a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts index 1671bb477bd..2d2343177c6 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-database-hooks.ts @@ -124,7 +124,8 @@ export function composeDatabaseHooks( // The development seed's stamp, on the password credential of an account // the seed creates (`dev-seed-credential.ts`). Never throws. await stampDevSeedCredential(this.config.dataEngine as never, account, { - error: (message, meta) => this.audienceLogError(message, meta as Record | undefined), + error: (message, meta) => this.audienceLogError(message, meta), + warn: (message, meta) => this.config.logger?.warn?.(message, meta), }); }; // [ADR-0151 D2] An AI service account holds no password and no sign-in diff --git a/packages/plugins/plugin-auth/src/dev-seed-credential.ts b/packages/plugins/plugin-auth/src/dev-seed-credential.ts index a399f97538d..5355f57851d 100644 --- a/packages/plugins/plugin-auth/src/dev-seed-credential.ts +++ b/packages/plugins/plugin-auth/src/dev-seed-credential.ts @@ -328,7 +328,7 @@ export async function stageDevSeedCredential(email: string): Promise { export async function stampDevSeedCredential( engine: DevSeedCredentialEngine | undefined, account: unknown, - logger?: { error?(message: string, meta?: unknown): void }, + logger?: { error?(message: string, meta?: Record): void; warn(message: string, meta?: Record): void }, ): Promise { let staged: { email: string } | undefined; try { @@ -363,12 +363,13 @@ export async function stampDevSeedCredential( ); await stagedSeedCreation.set(undefined); } catch (e) { - logger?.error?.( + const message = `[auth] the development seed created user ${userId} but its seed stamp was NOT written: the account works, ` + 'and on a server that is not in development mode it is refused only while its password is the default ' + `seed password, not a custom one. Remedy: set a new password with \`${OPERATOR_PASSWORD_RESET_COMMAND} \` ` - + 'before serving this database outside development, or delete the database and seed it again.', - { error: (e as Error)?.message }, - ); + + 'before serving this database outside development, or delete the database and seed it again.'; + const meta = { error: (e as Error)?.message }; + if (logger?.error) logger.error(message, meta); + else logger?.warn(message, meta); } } From 2ba2eb95d0dc00b5fc9436860b248442759700f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 07:30:46 +0000 Subject: [PATCH 06/12] test(dogfood): the colleague directory read leaves out an internal field, served to nobody Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../test/colleague-lookup-over-mcp.dogfood.test.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/qa/dogfood/test/colleague-lookup-over-mcp.dogfood.test.ts b/packages/qa/dogfood/test/colleague-lookup-over-mcp.dogfood.test.ts index 228cf5c0b24..97578fe3ea5 100644 --- a/packages/qa/dogfood/test/colleague-lookup-over-mcp.dogfood.test.ts +++ b/packages/qa/dogfood/test/colleague-lookup-over-mcp.dogfood.test.ts @@ -297,9 +297,14 @@ describe('a member\'s agent finds a colleague through the read-only sys_user ove // The served directory set the PR states, read off the live row: the // `Admin` group is the only thing withheld. // Read off the declaration, never listed here: every declared field - // outside the group, the set the PR body and the changeset enumerate. + // outside the group, the set the PR body and the changeset enumerate. An + // `internal` field is served to nobody on the generic data path, whatever + // its group, so it is no part of either read. const served = fieldsOf(agentRows, uid.colleague); - const directory = Object.keys(SysUser.fields as Record).filter((f) => !ADMIN_GROUP.includes(f)).sort(); + const directory = Object.entries(SysUser.fields as Record) + .filter(([f, field]) => !ADMIN_GROUP.includes(f) && field.internal !== true) + .map(([f]) => f) + .sort(); expect(served).toEqual(directory); expect(served).toEqual(expect.arrayContaining(['id', 'name', 'email'])); }); From 2b39170b75c0fd819f911adad88f0d39224e5a0b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 11:07:56 +0000 Subject: [PATCH 07/12] chore(census): regenerate the plugin-auth tenant audit shard over the merged tree The three plugin-auth write call sites this branch adds are placed in the per-package shard main now carries; the page holds no live total. Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../plugins/plugin-auth.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) 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 f0ba430bd55..6ed2a1666c7 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 98 | +| Write call sites | 101 | | Object name statically decidable | 58 | -| Object name chosen at run time | 40 | +| Object name chosen at run time | 43 | | Object name spelled inline | 47 | | Object name spelled through a `const` | 11 | | Object name is an `object: string` parameter | 2 | -| Object name is some other run-time expression | 38 | +| Object name is some other run-time expression | 41 | | Against a tenancy-enabled object | 56 | | Against an object declaring tenancy off | 2 | -| Threading a tenant context | 55 | +| Threading a tenant context | 58 | | Provably carrying none (options read, no context key) | 15 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 28 | | …and decidably tenancy-enabled | 16 | -| Threading a decidably elevated (`isSystem`) context | 38 | +| Threading a decidably elevated (`isSystem`) context | 41 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 45 | -| Receiver carried a readable engine type | 72 | +| Receiver carried a readable engine type | 75 | | Receiver erased, placed by the object NAME | 24 | | Receiver erased, placed by an `object: string` PARAMETER | 1 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 1 | @@ -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.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 | | `packages/plugins/plugin-auth/src/forced-reset-revocation.ts` | `update` | `SystemObjectName.API_KEY` | undecidable | elevated | 1 | @@ -94,6 +95,8 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-auth/src/objectql-adapter.ts` | `delete` | `objectName` | undecidable | PROVABLY NONE | 5 | | `packages/plugins/plugin-auth/src/objectql-adapter.ts` | `insert` | `objectName` | undecidable | options unreadable | 2 | | `packages/plugins/plugin-auth/src/objectql-adapter.ts` | `update` | `objectName` | undecidable | options unreadable | 5 | +| `packages/plugins/plugin-auth/src/operator-password-reset.ts` | `update` | `SystemObjectName.ACCOUNT` | undecidable | elevated | 1 | +| `packages/plugins/plugin-auth/src/operator-password-reset.ts` | `update` | `SystemObjectName.USER` | undecidable | elevated | 1 | | `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_team` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_team_member` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_user_permission_set` | enabled | elevated | 1 | From 6d75801d768fc46a4784319c042ceac141b91155 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 11:22:51 +0000 Subject: [PATCH 08/12] fix(auth): the operator reset ends the account's outstanding reset tokens before the password lands `os user set-password` sets a password, so it keeps the rule every password door now keeps: the account's outstanding password-reset rows are ended before the new credential is written. The CLI holds no server cache, so it ends the rows, as the raw adapter does. Docs and changeset state it at that reach. Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../dev-seed-credential-production-refusal.md | 2 +- content/docs/deployment/cli.mdx | 7 +++-- .../dev-seed-credential-production.test.ts | 21 +++++++++++++++ .../src/operator-password-reset.ts | 27 +++++++++++++++---- 4 files changed, 49 insertions(+), 8 deletions(-) diff --git a/.changeset/dev-seed-credential-production-refusal.md b/.changeset/dev-seed-credential-production-refusal.md index 5506af28870..4f12df497be 100644 --- a/.changeset/dev-seed-credential-production-refusal.md +++ b/.changeset/dev-seed-credential-production-refusal.md @@ -20,6 +20,6 @@ Metadata-protocol: none - **A marked account still on its seed password opens no session**, on any sign-in door (password, emailed link, one-time code, passkey, social or SSO, impersonation), whatever password it was seeded with, `os dev --admin-password` included. A password check never confirms that seed password: a password sign-in answers it as a wrong password. - **No password change is offered at sign-in.** Whoever signed in first could perform it. The way out is the operator's reset on the server. -**`os user set-password `** sets the account's password in the project database. It reads the new password from a terminal prompt (twice, not echoed) or from standard input with `--password-stdin`, never from the command line, and takes `--database-url` like the other one-shot commands. It refuses a development seed password and a password outside 8 to 128 characters, and writes nothing on a refusal. It clears the account's development seed mark and any sign-in lock, records the change time, and ends every session and revokes every API key of the account, as an administrator's forced reset does. It asks for no password change at the next sign-in. +**`os user set-password `** sets the account's password in the project database. It reads the new password from a terminal prompt (twice, not echoed) or from standard input with `--password-stdin`, never from the command line, and takes `--database-url` like the other one-shot commands. It refuses a development seed password and a password outside 8 to 128 characters, and writes nothing on a refusal. It deletes the account's outstanding password-reset links and codes from the project database before the new password lands; a server's secondary storage is out of its reach. It clears the account's development seed mark and any sign-in lock, records the change time, and ends every session and revokes every API key of the account, as an administrator's forced reset does. It asks for no password change at the next sign-in. **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. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index fb0b66d0ad8..41de4f710a2 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -883,9 +883,12 @@ What one run does: account with no password sign-in, are refused too. A refusal writes nothing. - **It sets the password with the hash every server verifies**, clears the account's development seed mark and a sign-in lock, and records the change time. +- **It deletes the account's outstanding password-reset links and codes from the project + database** before the new password lands. A server's secondary storage (a host cache) is + out of its reach. - **It ends every session and revokes every API key of the account**, as an - administrator's forced reset does: credentials issued under the old password do not - outlive it. It asks for no password change at the next sign-in. + administrator's forced reset does: the sessions and keys issued under the old password do + not outlive it. It asks for no password change at the next sign-in. ### Build & Validate diff --git a/packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts b/packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts index ce3d976458e..aa05114249c 100644 --- a/packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts +++ b/packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts @@ -344,6 +344,27 @@ describe('a server outside development mode refuses a development seed credentia expect((await server.doors.signIn(SEED_EMAIL, CUSTOM_SEED_PASSWORD)).status).toBe(401); }); + it('`os user set-password` ends the account\'s outstanding password-reset links before the password lands, and no other account\'s', async () => { + const seeded = await bootDevelopment(); + const adminId = await seeded.userId(SEED_EMAIL); + const staffId = await seeded.userId(STAFF_EMAIL); + const expiresAt = new Date(Date.now() + 3_600_000); + for (const [identifier, value] of [ + ['reset-password:tok_admin_1', adminId], + ['reset-password:tok_admin_2', adminId], + ['reset-password:tok_staff', staffId], + ] as const) { + await seeded.ql.insert('sys_verification', { identifier, value, expires_at: expiresAt }, { context: SYS } as never); + } + process.env.NODE_ENV = 'production'; + const links = async (userId: string) => (await seeded.rows('sys_verification', { value: userId })).length; + expect({ admin: await links(adminId), staff: await links(staffId) }).toEqual({ admin: 2, staff: 1 }); + + const outcome = await setOperatorPassword(seeded.ql as never, { email: SEED_EMAIL, password: NEW_PASSWORD }); + expect(outcome).toMatchObject({ outcome: 'set', userId: adminId }); + expect({ admin: await links(adminId), staff: await links(staffId) }).toEqual({ admin: 0, staff: 1 }); + }); + it('the operator reset refuses a password a server would refuse, and an address no account holds, and writes nothing', async () => { const seeded = await bootDevelopment(); const adminId = await seeded.userId(SEED_EMAIL); diff --git a/packages/plugins/plugin-auth/src/operator-password-reset.ts b/packages/plugins/plugin-auth/src/operator-password-reset.ts index 6e4fa18c8d1..e030432fa3f 100644 --- a/packages/plugins/plugin-auth/src/operator-password-reset.ts +++ b/packages/plugins/plugin-auth/src/operator-password-reset.ts @@ -20,10 +20,15 @@ * - **Clears the seed stamp** (`sys_user.dev_seed_credential`), stamps * `password_changed_at`, and clears a sign-in lock, so the new password * signs in at once. + * - **Ends every outstanding password-reset token** of the account before the + * password lands, as every door that sets a password does + * (`credential-change-ends-reset-tokens.ts`). The CLI holds no server cache, + * so it ends the token rows, as the raw adapter (handed no secondary storage) + * does. * - **Ends every session and revokes every API key** of the account, as an * administrator's forced reset with revocation does - * (`forced-reset-revocation.ts`, `admin_password_reset`): credentials minted - * under the old password do not outlive it. + * (`forced-reset-revocation.ts`, `admin_password_reset`): the sessions and + * keys issued under the old password do not outlive it. * * It asks for no password change at the next sign-in: the operator chose the * password. @@ -32,6 +37,7 @@ import { SystemObjectName } from '@objectstack/spec/system'; import { DEV_SEED_CREDENTIAL_FIELD, isDevSeedPassword } from './dev-seed-credential.js'; import { revokeSessionsAndApiKeys } from './forced-reset-revocation.js'; +import { endResetTokensOnCredentialWrite } from './credential-change-ends-reset-tokens.js'; /** better-auth's default bounds for a password (`emailAndPassword.minPasswordLength` / `maxPasswordLength`). */ export const OPERATOR_PASSWORD_MIN_LENGTH = 8; @@ -40,7 +46,9 @@ export const OPERATOR_PASSWORD_MAX_LENGTH = 128; /** The slice of the data engine the reset reads and writes through. */ export interface OperatorPasswordResetEngine { 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; } /** Why a reset was refused. Nothing was written. */ @@ -144,11 +152,20 @@ export async function setOperatorPassword( const { hashPassword } = await import('better-auth/crypto'); const now = (opts.now ?? (() => new Date()))(); - await engine.update( + const credentialWrite = { id: credential.id, password: await hashPassword(input.password), updated_at: now }; + // Before the write, as the adapters do: a token that cannot be ended aborts + // it, and the old password stands (`credential-change-ends-reset-tokens.ts`). + await endResetTokensOnCredentialWrite( + { + find: async (object, query) => rowsOf(await engine.find(object, { ...query, context: SYSTEM_CTX })), + findOne: (object, query) => engine.findOne(object, { ...query, context: SYSTEM_CTX }), + delete: (object, query) => engine.delete(object, { ...query, context: SYSTEM_CTX }), + }, SystemObjectName.ACCOUNT, - { id: credential.id, password: await hashPassword(input.password), updated_at: now }, - { context: SYSTEM_CTX }, + credentialWrite, + [{ user_id: user.id }], ); + await engine.update(SystemObjectName.ACCOUNT, credentialWrite, { context: SYSTEM_CTX }); await engine.update( SystemObjectName.USER, { From 16228898f87afeed0d5f2a4579d38a30ad11faf4 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 11:31:58 +0000 Subject: [PATCH 09/12] chore(census): place the operator reset's reset-token delete in the plugin-auth shard Regenerated with `node scripts/tenant-audit-census.mjs --write`. Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../plugins/plugin-auth.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) 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 6ed2a1666c7..a9a044d426a 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts/plugins/plugin-auth.md @@ -14,24 +14,24 @@ a row or a number here — fix the code, or the census, and regenerate. | Measure | Value | |---|---:| -| Write call sites | 101 | +| Write call sites | 102 | | Object name statically decidable | 58 | -| Object name chosen at run time | 43 | +| Object name chosen at run time | 44 | | Object name spelled inline | 47 | | Object name spelled through a `const` | 11 | | Object name is an `object: string` parameter | 2 | -| Object name is some other run-time expression | 41 | +| Object name is some other run-time expression | 42 | | Against a tenancy-enabled object | 56 | | Against an object declaring tenancy off | 2 | -| Threading a tenant context | 58 | +| Threading a tenant context | 59 | | Provably carrying none (options read, no context key) | 15 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 28 | | …and decidably tenancy-enabled | 16 | -| Threading a decidably elevated (`isSystem`) context | 41 | +| Threading a decidably elevated (`isSystem`) context | 42 | | Threading a decidably non-elevated context | 0 | | Threading a context of undecidable elevation | 45 | -| Receiver carried a readable engine type | 75 | +| Receiver carried a readable engine type | 76 | | Receiver erased, placed by the object NAME | 24 | | Receiver erased, placed by an `object: string` PARAMETER | 1 | | Receiver erased, placed by an `UNTYPED_RECEIVERS` row | 1 | @@ -95,6 +95,7 @@ a row or a number here — fix the code, or the census, and regenerate. | `packages/plugins/plugin-auth/src/objectql-adapter.ts` | `delete` | `objectName` | undecidable | PROVABLY NONE | 5 | | `packages/plugins/plugin-auth/src/objectql-adapter.ts` | `insert` | `objectName` | undecidable | options unreadable | 2 | | `packages/plugins/plugin-auth/src/objectql-adapter.ts` | `update` | `objectName` | undecidable | options unreadable | 5 | +| `packages/plugins/plugin-auth/src/operator-password-reset.ts` | `delete` | `object` | undecidable | elevated | 1 | | `packages/plugins/plugin-auth/src/operator-password-reset.ts` | `update` | `SystemObjectName.ACCOUNT` | undecidable | elevated | 1 | | `packages/plugins/plugin-auth/src/operator-password-reset.ts` | `update` | `SystemObjectName.USER` | undecidable | elevated | 1 | | `packages/plugins/plugin-auth/src/organization-delete.ts` | `delete` | `sys_team` | enabled | elevated | 1 | From 6178523ef4d36f0c9db577f2fc26d7f77e702bd2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 11:57:35 +0000 Subject: [PATCH 10/12] test(cli): the shared-data-key fixture sets the served password with `os user set-password` before `os start` A server outside development mode refuses the development seed password, so the fixture takes the documented step between `os dev` and `os start` and signs in to the production boots with the password it set. Its assertions are unchanged. Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- ...-start-shared-data-key.integration.test.ts | 107 +++++++++++------- 1 file changed, 69 insertions(+), 38 deletions(-) diff --git a/packages/cli/test/dev-start-shared-data-key.integration.test.ts b/packages/cli/test/dev-start-shared-data-key.integration.test.ts index a3ad09e1286..e637d4e17fc 100644 --- a/packages/cli/test/dev-start-shared-data-key.integration.test.ts +++ b/packages/cli/test/dev-start-shared-data-key.integration.test.ts @@ -1,5 +1,5 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. -// test-budget: 40 — spawns the real producer once per single-cause fixture: `os dev` then `os start` over one project, then two `os start` boots over that project's two key files (one reads back, one refuses); reading 24.3 s for the four boots on a shared local box (no CI reading yet) x 1.25, rounded up to the next 10 s +// test-budget: 40 — spawns the real producer once per single-cause fixture: `os dev`, `os user set-password` and `os start` over one project, then two `os start` boots over that project's two key files (one reads back, one refuses); reading 24.3 s for the four boots on a shared local box (no CI reading yet) x 1.25, rounded up to the next 10 s /** * #29934 — a secret saved under `os dev` reads back under `os start` over the @@ -19,7 +19,8 @@ * * The card's reproduction at the public door, with no env key anywhere and an * empty `HOME`: `os dev` → sign in → `PUT /api/settings/ai` with an - * `openai_api_key` → stop; `os start --artifact ./dist/objectstack.json` in the + * `openai_api_key` → stop; `os user set-password` (a server outside development + * mode refuses the seed password); `os start --artifact ./dist/objectstack.json` in the * same project → sign in → `GET /api/settings/ai` must carry the stored value * (masked, from `global`), and the project directory must hold no second key. * @@ -36,7 +37,7 @@ */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; -import { spawn, type ChildProcess } from 'node:child_process'; +import { spawn, spawnSync, type ChildProcess } from 'node:child_process'; import { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs'; import { randomBytes } from 'node:crypto'; import { tmpdir } from 'node:os'; @@ -64,6 +65,11 @@ const BOOT_TIMEOUT_MS = 180_000; /** The development dev-admin seed — the operator on both boots (one database). */ const EMAIL = 'admin@objectos.ai'; const PASSWORD = 'admin123'; +/** + * The password the operator sets with `os user set-password` before serving the + * database outside development mode, where the seed password is refused. + */ +const SERVED_PASSWORD = 'dsk-served-password-29934'; const SECRET = 'sk-29934-shared-key'; const MANIFEST = { id: 'com.example.dsk', namespace: 'dsk', version: '1.0.0', type: 'app', name: 'Dsk' }; @@ -104,40 +110,61 @@ let dir: string; let home: string; let reading: Reading = {}; +// `childEnv`, never a bare `...process.env` — see its header. No env key of +// any spelling and no home override: the key FILE is the subject, and `HOME` +// is this test's own empty directory. +function projectEnv(): Record { + return childEnv({ + NO_COLOR: '1', + HOME: home, + OS_CLOUD_URL: 'off', + OS_DISABLE_CONSOLE: '1', + OS_LOG_LEVEL: 'warn', + // A production boot on a kernel-assigned port derives its own trusted + // origin from the port it was ASKED for (0), so the origin it bound is + // named here; `os dev` trusts `http://localhost:*` on its own. + OS_TRUSTED_ORIGINS: 'http://localhost:*', + OS_SECRET_KEY: undefined, + OS_DEV_CRYPTO_KEY: undefined, + OBJECTSTACK_DEV_CRYPTO_KEY: undefined, + OS_INTERNAL_CRYPTO_KEY_FILE: undefined, + OS_INTERNAL_CRYPTO_KEY_FILE_CANDIDATE: undefined, + OS_HOME: undefined, + OBJECTSTACK_HOME: undefined, + OS_DATABASE_URL: undefined, + OS_ARTIFACT_URL: undefined, + OS_ARTIFACT_PATH: undefined, + OS_AUTH_SECRET: undefined, + OS_CLUSTER_DRIVER: undefined, + OS_MODE: undefined, + NODE_ENV: undefined, + OS_PORT: undefined, + PORT: undefined, + }); +} + +/** + * `os user set-password EMAIL --password-stdin` over the project database: the + * way a database `os dev` seeded is served outside development mode. + */ +function setServedPassword(): void { + const run = spawnSync(process.execPath, [CLI, 'user', 'set-password', EMAIL, '--password-stdin'], { + cwd: dir, + env: projectEnv(), + input: SERVED_PASSWORD, + encoding: 'utf8', + timeout: BOOT_TIMEOUT_MS, + }); + if (run.status !== 0) { + throw new Error(`os user set-password exited ${String(run.status)}\n--- output ---\n${run.stdout}${run.stderr}`); + } +} + function boot(what: string, args: string[]): Promise { return new Promise((resolveBoot, rejectBoot) => { const child = spawn(process.execPath, [CLI, ...args], { cwd: dir, - // `childEnv`, never a bare `...process.env` — see its header. No env key - // of any spelling and no home override: the key FILE is the subject, and - // `HOME` is this test's own empty directory. - env: childEnv({ - NO_COLOR: '1', - HOME: home, - OS_CLOUD_URL: 'off', - OS_DISABLE_CONSOLE: '1', - OS_LOG_LEVEL: 'warn', - // A production boot on a kernel-assigned port derives its own trusted - // origin from the port it was ASKED for (0), so the origin it bound is - // named here; `os dev` trusts `http://localhost:*` on its own. - OS_TRUSTED_ORIGINS: 'http://localhost:*', - OS_SECRET_KEY: undefined, - OS_DEV_CRYPTO_KEY: undefined, - OBJECTSTACK_DEV_CRYPTO_KEY: undefined, - OS_INTERNAL_CRYPTO_KEY_FILE: undefined, - OS_INTERNAL_CRYPTO_KEY_FILE_CANDIDATE: undefined, - OS_HOME: undefined, - OBJECTSTACK_HOME: undefined, - OS_DATABASE_URL: undefined, - OS_ARTIFACT_URL: undefined, - OS_ARTIFACT_PATH: undefined, - OS_AUTH_SECRET: undefined, - OS_CLUSTER_DRIVER: undefined, - OS_MODE: undefined, - NODE_ENV: undefined, - OS_PORT: undefined, - PORT: undefined, - }), + env: projectEnv(), stdio: ['ignore', 'pipe', 'pipe'], detached: true, }); @@ -209,8 +236,8 @@ function http(live: Live, method: string, path: string, token = '', body?: unkno ); } -async function signIn(live: Live): Promise { - const r = await http(live, 'POST', '/api/v1/auth/sign-in/email', '', { email: EMAIL, password: PASSWORD }); +async function signIn(live: Live, password: string): Promise { + const r = await http(live, 'POST', '/api/v1/auth/sign-in/email', '', { email: EMAIL, password }); const token = r.body?.token; if (r.status !== 200 || typeof token !== 'string') { throw new Error(`sign-in answered ${r.status}: ${JSON.stringify(r.body)}\n--- output ---\n${live.output().slice(-3000)}`); @@ -232,15 +259,19 @@ beforeAll(async () => { try { // `npm run dev`: the dev admin is seeded, the secret is sealed. live = await boot('os dev', ['dev', '--no-watch', '--no-restart', '-p', KERNEL_ASSIGNED_PORT]); - const devToken = await signIn(live); + const devToken = await signIn(live, PASSWORD); const put = await http(live, 'PUT', '/api/settings/ai', devToken, { openai_api_key: SECRET }); transcript += `--- os dev ---\n${live.output().slice(-3000)}\n`; await stopGroup(live.child); live = undefined; + // A server outside development mode refuses the seed password: the + // operator sets one first, as the refusal says. + setServedPassword(); + // `npx os start --artifact ./dist/objectstack.json` in the same project. live = await boot('os start', ['start', '--artifact', './dist/objectstack.json', '--port', KERNEL_ASSIGNED_PORT]); - const startToken = await signIn(live); + const startToken = await signIn(live, SERVED_PASSWORD); const get = await http(live, 'GET', '/api/settings/ai', startToken); transcript += `--- os start ---\n${live.output().slice(-3000)}\n`; reading = { put, get, transcript }; @@ -331,7 +362,7 @@ describe('#30042 — two key files: the boot takes the one that opens the stored renameSync(homeKey(), projectKey()); writeForeignKey(homeKey()); live = await boot('os start (two keys)', ['start', '--artifact', './dist/objectstack.json', '--port', KERNEL_ASSIGNED_PORT]); - const token = await signIn(live); + const token = await signIn(live, SERVED_PASSWORD); const get = await http(live, 'GET', '/api/settings/ai', token); const transcript = live.output().slice(-4000); await stopGroup(live.child); From 222a618930d75c96866e6ce5c495cccde8977197 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 12:05:07 +0000 Subject: [PATCH 11/12] test(cli): each shared-data-key spawn names its child's NODE_ENV at the call The built entry runs from dist/ only when the child is readably not in development or test; the env overrides are shared, the NODE_ENV clause is spelled at both spawns. Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- ...v-start-shared-data-key.integration.test.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/cli/test/dev-start-shared-data-key.integration.test.ts b/packages/cli/test/dev-start-shared-data-key.integration.test.ts index e637d4e17fc..43b9dddd843 100644 --- a/packages/cli/test/dev-start-shared-data-key.integration.test.ts +++ b/packages/cli/test/dev-start-shared-data-key.integration.test.ts @@ -110,11 +110,12 @@ let dir: string; let home: string; let reading: Reading = {}; -// `childEnv`, never a bare `...process.env` — see its header. No env key of -// any spelling and no home override: the key FILE is the subject, and `HOME` -// is this test's own empty directory. -function projectEnv(): Record { - return childEnv({ +// Handed to `childEnv`, never a bare `...process.env` — see its header. No env +// key of any spelling and no home override: the key FILE is the subject, and +// `HOME` is this test's own empty directory. Each spawn names `NODE_ENV` at +// the call, so the built entry runs from `dist/`. +function projectEnvOverrides(): Record { + return { NO_COLOR: '1', HOME: home, OS_CLOUD_URL: 'off', @@ -137,10 +138,9 @@ function projectEnv(): Record { OS_AUTH_SECRET: undefined, OS_CLUSTER_DRIVER: undefined, OS_MODE: undefined, - NODE_ENV: undefined, OS_PORT: undefined, PORT: undefined, - }); + }; } /** @@ -150,7 +150,7 @@ function projectEnv(): Record { function setServedPassword(): void { const run = spawnSync(process.execPath, [CLI, 'user', 'set-password', EMAIL, '--password-stdin'], { cwd: dir, - env: projectEnv(), + env: childEnv({ ...projectEnvOverrides(), NODE_ENV: undefined }), input: SERVED_PASSWORD, encoding: 'utf8', timeout: BOOT_TIMEOUT_MS, @@ -164,7 +164,7 @@ function boot(what: string, args: string[]): Promise { return new Promise((resolveBoot, rejectBoot) => { const child = spawn(process.execPath, [CLI, ...args], { cwd: dir, - env: projectEnv(), + env: childEnv({ ...projectEnvOverrides(), NODE_ENV: undefined }), stdio: ['ignore', 'pipe', 'pipe'], detached: true, }); From cc6754e708af478361640abaf6f0eff2b793b05d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 13:19:44 +0000 Subject: [PATCH 12/12] fix(auth): the development seed mark is staged only for a creation that proved the seed's own provisioning ticket The operator class is wider than the seed: an administrator's create-user, a bulk import and directory provisioning earn it too. The mark now keys on the proven ticket alone, so `os dev`'s admin and each `demoStaff` account are marked and an administrator-created account is not. Pinned: an account an administrator creates in development carries no mark and signs in outside development mode; the phone-number password sign-in refuses the seed password. Docs and changeset: the operator reset states exactly what it checks, its reach over a host secondary storage for reset links and sessions alike with the remedy, and the release's present limit with its follow-up; the ADR-0087 marker says a system column is added. The verifier's fail-closed answer is commented with its effect on the sign-in lock. Claude-Session: https://claude.ai/code/session_01QSeKYn5CmmdShCJifm6WYj Co-authored-by: Claude --- .../dev-seed-credential-production-refusal.md | 6 ++- content/docs/deployment/cli.mdx | 15 ++++--- content/docs/deployment/self-hosting.mdx | 6 +++ .../src/auth-manager-membership-admission.ts | 17 ++++---- .../dev-seed-credential-production.test.ts | 42 +++++++++++++++++-- .../plugin-auth/src/dev-seed-credential.ts | 16 ++++--- .../src/operator-password-reset.ts | 5 ++- 7 files changed, 83 insertions(+), 24 deletions(-) diff --git a/.changeset/dev-seed-credential-production-refusal.md b/.changeset/dev-seed-credential-production-refusal.md index 4f12df497be..40ea0b858f3 100644 --- a/.changeset/dev-seed-credential-production-refusal.md +++ b/.changeset/dev-seed-credential-production-refusal.md @@ -9,7 +9,7 @@ fix(auth)!: a server outside development mode refuses a development seed credent Clause-②: yes (narrowing) — narrowed: on a server whose `NODE_ENV` is not `development`, a password sign-in that submits the development seed password (`admin123`, or the value `OS_SEED_ADMIN_PASSWORD` sets) is refused on every account, and an account the development seed created opens no session while its stored password is still the one it was seeded with. Widened: the `os user set-password` command, the `sys_user.dev_seed_credential` column, and new `@objectstack/plugin-auth` exports `setOperatorPassword`, `findAccountByEmail`, `operatorPasswordRefusal`, `OPERATOR_PASSWORD_MIN_LENGTH`, `OPERATOR_PASSWORD_MAX_LENGTH` and the types `OperatorPasswordResetEngine`, `OperatorPasswordResetOutcome`, `OperatorPasswordResetRefusalReason`. Metadata-protocol: none - + **BREAKING** for a deployment that serves, outside development mode, a database `os dev` seeded, or any account whose password is the development seed password. Such a sign-in is refused. Set a new password on the server with `os user set-password `; the refusal names the command. A server in development mode (`os dev`) is unchanged. @@ -20,6 +20,8 @@ Metadata-protocol: none - **A marked account still on its seed password opens no session**, on any sign-in door (password, emailed link, one-time code, passkey, social or SSO, impersonation), whatever password it was seeded with, `os dev --admin-password` included. A password check never confirms that seed password: a password sign-in answers it as a wrong password. - **No password change is offered at sign-in.** Whoever signed in first could perform it. The way out is the operator's reset on the server. -**`os user set-password `** sets the account's password in the project database. It reads the new password from a terminal prompt (twice, not echoed) or from standard input with `--password-stdin`, never from the command line, and takes `--database-url` like the other one-shot commands. It refuses a development seed password and a password outside 8 to 128 characters, and writes nothing on a refusal. It deletes the account's outstanding password-reset links and codes from the project database before the new password lands; a server's secondary storage is out of its reach. It clears the account's development seed mark and any sign-in lock, records the change time, and ends every session and revokes every API key of the account, as an administrator's forced reset does. It asks for no password change at the next sign-in. +**`os user set-password `** sets the account's password in the project database. It reads the new password from a terminal prompt (twice, not echoed) or from standard input with `--password-stdin`, never from the command line, and takes `--database-url` like the other one-shot commands. It checks that the new password is not a development seed password and is 8 to 128 characters long; the deployment's own password policy and password history are not applied. It writes nothing on a refusal. It deletes the account's outstanding password-reset links and codes from the project database before the new password lands. It clears the account's development seed mark and any sign-in lock, records the change time, and ends every session and revokes every API key of the account, as an administrator's forced reset does. It asks for no password change at the next sign-in. It writes the project database only: a secondary storage the host configures for the auth service is out of its reach, for the reset links and the sessions alike. With one configured, run the command with the server stopped, or restart the server afterwards; a secondary storage kept outside the server process outlives a restart and is cleared of the account's entries by hand. **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. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 41de4f710a2..c5d273ea102 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -878,17 +878,22 @@ What one run does: - **The password never goes on the command line.** It is asked for on a terminal, or read from standard input. -- **It refuses a password a server would refuse:** a development seed password, or one - shorter than 8 or longer than 128 characters. An address no account holds, and an - account with no password sign-in, are refused too. A refusal writes nothing. +- **It checks two things about the new password:** it is not a development seed password, + and it is 8 to 128 characters long. The deployment's own password policy and password + history are not applied. An address no account holds, and an account with no password + sign-in, are refused too. A refusal writes nothing. - **It sets the password with the hash every server verifies**, clears the account's development seed mark and a sign-in lock, and records the change time. - **It deletes the account's outstanding password-reset links and codes from the project - database** before the new password lands. A server's secondary storage (a host cache) is - out of its reach. + database** before the new password lands. - **It ends every session and revokes every API key of the account**, as an administrator's forced reset does: the sessions and keys issued under the old password do not outlive it. It asks for no password change at the next sign-in. +- **It writes the project database only.** A secondary storage the host configures for the + auth service (a cache that can hold reset links and sessions) is out of its reach, for the + reset links and the sessions alike. With one configured, run the command with the server + stopped, or restart the server afterwards; a secondary storage kept outside the server + process outlives a restart and is cleared of the account's entries by hand. ### Build & Validate diff --git a/content/docs/deployment/self-hosting.mdx b/content/docs/deployment/self-hosting.mdx index 946da9745d7..56103a00f3b 100644 --- a/content/docs/deployment/self-hosting.mdx +++ b/content/docs/deployment/self-hosting.mdx @@ -625,6 +625,12 @@ 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`, so +run it on each seeded account before serving the database; ending them at boot +is follow-up #35184. + ### A seeded directory opens no bootstrap window Both paths above assume the deployment's **first login** is still ahead of it. diff --git a/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts b/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts index 46618470bdc..2aa1c200040 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-membership-admission.ts @@ -235,7 +235,8 @@ export async function validateAudienceAdmission( const provisioningTicket = (ctx as { body?: Record } | undefined)?.body?.[ AuthManager.OPERATOR_PROVISIONING_TICKET_FIELD ]; - const creationClass: AudienceCreationClass = this.isOperatorProvisioning(email, provisioningTicket) + const seedTicketProven = this.isOperatorProvisioning(email, provisioningTicket); + const creationClass: AudienceCreationClass = seedTicketProven ? 'operator' : classifyCreationMethod(data?.source, { enterpriseOAuthProviderIds: this.enterpriseOAuthProviderIds(), @@ -320,12 +321,14 @@ export async function validateAudienceAdmission( ) { this.stageOwnerVerifiedStamp(email); } - // An operator-class creation is the development seed's own (`os dev`'s - // admin, a stack's `demoStaff`): only its provisioning ticket earns the - // class. Its seed stamp is staged here, where the ticket is proven, and - // written when the creation's password credential lands - // (`dev-seed-credential.ts`). - if (email && creationClass === 'operator') await stageDevSeedCredential(email); + // The development seed's own creation (`os dev`'s admin, a stack's + // `demoStaff`) is the one that proved the boot's provisioning ticket for + // this address. The operator CLASS is wider (an administrator's + // create-user, a bulk import, directory provisioning all earn it from + // `classifyCreationMethod`), so the mark is staged on the proven ticket + // alone, never on the class. It is written when the creation's password + // credential lands (`dev-seed-credential.ts`). + if (email && seedTicketProven) await stageDevSeedCredential(email); // Admitted by its invitation alone (`isAdmittedByInvitationAlone`): the // membership settle does not bind this sign-up while its address is // unverified (`settleMembership`). diff --git a/packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts b/packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts index aa05114249c..3f07815d3e9 100644 --- a/packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts +++ b/packages/plugins/plugin-auth/src/dev-seed-credential-production.test.ts @@ -42,6 +42,8 @@ import 'better-auth/plugins/bearer'; import 'better-auth/plugins/custom-session'; import 'better-auth/plugins/organization'; import 'better-auth/plugins/magic-link'; +import 'better-auth/plugins/admin'; +import 'better-auth/plugins/phone-number'; import '@better-auth/core/context'; import '@better-auth/core/error'; @@ -54,6 +56,8 @@ const SEED_PASSWORD = 'admin123'; const CUSTOM_SEED_PASSWORD = 'Custom!Seed-Passw0rd-42'; const NEW_PASSWORD = 'Operator!Chosen-Passw0rd-7'; const STAFF_EMAIL = 'staff1@demo.example'; +const ADMIN_CREATED_EMAIL = 'colleague@company.example'; +const ADMIN_CHOSEN_PASSWORD = 'Admin-Chosen-Pass-29'; const RESET_COMMAND = 'os user set-password'; const ENV_KEYS = [ @@ -150,14 +154,19 @@ function doorsOf(manager: AuthManager) { * The development boot: `os dev` seeding the admin and one demo account into a * fresh database. `adminPassword` is `os dev --admin-password`. */ -async function bootDevelopment(options: { adminPassword?: string } = {}) { +async function bootDevelopment(options: { adminPassword?: string; adminPlugin?: boolean } = {}) { process.env.NODE_ENV = 'development'; if (options.adminPassword) process.env.OS_SEED_ADMIN_PASSWORD = options.adminPassword; kernel = new ObjectKernel({ logger: { level: 'silent' } }); await kernel.use(sqliteDriverPlugin()); await kernel.use(new ObjectQLPlugin()); await kernel.use( - new AuthPlugin({ secret: SECRET, baseUrl: ORIGIN, demoStaff: [{ name: 'Demo Staff 1', email: STAFF_EMAIL }] as never }), + new AuthPlugin({ + secret: SECRET, + baseUrl: ORIGIN, + demoStaff: [{ name: 'Demo Staff 1', email: STAFF_EMAIL }] as never, + ...(options.adminPlugin ? { plugins: { admin: true } } : {}), + } as never), ); await kernel.use(new SecurityPlugin()); await kernel.bootstrap(); @@ -175,13 +184,14 @@ type Seeded = Awaited>; * Leave development: the server that serves the database next. The seed's env * is not passed on, as `os start` does not pass it. */ -function productionServer(seeded: Seeded, options: { mails?: any[] } = {}) { +function productionServer(seeded: Seeded, options: { mails?: any[]; phoneNumber?: boolean } = {}) { process.env.NODE_ENV = 'production'; delete process.env.OS_SEED_ADMIN_PASSWORD; const manager = new AuthManager({ secret: SECRET, baseUrl: ORIGIN, dataEngine: seeded.ql as never, + ...(options.phoneNumber ? { plugins: { phoneNumber: true } } : {}), ...(options.mails ? { plugins: { magicLink: true }, @@ -258,6 +268,25 @@ describe('a server outside development mode refuses a development seed credentia expect(DEV_SEED_CREDENTIAL_FIELD in row).toBe(false); }); + it('an account an administrator creates in development carries no seed stamp, and signs in outside development mode', async () => { + const seeded = await bootDevelopment({ adminPlugin: true }); + const api: any = await seeded.manager.getApi(); + expect(typeof api.createUser, 'the admin plugin serves create-user on this boot').toBe('function'); + // The administrator's create-user, as the `/admin/create-user` route drives it. + await api.createUser({ body: { email: ADMIN_CREATED_EMAIL, name: 'Admin Created', password: ADMIN_CHOSEN_PASSWORD } }); + const createdId = await seeded.userId(ADMIN_CREATED_EMAIL); + expect(createdId, 'the administrator-created account exists').toBeTypeOf('string'); + expect(await isStamped(seeded, createdId)).toBe(false); + // The seed's own accounts on the same boot stay marked. + expect(await isStamped(seeded, await seeded.userId(SEED_EMAIL))).toBe(true); + expect(await isStamped(seeded, await seeded.userId(STAFF_EMAIL))).toBe(true); + + const server = productionServer(seeded); + const res = await server.doors.signIn(ADMIN_CREATED_EMAIL, ADMIN_CHOSEN_PASSWORD); + expect(res.status, await res.clone().text()).toBe(200); + expect(await server.doors.sessionUser(cookieHeader(res))).toBe(createdId); + }); + it('refuses a sign-in that submits the seed password to the seed admin, naming the operator reset command, and opens no session', async () => { const seeded = await bootDevelopment(); const adminId = await seeded.userId(SEED_EMAIL); @@ -284,6 +313,13 @@ describe('a server outside development mode refuses a development seed credentia expect(unknown).toEqual(known); }); + it('refuses the seed password on the phone-number password sign-in, naming the operator reset command', async () => { + const seeded = await bootDevelopment(); + const server = productionServer(seeded, { phoneNumber: true }); + const answer = await answerOf(await server.doors.post('/sign-in/phone-number', { phoneNumber: '+15555550123', password: SEED_PASSWORD })); + expectSeedPasswordRefusal(answer); + }); + it('refuses the seed password on an account that carries no seed stamp, as a database seeded before the stamp does', async () => { const seeded = await bootDevelopment(); const adminId = await seeded.userId(SEED_EMAIL); diff --git a/packages/plugins/plugin-auth/src/dev-seed-credential.ts b/packages/plugins/plugin-auth/src/dev-seed-credential.ts index 5355f57851d..6afcf8ab595 100644 --- a/packages/plugins/plugin-auth/src/dev-seed-credential.ts +++ b/packages/plugins/plugin-auth/src/dev-seed-credential.ts @@ -56,9 +56,11 @@ * through any door, writes a new salted hash and the stamp stops matching. * * It is written once, when the seed creates the account, in development: the - * audience gate (`validateAudienceAdmission`) stages it for an operator-class - * creation, the class only the seed's own provisioning ticket earns - * ({@link stageDevSeedCredential}), and `account.create.after` writes it when + * audience gate (`validateAudienceAdmission`) stages it for a creation that + * proved the seed's own provisioning ticket for its address, and no other + * (an administrator's create-user, a bulk import and directory provisioning + * share the operator class, never the ticket; {@link stageDevSeedCredential}), + * and `account.create.after` writes it when * that creation's password credential lands ({@link stampDevSeedCredential}). * * ## What it does not detect @@ -228,6 +230,10 @@ export function withDevSeedPasswordRefusal( ); return false; } catch { + // Fail closed, on purpose: when the mark cannot be read, a correct + // password is answered as a wrong one rather than accepted unchecked. + // That answer is a failed sign-in like any other, so it counts toward + // the account's sign-in lock. return false; } }, @@ -306,8 +312,8 @@ const stagedSeedCreation = defineRequestState<{ email: string } | undefined>(() /** * Stage the stamp for the creation running in this request: called by the - * audience gate for an operator-class creation, the class only the - * development seed's provisioning ticket earns. Nothing is staged outside + * audience gate for a creation that proved the development seed's own + * provisioning ticket (`os dev`'s admin, a stack's `demoStaff`). Nothing is staged outside * development mode. Never throws. */ export async function stageDevSeedCredential(email: string): Promise { diff --git a/packages/plugins/plugin-auth/src/operator-password-reset.ts b/packages/plugins/plugin-auth/src/operator-password-reset.ts index e030432fa3f..528ae92ceca 100644 --- a/packages/plugins/plugin-auth/src/operator-password-reset.ts +++ b/packages/plugins/plugin-auth/src/operator-password-reset.ts @@ -11,8 +11,9 @@ * * ## What one reset does * - * - **Refuses a password a server would refuse.** A development seed password - * is never set, and the length is held to better-auth's bounds (8 to 128). + * - **Checks two things about the new password:** it is not a development + * seed password, and its length is within better-auth's default bounds (8 + * to 128). The deployment's own password policy and history are not applied. * - **Writes the account's password credential** (`sys_account`, provider * `credential`) with better-auth's own hash, the one every server verifies. * An account with no password credential is refused: this sets a password,