Something went wrong. Try again.
This repository has no description
Something went wrong. Try again.
7.4 kB · 231 lines
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232import { 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<Record<string, unknown>> { 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<State>("loading"); const [details, setDetails] = useState<ProviderDetails | null>(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 ( <LayerCard className="connect-card"> <div className="intro"> <h2>Enable OpenRouter</h2> <p> Connect OpenRouter to this installation through Cloudflare AI Gateway. </p> </div> {state === "loading" && ( <p role="status">Checking installation access…</p> )} {state === "provisioning" && ( <p role="status">Enabling OpenRouter… Do not close this page.</p> )} {state === "success" && ( <p role="status">OpenRouter enabled. Returning to model settings…</p> )} {error && <p role="alert">{error}</p>} {state === "confirm" && details && ( <> <p> Confirm setup for installation {details.installationId.slice(0, 8)}{" "} in Cloudflare account {details.accountId}. </p> <div className="actions"> <Button variant="primary" onClick={() => void enable()}> Enable OpenRouter </Button> <a className="open-flarebot" href={new URL("/settings", details.runtimeOrigin).href} > Cancel </a> </div> </> )} {state === "error" && ( <div className="actions"> <Button variant="secondary" onClick={() => (details ? void enable() : void load())} > Retry </Button> </div> )} {state === "reconnect" && ( <> <p role="alert"> Reconnect Cloudflare to confirm ownership and continue setup. </p> <form action="/auth/start" method="post"> <input type="hidden" name="providerInstallationId" value={installationId} /> <Button type="submit" variant="primary"> Reconnect Cloudflare </Button> </form> </> )} </LayerCard> );}