diff --git a/docs/custom-sources-rollout.md b/docs/custom-sources-rollout.md index c212a2a8..1c973ce3 100644 --- a/docs/custom-sources-rollout.md +++ b/docs/custom-sources-rollout.md @@ -2,10 +2,8 @@ Custom sources remain disabled unless `CUSTOM_SOURCES_ENABLED=true`. Before enabling them: -1. Provision the `factorize-custom-handlers` Workers for Platforms dispatch namespace in default untrusted mode. -2. Deploy `wrangler.custom-egress.jsonc` and configure that service as the namespace outbound Worker. The outbound Worker always returns 403 and does not inspect or log requests; configuring it also disables outbound TCP. -3. Deploy `wrangler.custom-deployer.jsonc`. Store the least-privilege Workers Scripts API token as its `CLOUDFLARE_API_TOKEN` secret and configure `CLOUDFLARE_ACCOUNT_ID` there. The main Factorize Worker receives only a service binding; management credentials are never present in tenant objects or user Workers. -4. Run production probes that attempt HTTP and TCP egress, service binding access, cache persistence, and reads of secrets and every supported binding. Enable only when every access fails. -5. Enable one internal tenant and monitor deployment/invocation failures, CPU termination, outbound attempts, and overflow drops. +1. Confirm the `CUSTOM_HANDLER_LOADER` Dynamic Worker Loader binding is available in production. +2. Run production probes that attempt HTTP and TCP egress, service binding access, cache persistence, and reads of secrets and every supported binding. Dynamic handlers receive an empty environment and `globalOutbound: null`; enable only when every access fails. +3. Enable one internal tenant and monitor invocation failures, CPU termination, and overflow drops. Custom triggers are intentionally lossy once a flow has 100 pending jobs. Valid signed provider deliveries are still acknowledged to prevent retry storms. diff --git a/src/custom-deployer.ts b/src/custom-deployer.ts deleted file mode 100644 index 227edadd..00000000 --- a/src/custom-deployer.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { CUSTOM_HANDLER_COMPATIBILITY_DATE } from "./custom-handler"; - -type DeployerEnv = { CLOUDFLARE_ACCOUNT_ID: string; CLOUDFLARE_API_TOKEN: string; CUSTOM_DISPATCH_NAMESPACE: string }; -const scriptPattern = /^fh-[a-f0-9]{40}$/; - -export default { - async fetch(request: Request, env: DeployerEnv): Promise { - const url = new URL(request.url); - let scriptName: string; - let init: RequestInit; - if (request.method === "PUT" && url.pathname === "/scripts") { - const input = await request.json() as { scriptName?: unknown; module?: unknown }; - if (typeof input.scriptName !== "string" || !scriptPattern.test(input.scriptName) || typeof input.module !== "string") return new Response("Invalid deployment", { status: 400 }); - scriptName = input.scriptName; - const metadata = { main_module: "worker.mjs", compatibility_date: CUSTOM_HANDLER_COMPATIBILITY_DATE, bindings: [] }; - const form = new FormData(); - form.set("metadata", new Blob([JSON.stringify(metadata)], { type: "application/json" })); - form.set("worker.mjs", new Blob([input.module], { type: "application/javascript+module" }), "worker.mjs"); - init = { method: "PUT", body: form }; - } else if (request.method === "DELETE") { - scriptName = decodeURIComponent(url.pathname.slice("/scripts/".length)); - if (!url.pathname.startsWith("/scripts/") || !scriptPattern.test(scriptName)) return new Response("Invalid deployment", { status: 400 }); - init = { method: "DELETE" }; - } else return new Response("Not found", { status: 404 }); - const response = await fetch(`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(env.CLOUDFLARE_ACCOUNT_ID)}/workers/dispatch/namespaces/${encodeURIComponent(env.CUSTOM_DISPATCH_NAMESPACE)}/scripts/${scriptName}`, { ...init, headers: { Authorization: `Bearer ${env.CLOUDFLARE_API_TOKEN}` } }); - return new Response(null, { status: response.status }); - }, -}; diff --git a/src/custom-egress-deny.ts b/src/custom-egress-deny.ts deleted file mode 100644 index 858e5877..00000000 --- a/src/custom-egress-deny.ts +++ /dev/null @@ -1,3 +0,0 @@ -// Outbound Worker for the custom dispatch namespace. It intentionally does not -// inspect, resolve, log, authenticate, or forward attacker-controlled requests. -export default { fetch(): Response { return new Response(null, { status: 403 }); } }; diff --git a/src/custom-handler.ts b/src/custom-handler.ts index 976d92db..d1d4e852 100644 --- a/src/custom-handler.ts +++ b/src/custom-handler.ts @@ -1,4 +1,4 @@ -import type { CustomOrigin, CustomSource, Env } from "./types"; +import type { CustomOrigin, CustomSource } from "./types"; export const CUSTOM_HANDLER_SCAFFOLD = `function handler(webhook) { return true; @@ -48,14 +48,21 @@ export default { async fetch(request) { } };`; } -export async function invokeCustomHandler(dispatch: DispatchNamespace, source: CustomSource, payload: unknown): Promise { +export async function invokeCustomHandler(loader: WorkerLoader, source: CustomSource, payload: unknown): Promise { const body = JSON.stringify(payload); if (encoder.encode(body).byteLength > CUSTOM_HANDLER_MAX_PAYLOAD_BYTES) return { ok: false, category: "platform_error" }; const controller = new AbortController(); const deadline = setTimeout(() => controller.abort(), CUSTOM_HANDLER_DEADLINE_MS); try { - const worker = dispatch.get(source.handlerDeployment.scriptName, {}, { limits: { cpuMs: 10, subRequests: 1 } }); - const response = await worker.fetch("https://handler.internal/", { method: "POST", headers: { "Content-Type": "application/json" }, body, signal: controller.signal }); + const worker = loader.load({ + compatibilityDate: CUSTOM_HANDLER_COMPATIBILITY_DATE, + mainModule: "worker.js", + modules: { "worker.js": userWorkerModule(source.handlerCode) }, + env: {}, + globalOutbound: null, + limits: { cpuMs: 10, subRequests: 0 }, + }); + const response = await worker.getEntrypoint().fetch("https://handler.internal/", { method: "POST", headers: { "Content-Type": "application/json" }, body, signal: controller.signal }); if (!response.ok) return { ok: false, category: "platform_error" }; const result = await response.json() as HandlerDecision; return result?.ok === true && typeof result.decision === "boolean" ? result : result?.ok === false && ["handler_error", "invalid_return", "timeout", "platform_error"].includes(result.category) ? result : { ok: false, category: "platform_error" }; @@ -64,18 +71,9 @@ export async function invokeCustomHandler(dispatch: DispatchNamespace, source: C } finally { clearTimeout(deadline); } } -export async function deployCustomHandler(env: Env, tenantId: string, flowId: string, source: Omit, previous?: CustomSource): Promise { - if (!env.CUSTOM_DEPLOYER) throw new Error("Custom handler deployment is not configured."); +export async function prepareCustomHandler(tenantId: string, flowId: string, source: Omit, previous?: CustomSource): Promise { const scriptName = await customScriptName(tenantId, flowId); const codeDigest = await sha256(source.handlerCode); if (previous?.handlerDeployment.state === "ready" && previous.handlerDeployment.codeDigest === codeDigest) return { ...source, handlerDeployment: previous.handlerDeployment }; - const response = await env.CUSTOM_DEPLOYER.fetch("https://deployer.internal/scripts", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ scriptName, module: userWorkerModule(source.handlerCode) }) }); - if (!response.ok) throw new Error(`Handler deployment failed (${response.status}).`); return { ...source, handlerDeployment: { scriptName, codeDigest, state: "ready" } }; } - -export async function deleteCustomHandler(env: Env, scriptName: string): Promise { - if (!env.CUSTOM_DEPLOYER) return false; - const response = await env.CUSTOM_DEPLOYER.fetch(`https://deployer.internal/scripts/${encodeURIComponent(scriptName)}`, { method: "DELETE" }); - return response.ok || response.status === 404; -} diff --git a/src/index.ts b/src/index.ts index 27a9fb7a..1d6b80d3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,7 +7,7 @@ import { createAppJwt, githubHeaders, readSetupState, signSetupState } from "./g import { flowDetailPage, flowPage, flowsPage, landingPage } from "./ui"; import type { Env } from "./types"; import type { CustomSource, PipeInput } from "./types"; -import { deleteCustomHandler, deployCustomHandler, invokeCustomHandler, validateCustomHandler } from "./custom-handler"; +import { invokeCustomHandler, prepareCustomHandler, validateCustomHandler } from "./custom-handler"; const app = new Hono<{ Bindings: Env; Variables: { cspNonce: string } }>(); @@ -171,18 +171,14 @@ app.post("/api/connections/exe/test", async (c) => { app.post("/api/pipes", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); const input = await c.req.json() as PipeInput; - let newlyDeployed: CustomSource | undefined; if (input.source?.kind === "custom") { if (c.env.CUSTOM_SOURCES_ENABLED !== "true") return c.json({ error: "Custom sources are not enabled." }, 404); const valid = validateCustomHandler(input.source.origin, input.source.handlerName, input.source.handlerCode); const pipeId = crypto.randomUUID(); input.pipeId = pipeId; - newlyDeployed = await deployCustomHandler(c.env, session.tenantId, pipeId, { kind: "custom", ...valid }); - input.source = newlyDeployed; + input.source = await prepareCustomHandler(session.tenantId, pipeId, { kind: "custom", ...valid }); } - const response = await tenant(c, session.tenantId).fetch("https://tenant/pipes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); - if (!response.ok && newlyDeployed) await deleteCustomHandler(c.env, newlyDeployed.handlerDeployment.scriptName); - return response; + return tenant(c, session.tenantId).fetch("https://tenant/pipes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); }); app.put("/api/pipes/:id", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); @@ -195,31 +191,24 @@ app.put("/api/pipes/:id", async (c) => { let previous: CustomSource | undefined; try { const source = JSON.parse(current.flow.source_config ?? "{}"); if (source.kind === "custom") previous = source; } catch { /* fail closed */ } const valid = validateCustomHandler(input.source.origin, input.source.handlerName, input.source.handlerCode); - input.source = await deployCustomHandler(c.env, session.tenantId, pipeId, { kind: "custom", ...valid }, previous); + input.source = await prepareCustomHandler(session.tenantId, pipeId, { kind: "custom", ...valid }, previous); } return tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(pipeId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); }); app.delete("/api/pipes/:id", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); const pipeId = c.req.param("id"); - const currentResponse = await tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(pipeId)}`); - if (!currentResponse.ok) return currentResponse; - const current = await currentResponse.json() as { flow: { source_config?: string } }; - const response = await tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(pipeId)}`, { method: "DELETE" }); - if (response.ok) { try { const source = JSON.parse(current.flow.source_config ?? "{}"); if (source.kind === "custom") await deleteCustomHandler(c.env, source.handlerDeployment.scriptName); } catch { /* cleanup reconciliation can retry */ } } - return response; + return tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(pipeId)}`, { method: "DELETE" }); }); app.post("/api/custom-handlers/test", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); - if (c.env.CUSTOM_SOURCES_ENABLED !== "true" || !c.env.CUSTOM_HANDLERS) return c.json({ error: "Custom sources are not enabled." }, 404); + if (c.env.CUSTOM_SOURCES_ENABLED !== "true" || !c.env.CUSTOM_HANDLER_LOADER) return c.json({ error: "Custom sources are not enabled." }, 404); const input = await c.req.json() as { origin?: unknown; handlerName?: unknown; handlerCode?: unknown; payload?: unknown }; const valid = validateCustomHandler(input.origin, input.handlerName, input.handlerCode); const testId = `test-${crypto.randomUUID()}`; - try { - const source = await deployCustomHandler(c.env, session.tenantId, testId, { kind: "custom", ...valid }); - return c.json(await invokeCustomHandler(c.env.CUSTOM_HANDLERS, source, input.payload)); - } finally { await deleteCustomHandler(c.env, await (await import("./custom-handler")).customScriptName(session.tenantId, testId)); } + const source = await prepareCustomHandler(session.tenantId, testId, { kind: "custom", ...valid }); + return c.json(await invokeCustomHandler(c.env.CUSTOM_HANDLER_LOADER, source, input.payload)); }); app.post("/webhooks/linear", async (c) => { diff --git a/src/tenant.ts b/src/tenant.ts index f35b8764..a377523d 100644 --- a/src/tenant.ts +++ b/src/tenant.ts @@ -380,11 +380,11 @@ export class Tenant extends DurableObject { private async evaluateCustom(pipe: Row, origin: "linear" | "github", deliveryId: string, payload: Record): Promise { const source = this.sourceFor(pipe); if (source.kind !== "custom" || source.origin !== origin || source.handlerDeployment.state !== "ready") return; - if (!this.env.CUSTOM_HANDLERS) { + if (!this.env.CUSTOM_HANDLER_LOADER) { this.recordFlowEvent(pipe, deliveryId, deliveryId, null, payload, "handler_error", "Custom handler platform is unavailable.", origin); return; } - const result = await invokeCustomHandler(this.env.CUSTOM_HANDLERS, source, payload); + const result = await invokeCustomHandler(this.env.CUSTOM_HANDLER_LOADER, source, payload); if (!result.ok) { const detail = result.category === "timeout" ? "Handler exceeded its execution deadline." : result.category === "invalid_return" ? "Handler must return the literal boolean true or false synchronously." : "Handler failed closed without starting a run."; this.recordFlowEvent(pipe, deliveryId, deliveryId, null, payload, result.category, detail, origin); diff --git a/src/types.ts b/src/types.ts index cb782a1c..2c82cefb 100644 --- a/src/types.ts +++ b/src/types.ts @@ -19,9 +19,7 @@ export interface Env { GITHUB_WEBHOOK_SECRET?: string; GITHUB_INTEGRATION_ENABLED?: string; CUSTOM_SOURCES_ENABLED?: string; - CUSTOM_HANDLERS?: DispatchNamespace; - CUSTOM_DEPLOYER?: Fetcher; - CUSTOM_DISPATCH_NAMESPACE?: string; + CUSTOM_HANDLER_LOADER?: WorkerLoader; } export type CustomOrigin = "linear" | "github"; diff --git a/test/custom-handler.test.ts b/test/custom-handler.test.ts index a25dbedc..48d7de8b 100644 --- a/test/custom-handler.test.ts +++ b/test/custom-handler.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; -import { CUSTOM_HANDLER_MAX_CODE_BYTES, customScriptName, userWorkerModule, validateCustomHandler } from "../src/custom-handler"; +import { CUSTOM_HANDLER_MAX_CODE_BYTES, customScriptName, invokeCustomHandler, userWorkerModule, validateCustomHandler } from "../src/custom-handler"; +import type { CustomSource } from "../src/types"; describe("custom handlers", () => { const runAdapter = async (body: string) => { @@ -37,6 +38,32 @@ describe("custom handlers", () => { expect(module).not.toContain("error.stack"); }); + it("loads handlers without bindings or outbound network access", async () => { + let loaded: WorkerLoaderWorkerCode | undefined; + const loader = { + load(code: WorkerLoaderWorkerCode) { + loaded = code; + return { + getEntrypoint: () => ({ + fetch: async () => Response.json({ ok: true, decision: true }), + }), + }; + }, + } as unknown as WorkerLoader; + const source: CustomSource = { + kind: "custom", + origin: "github", + handlerName: "isolated", + handlerCode: "function handler(webhook) { return true; }", + handlerDeployment: { scriptName: "fh-0000000000000000000000000000000000000000", codeDigest: "0".repeat(64), state: "ready" }, + }; + + await expect(invokeCustomHandler(loader, source, {})).resolves.toEqual({ ok: true, decision: true }); + expect(loaded?.env).toEqual({}); + expect(loaded?.globalOutbound).toBeNull(); + expect(loaded?.limits).toEqual({ cpuMs: 10, subRequests: 0 }); + }); + it("admits literal booleans and fails closed on invalid synchronous results", async () => { await expect(runAdapter("return true;")).resolves.toEqual({ ok: true, decision: true }); await expect(runAdapter("return false;")).resolves.toEqual({ ok: true, decision: false }); diff --git a/wrangler.custom-deployer.jsonc b/wrangler.custom-deployer.jsonc deleted file mode 100644 index 5c7e16ba..00000000 --- a/wrangler.custom-deployer.jsonc +++ /dev/null @@ -1,8 +0,0 @@ -{ - "$schema": "./node_modules/wrangler/config-schema.json", - "name": "factorize-custom-deployer", - "main": "src/custom-deployer.ts", - "compatibility_date": "2026-09-10", - "workers_dev": false, - "vars": { "CUSTOM_DISPATCH_NAMESPACE": "factorize-custom-handlers" } -} diff --git a/wrangler.custom-egress.jsonc b/wrangler.custom-egress.jsonc deleted file mode 100644 index cbf0f7fd..00000000 --- a/wrangler.custom-egress.jsonc +++ /dev/null @@ -1,6 +0,0 @@ -{ - "$schema": "./node_modules/wrangler/config-schema.json", - "name": "factorize-custom-egress-deny", - "main": "src/custom-egress-deny.ts", - "compatibility_date": "2026-09-10" -} diff --git a/wrangler.jsonc b/wrangler.jsonc index fcdca4cd..82ed46c7 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -4,8 +4,7 @@ "main": "src/index.ts", "compatibility_date": "2026-09-10", "assets": { "directory": "./public", "binding": "ASSETS" }, - "dispatch_namespaces": [{ "binding": "CUSTOM_HANDLERS", "namespace": "factorize-custom-handlers" }], - "services": [{ "binding": "CUSTOM_DEPLOYER", "service": "factorize-custom-deployer" }], + "worker_loaders": [{ "binding": "CUSTOM_HANDLER_LOADER" }], "durable_objects": { "bindings": [{ "name": "TENANTS", "class_name": "Tenant" }, { "name": "GITHUB_INSTALLATIONS", "class_name": "GitHubInstallationRegistry" }] }, @@ -14,7 +13,6 @@ "APP_ORIGIN": "https://app.factorize.sh", "LINEAR_OAUTH_SCOPES": "read,write", "GITHUB_INTEGRATION_ENABLED": "false", - "CUSTOM_SOURCES_ENABLED": "false", - "CUSTOM_DISPATCH_NAMESPACE": "factorize-custom-handlers" + "CUSTOM_SOURCES_ENABLED": "false" } }