import * as Effect from "effect/Effect"; import { PROVIDER_PURPOSE } from "../shared/bridge.ts"; import { signBridgeAssertion } from "./bridge.ts"; import { CloudflareAccount } from "./cloudflare-account.ts"; import { configuration, type Env } from "./config.ts"; import { AccountDenied, ReauthorizationRequired, SetupRequired, TemporarilyUnavailable, } from "./deployment-errors.ts"; import { form, privateResponse } from "./http-response.ts"; import { ownedInstallation } from "./installation-access.ts"; import { ensureModelGateway } from "./model-gateway.ts"; import { installationRegistry } from "./registry-client.ts"; import { bodyJson, withResponse } from "../server/http.ts"; import { authenticatedPrincipal, authorizedGrant, grantedAccounts, } from "./session.ts"; // Invoked only behind handleInstallations' exact-Origin mutation guard. export function setupOpenRouter( request: Request, env: Env, installationId: string, network: typeof fetch, ) { return Effect.gen(function* () { const record = yield* ownedInstallation(request, env, installationId); if (!record.installedRelease || !record.resources.runtimeOrigin) return yield* new SetupRequired(); const domain = yield* installationRegistry( env, record.ownerSubject, ).getDomain(record.ownerSubject, installationId); const publicOrigin = domain?.status === "active" ? domain.origin! : record.resources.runtimeOrigin; if (request.method === "GET") return privateResponse( Response.json({ ownerSubject: record.ownerSubject, installationId: record.installationId, accountId: record.accountId, runtimeOrigin: publicOrigin, }), ); if ([...(yield* form(request)).keys()].length) return yield* new SetupRequired(); const principal = yield* authenticatedPrincipal(request, env); const grant = yield* authorizedGrant(env, principal); const config = yield* configuration(env); const required = config.oauthCapabilities!.scopes.filter((scope) => scope.capabilities.includes("model-gateway"), ); if (required.some((scope) => !grant.scopes.includes(scope.id))) return yield* new ReauthorizationRequired(); // The installation, not the account-picker's current selection, fixes the // destination. Fresh account membership is still required after reconnect. const accounts = yield* grantedAccounts(env, principal, network); if (!accounts.some((account) => account.id === record.accountId)) return yield* new AccountDenied(); yield* ensureModelGateway( new CloudflareAccount(grant.accessToken, record.accountId, network), ); const assertion = yield* signBridgeAssertion(env, { aud: record.resources.runtimeOrigin, sub: record.ownerSubject, installationId: record.installationId, purpose: PROVIDER_PURPOSE, state: "openrouter", challenge: "enabled", }); // The management token and provider keys never enter this notification or // the browser. A signed receipt only enables this installation's provider. yield* withResponse( network, new URL("/auth/provider-enabled", record.resources.runtimeOrigin), { method: "POST", headers: { Authorization: `Bearer ${assertion}` }, }, 15_000, new TemporarilyUnavailable(), (response) => Effect.gen(function* () { if (!response.ok) return yield* new TemporarilyUnavailable(); const receipt = yield* bodyJson( response, 1024, new TemporarilyUnavailable(), ); if ( !receipt || typeof receipt !== "object" || !("provider" in receipt) || !("enabled" in receipt) || receipt.provider !== "openrouter" || receipt.enabled !== true ) return yield* new TemporarilyUnavailable(); }), ); return privateResponse( Response.json({ returnTo: new URL("/settings", publicOrigin).href, }), ); }); }