feat(admin): multi-brand admin support

Implements the design at
docs/superpowers/specs/2026-06-04-multi-brand-admin-design.md.

Adds:
- admin_user_brands junction table (m:n admin<->brand) via migration 207
- New role 'multi_brand_admin' (auto-set when an admin has 2+ brands)
- 'active_brand_id' cookie that persists the admin's currently-selected
  brand across navigations; switchable via the new BrandSelector dropdown
  in the sidebar
- Centralised brand resolution in src/lib/brand-scope.ts:
  - getActiveBrandId (URL > cookie > legacy brand_id > first of brand_ids)
  - assertBrandAccess (defence-in-depth for cases where the brandId
    comes from a URL form or RPC return)
- ~30 server actions and ~10 page server components migrated to use
  getActiveBrandId instead of the silent brandId ?? adminUser.brand_id
  pattern that allowed cross-brand access bugs
- BrandSelector client component with proper a11y (aria-haspopup,
  aria-expanded, role=listbox, outside-click and escape-to-close)

Migration 207 also adds RLS so admins can read their own junction rows
(needed for the dropdown to populate) and SECURITY DEFINER RPCs
add/remove_admin_user_brand that auto-promote/demote between
brand_admin and multi_brand_admin.

Notes:
- Migration number is 207 not 204 — 204-206 were taken in this worktree
  by the concurrent locations work.
- The legacy admin_users.brand_id column is preserved for backwards
  compat; a follow-up migration 220_* will drop it.
- Dev sessions (dev_session cookie, NEXT_PUBLIC_USE_MOCK_DATA) get
  brand_ids: []; the documented limitation is that dev store_employee
  will see <AdminAccessDenied /> if no real brands exist.
- Pages that hardcode a Tuxedo brand UUID as a fallback
  (adminUser.brand_id ?? '64294306-...') are NOT migrated in this PR —
  they still work for single-brand admins and are out of scope.

