Files
route-commerce/src/lib/brand-scope.ts
T
tyler 63842a9efc 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
2026-06-04 17:09:40 +00:00

91 lines
3.2 KiB
TypeScript

/**
* 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");
}
}