Add Roles & Admin/Super-Admin interface

Per organized-ideas.md §6: role assignment, account ban/unban/delete, and
direct Admin/Super-Admin CRUD of public catalog entries outside the
submission workflow.

Backend:
- list_users_for_admin(): Super-Admin-gated SECURITY DEFINER function
  joining profiles + auth.users (username, email, role, banned_until) —
  auth.users isn't exposed through PostgREST, so this is the only way to
  list accounts at all.
- New Edge Function admin-user-action (ban/unban/delete), using
  @supabase/server's `auth: 'user'` mode to verify the caller's JWT, then
  Supabase Auth's Admin API for the actual mutation. This is deliberately
  an Edge Function rather than a Postgres function like everything else in
  this codebase: touching auth.users needs the Admin API, the stable
  documented interface, not a direct write to a schema Supabase manages
  internally. Self-action guard; verify_jwt = true at the gateway on top of
  the function's own JWT verification.
- 5 new pgTAP tests (43/43 total) for list_users_for_admin (Super-Admin-only,
  even regular Admins get 42501).
- CatalogRepository gains admin* methods (direct edit of a public port/cable/
  device entry, plus adminUnpublish which flips is_public rather than
  deleting) — the update methods were already ownership-agnostic (RLS's
  is_admin() clause is what actually permits it), so these are thin aliases,
  not duplicated logic.

Frontend:
- authStore/AdminUserRepository: minimal role plumbing, shared UserRole type.
- adminUserStore + AdminUsersModal: list/role-dropdown/ban/unban/delete,
  gated to Super Admin only via a new "Manage Users" TopBar button.
- PortTypeManager/CableTypeManager/DevicePalette: built-in entries now show
  direct "Edit"/"Unpublish" for Admins (regular Admin included, per §6's
  capability table — not Super-Admin-exclusive) instead of "Suggest edit";
  unpublish reuses the review-queue's impact-check RPC before confirming.
- DeviceTemplateEditor gains an `adminMode` save path alongside its existing
  submissionMode/resubmitId ones.