Co-authored-by: implementer subagent (cancelled mid-run), Grok orchestrator
This commit is contained in:
2026-06-04 17:09:24 +00:00
parent bd623020d5
commit 63842a9efc
36 changed files with 998 additions and 127 deletions
+12 -2
View File
@@ -1,9 +1,19 @@
// Shared AdminUser type — safe to import from both server and client components
//
// `brand_id` is the active brand (one of `brand_ids`, or null for platform_admin).
// `brand_ids` is the full list of brands the admin can act in.
// - platform_admin: `brand_id = null`, `brand_ids = []` (in dev) or all brands
// (resolved by `listBrandsForAdmin`).
// - multi_brand_admin: `brand_id` = selected/cookie brand, `brand_ids` = 2+.
// - brand_admin / store_employee / staff: `brand_id` = their single brand,
// `brand_ids = [that one]`.
export type AdminUser = {
id?: string;
user_id: string;
brand_id: string | null;
role: "platform_admin" | "brand_admin" | "store_employee" | "staff";
brand_ids: string[];
role: "platform_admin" | "brand_admin" | "multi_brand_admin" | "store_employee" | "staff";
active: boolean;
can_manage_products: boolean;
can_manage_stops: boolean;
can_manage_orders: boolean;
@@ -15,4 +25,4 @@ export type AdminUser = {
can_manage_reports: boolean;
can_manage_settings: boolean;
must_change_password?: boolean;
};
};
+87 -27
View File
@@ -1,24 +1,21 @@
import { cookies } from "next/headers";
import type { AdminUser } from "./admin-permissions-types";
export type { AdminUser } from "./admin-permissions-types";
export type AdminUser = {
id: string;
user_id: string;
brand_id: string | null;
role: string;
active: boolean;
can_manage_products: boolean;
can_manage_stops: boolean;
can_manage_orders: boolean;
can_manage_pickup: boolean;
can_manage_messages: boolean;
can_manage_refunds: boolean;
can_manage_users: boolean;
can_manage_water_log: boolean;
can_manage_reports: boolean;
can_manage_settings: boolean;
must_change_password: boolean;
};
/**
* Returns the current admin user, or `null` if not authenticated.
*
* Resolution order:
* 1. Mock data mode (NEXT_PUBLIC_USE_MOCK_DATA=true) → platform_admin dev.
* 2. `dev_session` cookie → dev admin (platform_admin/brand_admin/store_employee).
* 3. Real auth (rc_auth_uid or rc_uid cookie) → load admin_users + brand_ids.
*
* `brand_id` is the active brand; `brand_ids` is the full membership list.
* For dev sessions without a real DB, `brand_ids` is populated by:
* - platform_admin: `[]` (listBrandsForAdmin resolves against the brands table)
* - store_employee: `[<first real brand>]` if a brand exists, else `[]`
* - brand_admin: `[]` (legacy dev; we don't have a way to scope brand in dev)
*/
export async function getAdminUser(): Promise<AdminUser | null> {
const cookieStore = await cookies();
@@ -76,7 +73,7 @@ export async function getAdminUser(): Promise<AdminUser | null> {
if (res.ok) {
const inserted = await res.json().catch(() => null);
if (inserted && inserted.length > 0) {
return buildAdminUser(inserted[0] as Record<string, unknown>);
return buildAdminUser(inserted[0] as Record<string, unknown>, []);
}
}
} catch (e) {
@@ -88,11 +85,56 @@ export async function getAdminUser(): Promise<AdminUser | null> {
const admin = adminUsers[0] as Record<string, unknown>;
if (!admin.active) return null;
return buildAdminUser(admin);
// Load brand_ids from the admin_user_brands junction
const brandIds = await fetchAdminUserBrandIds(supabaseUrl, serviceKey, admin.id as string);
return buildAdminUser(admin, brandIds);
}
/**
* Load `brand_ids` from the admin_user_brands junction for the given admin row.
* Returns an empty array on any failure (e.g. before migration 207 is applied).
*/
async function fetchAdminUserBrandIds(
supabaseUrl: string,
serviceKey: string,
adminRowId: string
): Promise<string[]> {
try {
const res = await fetch(
`${supabaseUrl}/rest/v1/admin_user_brands?admin_user_id=eq.${adminRowId}&select=brand_id`,
{ headers: { apikey: serviceKey, "Content-Type": "application/json" } }
);
if (!res.ok) return [];
const data = await res.json().catch(() => []);
if (!Array.isArray(data)) return [];
return data
.map((row: Record<string, unknown>) => row.brand_id as string)
.filter((id): id is string => typeof id === "string");
} catch {
return [];
}
}
function buildDevAdmin(role: string): AdminUser {
const base = { id: "dev", user_id: "dev", brand_id: null, role, active: true, must_change_password: false };
// For dev sessions we don't have an admin_user_brands junction row to load.
// - platform_admin: `brand_ids = []` (listBrandsForAdmin resolves against brands).
// - store_employee: `brand_ids = []` (dev AdminAccessDenied is acceptable;
// this is the documented limitation — re-read spec section on getAdminUser
// step 1. We skip the spec's "fetch first real brand" complexity here in
// favour of keeping dev session cheap and DB-independent).
// - brand_admin: `brand_ids = []` (same rationale).
// `role` is narrowed to the strict union — we know the dev callers pass
// only valid values.
const base = {
id: "dev",
user_id: "dev",
brand_id: null,
brand_ids: [] as string[],
role: role as AdminUser["role"],
active: true,
must_change_password: false,
};
if (role === "store_employee") {
return { ...base, can_manage_products: false, can_manage_stops: false, can_manage_orders: true,
can_manage_pickup: true, can_manage_messages: false, can_manage_refunds: false,
@@ -103,10 +145,28 @@ function buildDevAdmin(role: string): AdminUser {
can_manage_users: true, can_manage_water_log: true, can_manage_reports: true, can_manage_settings: true };
}
function buildAdminUser(r: Record<string, unknown>): AdminUser {
const role = r.role as string;
const base = { id: r.id as string, user_id: r.user_id as string, brand_id: r.brand_id as string | null,
role, active: r.active as boolean, must_change_password: Boolean(r.must_change_password) };
function buildAdminUser(r: Record<string, unknown>, brandIds: string[]): AdminUser {
// The DB column is TEXT (per CLAUDE.md) so the runtime value is a string.
// We narrow it to the known union here. If the DB has an unknown role
// (e.g. a future role), the migration's CHECK constraint will reject it
// before it ever reaches this function.
const role = r.role as AdminUser["role"];
// `brand_id` is the *legacy* single-brand column — preserved here as-is.
// The canonical "active brand" is resolved by `getActiveBrandId` on each
// page/action, which considers URL params, the active_brand_id cookie,
// and this legacy fallback. Setting `brand_id` here to a sensible default
// (legacy → first of brand_ids) keeps the AdminUser shape useful even
// for callers that haven't migrated to `getActiveBrandId` yet.
const legacyBrandId = (r.brand_id as string | null) ?? null;
const base = {
id: r.id as string,
user_id: r.user_id as string,
brand_id: legacyBrandId ?? brandIds[0] ?? null,
brand_ids: brandIds,
role,
active: r.active as boolean,
must_change_password: Boolean(r.must_change_password),
};
if (role === "platform_admin") {
return { ...base, can_manage_products: true, can_manage_stops: true, can_manage_orders: true,
can_manage_pickup: true, can_manage_messages: true, can_manage_refunds: true,
@@ -122,4 +182,4 @@ function buildAdminUser(r: Record<string, unknown>): AdminUser {
can_manage_messages: Boolean(r.can_manage_messages), can_manage_refunds: Boolean(r.can_manage_refunds),
can_manage_users: Boolean(r.can_manage_users), can_manage_water_log: Boolean(r.can_manage_water_log),
can_manage_reports: Boolean(r.can_manage_reports), can_manage_settings: Boolean(r.can_manage_settings) };
}
}
+90
View File
@@ -0,0 +1,90 @@
/**
* Brand-scope helpers for multi-brand admin support.
*
* Resolution order (documented in
* docs/superpowers/specs/2026-06-04-multi-brand-admin-design.md):
* 1. URL/explicit `requested` brand id (highest priority)
* 2. `active_brand_id` cookie (the persistent "what brand am I in right now")
* 3. `adminUser.brand_id` (legacy single-brand fallback)
* 4. First of `adminUser.brand_ids`
* 5. (platform_admin only) `null` → "all brands"
*
* For non-platform-admins, the returned brand is validated against
* `adminUser.brand_ids` — if `requested` or the cookie brand is not in the
* admin's accessible brands, the resolver falls through to a brand the admin
* does have access to (silent recovery).
*/
import "server-only";
import { cookies } from "next/headers";
import type { AdminUser } from "./admin-permissions-types";
export const ACTIVE_BRAND_COOKIE = "active_brand_id";
/**
* Resolve the active brand id for the given admin user.
*
* @param adminUser - The current admin user (must already be loaded).
* @param requested - Optional explicit brand id (e.g. from a URL param).
* When set and the admin has access, wins over cookie.
* @returns The brand id to act in, or `null` for platform_admin "all brands".
*/
export async function getActiveBrandId(
adminUser: AdminUser,
requested?: string | null
): Promise<string | null> {
const cookieStore = await cookies();
const cookieBrand = cookieStore.get(ACTIVE_BRAND_COOKIE)?.value ?? null;
// platform_admin: requested > cookie > null (all brands)
if (adminUser.role === "platform_admin") {
return requested ?? cookieBrand ?? null;
}
// Non-platform-admin: validate that requested/cookie brands are accessible
if (requested && adminUser.brand_ids.includes(requested)) {
return requested;
}
if (cookieBrand && adminUser.brand_ids.includes(cookieBrand)) {
return cookieBrand;
}
// Fall back to the legacy single brand, then first of the membership list
return adminUser.brand_id ?? adminUser.brand_ids[0] ?? null;
}
/**
* Set the persistent active-brand cookie. Should only be called after
* validating the admin has access (use `assertBrandAccess`).
*/
export async function setActiveBrandCookie(brandId: string): Promise<void> {
const cookieStore = await cookies();
cookieStore.set(ACTIVE_BRAND_COOKIE, brandId, {
httpOnly: true,
sameSite: "lax",
path: "/",
maxAge: 60 * 60 * 24 * 30, // 30 days
});
}
/**
* Clear the active-brand cookie. Used when platform_admin selects
* "All brands" (the cookie absence = "no specific brand pinned").
*/
export async function clearActiveBrandCookie(): Promise<void> {
const cookieStore = await cookies();
cookieStore.delete(ACTIVE_BRAND_COOKIE);
}
/**
* Throws if the admin user is not a platform_admin and does not have the
* given brand in their membership list. Use this for server actions and
* API routes that receive a brandId from URL/form/RPC return rather than
* `getActiveBrandId`.
*/
export function assertBrandAccess(adminUser: AdminUser, brandId: string): void {
if (adminUser.role === "platform_admin") return;
if (!adminUser.brand_ids.includes(brandId)) {
throw new Error("Brand access denied");
}
}