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
4 changes: 3 additions & 1 deletion docs/cloudflare-tail.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Cloudflare Tail is a Factorize flow source for native uncaught Worker exceptions

## Configure the flow and relay

1. Create a flow, choose **Cloudflare Tail**, and save it. Copy the one-time relay destination and signing secret from the response/flow setup view.
1. Create a flow, choose **Cloudflare Tail**, and save it. On the edit page, copy the relay destination and signing secret. You can show, copy, edit, or generate a replacement secret there; replacements remain local until **Save Changes** succeeds.
2. From the repository root, run `npm ci` and set `FACTORIZE_TAIL_DESTINATION` as a Wrangler variable in `packages/tail-relay/wrangler.jsonc`.
3. Authenticate Wrangler to the producer Workers' Cloudflare account, then run `npm exec --workspace=factorize-tail-relay -- wrangler secret put FACTORIZE_TAIL_SECRET` and `npm run deploy:tail-relay`. Keep the relay name `factorize-tail-relay`; Factorize excludes its own relay traces to prevent loops.
4. Add the relay to every producer Worker. One relay can consume multiple producers and forwards each event with its `scriptName`:
Expand All @@ -17,6 +17,8 @@ Cloudflare Tail is a Factorize flow source for native uncaught Worker exceptions

Deploy each producer after changing `tail_consumers`. In the flow activity page, use the owner-only **Test Cloudflare Tail delivery** action before enabling concurrency/automation. The synthetic exception traverses the same isolated handler and normal queue path.

MCP clients should call `list_exe_connections`, select a `connectionId`, then call `create_flow` with `source: { "kind": "cloudflareTail" }`. The response contains the relay destination but never the signing secret. Omit `handlerCode` for the default exception/`console.error` filter. Protected REST and MCP cannot read or replace the secret; authenticated owners rotate it on the edit page and must then update `FACTORIZE_TAIL_SECRET` in Wrangler and redeploy the relay.

The relay redacts sensitive key names (authorization, cookies, tokens, secrets, credentials, prompts, and bodies), truncates oversized structures, signs the exact body with HMAC-SHA256, and aborts delivery after three seconds. Factorize sanitizes again before activity or agent context, rejects deliveries older than 60 seconds, deduplicates delivery IDs, and rate-limits repeated event fingerprints.

