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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions docs/custom-sources-rollout.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
28 changes: 0 additions & 28 deletions src/custom-deployer.ts

This file was deleted.

3 changes: 0 additions & 3 deletions src/custom-egress-deny.ts

This file was deleted.

26 changes: 12 additions & 14 deletions src/custom-handler.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -48,14 +48,21 @@ export default { async fetch(request) {
} };`;
}

export async function invokeCustomHandler(dispatch: DispatchNamespace, source: CustomSource, payload: unknown): Promise<HandlerDecision> {
export async function invokeCustomHandler(loader: WorkerLoader, source: CustomSource, payload: unknown): Promise<HandlerDecision> {
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" };
Expand All @@ -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<CustomSource, "handlerDeployment">, previous?: CustomSource): Promise<CustomSource> {
if (!env.CUSTOM_DEPLOYER) throw new Error("Custom handler deployment is not configured.");
export async function prepareCustomHandler(tenantId: string, flowId: string, source: Omit<CustomSource, "handlerDeployment">, previous?: CustomSource): Promise<CustomSource> {
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<boolean> {
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;
}
27 changes: 8 additions & 19 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } }>();

Expand Down Expand Up @@ -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);
Expand All @@ -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) => {
Expand Down
4 changes: 2 additions & 2 deletions src/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,11 +380,11 @@ export class Tenant extends DurableObject<Env> {
private async evaluateCustom(pipe: Row, origin: "linear" | "github", deliveryId: string, payload: Record<string, any>): Promise<void> {
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);
Expand Down
4 changes: 1 addition & 3 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
29 changes: 28 additions & 1 deletion test/custom-handler.test.ts
Original file line number Diff line number Diff line change
@@ -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) => {
Expand Down Expand Up @@ -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 });
Expand Down
8 changes: 0 additions & 8 deletions wrangler.custom-deployer.jsonc

This file was deleted.

6 changes: 0 additions & 6 deletions wrangler.custom-egress.jsonc

This file was deleted.

6 changes: 2 additions & 4 deletions wrangler.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -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" }]
},
Expand All @@ -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"
}
}