diff --git a/docs/cloudflare-tail.md b/docs/cloudflare-tail.md index 0fbd881e..1c89e747 100644 --- a/docs/cloudflare-tail.md +++ b/docs/cloudflare-tail.md @@ -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`: @@ -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: diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index eaf9020b..c9377aa1 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -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({ diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 96a06045..39c3acb9 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -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); } @@ -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, }; } @@ -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}`); } diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 6aa6959e..d1079c90 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -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 } }>(); @@ -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); @@ -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(); @@ -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; diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index 4ec528a2..4908cf93 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -47,6 +47,7 @@ export class ProtectedApiHandler extends WorkerEntrypoint { 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]))); @@ -65,11 +66,12 @@ export class ProtectedApiHandler extends WorkerEntrypoint { }); 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))); diff --git a/packages/app/src/source-lifecycle.ts b/packages/app/src/source-lifecycle.ts new file mode 100644 index 00000000..f655cebf --- /dev/null +++ b/packages/app/src/source-lifecycle.ts @@ -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, 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 { + 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; +} diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 30a2e3f6..a75dad1a 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -13,6 +13,7 @@ import { invokeCustomHandler, validateCustomHandler } from "./custom-handler"; import { sanitizeTailEvent, suppressTailEvent, tailFingerprint, verifyTailDelivery } from "./cloudflare-tail"; import { ExeHerdrBackend } from "./exe-herdr-backend"; import { DEFAULT_CONTEXT_TEMPLATE, LinearSourceAdapter, linearTicketPrompt, renderContextTemplate } from "./linear-source"; +import { renderSourcePrompt } from "./source-lifecycle"; export { DEFAULT_CONTEXT_TEMPLATE, linearTicketPrompt, renderContextTemplate } from "./linear-source"; @@ -199,7 +200,7 @@ export class Tenant extends DurableObject { if (!linear) throw new Error("Connect Linear first"); const exe = await this.exeConnection(input.exeConnectionId); if (!exe) throw new Error("Connect Herdr first"); - const cwd = this.cwdTemplate(input.cwd, flowId); + const cwd = this.cwdTemplate(input.cwd ?? exe.cwd, flowId); const workspaceName = flowId; // These legacy fields are retained for compatibility with the v1 Durable Object schema. // App-wide webhook verification is performed at the Worker edge before reaching this object. @@ -221,7 +222,7 @@ export class Tenant extends DurableObject { const workspaceName = flowId; const exe = await this.exeConnection(input.exeConnectionId); if (!exe) throw new Error("Choose an exe.dev connection."); - const cwd = this.cwdTemplate(input.cwd, flowId); + const cwd = this.cwdTemplate(input.cwd ?? exe.cwd, flowId); this.ctx.storage.sql.exec( "UPDATE pipes SET name=?, project_id=?, filter_type=?, filter_target_id=?, max_concurrency=?, workspace_name=?, agent_kind=?, context_template=?, match_rules=?, exe_connection_id=?, cwd=?, source_kind=?, source_config=?, trigger_kind=?, trigger_config=? WHERE id=?", input.name, source.kind === "linear" ? source.projectId : "", rules[0].type, rules[0].targetId, maxConcurrency, workspaceName, exe.agentKind, source.kind !== "github" ? this.contextTemplate(input.contextTemplate) : "", JSON.stringify(rules), input.exeConnectionId || "default", cwd, source.kind, JSON.stringify(source), source.kind === "github" ? source.trigger : source.kind === "custom" ? "custom_handler" : "linear_match", "{}", pipeId, @@ -306,7 +307,7 @@ export class Tenant extends DurableObject { } private getFlow(flowId: string): Response { - const flow = this.one("SELECT id, name, project_id, match_rules, source_kind, source_config, max_concurrency, workspace_name, agent_kind, cwd, COALESCE(NULLIF(context_template, ''), ?) AS context_template, enabled, created_at FROM pipes WHERE id = ?", DEFAULT_CONTEXT_TEMPLATE, flowId); + const flow = this.one("SELECT id, name, project_id, match_rules, source_kind, source_config, max_concurrency, workspace_name, agent_kind, exe_connection_id, cwd, COALESCE(NULLIF(context_template, ''), ?) AS context_template, enabled, created_at FROM pipes WHERE id = ?", DEFAULT_CONTEXT_TEMPLATE, flowId); return flow ? json(flow) : new Response("Not found", { status: 404 }); } @@ -526,7 +527,7 @@ export class Tenant extends DurableObject { return; } const workItem: WorkItem = { provider: origin, claimKey: deliveryId, identifier: deliveryId, title: source.handlerName, description: "", url: "", event: payload }; - const prompt = origin === "cloudflare" ? `---\npipe: "${String(pipe.name).replaceAll('"', "'")}"\nsource: "Cloudflare Tail"\ndelivery: "${deliveryId}"\n---\n\n# Cloudflare Worker Tail event\n\n\`\`\`json\n${JSON.stringify(payload, null, 2)}\n\`\`\`` : renderContextTemplate(String(pipe.context_template || DEFAULT_CONTEXT_TEMPLATE), payload, String(pipe.name)); + const prompt = renderSourcePrompt(source, String(pipe.context_template || DEFAULT_CONTEXT_TEMPLATE), payload, String(pipe.name), deliveryId); await this.queueWorkItem(pipe, deliveryId, workItem, prompt); } diff --git a/packages/app/src/types.ts b/packages/app/src/types.ts index fc65850b..85836da2 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -59,7 +59,7 @@ export interface PipeInput { name: string; /** Optional stable, machine-friendly identifier; defaults from the name. */ flowId?: string; - projectId: string; + projectId?: string; /** At least one rule is required. All rules must match the issue. */ matchRules?: MatchRule[]; /** Legacy single-rule input, retained so existing API clients keep working. */ diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 498b0800..b9a9f2b9 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -97,8 +97,9 @@ nameInput.oninput=()=>{if(!flowIdEdited)flowIdInput.value=slugFor(nameInput.valu if(editFlowId)fetch('/api/pipes/'+encodeURIComponent(editFlowId)).then(response=>response.ok?response.json():null).then(data=>{if(data?.flow?.workspace_name){flowIdInput.value=data.flow.workspace_name;flowIdEdited=true}}).catch(()=>{}); const $=s=>document.querySelector(s), data=f=>Object.fromEntries(new FormData(f));let exeConnected=false,linearOptions={statuses:[],users:[],labels:[]}; let githubRepositories=[];const sourceKind=$('#source-kind'),linearSource=$('#linear-source'),githubSource=$('#github-source'),customSource=$('#custom-source'),githubInstallation=$('#github-installation'),githubRepository=$('#github-repository'); +const tailCredentials=document.createElement('section');tailCredentials.id='tail-credentials';tailCredentials.className='hidden sm:col-span-2 rounded-xl border border-amber-300 bg-amber-50 p-4';tailCredentials.innerHTML='

Cloudflare Tail credentials

';customSource.append(tailCredentials); const loadRepositories=async()=>{githubRepository.replaceChildren(new Option('Loading repositories…',''));const installation=githubInstallation.value;if(!installation)return;const response=await fetch('/api/github/installations/'+encodeURIComponent(installation)+'/repositories');if(!response.ok){githubRepository.replaceChildren(new Option('Repository access unavailable',''));return}githubRepositories=await response.json();githubRepository.replaceChildren(...githubRepositories.map(repo=>new Option(repo.fullName,repo.id)));}; -const syncSource=()=>{const github=sourceKind.value==='github',custom=sourceKind.value==='custom';linearSource.classList.toggle('hidden',github||custom);linearSource.classList.toggle('contents',!github&&!custom);githubSource.classList.toggle('hidden',!github);customSource.classList.toggle('hidden',!custom);$('#project').required=!github&&!custom;$('#context-template').required=!github;};sourceKind.onchange=syncSource;githubInstallation.onchange=loadRepositories; +const syncSource=()=>{const github=sourceKind.value==='github',custom=sourceKind.value==='custom';linearSource.classList.toggle('hidden',github||custom);linearSource.classList.toggle('contents',!github&&!custom);githubSource.classList.toggle('hidden',!github);customSource.classList.toggle('hidden',!custom);tailCredentials.classList.toggle('hidden',!custom||!editFlowId);$('#project').required=!github&&!custom;$('#context-template').required=!github;};sourceKind.onchange=syncSource;githubInstallation.onchange=loadRepositories; sourceKind.querySelector('option[value=custom]').textContent='Cloudflare Tail';const customOrigin=$('[name=customOrigin]');customOrigin.append(new Option('Cloudflare','cloudflare'));customOrigin.value='cloudflare';customOrigin.onchange=()=>{if(customOrigin.value==='cloudflare'){$('[name=handlerName]').value='Cloudflare Worker failures';$('[name=handlerCode]').value='function handler(webhook) {\\n return webhook.outcome === "exception" || webhook.logs.some((log) => log.level === "error");\\n}'}}; fetch('/api/github/installations').then(async response=>{if(response.status===404){sourceKind.querySelector('option[value=github]')?.remove();return}if(!response.ok)return;const installations=await response.json(),active=installations.filter(item=>item.state==='active');githubInstallation.replaceChildren(...installations.map(item=>new Option(item.accountLogin+(item.state==='active'?'':' ('+item.state+')'),item.installationId)));$('#github-empty').classList.toggle('hidden',installations.length>0);if(active.length){githubInstallation.value=String(active[0].installationId);await loadRepositories()}else if(installations.length){$('#github-warning').textContent='This installation is disconnected. Reconnect it before saving the flow.';$('#github-warning').classList.remove('hidden')}}).catch(()=>{});syncSource(); const defaultContextTemplate=$('#context-template').value; @@ -122,9 +123,12 @@ function readRules(){return ruleRows().map(row=>{const [type,target]=row.querySe async function init(){try{const [projects,options,status,existing]=await Promise.all([fetch('/api/linear/projects'),fetch('/api/linear/options'),fetch('/api/connections/status'),editFlowId?fetch('/api/pipes/'+encodeURIComponent(editFlowId)):Promise.resolve(null)]);if(projects.status===401)return location.href='/auth/linear';if(!projects.ok){const result=await projects.json().catch(()=>({}));showError(result.error||'Could not load your Linear projects. Reconnect Linear and try again.',false);return}const projectList=await projects.json();const select=$('#project');select.replaceChildren(...projectList.map(p=>new Option(p.name,p.id)));if(projectList.length)select.value=projectList[0].id;if(options.ok)linearOptions=await options.json();let flow; if(existing){if(!existing.ok)throw new Error('Could not load this flow.');flow=(await existing.json()).flow;const form=$('#flow');form.elements.name.value=flow.name;select.value=flow.project_id;let saved=[];try{saved=JSON.parse(flow.match_rules||'[]')}catch{};(saved.length?saved:[{type:flow.filter_type,targetId:flow.filter_target_id}]).forEach(addRule);let source={};try{source=JSON.parse(flow.source_config||'{}')}catch{};if(flow.source_kind==='github'){sourceKind.value='github';syncSource();githubInstallation.value=String(source.installationId||'');await loadRepositories();githubRepository.value=String(source.repositoryId||'')}else if(flow.source_kind==='custom'){sourceKind.value='custom';form.elements.customOrigin.value=source.origin||'linear';form.elements.handlerName.value=source.handlerName||'';form.elements.handlerCode.value=source.handlerCode||'';syncSource()}form.elements.maxConcurrency.value=flow.max_concurrency;form.elements.contextTemplate.value=flow.context_template||form.elements.contextTemplate.value;form.elements.cwd.value=flow.cwd||''}else addRule();const connectionSelect=$('#exe-connection');if(status.ok){const s=await status.json(),connections=s.exeConnections||[];if(connections.length){connectionSelect.replaceChildren(...connections.map(c=>new Option(c.vmName+' · '+c.agentKind,c.connectionId)),new Option('Add a new connection…','new'));connectionSelect.value=flow?.exe_connection_id||connections[0].connectionId;exeConnected=true;const chosen=connections.find(c=>c.connectionId===connectionSelect.value)||connections[0],form=$('#flow');form.elements.agentKind.value=chosen.agentKind||'codex';if(!form.elements.cwd.value)form.elements.cwd.value=chosen.cwd||'';form.elements.herdrCommand.value=chosen.herdrCommand||'herdr';agentCommandInput.value=chosen.agentCommand??defaultAgentCommand();agentCommandCustomized=agentCommandInput.value!==defaultAgentCommand();$('#exe-status').textContent='Saved connection';$('#exe-status').className='rounded-full bg-factorize-50 px-2.5 py-1 text-xs font-medium text-factorize-700 dark:bg-factorize-500/20 dark:text-factorize-100'}else{connectionSelect.replaceChildren(new Option('Add a new connection…','new'));connectionSelect.value='new';$('#exe-fields').classList.remove('hidden');$('#exe-status').textContent='Not connected'}}else{connectionSelect.replaceChildren(new Option('Could not load connections',''));$('#exe-status').textContent='Unavailable'}connectionSelect.onchange=()=>{const adding=connectionSelect.value==='new';$('#exe-fields').classList.toggle('hidden',!adding);exeConnected=!adding;if(!adding){const chosen=connections.find(c=>c.connectionId===connectionSelect.value);if(chosen){$('#flow').elements.cwd.value=chosen.cwd||'';$('#flow').elements.agentKind.value=chosen.agentKind||'codex'}}}}catch(err){showError(err.message||'Could not reach Factorize. Check your connection and try again.',false)}} // Connection choices identify only the VM destination. Agent kind belongs to // the flow and is deliberately omitted from this picker. +if(editFlowId)fetch('/api/pipes/'+encodeURIComponent(editFlowId)).then(r=>r.ok?r.json():null).then(data=>{if(!data?.cloudflareTail)return;const form=$('#flow');form.elements.tailDestination.value=data.cloudflareTail.destination||'';form.elements.tailSigningSecret.value=data.cloudflareTail.signingSecret||''}).catch(()=>{}); +const tailSecret=$('[name=tailSigningSecret]');tailSecret.oninput=()=>$('#tail-secret-warning').classList.remove('hidden');$('#show-tail-secret').onclick=()=>{tailSecret.type=tailSecret.type==='password'?'text':'password';$('#show-tail-secret').textContent=tailSecret.type==='password'?'Show':'Hide'};$('#generate-tail-secret').onclick=()=>{const bytes=crypto.getRandomValues(new Uint8Array(32));tailSecret.value=btoa(String.fromCharCode(...bytes)).replaceAll('+','-').replaceAll('/','_').replaceAll('=','');tailSecret.dispatchEvent(new Event('input'))};$$('[data-copy]').forEach(button=>button.onclick=()=>navigator.clipboard.writeText($('[name='+button.dataset.copy+']').value)); +const browserFetch=window.fetch.bind(window);window.fetch=(input,init)=>{if(init?.body&&/^\/api\/pipes(?:\/|$)/.test(String(input))){try{const body=JSON.parse(String(init.body));if(body.source?.kind==='custom'&&body.source.origin==='cloudflare'){body.source={kind:'cloudflareTail',handlerCode:body.source.handlerCode};if(editFlowId)body.tailSigningSecret=tailSecret.value;init={...init,body:JSON.stringify(body)}}}catch{}}return browserFetch(input,init)}; const connectionPicker=$('#exe-connection');new MutationObserver(()=>Array.from(connectionPicker.options).forEach(option=>{if(option.value!=='new')option.textContent=option.textContent.split(' · ')[0]})).observe(connectionPicker,{childList:true}); $('#add-rule').onclick=()=>addRule(); -$('#reset-context-template').onclick=()=>{if(confirm('Reset this context template to Factorize’s default? Your current edits will be discarded.'))$('#context-template').value=defaultContextTemplate}; +const tailContextTemplate='---\npipe: "{{{flow.name}}}"\nsource: "Cloudflare Tail"\ndelivery: "{{{deliveryId}}}"\n---\n\n# Cloudflare Worker Tail event\n\n\`\`\`json\n{{{eventJson}}}\n\`\`\`';$('#reset-context-template').onclick=()=>{if(confirm('Reset this context template to Factorize’s default? Your current edits will be discarded.'))$('#context-template').value=sourceKind.value==='custom'?tailContextTemplate:defaultContextTemplate}; $('#test-exe').onclick=async()=>{const values=data($('#flow')),button=$('#test-exe'),result=$('#exe-test-result'),status=$('#exe-test-status');button.disabled=true;status.classList.add('hidden');result.classList.add('hidden');try{const payload=values.apiToken?{vmName:values.vmName,agentKind:values.agentKind,cwd:values.cwd,herdrCommand:values.herdrCommand,apiToken:values.apiToken}:{connectionId:values.exeConnection};const r=await fetch('/api/connections/exe/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload)});const body=await r.json().catch(()=>({}));if(r.ok&&body.ok){status.textContent='✓';status.className='grid h-6 w-6 place-items-center rounded-full bg-green-600 text-sm font-bold text-white';status.setAttribute('aria-label','Connection successful');return}status.textContent='×';status.className='grid h-6 w-6 place-items-center rounded-full bg-red-600 text-lg font-bold leading-none text-white';status.setAttribute('aria-label','Connection failed');result.textContent=body.error||('HTTP '+(body.httpStatus??r.status)+(body.exitCode!=null?' · VM exit '+body.exitCode:'')+'\\n\\n'+(body.output||'Connection test failed.'));result.classList.remove('hidden')}catch(err){status.textContent='×';status.className='grid h-6 w-6 place-items-center rounded-full bg-red-600 text-lg font-bold leading-none text-white';status.setAttribute('aria-label','Connection failed');result.textContent=err instanceof Error?err.message:'Connection test failed.';result.classList.remove('hidden')}finally{button.disabled=false}}; $('#test-handler').onclick=async()=>{const values=data($('#flow')),result=$('#handler-test-result');result.classList.remove('hidden');result.textContent='Deploying isolated test…';try{const payload=JSON.parse(values.handlerSample||'{}'),response=await fetch('/api/custom-handlers/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({origin:values.customOrigin,handlerName:values.handlerName||'Test handler',handlerCode:values.handlerCode,payload})}),body=await response.json();result.textContent=response.ok?(body.ok?'Handler returned '+body.decision:'Handler failed: '+body.category):(body.error||'Test failed.')}catch(err){result.textContent=err instanceof Error?err.message:'Test failed.'}}; $('#flow').onsubmit=async e=>{e.preventDefault();$('#error').classList.add('hidden');const values=data(e.currentTarget),button=$('#submit'),editing=!!editFlowId;button.disabled=true;button.textContent=editing?'Saving…':'Creating…';try{const matchRules=readRules(),isGitHub=values.sourceKind==='github',isCustom=values.sourceKind==='custom';if(!isGitHub&&!isCustom&&matchRules.some(rule=>!rule.targetId))throw new Error('Choose a target for every matching rule.');if(!values.cwd)throw new Error('Choose a working directory.');if(isGitHub&&(!values.githubInstallation||!values.githubRepository))throw new Error('Choose an active GitHub installation and repository.');if(isCustom&&(!values.handlerName||!values.handlerCode))throw new Error('Provide a handler name and complete function.');let connectionId=values.exeConnection;if(!exeConnected){if(!values.vmName||!values.apiToken)throw new Error('Complete the new Exe.dev connection.');const r=await fetch('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({vmName:values.vmName,agentKind:values.agentKind,cwd:values.cwd,herdrCommand:values.herdrCommand,agentCommand:values.agentCommand,apiToken:values.apiToken})});const result=await r.json().catch(()=>({}));if(!r.ok)throw new Error(result.error||'Could not connect to Herdr.');connectionId=result.connectionId}const source=isGitHub?{kind:'github',installationId:Number(values.githubInstallation),repositoryId:Number(values.githubRepository),baseRef:'main',trigger:'merge_queue_conflict'}:isCustom?{kind:'custom',origin:values.customOrigin,handlerName:values.handlerName,handlerCode:values.handlerCode}:{kind:'linear',projectId:values.projectId,matchRules};const r=await fetch('/api/pipes'+(editing?'/'+encodeURIComponent(editFlowId):''),{method:editing?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:values.name,flowId:values.flowId,projectId:values.projectId,matchRules,source,contextTemplate:values.contextTemplate,maxConcurrency:Number(values.maxConcurrency),exeConnectionId:connectionId,cwd:values.cwd})});const result=await r.json().catch(()=>({}));if(!r.ok)throw new Error(result.error||'Could not save the flow.');location.href=editing?'/flows/'+encodeURIComponent(editFlowId):'/flows'}catch(err){showError(err.message||'Something went wrong.');button.disabled=false;button.textContent=editing?'Save Changes':'Create Flow'}};syncMaxConcurrency();init().then(syncMaxConcurrency); diff --git a/packages/app/test/flow-service.test.ts b/packages/app/test/flow-service.test.ts index 687fdfea..d98a0003 100644 --- a/packages/app/test/flow-service.test.ts +++ b/packages/app/test/flow-service.test.ts @@ -29,7 +29,7 @@ describe("FlowService", () => { if (new URL(request.url).pathname === "/pipes" && request.method === "POST") mutated = true; return Response.json({ role: "owner", session_version: 4 }); }), auth); - await expect(service.createFlow({ name: "Triage", projectId: "p", matchRules: [{ type: "label", targetId: "l" }], maxConcurrency: 3 })).rejects.toMatchObject({ status: 403, code: "insufficient_scope" } satisfies Partial); + await expect(service.createFlow({ name: "Triage", source: { kind: "linear", projectId: "p", matchRules: [{ type: "label", targetId: "l" }] }, exeConnectionId: "exe-1", maxConcurrency: 3 })).rejects.toMatchObject({ status: 403, code: "insufficient_scope" } satisfies Partial); expect(mutated).toBe(false); }); @@ -41,7 +41,9 @@ describe("FlowService", () => { describe("shared API schemas", () => { it("rejects credential and unknown fields", () => { - expect(() => flowInputSchema.parse({ name: "Triage", projectId: "p", matchRules: [{ type: "label", targetId: "l" }], maxConcurrency: 3, apiToken: "secret" })).toThrow(); + expect(() => flowInputSchema.parse({ name: "Triage", source: { kind: "linear", projectId: "p", matchRules: [{ type: "label", targetId: "l" }] }, exeConnectionId: "exe-1", maxConcurrency: 3, apiToken: "secret" })).toThrow(); + expect(flowInputSchema.parse({ name: "Tail", source: { kind: "cloudflareTail" }, exeConnectionId: "exe-1" }).source.kind).toBe("cloudflareTail"); + expect(() => flowInputSchema.parse({ name: "Tail", source: { kind: "cloudflareTail", signingSecret: "nope" }, exeConnectionId: "exe-1" })).toThrow(); }); it("bounds pagination and run states", () => { diff --git a/packages/app/test/source-lifecycle.test.ts b/packages/app/test/source-lifecycle.test.ts new file mode 100644 index 00000000..0624b659 --- /dev/null +++ b/packages/app/test/source-lifecycle.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from "vitest"; +import { preparePublicSource, publicSource, resolveContextTemplate, renderSourcePrompt, TAIL_CONTEXT_TEMPLATE } from "../src/source-lifecycle"; + +describe("source lifecycle", () => { + it("prepares the default Tail handler and preserves its secret on update", async () => { + const created = await preparePublicSource("tenant", "flow", { kind: "cloudflareTail" }); + expect(created).toMatchObject({ kind: "custom", origin: "cloudflare", handlerDeployment: { state: "ready" } }); + const updated = await preparePublicSource("tenant", "flow", { kind: "cloudflareTail", handlerCode: (created as any).handlerCode }, created); + expect((updated as any).tail.signingSecret).toBe((created as any).tail.signingSecret); + expect(publicSource(updated)).not.toHaveProperty("tail"); + expect(publicSource(updated)).not.toHaveProperty("handlerDeployment"); + }); + + it("renders Tail data through its stored Mustache template", async () => { + const source = await preparePublicSource("tenant", "flow", { kind: "cloudflareTail" }); + expect(resolveContextTemplate({ kind: "cloudflareTail" })).toBe(TAIL_CONTEXT_TEMPLATE); + expect(renderSourcePrompt(source, "{{flow.name}}/{{deliveryId}}/{{eventJson}}", { outcome: "exception" }, "Tail", "d1")).toContain("Tail/d1/"); + expect(() => resolveContextTemplate({ kind: "cloudflareTail" }, "{{#broken}}")).toThrow("invalid Mustache"); + }); +}); diff --git a/packages/app/test/ui.test.ts b/packages/app/test/ui.test.ts index f7882df4..9681ad88 100644 --- a/packages/app/test/ui.test.ts +++ b/packages/app/test/ui.test.ts @@ -55,6 +55,12 @@ describe("pages", () => { expect(html).toContain("Connection successful"); expect(html).toContain("Connection failed"); expect(html).toContain("r.ok&&body.ok"); + expect(html).toContain("Cloudflare Tail credentials"); + expect(html).toContain("Generate new secret"); + expect(html).toContain("FACTORIZE_TAIL_SECRET"); + expect(html).toContain("navigator.clipboard.writeText"); + expect(html).toContain("crypto.getRandomValues(new Uint8Array(32))"); + expect(html).toContain("tailSigningSecret"); }); it("renders paginated agent runs with links to run and webhook pages", () => {