Skip to content

admin: real role permissions, deputy owner, and owner-approved agent roster changes - #23279

Merged
Git-on-my-level merged 9 commits into
mainfrom
lane/admin-roles
Oct 22, 2026
Merged

Git-on-my-level merged 9 commits into
mainfrom
lane/admin-roles

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Admin roles at admin.omi.me now actually restrict access, and agents can drive roster and role changes, but only with a human approving each one.

Today any adminData/{uid} doc means full admin, and role ("superadmin"/"Admin") is only a label. After this PR:

  • Scopes per dashboard area, enforced server-side. The one guard is requireScope(request, scope) in lib/auth.ts, and it replaces verifyAdmin in every one of the 101 scoped handlers. It denies by default: a role this code doesn't know grants nothing, and a handler not listed in lib/route-scopes.ts fails a test.
  • Roles are stored as adminData/{uid}.accessRole, with optional per-member scopeOverrides (grant/deny). Overrides can never grant team:manage.
  • Deputy owner (accessRole: "deputy") holds team:manage, so roster changes no longer depend on one account. Only the owner appoints, changes or removes deputies.
  • Team page (owner/deputies): change roles with a scope-diff confirmation. It also shows uid prefix, created, last sign-in (from Firebase Auth), a duplicate-email badge, pending agent proposals with one-click Approve/Reject, and the audit log.
  • Agent API (/api/agent/team*) takes a Google service-account ID token on an allowlist. Agents can read the roster and audit log and file add/remove/role proposals. A proposal applies only when the owner or a deputy approves it in the UI. Proposals expire after 72h. Agents cannot approve, cannot target themselves or any machine identity, and get no admin scope or user-data access.
  • Audit log (adminAuditLog): every add, removal, role change and proposal event (created, approved, rejected, expired) records who, when, what, and access before/after. Each entry is written in the same Firestore transaction as the change.
  • Sidebar and page-level gating hide what a role lacks (GET /api/omi/access). The server check is the authority.

Docs: web/admin/docs/team-access.md (model, rules, agent API with example request). web/admin/AGENTS.md gets two rules. It has a 1,500-byte budget, so the full agent API example lives in the linked doc.

Roles → scopes

