import { HttpApiBuilder, HttpServerRequest, HttpServerResponse, } from "@effect/platform"; import type { ExecutionInteraction, Source, ScopeId as WorkspaceId, ScopeOauthClient as WorkspaceOauthClient, } from "@executor/platform-sdk/schema"; import type { ExecutorMcpSourceInput, ExecutorSourceInput, } from "@executor/platform-sdk"; import * as Effect from "effect/Effect"; import { sourceAdapterRequiresInteractiveConnect, } from "@executor/platform-sdk/runtime"; import { ScopeOauthClientIdSchema as WorkspaceOauthClientIdSchema } from "@executor/platform-sdk/schema"; import { ControlPlaneBadRequestError, ControlPlaneNotFoundError, ControlPlaneStorageError, } from "../errors"; import { ExecutorApi } from "../api"; import type { ConnectSourcePayload } from "./api"; import { getControlPlaneExecutor, resolveRequestedLocalWorkspace, } from "../local-context"; const readHeader = (headers: unknown, name: string): string | null => { if (headers == null || typeof headers !== "object") { return null; } const record = headers as Record; const exact = record[name]; if (typeof exact === "string" && exact.length > 0) { return exact; } const lower = record[name.toLowerCase()]; if (typeof lower === "string" && lower.length > 0) { return lower; } return null; }; const resolveRequestOrigin = (request: { url: string; headers: unknown; }): string | null => { try { return new URL(request.url).origin; } catch { const forwardedHost = readHeader(request.headers, "x-forwarded-host"); const host = forwardedHost ?? readHeader(request.headers, "host"); if (!host) { return null; } const forwardedProto = readHeader(request.headers, "x-forwarded-proto"); const protocol = forwardedProto && forwardedProto.length > 0 ? forwardedProto : "http"; return `${protocol}://${host}`; } }; const toBadRequestError = (operation: string, cause: unknown) => { const message = cause instanceof Error ? cause.message : String(cause); return new ControlPlaneBadRequestError({ operation, message, details: message, }); }; const isInteractiveConnectPayload = ( payload: ConnectSourcePayload, ): payload is Extract => payload.kind === undefined || sourceAdapterRequiresInteractiveConnect(payload.kind); const nullToUndefined = (value: T | null | undefined): T | undefined => value ?? undefined; const toWorkspaceOauthClientId = ( value: string | null | undefined, ): WorkspaceOauthClient["id"] | null | undefined => value == null ? value : WorkspaceOauthClientIdSchema.make(value); const toExecutorSourceInput = ( payload: ConnectSourcePayload, ): ExecutorSourceInput | null => { if (isInteractiveConnectPayload(payload)) { return null; } switch (payload.kind) { case "openapi": return { kind: "openapi", endpoint: payload.endpoint, specUrl: payload.specUrl, name: payload.name, namespace: payload.namespace, importAuthPolicy: nullToUndefined(payload.importAuthPolicy), importAuth: payload.importAuth, auth: payload.auth, }; case "graphql": return { kind: "graphql", endpoint: payload.endpoint, name: payload.name, namespace: payload.namespace, importAuthPolicy: nullToUndefined(payload.importAuthPolicy), importAuth: payload.importAuth, auth: payload.auth, }; case "google_discovery": return { kind: "google_discovery", service: payload.service, version: payload.version, discoveryUrl: payload.discoveryUrl, scopes: payload.scopes, scopeOauthClientId: toWorkspaceOauthClientId( payload.scopeOauthClientId, ), oauthClient: payload.oauthClient, name: payload.name, namespace: payload.namespace, importAuthPolicy: nullToUndefined(payload.importAuthPolicy), importAuth: payload.importAuth, auth: payload.auth, }; } }; const toExecutorMcpSourceInput = ( payload: Extract, baseUrl: string | null, ): ExecutorMcpSourceInput => ({ endpoint: payload.endpoint, name: payload.name, namespace: payload.namespace, transport: payload.transport, queryParams: payload.queryParams, headers: payload.headers, command: payload.command, args: payload.args, env: payload.env, cwd: payload.cwd, baseUrl, }); const escapeHtml = (value: string): string => value .replaceAll("&", "&") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll('"', """) .replaceAll("'", "'"); const serializeJsonForScript = (value: unknown): string => JSON.stringify(value) .replaceAll("<", "\\u003c") .replaceAll(">", "\\u003e") .replaceAll("&", "\\u0026"); const SOURCE_OAUTH_RESULT_STORAGE_KEY_PREFIX = "executor:oauth-result:"; const credentialPageDocument = (input: { title: string; eyebrow: string; message: string; sourceLabel: string; endpoint: string; interactionId: string; error?: string; state?: "pending" | "stored" | "continued" | "cancelled" | "inactive"; }) => ` ${escapeHtml(input.title)}
${escapeHtml(input.state ?? "pending")}

${escapeHtml(input.title)}

${escapeHtml(input.message)}


Source ${escapeHtml(input.sourceLabel)}
API endpoint
${escapeHtml(input.endpoint)}
Interaction ${escapeHtml(input.interactionId)}

${input.error ? `

${escapeHtml(input.error)}

` : ""} ${ input.state === "stored" ? `

Credential stored

Executor resumed the source connection request. You can close this window.

` : input.state === "continued" ? `

Continuing without auth

Executor resumed the source connection without stored credentials. You can close this window.

` : input.state === "cancelled" ? `

Request cancelled

Executor was notified. You can close this window.

` : input.state === "inactive" ? `

No longer active

This credential request has expired. Start a new source connection flow if needed.

` : `

Add a token to enable authenticated requests, or continue without auth if this API supports public access.

` }
`; const sourceOAuthPopupResultDocument = (input: { title: string; message: string; state: "stored" | "cancelled"; sessionId?: string | null; payload: | { type: "executor:source-oauth-result"; ok: true; sourceId: Source["id"]; } | { type: "executor:source-oauth-result"; ok: false; error: string; }; }) => ` ${escapeHtml(input.title)}
${escapeHtml(input.state === "stored" ? "connected" : "failed")}

${escapeHtml(input.title)}

${escapeHtml(input.message)}

`; const htmlResponse = ( html: string, status = 200, ): ReturnType => HttpServerResponse.html(html).pipe( HttpServerResponse.setStatus(status), ) as ReturnType; const credentialErrorResponse = (input: { title: string; message: string; status: number; }) => htmlResponse( credentialPageDocument({ title: input.title, eyebrow: "Executor", message: input.message, sourceLabel: "Unavailable", endpoint: "Unavailable", interactionId: "unavailable", state: "inactive", error: input.message, }), input.status, ); const credentialErrorStatus = ( error: | ControlPlaneBadRequestError | ControlPlaneNotFoundError | ControlPlaneStorageError, ) => error instanceof ControlPlaneNotFoundError ? 404 : error instanceof ControlPlaneBadRequestError ? 400 : 500; const credentialSubmitErrorResponse = (input: { workspaceId: WorkspaceId; sourceId: Source["id"]; interactionId: ExecutionInteraction["id"]; message: string; status: number; }) => resolveRequestedLocalWorkspace( "sources.credentialSubmit", input.workspaceId, ).pipe( Effect.flatMap((executor) => executor.local.credentials.get({ sourceId: input.sourceId, interactionId: input.interactionId, }), ), Effect.match({ onFailure: () => credentialErrorResponse({ title: "Source Credential Request Failed", message: input.message, status: input.status, }), onSuccess: (interaction) => htmlResponse( credentialPageDocument({ title: "Configure Source Access", eyebrow: "Executor", message: interaction.message, sourceLabel: interaction.sourceLabel, endpoint: interaction.endpoint, interactionId: interaction.interactionId, error: input.message, state: "pending", }), input.status, ), }), ); export const ExecutorSourcesLive = HttpApiBuilder.group( ExecutorApi, "sources", (handlers) => handlers .handle("discover", ({ payload }) => Effect.flatMap(getControlPlaneExecutor(), (executor) => executor.sources.discover({ url: payload.url, probeAuth: payload.probeAuth, }).pipe( Effect.catchAll((cause) => Effect.fail(toBadRequestError("sources.discover", cause)), ), ) ) ) .handle("connect", ({ path, payload }) => resolveRequestedLocalWorkspace( "sources.connect", path.workspaceId, ).pipe( Effect.flatMap((executor) => Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; const baseUrl = resolveRequestOrigin(request); if (isInteractiveConnectPayload(payload)) { return yield* executor.sources.connect( toExecutorMcpSourceInput(payload, baseUrl), ); } const sourceInput = toExecutorSourceInput(payload); if (sourceInput) { return yield* executor.sources.add(sourceInput, { baseUrl, }); } return yield* Effect.fail( toBadRequestError( "sources.connect", new Error("Unsupported source connect payload"), ), ); }).pipe( Effect.catchAll((cause) => Effect.fail(toBadRequestError("sources.connect", cause)), ), ), ), ), ) .handle("connectBatch", ({ path, payload }) => resolveRequestedLocalWorkspace( "sources.connectBatch", path.workspaceId, ).pipe( Effect.flatMap((executor) => Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; return yield* executor.sources.connectBatch({ ...payload, baseUrl: resolveRequestOrigin(request), }); }).pipe( Effect.catchAll((cause) => Effect.fail(toBadRequestError("sources.connectBatch", cause)), ), ), ), ), ) .handle("listWorkspaceOauthClients", ({ path, urlParams }) => resolveRequestedLocalWorkspace( "sources.listWorkspaceOauthClients", path.workspaceId, ).pipe( Effect.flatMap((executor) => executor.sources.oauthClients.list(urlParams.providerKey).pipe( Effect.catchAll((cause) => Effect.fail( toBadRequestError("sources.listWorkspaceOauthClients", cause), ), ), ) ), ), ) .handle("createWorkspaceOauthClient", ({ path, payload }) => resolveRequestedLocalWorkspace( "sources.createWorkspaceOauthClient", path.workspaceId, ).pipe( Effect.flatMap((executor) => executor.sources.oauthClients.create(payload).pipe( Effect.catchAll((cause) => Effect.fail( toBadRequestError( "sources.createWorkspaceOauthClient", cause, ), ), ), ) ), ), ) .handle("removeWorkspaceOauthClient", ({ path }) => resolveRequestedLocalWorkspace( "sources.removeWorkspaceOauthClient", path.workspaceId, ).pipe( Effect.flatMap((executor) => executor.sources.oauthClients.remove(path.oauthClientId).pipe( Effect.map((result) => ({ removed: result })), Effect.catchAll((cause) => Effect.fail( toBadRequestError( "sources.removeWorkspaceOauthClient", cause, ), ), ), ) ), ), ) .handle("removeProviderAuthGrant", ({ path }) => resolveRequestedLocalWorkspace( "sources.removeProviderAuthGrant", path.workspaceId, ).pipe( Effect.flatMap((executor) => executor.sources.providerGrants.remove(path.grantId).pipe( Effect.map((result) => ({ removed: result })), Effect.catchAll((cause) => Effect.fail( toBadRequestError( "sources.removeProviderAuthGrant", cause, ), ), ), ) ), ), ) .handle("list", ({ path }) => resolveRequestedLocalWorkspace("sources.list", path.workspaceId).pipe( Effect.flatMap((executor) => executor.sources.list()), ), ) .handle("create", ({ path, payload }) => resolveRequestedLocalWorkspace("sources.create", path.workspaceId).pipe( Effect.flatMap((executor) => executor.sources.create(payload)), ), ) .handle("get", ({ path }) => resolveRequestedLocalWorkspace("sources.get", path.workspaceId).pipe( Effect.flatMap((executor) => executor.sources.get(path.sourceId)), ), ) .handle("inspection", ({ path }) => resolveRequestedLocalWorkspace( "sources.inspection", path.workspaceId, ).pipe( Effect.flatMap((executor) => executor.sources.inspection.get(path.sourceId)), ), ) .handle("inspectionTool", ({ path }) => resolveRequestedLocalWorkspace( "sources.inspection_tool", path.workspaceId, ).pipe( Effect.flatMap((executor) => executor.sources.inspection.tool({ sourceId: path.sourceId, toolPath: path.toolPath, }), ), ), ) .handle("inspectionDiscover", ({ path, payload }) => resolveRequestedLocalWorkspace( "sources.inspection_discover", path.workspaceId, ).pipe( Effect.flatMap((executor) => executor.sources.inspection.discover({ sourceId: path.sourceId, payload, }), ), ), ) .handle("update", ({ path, payload }) => resolveRequestedLocalWorkspace("sources.update", path.workspaceId).pipe( Effect.flatMap((executor) => executor.sources.update(path.sourceId, payload)), ), ) .handle("remove", ({ path }) => resolveRequestedLocalWorkspace("sources.remove", path.workspaceId).pipe( Effect.flatMap((executor) => executor.sources.remove(path.sourceId)), Effect.map((removed) => ({ removed })), ), ) .handle("credentialPage", ({ path, urlParams }) => resolveRequestedLocalWorkspace( "sources.credentialPage", path.workspaceId, ).pipe( Effect.flatMap((executor) => executor.local.credentials.get({ sourceId: path.sourceId, interactionId: urlParams.interactionId, }), ), Effect.map((interaction) => htmlResponse( credentialPageDocument({ title: "Configure Source Access", eyebrow: "Executor", message: interaction.message, sourceLabel: interaction.sourceLabel, endpoint: interaction.endpoint, interactionId: interaction.interactionId, state: interaction.status === "pending" ? "pending" : "inactive", }), ), ), Effect.catchAll((error) => Effect.succeed( credentialErrorResponse({ title: error instanceof ControlPlaneNotFoundError ? "Source Credential Request Unavailable" : "Source Credential Request Failed", message: error instanceof Error ? error.message : "Source credential request failed", status: error instanceof ControlPlaneNotFoundError || error instanceof ControlPlaneStorageError || error instanceof ControlPlaneBadRequestError ? credentialErrorStatus(error) : 500, }), ), ), ), ) .handle("credentialSubmit", ({ path, urlParams, payload }) => resolveRequestedLocalWorkspace( "sources.credentialSubmit", path.workspaceId, ).pipe( Effect.flatMap((executor) => executor.local.credentials.submit({ sourceId: path.sourceId, interactionId: urlParams.interactionId, action: payload.action === "cancel" ? "cancel" : payload.action === "continue" ? "continue" : "submit", token: payload.token, }), ), Effect.map((result) => htmlResponse( credentialPageDocument({ title: result.kind === "stored" ? "Source Credential Stored" : result.kind === "continued" ? "Source Access Updated" : "Source Credential Request Cancelled", eyebrow: "Executor", message: result.kind === "stored" ? "Executor stored the credential and resumed the source connection." : result.kind === "continued" ? "Executor resumed the source connection without stored credentials." : "Executor cancelled the source credential request.", sourceLabel: result.sourceLabel, endpoint: result.endpoint, interactionId: urlParams.interactionId, state: result.kind === "stored" ? "stored" : result.kind === "continued" ? "continued" : "cancelled", }), ), ), Effect.catchAll((error) => { if (error instanceof ControlPlaneBadRequestError) { return credentialSubmitErrorResponse({ workspaceId: path.workspaceId, sourceId: path.sourceId, interactionId: urlParams.interactionId, message: error.message, status: credentialErrorStatus(error), }); } return Effect.succeed( credentialErrorResponse({ title: error instanceof ControlPlaneNotFoundError ? "Source Credential Request Unavailable" : "Source Credential Request Failed", message: error instanceof Error ? error.message : "Source credential request failed", status: error instanceof ControlPlaneNotFoundError || error instanceof ControlPlaneStorageError ? credentialErrorStatus(error) : 500, }), ); }), ), ) .handle("credentialComplete", ({ path, urlParams }) => resolveRequestedLocalWorkspace( "sources.credentialComplete", path.workspaceId, ).pipe( Effect.flatMap((executor) => executor.local.credentials.complete({ sourceId: path.sourceId, state: urlParams.state, code: urlParams.code, error: urlParams.error, errorDescription: urlParams.error_description, }), ), Effect.map((completed) => htmlResponse( sourceOAuthPopupResultDocument({ title: "Source connected", message: `Source connected: ${completed.source.id}. You can close this window.`, state: "stored", sessionId: completed.sessionId, payload: { type: "executor:source-oauth-result", ok: true, sourceId: completed.source.id, }, }), ), ), Effect.catchAll((error) => Effect.succeed( htmlResponse( sourceOAuthPopupResultDocument({ title: "OAuth failed", message: error instanceof Error ? error.message : "Failed completing OAuth", state: "cancelled", payload: { type: "executor:source-oauth-result", ok: false, error: error instanceof Error ? error.message : "Failed completing OAuth", }, }), 500, ), ), ), ), ) .handle("providerOauthComplete", ({ path, urlParams }) => resolveRequestedLocalWorkspace( "sources.providerOauthComplete", path.workspaceId, ).pipe( Effect.flatMap((executor) => Effect.gen(function* () { const completed = yield* executor.oauth.completeProviderCallback({ scopeId: path.workspaceId, state: urlParams.state, code: urlParams.code, error: urlParams.error, errorDescription: urlParams.error_description, }); const primarySource = completed.sources[0] ?? null; return htmlResponse( sourceOAuthPopupResultDocument({ title: "Sources connected", message: `Connected ${completed.sources.length} source${completed.sources.length === 1 ? "" : "s"}. You can close this window.`, state: "stored", sessionId: completed.sessionId, payload: { type: "executor:source-oauth-result", ok: true, sourceId: primarySource?.id ?? ("src_oauth_complete" as Source["id"]), }, }), ); }).pipe( Effect.catchAll((error) => Effect.succeed( htmlResponse( sourceOAuthPopupResultDocument({ title: "OAuth failed", message: error instanceof Error ? error.message : "Failed completing OAuth", state: "cancelled", payload: { type: "executor:source-oauth-result", ok: false, error: error instanceof Error ? error.message : "Failed completing OAuth", }, }), 500, ), ), ), ), ), Effect.catchAll((error) => Effect.succeed( htmlResponse( sourceOAuthPopupResultDocument({ title: "OAuth failed", message: error instanceof Error ? error.message : "Failed completing OAuth", state: "cancelled", payload: { type: "executor:source-oauth-result", ok: false, error: error instanceof Error ? error.message : "Failed completing OAuth", }, }), 500, ), ), ), ), ), );