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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion apps/api/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
50 changes: 28 additions & 22 deletions apps/api/src/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -18,6 +17,7 @@ import {
bootstrapUserDecision,
} from './services/bootstrap-owner';
import { emailSignInPlugins } from './services/email-sign-in';
import { establishFirstSuperadmin, FIRST_SUPERADMIN_SETTING } from './services/first-superadmin';
import { refreshGitHubAccessToken } from './services/github-oauth-refresh';
import { untrustedGitLabUserInfo } from './services/gitlab-sign-in-identity';
import {
Expand All @@ -42,10 +42,12 @@ const log = createModuleLogger('auth');
* a single atomic UPDATE with no read-modify-write race; concurrent logins of the
* same user are idempotent (the second is a no-op).
*
* Numbered params: ?1 = current user id (referenced twice), ?2 = sentinel id.
* Numbered params: ?1 = current user id (referenced twice), ?2 = sentinel id,
* ?3 = the durable ordinary-install election marker.
* Guards: (a) skip already-superadmin rows; (d) never auto-elevate a suspended
* account; status!='system' never mutates the sentinel; (b) the current user is the
* only non-internal user; (c) no non-system superadmin exists anywhere.
* only non-internal user; (c) no non-system superadmin exists anywhere; (e) the
* ordinary one-time election has not already completed.
*
* Drizzle cannot express the correlated-subquery WHERE, so this is issued via the
* raw D1 binding (prepare/bind/run) — the same mechanism used by
Expand All @@ -69,6 +71,10 @@ WHERE id = ?1
WHERE u3.role = 'superadmin'
AND u3.status != 'system'
) = 0
AND NOT EXISTS (
SELECT 1 FROM platform_settings election
WHERE election.key = ?3
)
`;

interface GitHubEmailResponse {
Expand Down Expand Up @@ -391,22 +397,9 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) {
return { data: user };
}

// Check if this is the first user (auto-superadmin)
const hookDb = drizzle(env.DATABASE, { schema });
const existing = await hookDb
.select({ id: schema.users.id })
.from(schema.users)
.where(ne(schema.users.id, sentinelId))
.limit(1)
.all();

if (existing.length === 0 && bootstrapOwnerEmail(env) === undefined) {
return {
data: { ...user, role: 'superadmin', status: 'active' },
};
}

// Subsequent users need approval
// Approval-gated users start unprivileged. The first ordinary user is elected only
// after their row exists, in the atomic session hook below; assigning superadmin here
// would race BetterAuth's later INSERT under concurrent registrations.
return {
data: { ...user, role: 'user', status: 'pending' },
};
Expand All @@ -417,6 +410,19 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) {
create: {
before: async (session) => {
if (!(await bootstrapSessionAllowed(env, session.userId))) return false;
if (bootstrapOwnerEmail(env) === undefined) {
// Fail closed for privilege, never for login: a D1 error leaves the user
// unpromoted (the batch is atomic) and the next sign-in retries the election.
try {
await establishFirstSuperadmin(env, session.userId);
} catch (err) {
log.error('first_superadmin_election.failed', {
userId: session.userId,
error: err instanceof Error ? err.message : String(err),
action: 'continued_without_promotion',
});
}
}
return { data: session };
},
// Login-time superadmin self-heal. Fires on EVERY session creation —
Expand All @@ -441,12 +447,12 @@ export async function createAuth(env: Env, options: CreateAuthOptions = {}) {
const sql =
expectedOwner === undefined
? LOGIN_SELF_HEAL_SQL
: LOGIN_SELF_HEAL_SQL + ' AND lower(trim(email)) = ?3 AND email_verified = 1';
: LOGIN_SELF_HEAL_SQL + ' AND lower(trim(email)) = ?4 AND email_verified = 1';
const statement = env.DATABASE.prepare(sql);
const result = await (
expectedOwner === undefined
? statement.bind(userId, sentinelId)
: statement.bind(userId, sentinelId, expectedOwner)
? statement.bind(userId, sentinelId, FIRST_SUPERADMIN_SETTING)
: statement.bind(userId, sentinelId, FIRST_SUPERADMIN_SETTING, expectedOwner)
).run();
if (result.meta.changes > 0) {
log.info('login_self_heal.promoted', { userId });
Expand Down
26 changes: 26 additions & 0 deletions apps/api/src/db/migrations/0246_first_superadmin_election.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
-- Close the ordinary first-superadmin election on installations that already have an
-- administrator. The marker names the oldest real (status != 'system') superadmin, matching
-- RECORD_SQL in apps/api/src/services/first-superadmin.ts (establishFirstSuperadmin). While it
-- exists, no sign-in is promoted, even if that administrator is later deleted.
--
-- This migration only inserts the marker. It never updates or deletes user rows:
-- * An installation with more than one superadmin (possible only from the concurrent first
-- sign-up race that predates this election, or a manual database edit) keeps every one of
-- them. establishFirstSuperadmin logs first-superadmin.multiple_superadmins on each sign-in
-- until an operator resolves it.
-- * An installation with no superadmin gets no marker. A fresh installation has only the system
-- user here, so its first real user still wins the election at sign-in. An existing sole
-- non-suspended user stays electable, as the login-time self-heal already allowed. An
-- installation with several real users and no superadmin promotes nobody, because the election
-- requires the signing-in user to be the only real user.
INSERT OR IGNORE INTO platform_settings (key, value, updated_at, updated_by)
SELECT
'setup.firstSuperadminEstablished',
json_object('version', 1, 'ownerId', id),
CURRENT_TIMESTAMP,
id
FROM users
WHERE role = 'superadmin'
AND status != 'system'
ORDER BY created_at, id
LIMIT 1;
5 changes: 3 additions & 2 deletions apps/api/src/routes/agent-sign-in.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,9 @@ async function findTargetUser(env: Env, target: string): Promise<TargetUserRow |

/**
* BetterAuth's session hooks promote a user to superadmin only while no superadmin exists
* (`LOGIN_SELF_HEAL_SQL` and `bootstrapSessionAllowed` in auth.ts / bootstrap-owner.ts). Requiring
* one keeps both inert, so an agent sign-in can never change a role.
* (`LOGIN_SELF_HEAL_SQL`, `establishFirstSuperadmin`, and `bootstrapSessionAllowed` in auth.ts and
* its bootstrap services). Requiring one keeps every promotion path inert, so an agent sign-in
* can never change a role.
*/
async function hasEstablishedAdministrator(env: Env): Promise<boolean> {
const row = await env.DATABASE.prepare(
Expand Down
94 changes: 94 additions & 0 deletions apps/api/src/services/first-superadmin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import type { Env } from '../env';
import { createModuleLogger } from '../lib/logger';

type FirstSuperadminEnv = Pick<Env, 'DATABASE'>;

const log = createModuleLogger('first-superadmin');

/**
* Durable marker: initial administration of an ordinary (no `BOOTSTRAP_OWNER_EMAIL`) install is
* established. Written by the `*_first_superadmin_election.sql` migration for installs that already
* had a superadmin, and by
* {@link establishFirstSuperadmin} when it elects one. While it exists nobody is auto-promoted,
* even if every superadmin is later deleted.
*/
export const FIRST_SUPERADMIN_SETTING = 'setup.firstSuperadminEstablished';

/**
* Promote the bound user only when every guard holds inside this one statement: the user is a real
* (`status != 'system'`), non-suspended, non-superadmin account; it is the ONLY real user; and the
* election has not completed. D1 runs the statement atomically, so the guards are race-safe.
*
* The only-real-user guard does three jobs. A later sign-up never wins against an existing
* account, whatever that account's role or status. No other superadmin can exist (one would be
* another real user). And two racing sign-ups whose rows both exist both lose: the install fails
* closed with no administrator rather than electing by timing. A winner chosen by `created_at`
* would also promote the oldest account on an upgraded install with several users and no
* superadmin, which this election must never do.
*/
const ELECT_SQL = `
UPDATE users
SET role = 'superadmin', status = 'active', updated_at = cast(unixepoch() * 1000 as integer)
WHERE id = ?
AND role != 'superadmin'
AND status != 'system'
AND status != 'suspended'
AND NOT EXISTS (
SELECT 1 FROM users other
WHERE other.id != ?
AND other.status != 'system'
)
AND NOT EXISTS (
SELECT 1 FROM platform_settings election
WHERE election.key = ?
)`;

/**
* Record the marker for the oldest real superadmin, if one exists. Runs after `ELECT_SQL` in the
* same batch, so it names the user just elected; it also backfills an install that has a
* superadmin but no marker. It writes nothing while no superadmin exists, so a refused election
* leaves the install open for its sole real user.
*/
const RECORD_SQL = `
INSERT OR IGNORE INTO platform_settings (key, value, updated_at, updated_by)
SELECT ?, json_object('version', 1, 'ownerId', administrator.id), CURRENT_TIMESTAMP, administrator.id
FROM users administrator
WHERE administrator.role = 'superadmin'
AND administrator.status != 'system'
ORDER BY administrator.created_at, administrator.id
LIMIT 1`;

/**
* Elect the first administrator of an ordinary install after BetterAuth has inserted the user.
*
* The initial read keeps later sign-ins to one query. It also reports an install with more than
* one real superadmin (`first-superadmin.multiple_superadmins`): superadmin is never granted
* through the admin API, so a second one can only come from the sign-up race that predates this election or a manual
* database edit, and an operator must decide which accounts to keep. Nothing is changed for them.
*/
export async function establishFirstSuperadmin(
env: FirstSuperadminEnv,
userId: string
): Promise<void> {
const state = await env.DATABASE.prepare(
`SELECT
EXISTS (SELECT 1 FROM platform_settings WHERE key = ?) AS established,
(SELECT COUNT(*) FROM users WHERE role = 'superadmin' AND status != 'system') AS superadmins`
)
.bind(FIRST_SUPERADMIN_SETTING)
.first<{ established: number; superadmins: number }>();
if (state && state.superadmins > 1) {
log.warn('multiple_superadmins', {
superadminCount: state.superadmins,
signingInUserId: userId,
action: 'reported_for_operator_review',
});
}
if (state?.established) return;

const [elected] = await env.DATABASE.batch([
env.DATABASE.prepare(ELECT_SQL).bind(userId, userId, FIRST_SUPERADMIN_SETTING),
env.DATABASE.prepare(RECORD_SQL).bind(FIRST_SUPERADMIN_SETTING),
]);
if ((elected?.meta.changes ?? 0) > 0) log.info('elected', { userId });
}
Loading
Loading