feat(fase-13): admin UI + sidebar entry + isServerAdmin store + e2e SA-01..04

13.3 admin UI:
  - (admin) route group with own layout + red banner + sidebar (Collectives,
    Admins, Audit log, Server). +layout.ts is client-rendered (ssr=false),
    same rationale as the (app) group.
  - /admin/collectives — paginated list via admin_list_collectives, search
    by name, soft-delete / restore / hard-delete modals (hard-delete needs
    explicit checkbox; force toggle bypasses the 30-day wait server-side).
  - /admin/collectives/[id] — members list with kick action; recent actions
    for the collective filtered from admin_actions.
  - /admin/admins — list via server_admins join to users (disambiguated by
    FK name — there are TWO FKs to users so the embed needs the explicit
    server_admins_user_id_fkey); promote modal does an email lookup; revoke
    button is replaced by "you (cannot revoke yourself while sole admin)"
    when applicable.
  - /admin/audit — paginated feed (default 50), action filter.
  - /admin/server — server-layer default-section toggles backed by
    admin_set_default_section + the new admin_clear_default_section RPC
    (added because patching the JSONB to `true` is NOT equivalent to "no
    opinion" — `true` explicitly overrides a collective OFF).

13.4 sidebar/drawer entry:
  - $isServerAdmin store (writable; +$isServerAdminLoaded for the gate
    race) refreshed on every onAuthStateChange in root layout, cleared on
    sign-out. Cached so the sidebar tile is synchronous.
  - DesktopSidebar + MobileDrawer render the entry only when the store is
    true. Distinct red icon so it never blends with normal nav.

Stores wiring:
  - features.ts gains serverSectionDefaults writable + enabledSections
    derived now reads server > collective > user > default. Loader
    piggybacks on loadCurrentUserFeatures so the server layer is fetched
    once per sign-in.
  - serverAdmin.ts new module — refreshServerAdminFlag() + clearServerAdminFlag().
  - Tracks isServerAdminLoaded so the (admin) layout doesn't redirect away
    during the millisecond between SIGNED_IN and the RPC resolving (caught
    empirically — every hard-load to /admin/* bounced to / without it).

13.5 tests:
  - admin.test.ts (SA-01..SA-04) with new loginAsAdmin fixture. Ana is the
    seed admin (server_admins seeded via supabase/seed.sql).
  - SA-04 + SV-02 reset their server-layer JSONB via the new
    admin_clear_default_section RPC so the suites don't leak state into
    each other.

Migration 025 adds admin_clear_default_section(text) — same SECURITY DEFINER
+ audit pattern as the rest. pgTAP 017 updated (23 plans, AR-T13b + the
SECURITY DEFINER list now includes the clear RPC).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-18 05:30:56 +02:00
parent 7556d77bf8
commit 27afda74f1
21 changed files with 1726 additions and 11 deletions

View File

@@ -3,11 +3,12 @@
import { displayName } from '$lib/stores/auth';
import { currentCollective, userCollectives } from '$lib/stores/collective';
import { enabledSections } from '$lib/stores/features';
import { isServerAdmin } from '$lib/stores/serverAdmin';
import type { SectionKey } from '@colectivo/types';
import Avatar from '$lib/components/Avatar.svelte';
import CreateCollectiveModal from '$lib/components/CreateCollectiveModal.svelte';
import * as m from '$lib/paraglide/messages';
import { ShoppingCart, CheckSquare, FileText, Search, Settings, Plus } from 'lucide-svelte';
import { ShoppingCart, CheckSquare, FileText, Search, Settings, Plus, Shield } from 'lucide-svelte';
// Fase 12.3.1: nav items declared with their section key so we can filter
// by $enabledSections (precedence resolved client-side; see features.ts).
@@ -100,6 +101,18 @@
</nav>
<div class="p-3 pt-2">
{#if $isServerAdmin}
<!-- Fase 13.4: server-admin entry. Distinct red icon so it doesn't
blend with normal app nav. Hidden for non-admins. -->
<a
href="/admin"
data-testid="sidebar-admin-link"
class="mb-2 flex items-center gap-2 rounded-md border border-red-200 bg-red-50/50 px-3 py-2 text-sm font-medium text-red-700 hover:bg-red-50 dark:border-red-900/60 dark:bg-red-950/20 dark:text-red-300 dark:hover:bg-red-950/40"
>
<Shield size={14} strokeWidth={1.5} />
{m.admin_menu_entry()}
</a>
{/if}
<div class="flex items-center justify-between gap-2">
<div class="flex min-w-0 items-center gap-2">
<Avatar name={$displayName} size={32} />

View File

@@ -1,11 +1,12 @@
<script lang="ts">
import { currentCollective, userCollectives } from '$lib/stores/collective';
import { displayName } from '$lib/stores/auth';
import { isServerAdmin } from '$lib/stores/serverAdmin';
import Avatar from '$lib/components/Avatar.svelte';
import CreateCollectiveModal from '$lib/components/CreateCollectiveModal.svelte';
import { logout } from '$lib/auth';
import * as m from '$lib/paraglide/messages';
import { Settings, Users, LogOut, X, Plus } from 'lucide-svelte';
import { Settings, Users, LogOut, X, Plus, Shield } from 'lucide-svelte';
let showCreate = $state(false);
@@ -98,6 +99,18 @@
<Avatar name={$displayName} size={28} />
<span class="truncate text-sm font-medium text-text-primary">{$displayName}</span>
</div>
{#if $isServerAdmin}
<!-- Fase 13.4: server-admin entry. Same gating as DesktopSidebar. -->
<a
href="/admin"
onclick={close}
data-testid="drawer-admin-link"
class="flex items-center gap-2 rounded-md px-2 py-2 text-sm font-medium text-red-700 hover:bg-red-50 dark:text-red-300 dark:hover:bg-red-950/40"
>
<Shield size={14} strokeWidth={1.5} />
{m.admin_menu_entry()}
</a>
{/if}
<a
href="/settings"
onclick={close}

View File

@@ -42,26 +42,38 @@ import { currentCollective } from '$lib/stores/collective';
*/
export const currentUserFeatures = writable<{ feature_flags: FeatureFlags } | null>(null);
/**
* Server-layer overrides (Fase 13). Mirrors
* `public.server_settings.value WHERE key = 'default_sections'`. Loaded on
* sign-in and refreshed (no realtime — promote/revoke at this layer is rare
* and a reload is acceptable; a future migration can put server_settings in
* the realtime publication if needed).
*/
export const serverSectionDefaults = writable<FeatureFlags>({});
/**
* Derived map { section → boolean } applying the same precedence as
* `public.section_enabled()`. Layers, MOST restrictive wins:
* 1. collective.feature_flags[section] (admin override)
* 2. user.feature_flags[section] (per-user override)
* 3. default true
* 1. server.default_sections[section] (operator override)
* 2. collective.feature_flags[section] (admin override)
* 3. user.feature_flags[section] (per-user override)
* 4. default true
*
* Unknown section keys are not part of SECTION_KEYS so they are never queried
* here — that path is reserved for SQL-side callers (migrations 13+).
*/
export const enabledSections = derived(
[currentUserFeatures, currentCollective],
([$user, $collective]) => {
[currentUserFeatures, currentCollective, serverSectionDefaults],
([$user, $collective, $server]) => {
const userFlags = ($user?.feature_flags ?? {}) as FeatureFlags;
const collectiveFlags = ($collective?.feature_flags ?? {}) as FeatureFlags;
const serverFlags = ($server ?? {}) as FeatureFlags;
const out: Record<SectionKey, boolean> = {} as Record<SectionKey, boolean>;
for (const key of SECTION_KEYS) {
const serverVal = serverFlags[key];
const collectiveVal = collectiveFlags[key];
const userVal = userFlags[key];
out[key] = collectiveVal ?? userVal ?? true;
out[key] = serverVal ?? collectiveVal ?? userVal ?? true;
}
return out;
}
@@ -173,6 +185,20 @@ export async function loadCurrentUserFeatures(userId: string): Promise<void> {
feature_flags: ((data?.feature_flags ?? {}) as FeatureFlags) || {}
});
// Fase 13: also fetch the server-layer defaults. Read-allowed to everyone
// by `select_all` policy on server_settings. Failure is non-fatal — the
// derived store falls through to collective/user/default.
try {
const { data: ssRow } = await supabase
.from('server_settings')
.select('value')
.eq('key', 'default_sections')
.maybeSingle();
serverSectionDefaults.set(((ssRow?.value ?? {}) as FeatureFlags) || {});
} catch {
/* non-fatal */
}
if (userChannelUserId !== userId) {
await teardownUserChannel();
userChannelUserId = userId;
@@ -238,6 +264,7 @@ export async function teardownFeatureSubscriptions(): Promise<void> {
await teardownUserChannel();
await teardownCollectiveChannel();
currentUserFeatures.set(null);
serverSectionDefaults.set({});
}
async function teardownUserChannel(): Promise<void> {

View File

@@ -0,0 +1,57 @@
/**
* Server admin flag store (Fase 13.4).
*
* `is_server_admin()` is a cheap STABLE SECURITY DEFINER RPC; we cache its
* result client-side so the sidebar entry, route guards, and any other
* call-site can read `$isServerAdmin` synchronously without round-trip.
*
* Refresh hooks live in the root `+layout.svelte` — see the
* `onAuthStateChange` block where we re-run `refreshServerAdminFlag()` on
* INITIAL_SESSION / SIGNED_IN / TOKEN_REFRESHED. There is no realtime
* subscription: promote/revoke is rare and the flag stays accurate until the
* next token refresh (~1 hour) which is acceptable for an operator-facing
* surface. A user who is freshly granted can also just reload the page.
*/
import { writable } from 'svelte/store';
import { getSupabase } from '$lib/supabase';
export const isServerAdmin = writable<boolean>(false);
/**
* Has the flag been resolved at least once for the current session? Tracks
* the distinction between "definitely not admin" (false + loaded=true) and
* "we don't know yet" (false + loaded=false). The (admin) layout uses this
* to avoid redirecting away from /admin during the millisecond between the
* SIGNED_IN event firing and the RPC resolving. Without this guard, a hard
* navigation to /admin lands the user back at / every time.
*/
export const isServerAdminLoaded = writable<boolean>(false);
/**
* Re-read `is_server_admin()` and update the store. Call from the root layout
* after the auth listener fires so the flag follows the user's session.
*
* Defensive: any error (network, RLS, missing function on an older deploy)
* sets the flag to false rather than throwing — the admin area is gated by a
* second server-side check (the RPC guard), so a stale `false` is the safe
* default.
*/
export async function refreshServerAdminFlag(): Promise<void> {
try {
const { data, error } = await getSupabase().rpc('is_server_admin', {});
if (error) {
isServerAdmin.set(false);
return;
}
isServerAdmin.set(data === true);
} catch {
isServerAdmin.set(false);
} finally {
isServerAdminLoaded.set(true);
}
}
export function clearServerAdminFlag(): void {
isServerAdmin.set(false);
isServerAdminLoaded.set(false);
}