Skip to content

fix(web): show admin chrome only on the admin account's primary profile - #131

Merged
Quick104 merged 4 commits into
mainfrom
fix/admin-ui-primary-profile-gate
Jun 11, 2026
Merged

Quick104 merged 4 commits into
mainfrom
fix/admin-ui-primary-profile-gate

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The admin system-activity indicator (the upper-right notifications) and the sidebar Admin section were gated on the account-level role alone (user?.role === "admin"). Silo separates login accounts from household profiles, so every profile on an admin account — including a kid's profile — saw the admin chrome. The activity indicator also polls four admin endpoints (useAdminSessions, useTasks, useActiveScans, useAdminLibraries) on behalf of whoever is looking at it, so non-primary profiles were fetching other users' active sessions, scan and task state. On top of that, /admin could be deep-linked by URL from any profile on the account.

Fix

The policy is "an admin account only acts with admin powers through its household primary profile (or with no profile selected, e.g. right after login)", and it now lives in exactly one place per side:

Client

  • isActingAdmin(user, profile) in web/src/lib/permissions.ts is the single definition; the useIsActingAdmin() hook wraps it for components. Route gates (RequireAdmin, RequirePrimaryOrAdmin), the sidebar Admin link, the ServerActivity chrome, and the admin realtime channel subscription all share it, so the gate and the visible UI can no longer disagree about null-profile handling.
  • All remaining admin-gated surfaces reachable from regular pages were converted too: media-item context menus (play history / refresh metadata), the metadata dialog's Images tab, admin collection targets in Add-to-Collection, the marker editor, the theme catalog refresh, person-detail editing, the item-detail action bars, and the admin-only settings nav entries.
  • The role-derived permission bypass (hasPermission → metadata curation, marker editing) follows the same policy: an admin on a non-primary profile keeps only explicitly assigned permissions.
  • useCurrentProfile no longer spreads the whole react-query result (which defeated TanStack v5 tracked-properties and re-rendered route-gate subtrees on every isFetching flip); it returns { profile, isLoading } and is safe outside AuthProvider.

Server

  • New RequireActingAdmin middleware replaces RequireAdmin on the admin route groups: when a request declares an active profile (X-Profile-Id) that belongs to the admin account but is not primary, admin endpoints return 403. Requests with no declared profile behave as before.
  • The metadata-curation middleware applies the same rule to its admin bypass: an admin declaring a non-primary profile is held to explicitly assigned permissions like everyone else.
  • Honest scope note: profiles share the account's login session and X-Profile-Id is client-asserted, so this is a policy boundary for well-behaved clients (including PIN-locked profiles using stock clients), not a defense against the account holder. A hard boundary would require profile tokens on admin routes — out of scope here.

Why this approach

