diff --git a/apps/api/.claude/rules/40-sentinel-rows-excluded-from-counts.md b/apps/api/.claude/rules/40-sentinel-rows-excluded-from-counts.md index 285786e80e..6bbbf82e95 100644 --- a/apps/api/.claude/rules/40-sentinel-rows-excluded-from-counts.md +++ b/apps/api/.claude/rules/40-sentinel-rows-excluded-from-counts.md @@ -8,6 +8,8 @@ The `users` table (and others) contains internal **sentinel rows** that are not The first-user-superadmin promotion in `apps/api/src/auth.ts` (`user.create.before` hook) counted _all_ existing user rows to decide "is this the first human?". On a freshly forked deployment the `system_anonymous_trials` sentinel already existed, so the genuine first human was counted as the _second_ user, created as `role='user'` instead of `role='superadmin'`, and locked out of every superadmin-gated admin surface — with no in-product recovery (the role-change endpoint is itself superadmin-gated). The fix (idea `01KTBCWSTJ83YM280YP7MTE967`) was a login-time + migration self-heal whose every guard had to re-derive the `status != 'system'` exclusion the original count omitted. +Since 2026-11-15 the promotion is an atomic election in `session.create.before` (`establishFirstSuperadmin`, `apps/api/src/services/first-superadmin.ts`); its only-real-user guard and the `first_superadmin_election` migration still exclude `status = 'system'`. + ## Rule When writing any query or in-memory check whose result depends on **how many** rows exist (or whether _any_ real row exists) in a table that can hold internal/sentinel rows: diff --git a/apps/api/.env.example b/apps/api/.env.example index 181fc689ac..dd16853833 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -200,7 +200,8 @@ BASE_DOMAIN=workspaces.example.com # User approval / invite-only mode # When "true", new users require admin approval before accessing the platform. -# The first user to register automatically becomes superadmin. +# Without BOOTSTRAP_OWNER_EMAIL, the first real account to sign in becomes superadmin once, +# and only while it is the sole real account (see the self-hosting guide, "First Login & Admin Access"). # REQUIRE_APPROVAL=true # API tokens diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts index a62a2986df..d87399780e 100644 --- a/apps/api/src/auth.ts +++ b/apps/api/src/auth.ts @@ -2,7 +2,6 @@ import { SYSTEM_USER_ID } from '@simple-agent-manager/shared'; import { betterAuth } from 'better-auth'; import { drizzleAdapter } from 'better-auth/adapters/drizzle'; import type { GithubProfile, SocialProviders } from 'better-auth/social-providers'; -import { ne } from 'drizzle-orm'; import { drizzle } from 'drizzle-orm/d1'; import * as v from 'valibot'; @@ -18,6 +17,7 @@ import { bootstrapUserDecision, } from './services/bootstrap-owner'; import { emailSignInPlugins } from './services/email-sign-in'; +import { establishFirstSuperadmin, FIRST_SUPERADMIN_SETTING } from './services/first-superadmin'; import { refreshGitHubAccessToken } from './services/github-oauth-refresh'; import { untrustedGitLabUserInfo } from './services/gitlab-sign-in-identity'; import { @@ -42,10 +42,12 @@ const log = createModuleLogger('auth'); * a single atomic UPDATE with no read-modify-write race; concurrent logins of the * same user are idempotent (the second is a no-op). * - * Numbered params: ?1 = current user id (referenced twice), ?2 = sentinel id. + * Numbered params: ?1 = current user id (referenced twice), ?2 = sentinel id, + * ?3 = the durable ordinary-install election marker. * Guards: (a) skip already-superadmin rows; (d) never auto-elevate a suspended * account; status!='system' never mutates the sentinel; (b) the current user is the - * only non-internal user; (c) no non-system superadmin exists anywhere. + * only non-internal user; (c) no non-system superadmin exists anywhere; (e) the + * ordinary one-time election has not already completed. * * Drizzle cannot express the correlated-subquery WHERE, so this is issued via the * raw D1 binding (prepare/bind/run) — the same mechanism used by @@ -69,6 +71,10 @@ WHERE id = ?1 WHERE u3.role = 'superadmin' AND u3.status != 'system' ) = 0 + AND NOT EXISTS ( + SELECT 1 FROM platform_settings election + WHERE election.key = ?3 + ) `; interface GitHubEmailResponse { @@ -391,22 +397,9 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { return { data: user }; } - // Check if this is the first user (auto-superadmin) - const hookDb = drizzle(env.DATABASE, { schema }); - const existing = await hookDb - .select({ id: schema.users.id }) - .from(schema.users) - .where(ne(schema.users.id, sentinelId)) - .limit(1) - .all(); - - if (existing.length === 0 && bootstrapOwnerEmail(env) === undefined) { - return { - data: { ...user, role: 'superadmin', status: 'active' }, - }; - } - - // Subsequent users need approval + // Approval-gated users start unprivileged. The first ordinary user is elected only + // after their row exists, in the atomic session hook below; assigning superadmin here + // would race BetterAuth's later INSERT under concurrent registrations. return { data: { ...user, role: 'user', status: 'pending' }, }; @@ -417,6 +410,19 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { create: { before: async (session) => { if (!(await bootstrapSessionAllowed(env, session.userId))) return false; + if (bootstrapOwnerEmail(env) === undefined) { + // Fail closed for privilege, never for login: a D1 error leaves the user + // unpromoted (the batch is atomic) and the next sign-in retries the election. + try { + await establishFirstSuperadmin(env, session.userId); + } catch (err) { + log.error('first_superadmin_election.failed', { + userId: session.userId, + error: err instanceof Error ? err.message : String(err), + action: 'continued_without_promotion', + }); + } + } return { data: session }; }, // Login-time superadmin self-heal. Fires on EVERY session creation — @@ -441,12 +447,12 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { const sql = expectedOwner === undefined ? LOGIN_SELF_HEAL_SQL - : LOGIN_SELF_HEAL_SQL + ' AND lower(trim(email)) = ?3 AND email_verified = 1'; + : LOGIN_SELF_HEAL_SQL + ' AND lower(trim(email)) = ?4 AND email_verified = 1'; const statement = env.DATABASE.prepare(sql); const result = await ( expectedOwner === undefined - ? statement.bind(userId, sentinelId) - : statement.bind(userId, sentinelId, expectedOwner) + ? statement.bind(userId, sentinelId, FIRST_SUPERADMIN_SETTING) + : statement.bind(userId, sentinelId, FIRST_SUPERADMIN_SETTING, expectedOwner) ).run(); if (result.meta.changes > 0) { log.info('login_self_heal.promoted', { userId }); diff --git a/apps/api/src/db/migrations/0246_first_superadmin_election.sql b/apps/api/src/db/migrations/0246_first_superadmin_election.sql new file mode 100644 index 0000000000..c8bce60a3d --- /dev/null +++ b/apps/api/src/db/migrations/0246_first_superadmin_election.sql @@ -0,0 +1,26 @@ +-- Close the ordinary first-superadmin election on installations that already have an +-- administrator. The marker names the oldest real (status != 'system') superadmin, matching +-- RECORD_SQL in apps/api/src/services/first-superadmin.ts (establishFirstSuperadmin). While it +-- exists, no sign-in is promoted, even if that administrator is later deleted. +-- +-- This migration only inserts the marker. It never updates or deletes user rows: +-- * An installation with more than one superadmin (possible only from the concurrent first +-- sign-up race that predates this election, or a manual database edit) keeps every one of +-- them. establishFirstSuperadmin logs first-superadmin.multiple_superadmins on each sign-in +-- until an operator resolves it. +-- * An installation with no superadmin gets no marker. A fresh installation has only the system +-- user here, so its first real user still wins the election at sign-in. An existing sole +-- non-suspended user stays electable, as the login-time self-heal already allowed. An +-- installation with several real users and no superadmin promotes nobody, because the election +-- requires the signing-in user to be the only real user. +INSERT OR IGNORE INTO platform_settings (key, value, updated_at, updated_by) +SELECT + 'setup.firstSuperadminEstablished', + json_object('version', 1, 'ownerId', id), + CURRENT_TIMESTAMP, + id +FROM users +WHERE role = 'superadmin' + AND status != 'system' +ORDER BY created_at, id +LIMIT 1; diff --git a/apps/api/src/routes/agent-sign-in.ts b/apps/api/src/routes/agent-sign-in.ts index af198d79e3..f3a025ba03 100644 --- a/apps/api/src/routes/agent-sign-in.ts +++ b/apps/api/src/routes/agent-sign-in.ts @@ -70,8 +70,9 @@ async function findTargetUser(env: Env, target: string): Promise { const row = await env.DATABASE.prepare( diff --git a/apps/api/src/services/first-superadmin.ts b/apps/api/src/services/first-superadmin.ts new file mode 100644 index 0000000000..cfb47d6c07 --- /dev/null +++ b/apps/api/src/services/first-superadmin.ts @@ -0,0 +1,94 @@ +import type { Env } from '../env'; +import { createModuleLogger } from '../lib/logger'; + +type FirstSuperadminEnv = Pick; + +const log = createModuleLogger('first-superadmin'); + +/** + * Durable marker: initial administration of an ordinary (no `BOOTSTRAP_OWNER_EMAIL`) install is + * established. Written by the `*_first_superadmin_election.sql` migration for installs that already + * had a superadmin, and by + * {@link establishFirstSuperadmin} when it elects one. While it exists nobody is auto-promoted, + * even if every superadmin is later deleted. + */ +export const FIRST_SUPERADMIN_SETTING = 'setup.firstSuperadminEstablished'; + +/** + * Promote the bound user only when every guard holds inside this one statement: the user is a real + * (`status != 'system'`), non-suspended, non-superadmin account; it is the ONLY real user; and the + * election has not completed. D1 runs the statement atomically, so the guards are race-safe. + * + * The only-real-user guard does three jobs. A later sign-up never wins against an existing + * account, whatever that account's role or status. No other superadmin can exist (one would be + * another real user). And two racing sign-ups whose rows both exist both lose: the install fails + * closed with no administrator rather than electing by timing. A winner chosen by `created_at` + * would also promote the oldest account on an upgraded install with several users and no + * superadmin, which this election must never do. + */ +const ELECT_SQL = ` +UPDATE users +SET role = 'superadmin', status = 'active', updated_at = cast(unixepoch() * 1000 as integer) +WHERE id = ? + AND role != 'superadmin' + AND status != 'system' + AND status != 'suspended' + AND NOT EXISTS ( + SELECT 1 FROM users other + WHERE other.id != ? + AND other.status != 'system' + ) + AND NOT EXISTS ( + SELECT 1 FROM platform_settings election + WHERE election.key = ? + )`; + +/** + * Record the marker for the oldest real superadmin, if one exists. Runs after `ELECT_SQL` in the + * same batch, so it names the user just elected; it also backfills an install that has a + * superadmin but no marker. It writes nothing while no superadmin exists, so a refused election + * leaves the install open for its sole real user. + */ +const RECORD_SQL = ` +INSERT OR IGNORE INTO platform_settings (key, value, updated_at, updated_by) +SELECT ?, json_object('version', 1, 'ownerId', administrator.id), CURRENT_TIMESTAMP, administrator.id +FROM users administrator +WHERE administrator.role = 'superadmin' + AND administrator.status != 'system' +ORDER BY administrator.created_at, administrator.id +LIMIT 1`; + +/** + * Elect the first administrator of an ordinary install after BetterAuth has inserted the user. + * + * The initial read keeps later sign-ins to one query. It also reports an install with more than + * one real superadmin (`first-superadmin.multiple_superadmins`): superadmin is never granted + * through the admin API, so a second one can only come from the sign-up race that predates this election or a manual + * database edit, and an operator must decide which accounts to keep. Nothing is changed for them. + */ +export async function establishFirstSuperadmin( + env: FirstSuperadminEnv, + userId: string +): Promise { + const state = await env.DATABASE.prepare( + `SELECT + EXISTS (SELECT 1 FROM platform_settings WHERE key = ?) AS established, + (SELECT COUNT(*) FROM users WHERE role = 'superadmin' AND status != 'system') AS superadmins` + ) + .bind(FIRST_SUPERADMIN_SETTING) + .first<{ established: number; superadmins: number }>(); + if (state && state.superadmins > 1) { + log.warn('multiple_superadmins', { + superadminCount: state.superadmins, + signingInUserId: userId, + action: 'reported_for_operator_review', + }); + } + if (state?.established) return; + + const [elected] = await env.DATABASE.batch([ + env.DATABASE.prepare(ELECT_SQL).bind(userId, userId, FIRST_SUPERADMIN_SETTING), + env.DATABASE.prepare(RECORD_SQL).bind(FIRST_SUPERADMIN_SETTING), + ]); + if ((elected?.meta.changes ?? 0) > 0) log.info('elected', { userId }); +} diff --git a/apps/api/tests/unit/auth.test.ts b/apps/api/tests/unit/auth.test.ts index 5c2cfb12b7..a8ace1fe6c 100644 --- a/apps/api/tests/unit/auth.test.ts +++ b/apps/api/tests/unit/auth.test.ts @@ -13,6 +13,9 @@ interface AuthTestUser { } type BeforeCreateHook = (user: AuthTestUser) => Promise<{ data: AuthTestUser }>; +type SessionBeforeHook = ( + session: { userId: string } +) => Promise; type SessionAfterHook = (session: { userId?: string | null }) => Promise; interface BetterAuthOptions { @@ -27,6 +30,7 @@ interface BetterAuthOptions { }; session?: { create?: { + before?: SessionBeforeHook; after?: SessionAfterHook; }; }; @@ -35,6 +39,7 @@ interface BetterAuthOptions { const mocks = vi.hoisted(() => ({ drizzle: vi.fn(() => ({})), + establishFirstSuperadmin: vi.fn(async () => undefined), })); // Capture the options passed to betterAuth so we can assert on config @@ -51,6 +56,11 @@ vi.mock('drizzle-orm/d1', () => ({ drizzle: mocks.drizzle, })); +vi.mock('../../src/services/first-superadmin', () => ({ + establishFirstSuperadmin: mocks.establishFirstSuperadmin, + FIRST_SUPERADMIN_SETTING: 'setup.firstSuperadminEstablished', +})); + vi.mock('../../src/services/platform-config', async (importOriginal) => { const actual = await importOriginal(); const { buildResolvedPlatformConfig } = await import('../helpers/platform-config-fixture'); @@ -73,22 +83,15 @@ function fakeEnv(requireApproval = 'true') { }; } -function installExistingUsersQuery(existingUsers: Array<{ id: string }>) { +function installSignupApprovalQuery() { const get = vi.fn(async () => undefined); - const all = vi.fn(async () => existingUsers); - const limit = vi.fn(() => ({ all })); - const where = vi.fn(() => ({ limit })); + const where = vi.fn(() => ({ get })); const from = vi.fn(() => ({ where })); - const select = vi.fn((fields?: Record) => { - if (fields && 'value' in fields) { - return { from: vi.fn(() => ({ where: vi.fn(() => ({ get })) })) }; - } - return { from }; - }); + const select = vi.fn(() => ({ from })); mocks.drizzle.mockReturnValue({ select }); - return { all, from, get, limit, select, where }; + return { from, get, select, where }; } async function getBeforeCreateHook(): Promise { @@ -131,6 +134,18 @@ async function getSessionAfterHook(env: Record): Promise): Promise { + const { createAuth } = await import('../../src/auth'); + await createAuth(env as never); + + const hook = capturedOptions?.databaseHooks?.session?.create?.before; + if (!hook) { + throw new Error('BetterAuth session.create.before hook was not registered'); + } + + return hook; +} + const newUser: AuthTestUser = { id: 'github-user-1', email: 'user@example.com', @@ -142,6 +157,7 @@ describe('BetterAuth configuration', () => { capturedOptions = undefined; mocks.drizzle.mockReset(); mocks.drizzle.mockReturnValue({}); + mocks.establishFirstSuperadmin.mockClear(); }); it('enables OAuth token encryption (encryptOAuthTokens: true)', async () => { @@ -218,32 +234,49 @@ describe('BetterAuth configuration', () => { expect(capturedOptions?.socialProviders).not.toHaveProperty('google'); }); - it('promotes the first real user when only the system user exists', async () => { - const query = installExistingUsersQuery([]); + it('creates approval-gated users pending until the atomic session election', async () => { + const query = installSignupApprovalQuery(); const beforeCreate = await getBeforeCreateHook(); const result = await beforeCreate(newUser); expect(result.data).toMatchObject({ id: newUser.id, - role: 'superadmin', - status: 'active', + role: 'user', + status: 'pending', }); expect(query.where).toHaveBeenCalledOnce(); - expect(query.all).toHaveBeenCalledOnce(); }); - it('keeps later real users pending when the sentinel and a real user exist', async () => { - installExistingUsersQuery([{ id: 'real-user-1' }]); - const beforeCreate = await getBeforeCreateHook(); + it('elects an ordinary first administrator at the session boundary', async () => { + const beforeSession = await getSessionBeforeHook(fakeEnv()); - const result = await beforeCreate(newUser); + await expect(beforeSession({ userId: newUser.id })).resolves.toEqual({ + data: { userId: newUser.id }, + }); - expect(result.data).toMatchObject({ - id: newUser.id, - role: 'user', - status: 'pending', + expect(mocks.establishFirstSuperadmin).toHaveBeenCalledOnce(); + expect(mocks.establishFirstSuperadmin).toHaveBeenCalledWith( + expect.objectContaining({ BASE_DOMAIN: 'example.com' }), + newUser.id + ); + }); + + it('still creates the session when the election throws, without retrying privilege', async () => { + mocks.establishFirstSuperadmin.mockRejectedValueOnce(new Error('D1_ERROR: database unavailable')); + const error = vi.spyOn(console, 'error').mockImplementation(() => undefined); + const beforeSession = await getSessionBeforeHook(fakeEnv()); + + await expect(beforeSession({ userId: newUser.id })).resolves.toEqual({ + data: { userId: newUser.id }, }); + + expect(mocks.establishFirstSuperadmin).toHaveBeenCalledOnce(); + const logged = error.mock.calls + .map(([line]) => JSON.parse(String(line)) as Record) + .find((entry) => entry.event === 'auth.first_superadmin_election.failed'); + expect(logged).toMatchObject({ userId: newUser.id, action: 'continued_without_promotion' }); + error.mockRestore(); }); it('uses the migration-seeded system user id', () => { @@ -288,8 +321,13 @@ describe('login-time superadmin self-heal (session.create.after)', () => { expect(sql).toContain('u2.id != ?2'); // No-existing-superadmin guard. expect(sql).toContain("u3.role = 'superadmin'"); - // ?1 = current user id (referenced twice), ?2 = sentinel id. - expect(bind).toHaveBeenCalledWith('github-user-1', SYSTEM_USER_ID); + // ?1 = current user id, ?2 = sentinel id, ?3 = the durable one-time election marker. + expect(sql).toContain('platform_settings election'); + expect(bind).toHaveBeenCalledWith( + 'github-user-1', + SYSTEM_USER_ID, + 'setup.firstSuperadminEstablished' + ); expect(run).toHaveBeenCalledOnce(); }); @@ -305,7 +343,11 @@ describe('login-time superadmin self-heal (session.create.after)', () => { await hook({ userId: 'github-user-1' }); - expect(bind).toHaveBeenCalledWith('github-user-1', SYSTEM_USER_ID); + expect(bind).toHaveBeenCalledWith( + 'github-user-1', + SYSTEM_USER_ID, + 'setup.firstSuperadminEstablished' + ); }); it('does nothing (no query) when the session userId is null', async () => { @@ -405,11 +447,12 @@ describe('installer bootstrap owner hooks', () => { }); await hook({ userId: 'github-user-1' }); expect(prepare).toHaveBeenCalledWith( - expect.stringContaining('AND lower(trim(email)) = ?3 AND email_verified = 1') + expect.stringContaining('AND lower(trim(email)) = ?4 AND email_verified = 1') ); expect(bind).toHaveBeenCalledWith( 'github-user-1', SYSTEM_USER_ID, + 'setup.firstSuperadminEstablished', 'owner@example.com' ); }); @@ -440,7 +483,7 @@ describe('installer bootstrap owner hooks', () => { it('does not repeat first-user administration on an installer instance after its elected user rows are deleted', async () => { const { createAuth } = await import('../../src/auth'); - installExistingUsersQuery([]); + installSignupApprovalQuery(); await createAuth({ ...fakeEnv(), BOOTSTRAP_OWNER_EMAIL: 'owner@example.com', diff --git a/apps/api/tests/unit/services/first-superadmin.test.ts b/apps/api/tests/unit/services/first-superadmin.test.ts new file mode 100644 index 0000000000..1fb455e4b8 --- /dev/null +++ b/apps/api/tests/unit/services/first-superadmin.test.ts @@ -0,0 +1,334 @@ +/** + * The ordinary first-superadmin election and its migration, on a real SQLite engine. + * + * Every guard here is a SQL predicate, so each scenario runs the shipped statements against + * tables built from the drizzle schema (`.claude/rules/28`): a `.where()`-ignoring mock could not + * tell a guarded UPDATE from an unguarded one. + */ +import { readdirSync } from 'node:fs'; + +import { SYSTEM_USER_ID } from '@simple-agent-manager/shared'; +import Database from 'better-sqlite3'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import * as schema from '../../../src/db/schema'; +import type { Env } from '../../../src/env'; +import { + establishFirstSuperadmin, + FIRST_SUPERADMIN_SETTING, +} from '../../../src/services/first-superadmin'; +import { applySqliteMigration, createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; + +// Located by name, not number: the migration number is reconciled against main at merge time. +const MIGRATIONS_DIR = new URL('../../../src/db/migrations/', import.meta.url); +const MIGRATION_FILES = readdirSync(MIGRATIONS_DIR).filter((name) => + /^\d+_first_superadmin_election\.sql$/.test(name) +); +if (MIGRATION_FILES.length !== 1) { + throw new Error( + `expected one first_superadmin_election migration, found ${MIGRATION_FILES.length}` + ); +} +const MIGRATION = new URL(MIGRATION_FILES[0]!, MIGRATIONS_DIR); + +const databases: Database.Database[] = []; + +interface UserRow { + id: string; + role: string; + status: string; +} + +function fixture() { + const sqlite = new Database(':memory:'); + databases.push(sqlite); + createSchemaTables(sqlite, [schema.users, schema.platformSettings]); + const insert = sqlite.prepare( + `INSERT INTO users (id, email, email_verified, role, status, created_at, updated_at) + VALUES (?, ?, 1, ?, ?, ?, ?)` + ); + insert.run(SYSTEM_USER_ID, 'system@example.com', 'user', 'system', 1, 1); + const env = { DATABASE: createSqliteD1(sqlite) } as Env; + const user = (id: string, role = 'user', status = 'pending', createdAt = 2) => + insert.run(id, `${id}@example.com`, role, status, createdAt, createdAt); + const get = (id: string) => + sqlite.prepare('SELECT id, role, status FROM users WHERE id = ?').get(id) as UserRow; + const superadmins = () => + ( + sqlite + .prepare("SELECT id FROM users WHERE role = 'superadmin' AND status != 'system'") + .all() as Array<{ id: string }> + ).map((row) => row.id); + const electionOwner = () => { + const row = sqlite + .prepare('SELECT value FROM platform_settings WHERE key = ?') + .get(FIRST_SUPERADMIN_SETTING) as { value: string } | undefined; + return row ? (JSON.parse(row.value) as { ownerId: string }).ownerId : undefined; + }; + const allUsers = () => sqlite.prepare('SELECT * FROM users ORDER BY id').all(); + return { env, sqlite, user, get, superadmins, electionOwner, allUsers }; +} + +afterEach(() => { + vi.restoreAllMocks(); + for (const database of databases.splice(0)) database.close(); +}); + +describe('establishFirstSuperadmin — the election', () => { + it('promotes the first real user and records it as the election winner', async () => { + const f = fixture(); + f.user('first-user'); + + await establishFirstSuperadmin(f.env, 'first-user'); + + expect(f.get('first-user')).toMatchObject({ role: 'superadmin', status: 'active' }); + expect(f.electionOwner()).toBe('first-user'); + expect(f.get(SYSTEM_USER_ID)).toMatchObject({ role: 'user', status: 'system' }); + }); + + it('is idempotent: a second sign-in of the winner changes nothing', async () => { + const f = fixture(); + f.user('first-user'); + await establishFirstSuperadmin(f.env, 'first-user'); + const before = f.allUsers(); + + await establishFirstSuperadmin(f.env, 'first-user'); + + expect(f.allUsers()).toEqual(before); + expect(f.electionOwner()).toBe('first-user'); + }); + + describe('a later sign-up never wins against an existing account', () => { + it.each([ + ['(a)', 'suspended', 'suspended-owner'], + ['(b)', 'a non-admin', 'existing-user'], + ])( + '%s does not promote a new sign-up while the sole existing user is %s', + async (_case, _label, existingId) => { + const f = fixture(); + f.user(existingId, 'user', existingId === 'suspended-owner' ? 'suspended' : 'active', 2); + f.user('stranger', 'user', 'pending', 3); + + await establishFirstSuperadmin(f.env, 'stranger'); + + expect(f.superadmins()).toEqual([]); + expect(f.get('stranger')).toMatchObject({ role: 'user', status: 'pending' }); + expect(f.electionOwner()).toBeUndefined(); + } + ); + + it('(a) control: the same sign-up is promoted when no other account exists', async () => { + const f = fixture(); + f.user('stranger', 'user', 'pending', 3); + + await establishFirstSuperadmin(f.env, 'stranger'); + + expect(f.superadmins()).toEqual(['stranger']); + }); + + it('(b) control: the sole existing user is still elected on their own sign-in', async () => { + const f = fixture(); + f.user('existing-user', 'user', 'active', 2); + + await establishFirstSuperadmin(f.env, 'existing-user'); + + expect(f.superadmins()).toEqual(['existing-user']); + expect(f.electionOwner()).toBe('existing-user'); + }); + }); + + describe('concurrent first sign-ups', () => { + it('never produce two superadmins when both accounts exist before either election', async () => { + const f = fixture(); + f.user('oauth-user-a', 'user', 'pending', 2); + f.user('oauth-user-b', 'user', 'pending', 2); + + await Promise.all([ + establishFirstSuperadmin(f.env, 'oauth-user-a'), + establishFirstSuperadmin(f.env, 'oauth-user-b'), + ]); + + // Neither is the only real user, so both stay unprivileged (fail closed). Recovery: + // BOOTSTRAP_OWNER_EMAIL, documented in the self-hosting guide. + expect(f.superadmins()).toEqual([]); + expect(f.electionOwner()).toBeUndefined(); + expect(f.get('oauth-user-a')).toMatchObject({ role: 'user', status: 'pending' }); + expect(f.get('oauth-user-b')).toMatchObject({ role: 'user', status: 'pending' }); + }); + + it('elect exactly one when the first election lands before the second account exists', async () => { + const f = fixture(); + f.user('oauth-user-a', 'user', 'pending', 2); + await establishFirstSuperadmin(f.env, 'oauth-user-a'); + f.user('oauth-user-b', 'user', 'pending', 3); + + await establishFirstSuperadmin(f.env, 'oauth-user-b'); + + expect(f.superadmins()).toEqual(['oauth-user-a']); + expect(f.get('oauth-user-b')).toMatchObject({ role: 'user', status: 'pending' }); + expect(f.electionOwner()).toBe('oauth-user-a'); + }); + }); + + it('does not reopen the election after the elected user is deleted', async () => { + const f = fixture(); + f.user('first-user'); + await establishFirstSuperadmin(f.env, 'first-user'); + f.sqlite.prepare("DELETE FROM users WHERE id = 'first-user'").run(); + f.user('later-user'); + + await establishFirstSuperadmin(f.env, 'later-user'); + + expect(f.get('later-user')).toMatchObject({ role: 'user', status: 'pending' }); + expect(f.electionOwner()).toBe('first-user'); + }); + + it('keeps the election closed even when the initial read was stale', async () => { + // The marker can commit between the cheap initial read and the write batch. Feed the read a + // stale "not established" answer so only the guard inside the UPDATE stands in the way. + const f = fixture(); + f.sqlite + .prepare( + `INSERT INTO platform_settings (key, value, updated_at, updated_by) + VALUES (?, json_object('version', 1, 'ownerId', 'deleted-owner'), CURRENT_TIMESTAMP, NULL)` + ) + .run(FIRST_SUPERADMIN_SETTING); + f.user('sole-survivor', 'user', 'active', 3); + const real = f.env.DATABASE; + const staleRead = { + ...real, + prepare: (sql: string) => { + const statement = real.prepare(sql); + if (!sql.includes('AS established')) return statement; + return { + ...statement, + bind: () => ({ first: async () => ({ established: 0, superadmins: 0 }) }), + }; + }, + batch: real.batch.bind(real), + } as unknown as D1Database; + + await establishFirstSuperadmin({ DATABASE: staleRead }, 'sole-survivor'); + + expect(f.get('sole-survivor')).toMatchObject({ role: 'user', status: 'active' }); + expect(f.electionOwner()).toBe('deleted-owner'); + }); + + it('never promotes a suspended sole user', async () => { + const f = fixture(); + f.user('suspended-user', 'user', 'suspended', 2); + + await establishFirstSuperadmin(f.env, 'suspended-user'); + + expect(f.get('suspended-user')).toMatchObject({ role: 'user', status: 'suspended' }); + expect(f.electionOwner()).toBeUndefined(); + }); + + it('never promotes the system user, even on a sentinel-only install', async () => { + const f = fixture(); + + await establishFirstSuperadmin(f.env, SYSTEM_USER_ID); + + expect(f.get(SYSTEM_USER_ID)).toMatchObject({ role: 'user', status: 'system' }); + expect(f.electionOwner()).toBeUndefined(); + }); + + it('records an existing superadmin as the winner instead of promoting anyone', async () => { + const f = fixture(); + f.user('existing-admin', 'superadmin', 'active', 2); + + await establishFirstSuperadmin(f.env, 'existing-admin'); + + expect(f.superadmins()).toEqual(['existing-admin']); + expect(f.electionOwner()).toBe('existing-admin'); + }); + + it('reports more than one superadmin for review without changing any user', async () => { + const f = fixture(); + f.user('first-admin', 'superadmin', 'active', 2); + f.user('racing-admin', 'superadmin', 'active', 3); + applySqliteMigration(f.sqlite, MIGRATION); + const before = f.allUsers(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + + await establishFirstSuperadmin(f.env, 'racing-admin'); + + expect(f.allUsers()).toEqual(before); + const warning = warn.mock.calls + .map(([line]) => JSON.parse(String(line)) as Record) + .find((entry) => entry.event === 'first-superadmin.multiple_superadmins'); + expect(warning).toMatchObject({ level: 'warn', superadminCount: 2 }); + }); + + it('does not report a single superadmin', async () => { + const f = fixture(); + f.user('only-admin', 'superadmin', 'active', 2); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + + await establishFirstSuperadmin(f.env, 'only-admin'); + + expect(warn).not.toHaveBeenCalled(); + expect(f.electionOwner()).toBe('only-admin'); + }); +}); + +describe('first_superadmin_election migration — marks installs that already have a superadmin', () => { + it('keeps two existing superadmins untouched and records the oldest as the winner', () => { + const f = fixture(); + f.user('first-admin', 'superadmin', 'active', 3); + f.user('racing-admin', 'superadmin', 'active', 4); + f.user('member', 'user', 'active', 5); + const before = f.allUsers(); + + applySqliteMigration(f.sqlite, MIGRATION); + + expect(f.allUsers()).toEqual(before); + expect(f.superadmins().sort()).toEqual(['first-admin', 'racing-admin']); + expect(f.electionOwner()).toBe('first-admin'); + }); + + it('writes no marker without a superadmin, so the sole user can still win at sign-in', async () => { + const f = fixture(); + f.user('sole-user', 'user', 'active', 3); + + applySqliteMigration(f.sqlite, MIGRATION); + expect(f.electionOwner()).toBeUndefined(); + + await establishFirstSuperadmin(f.env, 'sole-user'); + expect(f.superadmins()).toEqual(['sole-user']); + }); + + it('writes no marker on a fresh install, so the first sign-up wins the election', async () => { + const f = fixture(); + + applySqliteMigration(f.sqlite, MIGRATION); + expect(f.electionOwner()).toBeUndefined(); + + f.user('first-user', 'user', 'pending', 3); + await establishFirstSuperadmin(f.env, 'first-user'); + expect(f.superadmins()).toEqual(['first-user']); + }); + + it('promotes nobody on an install with several users and no superadmin', async () => { + const f = fixture(); + f.user('existing-user-a', 'user', 'active', 3); + f.user('existing-user-b', 'user', 'pending', 4); + const before = f.allUsers(); + + applySqliteMigration(f.sqlite, MIGRATION); + await establishFirstSuperadmin(f.env, 'existing-user-a'); + await establishFirstSuperadmin(f.env, 'existing-user-b'); + + expect(f.electionOwner()).toBeUndefined(); + expect(f.allUsers()).toEqual(before); + }); + + it('never marks an install whose only superadmin-role row is the system user', () => { + const f = fixture(); + f.sqlite.prepare("UPDATE users SET role = 'superadmin' WHERE id = ?").run(SYSTEM_USER_ID); + + applySqliteMigration(f.sqlite, MIGRATION); + + expect(f.electionOwner()).toBeUndefined(); + }); +}); diff --git a/apps/api/tests/workers/superadmin-self-heal.test.ts b/apps/api/tests/workers/superadmin-self-heal.test.ts index 1f50e6666b..1ad0e23ac0 100644 --- a/apps/api/tests/workers/superadmin-self-heal.test.ts +++ b/apps/api/tests/workers/superadmin-self-heal.test.ts @@ -18,6 +18,7 @@ import { beforeEach, describe, expect, it } from 'vitest'; import { createAuth } from '../../src/auth'; import migrationSql from '../../src/db/migrations/0062_login_time_superadmin_self_heal.sql?raw'; +import { FIRST_SUPERADMIN_SETTING } from '../../src/services/first-superadmin'; /** * Miniflare's D1 `exec()` splits its input on newlines and runs each line as a @@ -45,6 +46,9 @@ interface UserRow { * we clear any real users left over from prior tests and re-assert the sentinel. */ async function resetUsers(): Promise { + await env.DATABASE.prepare('DELETE FROM platform_settings WHERE key = ?') + .bind(FIRST_SUPERADMIN_SETTING) + .run(); await env.DATABASE.prepare(`DELETE FROM users WHERE status != 'system'`).run(); await env.DATABASE.prepare( `INSERT INTO users (id, email, email_verified, role, status) @@ -210,22 +214,31 @@ describe('session.create.after — login-time self-heal (real D1)', () => { expect(await getUser('real-1')).toMatchObject({ role: 'user' }); }); - it('never promotes a suspended user, even as sole operator', async () => { - await insertUser('real-1', { role: 'user', status: 'suspended' }); + it('does not reopen administration after the one-time election has completed', async () => { + await insertUser('later-user', { role: 'user', status: 'pending' }); + await env.DATABASE.prepare( + `INSERT INTO platform_settings (key, value, updated_by) + VALUES (?, json_object('version', 1, 'ownerId', 'deleted-owner'), NULL)`, + ) + .bind(FIRST_SUPERADMIN_SETTING) + .run(); const hook = await getSessionAfterHook(); - await hook({ userId: 'real-1' }); + await hook({ userId: 'later-user' }); - expect(await getUser('real-1')).toMatchObject({ role: 'user', status: 'suspended' }); + expect(await getUser('later-user')).toMatchObject({ role: 'user', status: 'pending' }); }); - it('promotes a sole pending user on login (edge case 10)', async () => { - await insertUser('real-1', { role: 'user', status: 'pending' }); + it.each([ + ['never promotes a suspended user, even as sole operator', 'suspended', { role: 'user', status: 'suspended' }], + ['promotes a sole pending user on login (edge case 10)', 'pending', { role: 'superadmin', status: 'active' }], + ])('%s', async (_name, status, expected) => { + await insertUser('real-1', { role: 'user', status }); const hook = await getSessionAfterHook(); await hook({ userId: 'real-1' }); - expect(await getUser('real-1')).toMatchObject({ role: 'superadmin', status: 'active' }); + expect(await getUser('real-1')).toMatchObject(expected); }); it('promotes the sole user even when REQUIRE_APPROVAL is unset (open registration)', async () => { @@ -263,3 +276,136 @@ describe('session.create.after — login-time self-heal (real D1)', () => { expect(await getUser('real-1')).toMatchObject({ role: 'superadmin', status: 'active' }); }); }); + +/** + * The ordinary first-superadmin election runs in `session.create.before`. These tests create a + * session through BetterAuth's own `internalAdapter.createSession` (the path every sign-in takes, + * `services/session-factory.ts`), so the real hook chain runs against real D1. + */ +describe('session.create.before — first-superadmin election via BetterAuth (real D1)', () => { + beforeEach(resetUsers); + + async function createSession(userId: string, overrides?: Record) { + const auth = await createAuth(authEnv(overrides) as never); + const ctx = await auth.$context; + return ctx.internalAdapter.createSession(userId, false); + } + + async function electionMarker(): Promise { + const row = await env.DATABASE.prepare('SELECT value FROM platform_settings WHERE key = ?') + .bind(FIRST_SUPERADMIN_SETTING) + .first<{ value: string }>(); + return row ? (JSON.parse(row.value) as { ownerId: string }).ownerId : null; + } + + it('elects the sole real user when their first session is created', async () => { + await insertUser('first-user', { role: 'user', status: 'pending' }); + + const session = await createSession('first-user'); + + expect(session?.userId).toBe('first-user'); + expect(await getUser('first-user')).toMatchObject({ role: 'superadmin', status: 'active' }); + expect(await electionMarker()).toBe('first-user'); + }); + + it('does not elect a new sign-up while another real account exists', async () => { + await insertUser('existing-user', { role: 'user', status: 'suspended' }); + await insertUser('stranger', { role: 'user', status: 'pending' }); + + const session = await createSession('stranger'); + + expect(session?.userId).toBe('stranger'); + expect(await getUser('stranger')).toMatchObject({ role: 'user', status: 'pending' }); + expect(await electionMarker()).toBeNull(); + }); + + it('still creates the session, unpromoted, when D1 fails the election writes', async () => { + await insertUser('first-user', { role: 'user', status: 'pending' }); + // Fail every D1 batch (the election) and every UPDATE of users (the election and the + // after-hook self-heal), while BetterAuth's own session INSERT goes through. + const outage = () => Promise.reject(new Error('D1_ERROR: simulated outage')); + const failingWrites = new Proxy(env.DATABASE, { + get(target, property) { + if (property === 'batch') return outage; + if (property === 'prepare') { + return (sql: string) => { + const statement = target.prepare(sql); + if (!/^\s*UPDATE users\b/i.test(sql)) return statement; + return new Proxy(statement, { + get(inner, key) { + if (key === 'bind') return () => ({ run: outage, first: outage, all: outage }); + if (key === 'run' || key === 'first' || key === 'all') return outage; + const value = Reflect.get(inner, key, inner) as unknown; + return typeof value === 'function' ? value.bind(inner) : value; + }, + }); + }; + } + const value = Reflect.get(target, property, target) as unknown; + return typeof value === 'function' ? value.bind(target) : value; + }, + }); + + const session = await createSession('first-user', { DATABASE: failingWrites }); + + expect(session?.userId).toBe('first-user'); + const stored = await env.DATABASE.prepare('SELECT user_id FROM sessions WHERE id = ?') + .bind(session?.id) + .first<{ user_id: string }>(); + expect(stored?.user_id).toBe('first-user'); + expect(await getUser('first-user')).toMatchObject({ role: 'user', status: 'pending' }); + expect(await electionMarker()).toBeNull(); + + // Liveness: the same user is elected on the next sign-in once D1 recovers. + await createSession('first-user'); + expect(await getUser('first-user')).toMatchObject({ role: 'superadmin', status: 'active' }); + }); + + it('recovers a deleted sole superadmin through BOOTSTRAP_OWNER_EMAIL (documented path)', async () => { + // The election is closed for good: its winner was deleted and only ordinary accounts remain. + await env.DATABASE.prepare( + `INSERT INTO platform_settings (key, value, updated_by) + VALUES (?, json_object('version', 1, 'ownerId', 'deleted-owner'), NULL)`, + ) + .bind(FIRST_SUPERADMIN_SETTING) + .run(); + await insertUser('member', { role: 'user', status: 'active' }); + await insertUser('owner', { role: 'user', status: 'active' }); + const recovery = { BOOTSTRAP_OWNER_EMAIL: 'owner@example.com' }; + + try { + // Without the binding, the closed election promotes nobody. + await createSession('owner'); + expect(await getUser('owner')).toMatchObject({ role: 'user' }); + + await createSession('owner', recovery); + + expect(await getUser('owner')).toMatchObject({ role: 'superadmin', status: 'active' }); + expect(await getUser('member')).toMatchObject({ role: 'user', status: 'active' }); + } finally { + await env.DATABASE.prepare( + `DELETE FROM platform_settings WHERE key = 'setup.bootstrapOwnerEstablished'`, + ).run(); + } + }); + + it('skips the election on installer instances bound to BOOTSTRAP_OWNER_EMAIL', async () => { + await env.DATABASE.prepare( + `INSERT INTO platform_settings (key, value, updated_by) + VALUES ('setup.bootstrapOwnerEstablished', json_object('version', 1, 'ownerId', 'owner'), NULL) + ON CONFLICT(key) DO NOTHING`, + ).run(); + await insertUser('member', { role: 'user', status: 'active' }); + + try { + await createSession('member', { BOOTSTRAP_OWNER_EMAIL: 'owner@example.com' }); + + expect(await getUser('member')).toMatchObject({ role: 'user', status: 'active' }); + expect(await electionMarker()).toBeNull(); + } finally { + await env.DATABASE.prepare( + `DELETE FROM platform_settings WHERE key = 'setup.bootstrapOwnerEstablished'`, + ).run(); + } + }); +}); diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index 9561364bda..6246c8f0c3 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -15,7 +15,7 @@ Handoff removes hosted OAuth and deployment-credential copies while retaining th Experimental full installation is disabled by default and has not completed authenticated end-to-end validation. Its design separates temporary bootstrap OAuth, user-owned maintenance deployment authority, storage access, and narrower normal SAM runtime authority. Credential values pass through hosted bootstrap before transfer. Continued operation after OAuth revocation must be verified before claiming independence. Updates select an explicit immutable source version; they are not a promise of automatic conflict merging, transactional deployment, or database rollback. -For installer-bound instances, `BOOTSTRAP_OWNER_EMAIL` restricts initial administration to the matching verified email (verified by an OAuth provider or by an emailed sign-in code). Other initial identities are denied; an atomic election handles concurrent callbacks and durably records completion. Later changes to the elected owner's email, role or status do not reopen that election or lock out other authorized users; normal suspension checks still apply. The separate `SETUP_TOKEN` authorizes first-run setup, not user login. Setup closes once it completes or once the instance has an active superadmin (`isSetupCompleted`, `apps/api/src/services/platform-config-core.ts`), and the deploy job masks the token in its log (`scripts/deploy/setup-token.ts`), because the log of a public repository is public. A GitLab login provider can link a sign-in to an existing account by email, and refresh that account's profile, only when its host is `https://gitlab.com` or comes from the `GITLAB_HOST` Worker variable (`selectGitLabOAuthConfig`, `apps/api/src/services/platform-config-oauth.ts`): a self-managed host saved at runtime reports whatever its operator wants, so its email claims are treated as unverified and its accounts are stored under host-scoped ids (`untrustedGitLabUserInfo`, `apps/api/src/services/gitlab-sign-in-identity.ts`), because GitLab user ids are public and an account is otherwise matched on provider and id alone. Repository access then uses only a GitLab login the configured host issued (`gitlabAccountScope`, `getBetterAuthAccessTokenForProvider`), so one host's token is never refreshed against or sent to another; better-auth's HTTP token endpoints (`/api/auth/get-access-token`, `/refresh-token`, `/account-info`) are closed for the same reason (`routes/auth.ts`). A host saved at runtime that equals the `GITLAB_HOST` pin is trusted like the pin. GitHub and Google have fixed identity hosts and keep automatic linking. The installer's setup link carries it in the URL fragment, which browsers never send to a server; the setup page removes it from the address bar on load. Ordinary installations without this optional binding retain their existing first-user policy. +For installer-bound instances, `BOOTSTRAP_OWNER_EMAIL` restricts initial administration to the matching verified email (verified by an OAuth provider or by an emailed sign-in code). Other initial identities are denied; an atomic election handles concurrent callbacks and durably records completion. Later changes to the elected owner's email, role or status do not reopen that election or lock out other authorized users; normal suspension checks still apply. The separate `SETUP_TOKEN` authorizes first-run setup, not user login. Setup closes once it completes or once the instance has an active superadmin (`isSetupCompleted`, `apps/api/src/services/platform-config-core.ts`), and the deploy job masks the token in its log (`scripts/deploy/setup-token.ts`), because the log of a public repository is public. A GitLab login provider can link a sign-in to an existing account by email, and refresh that account's profile, only when its host is `https://gitlab.com` or comes from the `GITLAB_HOST` Worker variable (`selectGitLabOAuthConfig`, `apps/api/src/services/platform-config-oauth.ts`): a self-managed host saved at runtime reports whatever its operator wants, so its email claims are treated as unverified and its accounts are stored under host-scoped ids (`untrustedGitLabUserInfo`, `apps/api/src/services/gitlab-sign-in-identity.ts`), because GitLab user ids are public and an account is otherwise matched on provider and id alone. Repository access then uses only a GitLab login the configured host issued (`gitlabAccountScope`, `getBetterAuthAccessTokenForProvider`), so one host's token is never refreshed against or sent to another; better-auth's HTTP token endpoints (`/api/auth/get-access-token`, `/refresh-token`, `/account-info`) are closed for the same reason (`routes/auth.ts`). A host saved at runtime that equals the `GITLAB_HOST` pin is trusted like the pin. GitHub and Google have fixed identity hosts and keep automatic linking. The installer's setup link carries it in the URL fragment, which browsers never send to a server; the setup page removes it from the address bar on load. Ordinary installations without this optional binding elect their first superadmin once, with one atomic update that promotes the signing-in user only while they are the only real account, and record it durably so the election never reopens (`establishFirstSuperadmin`, `apps/api/src/services/first-superadmin.ts`). ## Cloud Credential Model (BYOC + Platform Fallback) diff --git a/apps/www/src/content/docs/docs/guides/admin-settings.md b/apps/www/src/content/docs/docs/guides/admin-settings.md index 269d366ba9..dadbfec641 100644 --- a/apps/www/src/content/docs/docs/guides/admin-settings.md +++ b/apps/www/src/content/docs/docs/guides/admin-settings.md @@ -20,6 +20,11 @@ Select **Admin** in the sidebar (only superadmins see it), then the **Settings** titled **Runtime settings**. An account must be an approved, active superadmin to use it; admins can't. +On an ordinary self-hosted instance, the first account to sign in while it is the only account +becomes the superadmin, once. That first-sign-in election never runs again, even if that +superadmin is deleted. If no account can open **Admin**, follow +[Recovering when no account can administer the instance](/docs/guides/self-hosting/#recovering-when-no-account-can-administer-the-instance). + Settings are grouped into **OAuth**, **Connector**, **Operations**, **Collaboration**, **Chat**, **AI models**, and **Email**. Type in **Search settings** to filter by name, group, or description. Each card is named after the setting, split into words (`operations.cronSweepsEnabled` diff --git a/apps/www/src/content/docs/docs/guides/self-hosting.mdx b/apps/www/src/content/docs/docs/guides/self-hosting.mdx index 635cf2e7b0..f0460bd88f 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -595,28 +595,49 @@ exactly `false`. Optional `CONTAINER_IMAGE_FINGERPRINT_TIMEOUT_MS` (default ## First Login & Admin Access -On ordinary deployments without an installer owner binding, the first genuine human to sign in becomes the **superadmin** — the account that can approve other users, manage platform credentials, and reach the admin dashboard. - -Installer deployments set the API Worker secret `BOOTSTRAP_OWNER_EMAIL` before enabling login. Until that owner is established, other identities are refused; only a matching verified email (from an OAuth provider, or proven by an emailed sign-in code) can establish initial administration. The owner is elected with an atomic database update, including concurrent callbacks from different providers. `SETUP_TOKEN` authorizes first-run setup; it does not itself grant a SAM user session. Finish `/setup`, then sign in with the approved owner email. +On ordinary deployments without an installer owner binding, the first genuine human to sign in becomes the **superadmin**: the account that can approve other users, manage platform credentials, and reach the admin dashboard. The promotion happens once, when that person's first session is created (`establishFirstSuperadmin`, `apps/api/src/services/first-superadmin.ts`), and only while they are the **only** real account on the instance. Email sign-in codes (`services/email-sign-in.ts`) create an account only for the installer owner email, before that owner exists. Otherwise only addresses that already belong to an account receive a code. Deployments without an owner email never create accounts by email, because the first person to ask for a code would become the administrator. The response is the same for every address, and the code is sent after the response, so its timing reveals nothing either. The password-reset, verification and email-change code routes are closed. Codes expire after 5 minutes and allow 3 attempts. Each address gets at most 5 codes an hour, each IP address at most 20 requests, and each address at most 10 code guesses an hour from all IP addresses combined (the `agentEmail.signInCodesPerEmailPerHour`, `agentEmail.signInCodesPerIpPerHour` and `agentEmail.signInCodeAttemptsPerEmailPerHour` settings). GitHub is not required before the instance exists. Preserve the owner binding across routine updates. -Fresh deployments are seeded with an internal system user (`system_anonymous_trials`, `status='system'`, created by a database migration). Its id dates from SAM's retired anonymous-trial product; it now records SAM itself as the author of platform settings saved during unattended setup, and it owns the placeholder GitHub installation row that Artifacts- and GitLab-backed projects point at. Never delete either row. This system user is **not** a real user, cannot sign in, and never counts toward "is this the first human" checks. Without the installer owner binding, two mechanisms handle first-user promotion regardless of the system user: +Fresh deployments are seeded with an internal system user (`system_anonymous_trials`, `status='system'`, created by a database migration). Its id dates from SAM's retired anonymous-trial product; it now records SAM itself as the author of platform settings saved during unattended setup, and it owns the placeholder GitHub installation row that Artifacts- and GitLab-backed projects point at. Never delete either row. This system user is **not** a real user, cannot sign in, and never counts toward "is this the first human" checks. + +Without the installer owner binding, the first-superadmin election works like this: + +- **One atomic write.** The promotion is a single guarded database update, so two sign-ups can never both become superadmin. It promotes the signing-in user only if they are not `suspended`, no other real account exists, and the election has not already happened. It then records the winner in the `platform_settings` row `setup.firstSuperadminEstablished`. +- **A later sign-up never wins.** If any other real account already exists, whether active, pending or suspended, nobody is promoted. If two people sign up at the same moment on a fresh instance and both accounts exist before either election runs, neither becomes superadmin. Use the recovery steps below. +- **The election happens once.** After the marker row exists, no sign-in is ever auto-promoted, even if every superadmin is later deleted. Instances that already had a superadmin got the marker from the `first_superadmin_election` database migration. That migration only writes the marker and never changes a user. +- **Login always succeeds.** If the database fails during the election, the sign-in still completes without promotion and the error is logged as `auth.first_superadmin_election.failed`. The next sign-in tries again. +- **Login-time self-heal** (`session.create.after`, `apps/api/src/auth.ts`) applies the same conditions and is a second attempt in the same sign-in. It is a no-op once the marker exists. + +#### More than one superadmin + +The admin API never grants the superadmin role, so an instance has at most one unless it was hit by the concurrent first-sign-up race that existed before this election, or someone edited the database by hand. SAM does not demote anyone automatically. On an instance without `BOOTSTRAP_OWNER_EMAIL`, each sign-in logs the warning `first-superadmin.multiple_superadmins` with the count, visible in the API Worker's logs (Cloudflare dashboard → Workers → your API worker → Logs, or `wrangler tail`). To review the accounts, run this against your D1 database: + +```sql +SELECT id, email, status, created_at FROM users +WHERE role = 'superadmin' AND status != 'system' ORDER BY created_at; +``` + +Demote any account you do not recognise with `UPDATE users SET role = 'user' WHERE id = '';`. The admin UI can't do this, because it refuses to modify superadmin accounts. + +#### Recovering when no account can administer the instance + +This applies when the only superadmin was deleted, or when no superadmin was ever elected (for example, after the simultaneous-sign-up case above). Pick one: -- **Deploy-time backfill** (migration): when a deployment has exactly one non-system human and no superadmin yet, that human is promoted to `superadmin`/`active` when migrations run. This also covers accounts created via token-login or device-flow. -- **Login-time self-heal** (all sign-in paths): on every session creation — GitHub OAuth, token-login, and device-flow — if the signing-in user is the only non-system human and no superadmin exists, they are promoted in a single atomic, idempotent write. A failure here never blocks login. +1. **Bind an owner email (recommended).** Add the API Worker secret `BOOTSTRAP_OWNER_EMAIL` with the email address of the person who should administer the instance: `wrangler secret put BOOTSTRAP_OWNER_EMAIL --name ` (the worker is named `-api-`), or in the Cloudflare dashboard under the API worker's **Settings → Variables and Secrets**. Deploys leave a secret they don't set in place (`scripts/deploy/configure-secrets.sh` skips an empty value). That person then signs in with that address as a **verified** email. While no superadmin exists, the owner path (`bootstrapSessionAllowed`, `apps/api/src/services/bootstrap-owner.ts`) promotes them. It does not depend on the first-superadmin marker. Until the owner has signed in, every other sign-in is refused. After that, normal sign-in resumes and the secret can stay or be removed. This option does not work on an installer-bound instance whose owner was already established (the `setup.bootstrapOwnerEstablished` row exists): the owner path runs only until that row is written, so use option 2 there. +2. **Edit D1 directly.** Promote a specific account: `UPDATE users SET role = 'superadmin', status = 'active' WHERE id = '';` (`wrangler d1 execute --remote --command "..."`). Role checks read the database on every request, so a page refresh is enough. -Both mechanisms apply the same promotion conditions and are strictly no-ops in any other state — they never promote a second user, never touch an existing superadmin, and never auto-promote a `suspended` or `system` account. They differ only in how they exclude the system user: the login-time hook excludes it by both `status='system'` and id, while the deploy-time migration excludes it by `status='system'` alone. On managed/multi-user deployments nothing changes. +Deleting the `setup.firstSuperadminEstablished` row does not choose an account. It only lets the election run again, and the election still promotes nobody unless exactly one real account exists. Notes: - **Promotion is independent of `REQUIRE_APPROVAL`.** Installer-bound deployments still require the configured verified owner identity. -- **Installer first-login race:** the owner-bound election promotes at most one matching verified user, including simultaneous provider callbacks. +- **First-login races:** both the owner-bound election and the ordinary election promote at most one user, including simultaneous provider callbacks. - **Session freshness:** SAM disables BetterAuth’s session-cookie cache when reading authorization state, so role and suspension checks use current database data. Refresh the page after a promotion; if access is still missing, recheck the promotion conditions rather than waiting for a cookie-cache timeout. ### Signup approval -When signup approval is on (`REQUIRE_APPROVAL`, or the runtime switch in **Admin → Users**), new accounts are created **pending** (except the very first, which becomes superadmin) and stay pending until a superadmin approves them there. Accounts created while approval was off stay active. A pending account can sign in, see that it is waiting for approval, sign out, and link its own GitHub App installation. SAM's features answer `403 APPROVAL_REQUIRED` until the account is approved, including the SAM and project agent chats, API token management, every project route, and browser-session workspace access. This also applies to pending accounts that already own resources when approval is turned on. Admins and superadmins are never held for approval, and suspended accounts are refused on authenticated account surfaces. Publicly published workspace ports and valid port-access links use their own anonymous or capability access model. +When signup approval is on (`REQUIRE_APPROVAL`, or the runtime switch in **Admin → Users**), new accounts are created **pending** (the very first is promoted to an active superadmin when its first session starts) and stay pending until a superadmin approves them there. Accounts created while approval was off stay active. A pending account can sign in, see that it is waiting for approval, sign out, and link its own GitHub App installation. SAM's features answer `403 APPROVAL_REQUIRED` until the account is approved, including the SAM and project agent chats, API token management, every project route, and browser-session workspace access. This also applies to pending accounts that already own resources when approval is turned on. Admins and superadmins are never held for approval, and suspended accounts are refused on authenticated account surfaces. Publicly published workspace ports and valid port-access links use their own anonymous or capability access model. ### Storage and archive circuit breakers diff --git a/apps/www/src/content/docs/docs/reference/configuration.md b/apps/www/src/content/docs/docs/reference/configuration.md index 9bb3364f68..2d78b5894c 100644 --- a/apps/www/src/content/docs/docs/reference/configuration.md +++ b/apps/www/src/content/docs/docs/reference/configuration.md @@ -59,7 +59,7 @@ These are Cloudflare Worker secrets, set during deployment. Pulumi auto-generate | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ENCRYPTION_KEY` | AES-256-GCM master key. Used for BetterAuth session cookies and user credential encryption unless a purpose-specific override below is set (auto-generated) | | `BETTER_AUTH_SECRET` | Optional purpose-specific override for BetterAuth session cookie signing/encryption. Falls back to `ENCRYPTION_KEY` when unset (`apps/api/src/lib/secrets.ts`) | -| `BOOTSTRAP_OWNER_EMAIL` | Optional installer-managed Worker secret restricting first administration to this verified login email. Unset preserves manual-install behavior. Set before enabling login; preserve across updates. | +| `BOOTSTRAP_OWNER_EMAIL` | Optional installer-managed Worker secret restricting first administration to this verified login email. Unset preserves manual-install behavior. Set before enabling login; preserve across updates. Also the recovery path when no superadmin remains (self-hosting guide). | | `CREDENTIAL_ENCRYPTION_KEY` | Optional purpose-specific override for AES-GCM encryption of user cloud/agent credentials. Falls back to `ENCRYPTION_KEY` when unset (`apps/api/src/lib/secrets.ts`) | | `JWT_PRIVATE_KEY` | RSA-2048 private key for signing tokens (auto-generated) | | `JWT_PUBLIC_KEY` | RSA-2048 public key for token verification (exposed via JWKS) |