For caught internal failures, log a structured event:
Expand Down
8 changes: 6 additions & 2 deletions packages/app/src/flow-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,19 @@ export const matchRuleSchema = z.object({
type: z.enum(["owner", "creator", "status", "label", "assignee"]),
targetId: z.string().min(1),
});
export const publicSourceSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("linear"), projectId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(),
z.object({ kind: z.literal("cloudflareTail"), handlerCode: z.string().max(16_384).optional() }).strict(),
]);
export const flowInputSchema = z.object({
name: z.string().trim().min(1).max(120),
flowId: z.string().trim().regex(/^[a-z0-9][a-z0-9-]*$/).optional(),
projectId: z.string().min(1),
matchRules: z.array(matchRuleSchema).min(1),
source: publicSourceSchema,
maxConcurrency: z.number().int().min(0).max(50).default(3),
workspaceName: z.string().max(120).optional(),
contextTemplate: z.string().max(50_000).optional(),
cwd: z.string().max(1_000).optional(),
exeConnectionId: z.string().min(1),
}).strict();
export const flowIdSchema = z.object({ flowId: z.string().min(1) });
export const listRunsSchema = z.object({
Expand Down
23 changes: 20 additions & 3 deletions packages/app/src/flow-service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { Env, OAuthProps } from "./types";
import type { FlowInput } from "./flow-schemas";
import { preparePublicSource, publicSource, resolveContextTemplate } from "./source-lifecycle";
import type { FlowSource } from "./types";

export class ServiceError extends Error {
constructor(public status: number, public code: string, message: string) { super(message); }
Expand Down Expand Up @@ -35,12 +37,14 @@ export class FlowService {
let matchRules: unknown = undefined;
try { source = typeof row.source_config === "string" ? JSON.parse(row.source_config) : undefined; } catch { /* omit malformed internal config */ }
try { matchRules = typeof row.match_rules === "string" ? JSON.parse(row.match_rules) : undefined; } catch { /* omit malformed internal config */ }
if (source?.kind === "custom") source = { kind: "custom", origin: source.origin, handlerName: source.handlerName, deploymentState: source.handlerDeployment?.state };
if (source) source = publicSource(source);
return {
id: row.id, name: row.name, projectId: row.project_id, source,
matchRules,
maxConcurrency: row.max_concurrency, workspaceName: row.workspace_name,
agentKind: row.agent_kind, cwd: row.cwd, contextTemplate: row.context_template,
exeConnectionId: row.exe_connection_id,
...(source?.kind === "cloudflareTail" ? { cloudflareTail: { destination: `${this.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(this.auth.tenantId)}/${encodeURIComponent(row.id)}` } } : {}),
enabled: Boolean(row.enabled), createdAt: row.created_at,
};
}
Expand All @@ -50,11 +54,24 @@ export class FlowService {
const value = await this.call("flows:read", `/v1/flows/${encodeURIComponent(flowId)}`) as any;
return this.publicFlow(value);
}
createFlow(input: FlowInput) { return this.call("flows:write", "/pipes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); }
updateFlow(flowId: string, input: FlowInput) { return this.call("flows:write", `/pipes/${encodeURIComponent(flowId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); }
async createFlow(input: FlowInput) {
const pipeId = crypto.randomUUID();
const source = await preparePublicSource(this.auth.tenantId, pipeId, input.source);
await this.call("flows:write", "/pipes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...input, pipeId, projectId: input.source.kind === "linear" ? input.source.projectId : "", matchRules: input.source.kind === "linear" ? input.source.matchRules : [], source, contextTemplate: resolveContextTemplate(input.source, input.contextTemplate) }) });
return this.publicFlow(await this.call("flows:write", `/v1/flows/${encodeURIComponent(pipeId)}`));
}
async updateFlow(flowId: string, input: FlowInput) {
const current = await this.call("flows:write", `/v1/flows/${encodeURIComponent(flowId)}`) as any;
let previous: FlowSource | undefined;
try { previous = JSON.parse(current.source_config); } catch { /* validation below will fail safely */ }
const source = await preparePublicSource(this.auth.tenantId, flowId, input.source, previous);
await this.call("flows:write", `/pipes/${encodeURIComponent(flowId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...input, projectId: input.source.kind === "linear" ? input.source.projectId : "", matchRules: input.source.kind === "linear" ? input.source.matchRules : [], source, contextTemplate: resolveContextTemplate(input.source, input.contextTemplate) }) });
return this.publicFlow(await this.call("flows:write", `/v1/flows/${encodeURIComponent(flowId)}`));
}
deleteFlow(flowId: string) { return this.call("flows:write", `/pipes/${encodeURIComponent(flowId)}`, { method: "DELETE" }); }
listProjects() { return this.call("flows:read", "/linear/projects"); }
listFlowOptions() { return this.call("flows:read", "/linear/options"); }
listExeConnections() { return this.call("flows:read", "/connections/status").then((value: any) => value.exeConnections ?? []); }
listRuns(query: URLSearchParams) { return this.call("runs:read", `/v1/runs?${query}`); }
getRun(runId: string) { return this.call("runs:read", `/v1/runs/${encodeURIComponent(runId)}`); }
listFlowEvents(query: URLSearchParams) { return this.call("runs:read", `/v1/events?${query}`); }
Expand Down
31 changes: 26 additions & 5 deletions packages/app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { flowDetailPage, flowPage, flowWebhooksPage, flowsPage, landingPage, run
import type { Env } from "./types";
import type { CustomSource, PipeInput } from "./types";
import { invokeCustomHandler, prepareCustomHandler, validateCustomHandler } from "./custom-handler";
import { preparePublicSource, resolveContextTemplate } from "./source-lifecycle";
import { generateTailSecret } from "./cloudflare-tail";

const app = new Hono<{ Bindings: Env; Variables: { cspNonce: string } }>();
Expand Down Expand Up @@ -110,7 +111,11 @@ app.get("/api/pipes/:id", async (c) => {
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
const url = new URL(`https://tenant/pipes/${encodeURIComponent(c.req.param("id"))}`);
for (const key of ["view", "page"]) { const value = c.req.query(key); if (value) url.searchParams.set(key, value); }
return tenant(c, session.tenantId).fetch(url);
const response = await tenant(c, session.tenantId).fetch(url);
if (!response.ok) return response;
const result = await response.json() as any;
let source: CustomSource | undefined; try { const parsed = JSON.parse(result.flow?.source_config ?? "{}"); if (parsed.kind === "custom" && parsed.origin === "cloudflare") source = parsed; } catch {}
return c.json({ ...result, ...(source ? { cloudflareTail: { destination: `${c.env.APP_ORIGIN}/webhooks/cloudflare/${encodeURIComponent(session.tenantId)}/${encodeURIComponent(c.req.param("id"))}`, signingSecret: source.tail?.signingSecret } } : {}) });
});
app.get("/api/runs", async (c) => {
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
Expand Down Expand Up @@ -184,8 +189,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;
if (input.source?.kind === "custom") {
const input = await c.req.json() as PipeInput & { source?: any };
if (input.source?.kind === "cloudflareTail") {
if (c.env.CUSTOM_SOURCES_ENABLED !== "true") return c.json({ error: "Custom sources are not enabled." }, 404);
const pipeId = crypto.randomUUID(); input.pipeId = pipeId;
input.contextTemplate = resolveContextTemplate(input.source, input.contextTemplate);
input.source = await preparePublicSource(session.tenantId, pipeId, input.source);
}
else 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();
Expand All @@ -199,8 +210,18 @@ app.post("/api/pipes", async (c) => {
});
app.put("/api/pipes/:id", async (c) => {
const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401);
const pipeId = c.req.param("id"), input = await c.req.json() as PipeInput;
if (input.source?.kind === "custom") {
const pipeId = c.req.param("id"), input = await c.req.json() as PipeInput & { source?: any; tailSigningSecret?: string };
if (input.source?.kind === "cloudflareTail") {
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/v1/flows/${encodeURIComponent(pipeId)}`);
if (!currentResponse.ok) return currentResponse;
const current = await currentResponse.json() as { source_config?: string };
let previous: CustomSource | undefined; try { const parsed = JSON.parse(current.source_config ?? "{}"); if (parsed.kind === "custom") previous = parsed; } catch {}
input.contextTemplate = resolveContextTemplate(input.source, input.contextTemplate);
input.source = await preparePublicSource(session.tenantId, pipeId, input.source, previous, input.tailSigningSecret);
delete input.tailSigningSecret;
}
else 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;
Expand Down
6 changes: 4 additions & 2 deletions packages/app/src/protected-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
if (flowMatch && request.method === "DELETE") return Response.json(await service.deleteFlow(decodeURIComponent(flowMatch[1])));
if (request.method === "GET" && path === "/api/v1/projects") return Response.json(await service.listProjects());
if (request.method === "GET" && path === "/api/v1/flow-options") return Response.json(await service.listFlowOptions());
if (request.method === "GET" && path === "/api/v1/exe-connections") return Response.json(await service.listExeConnections());
if (request.method === "GET" && path === "/api/v1/runs") { const q = listRunsSchema.parse(queryInput(url)); return Response.json(await service.listRuns(queryOf(q))); }
const runMatch = path.match(/^\/api\/v1\/runs\/([^/]+)$/);
if (runMatch && request.method === "GET") return Response.json(await service.getRun(decodeURIComponent(runMatch[1])));
Expand All @@ -65,11 +66,12 @@ export class ProtectedApiHandler extends WorkerEntrypoint<Env, OAuthProps> {
});
tool("list_flows", "List Factorize flows", z.object({}), () => service.listFlows());
tool("get_flow", "Get a flow", flowIdSchema, ({ flowId }: any) => service.getFlow(flowId));
tool("create_flow", "Create a flow", flowInputSchema, (input: any) => service.createFlow(input));
tool("update_flow", "Update a flow", flowInputSchema.extend({ flowId: z.string().min(1) }), ({ flowId, ...input }: any) => service.updateFlow(flowId, input));
tool("create_flow", "Create a flow. First call list_exe_connections, then select its connectionId. Cloudflare Tail returns a relay destination but never its signing secret.", flowInputSchema, (input: any) => service.createFlow(input));
tool("update_flow", "Update a flow using a saved exe.dev connection ID. Cloudflare Tail secrets are preserved and cannot be submitted or returned.", flowInputSchema.extend({ flowId: z.string().min(1) }), ({ flowId, ...input }: any) => service.updateFlow(flowId, input));
tool("delete_flow", "Delete a flow", flowIdSchema, ({ flowId }: any) => service.deleteFlow(flowId));
tool("list_projects", "List Linear projects", z.object({}), () => service.listProjects());
tool("list_flow_options", "List match-rule options", z.object({}), () => service.listFlowOptions());
tool("list_exe_connections", "List safe metadata for saved exe.dev connections. Select a connectionId before creating or updating a flow; API tokens are never returned.", z.object({}), () => service.listExeConnections());
tool("list_runs", "List and filter flow runs", listRunsSchema, (input: any) => service.listRuns(queryOf(input)));
tool("get_run", "Get a run and its current output", runIdSchema, ({ runId }: any) => service.getRun(runId));
tool("list_flow_events", "List webhook activity for a flow", listEventsSchema, (input: any) => service.listFlowEvents(queryOf(input)));
Expand Down
53 changes: 53 additions & 0 deletions packages/app/src/source-lifecycle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import Mustache from "mustache";
import { generateTailSecret, TAIL_HANDLER_SCAFFOLD } from "./cloudflare-tail";
import { prepareCustomHandler, validateCustomHandler } from "./custom-handler";
import { DEFAULT_CONTEXT_TEMPLATE, renderContextTemplate } from "./linear-source";
import type { CustomSource, FlowSource } from "./types";

export const TAIL_CONTEXT_TEMPLATE = `---
pipe: "{{{flow.name}}}"
source: "Cloudflare Tail"
delivery: "{{{deliveryId}}}"
---

# Cloudflare Worker Tail event

\`\`\`json
{{{eventJson}}}
\`\`\``;

export type PublicSource =
| { kind: "linear"; projectId: string; matchRules: Array<{ type: "owner" | "creator" | "status" | "label" | "assignee"; targetId: string }> }
| { kind: "cloudflareTail"; handlerCode?: string };

export function defaultContextTemplate(source: { kind: string }): string {
return source.kind === "cloudflareTail" ? TAIL_CONTEXT_TEMPLATE : DEFAULT_CONTEXT_TEMPLATE;
}

export function resolveContextTemplate(source: { kind: string }, value?: string): string {
const template = value || defaultContextTemplate(source);
if (template.length > 50_000) throw new Error("Context template must be 50,000 characters or fewer.");
try { Mustache.parse(template); } catch { throw new Error("Context template contains invalid Mustache syntax."); }
return template;
}

export function renderSourcePrompt(source: FlowSource, template: string, payload: Record<string, unknown>, flowName: string, deliveryId?: string): string {
if (source.kind === "custom" && source.origin === "cloudflare") return Mustache.render(template, { event: payload, eventJson: JSON.stringify(payload, null, 2), deliveryId, flow: { name: flowName } });
return renderContextTemplate(template, payload, flowName);
}

export async function preparePublicSource(tenantId: string, flowId: string, source: PublicSource, previous?: FlowSource, signingSecret?: string): Promise<FlowSource> {
if (source.kind === "linear") return source;
const handlerCode = source.handlerCode ?? TAIL_HANDLER_SCAFFOLD;
const valid = validateCustomHandler("cloudflare", "Cloudflare Worker failures", handlerCode);
const old = previous?.kind === "custom" && previous.origin === "cloudflare" ? previous as CustomSource : undefined;
const secret = signingSecret ?? old?.tail?.signingSecret ?? generateTailSecret();
if (secret.length < 32 || secret.length > 256) throw new Error("Cloudflare Tail signing secret must be between 32 and 256 characters.");
return prepareCustomHandler(tenantId, flowId, { kind: "custom", ...valid, tail: { signingSecret: secret } }, old);
}

export function publicSource(source: FlowSource): PublicSource {
return source.kind === "custom" && source.origin === "cloudflare"
? { kind: "cloudflareTail", handlerCode: source.handlerCode }
: source as PublicSource;
}
Loading