Role (accessRole) Scopes
Owner (owner: true, Firestore-only) all
deputy Deputy owner all, incl. team:manage
admin Admin all except team:manage
finance Finance analytics:read, finance:read, finance:write, partners:read
support Support analytics:read, users:read, users:write, apps:read, content:read
viewer Viewer (read-only) analytics:read, apps:read, content:read
legacy (no accessRole) all except team:manage (exactly what every admin could do before)
stats reader (machine, unchanged) analytics:read, finance:read, still GET /api/omi/stats/* only

Team rules (one code path for direct edits and approvals): team:invite grants a role no broader than the inviter's own. New people default to viewer when no role is sent. team:manage changes roles and removes people. Nobody changes or removes themselves or the owner.

Route inventory (lib/route-scopes.ts)

Policy Handlers
member GET /api/omi/access
analytics:read GET /api/omi/stats/activation, GET /api/omi/stats/conversation-count, GET /api/omi/stats/crash-rate, GET /api/omi/stats/daily-new-users, GET /api/omi/stats/dau-trends, GET /api/omi/stats/desktop-ratings, GET /api/omi/stats/device-health, GET /api/omi/stats/floating-bar-usage, GET /api/omi/stats/k-factor/posthog, GET /api/omi/stats/macos-versions, GET /api/omi/stats/message-ratings, GET /api/omi/stats/notifications, GET /api/omi/stats/onboarding/mobile, GET /api/omi/stats/onboarding/mobile/attach, GET /api/omi/stats/onboarding/mobile/tutorial, GET /api/omi/stats/onboarding/posthog, GET /api/omi/stats/releases, GET /api/omi/stats/response-reliability, GET /api/omi/stats/retention/posthog, GET /api/omi/stats/viral-metrics, GET /api/omi/csat/stats
analytics:share GET /api/omi/tv-links, POST /api/omi/tv-links, DELETE /api/omi/tv-links/[id]
finance:read GET /api/grafana/embed, GET /api/omi/stats/app-subscriptions, GET /api/omi/stats/infra-costs, GET /api/omi/stats/mrr-trends, GET /api/omi/stats/plan-economics, GET /api/omi/stats/profitability, GET /api/omi/stats/revenue, GET /api/omi/stats/subscription-trends, GET /api/omi/stats/subscriptions, GET /api/omi/stats/wall, GET /api/omi/stats/wall/series/[name], GET /api/omi/subscriptions, GET /api/omi/payouts, GET /api/omi/all-payouts, GET /api/omi/users-with-stripe, GET /api/omi/affiliates, GET /api/omi/affiliate-payouts
finance:write POST /api/omi/affiliate-payouts
users:read GET /api/omi/fair-use/flagged, GET /api/omi/fair-use/case/[caseRef], GET /api/omi/fair-use/user/[uid], GET /api/omi/feedback/reports, GET /api/omi/feedback/reports/[reportDate], GET /api/omi/feedback/events/[eventId]/context, GET /api/omi/notifications/user-notifications, POST /api/omi/notifications/regenerate
users:write POST /api/omi/fair-use/user/[uid]/reset, POST /api/omi/fair-use/user/[uid]/set-stage, POST /api/omi/fair-use/user/[uid]/resolve-event/[eventId], POST /api/omi/feedback/reports/[reportDate]
apps:read GET /api/omi/apps, GET /api/omi/apps/stats, GET /api/omi/apps/unapproved, GET /api/omi/apps/[app_id]/details, GET /api/omi/private-apps, GET /api/omi/summary-apps
open: CORS preflight; returns no data OPTIONS /api/omi/apps/stats
apps:write POST /api/omi/apps/[app_id]/review, POST /api/omi/apps/[app_id]/update, PATCH /api/omi/apps/[app_id]/popular, POST /api/omi/summary-apps, PATCH /api/omi/summary-apps, DELETE /api/omi/summary-apps
content:read GET /api/omi/announcements, GET /api/omi/announcements/[id], GET /api/omi/desktop-prompts, GET /api/omi/desktop-prompts/results, GET /api/omi/csat, GET /api/omi/releases, GET /api/omi/chat-lab/prompts, GET /api/omi/chat-lab/questions, GET /api/omi/chat-lab/ratings
content:write POST /api/omi/announcements, PUT /api/omi/announcements/[id], DELETE /api/omi/announcements/[id], POST /api/omi/desktop-prompts, PATCH /api/omi/desktop-prompts/[id], DELETE /api/omi/desktop-prompts/[id], PUT /api/omi/csat, POST /api/omi/chat-lab/prompts, POST /api/omi/chat-lab/questions, POST /api/omi/chat-lab/generate, POST /api/omi/chat-lab/evaluate
partners:read GET /api/distributors, GET /api/distributors/locations, GET /api/organizations
partners:write POST /api/distributors, PUT /api/distributors, POST /api/organizations, PATCH /api/organizations/[id]
dev:agent POST /api/omi/agent/customize
team:read GET /api/omi/team-members, GET /api/omi/team-members/audit, GET /api/omi/team-members/proposals
team:invite POST /api/omi/team-members
team:manage PATCH /api/omi/team-members, DELETE /api/omi/team-members, POST /api/omi/team-members/proposals/[id]
team-agent GET /api/agent/team, GET /api/agent/team/audit, GET /api/agent/team/proposals, POST /api/agent/team/proposals
open: public signing keys for Grafana GET /api/grafana/jwks
open: TV share-link capability token POST /api/grafana/tv-embed
open: x-cron-secret scheduler header POST /api/internal/precompute
open: public aggregate counts only GET /api/public/user-growth

The dead Pages Router duplicate pages/api/stats/conversation-count.ts is removed (no caller; the App Router route serves the dashboard), so the inventory test can see every handler.

Migration and ramp (no flag)

  • No lockout: docs without accessRole (all 11 today) keep exactly their current access until the owner or a deputy assigns a role. The Team page shows a banner counting them. Existing owner-only removal still works: the owner holds team:manage, legacy admins don't.
  • This ships on by default. Nothing changes for anyone until a role is assigned, so there is no default-off gate and no ramp plan. Suggested rollout: the owner appoints one deputy, then assigns roles person by person.
  • Behaviour changes: (1) deputies can remove non-deputy members, a new capability by design. (2) A POST to add a member without a role creates a viewer, where it used to create a full admin. The dialog now has a role picker.
  • Agent API is off until configured: with ADMIN_TEAM_AGENT_AUDIENCE/ADMIN_TEAM_AGENT_SAS unset, every /api/agent/team* call returns 401. This is fail-closed credential config, not a feature flag. Wiring them into the deploy workflow needs a .github/ change, which is out of scope here (see open questions).
  • New Firestore collections adminAuditLog and adminProposals are written only by the server's Admin SDK and added to the read-counter allowlist. Queries are single-field, so no composite index is needed (the query-contract test passes).

Test evidence

  • npm run lint passes with 0 errors; the 20 warnings are all pre-existing, in files this PR doesn't change.
  • npm run typecheck is clean.
  • npx vitest run (web/admin): 79 files passed, 6 skipped; 1006 tests passed, 13 skipped (updated after the financial-wall commit).
    • lib/__tests__/route-scopes.test.ts (314 tests) finds every exported handler under app/api. It fails if a handler is missing from the inventory or an inventory entry has no handler. Each scoped handler is called by a member holding every scope except the declared one and must return 403 naming that scope; it must also return 401 without a token and 403 for a non-admin. Agent routes must refuse human tokens. Every stats GET must stay within the stats reader's scopes. I mutation-checked it by changing one route's scope, bypassing another's guard and adding an undeclared route; all three made it fail.
    • app/api/omi/team-members/__tests__/route.test.ts (27 tests) runs the real guard against an in-memory Firestore/Auth fake. It covers the existing add/provision/invite and owner-only removal cases, deputy rules, no-broader-than-yourself, overrides, legacy access, roster fields and audit entries.
    • app/api/agent/team/__tests__/agent-team.test.ts (27 tests) uses real RS256-signed Google ID tokens. It checks audience, allowlist and expiry, rejects human and stats-reader tokens, and confirms an agent token gets 401 on human, user-data and approval routes. It also covers proposal validation (self, machine identities, owner, duplicates), approval by deputy or owner, owner-only deputy appointments, applying only once, rejection, expiry, and the audit trail.
    • lib/__tests__/admin-access.test.ts and the Team page component tests.
  • Local end-to-end run against the Firebase emulators (demo project demo-omi-admin with a fictional roster; no production data, no api.omi.me). next dev ran with the dev bypass as owner. Approving a seeded agent proposal from the UI changed the member's role in the emulator and wrote proposal.approved and member.role_changed audit entries. A human token on /api/agent/team got 401.
  • make preflight passes. One known limit: the Firestore query-contract test pins a whole-file fingerprint of fair-use/flagged/route.ts. I repinned it after reviewing that only quotes and the guard line changed (pre-commit Prettier). Most per-route diffs are that formatting; the real change is the one requireScope line, so git diff -w or lib/route-scopes.ts is the fastest way to review.

Review follow-up (Codex findings, commit after the screenshots)

  • Proposal limits are atomic. Filing reads and writes a per-agent and a per-target lock doc (adminProposalLocks) in the same transaction, so overlapping requests conflict and retry. The in-memory fake now retries on read-doc conflicts the way Firestore does. The burst tests (two at once for the same target; cap+3 at once) fail when the locks are removed.
  • Pending proposals are always listed. They are queried separately from the 100-item history.
  • Expiry is audited as a system actor (proposal-expiry), with the proposer kept in proposedBy.
  • The Team page shows proposal and audit-log fetch failures instead of empty states.
  • Access refreshes every minute and on focus. A readable page whose edit scope is missing shows a read-only notice. The coding-agent widget requires dev:agent. Hiding individual edit buttons on each page is a follow-up; the server refuses those actions with 403 today.

Follow-ups from review

Commit 866095ae401 (2026-10-22, decisions from David):

  • POST /api/omi/notifications/regenerate moved to users:write in the route policy and handler (resolves open question 2). SCOPE_LABELS now read "notification history" (read) / "regenerate notifications" (write), and the notifications page declares users:write as its edit scope for the read-only notice.
  • Bad Firebase tokens get 401, not 500. verifyFirebaseToken no longer swallows SDK errors; authenticate() maps token faults (malformed, bad signature, expired, revoked) to 401 via isFirebaseTokenError, and genuine server faults (Firestore down, SDK internal errors) stay 500. Both classes tested in lib/__tests__/auth.test.ts.
  • Agent routes reject a request with no Authorization header with 401 — now tested for all four agent routes.
  • Deputies may remove admins (never owners, never other deputies unless the actor is an owner) — confirmed already enforced by assertCanChange and covered by the existing deputy-removal test (resolves open question 3).
  • Several owners are supported (owner: true is per doc; prod carries two). No owner can be changed or removed through the UI or API by anyone, including another owner; a new two-owner test proves both owners have full access and cannot touch each other. Single-owner wording ("the workspace owner") became "an owner" across code, UI and docs.
  • The agent API ships disabled: no deploy sets ADMIN_TEAM_AGENT_* yet, so every agent call returns 401. Enabling is a separate, David-approved deploy-config change listing the allowlisted service accounts; documented in web/admin/AGENTS.md (open question 1 stays open).

Commit d40f20457db (2026-10-22, second Codex review — FIX-first findings; every fix landed with a test that fails without it):

  • P1 — TV share links can no longer bypass the financial wall. The only shareable board is the financial omi-tv-v2 Business one, so minting a link now requires finance:read besides analytics:share (no non-financial board exists to offer instead; refused with a clear error), the link list and revoke responses redact the share tokens without finance:read — the token is the capability — and resolveActiveTvToken re-checks on every kiosk view that the issuer still exists and still holds finance:read: a demoted, denied or removed issuer's links stop working at /tv/view/<token> and POST /api/grafana/tv-embed, before lastUsedAt refreshes. Tests: lib/__tests__/route-scopes.test.ts (mint refusal, list redaction, kiosk-embed issuer cases) and lib/__tests__/tv-links-issuer.test.ts.
  • P2 — organization billing is redacted and finance-gated. The subscription block (Stripe payment/customer ids, plan, status, period) is nulled in every organizations response for callers without finance:read, and attaching or clearing a Stripe payment requires finance:write before any Stripe or Firestore work; partner-metadata edits under partners:write are unchanged. Shared helper lib/organizations.ts.
  • P2 — team mutations re-authorize inside their transaction. Every add, removal, role change, deputy appointment and proposal approval/rejection re-reads the actor's adminData doc with tx.get and re-runs the authority checks from it (currentActor in lib/team/roster.ts), so a demotion or removal that lands mid-flight aborts the in-flight change. The tests demote the actor between the transaction's read and its commit using the fake Firestore's conflict retry (route.test.ts, agent-team.test.ts — 7 cases).
  • P3 — GET proposals is pure. listProposals derives expired from expiresAt per response and writes nothing; the persisted transition and its proposal.expired audit entry land on the next write. Deciding an expired proposal still refuses with 410 and records the expiry.
  • Financial-route audit. lib/route-scopes.ts exports FINANCIAL_ROUTES: one audited list of every route that can surface financial data — 18 pinned to finance:read/finance:write, the TV capability routes (tv-embed, tv-links GET/POST/DELETE) and the three organizations routes with billing mixed in. The route-scope tests walk that list, refuse an analytics-only member on every finance-scoped route, and fail when a new finance-scoped route is not audited into it. Sweep of the rest of app/api: fair-use user detail keeps only the subscription plan tier label under users:read (support context; no billing ids or amounts); app-store payment metadata (payment_link, price) stays under apps:write as listing configuration; /api/internal/precompute stays behind the cron secret and returns only metric names — nothing else financial is reachable without finance:read.

Commit 5fa2189832d (2026-10-22, third review round — Codex Luna FIX-first: financial FIELDS kept leaking through non-finance routes one route at a time; the fix is structural, not per route):

  • Central field-level redaction, applied at one choke point. lib/financial-fields.ts defines every financial field name and prefix (money_made, price/price_*, payment*, subscription*, stripe_*, customer_id, next_billing_date, revenue, mrr, arr, amount*, cost*, payout*, total_earned, pending_amount — derived from omiApi.generated.ts and the Firestore doc shapes the routes read) plus a deep redactor. It runs in ONE place every scoped JSON response passes through: AdminIdentity.json in lib/auth.ts, which strips those fields at any depth unless the caller holds finance:read. A route-scopes inventory test fails if a scoped route file calls NextResponse.json directly, so a new route cannot bypass the wall by accident.
  • Luna's findings covered by it: P1 app earnings — apps, apps/stats, apps/unapproved, apps/[app_id]/details, private-apps, summary-apps returned money_made/price/payment_* under apps:read; all redacted now. P2 fair-use user detail subscription.plan under users:read — redacted (the page falls back to the basic label). This supersedes the round-2 call to keep the plan tier label and payment_link/price visible: the apps UI only ever renders the is_paid Paid/Free badge, so nothing financial is lost.
  • No per-field opt-outs today. identity.json(body, init, keep?) exists for a justified exception and requires a comment at the call site plus a wall test. is_paid stays visible deliberately: it is the listing/review badge, not an amount.
  • organizations: the per-route redactBilling helper is retired into the wall (lib/organizations.ts deleted; the billing key is now removed rather than nulled, and the finance:write gate on attaching/clearing Stripe payments is unchanged).
  • P2 — invite Auth-account orphan. addMember (lib/team/roster.ts) re-authorizes from a current adminData read BEFORE provisioning a Firebase Auth account, and when its transaction still rejects (the demotion landed in between), deletes the Auth account — only when this request created it; a pre-existing account is never deleted. Tested with an email that has no existing Auth account (app/api/omi/team-members/__tests__/route.test.ts).
  • The guard against the next leak: lib/__tests__/financial-wall.test.ts reuses the route inventory to call every scoped GET handler as a member holding every scope EXCEPT finance:read, with every data source seeded with the entire financial field list (Omi API apps service, plugins_data, users + fair-use state/events, organisations, distributors), and fails if any financial field name appears anywhere in any response body. It also proves the fixtures actually flowed (so the scan is not vacuous) and that finance:read callers still see the fields. Fail-without-fix was verified separately for the redactor and the Auth-account rollback by disabling each: the matching test fails.

Commit ff7a10f0d52 (2026-10-22, final fix round — the five David-approved findings from Codex Luna's third review; each landed with a test that fails without it, proven by temporarily reverting the hunk):

  • P1 — the local coding-agent endpoint is unreachable outside local development. POST /api/omi/agent/customize (which spawns claude/codex with permission-bypass flags and streamed output) returns 404 for everyone — including owners with dev:agent — unless NODE_ENV !== "production" AND the explicit ADMIN_LOCAL_AGENT=1 opt-in is set (lib/local-agent.ts). When enabled, the child gets a minimal allowlisted env (PATH/HOME plus only the CLI's own ANTHROPIC_*/OPENAI_*/CLAUDE_*/CODEX_* auth vars), never process.env with the server's Firebase credentials and secrets. A new GET on the same route reports {enabled} to dev:agent holders, and the dashboard hides the "Customize this dashboard" card while the server reports disabled (hooks/useLocalAgent.ts). Tests: lib/__tests__/agent-customize-route.test.ts (404 without opt-in, 404 in production with it, allowlisted spawn env with a canary secret, honest enabled report) and the card-hiding case in lib/__tests__/classic-dashboard-finance.test.tsx.
  • P2 — invite orphan-cleanup race is closed. addMember (lib/team/roster.ts) now takes a per-normalized-email lock doc (adminProposalLocks/invite-<digest>, read and written inside the transaction like the proposal locks), so overlapping invites for one email conflict and re-run serially; and the rollback deletes the provisioned Auth account only when this request created it AND no adminData/{uid} doc references the uid after the transaction — a concurrent invite that adopted the account keeps it alive (a delete failure or unreadable re-check also keeps it; removing an orphan by hand beats deleting a live grant). Tests: app/api/omi/team-members/__tests__/route.test.ts — "never deletes an Auth account a concurrent invite adopted" drives the A-provisions/B-adopts/A-rejects interleaving through the fake Firestore, and "serializes invites per email on a lock doc".
  • P2 — mobile onboarding responses go through the wall. lib/mobile-onboarding-route.ts responds via AdminIdentity.json instead of NextResponse.json, so cached and computed payloads alike pass the financial field wall. The static guard in lib/__tests__/route-scopes.test.ts now also scans the lib helpers each scoped route imports (only error envelopes may be built with NextResponse.json; lib/auth.ts — the guard itself — is exempt), so a shared helper cannot bypass the wall either. The wall test seeds the precomputed onboarding payload cache with the financial sentinel list and asserts a successful onboarding response that redacts it for a non-finance member (lib/__tests__/financial-wall.test.ts).
  • P2 — the classic dashboard (the non-finance fallback) no longer fetches or renders finance data. For a viewer without finance:read, dashboard/classic/page.tsx skips the revenue, mrr-trends, subscription-trends, subscriptions, profitability and infra-costs requests entirely and renders neither their KPI tiles (MRR/ARR/Subscriptions/cost-per-user, the profitability summary's per-platform total-users KPIs) nor the Revenue Overview and Profitability sections — no $0 KPIs and no "Loading cost breakdown…" tile stuck forever; analytics tiles are unchanged. Component tests both ways (fetch URL capture + tile presence/absence, plus the agent-card gating): lib/__tests__/classic-dashboard-finance.test.tsx.
  • P2 — the fair-use plan row no longer invents a "basic" tier. The wall strips subscription_plan from the user-detail response without finance:read; the detail page now shows "Restricted" instead of falling back to basic (unknown access counts as restricted; a finance:read viewer still sees the real plan, with the basic fallback only when the plan is genuinely absent). Tests: lib/__tests__/fair-use-plan.test.tsx (restricted without finance, real plan and honest fallback with it).

Commit 831e6bdce71 (2026-10-22, Codex Luna verification — two final simplifications):

  • The invite Auth-account rollback is removed entirely. The check-then-delete outside the transaction still raced. A rejected invite may now leave the unverified, credential-less Firebase Auth user it provisioned behind — harmless (no adminData doc → no admin access) and reused by the next invite of the same email, so nothing deletes Auth accounts anymore (lib/team/roster.ts, docs/team-access.md). The per-email lock and the pre-provision re-authorization stay: a demoted actor still provisions nothing. Tests: the deletion-asserting tests are gone; "keeps the Auth account a rejected invite provisioned, and the next invite reuses it" replaces them and fails on the old code; "never deletes an Auth account a concurrent invite adopted" now asserts no deleteUser call at all; the lock test drives two overlapping invites for one email (exactly one commits, the other retries into 409) and fails if the transaction stops reading the lock — not merely because a lock doc exists.
  • The error-envelope exemption is strict. The static guard in lib/__tests__/route-scopes.test.ts exempts NextResponse.json({ error: <message> }, …) only when the object's only keys are error (required) plus optional code/details, each a string literal or plain message identifier; the old regex exempted { error: "x", revenue }. A negative fixture proves the leaky shape is flagged (it fails against the old regex), with a bare-envelope fixture guarding the exemption itself.

UI evidence

Team page: roles, proposals, audit log
Role change confirmation with scope diff

Product invariants affected

none

Open questions

  1. Deploy wiring: ADMIN_TEAM_AGENT_AUDIENCE (suggested https://admin.omi.me/api/agent/team) and ADMIN_TEAM_AGENT_SAS need passing to Cloud Run in .github/workflows/gcp_admin.yml, the same way as the stats-reader vars. I didn't touch .github/. A dedicated SA (e.g. omi-team-agent@, no roles, no keys) and its serviceAccountOpenIdTokenCreator grants are a separate IAM step.
  2. Scope placement: POST /api/omi/notifications/regenerate is under users:read because it only runs the LLM on data the page already shows and mutates nothing. The finance aggregates on /dashboard need finance:read, so Viewer/Support see N/A on those cards. Say if either should move.
  3. Should deputies keep the new ability to remove non-deputy members, or should removal stay owner-only and leave deputies with role changes and approvals?

🤖 Generated with Claude Code

Git-on-my-level and others added 2 commits October 22, 2026 16:36
…r proposals

Roles (owner, deputy, admin, finance, support, viewer) map to per-area
scopes stored on adminData/{uid}.accessRole with optional overrides.
requireScope replaces verifyAdmin in every API handler; a route inventory
test fails for any handler without a declared scope or that admits a member
lacking it. Docs without accessRole keep their pre-role access until a role
is assigned.

The Team page shows uid prefix, created and last sign-in, changes roles,
approves agent proposals and lists the audit log. Agents with an
allowlisted Google service-account ID token can read the roster and audit
log and file add/remove/role proposals that apply only on owner or deputy
approval.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T17:09:17.895213Z 831e6bd New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 91977f974a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +214 to +215
await db.runTransaction(async (tx) => {
tx.set(ref, proposal);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce proposal limits atomically

When multiple proposal POSTs overlap, each request can complete the pending-count and duplicate checks before any request reaches this transaction, after which every transaction writes a different auto-ID document without rechecking those constraints. A burst can therefore create duplicate changes for one target or exceed MAX_PENDING_PER_AGENT, defeating the controls intended to stop an agent from burying the approval queue; serialize the checks and creation through a shared transactional record or deterministic proposal key.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d36300e: filing now serializes on per-agent/per-target lock docs inside the transaction; pending proposals are listed independently of the history limit; expiry is audited with a system actor and proposedBy kept. Burst tests cover the races (they fail without the locks).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already addressed at this commit (d36300e): checks and creation run inside one transaction that reads and writes per-agent and per-target lock docs (lines ~203-210), so overlapping filings conflict and re-run the checks. Covered by the burst tests in agent-team.test.ts, which fail when the lock reads are removed.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

already covered by agent-team.test.ts — 'holds the per-agent cap under a burst of overlapping proposals' and 'files only one of two overlapping proposals for the same target' (fixed in d36300e)

Comment thread web/admin/lib/team/proposals.ts Outdated
Comment on lines +258 to +259
.orderBy("createdAt", "desc")
.limit(Math.min(Math.max(limit, 1), 200))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep live proposals visible beyond the history limit

When more than 100 newer proposals exist within the 72-hour window, this query limits the mixed-status history before the UI filters for pending, so an older but still-live pending proposal can disappear from both human and agent listings. For example, one pending request followed by 100 quickly rejected requests remains approvable by ID but is no longer shown to approvers; query pending proposals separately or paginate without dropping actionable entries.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d36300e: filing now serializes on per-agent/per-target lock docs inside the transaction; pending proposals are listed independently of the history limit; expiry is audited with a system actor and proposedBy kept. Burst tests cover the races (they fail without the locks).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

already covered by agent-team.test.ts — 'keeps an older pending proposal listed behind a long decided history' (fixed in d36300e)

Comment on lines +122 to +123
const { proposals, mutate: mutateProposals } = useTeamProposals();
const { entries, mutate: mutateAudit } = useTeamAudit();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Surface failures from proposal and audit requests

When the roster request succeeds but either the proposals or audit request returns an error, these destructurings discard those resources' error and loading state. Their hooks then supply empty arrays, causing pending approvals to vanish and the audit card to claim “No events yet” instead of showing unavailable data, so owners can mistake a partial fetch failure for an empty queue; handle each request's failure state explicitly.

AGENTS.md reference: web/admin/AGENTS.md:L9-L9

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d36300e: proposal and audit fetch errors are shown explicitly instead of empty states (tested).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

already covered by team page.test.tsx — 'says when proposals or the audit log failed to load, instead of showing them empty' (fixed in d36300e)

Comment on lines +108 to +112
const requiredScope = pageScope(pathname ?? "");
const blockedScope =
access && requiredScope && !access.scopes.includes(requiredScope)
? requiredScope
: null;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Gate write controls separately from readable pages

When a Viewer or Support member opens a page unlocked by content:read or apps:read, this layout admits the entire existing page even though those pages also render write controls. For example, /dashboard/announcements still shows Create, Edit, and Delete actions, but every corresponding request now requires content:write and returns 403; the same mismatch affects review and other read/write pages. Use the caller's write scope to hide or disable mutation controls rather than treating the page's read scope as sufficient for the whole UI.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly addressed in d36300e: pages readable without their write scope now show a read-only notice naming the missing scope, and the coding-agent widget requires dev:agent. The server already refuses the writes (403). Hiding each page's individual edit buttons is listed as a follow-up in the PR body.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as the earlier thread: this commit adds a read-only notice for pages whose write scope is missing; the server refuses the writes with 403. Per-button hiding on each page is a tracked follow-up in the PR body.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

already covered by admin-access.test.ts 'names the scope a page's edit controls need' plus the new dashboard layout test 'tells a member who can read a page but not change it that the page is read-only' in 5f8ce96 (read-only notice added in d36300e)

Comment thread web/admin/hooks/useAdminAccess.ts Outdated
Comment on lines +21 to +24
const { data, error, isLoading } = useSWR<AdminAccess>(
token ? ["/api/omi/access", token] : null,
authenticatedFetcher,
{ revalidateOnFocus: false }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Revalidate cached access after remote role changes

When an owner or deputy changes another currently signed-in member's role, the member's dashboard layout and sidebar keep this cached access response because focus revalidation is disabled and the persistent dashboard layout does not remount during navigation. Revoked pages therefore remain visible and newly granted pages remain hidden until a full reload, while requests to revoked APIs only start failing with 403; allow centralized SWR revalidation or otherwise refresh access so the UI follows server-side role changes.

AGENTS.md reference: web/admin/AGENTS.md:L9-L9

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d36300e: access revalidates on focus and every 60s, so the sidebar/page gates follow role changes without a reload.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

already covered by hooks/tests/useAdminAccess.test.tsx — 'follows role changes without a reload: revalidates on focus and every minute' (fix in d36300e, test pin in 5f8ce96)

Comment on lines +241 to +244
audit(tx, {
action: "proposal.expired",
actor: agentActor(data.proposedBy.email),
target: data.target,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Attribute automatic expiry to a system actor

Whenever a stale proposal is expired during a list request, this audit entry records the proposing agent as the actor even though the agent did not perform the expiry. The Team page consequently reports that agent under “Who” for proposal.expired, corrupting the audit trail and making an automatic lifecycle event look like an agent action; retain the existing proposedBy field and represent expiry with a distinct system actor instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d36300e: filing now serializes on per-agent/per-target lock docs inside the transaction; pending proposals are listed independently of the history limit; expiry is audited with a system actor and proposedBy kept. Burst tests cover the races (they fail without the locks).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already addressed at this commit: expiry is audited with EXPIRY_ACTOR ({type: "system", id: "proposal-expiry"}) and proposedBy keeps the agent; asserted in the expiry test.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

already covered by agent-team.test.ts — 'expires unapproved proposals and audits the expiry' (asserts actor {type: system, id: proposal-expiry}; fixed in d36300e)

…, honest errors, read-only notice

- Serialize proposal filing per agent and per target with lock docs read and
  written in the filing transaction; the in-memory fake now retries on
  read-doc conflicts like Firestore, and overlapping-burst tests fail without
  the locks.
- List every pending proposal regardless of the history limit.
- Attribute automatic expiry to a system actor, keeping proposedBy.
- Team page shows proposal and audit fetch failures instead of empty states.
- Access refreshes every minute and on focus; pages readable without their
  write scope show a read-only notice; the coding-agent widget needs dev:agent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d36300e965

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".


export async function GET(request: NextRequest) {
const admin = await verifyAdmin(request);
const admin = await requireScope(request, "analytics:read");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Require finance access before minting the business dashboard

When a Support or Viewer member opens /dashboard, they have analytics:read but not finance:read in lib/admin-access.ts, yet this endpoint enrolls them into the shared omi-tv-v2 board. That board contains Revenue, MRR-by-plan, Shopify sales, and Cost-vs-revenue panels in grafana/build_wall_dashboard.py, so these roles can bypass the finance-scoped API routes and view restricted Stripe and cost metrics; require finance access for this embed or provide an analytics-only board.

AGENTS.md reference: web/admin/AGENTS.md:L11-L12

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in 5f8ce96 + route-scopes.test.ts 'pins financial data endpoints to finance:read' and 'refuses an analytics-only member the business board and the wall'; /dashboard now falls back to the classic analytics page on 403

Comment thread web/admin/lib/team/proposals.ts Outdated
Comment on lines +205 to +207
const targetLock = locks.doc(
`target-${digest(`${input.kind}|${target.uid ?? target.email}`)}`
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Deduplicate all proposal kinds by target

When an agent files set_role and remove_member proposals for the same UID, including input.kind in the lock ID gives the requests different locks, and the duplicate predicate likewise requires matching kinds. Both proposals are therefore accepted despite the stated one-pending-per-target invariant; approving one can make the other fail as stale or apply a role change immediately before removal. Build the lock and duplicate identity from the target alone.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in 5f8ce96 + agent-team.test.ts 'refuses a pending proposal of another kind for the same target' and 'files only one of two overlapping proposals of different kinds for the same target' (lock id and duplicate predicate are now target-only)

…1, several owners

- POST /api/omi/notifications/regenerate moves from users:read to users:write
  in the route policy, the handler and SCOPE_LABELS; the notifications page
  declares users:write as its edit scope so read-only roles see the notice.
- authenticate() answers Firebase token verification throws (malformed, bad
  signature, expired, revoked) with 401 instead of 500. verifyFirebaseToken
  propagates SDK errors and a new isFirebaseTokenError classifies them;
  genuine server faults (Firestore, SDK internal errors) stay 500. Both
  classes are tested.
- Agent routes: a request with no Authorization header is rejected with 401
  on all four routes (test).
- Owners: confirmed deputies may remove admins but never owners or other
  deputies. Documented that there may be more than one owner (prod carries
  two), that no owner can be changed or removed through the UI or API by
  anyone including another owner, with a two-owner test; "the workspace
  owner" wording becomes "an owner" across code, UI and docs.
- web/admin/AGENTS.md notes the agent API ships disabled (no deploy sets
  ADMIN_TEAM_AGENT_*) and is enabled by a separate David-approved
  deploy-config change listing the allowlisted service accounts.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 866095ae40

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

props: { params: Promise<{ name: string }> }
) {
const auth = await verifyAdmin(request);
const auth = await requireScope(request, "analytics:read");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Require finance access for financial wall series

When a Viewer or Support member requests /api/omi/stats/wall/series/revenue, /health, or /headline, this analytics-only guard admits them even though those payloads include MRR, hardware revenue, net cost, and cost-per-MAU; the sibling /api/omi/stats/wall route has the same mixed financial payload. This provides a direct bypass around the routes protected by finance:read, even if the Grafana embed is fixed, so financial series need a finance check or must be filtered from analytics-only responses.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in 5f8ce96 + route-scopes.test.ts 'pins financial data endpoints to finance:read' and 'refuses an analytics-only member the business board and the wall' — /wall and /wall/series/[name] (headline, revenue, health included) are finance:read; no other analytics-scoped stats route serves financial data (audited)

Comment thread web/admin/lib/team/proposals.ts Outdated
};

if (proposal.kind === "add_member") {
await addMember(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Return invite failures from proposal approvals

When an approved add_member proposal reaches addMember and Resend is unconfigured, unreachable, or rejects the email, addMember returns emailSent: false, but this call discards that result and the approval endpoint still reports an ordinary success. Unlike the direct-add flow, the approver is never told that the newly provisioned member received no sign-in instructions, so propagate the delivery result in the approval response and UI.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in 5f8ce96 + agent-team.test.ts 'tells the approver when an approved add-person invite email fails, and audits it' and team page.test.tsx 'warns the approver when an approved add-person invite email fails' (emailSent:false in the approval response, member.invite_failed audit entry, approver toast)

… dedupe, invite-failure reporting

- GET /api/grafana/embed, /api/omi/stats/wall and /api/omi/stats/wall/series/[name]
  require finance:read: the omi-tv-v2 Business board and the wall carry MRR,
  hardware revenue and all-in cost, so analytics-only roles (viewer, support)
  can no longer reach them. The route-scope test pins the three financial
  endpoints and refuses a viewer on each; the dashboard falls back to the
  classic analytics page when the embed answers 403.
- Proposals dedupe by target regardless of kind: the target lock id and the
  duplicate predicate drop input.kind, so set_role and remove_member for one
  uid cannot both be pending (sequential 409; one of two overlapping filings
  wins — both tested).
- An approved add_member whose invite email fails reports emailSent: false in
  the approval response, writes a member.invite_failed audit entry, and the
  Team page toast tells the approver the person received no sign-in email.
- Direct tests for the earlier read-only notice and access revalidation fixes.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5f8ce96b39

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +59 to +60
<Suspense fallback={<p role="status">Loading analytics…</p>}>
<ClassicDashboard />

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Hide finance widgets from the analytics-only fallback

When a Viewer or Support member receives the expected 403 from the finance-protected embed, this fallback mounts ClassicDashboard, which still requests the finance-only revenue, MRR, subscription, profitability, and infrastructure endpoints. Those requests now fail, but the classic page defaults missing revenue and subscription values to zero and renders $0/0 cards, so these roles see false financial results rather than an analytics-only dashboard or N/A values; conditionally omit the finance widgets and requests for callers without finance:read.

AGENTS.md reference: web/admin/AGENTS.md:L9-L9

Useful? React with 👍 / 👎.

Comment on lines +128 to +132
const BAD_TOKEN_CODES = new Set([
"auth/argument-error", // malformed token or signature mismatch
"auth/id-token-expired",
"auth/id-token-revoked",
]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat invalid Firebase ID tokens as authentication failures

When verifyIdToken() rejects a structurally valid Firebase-looking JWT with auth/invalid-id-token, this set does not classify it as a client token fault, so authenticate() returns 500 instead of 401 and logs it as a server failure. The Firebase Admin API explicitly documents auth/invalid-id-token as a token-validation error; include it alongside the expired and revoked codes so invalid signatures or claims cannot masquerade as service outages.

Useful? React with 👍 / 👎.

Comment on lines +13 to 14
const authResult = await requireScope(request, "apps:read");
if (authResult instanceof NextResponse) return authResult;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Redact integration credentials from app-read responses

When a Viewer or Support member calls this endpoint, apps:read admits them and the handler returns the complete plugins_data document. MCP app documents store client_secret, code_verifier, and access/refresh tokens under external_integration.mcp_oauth_tokens, and the app detail UI renders that object as JSON; the sibling private-app and summary-app reads also spread raw documents into their responses. A nominally read-only role can therefore exfiltrate credentials and use them to mutate third-party integrations, so project or recursively redact secret fields server-side before returning any apps:read payload.

Useful? React with 👍 / 👎.

Comment on lines 92 to 94
export async function GET(request: NextRequest) {
const authResult = await verifyAdmin(request);
const authResult = await requireScope(request, "content:read");
if (authResult instanceof NextResponse) return authResult;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Require user-data access before sampling chat messages

When a member has content:read but not users:read—notably the new Viewer role—this guard still allows the request, after which the route reads hundreds of human messages from a known user and up to twenty other users and returns their normalized text in your_questions and all_users_questions. Because extractTopQuestions includes single-occurrence messages, this exposes verbatim private conversation content rather than only an aggregate; require users:read for this sampling path or return only curated/redacted questions to content-only roles.

Useful? React with 👍 / 👎.

…in-flight re-auth, pure proposal reads

- TV share links are finance data now that the only shareable board is the
  financial omi-tv-v2 Business one: minting a link requires finance:read on
  top of analytics:share, the link list and revoke responses redact the share
  tokens without it, and resolveActiveTvToken re-checks the issuer still
  exists and still holds finance:read on every kiosk view, so a demoted or
  removed issuer's links stop working (tv-embed, tv/view and lastUsedAt all
  behind that check). Tested at the lib and route level.
- Organizations: the subscription block (Stripe payment/customer ids, plan,
  status, period) is redacted from every organizations response without
  finance:read, and attaching or clearing a Stripe payment requires
  finance:write on top of the partners scope; partner-metadata edits are
  unchanged. Shared redaction helper in lib/organizations.ts.
- Team mutations no longer trust the request's access snapshot: every add,
  removal, role change, deputy appointment and proposal approval/rejection
  re-reads the actor's adminData doc inside the mutation's own transaction
  and re-authorizes from it, so a demotion or removal landing mid-flight
  aborts the change. Tests use the fake Firestore's conflict retry to land
  the demotion between the transaction's read and its commit.
- GET proposals is pure: expiry is derived per response from expiresAt and
  the persisted transition plus its audit entry land on the next write
  (deciding an expired proposal still refuses with 410 and records it).
- lib/route-scopes.ts exports FINANCIAL_ROUTES, the audited list of every
  route that can surface financial data directly (pinned to finance scopes),
  through the TV share-link capability, or mixed into partner org data. The
  route-scope tests walk that list, refuse an analytics-only member on every
  finance-scoped route, and fail when a new finance-scoped route is not
  audited into it. Audit of the rest of app/api: fair-use user detail keeps
  only the subscription plan tier label under users:read (support context);
  app-store payment metadata stays under apps:write (listing config, not
  company financials); precompute stays behind the cron secret and returns
  only metric names.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d40f20457d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

export async function listProposals(limit = 100): Promise<Proposal[]> {
const db = getDb();
const [pending, recent] = await Promise.all([
db.collection("adminProposals").where("status", "==", "pending").get(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Exclude expired proposals from the pending query

When proposals expire without anyone attempting a decision, their stored status remains pending because expireStale() is only called by decideProposal(). This query therefore keeps returning every expired proposal in addition to the limited recent history, making the limit ineffective and causing both proposal listings and filing-time pending scans to grow without bound; persist expiry during a write/cleanup path or exclude derived-expired records from the pending set.

Useful? React with 👍 / 👎.

Three review rounds found financial fields leaking through non-finance
routes one at a time. Stop patching per route:

- lib/financial-fields.ts: one list of financial field names and
  prefixes (derived from omiApi.generated.ts and the Firestore doc
  shapes routes read) plus a deep redactor.
- One choke point: AdminIdentity.json in lib/auth.ts. Every scoped
  route now serializes JSON through it, and it strips the financial
  fields unless the caller holds finance:read. A route-scopes test
  fails if a scoped route file calls NextResponse.json directly.
  Covers the P1 app-earnings leak (apps, apps/stats, unapproved,
  details, private-apps, summary-apps) and the P2 fair-use
  subscription.plan leak. No per-field opt-out is needed today; the
  keep parameter exists for one that is justified (comment + wall
  test required). is_paid stays: the review UI's Paid/Free badge.
- organizations: the per-route redactBilling is retired into the wall
  (the key is now removed, not nulled); finance:write checks unchanged.
- lib/team/roster.ts: addMember re-authorizes from a current read
  before provisioning a Firebase Auth account, and deletes the account
  it created (never a pre-existing one) if the transaction rejects —
  a demoted inviter no longer leaves an orphan Auth account.
- lib/__tests__/financial-wall.test.ts: calls every scoped GET handler
  as a member holding every scope except finance:read, with fixtures
  seeded with the entire financial field list in every data source,
  and fails if any financial field name appears in any response body.
  Fail-without-fix verified by disabling the redactor and the rollback
  separately; each makes its test fail.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ff7a10f0d5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".


export async function GET(request: NextRequest) {
const authResult = await verifyAdmin(request);
const authResult = await requireScope(request, "analytics:read");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require content access for CSAT comments

When a Finance member calls this endpoint directly, analytics:read admits them even though the CSAT page is gated by content:read and Finance lacks that scope; the response includes up to 50 verbatim comments and their user UIDs, not merely aggregate metrics. Require content:read here and in the route inventory, or split the comments into a separately protected response.

AGENTS.md reference: web/admin/AGENTS.md:L6-L6

Useful? React with 👍 / 👎.

Comment on lines +205 to +206
const targetKey = target.uid ?? target.email ?? "";
const targetLock = locks.doc(`target-${lockDigest(targetKey)}`);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize direct invites with add-member proposals

When a human invite and an agent add_member proposal for the same email overlap, this transaction locks target-<digest> while addMember() locks invite-<digest>, and the membership lookup was performed before either transaction. Both requests can therefore commit: the person is added directly while a redundant proposal remains pending, and approving that proposal later returns 409 without deciding it. Use the same normalized-email lock and repeat the membership check inside the filing transaction.

Useful? React with 👍 / 👎.

Comment thread web/admin/lib/team/roster.ts Outdated
Comment on lines +343 to +345
} else {
try {
await getAdminAuth().deleteUser(firebaseUser.uid);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Close the invite cleanup race before deleting Auth users

When one invite provisions an Auth user but its Firestore transaction fails, another invite can adopt that same user after this existence check returns false but before deleteUser() runs. The second invite then commits an adminData/{uid} grant whose Auth user is immediately deleted, so the successful invitee receives an email but cannot sign in under the granted UID. The cleanup must not rely on this non-atomic read-then-delete sequence; retaining the credential-less account is safer unless adoption can be fenced across both systems.

Useful? React with 👍 / 👎.

Comment on lines +116 to +118
if (
stripe_payment_id !== undefined &&
!hasScope(authResult.access, "finance:write")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Omit hidden billing fields from metadata edits

When a member has partners:write but not finance:write, the organization edit form still initializes stripe_payment_id to an empty string and serializes it with every name, website, or seat update. This presence check consequently treats an ordinary metadata edit as a request to clear billing and returns 403, making the full edit dialog unusable despite the caller holding its advertised write scope. Hide or omit the Stripe field unless the caller can intentionally change it.

AGENTS.md reference: web/admin/AGENTS.md:L13-L15

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 1ec0ba0 into main Oct 22, 2026
48 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/admin-roles branch October 22, 2026 17:08

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 831e6bdce7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".


export async function GET(request: NextRequest) {
const authResult = await verifyAdmin(request);
const authResult = await requireScope(request, "content:read");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep dashboard chat ratings available to Finance

When a Finance member opens /dashboard/classic, or /dashboard falls back there while the Grafana embed is disabled, the page is admitted by analytics:read but both chat-rating requests now require content:read, which Finance does not have. The hooks ignore the resulting 403 and convert the missing response into zero totals and “No chat ratings data available,” so this role sees false analytics; either keep this aggregate endpoint under analytics:read or gate the widget and surface an unavailable state.

AGENTS.md reference: web/admin/AGENTS.md:L6-L6

Useful? React with 👍 / 👎.


export async function GET(request: NextRequest) {
const authResult = await verifyAdmin(request);
const authResult = await requireScope(request, "finance:read");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Hide finance-only cards from the Apps page

When a Viewer or Support member opens /dashboard/apps, apps:read admits the page, but its unchanged WelcomeOverview still unconditionally requests this endpoint and /api/omi/stats/app-subscriptions. Both now require finance:read, so two cards render 403 error states on an otherwise permitted page; gate those requests and cards on finance:read or remove the financial overview from the Apps page.

AGENTS.md reference: web/admin/AGENTS.md:L6-L6

Useful? React with 👍 / 👎.

Git-on-my-level added a commit that referenced this pull request Oct 22, 2026
Conflict resolution: main's #23279 role-based admin auth (requireScope,
hasScope, authResult.json) taken everywhere; this lane's Stripe read-client
split re-applied on top (getStripeRead/getOptionalStripeRead in the read
routes and test mocks; affiliate-payouts keeps the full key only for
stripe.transfers.create).
Git-on-my-level added a commit that referenced this pull request Oct 22, 2026
#23279 review follow-ups (#23330)

* admin: sensitive-field classes (financial, credentials, user content) + #23279 review follow-ups

Generalize the financial field wall into a classification table
(lib/sensitive-fields.ts): one redactor, one table, one wall test that
sweeps every scoped GET per class. Credentials never reach the browser;
private user content needs users:read.

Follow-ups to #23279 Codex review findings that still apply at HEAD:
- app reads strip MCP integration credentials (credentials class)
- Chat Lab question sampling needs users:read; content:read keeps
  curated questions only
- CSAT stats gated content:read; free-text comments wall-gated users:read
- agent add_member proposals and direct invites share the per-email lock;
  membership re-checked inside the filing transaction; a pending proposal
  refuses a duplicate direct invite
- the next filing persists stale proposals' expiry (system actor)
- org edit dialog sends no billing field without finance:write
- Apps page and classic dashboard hide finance/content-scoped cards
- auth/invalid-id-token answers 401, not 500

* admin: billing edits need finance:read and finance:write

A member with finance:write but not finance:read sees the subscription
redacted; the edit form sent the blank Stripe field and PATCH cleared the
subscription. The form now hides the field and the route refuses billing
changes without both scopes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant