diff --git a/packages/api-client/src/schema.d.ts b/packages/api-client/src/schema.d.ts index 442837c2..5786083e 100644 --- a/packages/api-client/src/schema.d.ts +++ b/packages/api-client/src/schema.d.ts @@ -1,5 +1,93 @@ // Generated from packages/docs/openapi.yaml. Do not edit. export interface paths { + "/api/v1/integrations/cloudflare": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Read Cloudflare connections and pending account options + * @description Requires the integrations:read scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + get: operations["get_api_v1_integrations_cloudflare"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/integrations/cloudflare/authorize": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Start Cloudflare account authorization + * @description Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_integrations_cloudflare_authorize"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/integrations/cloudflare/select": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Connect exactly one authorized Cloudflare account + * @description Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + post: operations["post_api_v1_integrations_cloudflare_select"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/integrations/cloudflare/{connectionId}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + post?: never; + /** + * Disconnect a Cloudflare account inside this workspace + * @description Requires the integrations:write scope. + * + * An interactive owner session is required; bearer tokens cannot call this operation. + */ + delete: operations["delete_api_v1_integrations_cloudflare_connectionId"]; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/v1/x/connections": { parameters: { query?: never; @@ -929,13 +1017,7 @@ export interface paths { */ get: operations["get_api_v1_integrations_cloudflare_tail"]; put?: never; - /** - * Create a Tail integration - * @description Requires the integrations:write scope. - * - * Accepts a scoped bearer token or interactive owner session. - */ - post: operations["post_api_v1_integrations_cloudflare_tail"]; + post?: never; delete?: never; options?: never; head?: never; @@ -1548,13 +1630,7 @@ export interface paths { cookie?: never; }; get?: never; - /** - * Update a Tail integration - * @description Requires the integrations:write scope. - * - * Accepts a scoped bearer token or interactive owner session. - */ - put: operations["put_api_v1_integrations_cloudflare_tail_integrationId"]; + put?: never; post?: never; /** * Remove a Tail integration @@ -1568,28 +1644,6 @@ export interface paths { patch?: never; trace?: never; }; - "/api/v1/integrations/cloudflare-tail/{integrationId}/test": { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - get?: never; - put?: never; - /** - * Test a Tail integration - * @description Requires the integrations:write scope. - * - * Accepts a scoped bearer token or interactive owner session. - */ - post: operations["post_api_v1_integrations_cloudflare_tail_integrationId_test"]; - delete?: never; - options?: never; - head?: never; - patch?: never; - trace?: never; - }; "/api/v1/providers/github/installations/{installationId}/repositories": { parameters: { query?: never; @@ -2699,6 +2753,157 @@ export interface components { } export type $defs = Record; export interface operations { + get_api_v1_integrations_cloudflare: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Cloudflare OAuth metadata */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + configured: boolean; + writeAvailable: boolean; + accounts: { + id: string; + name: string; + }[]; + connections: { + /** Format: uuid */ + id: string; + accountId: string; + name: string; + writeEnabled: boolean; + connected: boolean; + }[]; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_integrations_cloudflare_authorize: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + /** @default false */ + enableWrites?: boolean; + }; + }; + }; + responses: { + /** @description Cloudflare authorization URL */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uri */ + authorizationUrl: string; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + post_api_v1_integrations_cloudflare_select: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + accountId: string; + }; + }; + }; + responses: { + /** @description Cloudflare account connected */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ok: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 415: components["responses"]["Error415"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; + delete_api_v1_integrations_cloudflare_connectionId: { + parameters: { + query?: never; + header?: never; + path: { + connectionId: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Cloudflare account disconnected */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + ok: boolean; + }; + }; + }; + 400: components["responses"]["Error400"]; + 401: components["responses"]["Error401"]; + 403: components["responses"]["Error403"]; + 404: components["responses"]["Error404"]; + 409: components["responses"]["Error409"]; + 429: components["responses"]["Error429"]; + 500: components["responses"]["Error500"]; + 503: components["responses"]["Error503"]; + }; + }; get_api_v1_x_connections: { parameters: { query?: never; @@ -4719,52 +4924,6 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; - post_api_v1_integrations_cloudflare_tail: { - parameters: { - query?: never; - header?: never; - path?: never; - cookie?: never; - }; - requestBody: { - content: { - "application/json": { - integrationId?: string; - name: string; - signingSecret?: "" | string; - generateSecret?: boolean; - }; - }; - }; - responses: { - /** @description Created */ - 201: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - integrationId: string; - name: string; - /** @constant */ - status: "connected"; - /** @constant */ - secretConfigured: true; - generatedSecret?: string; - }; - }; - }; - 400: components["responses"]["Error400"]; - 401: components["responses"]["Error401"]; - 403: components["responses"]["Error403"]; - 404: components["responses"]["Error404"]; - 409: components["responses"]["Error409"]; - 415: components["responses"]["Error415"]; - 429: components["responses"]["Error429"]; - 500: components["responses"]["Error500"]; - 503: components["responses"]["Error503"]; - }; - }; get_api_v1_integrations: { parameters: { query?: never; @@ -5954,54 +6113,6 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; - put_api_v1_integrations_cloudflare_tail_integrationId: { - parameters: { - query?: never; - header?: never; - path: { - integrationId: string; - }; - cookie?: never; - }; - requestBody: { - content: { - "application/json": { - integrationId?: string; - name: string; - signingSecret?: "" | string; - generateSecret?: boolean; - }; - }; - }; - responses: { - /** @description Updated */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - integrationId: string; - name: string; - /** @constant */ - status: "connected"; - /** @constant */ - secretConfigured: true; - generatedSecret?: string; - }; - }; - }; - 400: components["responses"]["Error400"]; - 401: components["responses"]["Error401"]; - 403: components["responses"]["Error403"]; - 404: components["responses"]["Error404"]; - 409: components["responses"]["Error409"]; - 415: components["responses"]["Error415"]; - 429: components["responses"]["Error429"]; - 500: components["responses"]["Error500"]; - 503: components["responses"]["Error503"]; - }; - }; delete_api_v1_integrations_cloudflare_tail_integrationId: { parameters: { query?: never; @@ -6032,38 +6143,6 @@ export interface operations { 503: components["responses"]["Error503"]; }; }; - post_api_v1_integrations_cloudflare_tail_integrationId_test: { - parameters: { - query?: never; - header?: never; - path: { - integrationId: string; - }; - cookie?: never; - }; - requestBody?: never; - responses: { - /** @description Test result */ - 200: { - headers: { - [name: string]: unknown; - }; - content: { - "application/json": { - ok: boolean; - }; - }; - }; - 400: components["responses"]["Error400"]; - 401: components["responses"]["Error401"]; - 403: components["responses"]["Error403"]; - 404: components["responses"]["Error404"]; - 409: components["responses"]["Error409"]; - 429: components["responses"]["Error429"]; - 500: components["responses"]["Error500"]; - 503: components["responses"]["Error503"]; - }; - }; get_api_v1_providers_github_installations_installationId_repositories: { parameters: { query?: never; @@ -6878,7 +6957,7 @@ export interface operations { name: string; description: string | null; /** @enum {string} */ - kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x"; + kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x" | "cloudflare"; /** @enum {string} */ policy: "baseline" | "requestable" | "disabled"; available: boolean; @@ -7702,7 +7781,7 @@ export interface operations { name: string; description: string | null; /** @enum {string} */ - kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x"; + kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x" | "cloudflare"; /** @enum {string} */ policy: "baseline" | "requestable" | "disabled"; available: boolean; @@ -7755,7 +7834,7 @@ export interface operations { name: string; description: string | null; /** @enum {string} */ - kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x"; + kind: "bearer" | "github" | "linear" | "model" | "fly" | "exe" | "amp" | "clickup" | "x" | "cloudflare"; /** @enum {string} */ policy: "baseline" | "requestable" | "disabled"; available: boolean; diff --git a/packages/api/.dev.vars.example b/packages/api/.dev.vars.example index 458e2778..a3707d56 100644 --- a/packages/api/.dev.vars.example +++ b/packages/api/.dev.vars.example @@ -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= diff --git a/packages/api/migrations/0108_cloudflare_rest_oauth.sql b/packages/api/migrations/0108_cloudflare_rest_oauth.sql new file mode 100644 index 00000000..62894061 --- /dev/null +++ b/packages/api/migrations/0108_cloudflare_rest_oauth.sql @@ -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')); diff --git a/packages/api/src/agent-api-contracts.ts b/packages/api/src/agent-api-contracts.ts index f90e9cec..d7c427c2 100644 --- a/packages/api/src/agent-api-contracts.ts +++ b/packages/api/src/agent-api-contracts.ts @@ -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({ diff --git a/packages/api/src/agent-api.ts b/packages/api/src/agent-api.ts index e27f7db0..d514dae4 100644 --- a/packages/api/src/agent-api.ts +++ b/packages/api/src/agent-api.ts @@ -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"; @@ -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", @@ -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."); } diff --git a/packages/api/src/agent-integration-access.ts b/packages/api/src/agent-integration-access.ts index fcf2f10a..240ba309 100644 --- a/packages/api/src/agent-integration-access.ts +++ b/packages/api/src/agent-integration-access.ts @@ -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; disabled_scopes: string[] }; export function connectionAccess(row: AgentIntegration, scopes: string[], policy: ConnectionPolicy) { diff --git a/packages/api/src/api-contract.ts b/packages/api/src/api-contract.ts index 0848b848..197ce424 100644 --- a/packages/api/src/api-contract.ts +++ b/packages/api/src/api-contract.ts @@ -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"; @@ -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"; @@ -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(), @@ -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.", @@ -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", @@ -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}", @@ -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", diff --git a/packages/api/src/api-service.ts b/packages/api/src/api-service.ts index fc57d076..62fbfa45 100644 --- a/packages/api/src/api-service.ts +++ b/packages/api/src/api-service.ts @@ -1,3 +1,4 @@ +import { cloudflareState, disconnectCloudflare, selectCloudflare, startCloudflare } from "./cloudflare-oauth"; import { initialIntegrationOverrides, lockOAuthPolicy } from "./oauth-reconnect"; import { lockMcpEventGrant } from "./postgres/mcp-event-outbox"; import { eventPayloadSchema, occurrenceEventName, occurrenceInputSchema, type ReadEventOccurrencesInput, type subscribeEventInput, type unsubscribeEventInput, type setProcessingAcknowledgmentsInput, type acknowledgeEventsInput } from "./mcp-event-contracts"; @@ -96,6 +97,13 @@ export class ApiService { // plus an insertion, never an in-place mutation of historical identity. const candidate = source.id ? prior.get(source.id) : undefined; const old = candidate?.kind === source.kind ? candidate : undefined; + if (source.kind === "webhook" && source.config.provider === "cloudflareTail") { + if (!old || old.config.provider !== "cloudflareTail" || old.config.integrationId !== source.config.integrationId) { + throw new ServiceError(400, "invalid_request", "Cloudflare Tail is retired. Remove this source or choose a different provider."); + } + // Retain historical configuration unchanged when editing other fields. + return { ...old, enabled: false }; + } while (used.has(`source-${next}`)) next++; const slug = old?.slug ?? source.slug ?? `source-${next++}`; used.add(slug); return { id: old?.id ?? crypto.randomUUID(), triggerId: old?.triggerId ?? "", kind: source.kind, slug, enabled: source.enabled !== false, config: source.config, template:source.template, createdAt: old?.createdAt ?? timestamp, updatedAt: timestamp }; @@ -105,7 +113,7 @@ export class ApiService { private async presentTrigger(trigger: Trigger) { - return publicValue(triggerResponse, { ...trigger, eventId: trigger.eventId ?? null, sources: trigger.sources.map(source => ({ ...source, config: source.kind === "webhook" ? { ...source.config, ...(source.config.signingSecret || source.config.secret ? { secretConfigured: true } : {}), ...(source.config.provider === "cloudflareTail" ? { destination: this.env.APP_ORIGIN + "/webhooks/cloudflare/" + encodeURIComponent(this.auth.tenantId) + "/" + encodeURIComponent(trigger.id) } : {}) } : source.config })) }); + return publicValue(triggerResponse, { ...trigger, eventId: trigger.eventId ?? null, sources: trigger.sources.map(source => ({ ...source, enabled: source.kind === "webhook" && source.config.provider === "cloudflareTail" ? false : source.enabled, config: source.kind === "webhook" ? { ...source.config, ...(source.config.signingSecret || source.config.secret ? { secretConfigured: true } : {}) } : source.config })) }); } async mcpListSkills(cursor?:string) { await this.authorizeIdentity(); @@ -323,7 +331,7 @@ export class ApiService { const result = await new EventMatchRepository(databaseFor(this.env), () => wakeMcpDeliveries(this.env)).match({ tenantId: this.auth.tenantId, triggerId, triggerRevision: trigger.revision, sourceIdentity: `manual:${source.id}`, deduplicationKey, evidence: input.data ?? {}, decision: "matched" }); return { occurrenceId: result.occurrence?.id ?? null, duplicate: result.duplicate }; } - async listTriggerEventAvailability() { await this.authorize("triggers:read"); const [kinds, installations] = await Promise.all([this.connections().kinds(), new GitHubRepository(databaseFor(this.env),this.auth.tenantId).installations()]), states=installations.map((x:any)=>x.state); return installedEventAvailability(kinds.includes("linear"),kinds.includes("clickup"),states,kinds.filter(x=>x.startsWith("cloudflare-tail:")).length); } + async listTriggerEventAvailability() { await this.authorize("triggers:read"); const [kinds, installations] = await Promise.all([this.connections().kinds(), new GitHubRepository(databaseFor(this.env),this.auth.tenantId).installations()]), states=installations.map((x:any)=>x.state); return installedEventAvailability(kinds.includes("linear"),kinds.includes("clickup"),states); } async previewSchedule(input: unknown) { await this.authorize("triggers:read"); try { @@ -337,6 +345,22 @@ export class ApiService { private integrations() { return new IntegrationService(databaseFor(this.env), this.auth.tenantId, this.env.CREDENTIAL_ENCRYPTION_KEY); } private providers() { return new ProviderCatalog(databaseFor(this.env), this.env, this.auth.tenantId); } + async cloudflareState(request: Request) { + await this.authorizeOwnerSession("integrations:read"); + return cloudflareState(this.env, this.auth, request); + } + async startCloudflare(writes: boolean) { + await this.authorizeOwnerSession("integrations:write"); + return startCloudflare(this.env, this.auth, writes); + } + async selectCloudflare(request: Request, accountId: string) { + await this.authorizeOwnerSession("integrations:write"); + return selectCloudflare(this.env, this.auth, request, accountId); + } + async disconnectCloudflare(id: string) { + await this.authorizeOwnerSession("integrations:write"); + return disconnectCloudflare(this.env, this.auth, id); + } async integrationStatus() { await this.authorize("integrations:read"); return publicValue(integrationStatus, await this.integrations().status()); } async saveExeIntegration(input: any) { await this.authorize("integrations:write"); return this.integrations().saveExe(input); } async removeIntegration(kind: "exe" | "amp", id: string) { await this.authorize("integrations:write"); const result = await this.integrations().remove(kind, id); if (result.conflict) throw new ServiceError(409, "conflict", "This integration is used by a trigger."); if (!result.deleted) throw new ServiceError(404, "not_found", "Integration not found"); return { id, deleted: true }; } diff --git a/packages/api/src/cloudflare-oauth.ts b/packages/api/src/cloudflare-oauth.ts new file mode 100644 index 00000000..5fbac4e0 --- /dev/null +++ b/packages/api/src/cloudflare-oauth.ts @@ -0,0 +1,271 @@ +import { z } from "zod"; +import { readBrowserSession } from "./browser-session"; +import { requestCookie } from "./session"; +import { IdentityRepository } from "./postgres/identity-repository"; +import { databaseFor, type DatabaseClient } from "./postgres/database"; +import { decrypt, encrypt } from "./crypto"; +import { AgentApiError } from "./agent-api-error"; +import type { Env, OAuthProps } from "./types"; + +export const cloudflareCallback = "/oauth/cloudflare/callback"; +export const cloudflareOrigin = "https://api.cloudflare.com"; +export const cloudflareCookie = "__Host-factorize_cloudflare_oauth"; +const tokenEndpoint = "https://dash.cloudflare.com/oauth2/token"; +const idPattern = /^[0-9a-f]{32}$/; +const encoder = new TextEncoder(); +const base64url = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +const unavailable = () => new AgentApiError(503, "unavailable", "Cloudflare OAuth is not configured."); +const reconnect = () => new AgentApiError(401, "reconnect_required", "Cloudflare authorization expired or was revoked. Reconnect in Integrations."); +const forbidden = () => new AgentApiError(403, "forbidden", "This operation is outside the Cloudflare connection's account or permission boundaries."); +const upstream = () => new AgentApiError(502, "cloudflare_unavailable", "Cloudflare did not complete the request. Try again if safe."); + +const accountSchema = z.object({ id: z.string().regex(idPattern), name: z.string().min(1).max(250) }); +type Account = z.infer; +export const cloudflareStartInput = z.object({ enableWrites: z.boolean().default(false) }).strict(); +export const cloudflareStartResult = z.object({ authorizationUrl: z.url() }); +export const cloudflareSelectInput = z.object({ accountId: z.string().regex(idPattern) }).strict(); +const metadata = z.object({ id: z.uuid(), accountId: z.string().regex(idPattern), name: z.string(), writeEnabled: z.boolean(), connected: z.boolean() }); +export const cloudflareStatus = z.object({ configured: z.boolean(), writeAvailable: z.boolean(), accounts: z.array(accountSchema), connections: z.array(metadata) }); +const credsSchema = z.object({ access: z.string().min(1).max(8192), refresh: z.string().min(1).max(8192).optional(), expiration: z.number(), scopes: z.array(z.string()) }); +type Credentials = z.infer; +type Pending = { accounts: Account[]; credentials: Credentials }; +type Connection = { id: string; account_id: string; account_name: string; write_enabled: boolean; encrypted_credentials: string | null }; +type Attempt = { state: string; verifier: string | null; scopes: string[]; write_requested: boolean; encrypted_pending: string | null }; +type Owner = Pick; + +const split = (value?: string) => [...new Set(value?.trim().split(/\s+/).filter(Boolean) ?? [])]; +export function cloudflareSettings(env: Env) { + const read = split(env.CLOUDFLARE_OAUTH_READ_SCOPES), write = split(env.CLOUDFLARE_OAUTH_WRITE_SCOPES); + const configured = !!(env.CLOUDFLARE_OAUTH_CLIENT_ID && env.CLOUDFLARE_OAUTH_CLIENT_SECRET && read.includes("account.read") + && read.length <= 40 && write.length <= 40 && read.every(s => /^[a-z0-9_.]+\.read$/.test(s)) && write.every(s => /^[a-z0-9_.]+\.write$/.test(s))); + return { configured, read, write }; +} +export const cloudflareCookieValue = (state: string) => + `${cloudflareCookie}=${state}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${state ? 600 : 0}`; +const lock = (sql: DatabaseClient, tenant: string) => sql.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", ["cloudflare:" + tenant]); +const open = async (input: string, env: Env) => JSON.parse(await decrypt(input, env.CREDENTIAL_ENCRYPTION_KEY)) as T; +const sealed = (value: unknown, env: Env) => encrypt(JSON.stringify(value), env.CREDENTIAL_ENCRYPTION_KEY); + +export async function startCloudflare(env: Env, owner: Owner, writes: boolean) { + const { configured, read, write } = cloudflareSettings(env); + if (!configured) throw unavailable(); + if (writes && !write.includes("dns.write")) throw forbidden(); + const verifier = base64url(crypto.getRandomValues(new Uint8Array(32))); + const challenge = base64url(new Uint8Array(await crypto.subtle.digest("SHA-256", encoder.encode(verifier)))); + const state = crypto.randomUUID(), scopes = writes ? [...read, ...write] : read; + await databaseFor(env).transaction(async sql => { + await lock(sql, owner.tenantId); + await sql.query(`INSERT INTO app.cloudflare_oauth_attempts + (tenant_id,user_id,session_version,state,verifier,scopes,write_requested,expires_at) + VALUES($1,$2,$3,$4,$5,$6,$7,clock_timestamp()+interval '10 minutes') + ON CONFLICT(tenant_id) DO UPDATE SET user_id=excluded.user_id,session_version=excluded.session_version,state=excluded.state, + verifier=excluded.verifier,scopes=excluded.scopes,write_requested=excluded.write_requested,expires_at=excluded.expires_at,encrypted_pending=NULL`, + [owner.tenantId, owner.userId, owner.sessionVersion, state, await encrypt(verifier, env.CREDENTIAL_ENCRYPTION_KEY), scopes, writes]); + }); + const target = new URL("https://dash.cloudflare.com/oauth2/auth"); + target.search = new URLSearchParams({ client_id: env.CLOUDFLARE_OAUTH_CLIENT_ID!, redirect_uri: env.APP_ORIGIN + cloudflareCallback, + response_type: "code", state, scope: scopes.join(" "), code_challenge: challenge, code_challenge_method: "S256" }).toString(); + return { authorizationUrl: target.href, cookie: cloudflareCookieValue(state) }; +} + +const tokenResult = z.object({ access_token: z.string().min(1).max(8192), refresh_token: z.string().min(1).max(8192).optional(), + expires_in: z.number().finite().positive(), token_type: z.string().refine(value => value.toLowerCase() === "bearer"), scope: z.string().optional() }); +async function exchange(env: Env, payload: Record, ceiling: string[], previous?: Credentials) { + const response = await fetch(tokenEndpoint, { method: "POST", redirect: "error", signal: AbortSignal.timeout(10_000), + headers: { Accept: "application/json" }, body: new URLSearchParams({ ...payload, + client_id: env.CLOUDFLARE_OAUTH_CLIENT_ID!, client_secret: env.CLOUDFLARE_OAUTH_CLIENT_SECRET! }) }); + const body = await response.json().catch(() => null); + if (!response.ok) { + const error = z.object({ error: z.string() }).safeParse(body); + if (previous && error.success && ["invalid_grant", "invalid_token"].includes(error.data.error)) throw reconnect(); + throw upstream(); + } + const result = tokenResult.parse(body); + // Optional writes are never assumed granted on first exchange. Omitted + // refresh scopes may only retain the already confirmed credential ceiling. + const resultScopes = result.scope === undefined ? previous?.scopes ?? ceiling.filter(scope => scope.endsWith(".read")) : split(result.scope); + return { access: result.access_token, refresh: result.refresh_token ?? previous?.refresh, + expiration: Date.now() + result.expires_in * 1000, scopes: resultScopes.filter(scope => ceiling.includes(scope)) }; +} + +async function apiJson(access: string, path: string) { + const response = await fetch(cloudflareOrigin + "/client/v4" + path, { + headers: { Authorization: "Bearer " + access, Accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(10_000) }); + if (response.status === 401) throw reconnect(); + if (response.status === 403 || response.status === 404) throw forbidden(); + if (!response.ok) throw upstream(); + const body = await response.json() as { success?: boolean; result?: unknown; result_info?: { total_pages?: number } }; + if (body.success !== true) throw upstream(); + return body; +} + +async function listAccounts(access: string) { + const accounts: Account[] = []; + for (let page = 1; page <= 10; page++) { + const result = await apiJson(access, "/accounts?per_page=50&page=" + page); + accounts.push(...z.array(accountSchema).max(50).parse(result.result)); + if (page >= (result.result_info?.total_pages ?? page)) break; + } + if (!accounts.length) throw forbidden(); + return accounts; +} + +export async function cloudflareOAuthCallback(request: Request, env: Env) { + const result = (status: string, keepCookie = false) => new Response(null, { status: 303, headers: { + Location: env.APP_ORIGIN + "/integrations?cloudflare=" + status, "Cache-Control": "no-store", "Referrer-Policy": "no-referrer", + ...(keepCookie ? {} : { "Set-Cookie": cloudflareCookieValue("") }), + } }); + if (request.method !== "GET") return new Response(null, { status: 405, headers: { Allow: "GET" } }); + try { + if (request.headers.has("Authorization") || !cloudflareSettings(env).configured) return result("failed"); + const url = new URL(request.url), state = url.searchParams.get("state"), code = url.searchParams.get("code"); + const owner = await readBrowserSession(request, env); + if (!owner || !z.uuid().safeParse(state).success || requestCookie(request, cloudflareCookie) !== state) return result("expired", true); + const db = databaseFor(env); + const member = await new IdentityRepository(db, owner.tenantId).member(owner.userId); + if (member?.role !== "owner" || member.sessionVersion !== owner.sessionVersion) return result("expired"); + const attempt = await db.transaction(async sql => { + await lock(sql, owner.tenantId); + const row = (await sql.query(`SELECT * FROM app.cloudflare_oauth_attempts + WHERE tenant_id=$1 AND user_id=$2 AND session_version=$3 AND state=$4 AND verifier IS NOT NULL AND expires_at>clock_timestamp()`, + [owner.tenantId, owner.userId, owner.sessionVersion, state])).rows[0]; + if (row) await sql.query("UPDATE app.cloudflare_oauth_attempts SET verifier=NULL WHERE tenant_id=$1 AND state=$2", [owner.tenantId, state]); + return row; + }); + if (!attempt) return result("expired", true); + if (!code || code.length > 4096 || url.searchParams.has("error")) return result("denied"); + const credentials = await exchange(env, { grant_type: "authorization_code", code, redirect_uri: env.APP_ORIGIN + cloudflareCallback, + code_verifier: await decrypt(attempt.verifier!, env.CREDENTIAL_ENCRYPTION_KEY) }, attempt.scopes); + if (!credentials.scopes.includes("account.read")) return result("failed"); + const accounts = await listAccounts(credentials.access); + const pending = await sealed({ credentials, accounts }, env); + const stored = await db.pool.query(`UPDATE app.cloudflare_oauth_attempts SET encrypted_pending=$3 + WHERE tenant_id=$1 AND state=$2 AND expires_at>clock_timestamp() RETURNING state`, [owner.tenantId, state, pending]); + return stored.rowCount ? result("select", true) : result("expired", true); + } catch { + return result("failed"); + } +} + +export async function cloudflareState(env: Env, owner: Owner, request: Request) { + const db = databaseFor(env), settings = cloudflareSettings(env); + const rows = (await db.pool.query(`SELECT id,account_id,account_name,write_enabled, + CASE WHEN encrypted_credentials IS NULL THEN NULL ELSE 'stored' END encrypted_credentials FROM app.cloudflare_connections + WHERE tenant_id=$1 ORDER BY account_name,id`, [owner.tenantId])).rows; + const state = requestCookie(request, cloudflareCookie); + const attempt = z.uuid().safeParse(state).success ? (await db.pool.query(`SELECT encrypted_pending FROM app.cloudflare_oauth_attempts + WHERE tenant_id=$1 AND user_id=$2 AND session_version=$3 AND state=$4 AND expires_at>clock_timestamp()`, + [owner.tenantId, owner.userId, owner.sessionVersion, state])).rows[0] : undefined; + const accounts = attempt?.encrypted_pending ? (await open(attempt.encrypted_pending, env)).accounts : []; + return cloudflareStatus.parse({ configured: settings.configured, writeAvailable: settings.write.includes("dns.write"), accounts, + connections: rows.map(row => ({ id: row.id, accountId: row.account_id, name: row.account_name, writeEnabled: row.write_enabled && settings.write.includes("dns.write"), connected: !!row.encrypted_credentials })) }); +} + +export async function selectCloudflare(env: Env, owner: Owner, request: Request, accountId: string) { + const state = requestCookie(request, cloudflareCookie); + if (!z.uuid().safeParse(state).success) throw forbidden(); + return databaseFor(env).transaction(async sql => { + await lock(sql, owner.tenantId); + const attempt = (await sql.query(`SELECT encrypted_pending,write_requested FROM app.cloudflare_oauth_attempts + WHERE tenant_id=$1 AND user_id=$2 AND session_version=$3 AND state=$4 AND expires_at>clock_timestamp()`, + [owner.tenantId, owner.userId, owner.sessionVersion, state])).rows[0]; + if (!attempt?.encrypted_pending) throw forbidden(); + const pending = await open(attempt.encrypted_pending, env); + const account = pending.accounts.find(row => row.id === accountId); + if (!account) throw forbidden(); + const writeEnabled = attempt.write_requested && pending.credentials.scopes.includes("dns.write"); + const { rows: [saved] } = await sql.query<{id: string}>(`INSERT INTO app.cloudflare_connections + (tenant_id,id,account_id,account_name,write_enabled,encrypted_credentials) VALUES($1,$2,$3,$4,$5,$6) + ON CONFLICT(tenant_id,account_id) DO UPDATE SET account_name=excluded.account_name, + write_enabled=excluded.write_enabled,encrypted_credentials=excluded.encrypted_credentials RETURNING id`, + [owner.tenantId, crypto.randomUUID(), account.id, account.name, writeEnabled, await sealed(pending.credentials, env)]); + await sql.query(`INSERT INTO app.agent_integrations AS i(tenant_id,kind,credential_id,name,description,available,policy) + VALUES($1,'cloudflare',$2,$3,'Selected Cloudflare account',true,'requestable') + ON CONFLICT(tenant_id,kind,credential_id) DO UPDATE SET name=excluded.name,available=true,epoch=i.epoch+1,revision=i.revision+1`, + [owner.tenantId, saved.id, "Cloudflare · " + account.name]); + await sql.query("DELETE FROM app.cloudflare_oauth_attempts WHERE tenant_id=$1", [owner.tenantId]); + return { ok: true }; + }); +} + +export async function disconnectCloudflare(env: Env, owner: Owner, id: string) { + return databaseFor(env).transaction(async sql => { + await lock(sql, owner.tenantId); + const result = await sql.query(`UPDATE app.cloudflare_connections SET encrypted_credentials=NULL,write_enabled=false + WHERE tenant_id=$1 AND id=$2 AND encrypted_credentials IS NOT NULL RETURNING id`, [owner.tenantId, id]); + if (!result.rowCount) throw forbidden(); + await sql.query("UPDATE app.agent_integrations SET available=false,epoch=epoch+1,revision=revision+1 WHERE tenant_id=$1 AND kind='cloudflare' AND credential_id=$2", [owner.tenantId, id]); + await sql.query("DELETE FROM app.cloudflare_oauth_attempts WHERE tenant_id=$1", [owner.tenantId]); + return { ok: true }; + }); +} + +const readFamilies = { + account: /^(?:workers\/(?:scripts|domains)|storage\/kv\/namespaces|r2\/buckets(?:\/[A-Za-z0-9_-]+)?|d1\/database(?:\/[A-Za-z0-9_-]+)?|queues(?:\/[A-Za-z0-9_-]+)?|pages\/projects)$/, + zone: /^(?:dns_records(?:\/[a-f0-9]{32})?|dnssec|settings(?:\/[A-Za-z0-9_-]+)?|workers\/routes(?:\/[a-f0-9]{32})?|cache\/cache_reserve|analytics\/dashboard)$/, +}; +const sensitive = /(?:^|\/)(?:tokens?|api[-_]keys?|members?|memberships?|roles?|permissions?|secrets?|secret_text|credentials?|oauth_clients|user|bindings|settings)(?:\/|$)/i; +export function cloudflareTarget(input: string, verb: string, account: string, writeEnabled: boolean) { + const [path, query = ""] = input.split(/\?(.*)/s, 2); + const raw = path.startsWith("/client/v4/") ? path.slice("/client/v4".length) : path; + if (!/^\/(?:[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*)$/.test(raw) || /[%\\#\r\n]/.test(raw) || /[#\r\n]/.test(query)) throw forbidden(); + const search = new URLSearchParams(query); + for (const key of search.keys()) if (!/^[A-Za-z0-9_.-]{1,64}$/.test(key) || /(?:^|[._\[\]])(?:account|zone)(?:$|[._\[\]])/i.test(key)) throw forbidden(); + const read = verb === "GET" || verb === "HEAD"; + if (raw === "/accounts" && read && !search.size) return { path: "/client/v4/accounts/" + account }; + if (raw === "/zones" && read) { + search.set("account.id", account); + return { path: "/client/v4/zones?" + search.toString(), zone: undefined }; + } + const parts = raw.slice(1).split("/"), [kind, resource, ...rest] = parts; + const suffix = rest.join("/"); + if (!idPattern.test(resource ?? "") || (kind !== "accounts" && kind !== "zones")) throw forbidden(); + if (kind === "accounts" && resource !== account) throw forbidden(); + const safeZoneSettings = kind === "zones" && /^settings(?:\/[A-Za-z0-9_-]+)?$/.test(suffix); + if (sensitive.test(suffix) && !safeZoneSettings) throw forbidden(); + if (read) { + if (suffix && !readFamilies[kind === "accounts" ? "account" : "zone"].test(suffix)) throw forbidden(); + } else { + // Mutations with account transfers, credentials, script uploads, or a + // separately scoped target need a dedicated policy before being exposed. + const safeDnsWrite = kind === "zones" && (verb === "POST" ? suffix === "dns_records" : + ["PATCH", "PUT", "DELETE"].includes(verb) && /^dns_records\/[a-f0-9]{32}$/.test(suffix)); + if (!writeEnabled || !safeDnsWrite || search.size) throw forbidden(); + } + return { path: "/client/v4" + raw + (search.size ? "?" + search.toString() : ""), zone: kind === "zones" ? resource : undefined }; +} + +export async function cloudflareCredential(env: Env, tenant: string, id: string, path: string, verb: string) { + const settings = cloudflareSettings(env); + if (!settings.configured) throw unavailable(); + const db = databaseFor(env); + const credential = await db.transaction(async sql => { + await lock(sql, tenant); + const connection = (await sql.query("SELECT * FROM app.cloudflare_connections WHERE tenant_id=$1 AND id=$2", [tenant, id])).rows[0]; + if (!connection?.encrypted_credentials) throw reconnect(); + let credentials = credsSchema.parse(await open(connection.encrypted_credentials, env)); + cloudflareTarget(path, verb, connection.account_id, connection.write_enabled && settings.write.includes("dns.write")); + if (credentials.expiration <= Date.now() + 30_000) { + if (!credentials.refresh) throw reconnect(); + try { + credentials = await exchange(env, { grant_type: "refresh_token", refresh_token: credentials.refresh }, credentials.scopes, credentials); + } catch (error) { if (error instanceof AgentApiError) throw error; throw upstream(); } + await sql.query("UPDATE app.cloudflare_connections SET encrypted_credentials=$3 WHERE tenant_id=$1 AND id=$2", + [tenant, id, await sealed(credentials, env)]); + } + const writes = connection.write_enabled && settings.write.includes("dns.write") && credentials.scopes.includes("dns.write"); + return { target: cloudflareTarget(path, verb, connection.account_id, writes), access: credentials.access, account: connection.account_id }; + }); + if (credential.target.zone) { + const { result } = await apiJson(credential.access, "/zones/" + credential.target.zone); + const owner = z.object({ account: z.object({ id: z.string() }) }).safeParse(result); + if (!owner.success || owner.data.account.id !== credential.account) throw forbidden(); + } + return { origin: cloudflareOrigin, path: credential.target.path, credential: credential.access }; +} + +export async function pruneCloudflareOAuth(sql: DatabaseClient) { + await sql.query(`DELETE FROM app.cloudflare_oauth_attempts WHERE tenant_id IN + (SELECT tenant_id FROM app.cloudflare_oauth_attempts WHERE expires_at { catch (error) { if (error instanceof Error && error.message === "installation_conflict") return c.text("This GitHub installation is already connected to another tenant", 409); throw error; } return c.redirect("/integrations"); }); -app.post("/webhooks/cloudflare/:tenantId/:triggerId", async (c) => { - const raw = await c.req.text(); - if (new TextEncoder().encode(raw).byteLength > 262_144) return c.text("Payload too large", 413); - try { await new WebhookService(databaseFor(c.env), c.env, c.req.param("tenantId")).tail(c.req.param("triggerId"), raw, c.req.raw.headers); return c.body(null, 202); } - catch (error) { return c.text(error instanceof Error && error.message === "not_found" ? "Not found" : "Invalid signature", error instanceof Error && error.message === "not_found" ? 404 : 401); } -}); +// Keep the old address as a tombstone so relays receive a permanent response. +app.post("/webhooks/cloudflare/:tenantId/:triggerId", c => c.text("Cloudflare Tail is retired", 410)); app.post("/webhooks/linear", async (c) => { if (!c.env.LINEAR_WEBHOOK_SIGNING_SECRET) return c.text("Webhook verification is not configured", 503); diff --git a/packages/api/src/mcp-event-subscriptions.ts b/packages/api/src/mcp-event-subscriptions.ts index 2a67efb8..05bd6c4a 100644 --- a/packages/api/src/mcp-event-subscriptions.ts +++ b/packages/api/src/mcp-event-subscriptions.ts @@ -371,8 +371,8 @@ async function dispatchClaim(env: Env, claim: Claim, now: () => number) { `SELECT * FROM app.mcp_event_subscriptions WHERE tenant_id=$1 AND id=$2 FOR NO KEY UPDATE`, key.slice(0, 2), ); if (!subscription) return; - const { rows: [record] } = await sql.query<{ occurred_at: Date; definition_id: string; ack_epoch: string | null; ack_state: string | null }>( - `SELECT o.occurred_at,o.definition_id,d.ack_epoch,d.ack_state FROM app.mcp_event_deliveries d + const { rows: [record] } = await sql.query<{ occurred_at: Date; definition_id: string; source_identity: string; ack_epoch: string | null; ack_state: string | null }>( + `SELECT o.occurred_at,o.definition_id,o.source_identity,d.ack_epoch,d.ack_state FROM app.mcp_event_deliveries d JOIN app.event_occurrences o ON o.tenant_id=d.tenant_id AND o.id=d.occurrence_id WHERE d.tenant_id=$1 AND d.subscription_id=$2 AND d.occurrence_id=$3 AND d.claim_id=$4 FOR UPDATE OF d`, key, ); @@ -409,6 +409,10 @@ async function dispatchClaim(env: Env, claim: Claim, now: () => number) { WHERE tenant_id=$1 AND subscription_id=$2 AND occurrence_id=$3 AND claim_id=$4`, key); return; } + if (record.source_identity.startsWith("cloudflareTail:")) { + await cancel("source_retired"); + return; + } if (!subscriptionActive(subscription, claim)) { await cancel("subscription_inactive"); return; diff --git a/packages/api/src/postgres/schema.ts b/packages/api/src/postgres/schema.ts index 90abfbd8..57a12390 100644 --- a/packages/api/src/postgres/schema.ts +++ b/packages/api/src/postgres/schema.ts @@ -45,6 +45,18 @@ export const oauthDeviceAuthorizations = app.table("oauth_device_authorizations" export const members = app.table("members", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), userId: uuid("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), email: text("email").notNull(), role: text("role").$type<"owner" | "member">().notNull(), sessionVersion: integer("session_version").notNull().default(1), createdAt: createdAt(), }, t => [primaryKey({ columns: [t.tenantId, t.userId] }), check("members_role_check", sql`${t.role} in ('owner','member')`), check("members_session_version_check", sql`${t.sessionVersion} > 0`)]); +export const cloudflareConnections = app.table("cloudflare_connections", { + tenantId: uuid("tenant_id").notNull().references(() => tenants.id, { onDelete: "cascade" }), + id: uuid("id").notNull(), accountId: text("account_id").notNull(), name: text("account_name").notNull(), + writeEnabled: boolean("write_enabled").notNull(), encryptedCredentials: text("encrypted_credentials"), +}, t => [primaryKey({ columns: [t.tenantId, t.id] }), unique().on(t.tenantId, t.accountId)]); +export const cloudflareOauthAttempts = app.table("cloudflare_oauth_attempts", { + tenantId: uuid("tenant_id").primaryKey().references(() => tenants.id, { onDelete: "cascade" }), + userId: uuid("user_id").notNull().references(() => authUsers.id, { onDelete: "cascade" }), + sessionVersion: integer("session_version").notNull(), state: uuid("state").notNull().unique(), + verifier: text("verifier"), scopes: text("scopes").array().notNull(), writeRequested: boolean("write_requested").notNull(), + encryptedPending: text("encrypted_pending"), expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), +}, t => [index("cloudflare_oauth_expiry").on(t.expiresAt)]); export const authTotp = app.table("auth_totp", { userId: uuid("user_id").primaryKey().references(() => authUsers.id, { onDelete: "cascade" }), encryptedSecret: text("encrypted_secret").notNull(), lastCounter: bigint("last_counter", { mode: "bigint" }).notNull(), enabledAt: timestamp("enabled_at", { withTimezone: true }).notNull().defaultNow(), @@ -98,7 +110,7 @@ export const xOAuthAttempts = app.table("x_oauth_attempts", { }, t => [primaryKey({ columns: [t.tenantId, t.nonce] }), foreignKey({ columns: [t.tenantId, t.connectionId], foreignColumns: [xConnections.tenantId, xConnections.id] }).onDelete("cascade"), index("x_oauth_attempt_expiry").on(t.expiresAt)]); export const agentIntegrations = app.table("agent_integrations", { tenantId: uuid("tenant_id").notNull().references(() => tenants.id, {onDelete:"cascade"}), id: uuid("id").notNull().defaultRandom(), - kind: text("kind").$type<"bearer"|"github"|"linear"|"fly"|"exe"|"amp"|"clickup"|"x">().notNull(), credentialId: text("credential_id").notNull(), name:text("name").notNull(), description:text("description"), available:boolean("available").notNull(), + kind: text("kind").$type<"bearer"|"github"|"linear"|"fly"|"exe"|"amp"|"clickup"|"x"|"cloudflare">().notNull(), credentialId: text("credential_id").notNull(), name:text("name").notNull(), description:text("description"), available:boolean("available").notNull(), policy:text("policy").$type<"baseline"|"requestable"|"disabled">().notNull().default("requestable"),epoch:integer("epoch").notNull().default(1),revision:integer("revision").notNull().default(1), },t=>[primaryKey({columns:[t.tenantId,t.id]}),unique().on(t.tenantId,t.kind,t.credentialId)]); export const agentIdentities = app.table("agent_identities", { @@ -230,7 +242,7 @@ export const triggerSourceRelations = relations(triggerSources, ({ one }) => ({ })); export const databaseSchema = { - teamSettings, schemaMigrations, tenants, oauthConnections, googleSignInAttempts, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, authTotp, authTotpRecoveryCodes, authTotpEnrollments, authTotpChallenges, authTotpLimits, accessTokens, + teamSettings, schemaMigrations, tenants, oauthConnections, googleSignInAttempts, oauthConsentPreviews, authUsers, authAccounts, authResetTokens, authSessions, oauthDeviceAuthorizations, members, cloudflareConnections, cloudflareOauthAttempts, authTotp, authTotpRecoveryCodes, authTotpEnrollments, authTotpChallenges, authTotpLimits, accessTokens, connections, agentIntegrations, agentIdentities, agentProxyResponses, integrationCollections, integrationRecords, integrationChanges, linearWorkspaces, githubInstallations, githubSetupStates, eventDefinitions, eventDefinitionRevisions, eventOccurrences, mcpEventSubscriptions, mcpEventDeliveries, triggerMatches, triggers, triggerSources, webhookConditionsCutover, scheduleState, triggerEditDeliveries, triggerEvents, webhookDeliveries, webhookDeliveryEvents, pendingVerifications, tailFingerprints, wakeHints, tenantRelations, triggerRelations, triggerSourceRelations, diff --git a/packages/api/src/postgres/webhook-service.ts b/packages/api/src/postgres/webhook-service.ts index 5221cc5e..fa1a056a 100644 --- a/packages/api/src/postgres/webhook-service.ts +++ b/packages/api/src/postgres/webhook-service.ts @@ -1,5 +1,4 @@ import { clickUpJson, matchingClickUpTask } from "../clickup"; -import { verifyTailDelivery, sanitizeTailEvent, suppressTailEvent } from "../cloudflare-tail"; import { equalHmac } from "../crypto"; import type { Trigger } from "../trigger-domain"; import { evaluateWebhookConditions } from "../webhook-conditions"; @@ -82,10 +81,4 @@ export class WebhookService { if (!matched) await this.database.pool.query("UPDATE app.webhook_deliveries SET outcome='ignored',detail='Delivery was received but did not match an enabled event.' WHERE tenant_id=$1 AND id=$2", [this.tenantId, deliveryPk]); await this.wake(); } - async tail(triggerId: string, raw: string, headers: Headers) { - const candidate = (await this.candidates("cloudflareTail")).find(value => value.trigger.id === triggerId); if (!candidate?.config.integrationId) throw new Error("not_found"); - const connection = await this.connections.get(`cloudflare-tail:${candidate.config.integrationId}`), timestamp = headers.get("x-factorize-timestamp") ?? "", delivery = headers.get("x-factorize-delivery") ?? "", signature = headers.get("x-factorize-signature") ?? ""; - if (!connection?.signingSecret || await verifyTailDelivery(connection.signingSecret, timestamp, delivery, raw, signature) !== "valid") throw new Error("invalid_signature"); - const payload = sanitizeTailEvent(JSON.parse(raw)) as Record; if (!suppressTailEvent(payload)) await this.invoke("cloudflareTail", delivery, payload, "tail"); - } } diff --git a/packages/api/src/static-app.ts b/packages/api/src/static-app.ts index e31ca623..b2302644 100644 --- a/packages/api/src/static-app.ts +++ b/packages/api/src/static-app.ts @@ -19,7 +19,7 @@ export function securityHeaders(request: Request, response: Response) { const headers = new Headers(response.headers); if (!headers.has("Cache-Control")) headers.set("Cache-Control", "no-store"); headers.set("Content-Security-Policy", STATIC_CSP); - headers.set("Referrer-Policy", ["/auth/google", "/oauth/google/sign-in/callback"].includes(new URL(request.url).pathname) ? "no-referrer" : "same-origin"); + headers.set("Referrer-Policy", ["/auth/google", "/oauth/google/sign-in/callback", "/oauth/cloudflare/callback"].includes(new URL(request.url).pathname) ? "no-referrer" : "same-origin"); headers.set("X-Content-Type-Options", "nosniff"); headers.set("X-Frame-Options", "DENY"); headers.set("Permissions-Policy", "camera=(), microphone=(), geolocation=()"); diff --git a/packages/api/src/trigger-availability.ts b/packages/api/src/trigger-availability.ts index 3bd9c119..4b05122a 100644 --- a/packages/api/src/trigger-availability.ts +++ b/packages/api/src/trigger-availability.ts @@ -7,13 +7,13 @@ export type EventAvailability = { cloudflareTail: boolean; }; -export const installedEventAvailability = (linearConnected: boolean, clickupConnected: boolean, githubStates: string[], tailInstallationCount: number): EventAvailability => ({ +export const installedEventAvailability = (linearConnected: boolean, clickupConnected: boolean, githubStates: string[]): EventAvailability => ({ manual: true, schedule: true, linear: linearConnected, clickup: clickupConnected, github: githubStates.some(state => state === "active"), - cloudflareTail: tailInstallationCount > 0, + cloudflareTail: false, }); export const sameProviderReference = (next: Record, previous: Record): boolean => { diff --git a/packages/api/src/types.ts b/packages/api/src/types.ts index dcaefa31..2c12c952 100644 --- a/packages/api/src/types.ts +++ b/packages/api/src/types.ts @@ -5,6 +5,10 @@ export interface Env { SCHEDULER?: DurableObjectNamespace; ASSETS: Fetcher; APP_ORIGIN: string; + CLOUDFLARE_OAUTH_CLIENT_ID?: string; + CLOUDFLARE_OAUTH_CLIENT_SECRET?: string; + CLOUDFLARE_OAUTH_READ_SCOPES?: string; + CLOUDFLARE_OAUTH_WRITE_SCOPES?: string; MARKETING_ORIGIN?: string; TOTP_ENCRYPTION_KEY?: string; GOOGLE_SIGN_IN_START_LIMIT?: RateLimit; diff --git a/packages/api/src/worker.ts b/packages/api/src/worker.ts index e02cd43f..ae1b98c4 100644 --- a/packages/api/src/worker.ts +++ b/packages/api/src/worker.ts @@ -1,3 +1,4 @@ +import { cloudflareCallback, cloudflareOAuthCallback, pruneCloudflareOAuth } from "./cloudflare-oauth"; import { mcpOAuthChallenge, withRefreshAdmission } from "./mcp-oauth-auth"; import { pruneTotp } from "./totp"; import { googleSignInCallback } from "./auth-api"; @@ -97,6 +98,7 @@ export class AlarmCoordinator extends BaseAlarmCoordinator { } const backend = { async fetch(request: Request, env: Env, ctx: ExecutionContext) { if (new URL(request.url).hostname === "git.factorize.sh") return new Response("Not found", { status: 404 }); + if (new URL(request.url).pathname === cloudflareCallback) return cloudflareOAuthCallback(request, env); if (new URL(request.url).pathname === googleCallbackPath) return googleSignInCallback(request, env); if (new URL(request.url).pathname === "/oauth/x/callback") return request.method === "GET" ? xOAuthCallback(request, env) : new Response("Method not allowed", { status: 405, headers: { Allow: "GET" } }); const oidc = await oidcRequest(request, env); @@ -176,6 +178,7 @@ export default { // Retire expired VM proofs and incomplete enrollments. const db = databaseFor(env); await clearExpiredGoogleSignIns(db.pool); + await pruneCloudflareOAuth(db.pool); await pruneTotp(db.pool); await db.pool.query(`DELETE FROM app.revoked_browser_sessions WHERE digest IN (SELECT digest FROM app.revoked_browser_sessions WHERE expires_at ({ WorkerEntrypoint: class {}, DurableObject: class {} })); +vi.mock("@cloudflare/workers-oauth-provider", () => ({ OAuthProvider: class {}, AuthorizationError: class extends Error {}, getOAuthApi: vi.fn() })); + +const database = process.env.AUTH_TEST_DATABASE_URL; +const primary = "a".repeat(32), secondary = "b".repeat(32); +const zone = "c".repeat(32), foreignZone = "d".repeat(32); +const url = "/api/v1/integrations/cloudflare"; +const headers = (owner: string) => ({ Cookie: owner, Origin: "https://factorize.test", "Content-Type": "application/json" }); +const listScopes = ["account.read", "zone.read", "dns.read"]; +const secret = "fixture-confidential-client-secret", accessToken = "fixture-private-cloudflare-access", refreshToken = "fixture-private-refresh"; +const envelope = (result: unknown) => Response.json({ success: true, result }); + +it("routes only recognized Cloudflare resources and write shapes", () => { + expect(cloudflareTarget("/zones?page=2", "GET", primary, false).path).toBe("/client/v4/zones?page=2&account.id=" + primary); + expect(cloudflareTarget("/accounts", "GET", primary, false).path).toBe("/client/v4/accounts/" + primary); + expect(cloudflareTarget("/accounts/" + primary + "/workers/scripts", "GET", primary, false).path).toContain("/workers/scripts"); + for (const path of ["/accounts/" + secondary + "/r2/buckets", "/zones?account.id=" + secondary, "/user/tokens", "/accounts/" + primary + "/workers/scripts/example/settings"]) { + expect(() => cloudflareTarget(path, "GET", primary, true)).toThrow(); + } + expect(() => cloudflareTarget("/zones/" + zone + "/dns_records", "POST", primary, false)).toThrow(); + expect(cloudflareTarget("/zones/" + zone + "/dns_records", "POST", primary, true).zone).toBe(zone); +}); + +it.skipIf(!database)("connects through Cloudflare OAuth and enforces account, zone, and explicit write consent through request_api", async () => { + const f = await loadingFixture(database!); + try { + Object.assign(f.env, { CLOUDFLARE_OAUTH_CLIENT_ID: "fixture-public-client", CLOUDFLARE_OAUTH_CLIENT_SECRET: secret, + CLOUDFLARE_OAUTH_READ_SCOPES: listScopes.join(" "), CLOUDFLARE_OAUTH_WRITE_SCOPES: "dns.write" }); + let grantWrite = false; + const calls: { url: string; method: string; authorization: string | null }[] = []; + const fetcher = vi.fn(async (url: URL | string, init?: RequestInit) => { + const target = new URL(url); + const h = new Headers(init?.headers), method = init?.method ?? "GET"; + calls.push({ url: target.href, method, authorization: h.get("Authorization") }); + expect(h.has("x-auth-key")).toBe(false); + if (target.origin === "https://dash.cloudflare.com") { + expect(target.pathname).toBe("/oauth2/token"); + const body = init?.body as URLSearchParams; + expect(body.get("client_secret")).toBe(secret); + if (body.get("grant_type") === "authorization_code") expect(body.get("code_verifier")).toHaveLength(43); + if (body.get("grant_type") === "refresh_token") expect(body.get("refresh_token")).toBe(refreshToken); + return Response.json({ access_token: accessToken, refresh_token: refreshToken, expires_in: 3600, + token_type: "Bearer", scope: [...listScopes, ...(grantWrite ? ["dns.write"] : [])].join(" ") }); + } + expect(target.origin).toBe("https://api.cloudflare.com"); + expect(h.get("Authorization")).toBe("Bearer " + accessToken); + if (target.pathname === "/client/v4/accounts") return envelope([{ id: primary, name: "Primary account" }, { id: secondary, name: "Secondary account" }]); + if (target.pathname === "/client/v4/zones") { + expect(target.searchParams.get("account.id")).toBe(primary); + return envelope([{ id: zone, name: "example.test", account: { id: primary } }]); + } + if (target.pathname === "/client/v4/zones/" + zone) return envelope({ id: zone, account: { id: primary } }); + if (target.pathname === "/client/v4/zones/" + foreignZone) return envelope({ id: foreignZone, account: { id: secondary } }); + if (target.pathname === "/client/v4/zones/" + zone + "/dns_records" && method === "POST") return envelope({ id: zone }); + throw new Error("Unexpected mock provider call"); + }); + vi.stubGlobal("fetch", fetcher); + const api = (method: string, path: string, body?: unknown, cookie = f.cookie) => + protectedApiFetch(new Request(f.env.APP_ORIGIN + path, { method, headers: headers(cookie), body: body ? JSON.stringify(body) : undefined }), f.env, f.auth, {} as ExecutionContext); + const activate = async (writes: boolean) => { + const start = await api("POST", url + "/authorize", { enableWrites: writes }); + expect(start.status, await start.clone().text()).toBe(200); + const browser = start.headers.get("Set-Cookie")!.split(";")[0]; + const { authorizationUrl } = await start.json() as {authorizationUrl:string}; + const external = new URL(authorizationUrl); + expect(external.origin).toBe("https://dash.cloudflare.com"); + expect(external.searchParams.get("scope")?.includes("dns.write")).toBe(writes); + const returned = new URL(f.env.APP_ORIGIN + "/oauth/cloudflare/callback"); + returned.search = new URLSearchParams({ code: "authorized-fixture", state: external.searchParams.get("state")! }).toString(); + const oauth = await cloudflareOAuthCallback(new Request(returned, { headers: { Cookie: f.cookie + "; " + browser } }), f.env); + expect(oauth.status).toBe(303); + expect(oauth.headers.get("Location")).toBe(f.env.APP_ORIGIN + "/integrations?cloudflare=select"); + const available = await api("GET", url, undefined, f.cookie + "; " + browser); + const serialized = await available.text(); + for (const value of [secret, refreshToken, accessToken]) expect(serialized).not.toContain(value); + expect(JSON.parse(serialized).accounts.map((a: {id: string}) => a.id)).toEqual([primary, secondary]); + const saved = await api("POST", url + "/select", { accountId: primary }, f.cookie + "; " + browser); + expect(saved.status, await saved.clone().text()).toBe(200); + const output = await (await api("GET", url)).json() as { connections: { id:string; writeEnabled:boolean }[] }; + return output.connections[0]; + }; + // Even if an upstream token returns a write scope, a read-only Factorize + // authorization cannot use it. Successful write requires new owner consent. + grantWrite = true; + const readOnly = await activate(false); + expect(readOnly.writeEnabled).toBe(false); + const integration = async () => (await f.db.pool.query<{id:string;epoch:number}>("SELECT id,epoch FROM app.agent_integrations WHERE tenant_id=$1 AND kind='cloudflare'", [f.tenantId])).rows[0]; + const rpc = async (name: string, input: Record) => { + const row = await integration(); + const auth = { ...f.auth, authMethod: "oauth" as const, oauthGrantId: "fixture", oauthClientId: "fixture-client", oauthExpiresAt: Date.now()/1000 + 600, + scopes: ["proxy:use", `integration:${row.id}:${row.epoch}`] }; + return mcpRequest(f.env, auth)("tools/call", { name, arguments: { ...input, ...(name === "request_api" ? { integration: row.id, execution: "sync" } : {}) } }); + }; + expect((await rpc("get_api_reflection", {})).message.result.structuredContent.integrations).toEqual([expect.objectContaining({ kind: "cloudflare", access: "granted" })]); + expect((await rpc("request_api", { method: "GET", path: "/zones" })).message.result.structuredContent.status).toBe(200); + const body = JSON.stringify({ type: "TXT", name: "example.test", content: "fixture-text" }); + expect((await rpc("request_api", { method: "POST", path: "/zones/" + zone + "/dns_records", body })).message.result.isError).toBe(true); + expect((await rpc("request_api", { method: "GET", path: "/zones/" + foreignZone + "/dns_records" })).message.result.isError).toBe(true); + expect(calls.some(c => c.url.endsWith(foreignZone + "/dns_records"))).toBe(false); + grantWrite = false; + expect((await activate(true)).writeEnabled).toBe(false); + grantWrite = true; + const writable = await activate(true); + expect(writable.writeEnabled).toBe(true); + + // Advance the provider credential clock so the same connection refreshes. + vi.spyOn(Date, "now").mockReturnValue(Date.now() + 3_601_000); + const wrote = await rpc("request_api", { method: "POST", path: "/zones/" + zone + "/dns_records", body, + headers: { "Content-Type": "application/json", "X-Auth-Key": "fixture-must-not-forward" } }); + expect(wrote.message.result.structuredContent.status).toBe(200); + expect(calls.filter(c => c.url.endsWith("/oauth2/token"))).toHaveLength(4); + vi.restoreAllMocks(); + expect((await api("DELETE", url + "/" + writable.id)).status).toBe(200); + const disabled = await f.db.pool.query("SELECT encrypted_credentials FROM app.cloudflare_connections WHERE id=$1", [writable.id]); + expect(disabled.rows[0].encrypted_credentials).toBeNull(); + } finally { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + await f.cleanup(); + } +}); diff --git a/packages/api/test/mcp-events.postgres.test.ts b/packages/api/test/mcp-events.postgres.test.ts index aa990855..134718a1 100644 --- a/packages/api/test/mcp-events.postgres.test.ts +++ b/packages/api/test/mcp-events.postgres.test.ts @@ -127,6 +127,46 @@ describe.skipIf(!process.env.AUTH_TEST_DATABASE_URL)("MCP event webhook lifecycl "SELECT occurrence_id,status,attempts,http_status FROM app.mcp_event_deliveries ORDER BY updated_at,occurrence_id", )).rows; + it("retires Cloudflare Tail ingress and suppresses a queued Tail callback without removing history", async () => { + expect((await subscribe()).message.result).toBeDefined(); + const outcome = await new EventMatchRepository(f.db).match({ + tenantId: f.tenantId, triggerId: source.triggerId, triggerRevision: 1, + sourceIdentity: `cloudflareTail:${crypto.randomUUID()}`, deduplicationKey: "historical", + evidence: { text: "preserved" }, decision: "matched", + }); + expect((await outbox()).find(row => row.occurrence_id === outcome.occurrence?.id)).toMatchObject({ status: "pending" }); + const response = await app.fetch(new Request(`${f.env.APP_ORIGIN}/webhooks/cloudflare/${f.tenantId}/${source.triggerId}`, { + method: "POST", body: "old relay payload", + }), f.env, {} as ExecutionContext); + expect(response.status).toBe(410); + const ordinary = await fire("still active"); + await dispatchMcpEvents(f.env); + expect(deliveries.map(delivery => delivery.event.data.occurrenceId)).toEqual([ordinary.occurrenceId]); + expect((await outbox()).find(row => row.occurrence_id === outcome.occurrence?.id)).toMatchObject({ status: "cancelled", attempts: 0 }); + expect((await f.db.pool.query("SELECT id FROM app.event_occurrences WHERE id=$1", [outcome.occurrence?.id])).rowCount).toBe(1); + }); + + it("shows old Tail sources as retired, rejects new ones, and permits removing the existing source", async () => { + const legacyId = crypto.randomUUID(), integrationId = crypto.randomUUID(); + const legacy = { id: legacyId, kind: "webhook", enabled: true, config: { provider: "cloudflareTail", integrationId } }; + await f.db.pool.query(`INSERT INTO app.events(tenant_id,id,trigger_id,kind,slug,position,config) + VALUES ($1,$2,$3,'webhook','legacy-tail',2,$4)`, [f.tenantId, legacyId, source.triggerId, legacy.config]); + const rest = (path: string, method = "GET", body?: unknown) => worker.fetch(new Request(f.env.APP_ORIGIN + path, { + method, headers: { Cookie: f.cookie, Origin: f.env.APP_ORIGIN, "Content-Type": "application/json" }, + body: body === undefined ? undefined : JSON.stringify(body), + }), f.env, {} as ExecutionContext); + const path = `/api/v1/triggers/${source.triggerId}`; + const payload = { name: "fixture-trigger", eventId: source.definitionId }; + expect((await (await rest(path)).json() as any).sources).toContainEqual(expect.objectContaining({ + id: legacyId, enabled: false, config: legacy.config, + })); + expect((await rest("/api/v1/triggers", "POST", { ...payload, sources: [legacy] })).status).toBe(400); + expect((await rest(path, "PUT", { ...payload, sources: [legacy] })).status).toBe(200); + const removed = await rest(path, "PUT", { ...payload, sources: [{ kind: "manual", enabled: true, config: {} }] }); + expect(removed.status).toBe(200); + expect((await removed.json() as any).sources).not.toContainEqual(expect.objectContaining({ id: legacyId })); + }); + it.each(["/api/v1/auth/logout", "/auth/logout"])("keeps existing MCP webhook deliveries active after browser sign-out via %s", async logoutPath => { const cookie2 = "factorize_session=" + encodeURIComponent(await signSession({ ...f.auth, email: "owner@example.test", exp: Math.floor(Date.now() / 1000) + 3600, browserNonce: crypto.randomUUID(), diff --git a/packages/api/test/trigger-availability.test.ts b/packages/api/test/trigger-availability.test.ts index d293dc5e..b4ce16c1 100644 --- a/packages/api/test/trigger-availability.test.ts +++ b/packages/api/test/trigger-availability.test.ts @@ -3,19 +3,19 @@ import { installedEventAvailability, sameProviderReference } from "../src/trigge describe("trigger event availability", () => { it("only offers universal events with zero installations", () => { - expect(installedEventAvailability(false, false, [], 0)).toEqual({ manual: true, schedule: true, linear: false, clickup: false, github: false, cloudflareTail: false }); + expect(installedEventAvailability(false, false, [])).toEqual({ manual: true, schedule: true, linear: false, clickup: false, github: false, cloudflareTail: false }); }); it("offers each provider for one matching installation", () => { - expect(installedEventAvailability(true, true, ["active"], 1)).toMatchObject({ linear: true, clickup: true, github: true, cloudflareTail: true }); + expect(installedEventAvailability(true, true, ["active"])).toMatchObject({ linear: true, clickup: true, github: true, cloudflareTail: false }); }); it("handles multiple installations without changing the provider result", () => { - expect(installedEventAvailability(true, true, ["active", "active"], 2)).toMatchObject({ github: true, cloudflareTail: true }); + expect(installedEventAvailability(true, true, ["active", "active"])).toMatchObject({ github: true, cloudflareTail: false }); }); it("ignores disconnected and stale GitHub installations", () => { - expect(installedEventAvailability(false, false, ["removed", "suspended"], 0)).toMatchObject({ linear: false, clickup: false, github: false, cloudflareTail: false }); + expect(installedEventAvailability(false, false, ["removed", "suspended"])).toMatchObject({ linear: false, clickup: false, github: false, cloudflareTail: false }); }); it("preserves a stale event only when its installation reference is unchanged", () => { diff --git a/packages/app/src/features/settings/cloudflare.tsx b/packages/app/src/features/settings/cloudflare.tsx new file mode 100644 index 00000000..65ec1b87 --- /dev/null +++ b/packages/app/src/features/settings/cloudflare.tsx @@ -0,0 +1,81 @@ +import { useState } from "react"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { api } from "factorize-api-client"; +import { Button, Label } from "../../shared/ui"; +import { Dialog } from "../../shared/dialog"; +import { messageOf } from "../auth/session"; +import { IntegrationRow, ProviderTile } from "./integration-ui"; + +const paths = { + status: "/api/v1/integrations/cloudflare", + authorize: "/api/v1/integrations/cloudflare/authorize", + select: "/api/v1/integrations/cloudflare/select", + connection: "/api/v1/integrations/cloudflare/{connectionId}", +} as const; +const key = ["settings", "cloudflare-rest"]; +export function useCloudflareIntegration() { + const cache = useQueryClient(); + const [open, setOpen] = useState(false); + const [writes, setWrites] = useState(false); + const [accountId, setAccountId] = useState(""); + const result = new URLSearchParams(window.location.search).get("cloudflare"); + const status = useQuery({ queryKey: key, retry: false, queryFn: async ({ signal }) => { + const { data, error } = await api.GET(paths.status, { signal }); + if (!data || error) throw new Error(messageOf(error)); + return data; + }}); + const authorize = useMutation({ retry: false, mutationFn: async () => { + const { data, error } = await api.POST(paths.authorize, { body: { enableWrites: writes } }); + if (!data || error) throw new Error(messageOf(error)); + return data.authorizationUrl; + }, onSuccess: url => window.location.assign(url) }); + const select = useMutation({ retry: false, mutationFn: async (accountId: string) => { + const { error } = await api.POST(paths.select, { body: { accountId } }); + if (error) throw new Error(messageOf(error)); + }, onSuccess: async () => { + window.history.replaceState(window.history.state, "", "/integrations"); + setAccountId(""); + await cache.invalidateQueries({ queryKey: ["settings"] }); + }}); + const disconnect = useMutation({ retry: false, mutationFn: async (id: string) => { + const { error } = await api.DELETE(paths.connection, { params: { path: { connectionId: id } } }); + if (error) throw new Error(messageOf(error)); + }, onSuccess: () => cache.invalidateQueries({ queryKey: ["settings"] }) }); + const data = status.data; + const connections = data?.connections?.filter(row => row.connected) ?? []; + const start = () => { setWrites(false); authorize.reset(); setOpen(true); }; + const accounts = data?.accounts ?? []; + const feedback = <> + {(result === "failed" || result === "expired" || result === "denied") &&

Cloudflare did not complete authorization. Start a new connection when you’re ready.

} + {result === "select" && !accounts.length && !status.isPending && !select.isSuccess &&

The Cloudflare account selection expired. Start a new connection.

} + {status.error &&

{status.error.message}

} + {disconnect.error &&

{disconnect.error.message}

} + {accounts.length > 0 &&
{ + event.preventDefault(); + if (accountId && !select.isPending) select.mutate(accountId); + }}> + + + {select.error &&

{select.error.message}

} +
} + ; + return { count: connections.length, pending: status.isPending, feedback, + rows: connections.map(row => { + if (window.confirm("Disconnect this Cloudflare account from Factorize?")) disconnect.mutate(row.id); + }}]} />), + tile: , + dialog: open && setOpen(false)}> +

Authorize Factorize on Cloudflare, then select one account to connect. No API key is needed.

+ {!data?.configured ?

Cloudflare OAuth has not been configured for this deployment.

: <> + {data.writeAvailable && } + + } + {authorize.error &&

{authorize.error.message}

} +
, + }; +} diff --git a/packages/app/src/features/settings/icon.tsx b/packages/app/src/features/settings/icon.tsx index d61099ae..02db8241 100644 --- a/packages/app/src/features/settings/icon.tsx +++ b/packages/app/src/features/settings/icon.tsx @@ -9,6 +9,7 @@ const icons: Record = { fly: , bearer: , model: , + cloudflare: , tail: , }; export function IntegrationIcon({ kind }: { kind: string }) { return ; } diff --git a/packages/app/src/features/settings/integration-form.tsx b/packages/app/src/features/settings/integration-form.tsx index 7ca6e7d6..7292b7af 100644 --- a/packages/app/src/features/settings/integration-form.tsx +++ b/packages/app/src/features/settings/integration-form.tsx @@ -1,32 +1,27 @@ import { SecretInput } from "../../shared/credential-fields"; -import { Button, Input, Label, Card } from "../../shared/ui"; +import { Button, Input, Label } from "../../shared/ui"; import { AutosaveStatus, useDebouncedAutosave } from "../../shared/use-debounced-autosave"; import { useRef, useState } from "react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { api } from "factorize-api-client"; import { messageOf } from "../auth/session"; -export function IntegrationForm({ kind, connectionId, initialName = "", initialApiBaseUrl }: { kind: "exe" | "amp" | "cloudflareTail"; connectionId?: string; initialName?: string; initialApiBaseUrl?: string }) { - const cache = useQueryClient(), [credential, setCredential] = useState(""), [name, setName] = useState(initialName), [generatedSecret, setGeneratedSecret] = useState(""), [savedFeedback, setSavedFeedback] = useState(false), savedSnapshot = useRef(""); +export function IntegrationForm({ kind, connectionId, initialName = "", initialApiBaseUrl }: { kind: "exe" | "amp"; connectionId?: string; initialName?: string; initialApiBaseUrl?: string }) { + const cache = useQueryClient(), [credential, setCredential] = useState(""), [name, setName] = useState(initialName), [savedFeedback, setSavedFeedback] = useState(false), savedSnapshot = useRef(""); const save = useMutation({ retry: false, mutationFn: async () => { if (kind === "exe") { const { data, error } = await api.PUT("/api/v1/integrations/exe", { body: { apiToken: credential || undefined, connectionId } }); if (!data || error) throw new Error(messageOf(error)); return { saved: true }; } if (kind === "amp") { const { data, error } = await api.PUT("/api/v1/integrations/amp", { body: { accessToken: credential || undefined, project: name || undefined, apiBaseUrl: initialApiBaseUrl, connectionId } }); if (!data || error) throw new Error(messageOf(error)); return { saved: true }; } - const body = { name, signingSecret: credential || undefined, generateSecret: !credential && !connectionId }; - const { data, error } = connectionId ? await api.PUT("/api/v1/integrations/cloudflare-tail/{integrationId}", { params: { path: { integrationId: connectionId } }, body }) : await api.POST("/api/v1/integrations/cloudflare-tail", { body }); - if (!data || error) throw new Error(messageOf(error)); setGeneratedSecret(data.generatedSecret ?? ""); return { saved: true }; }, onSuccess: async () => { setCredential(""); setSavedFeedback(true); await cache.invalidateQueries({ queryKey: ["settings"] }); await cache.invalidateQueries({ queryKey: ["providers"] }); await cache.invalidateQueries({ queryKey: ["editor"] }); } }); const value = { credential, name }; if (!savedSnapshot.current) savedSnapshot.current = JSON.stringify({ credential: "", name: initialName }); const validate = (next: typeof value) => { if ((kind !== "exe" && !next.name.trim()) || next.name.trim().length > 120) return "Enter a valid integration name."; - if (kind === "cloudflareTail" && next.credential && next.credential.length < 16) return "Tail signing secrets must be at least 16 characters."; return undefined; }; const autosave = useDebouncedAutosave({ value, enabled: Boolean(connectionId) && JSON.stringify(value) !== savedSnapshot.current, validate, save: async next => { await save.mutateAsync(); savedSnapshot.current = JSON.stringify({ ...next, credential: "" }); } }); return
{ e.preventDefault(); save.mutate(); }}> - {kind !== "exe" && } - + {kind !== "exe" && } + {!connectionId && } {connectionId && }{!connectionId && savedFeedback &&

Integration saved

}{[save.error].filter(Boolean).map((error, index) =>

{error?.message}

)} - {generatedSecret &&

Copy this signing secret now; it is displayed only once.

{generatedSecret}
} ; } diff --git a/packages/app/src/features/settings/integrations.tsx b/packages/app/src/features/settings/integrations.tsx index 56d69e3b..dfea252a 100644 --- a/packages/app/src/features/settings/integrations.tsx +++ b/packages/app/src/features/settings/integrations.tsx @@ -1,3 +1,4 @@ +import { useCloudflareIntegration } from "./cloudflare"; import { useDisableCredentialAutofill } from "../../shared/credential-fields"; import { useState, type ReactNode } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; @@ -23,34 +24,30 @@ export function Integrations() { function IntegrationsContent() { const cache = useQueryClient(), status = useQuery(integrationsQuery), github = useQuery(installationsQuery); const fly = useFlyIntegration(), bearer = useBearerIntegrations(), x = useXConnections(); + const cloudflare = useCloudflareIntegration(); const [setup, setSetup] = useState<{title: string; form: ReactNode} | null>(null); const [feedback, setFeedback] = useState<{key: string; message: string; error: boolean} | null>(null); - const action = useMutation({retry: false, mutationFn: async ({kind, id, test}: {kind: Kind; id: string; test?: boolean}) => { + const action = useMutation({retry: false, mutationFn: async ({kind, id}: {kind: Kind; id: string}) => { let result; if (kind === "exe") result = await api.DELETE("/api/v1/integrations/exe/{connectionId}", {params: {path: {connectionId: id}}}); else if (kind === "amp") result = await api.DELETE("/api/v1/integrations/amp/{connectionId}", {params: {path: {connectionId: id}}}); - else if (kind === "cloudflareTail") result = test ? await api.POST("/api/v1/integrations/cloudflare-tail/{integrationId}/test", {params: {path: {integrationId: id}}}) : await api.DELETE("/api/v1/integrations/cloudflare-tail/{integrationId}", {params: {path: {integrationId: id}}}); + else if (kind === "cloudflareTail") result = await api.DELETE("/api/v1/integrations/cloudflare-tail/{integrationId}", {params: {path: {integrationId: id}}}); else result = await api.DELETE("/api/v1/providers/github/installations/{installationId}", {params: {path: {installationId: id}}}); if (result.error) throw new Error(messageOf(result.error)); - if (test && (!result.data || !("ok" in result.data) || result.data.ok !== true)) { - const missing = result.data && "missingPermissions" in result.data && Array.isArray(result.data.missingPermissions) ? result.data.missingPermissions.filter((permission): permission is string => typeof permission === "string") : []; - throw new Error(missing.length ? `Connection verification failed. Missing exe.dev permissions: ${missing.join(", ")}.` : "Connection verification failed."); - } return result.data; }, onSuccess: async (_result, variables) => { - setFeedback({key: `${variables.kind}:${variables.id}`, message: variables.test ? "Connection verified." : "Integration disconnected.", error: false}); + setFeedback({key: `${variables.kind}:${variables.id}`, message: "Integration disconnected.", error: false}); await Promise.all([cache.invalidateQueries({queryKey: ["settings"]}), cache.invalidateQueries({queryKey: ["providers"]}), cache.invalidateQueries({queryKey: ["editor"]})]); }, onError: (error, variables) => setFeedback({key: `${variables.kind}:${variables.id}`, message: error.message, error: true})}); const actions = (kind: Kind, id: string, edit?: () => void): IntegrationAction[] => [ ...(edit ? [{label: "Edit integration", onClick: edit}] : []), - ...(kind === "cloudflareTail" ? [{label: "Test connection", disabled: action.isPending, onClick: () => {setFeedback(null); action.mutate({kind, id, test: true});}}] : []), {label: "Disconnect", destructive: true, disabled: action.isPending, onClick: () => {if (window.confirm("Disconnect this integration? Triggers that still reference it must be updated first.")) {setFeedback(null); action.mutate({kind, id});}}}, ]; const result = (key: string) => feedback?.key === key &&

{feedback.message}

; const open = (title: string, form: ReactNode) => setSetup({title, form}); const data = status.data; - const count = (data?.linear ? 1 : 0) + (data?.clickup ? 1 : 0) + (github.data?.length ?? 0) + (data?.exeConnections.length ?? 0) + (data?.ampConnections.length ?? 0) + (data?.cloudflareTail.installations.length ?? 0) + fly.count + bearer.count + x.count; - const pending = status.isPending || github.isPending || fly.pending || bearer.pending || x.pending; + const count = (data?.linear ? 1 : 0) + (data?.clickup ? 1 : 0) + (github.data?.length ?? 0) + (data?.exeConnections.length ?? 0) + (data?.ampConnections.length ?? 0) + (data?.cloudflareTail.installations.length ?? 0) + fly.count + bearer.count + x.count + cloudflare.count; + const pending = status.isPending || github.isPending || fly.pending || bearer.pending || x.pending || cloudflare.pending; return <> {[status.error, github.error].filter(Boolean).map((error, i) =>

{error?.message}

)}

Installed Integrations

Manage workspace connections. Default API access applies to connected MCP clients; other access requires approval.

@@ -62,11 +59,11 @@ function IntegrationsContent() { {github.data?.map(i => {result(`github:${i.installationId}`)})} {data?.exeConnections.map(c => open("Edit exe.dev integration", ))}>{result(`exe:${c.connectionId}`)})} {data?.ampConnections.map(c => open("Edit Amp integration", ))}>{result(`amp:${c.connectionId}`)})} - {fly.rows}{bearer.rows}{x.rows} - {data?.cloudflareTail.installations.map(c => open("Edit Tail integration", ))}>{result(`cloudflareTail:${c.integrationId}`)})} + {fly.rows}{bearer.rows}{x.rows}{cloudflare.rows} + {data?.cloudflareTail.installations.map(c => {result(`cloudflareTail:${c.integrationId}`)})} } {feedback && !feedback.error && feedback.message === "Integration disconnected." &&

Integration disconnected.

} - {fly.feedback}{bearer.feedback}{x.feedback} + {fly.feedback}{bearer.feedback}{x.feedback}{cloudflare.feedback}