Verified: tsc -b and oxlint clean; supabase db reset + 43/43 pgTAP tests
pass; confirmed both new privileged endpoints (the SQL function and the
Edge Function) actually work through the real REST API via live curl
calls — signup, email confirm, role promotion, ban/unban/delete round
trips, self-action guard, non-super-admin rejection, and verify_jwt=true
compatibility all exercised directly, not just asserted.
This commit is contained in:
2026-09-08 16:01:01 -05:00
parent 1f8d49345e
commit 4c45b5afa7
21 changed files with 804 additions and 51 deletions
+15
View File
@@ -431,3 +431,18 @@ enabled = true
# declarative_schema_path = "./schemas"
# JSON string passed through to pg-delta SQL formatting.
# format_options = "{\"keywordCase\":\"upper\",\"indent\":2,\"maxWidth\":80,\"commaStyle\":\"trailing\"}"
[functions.admin-user-action]
enabled = true
# This function expects a real signed-in user's JWT (auth: 'user' mode in
# index.ts already verifies it via project JWKS) — verify_jwt = true adds a
# cheap gateway-level rejection of missing/malformed tokens before the
# function even runs, on top of that.
verify_jwt = true
import_map = "./functions/admin-user-action/deno.json"
# Uncomment to specify a custom file path to the entrypoint.
# Supported file extensions are: .ts, .js, .mjs, .jsx, .tsx
entrypoint = "./functions/admin-user-action/index.ts"
# Specifies static files to be bundled with the function. Supports glob patterns.
# For example, if you want to serve static HTML pages in your function:
# static_files = [ "./functions/admin-user-action/*.html" ]
@@ -0,0 +1,3 @@
# Configuration for private npm package dependencies
# For more information on using private registries with Edge Functions, see:
# https://supabase.com/docs/guides/functions/import-maps#importing-from-private-registries
@@ -0,0 +1,6 @@
{
"imports": {
"@supabase/functions-js": "jsr:@supabase/functions-js@^2",
"@supabase/server": "npm:@supabase/server@^1"
}
}
@@ -0,0 +1,89 @@
// Ban/unban/delete a user account — organized-ideas.md §6, Super-Admin only.
//
// This has to be an Edge Function rather than a Postgres function (unlike
// list_users_for_admin or the other privileged functions in this codebase):
// touching auth.users needs Supabase Auth's Admin API (the stable,
// documented interface for account mutations), not a direct SQL write to
// a schema Supabase manages internally and doesn't guarantee stable
// across upgrades. Ban is reversible (banned_until, no data touched);
// delete cascades to profiles/diagrams via their existing FKs.
//
// To invoke locally (after `supabase start`), with a real user's access
// token in place of ACCESS_TOKEN:
// curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/admin-user-action' \
// --header 'apiKey: <anon key from `supabase status`>' \
// --header 'Authorization: Bearer ACCESS_TOKEN' \
// --header 'Content-Type: application/json' \
// --data '{"action":"ban","userId":"..."}'
import "@supabase/functions-js/edge-runtime.d.ts";
import { withSupabase } from "@supabase/server";
type Action = "ban" | "unban" | "delete";
interface RequestBody {
action: Action;
userId: string;
}
const VALID_ACTIONS: Action[] = ["ban", "unban", "delete"];
// ~100 years — Supabase Auth's own documented idiom for "indefinite ban"
// (there's no literal "forever" value); "none" is the matching unban value.
const PERMANENT_BAN_DURATION = "876000h";
export default {
fetch: withSupabase({ auth: "user" }, async (req, ctx) => {
const callerId = ctx.userClaims!.id;
// Confirm the caller is a Super Admin by reading their own profile
// through the user-scoped (RLS-respecting) client — this leans on the
// same "read your own row" policy every other profile read in the app
// uses, rather than trusting anything in the JWT itself (its `role`
// claim is just "authenticated", not this app's role column).
const { data: callerProfile, error: profileError } = await ctx.supabase
.from("profiles")
.select("role")
.eq("id", callerId)
.single();
if (profileError || callerProfile?.role !== "super_admin") {
return Response.json({ error: "Only a Super Admin can manage user accounts." }, { status: 403 });
}
let body: RequestBody;
try {
body = await req.json();
} catch {
return Response.json({ error: "Invalid request body." }, { status: 400 });
}
const { action, userId } = body;
if (typeof userId !== "string" || !userId || !VALID_ACTIONS.includes(action)) {
return Response.json({ error: "Request must include a valid action and userId." }, { status: 400 });
}
if (userId === callerId) {
return Response.json({ error: "You cannot perform this action on your own account." }, { status: 400 });
}
if (action === "ban") {
const { error } = await ctx.supabaseAdmin.auth.admin.updateUserById(userId, {
ban_duration: PERMANENT_BAN_DURATION,
});
if (error) return Response.json({ error: error.message }, { status: 500 });
} else if (action === "unban") {
const { error } = await ctx.supabaseAdmin.auth.admin.updateUserById(userId, { ban_duration: "none" });
if (error) return Response.json({ error: error.message }, { status: 500 });
} else {
// Cascades to profiles (and from there, diagrams/owned catalog
// entries) via their existing `on delete cascade` foreign keys —
// the frontend confirmation for this action says so explicitly,
// since it's the one irreversible option here.
const { error } = await ctx.supabaseAdmin.auth.admin.deleteUser(userId);
if (error) return Response.json({ error: error.message }, { status: 500 });
}
return Response.json({ success: true });
}),
};
@@ -0,0 +1,30 @@
-- Super-Admin user management (organized-ideas.md §6): "CRUD user accounts"
-- starts with being able to see them at all. auth.users isn't exposed
-- through PostgREST (by design — Supabase doesn't expose the `auth` schema
-- to the API), so this read-only, Super-Admin-gated function is the only
-- way the app can list users alongside their profile/ban status. The
-- mutations themselves (ban/unban/delete) go through a new Edge Function
-- instead of a SQL function here — those specifically need Supabase Auth's
-- Admin API (auth.admin.updateUserById/deleteUser), the stable, documented
-- interface for touching auth.users, rather than writing to that schema's
-- tables directly (undocumented, not guaranteed stable across upgrades).
create or replace function public.list_users_for_admin()
returns table(id uuid, username text, email text, role text, banned_until timestamptz, created_at timestamptz)
language plpgsql
stable
security definer
set search_path = public
as $$
begin
if not public.is_super_admin() then
raise exception 'insufficient_privilege' using errcode = '42501';
end if;
return query
select p.id, p.username, u.email::text, p.role, u.banned_until, p.created_at
from public.profiles p
join auth.users u on u.id = p.id
order by p.created_at desc;
end;
$$;
+42 -1
View File
@@ -25,7 +25,7 @@ begin;
create extension if not exists pgtap with schema extensions;
select plan(38);
select plan(43);
-- ----------------------------------------------------------------------
-- Fixtures (as postgres — RLS does not apply)
@@ -386,6 +386,47 @@ select is(
'carol (admin) can look up the submitter''s username for a submission she can review'
);
-- ----------------------------------------------------------------------
-- Admin user listing (organized-ideas.md §6: "CRUD user accounts" is
-- Super-Admin-only — even a regular Admin gets 42501 here, unlike the
-- Admin-gated functions above).
-- ----------------------------------------------------------------------
select set_config('request.jwt.claim.sub', '22222222-2222-2222-2222-222222222222', true);
select throws_ok(
$$ select * from public.list_users_for_admin() $$,
'42501'::char(5), null,
'bob (regular user) cannot list users'
);
select set_config('request.jwt.claim.sub', '33333333-3333-3333-3333-333333333333', true);
select throws_ok(
$$ select * from public.list_users_for_admin() $$,
'42501'::char(5), null,
'carol (admin, not super admin) cannot list users'
);
select set_config('request.jwt.claim.sub', '44444444-4444-4444-4444-444444444444', true);
select lives_ok(
$$ select * from public.list_users_for_admin() $$,
'dave (super admin) can list users'
);
select is(
(select role from public.list_users_for_admin() where username = 'alice'),
'admin',
'the listing reflects alice''s current role (promoted earlier in this test run)'
);
select is(
(select email from public.list_users_for_admin() where username = 'alice'),
'alice@example.com',
'the listing includes email, only readable via this Super-Admin-gated function (not directly through PostgREST)'
);
select * from finish();
rollback;