import { useEffect, useRef, useState } from "octane"; import { Button } from "octane-kumo/components/button"; import { LayerCard } from "octane-kumo/components/layer-card"; interface ProviderDetails { installationId: string; accountId: string; runtimeOrigin: string; } type State = "loading" | "confirm" | "provisioning" | "error" | "reconnect" | "success"; function safeMessage(status: number, code: unknown) { if (status === 403) return "You do not have permission to manage this installation."; if (status === 404) return "This installation could not be found. Check the setup link and try again."; if (status === 503 && code === "resource_conflict") return "OpenRouter setup conflicts with an existing Cloudflare resource. Resolve the conflicting resource, then retry."; if (status === 503 && code === "setup_required") return "This installation needs setup or an upgrade before OpenRouter can be enabled."; return "OpenRouter setup is temporarily unavailable. Try again."; } function trustedRuntime(value: string) { try { const url = new URL(value); const localDevelopment = typeof window !== "undefined" && (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1"); return ( !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash && (url.protocol === "https:" || (url.protocol === "http:" && localDevelopment && ["localhost", "127.0.0.1"].includes(url.hostname))) ); } catch { return false; } } async function responseJson( response: Response, ): Promise> { try { const value = await response.json(); return typeof value === "object" && value !== null ? value : {}; } catch { return {}; } } export function ProviderSetup({ installationId }: { installationId: string }) { const [state, setState] = useState("loading"); const [details, setDetails] = useState(null); const [error, setError] = useState(""); const generation = useRef(0); const endpoint = `/api/installations/${installationId}/providers/openrouter`; async function load() { const version = ++generation.current; setState("loading"); setError(""); try { const response = await fetch(endpoint, { credentials: "same-origin", cache: "no-store", signal: AbortSignal.timeout(15_000), }); const data = await responseJson(response); if (version !== generation.current) return; if (response.status === 401) return setState("reconnect"); if (!response.ok) { setError(safeMessage(response.status, data.error)); return setState("error"); } if ( data.installationId !== installationId || typeof data.accountId !== "string" || !/^[a-f0-9]{32}$/.test(data.accountId) || typeof data.runtimeOrigin !== "string" || !trustedRuntime(data.runtimeOrigin) ) throw new Error("Invalid setup response"); setDetails(data as unknown as ProviderDetails); setState("confirm"); } catch { if (version === generation.current) { setError( "Could not check this installation. Check your connection and try again.", ); setState("error"); } } } useEffect(() => { void load(); return () => { generation.current++; }; }, [installationId]); async function enable() { if (state === "provisioning") return; const version = ++generation.current; setState("provisioning"); setError(""); try { const response = await fetch(endpoint, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "", signal: AbortSignal.timeout(60_000), }); const data = await responseJson(response); if (version !== generation.current) return; if (response.status === 401) return setState("reconnect"); if (!response.ok) { setError(safeMessage(response.status, data.error)); return setState("error"); } if (typeof data.returnTo !== "string" || !details) throw new Error("Invalid setup response"); const destination = new URL(data.returnTo); const runtime = new URL(details.runtimeOrigin); const localDevelopment = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1"; if ( destination.origin !== runtime.origin || destination.username || destination.password || destination.pathname !== "/settings" || destination.search || destination.hash || (destination.protocol !== "https:" && !( destination.protocol === "http:" && localDevelopment && ["localhost", "127.0.0.1"].includes(destination.hostname) )) ) throw new Error("Unsafe setup destination"); setState("success"); window.location.assign(destination.href); } catch { if (version === generation.current) { setError( "OpenRouter may not have been enabled. Check your connection and retry setup safely.", ); setState("error"); } } } return (

Enable OpenRouter

Connect OpenRouter to this installation through Cloudflare AI Gateway.

{state === "loading" && (

Checking installation access…

)} {state === "provisioning" && (

Enabling OpenRouter… Do not close this page.

)} {state === "success" && (

OpenRouter enabled. Returning to model settings…

)} {error &&

{error}

} {state === "confirm" && details && ( <>

Confirm setup for installation {details.installationId.slice(0, 8)}{" "} in Cloudflare account {details.accountId}.

Cancel
)} {state === "error" && (
)} {state === "reconnect" && ( <>

Reconnect Cloudflare to confirm ownership and continue setup.

)}
); }