// Hanzo IAM read surface — the ONE identity source every Lux surface reads. // // Who am I, which orgs am I in, which projects does this org have. Every // surface needs those three answers and every surface had grown its own way to // get them (a hardcoded ORGS table here, a bespoke token store there, a // per-app `/branding` map somewhere else). They are IAM's answers, so they are // read from IAM. // // The endpoints are the Casdoor-compat verbs IAM opens to a registered browser // origin (see hanzoai/iam internal/cors: get-account, get-organizations, // get-organization, get-users, get-organization-projects). CORS decides which // ORIGIN may read; the bearer decides WHO — a caller only ever sees what its // own principal could already see, so there is nothing to gate here. // // VALUES ONLY: no React, no storage policy, no redirect. `fetch` is the single // effect, and the base URL comes from the host-resolved white-label, so this // module is identical on the server, in the browser and in a test. import { resolveWhiteLabel, type WhiteLabel } from './white-label'; /** A signed-in principal, as IAM describes it. */ export interface IamAccount { readonly owner: string; readonly name: string; readonly displayName?: string; readonly email?: string; readonly avatar?: string; readonly isAdmin?: boolean; } /** An organization the principal can see. */ export interface IamOrg { readonly owner: string; readonly name: string; readonly displayName?: string; readonly logo?: string; } /** A project inside an organization (IAM's Org → Workspace → Project tier). */ export interface IamProject { readonly owner: string; readonly name: string; readonly displayName?: string; readonly organization?: string; readonly workspace?: string; readonly isDefault?: boolean; } /** IAM's response envelope. `data2` carries the total for paged reads. */ interface Envelope { readonly status?: string; readonly msg?: string; readonly data?: T; readonly data2?: unknown; } /** * A refusal from IAM, carrying enough to tell "not signed in" apart from * "signed in, and the answer is genuinely empty" — the distinction a switcher * has to render honestly. */ export class IamError extends Error { readonly status: number; readonly unauthenticated: boolean; constructor(message: string, status: number, unauthenticated: boolean) { super(message); this.name = 'IamError'; this.status = status; this.unauthenticated = unauthenticated; } } /** * "No session" — as opposed to "a session that may not do this". * * IAM says it two ways: 401, and (measured against lux.id) HTTP **200** with * `{"status":"error","msg":"please sign in first"}`, which is what both a * missing and a malformed bearer get. So the message has to be read, not just * the status. * * 403 is deliberately NOT here. `get-organizations` answers 403 to an ordinary * signed-in user — listing the tenant table is a super-admin read — and folding * that into "signed out" logged the user out of the chrome: get-account had * already succeeded, then the org read's 403 wiped the account and every * switcher offered "Sign in" to somebody who was signed in. Forbidden means * signed in and not allowed; the caller falls back to the org it can see. */ const SIGNED_OUT = /please sign in|authentication required|unauthorized/i; function isSignedOut(status: number, msg: string): boolean { return status === 401 || SIGNED_OUT.test(msg); } /** The IAM API root for a host — `lux.cloud` → `https://lux.id/v1/iam`. */ export function iamBase(host?: string | null | WhiteLabel): string { const wl = typeof host === 'object' && host !== null ? host : resolveWhiteLabel(host as string | null | undefined); return `${ wl.issuer }/v1/iam`; } /** How a read reaches IAM: where, and with whose bearer. */ export interface IamCall { readonly base: string; readonly token?: string | null; readonly signal?: AbortSignal; } async function read(call: IamCall, verb: string, params: Record): Promise { const url = new URL(`${ call.base }/${ verb }`); for (const [ k, v ] of Object.entries(params)) url.searchParams.set(k, String(v)); let res: Response; try { res = await fetch(url.toString(), { method: 'GET', // The bearer is the whole credential. IAM does not allow credentialed // CORS, so sending cookies would only get the response blocked. headers: call.token ? { Authorization: `Bearer ${ call.token }` } : {}, signal: call.signal, }); } catch (e) { // A network/CORS failure is NOT "no orgs" — say so, so the caller can show // an error instead of an empty switcher. throw new IamError(e instanceof Error ? e.message : 'IAM unreachable', 0, false); } const body = (await res.json().catch(() => ({}))) as Envelope; const msg = typeof body.msg === 'string' ? body.msg : ''; if (!res.ok || body.status === 'error') { throw new IamError(msg || `IAM ${ verb } failed (${ res.status })`, res.status, isSignedOut(res.status, msg)); } return body.data as T; } /** Rows per page for the org list — small first paint, more on demand. */ export const IAM_PAGE_SIZE = 20; export const iam = { /** The signed-in principal, or null when there is no session. */ async account(call: IamCall): Promise { try { const data = await read(call, 'get-account', {}); return data && data.name ? data : null; } catch (e) { if (e instanceof IamError && e.unauthenticated) return null; throw e; } }, /** * One page of the orgs the principal can see. IAM scopes the read to the * caller's authority, so a normal member gets their own org and a super * admin gets the tenant list — the page never has to decide. */ async organizations(call: IamCall, page = 0, query = '', pageSize = IAM_PAGE_SIZE): Promise> { const params: Record = { owner: 'admin', // IAM orgs live under the reserved `admin` owner p: page + 1, // the backend page is 1-based pageSize, sortField: 'name', sortOrder: 'ascending', }; const q = query.trim(); if (q) { params.field = 'name'; params.value = q; } return (await read | null>(call, 'get-organizations', params)) ?? []; }, /** One organization by name. */ async organization(call: IamCall, name: string): Promise { return (await read(call, 'get-organization', { id: `admin/${ name }` })) ?? null; }, /** Members of an organization. */ async users(call: IamCall, org: string): Promise> { return (await read | null>(call, 'get-users', { owner: org })) ?? []; }, /** The organization's projects — IAM keys this read by `organization`. */ async projects(call: IamCall, org: string): Promise> { return (await read | null>(call, 'get-organization-projects', { organization: org })) ?? []; }, };