From d2b0f77306524a174fc16f37fa2baaed3bca9fc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 12:46:11 +0100 Subject: [PATCH 1/8] Fix security finding acf_1c430965be49bdf046a1933ae3b533a0 --- apps/api/src/auth.ts | 48 +++--- .../0242_first_superadmin_election.sql | 41 +++++ apps/api/src/routes/agent-sign-in.ts | 5 +- apps/api/src/services/first-superadmin.ts | 61 ++++++++ apps/api/tests/unit/auth.test.ts | 85 +++++++---- .../unit/services/first-superadmin.test.ts | 143 ++++++++++++++++++ .../workers/superadmin-self-heal.test.ts | 19 +++ 7 files changed, 348 insertions(+), 54 deletions(-) create mode 100644 apps/api/src/db/migrations/0242_first_superadmin_election.sql create mode 100644 apps/api/src/services/first-superadmin.ts create mode 100644 apps/api/tests/unit/services/first-superadmin.test.ts diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts index a62a2986df..43dc1809a2 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,10 @@ 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 +45,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 +74,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 +400,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 +413,9 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { create: { before: async (session) => { if (!(await bootstrapSessionAllowed(env, session.userId))) return false; + if (bootstrapOwnerEmail(env) === undefined) { + await establishFirstSuperadmin(env, session.userId); + } return { data: session }; }, // Login-time superadmin self-heal. Fires on EVERY session creation — @@ -441,12 +440,17 @@ 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/0242_first_superadmin_election.sql b/apps/api/src/db/migrations/0242_first_superadmin_election.sql new file mode 100644 index 0000000000..db3a5b8e7f --- /dev/null +++ b/apps/api/src/db/migrations/0242_first_superadmin_election.sql @@ -0,0 +1,41 @@ +-- Close the ordinary first-superadmin election on installations that already have an +-- administrator or multiple real users. A sole non-admin stays eligible for the existing +-- single-operator self-heal. New installations have only the status='system' sentinel when this +-- migration runs, so their first session can atomically create this marker and promote its owner. +-- The marker is durable even if that owner is later deleted, preventing initial administration +-- from reopening. Multiple non-system superadmins can only originate from the former concurrent +-- bootstrap race: the admin API never accepts 'superadmin' as a role change. Keep the oldest active +-- winner and return every other active duplicate to the ordinary pending approval path. +UPDATE users +SET + role = 'user', + status = CASE WHEN status = 'active' THEN 'pending' ELSE status END, + updated_at = cast(unixepoch() * 1000 as integer) +WHERE role = 'superadmin' + AND status != 'system' + AND id != ( + SELECT winner.id + FROM users winner + WHERE winner.role = 'superadmin' AND winner.status != 'system' + ORDER BY CASE WHEN winner.status = 'active' THEN 0 ELSE 1 END, winner.created_at, winner.id + LIMIT 1 + ); + +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 status != 'system' + AND ( + role = 'superadmin' + OR (SELECT COUNT(*) FROM users real_user WHERE real_user.status != 'system') > 1 + ) +ORDER BY + CASE WHEN role = 'superadmin' THEN 0 ELSE 1 END, + CASE WHEN status = 'active' THEN 0 ELSE 1 END, + 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..b8d79e4323 --- /dev/null +++ b/apps/api/src/services/first-superadmin.ts @@ -0,0 +1,61 @@ +import type { Env } from '../env'; + +type FirstSuperadminEnv = Pick; + +export const FIRST_SUPERADMIN_SETTING = 'setup.firstSuperadminEstablished'; + +/** + * Elect the first ordinary-install administrator after BetterAuth has inserted the user. + * + * The initial read only avoids a write batch on every later login. The INSERT and promotion are + * the authoritative security boundary: D1 executes the batch atomically, the settings primary + * key admits one winner, and the UPDATE trusts only the user id stored by that winning INSERT. + */ +export async function establishFirstSuperadmin( + env: FirstSuperadminEnv, + userId: string +): Promise { + const established = await env.DATABASE.prepare( + 'SELECT 1 AS established FROM platform_settings WHERE key = ? LIMIT 1' + ) + .bind(FIRST_SUPERADMIN_SETTING) + .first(); + if (established) return; + + await env.DATABASE.batch([ + env.DATABASE.prepare( + `INSERT OR IGNORE INTO platform_settings (key, value, updated_at, updated_by) + SELECT ?, json_object('version', 1, 'ownerId', selected.id), CURRENT_TIMESTAMP, selected.id + FROM users selected + WHERE selected.id = COALESCE( + (SELECT administrator.id FROM users administrator + WHERE administrator.role = 'superadmin' AND administrator.status != 'system' + ORDER BY administrator.id LIMIT 1), + (SELECT candidate.id FROM users candidate + WHERE candidate.id = ? + AND candidate.status != 'system' + AND candidate.status != 'suspended' + LIMIT 1) + )` + ).bind(FIRST_SUPERADMIN_SETTING, userId), + env.DATABASE.prepare( + `UPDATE users + SET role = 'superadmin', status = 'active' + WHERE id = ? + AND role != 'superadmin' + AND status != 'system' + AND status != 'suspended' + AND EXISTS ( + SELECT 1 FROM platform_settings election + WHERE election.key = ? + AND json_extract(election.value, '$.version') = 1 + AND json_extract(election.value, '$.ownerId') = users.id + ) + AND NOT EXISTS ( + SELECT 1 FROM users administrator + WHERE administrator.role = 'superadmin' + AND administrator.status != 'system' + )` + ).bind(userId, FIRST_SUPERADMIN_SETTING), + ]); +} diff --git a/apps/api/tests/unit/auth.test.ts b/apps/api/tests/unit/auth.test.ts index 5c2cfb12b7..5ba294d2cc 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,32 @@ 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(); - - const result = await beforeCreate(newUser); + it('elects an ordinary first administrator at the session boundary', async () => { + const beforeSession = await getSessionBeforeHook(fakeEnv()); - expect(result.data).toMatchObject({ - id: newUser.id, - role: 'user', - status: 'pending', + await expect(beforeSession({ userId: newUser.id })).resolves.toEqual({ + data: { userId: newUser.id }, }); + + expect(mocks.establishFirstSuperadmin).toHaveBeenCalledOnce(); + expect(mocks.establishFirstSuperadmin).toHaveBeenCalledWith( + expect.objectContaining({ BASE_DOMAIN: 'example.com' }), + newUser.id + ); }); it('uses the migration-seeded system user id', () => { @@ -288,8 +304,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 +326,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 +430,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 +466,6 @@ 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([]); 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..56a1dfc604 --- /dev/null +++ b/apps/api/tests/unit/services/first-superadmin.test.ts @@ -0,0 +1,143 @@ +import { readFileSync } from 'node:fs'; + +import Database from 'better-sqlite3'; +import { afterEach, describe, expect, it } from 'vitest'; + +import type { Env } from '../../../src/env'; +import { + establishFirstSuperadmin, + FIRST_SUPERADMIN_SETTING, +} from '../../../src/services/first-superadmin'; +import { createSqliteD1 } from '../../helpers/sqlite-d1'; + +const databases: Database.Database[] = []; + +function fixture() { + const sqlite = new Database(':memory:'); + databases.push(sqlite); + sqlite.exec(`PRAGMA foreign_keys=ON; + CREATE TABLE users ( + id TEXT PRIMARY KEY, + role TEXT NOT NULL, + status TEXT NOT NULL, + created_at INTEGER NOT NULL + ); + CREATE TABLE platform_settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT, + updated_by TEXT REFERENCES users(id) ON DELETE SET NULL + ); + INSERT INTO users VALUES ('system_anonymous_trials', 'user', 'system', 1);`); + const env = { DATABASE: createSqliteD1(sqlite) } as Env; + const user = (id: string, role = 'user', status = 'pending', createdAt = 2) => + sqlite.prepare('INSERT INTO users VALUES (?, ?, ?, ?)').run(id, role, status, createdAt); + return { env, sqlite, user }; +} + +function electionOwner(sqlite: Database.Database): string | undefined { + 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).ownerId as string) : undefined; +} + +afterEach(() => { + for (const database of databases.splice(0)) database.close(); +}); + +describe('ordinary first-superadmin election', () => { + it('promotes the first session user and permanently records its identity', async () => { + const f = fixture(); + f.user('first-user'); + + await establishFirstSuperadmin(f.env, 'first-user'); + + expect(f.sqlite.prepare("SELECT role, status FROM users WHERE id='first-user'").get()).toEqual({ + role: 'superadmin', + status: 'active', + }); + expect(electionOwner(f.sqlite)).toBe('first-user'); + }); + + it('elects exactly one winner across concurrent first sessions and leaves the loser pending', async () => { + const f = fixture(); + f.user('oauth-user-a'); + f.user('oauth-user-b'); + + await Promise.all([ + establishFirstSuperadmin(f.env, 'oauth-user-a'), + establishFirstSuperadmin(f.env, 'oauth-user-b'), + ]); + + const users = f.sqlite + .prepare("SELECT id, role, status FROM users WHERE status != 'system' ORDER BY id") + .all() as Array<{ id: string; role: string; status: string }>; + expect(users.filter((user) => user.role === 'superadmin')).toHaveLength(1); + expect(users.filter((user) => user.status === 'pending')).toHaveLength(1); + expect(electionOwner(f.sqlite)).toBe(users.find((user) => user.role === 'superadmin')?.id); + }); + + it('does not reopen first-user administration 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.sqlite.prepare("SELECT role, status FROM users WHERE id='later-user'").get()).toEqual({ + role: 'user', + status: 'pending', + }); + expect(electionOwner(f.sqlite)).toBe('first-user'); + }); + + it('marks upgraded installations while leaving eligible single-operator installations open', async () => { + const migration = readFileSync( + new URL('../../../src/db/migrations/0242_first_superadmin_election.sql', import.meta.url), + 'utf8' + ); + expect(migration).toContain(FIRST_SUPERADMIN_SETTING); + const fresh = fixture(); + fresh.sqlite.exec(migration); + expect(electionOwner(fresh.sqlite)).toBeUndefined(); + + const upgraded = fixture(); + upgraded.user('existing-user', 'user', 'active', 3); + upgraded.user('existing-admin', 'superadmin', 'active', 4); + upgraded.sqlite.exec(migration); + expect(electionOwner(upgraded.sqlite)).toBe('existing-admin'); + + const racedUpgrade = fixture(); + racedUpgrade.user('first-admin', 'superadmin', 'active', 3); + racedUpgrade.user('racing-admin', 'superadmin', 'active', 4); + racedUpgrade.sqlite.exec(migration); + expect( + racedUpgrade.sqlite + .prepare("SELECT id, role, status FROM users WHERE status != 'system' ORDER BY id") + .all() + ).toEqual([ + { id: 'first-admin', role: 'superadmin', status: 'active' }, + { id: 'racing-admin', role: 'user', status: 'pending' }, + ]); + expect(electionOwner(racedUpgrade.sqlite)).toBe('first-admin'); + + const orphanedSingleOperator = fixture(); + orphanedSingleOperator.user('sole-user', 'user', 'active', 3); + orphanedSingleOperator.sqlite.exec(migration); + expect(electionOwner(orphanedSingleOperator.sqlite)).toBeUndefined(); + + const establishedWithoutAdmin = fixture(); + establishedWithoutAdmin.user('existing-user-a', 'user', 'active', 3); + establishedWithoutAdmin.user('existing-user-b', 'user', 'pending', 4); + establishedWithoutAdmin.sqlite.exec(migration); + await establishFirstSuperadmin(establishedWithoutAdmin.env, 'existing-user-b'); + expect( + establishedWithoutAdmin.sqlite + .prepare("SELECT COUNT(*) AS count FROM users WHERE role='superadmin'") + .get() + ).toEqual({ count: 0 }); + }); +}); diff --git a/apps/api/tests/workers/superadmin-self-heal.test.ts b/apps/api/tests/workers/superadmin-self-heal.test.ts index 1f50e6666b..9fe2f3feef 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,6 +214,21 @@ describe('session.create.after — login-time self-heal (real D1)', () => { expect(await getUser('real-1')).toMatchObject({ role: 'user' }); }); + 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: 'later-user' }); + + expect(await getUser('later-user')).toMatchObject({ role: 'user', status: 'pending' }); + }); + it('never promotes a suspended user, even as sole operator', async () => { await insertUser('real-1', { role: 'user', status: 'suspended' }); const hook = await getSessionAfterHook(); From 168004f8ba19f14a9153fdc783ccc0a013907916 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 14:14:01 +0000 Subject: [PATCH 2/8] fix(api): race-safe first-superadmin election without demoting anyone Corrects the bot election from #2753: - Election (services/first-superadmin.ts): promote the signing-in user in one guarded UPDATE only while they are the ONLY real (status != 'system') account, are not suspended, and the election marker is absent; then record the oldest real superadmin as the marker in the same D1 batch. A later sign-up never wins against an existing account (suspended or non-admin), and two sign-ups whose rows both exist fail closed rather than electing by timing. - Report installs with more than one superadmin via a structured first-superadmin.multiple_superadmins warning on sign-in, folded into the existing single read. No user row is changed. - session.create.before: catch election failures, log auth.first_superadmin_election.failed and continue without promotion, so a D1 error never blocks login. - Migration renumbered 0242 -> 0243 (open PR #2721 already uses 0242). It now only inserts the marker for installs that already have a non-system superadmin and never updates or deletes users; the oldest-superadmin demotion is removed. - Tests: real-SQL election/migration tests on drizzle-built tables (attack cases paired with owner controls), the auth.test fixture regression, and workers tests that drive BetterAuth's createSession against real D1 (happy path, existing-account refusal, D1 outage, owner-email skip, and the BOOTSTRAP_OWNER_EMAIL recovery path). Co-Authored-By: Claude Opus 5.5 --- apps/api/src/auth.ts | 24 +- .../0242_first_superadmin_election.sql | 41 -- .../0243_first_superadmin_election.sql | 25 ++ apps/api/src/services/first-superadmin.ts | 118 ++++-- apps/api/tests/unit/auth.test.ts | 18 + .../unit/services/first-superadmin.test.ts | 390 +++++++++++++----- .../workers/superadmin-self-heal.test.ts | 133 ++++++ 7 files changed, 553 insertions(+), 196 deletions(-) delete mode 100644 apps/api/src/db/migrations/0242_first_superadmin_election.sql create mode 100644 apps/api/src/db/migrations/0243_first_superadmin_election.sql diff --git a/apps/api/src/auth.ts b/apps/api/src/auth.ts index 43dc1809a2..d87399780e 100644 --- a/apps/api/src/auth.ts +++ b/apps/api/src/auth.ts @@ -17,10 +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 { establishFirstSuperadmin, FIRST_SUPERADMIN_SETTING } from './services/first-superadmin'; import { refreshGitHubAccessToken } from './services/github-oauth-refresh'; import { untrustedGitLabUserInfo } from './services/gitlab-sign-in-identity'; import { @@ -414,7 +411,17 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { before: async (session) => { if (!(await bootstrapSessionAllowed(env, session.userId))) return false; if (bootstrapOwnerEmail(env) === undefined) { - await establishFirstSuperadmin(env, session.userId); + // 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 }; }, @@ -445,12 +452,7 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) { const result = await ( expectedOwner === undefined ? statement.bind(userId, sentinelId, FIRST_SUPERADMIN_SETTING) - : statement.bind( - userId, - sentinelId, - FIRST_SUPERADMIN_SETTING, - expectedOwner - ) + : 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/0242_first_superadmin_election.sql b/apps/api/src/db/migrations/0242_first_superadmin_election.sql deleted file mode 100644 index db3a5b8e7f..0000000000 --- a/apps/api/src/db/migrations/0242_first_superadmin_election.sql +++ /dev/null @@ -1,41 +0,0 @@ --- Close the ordinary first-superadmin election on installations that already have an --- administrator or multiple real users. A sole non-admin stays eligible for the existing --- single-operator self-heal. New installations have only the status='system' sentinel when this --- migration runs, so their first session can atomically create this marker and promote its owner. --- The marker is durable even if that owner is later deleted, preventing initial administration --- from reopening. Multiple non-system superadmins can only originate from the former concurrent --- bootstrap race: the admin API never accepts 'superadmin' as a role change. Keep the oldest active --- winner and return every other active duplicate to the ordinary pending approval path. -UPDATE users -SET - role = 'user', - status = CASE WHEN status = 'active' THEN 'pending' ELSE status END, - updated_at = cast(unixepoch() * 1000 as integer) -WHERE role = 'superadmin' - AND status != 'system' - AND id != ( - SELECT winner.id - FROM users winner - WHERE winner.role = 'superadmin' AND winner.status != 'system' - ORDER BY CASE WHEN winner.status = 'active' THEN 0 ELSE 1 END, winner.created_at, winner.id - LIMIT 1 - ); - -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 status != 'system' - AND ( - role = 'superadmin' - OR (SELECT COUNT(*) FROM users real_user WHERE real_user.status != 'system') > 1 - ) -ORDER BY - CASE WHEN role = 'superadmin' THEN 0 ELSE 1 END, - CASE WHEN status = 'active' THEN 0 ELSE 1 END, - created_at, - id -LIMIT 1; diff --git a/apps/api/src/db/migrations/0243_first_superadmin_election.sql b/apps/api/src/db/migrations/0243_first_superadmin_election.sql new file mode 100644 index 0000000000..2c9a5278d8 --- /dev/null +++ b/apps/api/src/db/migrations/0243_first_superadmin_election.sql @@ -0,0 +1,25 @@ +-- 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 pre-0243 concurrent +-- first sign-up race, 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/services/first-superadmin.ts b/apps/api/src/services/first-superadmin.ts index b8d79e4323..4d94b59905 100644 --- a/apps/api/src/services/first-superadmin.ts +++ b/apps/api/src/services/first-superadmin.ts @@ -1,61 +1,93 @@ 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 migration 0243 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'; /** - * Elect the first ordinary-install administrator after BetterAuth has inserted the user. + * 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 only avoids a write batch on every later login. The INSERT and promotion are - * the authoritative security boundary: D1 executes the batch atomically, the settings primary - * key admits one winner, and the UPDATE trusts only the user id stored by that winning INSERT. + * 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 pre-0243 sign-up race 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 established = await env.DATABASE.prepare( - 'SELECT 1 AS established FROM platform_settings WHERE key = ? LIMIT 1' + 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(); - if (established) return; + .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; - await env.DATABASE.batch([ - env.DATABASE.prepare( - `INSERT OR IGNORE INTO platform_settings (key, value, updated_at, updated_by) - SELECT ?, json_object('version', 1, 'ownerId', selected.id), CURRENT_TIMESTAMP, selected.id - FROM users selected - WHERE selected.id = COALESCE( - (SELECT administrator.id FROM users administrator - WHERE administrator.role = 'superadmin' AND administrator.status != 'system' - ORDER BY administrator.id LIMIT 1), - (SELECT candidate.id FROM users candidate - WHERE candidate.id = ? - AND candidate.status != 'system' - AND candidate.status != 'suspended' - LIMIT 1) - )` - ).bind(FIRST_SUPERADMIN_SETTING, userId), - env.DATABASE.prepare( - `UPDATE users - SET role = 'superadmin', status = 'active' - WHERE id = ? - AND role != 'superadmin' - AND status != 'system' - AND status != 'suspended' - AND EXISTS ( - SELECT 1 FROM platform_settings election - WHERE election.key = ? - AND json_extract(election.value, '$.version') = 1 - AND json_extract(election.value, '$.ownerId') = users.id - ) - AND NOT EXISTS ( - SELECT 1 FROM users administrator - WHERE administrator.role = 'superadmin' - AND administrator.status != 'system' - )` - ).bind(userId, FIRST_SUPERADMIN_SETTING), + 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 5ba294d2cc..a8ace1fe6c 100644 --- a/apps/api/tests/unit/auth.test.ts +++ b/apps/api/tests/unit/auth.test.ts @@ -262,6 +262,23 @@ describe('BetterAuth configuration', () => { ); }); + 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', () => { expect(SYSTEM_USER_ID).toBe('system_anonymous_trials'); }); @@ -466,6 +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'); + 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 index 56a1dfc604..f5e36e7269 100644 --- a/apps/api/tests/unit/services/first-superadmin.test.ts +++ b/apps/api/tests/unit/services/first-superadmin.test.ts @@ -1,143 +1,331 @@ -import { readFileSync } from 'node:fs'; - +/** + * 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 { SYSTEM_USER_ID } from '@simple-agent-manager/shared'; import Database from 'better-sqlite3'; -import { afterEach, describe, expect, it } from 'vitest'; +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 { createSqliteD1 } from '../../helpers/sqlite-d1'; +import { applySqliteMigration, createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; + +const MIGRATION = new URL( + '../../../src/db/migrations/0243_first_superadmin_election.sql', + import.meta.url +); const databases: Database.Database[] = []; +interface UserRow { + id: string; + role: string; + status: string; +} + function fixture() { const sqlite = new Database(':memory:'); databases.push(sqlite); - sqlite.exec(`PRAGMA foreign_keys=ON; - CREATE TABLE users ( - id TEXT PRIMARY KEY, - role TEXT NOT NULL, - status TEXT NOT NULL, - created_at INTEGER NOT NULL - ); - CREATE TABLE platform_settings ( - key TEXT PRIMARY KEY, - value TEXT NOT NULL, - updated_at TEXT, - updated_by TEXT REFERENCES users(id) ON DELETE SET NULL - ); - INSERT INTO users VALUES ('system_anonymous_trials', 'user', 'system', 1);`); + 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) => - sqlite.prepare('INSERT INTO users VALUES (?, ?, ?, ?)').run(id, role, status, createdAt); - return { env, sqlite, user }; -} - -function electionOwner(sqlite: Database.Database): string | undefined { - 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).ownerId as string) : undefined; + 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('ordinary first-superadmin election', () => { - it('promotes the first session user and permanently records its identity', async () => { +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.sqlite.prepare("SELECT role, status FROM users WHERE id='first-user'").get()).toEqual({ - role: 'superadmin', - status: 'active', - }); - expect(electionOwner(f.sqlite)).toBe('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('elects exactly one winner across concurrent first sessions and leaves the loser pending', async () => { + it('is idempotent: a second sign-in of the winner changes nothing', async () => { const f = fixture(); - f.user('oauth-user-a'); - f.user('oauth-user-b'); + f.user('first-user'); + await establishFirstSuperadmin(f.env, 'first-user'); + const before = f.allUsers(); - await Promise.all([ - establishFirstSuperadmin(f.env, 'oauth-user-a'), - establishFirstSuperadmin(f.env, 'oauth-user-b'), - ]); + await establishFirstSuperadmin(f.env, 'first-user'); - const users = f.sqlite - .prepare("SELECT id, role, status FROM users WHERE status != 'system' ORDER BY id") - .all() as Array<{ id: string; role: string; status: string }>; - expect(users.filter((user) => user.role === 'superadmin')).toHaveLength(1); - expect(users.filter((user) => user.status === 'pending')).toHaveLength(1); - expect(electionOwner(f.sqlite)).toBe(users.find((user) => user.role === 'superadmin')?.id); + expect(f.allUsers()).toEqual(before); + expect(f.electionOwner()).toBe('first-user'); }); - it('does not reopen first-user administration after the elected user is deleted', async () => { + describe('a later sign-up never wins against an existing account', () => { + it('(a) does not promote a new sign-up while the sole existing user is suspended', async () => { + const f = fixture(); + f.user('suspended-owner', 'user', 'suspended', 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) does not promote a new sign-up while the sole existing user is a non-admin', async () => { + const f = fixture(); + f.user('existing-user', 'user', '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('(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.sqlite.prepare("DELETE FROM users WHERE id = 'first-user'").run(); f.user('later-user'); await establishFirstSuperadmin(f.env, 'later-user'); - expect(f.sqlite.prepare("SELECT role, status FROM users WHERE id='later-user'").get()).toEqual({ - role: 'user', - status: 'pending', - }); - expect(electionOwner(f.sqlite)).toBe('first-user'); - }); - - it('marks upgraded installations while leaving eligible single-operator installations open', async () => { - const migration = readFileSync( - new URL('../../../src/db/migrations/0242_first_superadmin_election.sql', import.meta.url), - 'utf8' - ); - expect(migration).toContain(FIRST_SUPERADMIN_SETTING); - const fresh = fixture(); - fresh.sqlite.exec(migration); - expect(electionOwner(fresh.sqlite)).toBeUndefined(); - - const upgraded = fixture(); - upgraded.user('existing-user', 'user', 'active', 3); - upgraded.user('existing-admin', 'superadmin', 'active', 4); - upgraded.sqlite.exec(migration); - expect(electionOwner(upgraded.sqlite)).toBe('existing-admin'); - - const racedUpgrade = fixture(); - racedUpgrade.user('first-admin', 'superadmin', 'active', 3); - racedUpgrade.user('racing-admin', 'superadmin', 'active', 4); - racedUpgrade.sqlite.exec(migration); - expect( - racedUpgrade.sqlite - .prepare("SELECT id, role, status FROM users WHERE status != 'system' ORDER BY id") - .all() - ).toEqual([ - { id: 'first-admin', role: 'superadmin', status: 'active' }, - { id: 'racing-admin', role: 'user', status: 'pending' }, - ]); - expect(electionOwner(racedUpgrade.sqlite)).toBe('first-admin'); - - const orphanedSingleOperator = fixture(); - orphanedSingleOperator.user('sole-user', 'user', 'active', 3); - orphanedSingleOperator.sqlite.exec(migration); - expect(electionOwner(orphanedSingleOperator.sqlite)).toBeUndefined(); - - const establishedWithoutAdmin = fixture(); - establishedWithoutAdmin.user('existing-user-a', 'user', 'active', 3); - establishedWithoutAdmin.user('existing-user-b', 'user', 'pending', 4); - establishedWithoutAdmin.sqlite.exec(migration); - await establishFirstSuperadmin(establishedWithoutAdmin.env, 'existing-user-b'); - expect( - establishedWithoutAdmin.sqlite - .prepare("SELECT COUNT(*) AS count FROM users WHERE role='superadmin'") - .get() - ).toEqual({ count: 0 }); + 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('migration 0243 — 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 9fe2f3feef..2aed421d26 100644 --- a/apps/api/tests/workers/superadmin-self-heal.test.ts +++ b/apps/api/tests/workers/superadmin-self-heal.test.ts @@ -282,3 +282,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(); + } + }); +}); From 20c8d06717f7e68876219129cdb89c8496efa2e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 14:14:05 +0000 Subject: [PATCH 3/8] docs: first-superadmin election, duplicate superadmins and admin recovery Describe the one-time ordinary election (only-real-account guard, durable setup.firstSuperadminEstablished marker, login never blocked), how to review and resolve more than one superadmin, and the recovery paths when no account can administer the instance: the BOOTSTRAP_OWNER_EMAIL Worker secret (bootstrapSessionAllowed) or a direct D1 update. Co-Authored-By: Claude Opus 5.5 --- .../docs/docs/architecture/security.md | 2 +- .../docs/docs/guides/admin-settings.md | 5 +++ .../content/docs/docs/guides/self-hosting.mdx | 39 ++++++++++++++----- .../docs/docs/reference/configuration.md | 2 +- 4 files changed, 37 insertions(+), 11 deletions(-) diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index 03ebd44b5c..cad7f448b8 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 85d023653e..d4c71b0e42 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. SAM never promotes anyone automatically after that, 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 80ac85585d..e75116b41b 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -556,28 +556,49 @@ Worker runtime settings. Timeout errors include the rollout ID and last status. ## 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 when migration `0243_first_superadmin_election.sql` ran. 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 migration 0243, or someone edited the database by hand. SAM does not demote anyone automatically. Each sign-in on such an instance 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 --env production`, 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. +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 df5da0ae02..de7545fada 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) | From 4366d62f2f0e9d787d96098406baad1a89579470 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 17:25:37 +0000 Subject: [PATCH 4/8] chore(api): keep first-superadmin migration at 0242 and locate it by name Coordinator decision: main ends at 0241 and the builder branch also uses 0242; whichever merges second renumbers, so do not renumber speculatively. Tests now find the migration by its `_first_superadmin_election.sql` suffix, and the code comments and docs name it without a number, so a renumber is a file rename only. Co-Authored-By: Claude Opus 5.5 --- ...n.sql => 0242_first_superadmin_election.sql} | 7 ++++--- apps/api/src/services/first-superadmin.ts | 5 +++-- .../unit/services/first-superadmin.test.ts | 17 +++++++++++++---- .../content/docs/docs/guides/self-hosting.mdx | 4 ++-- 4 files changed, 22 insertions(+), 11 deletions(-) rename apps/api/src/db/migrations/{0243_first_superadmin_election.sql => 0242_first_superadmin_election.sql} (82%) diff --git a/apps/api/src/db/migrations/0243_first_superadmin_election.sql b/apps/api/src/db/migrations/0242_first_superadmin_election.sql similarity index 82% rename from apps/api/src/db/migrations/0243_first_superadmin_election.sql rename to apps/api/src/db/migrations/0242_first_superadmin_election.sql index 2c9a5278d8..c8bce60a3d 100644 --- a/apps/api/src/db/migrations/0243_first_superadmin_election.sql +++ b/apps/api/src/db/migrations/0242_first_superadmin_election.sql @@ -4,9 +4,10 @@ -- 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 pre-0243 concurrent --- first sign-up race, 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 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 diff --git a/apps/api/src/services/first-superadmin.ts b/apps/api/src/services/first-superadmin.ts index 4d94b59905..cfb47d6c07 100644 --- a/apps/api/src/services/first-superadmin.ts +++ b/apps/api/src/services/first-superadmin.ts @@ -7,7 +7,8 @@ const log = createModuleLogger('first-superadmin'); /** * Durable marker: initial administration of an ordinary (no `BOOTSTRAP_OWNER_EMAIL`) install is - * established. Written by migration 0243 for installs that already had a superadmin, and by + * 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. */ @@ -62,7 +63,7 @@ LIMIT 1`; * * 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 pre-0243 sign-up race or a manual + * 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( diff --git a/apps/api/tests/unit/services/first-superadmin.test.ts b/apps/api/tests/unit/services/first-superadmin.test.ts index f5e36e7269..ebe6d6cbe9 100644 --- a/apps/api/tests/unit/services/first-superadmin.test.ts +++ b/apps/api/tests/unit/services/first-superadmin.test.ts @@ -5,6 +5,8 @@ * 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'; @@ -17,10 +19,17 @@ import { } from '../../../src/services/first-superadmin'; import { applySqliteMigration, createSchemaTables, createSqliteD1 } from '../../helpers/sqlite-d1'; -const MIGRATION = new URL( - '../../../src/db/migrations/0243_first_superadmin_election.sql', - import.meta.url +// 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[] = []; @@ -269,7 +278,7 @@ describe('establishFirstSuperadmin — the election', () => { }); }); -describe('migration 0243 — marks installs that already have a superadmin', () => { +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); 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 e75116b41b..c58a9caf6e 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -566,13 +566,13 @@ Without the installer owner binding, the first-superadmin election works like th - **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 when migration `0243_first_superadmin_election.sql` ran. That migration only writes the marker and never changes a user. +- **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 migration 0243, or someone edited the database by hand. SAM does not demote anyone automatically. Each sign-in on such an instance 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: +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. Each sign-in on such an instance 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 From 75e3fa7f6e22f59b68f436b71f29f1cf93a71ab9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 19:35:23 +0000 Subject: [PATCH 5/8] docs: correct first-superadmin recovery details after review - wrangler secret put needs --name (no checked-in env sections) - owner-email recovery does not apply to an installer-bound instance whose owner was already established; use the D1 update there - the duplicate-superadmin warning is logged only without BOOTSTRAP_OWNER_EMAIL - admin-settings and .env.example no longer claim nobody is ever promoted again - rule 40 notes where the promotion lives now Co-Authored-By: Claude Opus 5.5 --- .../rules/40-sentinel-rows-excluded-from-counts.md | 2 ++ apps/api/.env.example | 3 ++- .../www/src/content/docs/docs/guides/admin-settings.md | 10 +++++----- apps/www/src/content/docs/docs/guides/self-hosting.mdx | 4 ++-- 4 files changed, 11 insertions(+), 8 deletions(-) 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/www/src/content/docs/docs/guides/admin-settings.md b/apps/www/src/content/docs/docs/guides/admin-settings.md index cbd19a44b7..70893ab4cf 100644 --- a/apps/www/src/content/docs/docs/guides/admin-settings.md +++ b/apps/www/src/content/docs/docs/guides/admin-settings.md @@ -21,7 +21,7 @@ titled **Runtime settings**. An account must be an approved, active superadmin t can't. On an ordinary self-hosted instance, the first account to sign in while it is the only account -becomes the superadmin, once. SAM never promotes anyone automatically after that, even if that +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). @@ -73,11 +73,11 @@ value and **Source** after the reload, nothing was saved: check the value and tr The **Operations** category includes these chat storage settings: -| Setting | Code default | Effect | -| ------------------------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | -| `chat.messageMergingEnabled` | `false` | Combine new consecutive assistant text chunks under the first chunk's message ID. | +| Setting | Code default | Effect | +| ------------------------------ | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `chat.messageMergingEnabled` | `false` | Combine new consecutive assistant text chunks under the first chunk's message ID. | | `chat.messageMergeMaxRowBytes` | `65536` | Serialized merged-row cap, from 1 KiB to 256 KiB. Also supplies the admission budget for retry state; batches that cannot fit keep individual rows. | -| `chat.messageMergeRecentIds` | `200` | Recent reporter IDs retained across credential rotation, from 50 to 2,000; a complete received batch is always retained. | +| `chat.messageMergeRecentIds` | `200` | Recent reporter IDs retained across credential rotation, from 50 to 2,000; a complete received batch is always retained. | Merging requires an updated reporter that sends its durable outbox incarnation. Older reporters, and requests with a missing or malformed incarnation, keep individual inserts and provide **zero 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 c58a9caf6e..98bb9ed58a 100644 --- a/apps/www/src/content/docs/docs/guides/self-hosting.mdx +++ b/apps/www/src/content/docs/docs/guides/self-hosting.mdx @@ -572,7 +572,7 @@ Without the installer owner binding, the first-superadmin election works like th #### 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. Each sign-in on such an instance 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: +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 @@ -585,7 +585,7 @@ Demote any account you do not recognise with `UPDATE users SET role = 'user' WHE 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: -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 --env production`, 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. +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. 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. From 3cb4570563819ae9bf0eefc6aa3fc1f04cf90c30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Sun, 15 Nov 2026 23:25:16 +0000 Subject: [PATCH 6/8] test: parameterize duplicated first-superadmin attack and self-heal cases Co-Authored-By: Claude Opus 5.5 --- .../unit/services/first-superadmin.test.ts | 40 ++++++++----------- .../workers/superadmin-self-heal.test.ts | 18 +++------ 2 files changed, 23 insertions(+), 35 deletions(-) diff --git a/apps/api/tests/unit/services/first-superadmin.test.ts b/apps/api/tests/unit/services/first-superadmin.test.ts index ebe6d6cbe9..1fb455e4b8 100644 --- a/apps/api/tests/unit/services/first-superadmin.test.ts +++ b/apps/api/tests/unit/services/first-superadmin.test.ts @@ -99,17 +99,23 @@ describe('establishFirstSuperadmin — the election', () => { }); describe('a later sign-up never wins against an existing account', () => { - it('(a) does not promote a new sign-up while the sole existing user is suspended', async () => { - const f = fixture(); - f.user('suspended-owner', 'user', 'suspended', 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.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(); @@ -120,18 +126,6 @@ describe('establishFirstSuperadmin — the election', () => { expect(f.superadmins()).toEqual(['stranger']); }); - it('(b) does not promote a new sign-up while the sole existing user is a non-admin', async () => { - const f = fixture(); - f.user('existing-user', 'user', '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('(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); diff --git a/apps/api/tests/workers/superadmin-self-heal.test.ts b/apps/api/tests/workers/superadmin-self-heal.test.ts index 2aed421d26..1ad0e23ac0 100644 --- a/apps/api/tests/workers/superadmin-self-heal.test.ts +++ b/apps/api/tests/workers/superadmin-self-heal.test.ts @@ -229,22 +229,16 @@ describe('session.create.after — login-time self-heal (real D1)', () => { expect(await getUser('later-user')).toMatchObject({ role: 'user', status: 'pending' }); }); - it('never promotes a suspended user, even as sole operator', async () => { - await insertUser('real-1', { role: 'user', status: 'suspended' }); - const hook = await getSessionAfterHook(); - - await hook({ userId: 'real-1' }); - - expect(await getUser('real-1')).toMatchObject({ role: 'user', status: 'suspended' }); - }); - - 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 () => { From 3ab759c854d15479a03f9555ed1896c8bacaafd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 00:05:04 +0000 Subject: [PATCH 7/8] chore(api): number the first-superadmin migration 0243 0242 is taken by the Cloudflare build executor migration (PR #2721), which is already applied on staging. Migration-ordering CI rejects duplicate prefixes; the migration is replay-safe and tests locate it by name. Co-Authored-By: Claude Opus 5.5 --- ...superadmin_election.sql => 0243_first_superadmin_election.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename apps/api/src/db/migrations/{0242_first_superadmin_election.sql => 0243_first_superadmin_election.sql} (100%) diff --git a/apps/api/src/db/migrations/0242_first_superadmin_election.sql b/apps/api/src/db/migrations/0243_first_superadmin_election.sql similarity index 100% rename from apps/api/src/db/migrations/0242_first_superadmin_election.sql rename to apps/api/src/db/migrations/0243_first_superadmin_election.sql From 0cdc603793ee962358af48624ff8383ce92e0924 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 05:46:43 +0000 Subject: [PATCH 8/8] chore(api): renumber the first-superadmin migration to 0246 after main's 0245 Co-Authored-By: Claude Opus 5.5 --- ...superadmin_election.sql => 0246_first_superadmin_election.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename apps/api/src/db/migrations/{0243_first_superadmin_election.sql => 0246_first_superadmin_election.sql} (100%) diff --git a/apps/api/src/db/migrations/0243_first_superadmin_election.sql b/apps/api/src/db/migrations/0246_first_superadmin_election.sql similarity index 100% rename from apps/api/src/db/migrations/0243_first_superadmin_election.sql rename to apps/api/src/db/migrations/0246_first_superadmin_election.sql