// --------------------------------------------------------------------------- // settings / settingsApi.ts — EXIT wave 2 (W2-8, contract Y4). // // `GET /api/v1/settings` and the four `/api/v1/admin/users` routes. // // ⛔ THE CLIENT HIDES; THE SERVER FORBIDS. Every admin control in this module is // also gated server-side, fail-closed, and Y4 has the gate PROVE it by having a // viewer try. Nothing here may be read as the enforcement — a hidden button is // a courtesy to the user, never a permission check ([[aios-permissioning]]). // // ⚠ TWO FAIL-CLOSED WRITE RULES FROM S1's Y4 AMENDMENT ARE MIRRORED IN THE UI, // so the user learns them from the form rather than from a 400: // 1. **`POST` on an existing username is 409** — `PATCH` is the update path. // The reason is a real defect, not style: `create_user` overwrites the // record with a fresh one, dropping `epoch` back to absent(0) and thereby // REVIVING every cookie minted before the last password rotation. // 2. **`modules: []` is REFUSED on write (400).** The READ semantic stays // "[] means unrestricted" (Y4 says do not fix it this wave) — which means // an admin unticking every box to lock an account down would grant it // EVERYTHING. These routes are the first UI-reachable writer of `modules` // in the product's history, so the footgun simply never gets built. // --------------------------------------------------------------------------- import { API_V1, CREDENTIALS, checkTenant, UNAUTHORIZED_EVENT } from "../apiContract"; export interface AdminUser { username: string; name: string; role: string; /** `'all'` or the granted team ids. */ bus: number[] | "all"; /** `'all'` or the granted registry keys. ⚠ `[]` READS as unrestricted. */ modules: string[] | "all"; active: boolean; epoch?: number; /** * ⭢ REQUESTED OF S1, ADDITIVE, NOT YET SERVED (wave 15). One sentence per * account for the list's Access column — "All 2 modules, 1 restricted" — * computed from `perms` server-side, because the alternative is one * `/perms` round trip per row to fill one cell. * * Absent is handled, not assumed: the column falls back to the legacy * `modules` grant, which is what governs an un-migrated record anyway. The * shape is `permsModel.accessSummary`'s output, so both ends say the same * sentence rather than two dialects of it. */ accessSummary?: string; } export interface SettingsPayload { freezeNotice?: FreezeNoticeState; user: { username: string; name: string; role: string }; scope: { bus: string[] | "all"; modules: string[] | "all"; /** C-PERM — the caller's OWN effective wall, read-only. Present since wave * 15. Read here so "Your access" can state what NARROWS this account, not * merely what it may open: a pane saying "All modules" while a permanent * filter halves somebody's book is how a user comes to believe the numbers * are wrong. Never enforcement — hidden fields are stripped from every wire * regardless, so a client ignoring this is narrowed anyway, never widened. */ perms?: Record; }; tenant?: Record; /** * Wave 19 (R3 / contract C2) — is this account the LOOPABLE PLATFORM ADMIN? * * ⛔ NOT `admin`, AND THE DISTINCTION IS THE WHOLE RULING. `admin` is * tenant-scoped: every tenant has them, and R3 says in as many words that a * tenant-scoped `is_admin` does NOT qualify for this. This flag comes from a * separate fail-closed server predicate (record flag AND `tenant == "loopable"`, * a double lock) and is true for exactly one account. * * ⚠ CHROME, NEVER THE WALL. It decides whether a rail entry is drawn. Every * route behind that entry 403s a non-platform-admin on its own, so a client * that forged this flag would reach a pane whose every fetch is refused. * Optional on purpose: a server that predates the field, or one that omits it, * reads as `false` — fail-closed by absence, like every other flag here. */ platformAdmin?: boolean; } export type ApiResult = | { ok: true; data: T } | { ok: false; status: number; message: string; code?: string }; export interface FreezeNoticeState { enabled: boolean; text: string; } export function getFreezeNotice(signal?: AbortSignal): Promise> { return call("/freeze-notice", { cache: "no-store", signal }); } async function call( path: string, init?: RequestInit & { body?: string } ): Promise> { try { const res = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, headers: init?.body ? { "Content-Type": "application/json" } : undefined, ...init, }); if (res.status === 204) return { ok: true, data: undefined as T }; let body: unknown = null; try { body = await res.json(); } catch { /* 204s and empty bodies are normal; a parse failure is not fatal here */ } if (!res.ok) { const err = (body as { error?: { message?: string; code?: string } } | null)?.error; // A 5xx message is never surfaced verbatim — a server stack trace behind // a login is still a leak. const message = res.status >= 500 ? "Something went wrong on our side. Try again in a moment." : err?.message || (res.status === 403 ? "Administrators only." : res.status === 409 ? "That username already exists. Edit the existing account instead." : "That change could not be saved."); const code = typeof err?.code === "string" ? err.code : undefined; return { ok: false, status: res.status, message, code }; } return { ok: true, data: body as T }; } catch { return { ok: false, status: 0, message: "The server could not be reached." }; } } export function getSettings(): Promise> { return call("/settings"); } // Keep this vocabulary aligned with usage_activity.KINDS. export const USAGE_KIND_LABELS = { mcp: "MCP", api: "API", sign_in: "Sign-ins", record_edit: "Record edits", field_edit: "Field edits", cell_edit: "Cell edits", view_edit: "View edits", ai_turn: "AI turns", } as const; export type UsageKind = keyof typeof USAGE_KIND_LABELS; export type UsageCounts = Partial>; export interface UsageSource { source: string; kinds: UsageKind[]; heldFrom: string; retention?: Record; status: "ok" | "partial" | "error"; error: { code: string; type: string; message: string } | null; limitations: Array<{ code: string; cause: string; week?: string; heldFrom?: string; lost?: number; limit?: number }>; total: number | null; } export interface UsageActivity { tenant: string; from: string; to: string; timezone: string; filters: { user: string | null; kind: UsageKind | null }; complete: boolean; total: number | null; availableTotal: number; byKind: UsageCounts; byUser: Array<{ user: string; byKind: UsageCounts }>; byDay: Array<{ day: string; byKind: UsageCounts }>; counts: Array<{ day: string; user: string; kind: UsageKind; count: number }>; sources: UsageSource[]; } export interface UsageMcpEvent { id: string; tool: string; action: string; outcome: string; code: string; time: string; user: string; database: string; keyId: string; keyLabel: string; } export interface UsageMcpActivity { tenant: string; from: string; to: string; timezone: string; filters: { user: string | null; tool: string | null }; asOf: string; limit: number; complete: boolean; total: number | null; byTool: Array<{ tool: string; total: number; byOutcome: Record }>; events: UsageMcpEvent[]; nextCursor: string | null; source: UsageSource; } export interface UsageActivityFilters { from: string; to: string; user?: string; kind?: UsageKind | ""; } async function readUsageActivity(path: string, query: URLSearchParams, signal: AbortSignal): Promise> { try { const response = await fetch(`${API_V1}${path}?${query}`, { credentials: CREDENTIALS, cache: "no-store", signal }); if (checkTenant(response)) return { ok: false, status: 403, message: "Reopen Settings to view usage." }; if (response.status === 401) window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); const body = await response.json().catch(() => null); if (!response.ok) return { ok: false, status: response.status, message: "Usage could not be loaded.", code: body?.error?.code }; if (!body || typeof body.tenant !== "string") return { ok: false, status: 0, message: "Usage could not be loaded." }; return { ok: true, data: body as T }; } catch { return { ok: false, status: 0, message: "Usage could not be loaded." }; } } export function getUsageActivity(filters: UsageActivityFilters, signal: AbortSignal): Promise> { const query = new URLSearchParams({ from: filters.from, to: filters.to }); if (filters.user) query.set("user", filters.user); if (filters.kind) query.set("kind", filters.kind); return readUsageActivity("/usage/activity", query, signal); } export function getUsageMcpActivity(filters: UsageActivityFilters, signal: AbortSignal, cursor?: string, tool?: string): Promise> { const query = new URLSearchParams({ from: filters.from, to: filters.to, limit: "100" }); if (filters.user) query.set("user", filters.user); if (tool) query.set("tool", tool); if (cursor) query.set("cursor", cursor); return readUsageActivity("/usage/activity/mcp", query, signal); } export const NOTIFICATIONS_SETTINGS_EVENT = "loopable:open-notifications-settings"; export function openNotificationSettings(): void { window.dispatchEvent(new Event(NOTIFICATIONS_SETTINGS_EVENT)); } export interface NotificationDestinationPick { slackChannels: string[]; email: string | null; inApp: boolean; webhooks: string[]; } export interface NotificationReadiness { available: boolean; reason: string | null; message: string; } export interface NotificationDelivery { state: "sent" | "refused"; reason: string | null; message?: string; at?: string; } /** Writes return stored fields without GET's label and readiness projection. */ export interface NotificationDestinationRow extends NotificationDestinationPick { kind: string; revision: number; delivery: Record; slackAutomations: Record; } export interface NotificationDestination extends NotificationDestinationRow { label: string; readiness: Record; } export type NotificationWebhookDestination = NotificationReadiness & { id: string; label: string; destination: string }; export interface NotificationDestinationsPayload { destinations: NotificationDestination[]; email: NotificationReadiness; inApp: NotificationReadiness & { configured: boolean; destination: string }; webhooks: { configured: boolean; destinations: NotificationWebhookDestination[]; reason?: string | null }; } export interface NotificationSlackChannel { channel: string; channelName: string; label: string; active: boolean; } export interface NotificationSlackChannelsPage { configured: boolean; channels: NotificationSlackChannel[]; nextCursor: string | null; } export function getNotificationDestinations( signal?: AbortSignal ): Promise> { return call("/notifications/destinations", { cache: "no-store", signal }); } export function getNotificationSlackChannels( after = "", signal?: AbortSignal ): Promise> { return call( `/notifications/slack-channels?limit=100&after=${encodeURIComponent(after)}`, { cache: "no-store", signal } ); } export function saveNotificationDestinations( kind: string, patch: Partial, signal?: AbortSignal ): Promise> { const body: Partial = { slackChannels: patch.slackChannels, email: patch.email }; // PATCH merges, so a kind the patch leaves undefined stays as saved. if (patch.inApp !== undefined) body.inApp = patch.inApp; if (patch.webhooks !== undefined) body.webhooks = patch.webhooks; return call(`/notifications/destinations/${encodeURIComponent(kind)}`, { method: "PATCH", body: JSON.stringify(body), signal, }); } export function listUsers(): Promise> { return call<{ users: AdminUser[] }>("/admin/users"); } /** ⚠ NO `bus` (wave 15, R1). The field still exists on the RECORD — `AdminUser` * keeps reading it through the strangler period — but nothing in this client * writes it any more, so the create payload does not name it. The route * defaults an absent `bus` to `"all"`, which is what this form always sent. */ export interface NewUser { username: string; name: string; role: string; modules: string[] | "all"; password: string; } export function createUser(u: NewUser): Promise> { return call("/admin/users", { method: "POST", body: JSON.stringify(u) }); } /** ⚠ `bus` is NOT patchable from this client any more (R1) — a form writes what * it edits, and once the migration converts `bus` into a permanent filter and * clears the field, an echoed value would put it back. */ export type UserPatch = Partial>; export function patchUser(username: string, patch: UserPatch): Promise> { return call(`/admin/users/${encodeURIComponent(username)}`, { method: "PATCH", body: JSON.stringify(patch), }); } /** ⚠ This BUMPS THE EPOCH, which revokes every outstanding session for that * account. That is the point of the route and the UI says so out loud — an * admin resetting a password should know the person is being signed out. */ export function setPassword(username: string, password: string): Promise> { return call(`/admin/users/${encodeURIComponent(username)}/password`, { method: "POST", body: JSON.stringify({ password }), }); } // --- wave 15, C-PERM: the per-module permission record ---------------------- // // ⛔ ADMIN-ONLY AND FAIL-CLOSED AT THE SERVER. These two calls are exactly as // forbidden to a member as the rest of `/admin/*`; the editor that consumes them // is hidden from non-admins as a courtesy and refused as a rule. // // The body is passed through UNPARSED on purpose — `permsModel.parsePermsPayload` // owns the shape, so the parse is one testable function rather than a validation // that half-lives in a fetch wrapper. export function getUserPerms(username: string): Promise> { return call(`/admin/users/${encodeURIComponent(username)}/perms`); } /** * WHOLE-RECORD REPLACE. Every module the server declared is present in `perms`, * including untouched ones: a key omitted from a replace is a DELETION. * `permsModel.toPutBody` is the only sanctioned way to build this body. */ export function putUserPerms( username: string, body: { perms: Record } ): Promise> { return call(`/admin/users/${encodeURIComponent(username)}/perms`, { method: "PUT", body: JSON.stringify(body), }); } // --- wave 54, W54-T47 / R4 / contract C4: the THIRD grant axis --------------- // // Owner, verbatim: *"Under Settings, an Admin should grant a user access to add // connectors, so access becomes Database / Module / Connector."* Database and // Module are two groupings of the `perms` record above; Connector is not a // registry key at all, it is a CREDENTIAL KIND, so it has its own pair of calls // rather than a third section of the perms body. // // ⛔ ADMIN-ONLY AND FAIL-CLOSED AT THE SERVER, exactly like the two above. And // the grant these write is consulted by `POST /admin/keychain` itself // (`core/perm_scope.may_add_connection`), so a client that never called them // changes nothing: absence is the behaviour that shipped before this wave. /** One connectable kind, as the server declares it. */ export interface ConnectorKind { key: string; label: string; /** True when the whole workspace reads its databases through this source, so a * connection of it is never personal. Granting it hands the member the * workspace's own credential slot, which an admin should read before ticking. */ tenantWide: boolean; } export interface ConnectorGrants { username: string; /** The vocabulary, served rather than hard-coded here: it is * `core/keychain.py::ENTRY_TYPES`, and a client copy is the drift a parity * gate exists to stop. */ kinds: ConnectorKind[]; /** The kinds this account may create a business-wide connection of. Empty is * the ordinary state and means "no grant", never "denied everything". */ granted: string[]; } export function getConnectorGrants( username: string ): Promise> { return call( `/admin/users/${encodeURIComponent(username)}/connector-grants` ); } /** WHOLE-LIST REPLACE, for the reason `putUserPerms` is one: revoking has to be * expressible, and a merge cannot express a deletion without a second * vocabulary for it. An empty list is a legal body and it revokes. */ export function putConnectorGrants( username: string, granted: string[] ): Promise> { return call( `/admin/users/${encodeURIComponent(username)}/connector-grants`, { method: "PUT", body: JSON.stringify({ granted }) } ); } /** Wave 14 C-AVATAR — own-profile photo. The server returns the refreshed `{user}` envelope; * the caller parses it with `session.parseUserEnvelope` so the shell chip updates live. */ export function setAvatar(dataUrl: string): Promise> { return call<{ user: unknown }>("/auth/me/avatar", { method: "POST", body: JSON.stringify({ dataUrl }), }); } export function clearAvatar(): Promise> { return call<{ user: unknown }>("/auth/me/avatar", { method: "DELETE" }); } // ── Wave 18 (C7): Keychains + Connectors ──────────────────────────────────────────────────── export interface KeyEntry { id: string; label: string; type: string; preview: string; created: string; createdBy: string; /** * ⭐ WAVE 32 · R4 / contract C1 — `"business" | "personal"`, read as a STRING (the wave-9 law). * A business-wide connection applies to every user in the tenant and only an admin can create * one; a personal one is visible to its owner alone. Absent on an older server ⇒ business, * which is what every entry stored before this wave actually is. */ scope?: string; /** Who owns a PERSONAL connection. Empty for a business-wide one — it has no single owner. */ owner?: string; } export interface ConnectorRow { key: string; label: string; type: string; source: "env" | "keychain"; preview?: string; paused: boolean; /** R4's scope, the same vocabulary as `KeyEntry.scope`. */ scope?: string; owner?: string; } export interface UnsyncedInfo { known: boolean; count: number | null; rows: Array<{ pid: number | string; fields: number; hint: string }>; shown?: number; note?: string; } export function listKeychain(): Promise< ApiResult<{ entries: KeyEntry[]; locked: boolean; /** R4's vocabulary, served rather than hard-coded here — contract C1 declares it server-side * in `routes_keychain.py`, and a client copy is the drift a parity gate exists to stop. */ scopes?: string[]; /** May THIS account create a business-wide connection (R4: administrators only)? */ canBusiness?: boolean; /** Types that are always business-wide — the whole workspace reads its databases through * them, so "personal" would be a label rather than a boundary. */ tenantWideTypes?: string[]; /** W54-T47 / R4 — the kinds THIS reader may create a business-wide connection of without * being an admin, because an admin granted them the Connector axis. * ⛔ COURTESY, NEVER THE WALL: `POST /admin/keychain` asks the server-side predicate * regardless of what a client believes about this list. Absent reads as none, which is the * behaviour every account had before this wave. */ connectorGrants?: string[]; }> > { return call("/admin/keychain"); } export function addKeychainEntry( label: string, type: string, fields: Record, scope: string ): Promise> { return call("/admin/keychain", { method: "POST", body: JSON.stringify({ label, type, fields, scope }), }); } /** R4's scope door — the ONLY editable part of a stored key. A secret is never re-openable, so * "change the key" means delete and re-add; "change who it is for" is this. */ export function setKeychainScope( id: string, scope: string ): Promise> { return call(`/admin/keychain/${encodeURIComponent(id)}`, { method: "PUT", body: JSON.stringify({ scope }), }); } export function deleteKeychainEntry(id: string): Promise> { return call(`/admin/keychain/${encodeURIComponent(id)}`, { method: "DELETE" }); } export function testKeychainEntry( id: string ): Promise> { return call(`/admin/keychain/${encodeURIComponent(id)}/test`, { method: "POST" }); } export function getConnectors(): Promise< ApiResult<{ connectors: ConnectorRow[]; locked: boolean; pausedNote: string; unsynced?: UnsyncedInfo; scopes?: string[]; canBusiness?: boolean; }> > { return call("/admin/connectors"); } export function pauseConnector( key: string, paused: boolean ): Promise> { return call(`/admin/connectors/${encodeURIComponent(key)}/pause`, { method: "POST", body: JSON.stringify({ paused }), }); }