It matches the idiom the codebase already established: SettingsLayout.tsx gates profile management on is_primary, and the server-side transcription-quota exemption (#127 follow-up) treats "admin account acting as itself or through its primary profile" as the privileged combination — other profiles on the admin account are regular viewers. Centralizing the predicate (one function per side) follows the repo guideline that duplicate logic across files is a code smell.

Behavior changes to note

  • An admin on a non-primary profile now also loses: per-item admin actions on library pages, metadata/marker editing (unless explicitly granted as a permission), and direct API access to /admin/* while that profile is declared. Switching to the primary profile (or deselecting the profile) restores everything.
  • RequirePrimaryOrAdmin-gated settings (household profile management) are now also closed to an admin acting through a non-primary profile.

Follow-up candidates

  • Android/Apple clients should adopt the same acting-admin rule for their admin UI (the server now enforces it for declared profiles, so stock clients get 403s instead of silent inconsistency).
  • A hard enforcement story (profile tokens on admin routes) if profile PIN locks should ever be a real security boundary.

Verification

  • Go: go build ./internal/..., go vet ./internal/api/..., full go test ./internal/api/... pass; new middleware tests cover primary/non-primary/no-profile/unknown-profile/checker-error paths for both RequireActingAdmin and the curation bypass.
  • Web: production build (tsc -b + vite), ESLint (0 errors, warnings pre-existing), prettier, and the full frontend suite (187 files / 1,033 tests) pass.

AI-use disclosure

Diagnosed, implemented, and verified with Claude Code under human direction and review.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Changes

    • Admin navigation and actions now depend on whether you’re “acting” as an admin (tied to the selected profile); admin links, refresh buttons, and admin-only menu items hide or disable when not acting as admin.
    • Access to admin areas and server activity indicators is restricted to acting admins or when the selected profile is primary; non-primary profiles may be blocked or require explicit permissions.
    • Realtime admin jobs fall back to polling when not acting as admin.
  • Tests

    • Added coverage for profile-aware admin access scenarios.

The top-right ServerActivity indicator and the sidebar Admin section were
gated on the account-level role alone, so every profile on an admin
account — including child profiles — saw admin system notifications and
the indicator polled four admin endpoints on their behalf. Gate both on
the active profile being the household primary, matching the existing
is_primary idiom in SettingsLayout and the server-side quota exemption.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Quick104, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 35 minutes. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more credits in the billing tab to continue.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 42210859-abe5-4492-b0ec-f3b8d41344b9

📥 Commits

Reviewing files that changed from the base of the PR and between a18f1e2 and 48facf6.

📒 Files selected for processing (6)
  • internal/api/middleware/acting_admin_test.go
  • internal/api/middleware/auth.go
  • web/src/hooks/useCurrentProfile.ts
  • web/src/hooks/useIsActingAdmin.ts
  • web/src/lib/permissions.test.ts
  • web/src/lib/permissions.ts
📝 Walkthrough

Walkthrough

Introduce an acting-admin policy: server middleware enforces primary-profile-aware admin checks and permission middleware uses the checker; router wires the checker into admin routes; frontend adds isActingAdmin/useIsActingAdmin and updates permission checks and many UI components to use the new hook.

Changes

Acting-admin policy and UI gating

Layer / File(s) Summary
RequireActingAdmin middleware and tests
internal/api/middleware/auth.go, internal/api/middleware/acting_admin_test.go
Add PrimaryProfileChecker, RequireActingAdmin, standardized 500 helper, and tests covering admin/profile permutations.
Permission middleware changes and tests
internal/api/middleware/permissions.go, internal/api/middleware/permissions_test.go
PermissionMiddleware accepts a PrimaryProfileChecker; admin bypasses are gated by acting-admin logic and tests validate admin behavior with X-Profile-Id.
Router wiring for acting-admin
internal/api/router.go
Construct primary-profile checker from UserStoreProvider, wire requireActingAdmin into admin routes and permission middleware.
Frontend permissions lib and hook
web/src/lib/permissions.ts, web/src/hooks/useIsActingAdmin.ts, web/src/hooks/useCurrentProfile.ts
Add isActingAdmin and profile-aware hasPermission/helpers; add useIsActingAdmin and adjust useCurrentProfile to use optional-auth cached profile.
App route wrappers & realtime gating
web/src/App.tsx
RequireAdmin/RequirePrimaryOrAdmin and Admin realtime channels now use useIsActingAdmin and current-profile checks.
UI components updates & tests
web/src/components/*, web/src/pages/*, web/src/playback/*, tests
Replace direct user.role === "admin" checks with useIsActingAdmin(); update permission calls to pass currentProfile; adjust Vitest mocks to export useOptionalAuth where needed.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Silo-Server/silo-server#11: Adds metadata curation PermissionMiddleware and related admin-job handling; this PR modifies that middleware to integrate primary-profile acting-admin logic.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: restricting admin UI visibility to only an admin account's primary profile, which is the core objective and the primary change across the UI components.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/admin-ui-primary-profile-gate

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/src/App.tsx`:
- Around line 175-180: The admin-gate logic in RequireAdmin (currently reading
profile from useAuth()) is inconsistent with the rest of the UI which uses
useCurrentProfile(); update RequireAdmin to derive the active profile via
useCurrentProfile() instead of useAuth(). Locate the gating checks in the
component that uses user/profile (the RequireAdmin logic in App.tsx) and replace
the profile reference with the value returned from useCurrentProfile(), keeping
the same role check on user from useAuth(); ensure you import useCurrentProfile
and maintain the existing primary-profile check (profile.is_primary) so Admin
routes match AppSidebar and Layout behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1bdf703d-6622-4bc9-a9a0-bec841973f92

📥 Commits

Reviewing files that changed from the base of the PR and between bcfab5f and c17c0bb.

📒 Files selected for processing (3)
  • web/src/App.tsx
  • web/src/components/AppSidebar.tsx
  • web/src/components/Layout.tsx

Comment thread web/src/App.tsx Resolved
claude and others added 2 commits June 11, 2026 15:07
… gates

RequireAdmin/RequirePrimaryOrAdmin read the profile from useAuth(), but the
admin chrome (AppSidebar, Layout) gates on useCurrentProfile(), which resolves
the selected profile. Use the same source in the route gates so the redirect
and the visible admin UI can never disagree.

Co-Authored-By: Claude Fable 5 <[email protected]>
Address code-review findings on the primary-profile admin gate:

- Add isActingAdmin to web/src/lib/permissions.ts as the single
  client-side definition of the policy (admin role + primary or no
  profile), with a useIsActingAdmin hook on top. Route gates, sidebar,
  Layout, and realtime channel gating all use it now, so the gate and
  the chrome can no longer disagree on null-profile handling.
- Convert the admin-gated surfaces the original change missed
  (MediaItemMenu, EditMetadataDialog images tab, AddToCollectionDialog,
  MarkerEditor, theme CatalogBrowser, PersonDetail, SettingsLayout,
  ItemDetail content pages) so an admin on a non-primary profile is a
  regular viewer everywhere, not just in the sidebar.
- Make the role-derived permission bypass (metadata curation, marker
  edit) follow the same policy on both client and server.
- Enforce the policy server-side: RequireActingAdmin middleware refuses
  admin routes when the request declares a non-primary profile via
  X-Profile-Id, and the metadata-curation middleware holds admins on
  non-primary profiles to explicitly assigned permissions.
- Stop spreading the profiles query result from useCurrentProfile so
  route gates only re-render when the resolved profile changes, and
  make it safe outside AuthProvider.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Copy link
Copy Markdown
Contributor

Code review follow-up — addressed in a18f1e2

A review pass over this PR surfaced 7 findings (3 correctness/consistency, 2 completeness, 2 quality). All are addressed:

1. Policy was UI-only — no server enforcement ✅
New RequireActingAdmin middleware now backs all four admin route groups: a request declaring a non-primary profile via X-Profile-Id gets a 403 on /admin/*. The metadata-curation middleware applies the same rule to its admin bypass, so an admin on a non-primary profile is held to explicitly assigned permissions. Scope note: profiles share the account's login session and the header is client-asserted, so this is a policy boundary for well-behaved clients — a hard boundary (profile tokens on admin routes) is listed as follow-up.

2. Other admin-gated surfaces were missed ✅
Converted every role === "admin" surface reachable from regular pages: MediaItemMenu (play history / refresh metadata), EditMetadataDialog images tab, AddToCollectionDialog admin targets, MarkerEditor, theme CatalogBrowser refresh, PersonDetail editing, all four ItemDetail content pages (feeding ActionBar), SettingsLayout nav, and the admin realtime channel subscription + job waiter.

3. Gate vs. chrome disagreed on null profile ✅
RequireAdmin was null-permissive while the sidebar/Layout were null-restrictive. Both now share one predicate, so they can't disagree by construction.

4. Predicate duplicated 4 ways with variant semantics ✅
The policy now has a single client-side definition — isActingAdmin(user, profile) in lib/permissions.ts — with a useIsActingAdmin() hook for components. The role-derived permission bypass (hasPermission) routes through it too.

5. Two sources of truth for the current profile across gates ✅
All admin/primary decisions flow through useCurrentProfile via the shared hook. useAuth().profile remains only for existence checks (RequireProfile), where the sources can't diverge.

6. useCurrentProfile spread the whole query result ✅
Returning { profile, isLoading } instead of spreading restores TanStack v5 tracked-properties, so route gates no longer re-render the page tree on every background isFetching toggle. The hook is also safe outside AuthProvider now.

7. Stale cached is_primary during the profiles fetch — accepted as-is: the window is brief and self-correcting, is_primary is immutable through the API, and the server now enforces the policy independently.

Behavior change to note: RequirePrimaryOrAdmin previously admitted an admin on any profile; it now requires a primary profile or acting-admin, consistent with the policy.

Verification: full go test ./internal/api/... (incl. new middleware tests for primary/non-primary/no-profile/unknown-profile/checker-error paths), web production build, ESLint (0 errors), prettier, and the full frontend suite (187 files / 1,033 tests) all pass.

🤖 Generated with Claude Code

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
internal/api/middleware/permissions_test.go (1)

56-77: ⚡ Quick win

Add a regression test for the checker-error path.

RequireMetadataCurationForItem now returns 500 internal_error when checkPrimary fails, but the new profile-aware tests only cover allow/forbid outcomes. A single case here would lock down that new failure-mode contract.

Also applies to: 79-100

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/api/middleware/permissions_test.go` around lines 56 - 77, Add a
regression test that asserts RequireMetadataCurationForItem returns HTTP 500
when the PrimaryProfileChecker returns an error: update the test using
runMetadataCurationMiddlewareWithProfile by passing a fake checker
implementation that returns (false, error) (or make checkPrimary return an
error) and assert the response code is http.StatusInternalServerError; replicate
the same error-case test in the other profile-aware test block covering lines
79-100 so the new failure-mode contract is locked down.
web/src/components/RealtimeEventsProvider.test.tsx (1)

26-32: ⚡ Quick win

Add a non-primary-profile fixture for the new fallback path.

This mock still renders the provider as acting admin (profile: null), so the new !actingAdmin branch in awaitAdminJob(...) never gets exercised here. A focused case with profile: { id: "kid", is_primary: false } would lock in the "poll instead of waiting on admin channels" behavior that this PR is relying on.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/components/RealtimeEventsProvider.test.tsx` around lines 26 - 32, The
test mock for authentication always returns profile: null so the !actingAdmin
branch in awaitAdminJob(...) is never exercised; add a focused fixture and test
that returns useAuth/useOptionalAuth => { user: mockState.user, profile: { id:
"kid", is_primary: false } } (or create a separate test case that swaps the
mock) and assert that awaitAdminJob falls back to polling rather than waiting on
admin channels; update RealtimeEventsProvider.test.tsx to include this
non-primary-profile mock and the corresponding expectation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/api/middleware/auth.go`:
- Around line 213-230: The actingAdminAllowed function currently treats an
unresolved profile (found == false) as allowed; change it to fail-closed: after
calling checkPrimary(r.Context(), userID, profileID) return false, nil when
found is false, and only allow when isPrimary is true. Keep the existing
early-returns for checkPrimary == nil and empty declaredProfileID(r) unchanged;
update the final return logic so it returns isPrimary (not !found || isPrimary)
and still propagate errors from checkPrimary.

In `@web/src/hooks/useIsActingAdmin.ts`:
- Around line 10-13: useIsActingAdmin currently treats profile null the same for
"no profile selected" and "profile still loading", causing transient admin
access; update useCurrentProfile to expose an explicit unresolved/loading flag
(e.g., return { profile, isProfileUnresolved } or similar) and then change
useIsActingAdmin to early-return false while that unresolved flag is true before
calling isActingAdmin(user, profile); ensure types/signatures for
useCurrentProfile and useIsActingAdmin are updated accordingly so callers can
rely on the explicit unresolved state.

In `@web/src/lib/permissions.ts`:
- Around line 25-35: The profile parameter in hasPermission must fail closed
instead of treating undefined like null; update hasPermission (and its callers)
so profile is required or undefined is rejected: either remove the optional
marker so the signature is profile: Pick<Profile,"is_primary"> | null and update
all call sites to pass a resolved profile or explicit null, or add an explicit
guard at the top of hasPermission (if (profile === undefined) throw new
Error("profile must be provided or explicit null")) before calling
isActingAdmin(user, profile) to force callers to supply the resolved profile or
explicit null; ensure references to isActingAdmin and hasPermission are updated
accordingly.

---

Nitpick comments:
In `@internal/api/middleware/permissions_test.go`:
- Around line 56-77: Add a regression test that asserts
RequireMetadataCurationForItem returns HTTP 500 when the PrimaryProfileChecker
returns an error: update the test using runMetadataCurationMiddlewareWithProfile
by passing a fake checker implementation that returns (false, error) (or make
checkPrimary return an error) and assert the response code is
http.StatusInternalServerError; replicate the same error-case test in the other
profile-aware test block covering lines 79-100 so the new failure-mode contract
is locked down.

In `@web/src/components/RealtimeEventsProvider.test.tsx`:
- Around line 26-32: The test mock for authentication always returns profile:
null so the !actingAdmin branch in awaitAdminJob(...) is never exercised; add a
focused fixture and test that returns useAuth/useOptionalAuth => { user:
mockState.user, profile: { id: "kid", is_primary: false } } (or create a
separate test case that swaps the mock) and assert that awaitAdminJob falls back
to polling rather than waiting on admin channels; update
RealtimeEventsProvider.test.tsx to include this non-primary-profile mock and the
corresponding expectation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d37ee409-168c-4e1f-8e38-9f6e62b4d463

📥 Commits

Reviewing files that changed from the base of the PR and between c17c0bb and a18f1e2.

📒 Files selected for processing (30)
  • internal/api/middleware/acting_admin_test.go
  • internal/api/middleware/auth.go
  • internal/api/middleware/permissions.go
  • internal/api/middleware/permissions_test.go
  • internal/api/router.go
  • web/src/App.tsx
  • web/src/components/AddToCollectionDialog.tsx
  • web/src/components/AppSidebar.test.tsx
  • web/src/components/AppSidebar.tsx
  • web/src/components/EditMetadataDialog.tsx
  • web/src/components/Layout.tsx
  • web/src/components/MediaItemMenu.tsx
  • web/src/components/RealtimeEventsProvider.test.tsx
  • web/src/components/RealtimeEventsProvider.tsx
  • web/src/components/markers/MarkerEditor.tsx
  • web/src/components/theme/CatalogBrowser.tsx
  • web/src/hooks/useCurrentProfile.ts
  • web/src/hooks/useIsActingAdmin.ts
  • web/src/lib/permissions.ts
  • web/src/pages/ItemDetail/EpisodeContent.test.tsx
  • web/src/pages/ItemDetail/EpisodeContent.tsx
  • web/src/pages/ItemDetail/MovieContent.test.tsx
  • web/src/pages/ItemDetail/MovieContent.tsx
  • web/src/pages/ItemDetail/SeasonContent.test.tsx
  • web/src/pages/ItemDetail/SeasonContent.tsx
  • web/src/pages/ItemDetail/SeriesContent.tsx
  • web/src/pages/PersonDetail.tsx
  • web/src/pages/SettingsLayout.test.tsx
  • web/src/pages/SettingsLayout.tsx
  • web/src/playback/WatchPlaybackChrome.tsx
✅ Files skipped from review due to trivial changes (1)
  • web/src/pages/ItemDetail/EpisodeContent.test.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/src/components/AppSidebar.tsx

Comment thread internal/api/middleware/auth.go Resolved
Comment thread web/src/hooks/useIsActingAdmin.ts Resolved
Comment thread web/src/lib/permissions.ts Resolved
Address review feedback on the acting-admin gate:

- Server: actingAdminAllowed now denies when the declared profile cannot
  be resolved to one of the caller's profiles, so a bogus X-Profile-Id
  can no longer restore admin powers to a non-primary session.
- Client: useIsActingAdmin returns false while a selected profile id has
  not yet resolved (e.g. hard refresh before the profiles query
  returns), instead of briefly treating it as "no profile selected".
  useCurrentProfile exposes hasSelectedProfile to make that state
  distinguishable.
- hasPermission/canCurateMetadata/canEditMarkers now require the profile
  argument (resolved profile or explicit null), so a missed call site
  fails the typecheck instead of silently restoring the admin bypass.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104
Quick104 merged commit 6781c20 into main Jun 11, 2026
13 checks passed
@Quick104
Quick104 deleted the fix/admin-ui-primary-profile-gate branch June 11, 2026 14:41
Quick104 added a commit that referenced this pull request Jun 17, 2026
…le (#131)

* fix(web): show admin chrome only on the admin account's primary profile

The top-right ServerActivity indicator and the sidebar Admin section were
gated on the account-level role alone, so every profile on an admin
account — including child profiles — saw admin system notifications and
the indicator polled four admin endpoints on their behalf. Gate both on
the active profile being the household primary, matching the existing
is_primary idiom in SettingsLayout and the server-side quota exemption.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(web): resolve active profile via useCurrentProfile in admin route gates

RequireAdmin/RequirePrimaryOrAdmin read the profile from useAuth(), but the
admin chrome (AppSidebar, Layout) gates on useCurrentProfile(), which resolves
the selected profile. Use the same source in the route gates so the redirect
and the visible admin UI can never disagree.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(web,api): centralize acting-admin policy and enforce it server-side

Address code-review findings on the primary-profile admin gate:

- Add isActingAdmin to web/src/lib/permissions.ts as the single
  client-side definition of the policy (admin role + primary or no
  profile), with a useIsActingAdmin hook on top. Route gates, sidebar,
  Layout, and realtime channel gating all use it now, so the gate and
  the chrome can no longer disagree on null-profile handling.
- Convert the admin-gated surfaces the original change missed
  (MediaItemMenu, EditMetadataDialog images tab, AddToCollectionDialog,
  MarkerEditor, theme CatalogBrowser, PersonDetail, SettingsLayout,
  ItemDetail content pages) so an admin on a non-primary profile is a
  regular viewer everywhere, not just in the sidebar.
- Make the role-derived permission bypass (metadata curation, marker
  edit) follow the same policy on both client and server.
- Enforce the policy server-side: RequireActingAdmin middleware refuses
  admin routes when the request declares a non-primary profile via
  X-Profile-Id, and the metadata-curation middleware holds admins on
  non-primary profiles to explicitly assigned permissions.
- Stop spreading the profiles query result from useCurrentProfile so
  route gates only re-render when the resolved profile changes, and
  make it safe outside AuthProvider.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(web,api): fail closed on unresolved profiles in acting-admin policy

Address review feedback on the acting-admin gate:

- Server: actingAdminAllowed now denies when the declared profile cannot
  be resolved to one of the caller's profiles, so a bogus X-Profile-Id
  can no longer restore admin powers to a non-primary session.
- Client: useIsActingAdmin returns false while a selected profile id has
  not yet resolved (e.g. hard refresh before the profiles query
  returns), instead of briefly treating it as "no profile selected".
  useCurrentProfile exposes hasSelectedProfile to make that state
  distinguishable.
- hasPermission/canCurateMetadata/canEditMarkers now require the profile
  argument (resolved profile or explicit null), so a missed call site
  fails the typecheck instead of silently restoring the admin bypass.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Code <[email protected]>
Co-authored-by: Quick <[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.

3 participants