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
11 changes: 11 additions & 0 deletions docs/custom-sources-rollout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Custom source rollout

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.

Custom triggers are intentionally lossy once a flow has 100 pending jobs. Valid signed provider deliveries are still acknowledged to prevent retry storms.
2 changes: 1 addition & 1 deletion public/styles.css

Large diffs are not rendered by default.

28 changes: 28 additions & 0 deletions src/custom-deployer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
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<Response> {
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 });
},
};
3 changes: 3 additions & 0 deletions src/custom-egress-deny.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// 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 }); } };
81 changes: 81 additions & 0 deletions src/custom-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import type { CustomOrigin, CustomSource, Env } from "./types";

export const CUSTOM_HANDLER_SCAFFOLD = `function handler(webhook) {
return true;
}`;
export const CUSTOM_HANDLER_MAX_CODE_BYTES = 16_384;
export const CUSTOM_HANDLER_MAX_PAYLOAD_BYTES = 262_144;
export const CUSTOM_HANDLER_COMPATIBILITY_DATE = "2026-09-10";
export const CUSTOM_HANDLER_DEADLINE_MS = 250;

export type HandlerDecision =
| { ok: true; decision: boolean }
| { ok: false; category: "handler_error" | "invalid_return" | "timeout" | "platform_error" };

const encoder = new TextEncoder();
const hex = (bytes: ArrayBuffer) => [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");

export async function sha256(value: string): Promise<string> {
return hex(await crypto.subtle.digest("SHA-256", encoder.encode(value)));
}

export async function customScriptName(tenantId: string, flowId: string): Promise<string> {
return `fh-${(await sha256(`${tenantId}\0${flowId}`)).slice(0, 40)}`;
}

export function validateCustomHandler(origin: unknown, handlerName: unknown, handlerCode: unknown): { origin: CustomOrigin; handlerName: string; handlerCode: string } {
if (origin !== "linear" && origin !== "github") throw new Error("Custom handler origin must be Linear or GitHub.");
if (typeof handlerName !== "string" || !handlerName.trim() || handlerName.trim().length > 80) throw new Error("Handler name must be between 1 and 80 characters.");
if (typeof handlerCode !== "string" || encoder.encode(handlerCode).byteLength > CUSTOM_HANDLER_MAX_CODE_BYTES) throw new Error(`Handler code must be at most ${CUSTOM_HANDLER_MAX_CODE_BYTES} bytes.`);
// This is input validation, not the isolation boundary. Requiring exactly one
// complete declaration prevents ambiguous adapters and accidental snippets.
const declaration = /^\s*function\s+handler\s*\(\s*webhook\s*\)\s*\{[\s\S]*\}\s*;?\s*$/;
if (!declaration.test(handlerCode)) throw new Error("Provide one complete function handler(webhook) declaration.");
return { origin, handlerName: handlerName.trim(), handlerCode };
}

export function userWorkerModule(handlerCode: string): string {
return `${handlerCode}\n
export default { async fetch(request) {
if (request.method !== "POST") return Response.json({ ok: false, category: "handler_error" }, { status: 405 });
try {
const webhook = await request.json();
const result = handler(webhook);
if (result !== null && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") return Response.json({ ok: false, category: "invalid_return" });
if (typeof result !== "boolean") return Response.json({ ok: false, category: "invalid_return" });
return Response.json({ ok: true, decision: result });
} catch { return Response.json({ ok: false, category: "handler_error" }); }
} };`;
}

export async function invokeCustomHandler(dispatch: DispatchNamespace, 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 });
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" };
} catch (error) {
return { ok: false, category: error instanceof DOMException && error.name === "AbortError" ? "timeout" : "platform_error" };
} 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.");
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;
}
49 changes: 46 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import { GitHubInstallationRegistry } from "./github-registry";
import { createAppJwt, githubHeaders, readSetupState, signSetupState } from "./github";
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";

const app = new Hono<{ Bindings: Env; Variables: { cspNonce: string } }>();

Expand Down Expand Up @@ -168,15 +170,56 @@ 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);
return tenant(c, session.tenantId).fetch("https://tenant/pipes", { method: "POST", headers: { "Content-Type": "application/json" }, body: await c.req.text() });
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;
}
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;
});
app.put("/api/pipes/:id", async (c) => {
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
return tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(c.req.param("id"))}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: await c.req.text() });
const pipeId = c.req.param("id"), input = await c.req.json() as PipeInput;
if (input.source?.kind === "custom") {
if (c.env.CUSTOM_SOURCES_ENABLED !== "true") return c.json({ error: "Custom sources are not enabled." }, 404);
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 } };
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);
}
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);
return tenant(c, session.tenantId).fetch(`https://tenant/pipes/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" });
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;
});

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);
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)); }
});

app.post("/webhooks/linear", async (c) => {
Expand Down
Loading
Loading