Available integrations

Choose a provider to connect or configure an integration.

    @@ -74,9 +71,8 @@ function IntegrationsContent() { open("Add exe.dev integration", )} /> open("Add Amp integration", )} /> - {fly.tile}{bearer.tile}{x.tile} - open("Add Tail integration", )} /> + {fly.tile}{bearer.tile}{x.tile}{cloudflare.tile}
- {setup && setSetup(null)}>{setup.form}}{fly.dialog}{bearer.dialog}{x.dialog} + {setup && setSetup(null)}>{setup.form}}{fly.dialog}{bearer.dialog}{x.dialog}{cloudflare.dialog} ; } diff --git a/packages/app/src/features/triggers/editor.tsx b/packages/app/src/features/triggers/editor.tsx index f1803435..c0a4aa75 100644 --- a/packages/app/src/features/triggers/editor.tsx +++ b/packages/app/src/features/triggers/editor.tsx @@ -10,12 +10,16 @@ export function TriggerEditor() { const params = useParams({ strict: false }), id = params.triggerId; const navigate = useNavigate(), cache = useQueryClient(); const current = useQuery({ ...triggerQuery(id ?? ""), enabled: !!id }), events = useQuery(eventsQuery()); const [name, setName] = useState(""), [eventId, setEventId] = useState(""), [kind, setKind] = useState<"manual" | "schedule" | "webhook">("manual"), [cron, setCron] = useState("0 * * * *"), [timezone, setTimezone] = useState("UTC"), [webhook, setWebhook] = useState('{"provider":"linear","projectId":"","matchRules":[]}'); + const [removeRetired, setRemoveRetired] = useState(false); + const retiredSources = current.data?.sources.flatMap(source => source.kind === "webhook" && source.config.provider === "cloudflareTail" ? [{ id: source.id, integrationId: source.config.integrationId }] : []) ?? []; const [initialized, setInitialized] = useState(false); - if (current.data && !initialized) { setName(current.data.name); setEventId(current.data.eventId ?? ""); const source = current.data.sources[0]; if (source?.kind === "schedule") { setKind("schedule"); setCron(source.config.cron); setTimezone(source.config.timezone); } else if (source?.kind === "webhook") { setKind("webhook"); setWebhook(JSON.stringify(source.config, null, 2)); } setInitialized(true); } + if (current.data && !initialized) { setName(current.data.name); setEventId(current.data.eventId ?? ""); const source = current.data.sources.find(source => source.kind !== "webhook" || source.config.provider !== "cloudflareTail"); if (source?.kind === "schedule") { setKind("schedule"); setCron(source.config.cron); setTimezone(source.config.timezone); } else if (source?.kind === "webhook") { setKind("webhook"); setWebhook(JSON.stringify(source.config, null, 2)); } setInitialized(true); } const inputSource: InputSource | undefined = kind === "manual" ? { kind, enabled: true, config: {} } : kind === "schedule" ? { kind, enabled: true, config: { cron, timezone } } : (() => { try { const config = JSON.parse(webhook); return { kind, enabled: true, config } as InputSource; } catch { return undefined; } })(); const save = useMutation({ mutationFn: async () => { if (!inputSource) throw new Error("Webhook configuration must be valid JSON."); - const body = { name, eventId, sources: [inputSource] }; + const retired = removeRetired ? [] : retiredSources.map(source => ({ id: source.id, kind: "webhook" as const, enabled: false, + config: { provider: "cloudflareTail" as const, integrationId: source.integrationId } })); + const body = { name, eventId, sources: [inputSource, ...retired] }; const result = id ? await api.PUT("/api/v1/triggers/{triggerId}", { params: { path: { triggerId: id } }, body }) : await api.POST("/api/v1/triggers", { body }); if (!result.data || result.error) throw new Error(messageOf(result.error)); return result.data; }, onSuccess: async trigger => { await Promise.all([cache.invalidateQueries({ queryKey: ["triggers"] }), cache.invalidateQueries({ queryKey: ["events"] })]); await navigate({ to: "/triggers/$triggerId", params: { triggerId: trigger.id } }); } }); @@ -25,6 +29,8 @@ export function TriggerEditor() { + {retiredSources.length > 0 &&

Cloudflare Tail is retired. These sources no longer deliver events.

+
} {kind === "schedule" && <>} {kind === "webhook" &&