'use client'; import * as React from 'react'; import { iam, iamBase, IamError, type IamAccount, type IamOrg, type IamProject, } from './iam'; import { useWhiteLabel } from './provider'; import type { WhiteLabel } from './white-label'; // Who is signed in, and what are they acting as. // // One context, read by every piece of chrome. Identity and org membership come // from IAM (see ./iam); brand, theme, issuer and IAM client come from the host // (see ./white-label). Nothing here is configured per deployment. // // The state is FOUR values, not a boolean, because a switcher renders each of // them differently and conflating them is how an app ends up showing an empty // account menu to a signed-out visitor: // // loading — the answer is on its way // anonymous — nobody is signed in; offer sign-in, never an empty list // ready — signed in; the lists are the real lists (possibly empty) // error — IAM could not be read; say so, never render "no organizations" export type IdentityStatus = 'loading' | 'anonymous' | 'ready' | 'error'; /** * How the chrome gets a bearer and moves the user in and out of a session. * * Credentials are `@hanzo/iam`'s job, not the design system's — so this is the * seam, and a surface using the SDK supplies only the two verbs: * * auth={{ signIn: () => void startLogin(), signOut: () => void logout() }} * * The bearer itself needs no wiring: the default reads the SDK's own token * store, so there is exactly one token and one refresh timer per surface. */ export interface IdentityAuth { /** The IAM access token. Defaults to the `@hanzo/iam` SDK's token store. */ readonly token?: () => string | null | Promise; /** Start a sign-in. */ readonly signIn?: () => void; /** End the session. */ readonly signOut?: () => void; } export interface Identity { readonly status: IdentityStatus; /** The signed-in principal, or null. */ readonly account: IamAccount | null; /** Organizations the principal can act in. */ readonly orgs: ReadonlyArray; /** The organization the surface is currently scoped to, or null. */ readonly org: IamOrg | null; /** Projects in the current organization. */ readonly projects: ReadonlyArray; /** The project the surface is currently scoped to, or null. */ readonly project: IamProject | null; /** Why the reads failed, when status is 'error'. */ readonly error: string | null; /** Host-resolved brand, theme, issuer and IAM client. */ readonly whiteLabel: WhiteLabel; readonly setOrg: (name: string) => void; readonly setProject: (name: string) => void; readonly signIn: () => void; readonly signOut: () => void; readonly reload: () => void; } // --- The default auth: the @hanzo/iam SDK's own token store ----------------- // `@hanzo/iam/browser` keeps its PKCE tokens under `hanzo_iam_*`. Reading that // key IS the integration — no second SDK instance, no duplicated refresh // timer, and a surface already using @hanzo/iam needs no wiring at all. const IAM_TOKEN_KEY = 'hanzo_iam_access_token'; function storedToken(): string | null { if (typeof window === 'undefined') return null; for (const store of [ window.sessionStorage, window.localStorage ]) { try { const t = store.getItem(IAM_TOKEN_KEY); if (t) return t; } catch { // Storage disabled (private mode / sandboxed frame) — treat as signed out. } } return null; } function clearStoredTokens(): void { if (typeof window === 'undefined') return; for (const store of [ window.sessionStorage, window.localStorage ]) { try { for (const k of [ 'access_token', 'refresh_token', 'id_token', 'expires_at' ]) { store.removeItem(`hanzo_iam_${ k }`); } } catch { // Nothing to clear. } } } const defaultAuth: IdentityAuth = {}; // --- Scope persistence ------------------------------------------------------ // Which org/project the user last acted in, per host, so a reload does not // silently move them somewhere else. const scopeKey = (host: string, kind: string) => `lux-ui:${ kind }:${ host }`; function readScope(host: string, kind: string): string | null { if (typeof window === 'undefined') return null; try { return window.localStorage.getItem(scopeKey(host, kind)); } catch { return null; } } function writeScope(host: string, kind: string, value: string): void { if (typeof window === 'undefined') return; try { window.localStorage.setItem(scopeKey(host, kind), value); } catch { // Selection stays live in-session; it just will not survive a reload. } } const IdentityContext = React.createContext(null); export interface IdentityProviderProps { readonly children: React.ReactNode; /** Bearer + sign-in/out. Defaults to the `@hanzo/iam` token store. */ readonly auth?: IdentityAuth; /** Where sign-in goes when `auth.signIn` is not supplied. */ readonly loginPath?: string; } export const IdentityProvider = ({ children, auth = defaultAuth, loginPath = '/login', }: IdentityProviderProps): React.ReactElement => { const whiteLabel = useWhiteLabel(); const base = React.useMemo(() => iamBase(whiteLabel), [ whiteLabel ]); const [ status, setStatus ] = React.useState('loading'); const [ account, setAccount ] = React.useState(null); const [ orgs, setOrgs ] = React.useState>([]); const [ projects, setProjects ] = React.useState>([]); const [ error, setError ] = React.useState(null); const [ orgName, setOrgName ] = React.useState(null); const [ projectName, setProjectName ] = React.useState(null); const [ epoch, setEpoch ] = React.useState(0); // Identity + org membership. React.useEffect(() => { const ac = new AbortController(); let live = true; void (async () => { const token = await (auth.token ?? storedToken)(); if (!live) return; if (!token) { setStatus('anonymous'); setAccount(null); setOrgs([]); return; } const call = { base, token, signal: ac.signal }; try { const me = await iam.account(call); if (!live) return; if (!me) { setStatus('anonymous'); setAccount(null); setOrgs([]); return; } setAccount(me); // A member who cannot list the tenant table still has their OWN org. // `get-organizations` is a super-admin read and answers 403 to everyone // else (measured on lux.id with a real z@lux.network bearer), so this is // the COMMON path, not an edge case: fall back to the org the account // itself names rather than showing an empty switcher — or, worse, // treating the refusal as "not signed in". const rows = await iam.organizations(call).catch((e: unknown) => { if (e instanceof IamError && !e.unauthenticated) return [ { owner: 'admin', name: me.owner } ]; throw e; }); if (!live) return; setOrgs(rows); setStatus('ready'); setError(null); } catch (e) { if (!live || ac.signal.aborted) return; if (e instanceof IamError && e.unauthenticated) { setStatus('anonymous'); setAccount(null); setOrgs([]); return; } setStatus('error'); setError(e instanceof Error ? e.message : 'Could not reach IAM.'); } })(); return () => { live = false; ac.abort(); }; }, [ base, auth, epoch ]); // The org the surface is scoped to: the persisted choice when it is still // one the user has, else the account's own org, else the first row. const org = React.useMemo(() => { if (orgs.length === 0) return null; const saved = orgName ?? readScope(whiteLabel.host, 'org'); return ( orgs.find((o) => o.name === saved) ?? orgs.find((o) => o.name === account?.owner) ?? orgs[0] ); }, [ orgs, orgName, account, whiteLabel.host ]); // Projects follow the org. A project read is allowed to fail without // downgrading the whole identity — the org switcher still works. React.useEffect(() => { if (!org) { setProjects([]); return; } const ac = new AbortController(); let live = true; void (async () => { const token = await (auth.token ?? storedToken)(); if (!live || !token) return; const rows = await iam .projects({ base, token, signal: ac.signal }, org.name) .catch(() => [] as Array); if (live) setProjects(rows); })(); return () => { live = false; ac.abort(); }; }, [ base, auth, org, epoch ]); const project = React.useMemo(() => { if (projects.length === 0) return null; const saved = projectName ?? readScope(whiteLabel.host, 'project'); return ( projects.find((p) => p.name === saved) ?? projects.find((p) => p.isDefault) ?? projects[0] ); }, [ projects, projectName, whiteLabel.host ]); const value = React.useMemo(() => ({ status, account, orgs, org, projects, project, error, whiteLabel, setOrg: (name: string) => { writeScope(whiteLabel.host, 'org', name); setOrgName(name); setProjectName(null); }, setProject: (name: string) => { writeScope(whiteLabel.host, 'project', name); setProjectName(name); }, signIn: () => { if (auth.signIn) return auth.signIn(); if (typeof window !== 'undefined') window.location.assign(loginPath); }, signOut: () => { if (auth.signOut) return auth.signOut(); clearStoredTokens(); if (typeof window !== 'undefined') window.location.assign(loginPath); }, reload: () => setEpoch((n) => n + 1), }), [ status, account, orgs, org, projects, project, error, whiteLabel, auth, loginPath ]); return { children }; }; /** * The current identity. * * Outside an `` this reports `anonymous` rather than * throwing: chrome that renders before a surface has wired identity should * offer sign-in, not crash the page. */ export function useIdentity(): Identity { const ctx = React.useContext(IdentityContext); const whiteLabel = useWhiteLabel(); const fallback = React.useMemo(() => ({ status: 'anonymous', account: null, orgs: [], org: null, projects: [], project: null, error: null, whiteLabel, setOrg: () => undefined, setProject: () => undefined, signIn: () => { if (typeof window !== 'undefined') window.location.assign('/login'); }, signOut: () => undefined, reload: () => undefined, }), [ whiteLabel ]); return ctx ?? fallback; }