Repository navigation
fix(api): atomic first-superadmin election without demotion (replaces #2753) - #2772
Conversation
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 <noreply@anthropic.com>
…very 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 <noreply@anthropic.com>
…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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 19 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
…ases Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
|
Migration numbering note from the coordinator: PR #2721 has |
…n's 0245 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
|
@coderabbitai review |
Action not completed
|
* feat(overview): aggregated project overview read (operation + REST route)
projectOverviewGet returns running chats and recent ideas/merged PRs for
the Inbox F1 Project Overview page; GET /api/projects/:projectId/overview.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor(chat): share the new-chat composer and start path
Move composer state and the Instant/task start out of useProjectChatState
into useNewChatComposer, which returns what it started and never
navigates. The chat page keeps opening the new chat; the Project Overview
task box will reuse the same start without leaving the page.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat(web): Project Overview page with Running now, Budgets, Automations, Recently and a task box
New lazy-loaded page at /projects/:id/overview, first in the project nav
on desktop and phone. Running now and Recently come from the aggregated
overview read (refreshed by project socket events); Budgets reuses the
composer's usage model; Automations reuses the Automation page's model and
fix button through a new one-line AttentionLine. The task box is the real
new-chat composer and start path; sending stays on the page with a receipt
and an optimistic Running now row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(overview): task box start without navigation, budgets wording, composer collapse
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style: sort test imports
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test(overview): Playwright visual audit; keep the idle phone task box to one row
The composer measured its height only when its text changed, so a box
first measured while its row was narrower kept a wrapped placeholder's
height. It now re-measures on width changes. While folded, attach waits
in the To row.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* docs: Project Overview guide and overview API reference
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style: sort operations exports
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(overview): review findings — waiting-on-you ranked first, phone box refolds, accessible budgets
- Running now ranks chats waiting on the viewer first and reports
waitingOnViewerTotal, so the cap never hides the page's one exception
('7 more running · 2 waiting on you').
- Composer folds on an outside tap or a completed send instead of on blur
(iOS does not focus tapped buttons); the success receipt is transient;
receipt live regions are persistent; the text box has a name.
- Budgets tiles speak the usage left; failing automations count in red with
a secondary Resume; compact idea rows in Recently.
- Merged PR links must be https; global profile names only for the task
creator's own profiles.
- Performance: index for newest merged PRs (migration 0246), a lighter
recent-ideas read (11 measured round trips), no socket refetch on a
hidden tab, ResizeObserver work deferred to the next frame.
- Tests: nav order on desktop and phone, round-trip budget, query plan,
automation fix, Recently links, hidden-tab, fold-after-send.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* style: sort operations imports
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* task: archive inbox F1 project overview task
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test: sidebar scroll audit counts the Overview nav item
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* task: record F1 checklist and review outcomes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* chore: renumber overview index migration to 0249
0246 is taken by #2772 (already applied on staging2), 0247 by #2780 and 0248 by #2781.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: give the GitHub sign-in prompt a painted background
The app-wide prompt in AuthProvider used bg-surface-elevated, a class no theme defines, so it
rendered transparent over whatever sat at the bottom of the page. Staging2 showed it over the
Overview task box. Use the Toast's glass-surface and shadow-dropdown. The Overview audit gains a
GitHub-reauth failed-start scene that asserts the prompt paints a background (red against the
old class).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Raphaël Titsworth-Morin <raphael@raphaeltm.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>



Summary
This replaces Codex Security draft PR #2753. The finding was confirmed real (low to medium) on 2026-11-15, but the patch had defects.
Vulnerability (confirmed): in
apps/api/src/auth.ts, theuser.create.beforehook read "no real users" and returnedrole: 'superadmin'. The insert happens after the hook, so two first sign-ups racing on a fresh install both won. This applies only to installs withoutBOOTSTRAP_OWNER_EMAIL.Kept from the scanner patch: the atomic election, which runs a guarded UPDATE plus a
platform_settingsmarker insert in one D1 batch (apps/api/src/services/first-superadmin.ts). It runs insession.create.before.Defects fixed:
Two failing tests.
first-superadmin.test.tsbuilds its tables from the drizzle schema, so they includeupdated_at.auth.test.tsnow usesinstallSignupApprovalQuery()instead of the removed mock.The migration no longer demotes anyone. It only inserts the marker, and only when a non-system superadmin exists. It never touches user rows.
first-superadmin.multiple_superadminswarning on each sign-in. The count comes from the existing first read, so it adds no query."Only real user" guard. The guarded UPDATE requires all of the following:
Real-SQL tests cover (a) a sole suspended user plus a new sign-up and (b) a sole non-admin user plus a new sign-up. Each is paired with an owner-path control. A stale-read test covers the guard inside the UPDATE.
A D1 failure no longer blocks sign-in. On error,
session.create.beforelogsauth.first_superadmin_election.failedand returns the session without promoting anyone. A workers test drives BetterAuth's realcreateSessionagainst a failing D1, then shows the user is elected on the next sign-in once D1 recovers.Recovery documented in
self-hosting.mdx("Recovering when no account can administer the instance"),admin-settings.md,security.mdandconfiguration.md. There are two paths:BOOTSTRAP_OWNER_EMAILWorker secret (not available on installer-bound instances whose owner is already established);Design decision (fail closed): if two sign-ups both create their account rows before either election runs, both lose. The install then has no superadmin until the documented recovery is used. Electing the oldest account instead would also promote someone on upgraded installs that have several users and no superadmin, so that option was rejected. This matches the project's "fail closed instead of insecure fallback" policy.
Migration number:
0246_first_superadmin_election.sql. It was renumbered from 0243 in 0cdc603 because main now has0245_asks.sqland #2691 also uses 0243. The migration-ordering check only rejects duplicate prefixes. Tests locate the file by its name suffix.Validation
pnpm quality:migration-safety0 violations;format:checkratchet passesfirst-superadmin.test.ts+auth.test.ts45/45;superadmin-self-heal.test.ts(workers, real D1) 21/21capacity-pool-edit-query-plan.test.ts, 5s timeout on a shared machine). It passes alone, and this branch doesn't touch that file.Discrimination checks (each guard deleted once):
auth.tsPer-sign-in cost: once established, +1 D1 round trip per session creation (the marker and duplicate count in one SELECT). Before establishment: +2.
Staging Verification (REQUIRED for all code changes — merge-blocking)
Verified on
staging2(sammy2.party). The primary staging worker is blocked by the #2721 DO migration tag. Deploy run 43812594179 of head 0cdc603 passed: lease, validate, deploy (D1 migrations applied) and smoke tests.0246_first_superadmin_election.sqlis recorded ind1_migrations/dashboard,/projectsand/settings(all 200, no error text)Staging Verification Evidence
users WHERE role='superadmin'staging2-agent-admin(active)staging2-agent-admin(active), unchangedstaging2-agent-user: roleuseruser(not promoted)system_anonymous_trials: roleuser, statussystemsetup.firstSuperadminEstablished{"version":1,"ownerId":"staging2-agent-admin"}, written 05:56:30Z by the migration0245_asks.sql0246_first_superadmin_election.sqlSign-ins after the deploy:
sessionsrow was created and their role stayeduser.GET /api/auth/mereturnedrole: superadmin, andGET /api/admin/userslisted exactly one superadmin.Both logins completed, so the election hook ran without blocking sign-in. The only console errors were 404s for a placeholder
/projects/noneURL used by the check script.UI Compliance Checklist (Required for UI changes)
N/A: no UI changes.
End-to-End Verification (Required for multi-component changes)
bootstrapSessionAllowedindependent of the marker, admin API cannot grant superadminData Flow Trace
user.create.before(auth.ts) no longer promotes anyone; the account is created as an ordinary user.session.create.beforecallsestablishFirstSuperadmin(env.DATABASE, userId)whenbootstrapOwnerEmail(env)is unset. That runs one SELECT (marker exists? superadmin count) and then, if the install is not yet established, a D1 batch:ELECT_SQL(the guarded UPDATE), thenRECORD_SQL(insert the marker naming the oldest real superadmin).session.create.afterself-heal (LOGIN_SELF_HEAL_SQL) applies the same sole-user conditions plusNOT EXISTS marker. It is a retry only when the election failed.0246_first_superadmin_election.sqlbackfills the marker on installs that already have a superadmin.bootstrapSessionAllowed(services/bootstrap-owner.ts) promotes a verifiedBOOTSTRAP_OWNER_EMAILwhile no superadmin exists and the owner is not yet established.Untested Gaps
The concurrency test uses better-sqlite3, so it proves the guard predicates rather than true cross-isolate interleaving. Atomicity rests on D1's batch transaction and single-statement UPDATE semantics.
Post-Mortem (Required for bug fix PRs)
What broke
Two concurrent first sign-ups on a fresh install could both become superadmin.
Root cause
A "no other users" read in
user.create.beforedecided the role before the insert, which is a check-then-act gap.Class of bug
A privilege decided by a non-atomic count instead of in the final atomic write (rule 69: enforce at the final reservation).
Why it wasn't caught
The existing tests ran sign-ups sequentially.
Process fix included in this PR
The election is a single guarded write. Real-SQL attack and control tests cover it, plus BetterAuth-driven workers tests.
Post-mortem file
The task file
tasks/active/2026-11-15-ship-codex-security-fixes-2753-2754-2755.mdlives on the #2759 branch.Specialist Review Evidence (Required for agent-authored PRs)
needs-human-reviewlabel added and merge deferred to human: N/Awrangler secret putnow uses--name; the owner-email recovery is scoped; the warning-condition wording is fixed;admin-settings.mdand.env.examplewere stale. All fixed in 75e3fa7.CodeRabbit Review Evidence (Required for agent-authored PRs)
CodeRabbit Notes
coderabbit-reviewlabel applied after CI run 43815768248 passed and staging2 verification completed. The bridge workflow run 43819045056 succeeded.Exceptions (If any)
Agent Preflight (Required)
Classification
External References
N/A: no external API changes. BetterAuth database-hook behaviour was verified through the existing workers harness, which drives the real
internalAdapter.createSession.Codebase Impact Analysis
apps/api/src/auth.ts:user.create.beforeno longer promotes anyone;session.create.beforeruns the election inside a try/catch; the self-heal gains a marker guardapps/api/src/services/first-superadmin.ts(new)apps/api/src/db/migrations/0246_first_superadmin_election.sql(new; inserts the marker only)apps/api/src/routes/agent-sign-in.ts: comment onlytests/unit/services/first-superadmin.test.ts,tests/unit/auth.test.ts,tests/workers/superadmin-self-heal.test.tsDocumentation & Specs
apps/www/src/content/docs/docs/guides/self-hosting.mdxapps/www/src/content/docs/docs/guides/admin-settings.mdapps/www/src/content/docs/docs/architecture/security.mdapps/www/src/content/docs/docs/reference/configuration.mdapps/api/.env.exampleapps/api/.claude/rules/40-sentinel-rows-excluded-from-counts.md(a note on where the promotion lives)Constitution & Risk Check
🤖 Generated with Claude Code