Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
409 changes: 244 additions & 165 deletions packages/api-client/src/schema.d.ts

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions packages/api/.dev.vars.example
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,9 @@ GOOGLE_SIGN_IN_CLIENT_SECRET=

# Optional TOTP secret encryption. Use a separate 32-byte base64 key.
TOTP_ENCRYPTION_KEY=

# Optional hosted Cloudflare REST OAuth (operator-managed web client).
CLOUDFLARE_OAUTH_CLIENT_ID=
CLOUDFLARE_OAUTH_CLIENT_SECRET=
CLOUDFLARE_OAUTH_READ_SCOPES=account.read
CLOUDFLARE_OAUTH_WRITE_SCOPES=
25 changes: 25 additions & 0 deletions packages/api/migrations/0108_cloudflare_rest_oauth.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
CREATE TABLE app.cloudflare_connections (
tenant_id uuid NOT NULL REFERENCES app.tenants(id) ON DELETE CASCADE,
id uuid NOT NULL,
account_id text NOT NULL,
account_name text NOT NULL,
write_enabled boolean NOT NULL,
encrypted_credentials text,
PRIMARY KEY(tenant_id,id),
UNIQUE(tenant_id,account_id)
);
CREATE TABLE app.cloudflare_oauth_attempts (
tenant_id uuid PRIMARY KEY REFERENCES app.tenants(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES app.auth_users(id) ON DELETE CASCADE,
session_version integer NOT NULL,
state uuid NOT NULL UNIQUE,
verifier text,
scopes text[] NOT NULL,
write_requested boolean NOT NULL,
encrypted_pending text,
expires_at timestamptz NOT NULL
);
CREATE INDEX cloudflare_oauth_expiry ON app.cloudflare_oauth_attempts(expires_at);
ALTER TABLE app.agent_integrations DROP CONSTRAINT agent_integrations_kind_check;
ALTER TABLE app.agent_integrations ADD CONSTRAINT agent_integrations_kind_check
CHECK(kind IN ('bearer','github','linear','fly','exe','amp','clickup','x','cloudflare'));
2 changes: 1 addition & 1 deletion packages/api/src/agent-api-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export const integrationScopePattern = /^integration:([0-9a-f]{8}-[0-9a-f]{4}-[0
export const isIntegrationScope = (scope: string) => integrationScopePattern.test(scope);
export const integrationRef = z.uuid();
export const apiPolicyInput = z.object({ policy: z.enum(["baseline", "requestable", "disabled"]), expectedRevision: z.number().int().positive() }).strict();
export const apiPolicy = z.object({ id: integrationRef, credentialId: z.string(), name: z.string(), description: z.string().nullable(), kind: z.enum(["bearer", "github", "linear", "model", "fly", "exe", "amp", "clickup", "x"]), policy: z.enum(["baseline", "requestable", "disabled"]), available: z.boolean(), revision: z.number().int(), requiredScope: z.string() });
export const apiPolicy = z.object({ id: integrationRef, credentialId: z.string(), name: z.string(), description: z.string().nullable(), kind: z.enum(["bearer", "github", "linear", "model", "fly", "exe", "amp", "clickup", "x", "cloudflare"]), policy: z.enum(["baseline", "requestable", "disabled"]), available: z.boolean(), revision: z.number().int(), requiredScope: z.string() });
export const apiPolicyList = z.object({ integrations: z.array(apiPolicy) });
export const apiReflection = z.object({ identity: z.object({ id: z.uuid(), kind: z.enum(["oauth", "vm"]) }), scopes: z.array(z.string()), proxy: z.object({ requestUrl: z.url(), readResponseUrl: z.url(), requestTool:z.literal("request_api"), readResponseTool:z.literal("read_api_response"), authentication: z.string() }), integrations: z.array(apiPolicy.extend({ access: z.enum(["granted", "requestable", "unavailable"]), instructions: z.string(), requestExample:z.object({integration:integrationRef,method:z.enum(["GET","POST"]),path:z.string(),headers:z.record(z.string(),z.string()).optional(),body:z.string().optional()}) })) });
export const requestApiInput = z.object({
Expand Down
32 changes: 30 additions & 2 deletions packages/api/src/agent-api.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { cloudflareCredential } from "./cloudflare-oauth";
import { initialIntegrationOverrides } from "./oauth-reconnect";
import { activeVmAuthorization } from "./vm-auth";
import { connectionAccess, requiredIntegrationScope, type AgentIntegration, type ConnectionPolicy } from "./agent-integration-access";
Expand Down Expand Up @@ -106,10 +107,10 @@ export class AgentApiService {
if (!(error instanceof AgentApiError) || error.status === 401) throw error;
access = error.code === "insufficient_scope" ? "requestable" : "unavailable";
}
const path = row.kind === "linear" ? "/graphql" : row.kind === "x" ? "/2/users/me" : row.kind === "fly" ? "/v1/apps" : row.kind === "exe" ? "/exec" : "/";
const path = row.kind === "linear" ? "/graphql" : row.kind === "x" ? "/2/users/me" : row.kind === "cloudflare" ? "/zones" : row.kind === "fly" ? "/v1/apps" : row.kind === "exe" ? "/exec" : "/";
const method = row.kind === "linear" || row.kind === "exe" ? "POST" : "GET";
const requestExample = {integration:row.id,method,path,...(row.kind === "linear" ? {headers:{"Content-Type":"application/json"},body:JSON.stringify({query:"query { viewer { id name } }"})} : row.kind === "exe" ? {headers:{"Content-Type":"text/plain"},body:"help"} : {})};
result.push({...publicIntegration(row), access, requestExample, instructions: "Call MCP request_api with this integration ID and requestExample; no shell, local VM, raw HTTP client or access token is needed. Read retained results with read_api_response. " + (row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions.")});
result.push({...publicIntegration(row), access, requestExample, instructions: "Call MCP request_api with this integration ID and requestExample; no shell, local VM, raw HTTP client or access token is needed. Read retained results with read_api_response. " + (row.kind === "cloudflare" ? "Use Cloudflare API v4 paths for the selected account. GET /zones lists its zones; Cloudflare permissions and Factorize policy both apply. DNS writes require separate opt-in." : row.kind === "x" ? "Use the HTTP request endpoint with an X API v2 path, such as /2/users/me. Only granted OAuth scopes and supported resources are available." : row.kind === "linear" ? "Use the HTTP request endpoint with path /graphql and a JSON GraphQL body." : row.kind === "exe" ? "Use the HTTP request endpoint with POST /exec and a text/plain exe.dev command body." : row.kind === "amp" ? "Use the HTTP request endpoint with a path relative to the configured Amp API base." : row.kind === "clickup" ? "Use the HTTP request endpoint with a path relative to /api/v2." : row.kind === "fly" ? "Use the HTTP request endpoint with a Fly Machines API path, such as /v1/apps." : row.kind === "model" ? "Use the HTTP request endpoint with an OpenAI-compatible path relative to /v1." : "Use the HTTP request endpoint with a relative API path and query. Access covers this integration, bounded by the upstream credential permissions.")});
}
return {identity: {id: identity.id, kind: identity.kind}, scopes: normalizeScopes(identity.scopes).filter(scope => !identity.policy.disabled_scopes.includes(scope)), proxy: {
requestUrl: this.env.APP_ORIGIN + "/api/v1/agent/requests",
Expand All @@ -121,6 +122,33 @@ export class AgentApiService {
async forward(integration: string, path: string, request: Request) {
const grant = await this.authorize(integration);
if (grant.integration.kind === "x") return this.forwardX(grant.integration.credential_id, path, request);
if (grant.integration.kind === "cloudflare") {
let credential;
try { credential = await cloudflareCredential(this.env, this.auth.tenantId, grant.integration.credential_id, path, request.method); }
catch (error) {
if (error instanceof AgentApiError) throw error;
throw new AgentApiError(502, "credential_unavailable", "The Cloudflare authorization could not be checked.");
}
const current = await this.authorize(integration);
if (current.integration.epoch !== grant.integration.epoch) throw forbidden();
// Cloudflare has additional legacy authentication headers. Do not accept
// caller credentials, method overrides, or Cloudflare-specific controls.
const headers = new Headers();
for (const name of ["Accept", "Content-Type", "If-Match", "If-None-Match"]) {
const value = request.headers.get(name);
if (value) headers.set(name, value);
}
const outbound = new Request(request, { headers });
try {
const response = await forwardOutbound(outbound, credential);
if (response.ok) return new Response(response.body, { status: response.status, headers: {
"Content-Type": response.headers.get("Content-Type") ?? "application/json", "Cache-Control": "no-store",
} });
await response.body?.cancel();
return Response.json({ error: response.status === 401 ? "Cloudflare authorization expired. Reconnect in Integrations." :
"Cloudflare declined this request. Check the selected account and its Cloudflare permissions." }, { status: response.status });
} catch { throw new AgentApiError(502, "proxy_failed", "The upstream Cloudflare request failed."); }
}
let credential;
try { credential = await resolveAgentCredential(this.env, this.auth.tenantId, grant.integration.kind, grant.integration.credential_id, path); }
catch { throw new AgentApiError(502, "credential_unavailable", "The upstream credential could not be resolved."); }
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/agent-integration-access.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export type AgentIntegration = {id: string; kind: "bearer" | "model" | "github" | "linear" | "fly" | "exe" | "amp" | "clickup" | "x"; credential_id: string; name: string; description: string | null; available: boolean; policy: "baseline" | "requestable" | "disabled"; epoch: number; revision: number};
export type AgentIntegration = {id: string; kind: "bearer" | "model" | "github" | "linear" | "fly" | "exe" | "amp" | "clickup" | "x" | "cloudflare"; credential_id: string; name: string; description: string | null; available: boolean; policy: "baseline" | "requestable" | "disabled"; epoch: number; revision: number};
export const requiredIntegrationScope = (row: AgentIntegration) => `integration:${row.id}:${row.epoch}`;
export type ConnectionPolicy = { integration_overrides: Record<string, string | false>; disabled_scopes: string[] };
export function connectionAccess(row: AgentIntegration, scopes: string[], policy: ConnectionPolicy) {
Expand Down
71 changes: 25 additions & 46 deletions packages/api/src/api-contract.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { cloudflareCookieValue, cloudflareSelectInput, cloudflareStartInput, cloudflareStartResult, cloudflareStatus } from "./cloudflare-oauth";
import { cloneInfo, gitCredential } from "./git-https-contracts";
import { profileInput, profileResponse } from "./usernames";
import {createPayloadInput,payloadReceipt,appendPayloadInput,finalizePayloadInput,attachmentInput} from "./proxy-payloads";
Expand All @@ -6,7 +7,7 @@ import {queryApiResponseInput,queryApiResponseResult} from "./agent-api-contract
import { apiReflection, apiPolicyList, apiPolicyInput, requestApiInput, requestApiResponse, readApiResponseInput, apiResponseChunk } from "./agent-api-contracts";
import { queryOf } from "./query-params";
import { consentPreviewInput, consentPreviewResponse, consentDecisionInput, consentDecisionResponse } from "./consent-api";
import { exeConnection, integrationStatus, clientPermissionsUpdate, clientNameInput, authorizedClient, accessToken, createdAccessToken, savedExe, savedAmp, savedTail, okResult, permissionPreset, permissionPresetInput, permissionPresetList } from "./settings-contracts";
import { exeConnection, integrationStatus, clientPermissionsUpdate, clientNameInput, authorizedClient, accessToken, createdAccessToken, savedExe, savedAmp, okResult, permissionPreset, permissionPresetInput, permissionPresetList } from "./settings-contracts";
import { eventAvailabilityResponse, namedOption, providerOptions, githubInstallation, githubRepository, tailIntegration } from "./editor-contracts";
import { triggerResponse, triggerUpdateInput } from "./trigger-contracts";
import { z } from "zod";
Expand Down Expand Up @@ -59,15 +60,7 @@ const ampBody = z.object({
project: z.string().min(1).optional(),
apiBaseUrl: z.url().optional(),
});
const tailBody = z.object({
integrationId: z.string().min(1).optional(),
name: z.string().trim().min(1).max(120),
signingSecret: z
.union([z.literal(""), z.string().min(16)])
.optional()
.meta({ writeOnly: true }),
generateSecret: z.boolean().optional(),
});

const deliveryQuery = z.object({
provider: z.string().optional(),
deliveryId: z.string().optional(),
Expand Down Expand Up @@ -174,6 +167,28 @@ function authRoute(method: string, path: string, action: AuthAction, summary: st
}

export const API_ROUTES: RouteContract[] = [
route("GET", "/api/v1/integrations/cloudflare", "integrations:read", {
summary: "Read Cloudflare connections and pending account options",
responses: { "200": { description: "Cloudflare OAuth metadata", content: { "application/json": { schema: jsonSchema(cloudflareStatus, "output") } } } },
}, (service, { request }) => service.cloudflareState(request!), { ownerSession: true }),
route("POST", "/api/v1/integrations/cloudflare/authorize", "integrations:write", {
summary: "Start Cloudflare account authorization",
responses: { "200": { description: "Cloudflare authorization URL", content: { "application/json": { schema: jsonSchema(cloudflareStartResult, "output") } } } },
}, async (service, { body }) => {
const started = await service.startCloudflare(body.enableWrites);
return Response.json({ authorizationUrl: started.authorizationUrl }, { headers: { "Set-Cookie": started.cookie } });
}, { ownerSession: true, body: cloudflareStartInput, maxBodyBytes: 1024 }),
route("POST", "/api/v1/integrations/cloudflare/select", "integrations:write", {
summary: "Connect exactly one authorized Cloudflare account",
responses: { "200": { description: "Cloudflare account connected", content: { "application/json": { schema: jsonSchema(okResult, "output") } } } },
}, async (service, { request, body }) => {
const result = await service.selectCloudflare(request!, body.accountId);
return Response.json(result, { headers: { "Set-Cookie": cloudflareCookieValue("") } });
}, { ownerSession: true, body: cloudflareSelectInput, maxBodyBytes: 1024 }),
route("DELETE", "/api/v1/integrations/cloudflare/{connectionId}", "integrations:write", {
summary: "Disconnect a Cloudflare account inside this workspace",
responses: { "200": { description: "Cloudflare account disconnected", content: { "application/json": { schema: jsonSchema(okResult, "output") } } } },
}, (service, { params }) => service.disconnectCloudflare(params.connectionId), { ownerSession: true, parameters: z.object({ connectionId: z.uuid() }) }),
route("GET", "/api/v1/x/connections", "integrations:read", {
summary: "List X connections",
description: "Requires an interactive owner session. Returns named connection metadata, account identity, selected/granted scopes, and status. Client secrets and OAuth tokens are never returned.",
Expand Down Expand Up @@ -411,17 +426,6 @@ export const API_ROUTES: RouteContract[] = [
(service, { body }) => service.saveAmpIntegration(body),
{ body: ampBody },
),
route(
"POST",
"/api/v1/integrations/cloudflare-tail",
"integrations:write",
{
summary: "Create a Tail integration",
responses: { "201": { description: "Created", content: { "application/json": { schema: jsonSchema(savedTail, "output") } } } },
},
(service, { body }) => service.saveTailIntegration(body),
{ body: tailBody },
),
route(
"GET",
"/api/v1/providers/linear/projects",
Expand Down Expand Up @@ -625,21 +629,6 @@ export const API_ROUTES: RouteContract[] = [
(service, { params }) =>
service.removeIntegration("amp", params.connectionId),
),
route(
"PUT",
"/api/v1/integrations/cloudflare-tail/{integrationId}",
"integrations:write",
{
summary: "Update a Tail integration",
responses: { "200": { description: "Updated", content: { "application/json": { schema: jsonSchema(savedTail, "output") } } } },
},
(service, { params, body }) =>
service.saveTailIntegration({
...body,
integrationId: params.integrationId,
}),
{ body: tailBody },
),
route(
"DELETE",
"/api/v1/integrations/cloudflare-tail/{integrationId}",
Expand All @@ -651,16 +640,6 @@ export const API_ROUTES: RouteContract[] = [
(service, { params }) =>
service.removeTailIntegration(params.integrationId),
),
route(
"POST",
"/api/v1/integrations/cloudflare-tail/{integrationId}/test",
"integrations:write",
{
summary: "Test a Tail integration",
responses: { "200": { description: "Test result", content: { "application/json": { schema: jsonSchema(okResult, "output") } } } },
},
(service, { params }) => service.testTailIntegration(params.integrationId),
),
route(
"GET",
"/api/v1/providers/github/installations/{installationId}/repositories",
Expand Down
Loading
Loading