loopable / web /src /settings /ExternalAccessPane.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
a5981db verified
Raw History Blame Contribute Delete
73.1 kB
// settings / ExternalAccessPane.tsx - W63-T06, rulings R4/R14, contract C7. // // This is the shared setup pane opened by the Connectors directory. OAuth clients receive the remote // MCP URL; API-key secrets appear only in the one-time reveal returned by create or rotate. All // editable metadata is seeded again from the server response. // // Setup instructions share one numbered list. Every AI client receives the public starter prompt. import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { FormEvent, ReactNode } from "react"; import { Copy } from "@phosphor-icons/react/dist/csr/Copy"; import { Check } from "@phosphor-icons/react/dist/csr/Check"; import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant } from "../apiContract"; import { Mark } from "../shell/Brand"; import { AiClientMark } from "./aiClientMarks"; import { KeyOpenApiRow, openApiDocumentUrl } from "./KeyOpenApiRow"; import { ExpiryPresets, presetToExpiresAt } from "./ExpiryPresets"; import type { ExpiryPreset } from "./ExpiryPresets"; import { parseTutorialGuide } from "../connectors/ConnectTutorial"; import type { TutorialGuide } from "../connectors/ConnectTutorial"; import "../connectors/connectors.css"; import "../styles/sdlc73/connectors.css"; type Access = "read" | "readwrite"; type ResourceScope = string[] | "all"; type ConnectionKind = "mcp" | "key"; // Copyable instructions never interpolate a stored credential. interface StepAction { label: string; url: string } export interface GuideStep { id?: string; title?: string; text: ReactNode; block?: string; copyValue?: string; action?: StepAction; hint?: string; details?: readonly GuideStep[]; } function GuideInstruction({ text }: { text: string }) { // Split only at an existing sentence or sequencing clause, keeping every character. const boundary = /[.!?](?=\s+[A-Z])|,(?=\s+then\b)/.exec(text); const end = boundary ? boundary.index + 1 : text.length; return <p className="external-step-instruction"> <span className="external-step-lead">{text.slice(0, end)}</span> {end < text.length ? <span className="external-step-detail">{text.slice(end)}</span> : null} </p>; } // S70-T09: the AI setup and connector tutorials share this actual frame and guide renderer. // Each caller owns its steps, fields and actions; the frame makes no requests. export function GuideSteps({ steps, tutorial, finalSteps = [], renderCopy, mode = "full" }: { steps: readonly GuideStep[]; tutorial?: TutorialGuide; finalSteps?: readonly GuideStep[]; renderCopy?: (value: string, index: number, step: GuideStep) => ReactNode; /** Short guides keep preparation and test limits outside the numbered instructions. */ mode?: "full" | "short"; }) { const body: readonly GuideStep[] = tutorial && mode === "full" ? [ { id: "tutorial-need", text: `What you need: ${tutorial.need}` }, ...steps, ...(tutorial.testNote ? [{ id: "tutorial-test", text: `Test: ${tutorial.testNote}` }] : []), { id: "tutorial-failure", text: `If it fails: ${tutorial.failureAction}` }, ] : steps; const entries = [...body, ...finalSteps]; if (!entries.length) return null; const content = (entry: GuideStep, index: number): ReactNode => { const copyValue = entry.copyValue ?? entry.block; return <> <div className={`external-step-content${copyValue && renderCopy ? "" : " external-step-content--wide"}`}> {entry.title ? <p className="external-step-title">{entry.title}</p> : typeof entry.text === "string" ? <GuideInstruction text={entry.text} /> : entry.text} </div> {copyValue ? renderCopy?.(copyValue, index, entry) : null} {entry.title ? <p className="external-step-description">{entry.text}</p> : null} {entry.block ? <pre className="external-step-code">{entry.block}</pre> : null} {entry.hint ? <p className="external-step-hint" id={entry.id ? `${entry.id}-hint` : undefined}> {entry.hint} </p> : null} {entry.action ? <a className="external-step-action" href={entry.action.url} target="_blank" rel="noopener noreferrer">{entry.action.label}</a> : null} {entry.details?.map((detail, detailIndex) => <div className="external-step-details" data-step-id={detail.id} key={detail.id ?? detailIndex}> {content(detail, detailIndex)} </div>)} </>; }; return <> {tutorial && mode === "short" ? <p className="external-sub">{tutorial.need}</p> : null} <ol className="external-steps" role="list" data-guide-renderer="GuideSteps" data-guide-mode={mode}> {entries.map((entry, index) => { return <li key={entry.id ?? index} data-step-id={entry.id} className={entry.copyValue ? "external-step--copy-text" : undefined}> <span className="external-step-number" aria-hidden="true">{index + 1}</span> {content(entry, index)} </li>; })} </ol> {tutorial && mode === "short" ? <div className="external-guide-help"> {tutorial.testNote ? <p className="external-sub">{tutorial.testNote}</p> : null} <p className="external-sub">{tutorial.failureAction}</p> </div> : null} </>; } export function ConnectionWizard({ title, titleId, metadata, footer, children }: { title: string; titleId: string; metadata?: ReactNode; footer?: ReactNode; children: ReactNode; }) { return <section className="external-wizard" aria-labelledby={titleId}> <header className="external-wizard-head"> <div className="external-wizard-heading"> <h2 id={titleId}>{title}</h2> {metadata} </div> <Mark size={28} /> </header> <div className="external-wizard-body">{children}</div> {footer ? <footer className="external-wizard-foot">{footer}</footer> : null} </section>; } // Client identity and grant matching stay stable when the served instructions change. export const CLIENTS = [ { id: "claude", label: "Claude.ai", connections: ["mcp"], skill: false, match: ["claude"] }, { id: "chatgpt", label: "ChatGPT", connections: ["mcp"], skill: false, match: ["chatgpt", "chat gpt"] }, { id: "claude-code", label: "Claude Code", connections: ["mcp", "key"], skill: true, match: ["claude code", "claude-code", "claude_code"] }, { id: "codex", label: "Codex", connections: ["mcp", "key"], skill: true, match: ["codex"] }, { id: "cursor", label: "Cursor", connections: ["mcp", "key"], skill: true, match: ["cursor"] }, { id: "muse", label: "Meta Muse", connections: ["key"], skill: false, match: ["muse", "meta muse"] }, ] as const satisfies readonly { id: string; label: string; connections: readonly ConnectionKind[]; skill: boolean; match: readonly string[]; }[]; export type ClientId = (typeof CLIENTS)[number]["id"]; interface ServedStep { title?: string; text: string; block?: string; action?: StepAction } interface ClientGuide { verified: string; documentation?: string; provenance: string; need: string; steps: ServedStep[]; keySteps?: ServedStep[]; caveat: string; failureAction: string; testNote: string; tutorial: TutorialGuide; keyTutorial?: TutorialGuide; } interface ClientStepsResponse { starterPrompt: string; clients: Record<ClientId, ClientGuide>; shared: { connection: Record<ConnectionKind, string>; skill: ServedStep; verification: Record<"mcp" | "key" | "activeKey" | "newKey" | "savedKey" | "noGrant" | "otherGrant", string>; keySetup: Record<"saved" | "saveNew", string>; }; } export function parseClientSteps(value: unknown): ClientStepsResponse | null { if (!value || typeof value !== "object") return null; const data = value as Partial<ClientStepsResponse>; const text = (item: unknown): item is string => typeof item === "string" && item.trim() !== ""; const action = (item: unknown): item is StepAction => { if (!item || typeof item !== "object" || Array.isArray(item)) return false; const row = item as Partial<StepAction>; if (!text(row.label) || row.label !== row.label.trim() || /[\x00-\x1f]/.test(row.label) || !text(row.url) || !/^https:\/\/[^/?#]+/.test(row.url) || /[\s\\\x00-\x1f\x7f]/.test(row.url) || /%(?![0-9a-fA-F]{2})/.test(row.url)) return false; try { const url = new URL(row.url); return url.protocol === "https:" && !!url.hostname && !url.username && !url.password; } catch { return false; } }; const step = (item: unknown): item is ServedStep => { if (!item || typeof item !== "object") return false; const row = item as Partial<ServedStep>; return text(row.text) && (row.block === undefined || text(row.block)) && (row.action === undefined || action(row.action)); }; const steps = (items: unknown) => Array.isArray(items) && items.length >= 2 && items.length <= 3 && items.every((item) => step(item) && text(item.title) && item.title.length <= 48 && text(item.block) && !/\bTest\s*:/i.test(`${item.title} ${item.text} ${item.block}`)); const shared = data.shared; if (!text(data.starterPrompt) || data.starterPrompt.length >= 600 || !data.clients || !shared || !step(shared.skill) || !text(shared.skill.block) || !text(shared.connection?.mcp) || !text(shared.connection?.key) || !["mcp", "key", "activeKey", "newKey", "savedKey", "noGrant", "otherGrant"].every( (key) => text(shared.verification?.[key as keyof typeof shared.verification])) || !text(shared.keySetup?.saved) || !text(shared.keySetup?.saveNew)) return null; const clients = {} as Record<ClientId, ClientGuide>; for (const client of CLIENTS) { const guide = data.clients[client.id]; if (!guide || !text(guide.verified) || !/^\d{4}-\d{2}-\d{2}$/.test(guide.verified) || !Number.isFinite(Date.parse(guide.verified)) || !text(guide.provenance) || (client.id === "muse" ? guide.documentation !== undefined : !text(guide.documentation) || !/^https:\/\//.test(guide.documentation)) || !text(guide.caveat) || !steps(guide.steps) || (guide.keySteps !== undefined && !steps(guide.keySteps)) || ((client.connections as readonly ConnectionKind[]).includes("key") && !steps(guide.keySteps))) return null; const tutorial = parseTutorialGuide({ ...guide, steps: guide.steps.map((entry) => entry.text) }, "ai"); const keyTutorial = (client.connections as readonly ConnectionKind[]).includes("key") ? parseTutorialGuide({ ...guide, steps: guide.keySteps!.map((entry) => entry.text) }, "ai") : null; if (!tutorial || ((client.connections as readonly ConnectionKind[]).includes("key") && !keyTutorial)) return null; clients[client.id] = { ...guide, tutorial, ...(keyTutorial ? { keyTutorial } : {}) }; } return { ...data, clients } as ClientStepsResponse; } export function isClientId(value: unknown): value is ClientId { return typeof value === "string" && CLIENTS.some((entry) => entry.id === value); } interface ExternalKeyMetadata { id: string; label: string; created: string; last_used: string | null; revoked_at: string | null; access: Access; databases: ResourceScope; expires_at: string | null; } interface ScopeDatabase { database: string; label: string } interface ExternalConnection { id: string; // This field holds the grant id; its existing name keeps disconnect URLs addressing the server's connection id. client: string; clientId: ClientId | null; label: string | null; status: "connected" | "expired" | "disconnected"; created: string | null; last_used: string | null; expires_at: string | null; disconnected_at: string | null; access: Access | null; databases: ResourceScope | null; } interface KeyListResponse { keys: ExternalKeyMetadata[]; can_mint: boolean } interface ConnectionListResponse { connections: unknown[] } interface MintResponse { key: ExternalKeyMetadata; secret: string } interface KeyDraft { label: string; access: Access; databaseMode: "all" | "subset"; databases: string[]; expiryPreset: ExpiryPreset; } const KEY_REFUSALS = { minted_elsewhere: "This key was minted on another Space. Create a key on this Space", revoked: "This key was revoked. Create a new key", expired: "This key expired. Update its expiry or create a new key", unknown_key: "This key is unknown to your account on this Space. Paste your saved key or create a new one", } as const; type KeyRefusal = keyof typeof KEY_REFUSALS; interface OwnerKeyVerification { valid: boolean; cause: KeyRefusal | null; warning: "store_write_refused" | null; origin_recorded: boolean | null; key_id?: string; } type VerifyResult = { state: "ok" | "failed"; message: string; cause?: KeyRefusal | "store_write_refused" }; type ConfirmedConnection = { clientId: ClientId } & ( { kind: "mcp"; grantId: string } | { kind: "key"; keyId: string } ); type KeyChoice = "create" | "saved"; type ApiResult<T> = | { ok: true; data: T } | { ok: false; message: string; status: number }; // The one spelling of the OAuth connections route. The pane reads it on mount and again when // the MCP step verifies, and two copies of a route are two things to keep in step. const CONNECTIONS_PATH = "/external/oauth/connections"; function messageFrom(body: unknown, fallback: string): string { if (!body || typeof body !== "object") return fallback; const error = (body as { error?: unknown }).error; if (!error || typeof error !== "object") return fallback; const message = (error as { message?: unknown }).message; return typeof message === "string" && message.trim() !== "" ? message : fallback; } async function call<T>(path: string, init?: RequestInit): Promise<ApiResult<T>> { try { const response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init }); if (checkTenant(response)) { return { ok: false, message: "This workspace changed. Reloading.", status: 409 }; } let body: unknown = null; try { body = await response.json(); } catch { /* Keep non-JSON failures generic. */ } if (!response.ok) { if (response.status === 401 && typeof window !== "undefined") { window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); } return { ok: false, status: response.status, message: response.status >= 500 ? "The AI API is unavailable right now." : messageFrom(body, "That request could not be completed."), }; } return { ok: true, data: body as T }; } catch { return { ok: false, message: "The server could not be reached.", status: 0 }; } } function parseKey(value: unknown): ExternalKeyMetadata | null { if (!value || typeof value !== "object" || Array.isArray(value)) return null; const row = value as Record<string, unknown>; if (typeof row.id !== "string" || typeof row.label !== "string" || typeof row.created !== "string") { return null; } const databases = Array.isArray(row.databases) && row.databases.every( (database): database is string => typeof database === "string" && database.trim() !== "", ) ? row.databases.map((database) => database.trim()) : "all"; return { id: row.id, label: row.label, created: row.created, last_used: typeof row.last_used === "string" ? row.last_used : null, revoked_at: typeof row.revoked_at === "string" ? row.revoked_at : null, access: row.access === "read" ? "read" : "readwrite", databases, expires_at: typeof row.expires_at === "string" ? row.expires_at : null, }; } function parseConnection(value: unknown): ExternalConnection | null { if (!value || typeof value !== "object" || Array.isArray(value)) return null; const row = value as Record<string, unknown>; if (typeof row.id !== "string" || !row.id.trim()) return null; const label = typeof row.label === "string" ? row.label : null; // Prefer the longest matching name, so Claude Code resolves before the broader Claude match. const resolved = CLIENTS.flatMap((entry) => entry.match.map((match) => ({ id: entry.id, match }))) .sort((a, b) => b.match.length - a.match.length) .find((entry) => label?.toLowerCase().includes(entry.match))?.id; const expires_at = typeof row.expires_at === "string" ? row.expires_at : null; const disconnected_at = typeof row.disconnected_at === "string" ? row.disconnected_at : null; return { id: row.id, client: row.id, clientId: isClientId(resolved) ? resolved : null, label, status: disconnected_at ? "disconnected" : expires_at && Date.parse(expires_at) <= Date.now() ? "expired" : "connected", created: typeof row.created === "string" ? row.created : null, last_used: typeof row.last_used === "string" ? row.last_used : null, expires_at, disconnected_at, access: row.access === "read" || row.access === "readwrite" ? row.access : null, databases: row.databases === "all" ? "all" : Array.isArray(row.databases) ? row.databases.filter((item): item is string => typeof item === "string") : null, }; } function when(value: string | null): string { if (!value) return "Never"; const parsed = new Date(value); if (Number.isNaN(parsed.getTime())) return "Unknown"; return parsed.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }); } function keyExpiryLabel(key: ExternalKeyMetadata): string { if (!key.expires_at) return "No expiry"; if (Date.parse(key.expires_at) <= Date.now()) return "Expired"; return `Expires ${when(key.expires_at)}`; } function draftFor(key: ExternalKeyMetadata): KeyDraft { return { label: key.label, access: key.access, databaseMode: key.databases === "all" ? "all" : "subset", databases: key.databases === "all" ? [] : [...key.databases], expiryPreset: "keep", }; } function connectionLabel(connection: ExternalConnection | undefined): string { if (!connection || connection.status === "disconnected") return "Not connected"; if (connection.status === "connected") return "Connected"; if (connection.status === "expired") return "Reconnect required"; return "Not connected"; } function SettingsSkeleton({ label }: { label: string }) { return <div className="set-skeleton" role="status" aria-label={label} aria-busy="true"> <span className="set-skeleton-line" aria-hidden="true" /> <span className="set-skeleton-line" aria-hidden="true" /> <span className="set-skeleton-line" aria-hidden="true" /> </div>; } /** The directory selects a client; this pane remains the one setup and credential implementation. */ export default function ExternalAccessPane({ initialClient, view = "all", settings = false, onChanged, onOpenApi, }: { initialClient?: ClientId; view?: "all" | "client" | "api"; settings?: boolean; onChanged?: () => void; onOpenApi?: () => void; } = {}) { const initialEntry = CLIENTS.find((entry) => entry.id === initialClient); const [clientId, setClientId] = useState<ClientId | null>(initialClient ?? null); const [connection, setConnection] = useState<ConnectionKind | null>( initialEntry?.connections[0] ?? null, ); const [showSetup, setShowSetup] = useState(!settings || view === "api"); const [keyChoice, setKeyChoice] = useState<KeyChoice>(view === "client" ? "saved" : "create"); const [selectedKeyId, setSelectedKeyId] = useState(""); const [verifyResult, setVerifyResult] = useState<VerifyResult | null>(null); const [confirmedConnection, setConfirmedConnection] = useState<ConfirmedConnection | null>(null); const [verifySecret, setVerifySecret] = useState(""); const verificationVersion = useRef(0); const [keys, setKeys] = useState<ExternalKeyMetadata[] | null>(null); const [keysError, setKeysError] = useState(""); const [connections, setConnections] = useState<ExternalConnection[]>([]); const [connectionsLoading, setConnectionsLoading] = useState(view !== "api"); const [connectionsError, setConnectionsError] = useState(""); const [clientSteps, setClientSteps] = useState<ClientStepsResponse | null>(null); const [stepsError, setStepsError] = useState(""); const [stepsLoading, setStepsLoading] = useState(view !== "api"); const [canMint, setCanMint] = useState<boolean | null>(null); const [label, setLabel] = useState(""); const [access, setAccess] = useState("read"); const [databaseMode, setDatabaseMode] = useState<"all" | "subset">("all"); const [selectedDatabases, setSelectedDatabases] = useState<string[]>([]); const [expiryPreset, setExpiryPreset] = useState<ExpiryPreset>("1-year"); const [scopeDatabases, setScopeDatabases] = useState<ScopeDatabase[] | null>(null); const [scopeError, setScopeError] = useState(""); const [scopeRevision, setScopeRevision] = useState(0); const [editing, setEditing] = useState<string | null>(null); const [editDraft, setEditDraft] = useState<KeyDraft | null>(null); const [busy, setBusy] = useState(""); const [error, setError] = useState(""); const [notice, setNotice] = useState(""); const [revealed, setRevealed] = useState<MintResponse | null>(null); // The client view closes its in-step reveal but keeps the secret in memory for the verify step. const [revealClosed, setRevealClosed] = useState(false); const [copied, setCopied] = useState(""); const copyTimer = useRef<ReturnType<typeof setTimeout> | null>(null); const savedKeySelect = useRef<HTMLSelectElement | null>(null); useEffect(() => () => { if (copyTimer.current !== null) clearTimeout(copyTimer.current); }, []); const mcpUrl = useMemo(() => { const origin = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin; return `${origin}${API_V1}/external/mcp`; }, []); const openApiUrl = useMemo(() => { const origin = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin; return openApiDocumentUrl(API_V1, origin); }, []); const client = CLIENTS.find((entry) => entry.id === clientId); const guide = client ? clientSteps?.clients[client.id] : undefined; const sharedSteps = clientSteps?.shared; // Replace only known text tokens. React escapes the result, including command placeholders. function instruction(value: string): string { const base = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin; return value.replace(/<base>|<mcpUrl>|<client>/g, (token) => token === "<base>" ? base : token === "<mcpUrl>" ? mcpUrl : client?.label ?? ""); } function guideStep(step: ServedStep): GuideStep { return { title: step.title, text: instruction(step.text), ...(step.block ? { block: instruction(step.block) } : {}), ...(step.action ? { action: step.action } : {}) }; } const starterPrompt = view === "client" && clientSteps ? instruction(clientSteps.starterPrompt) : null; const connectionKinds: readonly ConnectionKind[] = client?.connections ?? []; const selectedKey = keys?.find((key) => key.id === selectedKeyId); const keyIsActive = (key: ExternalKeyMetadata) => !key.revoked_at && (!key.expires_at || Date.parse(key.expires_at) > Date.now()); const selectedKeyIsActive = selectedKey !== undefined && keyIsActive(selectedKey); // The client view opens on a saved key only when an active one exists. const shownKeyChoice: KeyChoice = view === "client" && canMint === true && keys !== null && !keys.some(keyIsActive) ? "create" : keyChoice; const stepReveal = view === "client" && !revealClosed ? revealed : null; // A reveal from a different key must never silently replace the saved key the user chose. const verificationReveal = revealed?.key.id === selectedKeyId ? revealed : null; const confirmedGrant = confirmedConnection?.kind === "mcp" ? connections.find((grant) => grant.id === confirmedConnection.grantId && grant.clientId === clientId) : undefined; const confirmationIsActive = confirmedConnection?.clientId === clientId && ( connection === "mcp" && confirmedConnection?.kind === "mcp" && !connectionsLoading && !connectionsError && confirmedGrant?.status === "connected" && !confirmedGrant.disconnected_at && (!confirmedGrant.expires_at || Date.parse(confirmedGrant.expires_at) > Date.now()) || connection === "key" && confirmedConnection?.kind === "key" && confirmedConnection.keyId === selectedKeyId && selectedKeyIsActive ); const canCopyStarterPrompt = view === "client" && showSetup && confirmationIsActive; const confirmationExpiresAt = connection === "key" ? selectedKey?.expires_at : confirmedGrant?.expires_at; useEffect(() => { if (!confirmedConnection) return; const invalidate = () => { verificationVersion.current += 1; setConfirmedConnection(null); setVerifyResult(null); setCopied(""); }; if (!confirmationIsActive) { invalidate(); return; } if (!confirmationExpiresAt) return; let timer: ReturnType<typeof setTimeout>; const schedule = () => { const remaining = Date.parse(confirmationExpiresAt) - Date.now(); if (remaining <= 0) { invalidate(); return; } timer = setTimeout(schedule, Math.min(remaining, 2_147_483_647)); }; schedule(); return () => clearTimeout(timer); }, [confirmedConnection, confirmationIsActive, confirmationExpiresAt]); useEffect(() => { if (revealClosed) savedKeySelect.current?.focus(); }, [revealClosed]); function resetVerification() { verificationVersion.current += 1; setConfirmedConnection(null); setVerifyResult(null); setVerifySecret(""); setCopied(""); } function chooseClient(id: ClientId) { const entry = CLIENTS.find((candidate) => candidate.id === id); if (id !== clientId) { setClientId(id); setConnection(entry?.connections[0] ?? null); resetVerification(); setCopied(""); setError(""); setNotice(""); } } function chooseConnection(kind: ConnectionKind) { if (kind !== connection) { setConnection(kind); resetVerification(); setCopied(""); setError(""); setNotice(""); } } function chooseKey(id: string) { setSelectedKeyId(id); resetVerification(); } const load = useCallback(async () => { setKeysError(""); const result = await call<KeyListResponse>("/external/keys"); if (!result.ok) { setKeys(null); setCanMint(null); setKeysError(result.message); setError(result.message); return; } if (!Array.isArray(result.data?.keys) || typeof result.data.can_mint !== "boolean") { setKeys(null); setCanMint(null); setKeysError("The AI API returned an unreadable response."); setError("The AI API returned an unreadable response."); return; } const parsed = result.data.keys.map(parseKey); if (parsed.some((row) => row === null)) { setKeys(null); setCanMint(null); setKeysError("The AI API returned an unreadable response."); setError("The AI API returned an unreadable response."); return; } setKeys(parsed as ExternalKeyMetadata[]); setCanMint(result.data.can_mint); setError(""); }, []); const loadConnections = useCallback(async (confirmClient = true) => { const version = verificationVersion.current; if (connection === "mcp") { setConfirmedConnection(null); setVerifyResult(null); setCopied(""); } setConnectionsLoading(true); setConnectionsError(""); const result = await call<ConnectionListResponse>(CONNECTIONS_PATH); setConnectionsLoading(false); if (version !== verificationVersion.current) return; if (!result.ok || !Array.isArray(result.data?.connections)) { // Key management remains usable if OAuth discovery is unavailable. setConnectionsError(result.ok ? "Connections could not be loaded." : result.message); return; } const parsed = result.data.connections.map(parseConnection); if (parsed.some((row) => row === null)) { setConnectionsError("Connections could not be loaded."); return; } const grants = parsed as ExternalConnection[]; setConnections(grants); const matched = grants.find((grant) => grant.clientId === clientId && grant.status === "connected" && (!grant.expires_at || Date.parse(grant.expires_at) > Date.now())); if (confirmClient && connection === "mcp" && clientId && matched) { setConfirmedConnection({ clientId, kind: "mcp", grantId: matched.id }); } }, [clientId, connection]); const loadClientSteps = useCallback(async () => { setStepsLoading(true); setStepsError(""); setClientSteps(null); const result = await call<unknown>("/connectors/ai-client-steps"); const parsed = result.ok ? parseClientSteps(result.data) : null; setStepsLoading(false); if (!parsed) { setStepsError(result.ok ? "AI client instructions could not be read." : result.message); return; } setClientSteps(parsed); }, []); useEffect(() => { if (view !== "api") void loadClientSteps(); }, [loadClientSteps, view]); useEffect(() => { if (view !== "client" || connection === "key") void load(); }, [load, view, connection]); useEffect(() => { if (view !== "api") void loadConnections(); }, [loadConnections, view]); const visibleConnections = view === "client" ? connections.filter((entry) => entry.clientId === initialClient) : connections; // Report changed metadata only. Secrets remain inside this pane's one-time reveal. const changed = useRef(false); useEffect(() => { if (changed.current) onChanged?.(); changed.current = true; }, [keys, connections, onChanged]); useEffect(() => { if (canMint !== true) return; let active = true; setScopeDatabases(null); setScopeError(""); void call<{ databases: ScopeDatabase[] }>("/external/scope/databases").then((result) => { if (!active) return; if (!result.ok) { setScopeError(result.message); setScopeDatabases([]); return; } const rows = result.data?.databases; if (!Array.isArray(rows) || rows.some((row) => !row || typeof row.database !== "string" || !row.database.trim())) { setScopeError("The database list could not be read."); setScopeDatabases([]); return; } setScopeError(""); setScopeDatabases(rows.map((row) => ({ database: row.database, label: typeof row.label === "string" && row.label.trim() ? row.label : row.database, }))); }); return () => { active = false; }; }, [canMint, scopeRevision]); function databaseLabels(databases: ResourceScope): string { if (databases === "all") return "All databases"; if (databases.length === 0) return "No databases"; const labels = databases.slice(0, 4).map((database) => ( scopeDatabases?.find((row) => row.database === database)?.label || database )); return labels.join(", ") + (databases.length > 4 ? ` and ${databases.length - 4} more` : ""); } function selectedScope(mode: "all" | "subset", selected: string[]): ResourceScope { return mode === "all" ? "all" : selected; } function validateDraft(draft: KeyDraft): string { if (!draft.label.trim()) return "Enter a label for this API key."; if (draft.databaseMode === "subset" && draft.databases.length === 0) { return "Choose at least one database for this API key."; } return ""; } async function create(event: FormEvent) { event.preventDefault(); const draft: KeyDraft = { label, access: access as Access, databaseMode, databases: selectedDatabases, expiryPreset, }; const invalid = validateDraft(draft); if (invalid) { setError(invalid); return; } const databases = selectedScope(databaseMode, selectedDatabases); setBusy("create"); setError(""); setNotice(""); resetVerification(); const result = await call<MintResponse>("/external/keys", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ label: label.trim(), access: access, databases: databases, resources: databases, expires_at: presetToExpiresAt(expiryPreset, new Date()), }), }); setBusy(""); if (!result.ok) { setError(result.message); return; } const key = parseKey(result.data?.key); if (!key || typeof result.data?.secret !== "string" || result.data.secret === "") { setError("The API key was created, but its secret could not be read."); void load(); return; } setKeys((current) => [key, ...(current ?? []).filter((row) => row.id !== key.id)]); setLabel(""); setAccess("read"); setDatabaseMode("all"); setSelectedDatabases([]); setExpiryPreset("1-year"); setCopied(""); setRevealed({ key, secret: result.data.secret }); setSelectedKeyId(key.id); setKeyChoice("saved"); setRevealClosed(false); } async function copy(value: string, name: string) { if (copyTimer.current !== null) clearTimeout(copyTimer.current); setCopied(""); setBusy(`copy:${name}`); try { await navigator.clipboard.writeText(value); setCopied(name); setError(""); copyTimer.current = setTimeout(() => { setCopied(""); copyTimer.current = null; }, 2000); } catch { setCopied(""); setError("That text could not be copied. Select it and copy it manually."); } finally { setBusy((current) => current === `copy:${name}` ? "" : current); } } async function saveEdit(event: FormEvent) { event.preventDefault(); if (!editing || !editDraft) return; const invalid = validateDraft(editDraft); if (invalid) { setError(invalid); return; } const databases = selectedScope(editDraft.databaseMode, editDraft.databases); setBusy(`edit:${editing}`); setError(""); setNotice(""); resetVerification(); const result = await call<{ key: ExternalKeyMetadata }>(`/external/keys/${encodeURIComponent(editing)}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ label: editDraft.label.trim(), access: editDraft.access, databases: databases, ...(editDraft.expiryPreset === "keep" ? {} : { expires_at: presetToExpiresAt(editDraft.expiryPreset, new Date()), }), }), }); setBusy(""); if (!result.ok) { setError(result.message); return; } const saved = parseKey(result.data?.key); if (!saved) { setError("The API key was updated, but its metadata could not be read."); void load(); return; } setKeys((current) => (current ?? []).map((row) => row.id === saved.id ? saved : row)); setEditing(null); setEditDraft(null); setNotice("API key settings saved."); } async function rotate(key: ExternalKeyMetadata) { if (!window.confirm(`Rotate "${key.label}"? Its current secret will stop working immediately.`)) return; setBusy(`rotate:${key.id}`); setError(""); setNotice(""); resetVerification(); const result = await call<MintResponse>(`/external/keys/${encodeURIComponent(key.id)}/rotate`, { method: "POST" }); setBusy(""); if (!result.ok) { setError(result.message); return; } const replacement = parseKey(result.data?.key); if (!replacement || typeof result.data?.secret !== "string" || !result.data.secret) { setError("The API key was rotated, but its replacement secret could not be read."); void load(); return; } setKeys((current) => (current ?? []).map((row) => row.id === key.id ? replacement : row)); setSelectedKeyId((current) => current === key.id ? replacement.id : current); setEditing(null); setEditDraft(null); setCopied(""); setRevealed({ key: replacement, secret: result.data.secret }); } async function revoke(key: ExternalKeyMetadata) { if (!window.confirm(`Revoke "${key.label}"? Its next request will be refused.`)) return; setBusy(`revoke:${key.id}`); setError(""); setNotice(""); resetVerification(); const result = await call<{ key: ExternalKeyMetadata }>( `/external/keys/${encodeURIComponent(key.id)}/revoke`, { method: "POST" }, ); setBusy(""); if (!result.ok) { setError(result.message); return; } setKeys((current) => (current ?? []).filter((row) => row.id !== key.id)); if (revealed?.key.id === key.id) setRevealed(null); if (editing === key.id) { setEditing(null); setEditDraft(null); } setNotice("API key revoked. Its next request will be refused."); } async function disconnect(connection: ExternalConnection) { const name = connection.label?.trim() || CLIENTS.find((entry) => entry.id === connection.clientId)?.label || "this AI app"; if (!window.confirm(`Disconnect ${name} from Loopable?`)) return; setBusy(`disconnect:${connection.client}`); setError(""); resetVerification(); const result = await call<{ connection: unknown }>( `/external/oauth/connections/${encodeURIComponent(connection.client)}/disconnect`, { method: "POST" }, ); setBusy(""); if (!result.ok) { setError(result.message); return; } setConnections((current) => current.filter((grant) => grant.id !== connection.id)); void loadConnections(false); setNotice("AI app disconnected. Its next request will be refused."); } async function verifyKey() { const useSelectedKey = view === "client"; const secret = (useSelectedKey ? verificationReveal?.secret : undefined) ?? verifySecret.trim(); if (!secret || busy !== "" || canMint !== true) return; setBusy("verify:key"); setConfirmedConnection(null); setVerifyResult(null); setCopied(""); const version = ++verificationVersion.current; const report = (state: VerifyResult["state"], message: string, cause?: VerifyResult["cause"]) => { if (version !== verificationVersion.current) return; setVerifyResult({ state, message, cause }); if (state === "ok" && useSelectedKey && clientId && selectedKeyIsActive) { setConfirmedConnection({ clientId, kind: "key", keyId: selectedKeyId }); } }; try { const result = await call<OwnerKeyVerification>("/external/keys/verify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: secret }), }); if (version !== verificationVersion.current) return; if (!result.ok) { report("failed", result.status === 403 ? "Verifying API keys requires AI apps access. Ask an administrator for access" : "Could not verify the API key. Try again"); return; } const diagnosis = result.data; if (diagnosis?.valid === false && diagnosis.cause && Object.prototype.hasOwnProperty.call(KEY_REFUSALS, diagnosis.cause)) { report("failed", KEY_REFUSALS[diagnosis.cause], diagnosis.cause); return; } if (diagnosis?.valid !== true || diagnosis.cause !== null || typeof diagnosis.origin_recorded !== "boolean" || typeof diagnosis.key_id !== "string" || (diagnosis.warning !== null && diagnosis.warning !== "store_write_refused")) { report("failed", "The AI API returned an unreadable response."); return; } if (useSelectedKey && selectedKeyId && diagnosis.key_id !== selectedKeyId) { report("failed", "This secret does not match the selected API key."); return; } const warning = diagnosis.warning === "store_write_refused" ? ". The last-used store write was refused. Retry Verify to save it" : ""; const origin = diagnosis.origin_recorded ? "" : ". This legacy key has no recorded Space origin. Its minting Space cannot be proved"; report("ok", `API key accepted${warning}${origin}`, diagnosis.warning ?? undefined); } catch { report("failed", "The server could not be reached."); } finally { setVerifySecret(""); setBusy((current) => current === "verify:key" ? "" : current); } } async function verifyMcp() { if (!client || !sharedSteps || busy !== "" || connection !== "mcp") return; setBusy("verify:mcp"); setConfirmedConnection(null); setVerifyResult(null); setCopied(""); const version = ++verificationVersion.current; // OAuth grants belong to the signed-in session, independently of the API-key bearer check. const result = await call<ConnectionListResponse>(CONNECTIONS_PATH); setBusy((current) => current === "verify:mcp" ? "" : current); if (version !== verificationVersion.current) return; if (!result.ok) { setVerifyResult({ state: "failed", message: result.status ? `${result.status}: ${result.message}` : result.message }); return; } if (!Array.isArray(result.data?.connections)) { setVerifyResult({ state: "failed", message: "The AI API returned an unreadable response." }); return; } const parsed = result.data.connections.map(parseConnection); const grants = parsed.filter((row): row is ExternalConnection => row !== null); if (grants.length !== parsed.length) { setVerifyResult({ state: "failed", message: "The AI API returned an unreadable response." }); return; } setConnections(grants); setConnectionsError(""); const live = grants.filter((grant) => grant.status === "connected" && (!grant.expires_at || Date.parse(grant.expires_at) > Date.now())); const matched = live.find((grant) => grant.clientId === client.id); if (matched) { setConfirmedConnection({ clientId: client.id, kind: "mcp", grantId: matched.id }); setVerifyResult({ state: "ok", message: `Loopable sign-in completed for ${matched.label}. Last used: ${when(matched.last_used)}.` }); } else if (live.length) { setVerifyResult({ state: "failed", message: `Connected: ${live.map((grant) => grant.label || "Unnamed AI app").join(", ")}. ${instruction(sharedSteps.verification.otherGrant)}` }); } else { setVerifyResult({ state: "failed", message: instruction(sharedSteps.verification.noGrant) }); } } function databaseChecks(selected: string[], change: (next: string[]) => void) { return ( <div className="set-field" style={{ maxHeight: 216, overflowY: "auto" }}> {scopeDatabases === null ? <SettingsSkeleton label="Loading databases" /> : null} {scopeError ? <div className="set-error" role="alert"><span title={scopeError}>Could not read the database list.</span> <button type="button" className="set-secondary" onClick={() => setScopeRevision(value => value + 1)}>Retry</button></div> : null} {scopeDatabases?.map((database) => ( <label className="set-check" key={database.database}> <input type="checkbox" checked={selected.includes(database.database)} onChange={(event) => change(event.currentTarget.checked ? [...selected, database.database] : selected.filter((key) => key !== database.database))} /> <span>{database.label || database.database}</span> </label> ))} {selected.length === 0 ? <p className="set-help">Choose at least one database for this API key.</p> : null} </div> ); } function codeBlock(value: string, name: string, content?: ReactNode) { return ( <div className="external-code"> <pre>{content ?? value}</pre> <button type="button" className="external-code-copy" disabled={busy !== ""} aria-label={copied === name ? "Copied" : "Copy"} title={copied === name ? "Copied" : "Copy"} onClick={() => void copy(value, name)}> <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" aria-hidden="true"> {copied === name ? <path d="M3 8.5l3 3 7-7" /> : <><rect x="5.5" y="5.5" width="8" height="8" rx="1.5" /> <path d="M10.5 5.5V3.5a1 1 0 00-1-1h-6a1 1 0 00-1 1v6a1 1 0 001 1h2" /></>} </svg> </button> </div> ); } function clientGuide(kind: ConnectionKind): GuideStep[] { if (!guide) return []; const tutorial = kind === "mcp" ? guide.tutorial : guide.keyTutorial; if (!tutorial) return []; return (kind === "mcp" ? guide.steps : guide.keySteps ?? []).map((step, index) => ({ ...guideStep({ ...step, text: tutorial.steps[index] }), id: `client-step-${index}` })); } function clientSetupSteps(keySteps: GuideStep[], completionSteps: GuideStep[]): GuideStep[] { if (view === "api") return keySteps; if (!connection) return []; const steps = clientGuide(connection); return steps.map((step, index) => ({ ...step, details: [ ...(index === 0 ? keySteps : []), ...(index === steps.length - 1 ? completionSteps : []), ] })); } function revealPanel(reveal: MintResponse, close: ReactNode) { return <> <p className="set-help">Copy it now. Loopable cannot show this secret again.</p> <div className="set-field"><label className="set-label" htmlFor="set-external-secret">API key</label> <input id="set-external-secret" className="set-input" type="text" value={reveal.secret} readOnly autoComplete="off" spellCheck={false} /></div> <div className="set-actions"> <button type="button" className="set-primary" disabled={busy !== ""} onClick={() => void copy(reveal.secret, "secret")}> {busy === "copy:secret" ? "Copying…" : copied === "secret" ? "Copied" : "Copy API key"}</button> {close} </div> </>; } // The client view shows its reveal inside the key step, so only the other views draw this card. const revealCard = revealed && view !== "client" ? ( <section className="set-card"> <h2 className="set-h4">API key</h2> {revealPanel(revealed, <button type="button" className="set-secondary" disabled={busy !== ""} onClick={() => { setRevealed(null); setCopied(""); }}>Done</button>)} </section> ) : null; return ( <div className="set-pane external-access-pane" data-connect-tutorial={view === "client" ? clientId : undefined}> <style>{` .external-access-pane .set-card { padding: 16px; } .external-access-pane .set-field { margin-bottom: 16px; } .external-access-pane .set-label { margin-bottom: 4px; } .external-access-pane .set-check { gap: 8px; padding: 4px 0; } .external-access-pane .set-actions { margin-top: 16px; align-items: center; } .external-access-pane .set-input { padding: 0 8px; } .external-access-pane textarea.set-input { height: auto; padding: 8px; } .external-access-pane .pg-select { height: 32px; max-width: 100%; } .external-clients { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; } .external-access-pane .external-tile { display: flex; align-items: center; gap: 10px; min-height: 44px; padding: 0 12px; text-align: left; color: var(--lp-ink); background: var(--lp-surface); cursor: pointer; border: 1px solid var(--lp-line); border-radius: var(--lp-r-md); font-size: var(--lp-fs-sm); } .external-access-pane .external-tile[aria-pressed="true"] { border-color: var(--lp-ink); background: var(--lp-wash); box-shadow: inset 0 0 0 1px var(--lp-ink); } .external-choices { display: grid; gap: 8px; } .external-access-pane .external-choice { flex-direction: column; align-items: flex-start; gap: 2px; padding: 10px 12px; } .external-choice span { font-size: var(--lp-fs-xs); color: var(--lp-muted); } .external-for { display: flex; align-items: center; gap: 8px; margin: 0 0 16px; font-size: var(--lp-fs-xs); color: var(--lp-muted); } .external-for strong { color: var(--lp-ink); font-weight: 500; } .external-access-pane kbd { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 0.92em; padding: 1px 6px; color: var(--lp-ink); background: var(--lp-wash); border: 1px solid var(--lp-line); border-radius: var(--lp-r-sm); } .external-code { position: relative; margin-top: 8px; background: var(--lp-wash); border: 1px solid var(--lp-line); border-radius: var(--lp-r-md); } .external-code pre { margin: 0; padding: 12px 44px 12px 14px; white-space: pre-wrap; overflow-wrap: anywhere; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: var(--lp-fs-xs); color: var(--lp-ink); line-height: var(--lp-lh); } .external-access-pane .external-code-copy { position: absolute; top: 8px; right: 8px; width: 28px; height: 28px; display: grid; place-items: center; color: var(--lp-muted); cursor: pointer; border-radius: var(--lp-r-sm); } .external-guide .set-help { margin-top: 16px; } .external-send { margin: 0; font-size: var(--lp-fs-sm); color: var(--lp-ink); } .external-instructions { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; font-size: var(--lp-fs-xs); color: var(--lp-ink); line-height: var(--lp-lh); } .external-access-pane .external-command { height: 40px; font-weight: 500; } .external-guide { min-width: 0; } .external-guide code { font: inherit; color: var(--lp-ink); } .external-divider { border-top: 1px solid var(--lp-line); margin-top: 16px; padding-top: 16px; } .external-access-pane .external-steps .external-verification-result { margin-top: 8px; } @media (hover: hover) and (pointer: fine) { .external-access-pane .external-tile:hover:enabled { border-color: var(--lp-line-strong); } .external-access-pane .external-code-copy:hover:enabled { color: var(--lp-ink); background: var(--lp-surface); } } @media (max-width: 560px) { .external-clients { grid-template-columns: repeat(2, minmax(0, 1fr)); } } `}</style> {view === "all" ? <h1 className="set-h">Loopable connections</h1> : null} {error ? <p className="set-error" role="alert">{error}</p> : null} {notice ? <p className="set-notice" role="status">{notice}</p> : null} {view !== "api" && connectionsLoading ? <SettingsSkeleton label="Loading connections" /> : null} {view !== "api" && connectionsError ? ( <div className="set-error" role="alert"><span title={connectionsError}>Could not load connections.</span> <button type="button" className="set-secondary" disabled={connectionsLoading} onClick={() => void loadConnections()}>Retry</button></div> ) : null} {!showSetup && view === "client" && !connectionsLoading ? ( <div className="set-actions"><button type="button" className="set-primary" onClick={() => setShowSetup(true)}>Connect another</button></div> ) : null} {showSetup ? <ConnectionWizard titleId="external-step-title" title={view === "api" ? "Create API key" : "Connect Loopable"} metadata={view !== "api" && guide ? <p className="set-help" title={guide.provenance}> {clientId === "muse" ? "Setup guide" : <> Checked <time dateTime={guide.verified}>{guide.verified}</time>{" · "} <a href={guide.documentation} target="_blank" rel="noreferrer" style={{ color: "var(--lp-blue-deep)" }}>Documentation</a> </>} </p> : undefined}> {view !== "api" ? ( <> <div className="external-clients" role="group" aria-label="Which AI are you using?"> {CLIENTS.map((entry) => ( <button key={entry.id} type="button" className="external-tile" data-client={entry.id} aria-pressed={clientId === entry.id} disabled={busy !== ""} onClick={() => chooseClient(entry.id)}> <AiClientMark id={entry.id} /><span>{entry.label}</span> </button> ))} </div> </> ) : null} {view !== "api" && client && connectionKinds.length > 1 ? ( <> <p className="external-sub">How should {client.label} reach Loopable?</p> <div className="external-choices" aria-label="AI API connection choices"> {connectionKinds.includes("mcp") ? ( <button type="button" className="external-tile external-choice" data-connection="mcp" disabled={busy !== ""} aria-pressed={connection === "mcp"} onClick={() => chooseConnection("mcp")}> <strong>Sign in with Loopable</strong> {sharedSteps ? <span>{instruction(sharedSteps.connection.mcp)}</span> : null} </button> ) : null} {connectionKinds.includes("key") ? ( <button type="button" className="external-tile external-choice" data-connection="key" disabled={busy !== ""} aria-pressed={connection === "key"} onClick={() => chooseConnection("key")}> <strong>API key</strong> {sharedSteps ? <span>{sharedSteps.connection.key}</span> : null} </button> ) : null} </div> </> ) : null} <div className="external-guide" title={view !== "api" ? guide?.caveat : undefined}> {view !== "api" && stepsLoading ? <SettingsSkeleton label="Loading instructions" /> : null} {view !== "api" && stepsError ? <div className="set-error" role="alert"> <span title={stepsError}>Could not read the instructions.</span> <button type="button" className="set-secondary" onClick={() => void loadClientSteps()}> Retry </button> </div> : null} {view === "api" || (guide && sharedSteps) ? <GuideSteps mode="short" tutorial={view === "api" ? undefined : connection === "key" ? guide?.keyTutorial : guide?.tutorial} renderCopy={(value, index, step) => { const name = `guide:${clientId}:${connection}:${step.id ?? index}`; const isStarter = step.id === "starter-prompt"; return <button type="button" className="external-step-copy" disabled={busy !== "" || (isStarter && !canCopyStarterPrompt)} data-starter-prompt={isStarter || undefined} aria-describedby={isStarter && !canCopyStarterPrompt ? "starter-prompt-hint" : undefined} onClick={() => { if (!isStarter || canCopyStarterPrompt) void copy(value, name); }} aria-live="polite"> {copied === name ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />} <span>{copied === name ? "Copied" : isStarter ? "Copy starter prompt" : "Copy"}</span> </button>; }} steps={clientSetupSteps([ ...((connection === "key" && client) || view === "api" ? [{ id: "key-step", text: stepReveal ? ( <div data-key-reveal> {revealPanel(stepReveal, <button type="button" className="set-secondary" disabled={busy !== ""} onClick={() => { setRevealClosed(true); setCopied(""); }}>Back to steps</button>)} </div> ) : <> {view === "all" || (view === "client" && canMint === true) ? <div className="set-actions" style={{ marginTop: 0, justifyContent: "flex-start" }} aria-label="API key choices"> <button type="button" className="set-secondary" data-key-choice="create" aria-pressed={shownKeyChoice === "create"} disabled={canMint !== true || busy !== ""} onClick={() => { setKeyChoice("create"); resetVerification(); }}>Create a new key</button> <button type="button" className="set-secondary" data-key-choice="saved" aria-pressed={shownKeyChoice === "saved"} disabled={!keys?.some(keyIsActive) || busy !== ""} onClick={() => { setKeyChoice("saved"); resetVerification(); }}>Use a saved key</button> </div> : null} {keysError ? ( <div role="alert"> <p className="set-help">{keysError}</p> <div className="set-actions"><button type="button" className="set-secondary" disabled={busy !== ""} onClick={() => void load()}>Try again</button></div> </div> ) : keys === null ? ( <SettingsSkeleton label="Loading API key settings" /> ) : keys.length === 0 ? ( <p className="set-help">{view === "client" ? "No saved API keys." : "You have no saved keys yet, so create one here."}</p> ) : !keys.some(keyIsActive) ? ( <p className="set-help">{view === "client" ? "No active API keys." : "No saved key is active. Create one or update its expiry below."}</p> ) : null} {canMint === false ? ( <p className="set-help">Creating API keys requires AI apps access. Ask an administrator for access</p> ) : null} {(shownKeyChoice === "create" || view === "api") && canMint === true ? ( <form className="external-divider" onSubmit={(event) => void create(event)}> <div className="set-field"><label className="set-label" htmlFor="set-external-label">Label</label> <input id="set-external-label" className="set-input" type="text" maxLength={80} value={label} autoComplete="off" placeholder="Reporting SDK" onChange={(event) => setLabel(event.currentTarget.value)} /></div> <div className="set-field"><label className="set-label" htmlFor="set-external-access">Access</label> <select id="set-external-access" className="pg-select" value={access} onChange={(event) => setAccess(event.currentTarget.value as Access)}> <option value="read">Read only</option><option value="readwrite">Read and write</option> </select></div> <div className="set-field"><label className="set-label" htmlFor="set-external-databases">Resources</label> <select id="set-external-databases" className="pg-select" value={databaseMode} onChange={(event) => setDatabaseMode(event.currentTarget.value as "all" | "subset")}> <option value="all">All databases</option><option value="subset">Selected databases</option> </select></div> {databaseMode === "subset" ? databaseChecks(selectedDatabases, setSelectedDatabases) : null} <ExpiryPresets id="set-external-expiry" value={expiryPreset} onChange={setExpiryPreset} /> <div className="set-actions"><button type="submit" className="set-primary" disabled={busy !== ""}> {busy === "create" ? "Creating…" : "Create API key"}</button></div> </form> ) : null} {shownKeyChoice === "saved" && client && keys && keys.length > 0 ? ( <div className="set-field external-divider"> <label className="set-label" htmlFor="external-saved-key">Saved key</label> <select id="external-saved-key" ref={savedKeySelect} className="pg-select" value={selectedKey?.id ?? ""} disabled={busy !== ""} aria-describedby="external-saved-key-help" onChange={(event) => chooseKey(event.currentTarget.value)}> <option value="">Choose a key</option> {keys.map((key) => ( <option key={key.id} value={key.id}> {key.label} · {key.access === "read" ? "Read only" : "Read and write"} · {key.expires_at ? "Expires " + when(key.expires_at) : "No expiry"} {key.revoked_at ? " (Revoked)" : !keyIsActive(key) ? " (Expired)" : ""} </option> ))} </select> <p id="external-saved-key-help" className="set-help"> {sharedSteps ? instruction(sharedSteps.keySetup.saved) : null} </p> {verificationReveal && view !== "client" ? <p className="set-help">{sharedSteps?.keySetup.saveNew}</p> : null} </div> ) : null} {view === "client" && onOpenApi ? ( <div className="set-actions"><button type="button" className="set-secondary" disabled={busy !== ""} onClick={onOpenApi}>API key settings</button></div> ) : null} </> }] : []), ], [ ...(view !== "api" && client?.skill && connection && sharedSteps ? [guideStep(sharedSteps.skill)] : []), ...(view !== "api" && client && connection && sharedSteps ? [{ text: <> {connection === "key" ? ( <> {selectedKey ? <p className="set-help">Key: {selectedKey.label}</p> : null} {verificationReveal ? <p className="set-help">{sharedSteps.verification.newKey}</p> : ( <div className="set-field"> <label className="set-label" htmlFor="external-verify-key">Saved API key</label> <input id="external-verify-key" className="set-input" type="password" value={verifySecret} autoComplete="off" spellCheck={false} disabled={busy !== "" || canMint !== true} aria-describedby="external-verify-key-help" onChange={(event) => { resetVerification(); setVerifySecret(event.currentTarget.value); }} /> <p id="external-verify-key-help" className="set-help">{sharedSteps.verification.savedKey}</p> </div> )} <p className="set-help">{sharedSteps.verification.key}</p> </> ) : ( <GuideInstruction text={instruction(sharedSteps.verification.mcp)} /> )} <div className="set-actions"> {connection === "key" ? ( <button type="button" className="set-primary" data-verify="key" disabled={busy !== "" || canMint !== true || !(verificationReveal?.secret || verifySecret.trim())} onClick={() => void verifyKey()}>{busy === "verify:key" ? "Verifying…" : "Verify API key"}</button> ) : ( <button type="button" className="set-primary" data-verify="mcp" disabled={busy !== ""} onClick={() => void verifyMcp()}>{busy === "verify:mcp" ? "Checking…" : "Verify sign-in"}</button> )} </div> {verifyResult ? ( <p className={`external-verification-result ${verifyResult.state === "failed" ? "set-error" : "set-notice"}`} role="status" data-verify-result data-verify-state={verifyResult.state} data-verify-cause={verifyResult.cause}> {verifyResult.message} </p> ) : null} </> }] : []), ...(starterPrompt ? [{ id: "starter-prompt", text: "Starter prompt", block: starterPrompt, copyValue: starterPrompt, hint: canCopyStarterPrompt ? undefined : "Verify the connection to copy the starter prompt." }] : []), ])} /> : null} </div> </ConnectionWizard> : null} {revealCard} {view !== "client" ? <section className="set-card" data-owner-key-verify aria-labelledby="external-verify-title" aria-busy={busy === "verify:key"}> <h2 id="external-verify-title" className="set-h4">Verify</h2> {keysError ? <div className="set-error" role="alert"> <span>Could not load API key access</span> <button type="button" className="set-secondary" onClick={() => void load()}>Retry</button> </div> : canMint === null ? <SettingsSkeleton label="Loading Verify access" /> : canMint === false ? <p className="set-help"> Verifying API keys requires AI apps access. Ask an administrator for access </p> : <form onSubmit={(event) => { event.preventDefault(); void verifyKey(); }}> <div className="set-field"> <label className="set-label" htmlFor="external-owner-verify-key">API key</label> <input id="external-owner-verify-key" className="set-input" type="password" value={verifySecret} autoComplete="off" spellCheck={false} disabled={busy !== ""} aria-describedby="external-owner-verify-help" onChange={(event) => { resetVerification(); setVerifySecret(event.currentTarget.value); }} /> <p id="external-owner-verify-help" className="set-help">Paste your saved key, including a revoked or expired key</p> </div> <div className="set-actions"> <button type="submit" className="set-primary" data-verify="key" disabled={busy !== "" || !verifySecret.trim()}> {busy === "verify:key" ? "Verifying…" : "Verify API key"} </button> </div> </form>} {verifyResult ? <p className={verifyResult.state === "failed" ? "set-error" : "set-notice"} role="status" data-verify-result data-verify-state={verifyResult.state} data-verify-cause={verifyResult.cause}> {verifyResult.message} </p> : null} </section> : null} {view !== "api" && visibleConnections.length > 0 ? ( /* HOTFIX 2026-09-24 (owner: the AI connections list "is really ugly, let's make it look like a Grid view"). One row per connection in the Data grid's own look: row numbers, a washed header, hairline cells and a status pill (`index.css` `.ea-grid`). */ <section className="set-card"> <h2 className="set-h4">AI connections</h2> <div className="ea-grid" role="region" aria-label="AI connections" tabIndex={0}> <table className="ea-grid-table"> <thead> <tr> <th scope="col" className="ea-grid-num"><span className="ea-grid-sr">Row</span></th> <th scope="col">AI app</th> <th scope="col">Status</th> <th scope="col">Access</th> <th scope="col">Databases</th> <th scope="col">Connected</th> <th scope="col">Last used</th> <th scope="col" className="ea-grid-act"><span className="ea-grid-sr">Actions</span></th> </tr> </thead> <tbody> {visibleConnections.map((connection, index) => ( <tr key={connection.id}> <td className="ea-grid-num">{index + 1}</td> <td> <span className="ea-grid-app"> {connection.clientId ? <AiClientMark id={connection.clientId} size={16} /> : null} <span>{connection.label || "Unnamed AI app"}</span> </span> </td> <td><span className={`ea-grid-pill is-${connection.status}`}>{connectionLabel(connection)}</span></td> <td>{connection.access === null ? "" : connection.access === "read" ? "Read only" : "Read and write"}</td> <td>{connection.databases === null ? "" : databaseLabels(connection.databases)}</td> <td>{when(connection.created)}</td> <td>{when(connection.last_used)}</td> <td className="ea-grid-act"> {connection.status === "connected" ? ( <button type="button" className="ea-grid-btn" disabled={busy !== ""} onClick={() => void disconnect(connection)}> {busy === `disconnect:${connection.client}` ? "Disconnecting…" : "Disconnect"} </button> ) : null} </td> </tr> ))} </tbody> </table> </div> </section> ) : null} {view !== "client" ? <> <div className="set-perm-sect"><h2 className="set-h4">API keys</h2></div> {keysError ? <div className="set-error" role="alert"><span title={keysError}>Could not load API keys.</span> <button type="button" className="set-secondary" disabled={busy !== ""} onClick={() => void load()}>Retry</button></div> : keys === null ? <SettingsSkeleton label="Loading API keys" /> : keys.length === 0 ? <p className="set-help">You have no API keys yet.</p> : ( <div aria-label="Active API keys"> {keys.map((key) => ( <section className="set-card" key={key.id}> {editing === key.id && editDraft ? ( <form onSubmit={(event) => void saveEdit(event)}> <h2 className="set-h4">Edit API key</h2> <div className="set-field"><label className="set-label" htmlFor={`key-label-${key.id}`}>Label</label> <input id={`key-label-${key.id}`} className="set-input" maxLength={80} value={editDraft.label} onChange={(event) => setEditDraft({ ...editDraft, label: event.currentTarget.value })} /></div> <div className="set-field"><label className="set-label" htmlFor={`key-access-${key.id}`}>Access</label> <select id={`key-access-${key.id}`} className="pg-select" value={editDraft.access} onChange={(event) => setEditDraft({ ...editDraft, access: event.currentTarget.value as Access })}> <option value="read">Read only</option><option value="readwrite">Read and write</option> </select></div> <div className="set-field"><label className="set-label" htmlFor={`key-databases-${key.id}`}>Resources</label> <select id={`key-databases-${key.id}`} className="pg-select" value={editDraft.databaseMode} onChange={(event) => setEditDraft({ ...editDraft, databaseMode: event.currentTarget.value as "all" | "subset" })}> <option value="all">All databases</option><option value="subset">Selected databases</option> </select></div> {editDraft.databaseMode === "subset" ? databaseChecks(editDraft.databases, (databases) => setEditDraft({ ...editDraft, databases })) : null} {keyExpiryLabel(key) === "Expired" ? <p className="set-help">Expired</p> : null} <ExpiryPresets id={`key-expiry-${key.id}`} value={editDraft.expiryPreset} keepCurrent onChange={(expiryPreset) => setEditDraft({ ...editDraft, expiryPreset })} /> <div className="set-actions"> <button type="submit" className="set-primary" disabled={busy === `edit:${key.id}`}> {busy === `edit:${key.id}` ? "Saving…" : "Save changes"}</button> <button type="button" className="set-secondary" onClick={() => { setEditing(null); setEditDraft(null); }}>Cancel</button> </div> </form> ) : ( <> <h2 className="set-h4">{key.label}</h2> <div className="pg-drill-row"><span className="pg-drill-key">Access</span> <span className="pg-drill-val">{key.access === "read" ? "Read only" : "Read and write"}</span></div> <div className="pg-drill-row"><span className="pg-drill-key">Resources</span> <span className="pg-drill-val">{databaseLabels(key.databases)}</span></div> <div className="pg-drill-row"><span className="pg-drill-key">Expiry</span> <span className="pg-drill-val">{keyExpiryLabel(key)}</span></div> <div className="pg-drill-row"><span className="pg-drill-key">Last used</span> <span className="pg-drill-val">{when(key.last_used)}</span></div> {keyIsActive(key) ? <KeyOpenApiRow documentUrl={openApiUrl} renderCode={(value, name, content) => codeBlock(value, `openapi:${key.id}:${name}`, content)} /> : null} <div className="set-actions"> <button type="button" className="set-secondary" onClick={() => { setEditing(key.id); setEditDraft(draftFor(key)); }}>Edit</button> <button type="button" className="set-secondary" disabled={busy === `rotate:${key.id}`} onClick={() => void rotate(key)}>{busy === `rotate:${key.id}` ? "Rotating…" : "Rotate"}</button> <button type="button" className="set-secondary kc-danger" disabled={busy === `revoke:${key.id}`} onClick={() => void revoke(key)}>{busy === `revoke:${key.id}` ? "Revoking…" : "Revoke"}</button> </div> </> )} </section> ))} </div> )} </> : null} </div> ); }
// settings / ExternalAccessPane.tsx - W63-T06, rulings R4/R14, contract C7.
//
// This is the shared setup pane opened by the Connectors directory. OAuth clients receive the remote
// MCP URL; API-key secrets appear only in the one-time reveal returned by create or rotate. All
// editable metadata is seeded again from the server response.
//
// Setup instructions share one numbered list. Every AI client receives the public starter prompt.
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { FormEvent, ReactNode } from "react";
import { Copy } from "@phosphor-icons/react/dist/csr/Copy";
import { Check } from "@phosphor-icons/react/dist/csr/Check";
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant } from "../apiContract";
import { Mark } from "../shell/Brand";
import { AiClientMark } from "./aiClientMarks";
import { KeyOpenApiRow, openApiDocumentUrl } from "./KeyOpenApiRow";
import { ExpiryPresets, presetToExpiresAt } from "./ExpiryPresets";
import type { ExpiryPreset } from "./ExpiryPresets";
import { parseTutorialGuide } from "../connectors/ConnectTutorial";
import type { TutorialGuide } from "../connectors/ConnectTutorial";
import "../connectors/connectors.css";
import "../styles/sdlc73/connectors.css";
type Access = "read" | "readwrite";
type ResourceScope = string[] | "all";
type ConnectionKind = "mcp" | "key";
// Copyable instructions never interpolate a stored credential.
interface StepAction { label: string; url: string }
export interface GuideStep {
id?: string;
title?: string;
text: ReactNode;
block?: string;
copyValue?: string;
action?: StepAction;
hint?: string;
details?: readonly GuideStep[];
}
function GuideInstruction({ text }: { text: string }) {
// Split only at an existing sentence or sequencing clause, keeping every character.
const boundary = /[.!?](?=\s+[A-Z])|,(?=\s+then\b)/.exec(text);
const end = boundary ? boundary.index + 1 : text.length;
return <p className="external-step-instruction">
<span className="external-step-lead">{text.slice(0, end)}</span>
{end < text.length ? <span className="external-step-detail">{text.slice(end)}</span> : null}
</p>;
}
// S70-T09: the AI setup and connector tutorials share this actual frame and guide renderer.
// Each caller owns its steps, fields and actions; the frame makes no requests.
export function GuideSteps({ steps, tutorial, finalSteps = [], renderCopy, mode = "full" }: {
steps: readonly GuideStep[];
tutorial?: TutorialGuide;
finalSteps?: readonly GuideStep[];
renderCopy?: (value: string, index: number, step: GuideStep) => ReactNode;
/** Short guides keep preparation and test limits outside the numbered instructions. */
mode?: "full" | "short";
}) {
const body: readonly GuideStep[] = tutorial && mode === "full" ? [
{ id: "tutorial-need", text: `What you need: ${tutorial.need}` },
...steps,
...(tutorial.testNote ? [{ id: "tutorial-test", text: `Test: ${tutorial.testNote}` }] : []),
{ id: "tutorial-failure", text: `If it fails: ${tutorial.failureAction}` },
] : steps;
const entries = [...body, ...finalSteps];
if (!entries.length) return null;
const content = (entry: GuideStep, index: number): ReactNode => {
const copyValue = entry.copyValue ?? entry.block;
return <>
<div className={`external-step-content${copyValue && renderCopy ? "" : " external-step-content--wide"}`}>
{entry.title ? <p className="external-step-title">{entry.title}</p>
: typeof entry.text === "string" ? <GuideInstruction text={entry.text} /> : entry.text}
</div>
{copyValue ? renderCopy?.(copyValue, index, entry) : null}
{entry.title ? <p className="external-step-description">{entry.text}</p> : null}
{entry.block ? <pre className="external-step-code">{entry.block}</pre> : null}
{entry.hint ? <p className="external-step-hint" id={entry.id ? `${entry.id}-hint` : undefined}>
{entry.hint}
</p> : null}
{entry.action ? <a className="external-step-action" href={entry.action.url}
target="_blank" rel="noopener noreferrer">{entry.action.label}</a> : null}
{entry.details?.map((detail, detailIndex) => <div className="external-step-details" data-step-id={detail.id} key={detail.id ?? detailIndex}>
{content(detail, detailIndex)}
</div>)}
</>;
};
return <>
{tutorial && mode === "short" ? <p className="external-sub">{tutorial.need}</p> : null}
<ol className="external-steps" role="list" data-guide-renderer="GuideSteps" data-guide-mode={mode}>
{entries.map((entry, index) => {
return <li key={entry.id ?? index} data-step-id={entry.id}
className={entry.copyValue ? "external-step--copy-text" : undefined}>
<span className="external-step-number" aria-hidden="true">{index + 1}</span>
{content(entry, index)}
</li>;
})}
</ol>
{tutorial && mode === "short" ? <div className="external-guide-help">