import * as Effect from "effect/Effect"; import { loadControlPlaneOrigin } from "../configuration/control-plane.ts"; import type { CloudflareFetch } from "./cloudflare.ts"; import type { Env } from "./config.ts"; import { OAuthError, messages, safeCode } from "./errors.ts"; import { checkOrigin, form, privateResponse } from "./http-response.ts"; import { InvalidMetadata, isRegistryFailure } from "./installation-errors.ts"; import { installationId, parse, releaseIdentity, } from "./installation-metadata.ts"; import { installationRegistry } from "./registry-client.ts"; import { authenticatedPrincipal, selectedDeploymentGrant } from "./session.ts"; import { customerArtifact, type ArtifactLoader } from "./catalog.ts"; import { isDeploymentFailure } from "./deployment-errors.ts"; import { isDomainFailure } from "./domain-errors.ts"; import { setupDomain } from "./domain-setup.ts"; import { setupOpenRouter } from "./provider-setup.ts"; import { startInstallation, type InstallationCommand, } from "./start-installation.ts"; import { ownedInstallation } from "./installation-access.ts"; const json = (body: unknown, status = 200) => privateResponse(Response.json(body, { status })); const metadataMessages = { invalid_metadata: "This installation request is invalid.", installation_not_found: "Installation not found.", installation_conflict: "The installation changed or this request was already used. Reload and try again.", }; export function handleInstallations( request: Request, env: Env, network: CloudflareFetch = fetch, artifactLoader: ArtifactLoader = customerArtifact, ) { return Effect.gen(function* () { const url = new URL(request.url); if ( url.pathname !== "/api/releases/latest" && url.pathname !== "/api/installations" && !url.pathname.startsWith("/api/installations/") ) return null; const origin = loadControlPlaneOrigin(env); if (url.origin !== origin) return yield* new OAuthError("forbidden"); if (request.method !== "GET") yield* checkOrigin(request, origin); if (url.pathname === "/api/releases/latest" && request.method === "GET") { if (url.search) return yield* new InvalidMetadata(); const latest = yield* artifactLoader(); // Public and deliberately minimal: no installation, owner, account, // resource, operation, or grant metadata is exposed here. return Response.json(latest.identity, { headers: { "Cache-Control": "public, max-age=60" }, }); } const domain = /^\/api\/installations\/([a-f0-9]{32})\/domain(?:\/(zones|remove|retry))?$/.exec( url.pathname, ); if (domain) { if (url.search) return yield* new InvalidMetadata(); return yield* setupDomain(request, env, domain[1], domain[2], network); } const provider = /^\/api\/installations\/([a-f0-9]{32})\/providers\/openrouter$/.exec( url.pathname, ); if (provider && ["GET", "POST"].includes(request.method)) { if (url.search) return yield* new InvalidMetadata(); return yield* setupOpenRouter(request, env, provider[1], network); } const start = /^\/api\/installations\/([a-f0-9]{32})\/(start|recover|upgrade)$/.exec( url.pathname, ); if (start && request.method === "POST") { if (url.search) return yield* new InvalidMetadata(); const input = yield* form(request); if ( [...input.keys()].some( (key) => key !== "requestId" && !(start[2] === "upgrade" && key === "target"), ) || input.getAll("requestId").length !== 1 || (start[2] === "upgrade" && input.getAll("target").length !== 1) ) return yield* new InvalidMetadata(); const requestId = parse(installationId, input.get("requestId")); let command: InstallationCommand = { action: start[2] === "recover" ? "recover" : "start", }; if (start[2] === "upgrade") { try { command = { action: "upgrade", target: parse(releaseIdentity, JSON.parse(input.get("target")!)), }; } catch { return yield* new InvalidMetadata(); } } return json( { installation: yield* startInstallation( request, env, start[1], requestId, network, artifactLoader, command, ), }, 202, ); } if (url.pathname === "/api/installations" && request.method === "POST") { if (url.search) return yield* new InvalidMetadata(); const input = yield* form(request); if ( [...input.keys()].some((key) => key !== "requestId") || input.getAll("requestId").length !== 1 ) return yield* new InvalidMetadata(); const requestId = parse(installationId, input.get("requestId")); // Fresh account/grant authorization is needed to reserve deployment intent. // The credential returned by this seam stays outside metadata/DO arguments. const { principal } = yield* selectedDeploymentGrant( request, env, network, ); const record = yield* installationRegistry( env, principal.subject, ).reserve(principal.subject, principal.selectedAccountId!, requestId); return json({ installation: record }); } if (url.pathname === "/api/installations" && request.method === "GET") { if ( [...url.searchParams.keys()].some((key) => key !== "cursor") || url.searchParams.getAll("cursor").length > 1 ) return yield* new InvalidMetadata(); const cursor = url.searchParams.has("cursor") ? parse(installationId, url.searchParams.get("cursor")) : null; const principal = yield* authenticatedPrincipal(request, env); const page = yield* installationRegistry(env, principal.subject).list( principal.subject, cursor, ); const latest = yield* artifactLoader().pipe( Effect.catch(() => Effect.succeed(null)), ); return json({ ownerSubject: principal.subject, installations: page.installations, nextCursor: page.nextCursor, latestRelease: latest?.identity ?? null, upgradeFrom: latest?.compatibility.fromArtifacts ?? [], }); } if (request.method === "GET") { if (url.search) return yield* new InvalidMetadata(); const id = url.pathname.slice("/api/installations/".length); const installation = yield* ownedInstallation(request, env, id); const latest = yield* artifactLoader().pipe( Effect.catch(() => Effect.succeed(null)), ); return json({ installation, latestRelease: latest?.identity ?? null, upgradeFrom: latest?.compatibility.fromArtifacts ?? [], }); } return json({ error: "not_found" }, 404); }).pipe( Effect.catch((error) => Effect.succeed(installationFailure(error))), Effect.catchDefect((error) => Effect.succeed(installationFailure(error))), ); } function installationFailure(error: unknown) { if (isDomainFailure(error)) return json( { error: error.code }, error.code === "reauthorization_required" ? 401 : error.code === "account_denied" ? 403 : error.code === "invalid_hostname" ? 400 : ["resource_conflict", "attachment_outcome_unknown"].includes( error.code, ) ? 409 : 503, ); if (isDeploymentFailure(error)) return json( { error: error.code }, error.code === "account_denied" ? 403 : error.code === "reauthorization_required" ? 401 : 503, ); if (isRegistryFailure(error)) return json( { error: error.code, message: metadataMessages[error.code] }, error.code === "installation_not_found" ? 404 : error.code === "installation_conflict" ? 409 : 400, ); const code = safeCode(error); return json( { error: code, message: messages[code] }, code === "forbidden" ? 403 : code === "reauthorization_required" ? 401 : code === "account_denied" || code === "invalid_request" ? 400 : 503, ); }