Phase 5: platform feature-flags CRUD, impersonation, billing catalogue
Three new platform screens on top of the Phase 1-4 work. Feature flags (/feature-flags) — platform-wide flag registry. New route + lib/arcadia/feature-flags.ts, capability platform.feature_flags, nav under Automation. List/create/edit/delete with a per-row default toggle; pairs with the Phase-4 per-tenant override tab. Impersonation — "Impersonate" action on active users. Entirely client-side token swap in session.ts (beginImpersonation parks the operator's session + API token and swaps to the impersonation token; endImpersonation restores it), with a sticky "Viewing as <email> — Stop" banner in the shell driven by the JWT's impersonated_by claim. Stop is client-side because the impersonation token carries the target's roles and can't reach the admin-gated /stop endpoint; impersonation is stateless JWT so restoring the parked token is sufficient. Billing (/billing) — replaced the coming-soon stub with the real plan catalogue from GET /billing/plans (lib/arcadia/billing.ts). Per-tenant plan assignment stays on the tenant detail page; Entitlements + Apps remain honestly marked "Soon". Verified in-browser with real backend; typecheck adds zero errors (36→36). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
26
app/lib/arcadia/billing.ts
Normal file
26
app/lib/arcadia/billing.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
// Billing — the plan catalogue (what plans tenants can be on). Per-tenant plan
|
||||
// assignment lives on the tenant detail page; this is the platform-level view
|
||||
// of what's on offer. Backend: /api/v1/billing/plans.
|
||||
|
||||
import type { ArcadiaClient } from "@crema/arcadia-core-client"
|
||||
|
||||
export interface PlanMeter {
|
||||
meter_key: string
|
||||
included_units: number | null
|
||||
overage_price_cents: number | null
|
||||
}
|
||||
|
||||
export interface Plan {
|
||||
name: string
|
||||
slug: string
|
||||
description: string | null
|
||||
meters: PlanMeter[]
|
||||
pricing: unknown[]
|
||||
billing_track: string
|
||||
trial_days: number
|
||||
}
|
||||
|
||||
export async function listPlans(arcadia: ArcadiaClient): Promise<Plan[]> {
|
||||
const res = await arcadia.GET<{ data: Plan[] }>("/api/v1/billing/plans")
|
||||
return res.data
|
||||
}
|
||||
51
app/lib/arcadia/feature-flags.ts
Normal file
51
app/lib/arcadia/feature-flags.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
// Platform-wide feature flags — the registry of flags that exist across the
|
||||
// whole deployment. A tenant then overrides any of these under its detail page
|
||||
// (see tenant-detail/feature-flags-tab). Backend: /api/v1/admin/feature-flags
|
||||
// (platform_admin only).
|
||||
|
||||
import type { ArcadiaClient } from "@crema/arcadia-core-client"
|
||||
|
||||
export interface PlatformFlag {
|
||||
id: string
|
||||
key: string
|
||||
description: string | null
|
||||
enabled_by_default: boolean
|
||||
inserted_at?: string
|
||||
updated_at?: string
|
||||
}
|
||||
|
||||
export type PlatformFlagInput = {
|
||||
key?: string
|
||||
description?: string | null
|
||||
enabled_by_default?: boolean
|
||||
}
|
||||
|
||||
export async function listPlatformFlags(arcadia: ArcadiaClient): Promise<PlatformFlag[]> {
|
||||
const res = await arcadia.GET<{ data: PlatformFlag[] }>("/api/v1/admin/feature-flags")
|
||||
return res.data
|
||||
}
|
||||
|
||||
export async function createPlatformFlag(
|
||||
arcadia: ArcadiaClient,
|
||||
input: PlatformFlagInput,
|
||||
): Promise<PlatformFlag> {
|
||||
const res = await arcadia.POST<{ data: PlatformFlag }>("/api/v1/admin/feature-flags", {
|
||||
body: { flag: input },
|
||||
})
|
||||
return res.data
|
||||
}
|
||||
|
||||
export async function updatePlatformFlag(
|
||||
arcadia: ArcadiaClient,
|
||||
id: string,
|
||||
input: PlatformFlagInput,
|
||||
): Promise<PlatformFlag> {
|
||||
const res = await arcadia.PUT<{ data: PlatformFlag }>(`/api/v1/admin/feature-flags/${id}`, {
|
||||
body: { flag: input },
|
||||
})
|
||||
return res.data
|
||||
}
|
||||
|
||||
export async function deletePlatformFlag(arcadia: ArcadiaClient, id: string): Promise<void> {
|
||||
await arcadia.DELETE(`/api/v1/admin/feature-flags/${id}`)
|
||||
}
|
||||
@@ -109,3 +109,41 @@ export async function setUserStatus(
|
||||
): Promise<User> {
|
||||
return updateUser(arcadia, id, { status })
|
||||
}
|
||||
|
||||
// --- Impersonation ---
|
||||
// The operator (platform/tenant admin) can act as another user for support.
|
||||
// `startImpersonation` returns a token scoped to the target; the client swaps
|
||||
// to it (see session.beginImpersonation). Stopping is a client-side restore of
|
||||
// the operator's parked session — the /stop endpoint can't be reached with the
|
||||
// impersonation token (it lacks admin), so we don't rely on it.
|
||||
|
||||
export interface CanImpersonate {
|
||||
can_impersonate: boolean
|
||||
user: Pick<User, "id" | "email" | "status"> & { first_name?: string; last_name?: string }
|
||||
}
|
||||
|
||||
export interface ImpersonationToken {
|
||||
access_token: string
|
||||
impersonated_by: string
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
export async function canImpersonate(
|
||||
arcadia: ArcadiaClient,
|
||||
userId: string,
|
||||
): Promise<CanImpersonate> {
|
||||
const res = await arcadia.GET<{ data: CanImpersonate }>(
|
||||
`/api/v1/admin/impersonate/${userId}/can-impersonate`,
|
||||
)
|
||||
return res.data
|
||||
}
|
||||
|
||||
export async function startImpersonation(
|
||||
arcadia: ArcadiaClient,
|
||||
userId: string,
|
||||
): Promise<ImpersonationToken> {
|
||||
const res = await arcadia.POST<{ data: ImpersonationToken }>(
|
||||
`/api/v1/admin/impersonate/${userId}`,
|
||||
)
|
||||
return res.data
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ export type Capability =
|
||||
| "platform.search"
|
||||
| "platform.ai"
|
||||
| "platform.integrations" // external-API registry (keys/budgets) on the gateway
|
||||
| "platform.feature_flags"
|
||||
// Special — always-on; not gated.
|
||||
| "always.assistant"
|
||||
| "always.profile"
|
||||
@@ -84,6 +85,7 @@ const PLATFORM_ADMIN_CAPS: Capability[] = [
|
||||
"platform.search",
|
||||
"platform.ai",
|
||||
"platform.integrations",
|
||||
"platform.feature_flags",
|
||||
]
|
||||
|
||||
const ALWAYS_CAPS: Capability[] = ["always.assistant", "always.profile"]
|
||||
@@ -135,6 +137,7 @@ export const ROUTE_CAPABILITY: Record<string, Capability> = {
|
||||
"/search": "platform.search",
|
||||
"/ai": "platform.ai",
|
||||
"/integrations": "platform.integrations",
|
||||
"/feature-flags": "platform.feature_flags",
|
||||
|
||||
"/assistant": "always.assistant",
|
||||
"/profile": "always.profile",
|
||||
|
||||
@@ -27,9 +27,16 @@ export type Session = {
|
||||
tenantSlug?: string
|
||||
roles: string[]
|
||||
availableTenants: AvailableTenant[]
|
||||
// Set (to the operator's user id) when this session is an impersonation —
|
||||
// derived from the JWT's `impersonated_by` claim. Drives the "Viewing as"
|
||||
// banner and gates the normal identity chrome.
|
||||
impersonatedBy?: string
|
||||
}
|
||||
|
||||
const STORAGE_KEY = "crema.session"
|
||||
// Where the operator's real session is parked while they impersonate someone,
|
||||
// so Stop can restore it without another round-trip.
|
||||
const IMPERSONATION_BACKUP_KEY = "crema.session.impersonation-backup"
|
||||
const CHANGE_EVENT = "crema:session-change"
|
||||
|
||||
function readFromStorage(): Session | null {
|
||||
@@ -66,6 +73,8 @@ function readFromStorage(): Session | null {
|
||||
!!t && typeof (t as AvailableTenant).id === "string",
|
||||
) as AvailableTenant[])
|
||||
: [],
|
||||
impersonatedBy:
|
||||
typeof parsed.impersonatedBy === "string" ? parsed.impersonatedBy : undefined,
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
@@ -157,6 +166,90 @@ export function hasSession(): boolean {
|
||||
return !!readFromStorage()
|
||||
}
|
||||
|
||||
/** Build a Session from a bare access token (used for impersonation, where the
|
||||
* server hands back a token but no user record — identity comes from the
|
||||
* token's own claims). */
|
||||
function sessionFromToken(token: string, fallbackEmail = "impersonated user"): Session {
|
||||
const claims = decodeJwt(token) ?? {}
|
||||
const email = typeof claims.email === "string" ? claims.email : fallbackEmail
|
||||
// `sub` is "<user_id>:<tenant_id>" — take the user id.
|
||||
const sub = typeof claims.sub === "string" ? claims.sub.split(":")[0] : ""
|
||||
const availableTenants: AvailableTenant[] = Array.isArray(claims.available_tenants)
|
||||
? (claims.available_tenants as AvailableTenantClaim[])
|
||||
.filter((t) => t && typeof t.id === "string")
|
||||
.map((t) => ({ id: t.id as string, slug: t.slug, name: t.name, roles: t.roles ?? [] }))
|
||||
: []
|
||||
return {
|
||||
userId: (typeof claims.sub === "string" ? sub : "") || email,
|
||||
name: email,
|
||||
email,
|
||||
token,
|
||||
issuedAt: Date.now(),
|
||||
tenantId: typeof claims.tenant_id === "string" ? claims.tenant_id : undefined,
|
||||
tenantSlug: typeof claims.tenant_slug === "string" ? claims.tenant_slug : undefined,
|
||||
roles: Array.isArray(claims.roles) ? (claims.roles as string[]) : [],
|
||||
availableTenants,
|
||||
impersonatedBy:
|
||||
typeof claims.impersonated_by === "string" ? claims.impersonated_by : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enter impersonation: park the operator's real session, then swap the active
|
||||
* session + token to the impersonation token the server minted. Every
|
||||
* subsequent request acts as the target user.
|
||||
*/
|
||||
export function beginImpersonation(impersonationToken: string): Session | null {
|
||||
if (typeof window === "undefined") return null
|
||||
const current = readFromStorage()
|
||||
if (!current) return null
|
||||
|
||||
// Back up the operator's real session + API token so Stop can restore both.
|
||||
const currentApiToken = sessionStorage.getItem("arcadia_access_token")
|
||||
localStorage.setItem(
|
||||
IMPERSONATION_BACKUP_KEY,
|
||||
JSON.stringify({ session: current, apiToken: currentApiToken }),
|
||||
)
|
||||
|
||||
const next = sessionFromToken(impersonationToken, current.email)
|
||||
sessionStorage.setItem("arcadia_access_token", impersonationToken)
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(next))
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
return next
|
||||
}
|
||||
|
||||
/** True when an impersonation backup is parked (i.e. we can Stop). */
|
||||
export function isImpersonating(): boolean {
|
||||
if (typeof window === "undefined") return false
|
||||
return !!localStorage.getItem(IMPERSONATION_BACKUP_KEY)
|
||||
}
|
||||
|
||||
/**
|
||||
* Leave impersonation: restore the operator's parked session + API token.
|
||||
* Impersonation is stateless (just which token the client sends), so this is a
|
||||
* pure client-side restore — no server round-trip needed.
|
||||
*/
|
||||
export function endImpersonation(): Session | null {
|
||||
if (typeof window === "undefined") return null
|
||||
const raw = localStorage.getItem(IMPERSONATION_BACKUP_KEY)
|
||||
if (!raw) return null
|
||||
try {
|
||||
const { session, apiToken } = JSON.parse(raw) as {
|
||||
session: Session
|
||||
apiToken: string | null
|
||||
}
|
||||
if (apiToken) sessionStorage.setItem("arcadia_access_token", apiToken)
|
||||
else sessionStorage.removeItem("arcadia_access_token")
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(session))
|
||||
localStorage.removeItem(IMPERSONATION_BACKUP_KEY)
|
||||
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
||||
return session
|
||||
} catch {
|
||||
localStorage.removeItem(IMPERSONATION_BACKUP_KEY)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// `useSyncExternalStore` demands a *referentially stable* snapshot: it must
|
||||
// return the identical object until the underlying value genuinely changes.
|
||||
// Keying the cache on the raw stored string gives us that for free — reparse
|
||||
|
||||
Reference in New Issue
Block a user