diff --git a/docs/cloudflare-tail.md b/docs/cloudflare-tail.md index 0c26630f..892c4d84 100644 --- a/docs/cloudflare-tail.md +++ b/docs/cloudflare-tail.md @@ -4,10 +4,11 @@ Cloudflare Tail is an authenticated Factorize Job trigger for native uncaught Wo ## Configure the job and relay -1. Create a Job, add a **Cloudflare Tail** trigger, and save it. Copy its relay destination and signing secret. -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`: +1. In **Settings → Integrations**, install Cloudflare Tail. Give the installation a name and either paste a signing secret or generate one. Generated secrets are returned only once, so copy it during setup. +2. Create a Job, add a **Cloudflare Tail** trigger, select the installation, and save it. Copy the Job's relay destination. +3. From the repository root, run `npm ci` and set `FACTORIZE_TAIL_DESTINATION` as a Wrangler variable in `packages/tail-relay/wrangler.jsonc`. +4. 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`. Use the selected installation's secret. Keep the relay name `factorize-tail-relay`; Factorize excludes its own relay traces to prevent loops. +5. Add the relay to every producer Worker. One relay can consume multiple producers and forwards each event with its `scriptName`: ```jsonc { @@ -17,7 +18,7 @@ Cloudflare Tail is an authenticated Factorize Job trigger for native uncaught Wo Deploy each producer after changing `tail_consumers`. -MCP clients create or update a Job with a `cloudflareTail` webhook trigger and an execution target returned by `list_execution_targets`. Protected REST and MCP never return the signing secret. After rotating it, update `FACTORIZE_TAIL_SECRET` in Wrangler and redeploy the relay. +Jobs refer to the installation by `integrationId`; secrets are encrypted and are never included in list, status, Job, REST, or MCP responses. Rotating an installation updates every Job that selects it after the relay secret is updated and redeployed. Factorize refuses to disconnect installations still referenced by Jobs, so a missing installation can never turn into unsigned ingestion. 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. diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index 1d8c6dff..ad378440 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -17,7 +17,7 @@ const webhookCommonSchema = z.object({ handlerCode: z.string().max(16_384).optio export const webhookTriggerConfigSchema = z.discriminatedUnion("provider", [ webhookCommonSchema.extend({ provider: z.literal("linear"), projectId: z.string().min(1), matchRules: z.array(matchRuleSchema).min(1) }).strict(), webhookCommonSchema.extend({ provider: z.literal("github"), installationId: z.number().int().positive(), repositoryId: z.number().int().positive(), event: z.string().min(1).default("pull_request"), action: z.string().min(1).default("dequeued") }).strict(), - webhookCommonSchema.extend({ provider: z.literal("cloudflareTail"), signingSecret: z.string().min(16).optional(), handlerCode: z.string().max(16_384).optional() }).strict(), + webhookCommonSchema.extend({ provider: z.literal("cloudflareTail"), integrationId: z.string().min(1) }).strict(), ]); export const triggerSchema = z.discriminatedUnion("kind", [ z.object({ id: z.string().min(1).optional(), slug: z.string().regex(/^trigger-[1-9][0-9]*$/).optional(), kind: z.literal("manual"), enabled: z.boolean().default(true), config: z.object({}).strict().default({}) }).strict(), diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 11205525..8ef186cd 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -43,6 +43,7 @@ export class ApiService { } listExeConnections() { return this.call("flows:read", "/connections/status").then((value: any) => value.exeConnections ?? []); } + listTailIntegrations() { return this.call("flows:read", "/connections/cloudflare-tail"); } listRuns(query: URLSearchParams) { return this.call("runs:read", `/v1/runs?${query}`); } getRun(runId: string) { return this.call("runs:read", `/v1/runs/${encodeURIComponent(runId)}`); } stopRun(runId: string) { return this.call("runs:write", `/v1/runs/${encodeURIComponent(runId)}/stop`, { method: "POST" }); } diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index e058d6c1..357df615 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -168,6 +168,26 @@ app.get("/api/connections/status", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); return tenant(c, session.tenantId).fetch("https://tenant/connections/status"); }); +app.get("/api/connections/cloudflare-tail", async (c) => { + const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); + return tenant(c, session.tenantId).fetch("https://tenant/connections/cloudflare-tail"); +}); +app.post("/api/connections/cloudflare-tail", async (c) => { + const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); + return tenant(c, session.tenantId).fetch("https://tenant/connections/cloudflare-tail", { method: "POST", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); +}); +app.put("/api/connections/cloudflare-tail/:id", async (c) => { + const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); + return tenant(c, session.tenantId).fetch(`https://tenant/connections/cloudflare-tail/${encodeURIComponent(c.req.param("id"))}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: await c.req.text() }); +}); +app.post("/api/connections/cloudflare-tail/:id/test", async (c) => { + const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); + return tenant(c, session.tenantId).fetch(`https://tenant/connections/cloudflare-tail/${encodeURIComponent(c.req.param("id"))}/test`, { method: "POST" }); +}); +app.delete("/api/connections/cloudflare-tail/:id", async (c) => { + const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); + return tenant(c, session.tenantId).fetch(`https://tenant/connections/cloudflare-tail/${encodeURIComponent(c.req.param("id"))}`, { method: "DELETE" }); +}); app.get("/api/linear/projects", async (c) => { const session = await owner(c); if (!session) return c.json({ error: "Unauthorized" }, 401); return tenant(c, session.tenantId).fetch("https://tenant/linear/projects"); diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index 0369fcdb..77479d24 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -40,6 +40,7 @@ export async function protectedApiFetch(request: Request, env: Env, auth: OAuthP if (!path.startsWith("/api/v1")) return Response.json({ error: { code: "not_found", message: "Not found" } }, { status: 404 }); if (request.method === "GET" && path === "/api/v1/exe-connections") return Response.json(await service.listExeConnections()); if (request.method === "GET" && path === "/api/v1/execution-targets") return Response.json(await service.listExecutionTargets()); + if (request.method === "GET" && path === "/api/v1/integrations/cloudflare-tail") return Response.json(await service.listTailIntegrations()); if (request.method === "GET" && path === "/api/v1/jobs") return Response.json(await service.listJobs()); if (request.method === "POST" && path === "/api/v1/jobs") return Response.json(await service.createJob(jobInputSchema.parse(await request.json())), { status: 201 }); if (request.method === "POST" && path === "/api/v1/job-handlers/test") return Response.json(await service.testJobHandler(jobHandlerTestSchema.parse(await request.json()))); @@ -83,6 +84,7 @@ async function mcp(request: Request, service: ApiService, env: Env, ctx: Executi tool("list_job_webhook_activity", "List matching, rejected, duplicate, and accepted webhook activity for a job", z.object({ jobId: z.string().min(1), limit: z.number().int().min(1).max(100).default(50) }), ({ jobId, limit }: any) => service.listJobEvents(jobId, limit)); tool("test_job_webhook_handler", "Test an isolated synchronous Job webhook handler without creating a run. Returns the decision and never accepts credentials.", jobHandlerTestSchema, (input: any) => service.testJobHandler(input)); tool("list_execution_targets", "List non-secret execution target metadata and capabilities", z.object({}), () => service.listExecutionTargets()); + tool("list_cloudflare_tail_integrations", "List installed Cloudflare Tail integrations and reference counts. Signing secrets are never returned.", z.object({}), () => service.listTailIntegrations()); const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined }); await server.connect(transport); const appHostname = new URL(env.APP_ORIGIN).hostname; diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index a28dc112..81acdf0c 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -5,12 +5,12 @@ import { agentListCommand, agentOutputCommand, agentStartupBlocked, agentStatusC import { findOwnedAgent, ownsPane, parseAgent, parseAgentList, parsePaneProcess, type HerdrIdentity } from "./recovery"; import { LINEAR_ISSUE_PROJECT_QUERY, LINEAR_OPTION_QUERIES, LINEAR_PROJECTS_QUERY, isLinearAuthenticationError, refreshLinearToken } from "./linear"; import { matchingIssue } from "./matcher"; -import type { AmpConnectionInput, Env, ExeConnectionInput, FilterType, MatchRule, RunState } from "./types"; +import type { AmpConnectionInput, Env, ExeConnectionInput, FilterType, MatchRule, RunState, TailIntegrationInput } from "./types"; import { workingDirectoryFor, workspaceNameFor } from "./workspace"; import { githubClaimKey, githubHeaders, installationToken, normalizeRepository, renderGitHubPrompt } from "./github"; import type { WorkItem } from "./types"; import { invokeCustomHandler } from "./custom-handler"; -import { sanitizeTailEvent, suppressTailEvent, tailFingerprint, verifyTailDelivery } from "./cloudflare-tail"; +import { generateTailSecret, sanitizeTailEvent, signTailDelivery, suppressTailEvent, tailFingerprint, verifyTailDelivery } from "./cloudflare-tail"; import { ExeHerdrBackend } from "./exe-herdr-backend"; import { AmpBackend, type AmpConnection } from "./amp-backend"; import { DEFAULT_CONTEXT_TEMPLATE, LinearSourceAdapter, linearTicketPrompt, renderContextTemplate } from "./linear-source"; @@ -209,6 +209,13 @@ export class Tenant extends DurableObject { if (request.method === "POST" && url.pathname === "/connections/exe/test") return await this.testExe(await request.json()); if (request.method === "PUT" && url.pathname === "/connections/amp") return await this.saveAmp(await request.json()); if (request.method === "POST" && url.pathname === "/connections/amp/test") return await this.testAmp(await request.json()); + if (request.method === "GET" && url.pathname === "/connections/cloudflare-tail") return json(await this.tailIntegrationStatus()); + if (request.method === "POST" && url.pathname === "/connections/cloudflare-tail") return await this.saveTailIntegration(await request.json()); + const tailConnectionMatch = url.pathname.match(/^\/connections\/cloudflare-tail\/([^/]+)$/); + if (request.method === "PUT" && tailConnectionMatch) return await this.saveTailIntegration({ ...await request.json() as object, integrationId: decodeURIComponent(tailConnectionMatch[1]) }); + if (request.method === "DELETE" && tailConnectionMatch) return this.disconnectTailIntegration(decodeURIComponent(tailConnectionMatch[1])); + const tailTestMatch = url.pathname.match(/^\/connections\/cloudflare-tail\/([^/]+)\/test$/); + if (request.method === "POST" && tailTestMatch) return await this.testTailIntegration(decodeURIComponent(tailTestMatch[1])); if (request.method === "POST" && url.pathname === "/webhook/linear") return await this.acceptLinearWebhook(await request.json() as Record, request.headers.get("linear-delivery")); if (request.method === "POST" && url.pathname === "/webhook/github") return await this.acceptGitHubWebhook(await request.json() as Record, request.headers.get("github-delivery"), request.headers.get("github-event")); const tailMatch = url.pathname.match(/^\/webhook\/cloudflare\/([^/]+)$/); @@ -306,6 +313,46 @@ export class Tenant extends DurableObject { return json({ ok: await new AmpBackend(connection).test() }); } + private async tailIntegrations(): Promise> { + const rows = this.rows("SELECT kind,value FROM connections WHERE kind LIKE 'cloudflare-tail:%' ORDER BY updated_at DESC"); + return Promise.all(rows.map(async row => ({ ...(JSON.parse(await decrypt(String(row.value), this.env.CREDENTIAL_ENCRYPTION_KEY)) as any), integrationId: String(row.kind).slice(16) }))); + } + + private async tailIntegrationStatus(): Promise>> { + const installations = await this.tailIntegrations(); + return installations.map(({ signingSecret: _secret, ...installation }) => ({ ...installation, status: "connected", secretConfigured: true, + referencedJobCount: Number((this.one("SELECT count(DISTINCT job_id) AS count FROM triggers WHERE kind='webhook' AND json_extract(config,'$.provider')='cloudflareTail' AND json_extract(config,'$.integrationId')=?", installation.integrationId) as Row)?.count ?? 0) })); + } + + private async saveTailIntegration(input: unknown): Promise { + const value = input as TailIntegrationInput; + const name = String(value.name ?? "").trim(); + if (!name || name.length > 120) throw new Error("A Tail installation name is required"); + const existing = value.integrationId ? await this.connection(`cloudflare-tail:${value.integrationId}`) : null; + const supplied = String(value.signingSecret ?? ""); + if (supplied && supplied.length < 16) throw new Error("Tail signing secrets must be at least 16 characters"); + const signingSecret = supplied || (value.generateSecret ? generateTailSecret() : existing?.signingSecret); + if (!signingSecret) throw new Error("Paste a signing secret or request a generated secret"); + const integrationId = value.integrationId || id(), timestamp = now(); + await this.putConnection(`cloudflare-tail:${integrationId}`, { name, signingSecret, createdAt: existing?.createdAt ?? timestamp, updatedAt: timestamp }); + return Response.json({ integrationId, name, status: "connected", secretConfigured: true, ...(value.generateSecret ? { generatedSecret: signingSecret } : {}) }, { status: existing ? 200 : 201 }); + } + + private disconnectTailIntegration(integrationId: string): Response { + const referenced = this.one("SELECT count(*) AS count FROM triggers WHERE kind='webhook' AND json_extract(config,'$.provider')='cloudflareTail' AND json_extract(config,'$.integrationId')=?", integrationId) as Row; + if (Number(referenced?.count ?? 0)) return Response.json({ error: "Disable or remove Jobs that reference this Tail installation before disconnecting it." }, { status: 409 }); + const result = this.ctx.storage.sql.exec("DELETE FROM connections WHERE kind=?", `cloudflare-tail:${integrationId}`); + return Number(result.rowsWritten) ? new Response(null, { status: 204 }) : new Response("Not found", { status: 404 }); + } + + private async testTailIntegration(integrationId: string): Promise { + const installation = await this.connection<{ signingSecret: string }>(`cloudflare-tail:${integrationId}`); + if (!installation) return new Response("Not found", { status: 404 }); + const timestamp = String(Date.now()), delivery = `test-${id()}`, body = "{}"; + const signature = await signTailDelivery(installation.signingSecret, timestamp, delivery, body); + return json({ ok: await verifyTailDelivery(installation.signingSecret, timestamp, delivery, body, signature) === "valid" }); + } + private async createPipe(input: PipeInput): Promise { const source = await this.validateSource(input); const rules = source.kind === "linear" ? source.matchRules : [{ type: "status", targetId: source.kind } as MatchRule]; @@ -359,6 +406,7 @@ export class Tenant extends DurableObject { exe: exe ? { vmName: exe.vmName, agentKind: exe.agentKind, cwd: exe.cwd, herdrCommand: exe.herdrCommand ?? "herdr", agentCommand: exe.agentCommand ?? defaultAgentCommand(exe.agentKind) } : null, exeConnections: connections.map(({ apiToken, ...connection }) => connection), ampConnections: ampConnections.map(({ accessToken, ...connection }) => connection), + cloudflareTail: { count: (await this.tailIntegrations()).length, installations: await this.tailIntegrationStatus() }, }); } @@ -448,6 +496,13 @@ export class Tenant extends DurableObject { }); } + private async validateTailIntegrations(triggers: any[]): Promise { + for (const trigger of triggers) { + if (trigger.kind !== "webhook" || trigger.config?.provider !== "cloudflareTail") continue; + if (!await this.connection(`cloudflare-tail:${trigger.config.integrationId}`)) throw new Error("Choose a connected Cloudflare Tail installation"); + } + } + private async resetSchedules(jobId: string): Promise { const job = this.one("SELECT enabled FROM jobs WHERE id=?", jobId) as Row | undefined; const schedules = this.rows("SELECT id,enabled,config FROM triggers WHERE job_id=? AND kind='schedule'", jobId); @@ -470,15 +525,12 @@ export class Tenant extends DurableObject { if (!config.signingSecret && prior.signingSecret) config.signingSecret = prior.signingSecret; if (!config.secret && prior.secret) config.secret = prior.secret; } - if (config.provider === "cloudflareTail" && !config.signingSecret) { - const bytes = crypto.getRandomValues(new Uint8Array(32)); - config.signingSecret = [...bytes].map(byte => byte.toString(16).padStart(2, "0")).join(""); - } return config; } private async createJob(input: any): Promise { this.validateJobInput(input); + await this.validateTailIntegrations(input.triggers); const target = await this.jobTarget(input.executionTargetId), jobId = id(), timestamp = now(); const triggers = this.normalizedTriggers(input.triggers); this.validateLifecycleGraph(jobId, triggers); @@ -496,6 +548,7 @@ export class Tenant extends DurableObject { private async updateJob(jobId: string, input: any): Promise { if (!this.one("SELECT id FROM jobs WHERE id = ?", jobId)) return new Response("Not found", { status: 404 }); this.validateJobInput(input); + await this.validateTailIntegrations(input.triggers); const existing = new Map(this.triggersFor(jobId).map(trigger => [String(trigger.id), trigger])); const triggers = this.normalizedTriggers(input.triggers, existing); this.validateLifecycleGraph(jobId, triggers); @@ -919,10 +972,12 @@ export class Tenant extends DurableObject { private async acceptCloudflareTail(jobId: string, raw: string, headers: Headers): Promise { const item = this.webhookJobs("cloudflareTail").find(({ job }) => job.id === jobId); - if (!item?.config.signingSecret) return new Response("Not found", { status: 404 }); + if (!item?.config.integrationId) return new Response("Not found", { status: 404 }); + const installation = await this.connection<{ signingSecret: string }>(`cloudflare-tail:${item.config.integrationId}`); + if (!installation?.signingSecret) { this.recordJobEvent(jobId, "cloudflareTail", headers.get("x-factorize-delivery") ?? "unknown", "disconnected", "Tail installation is unavailable; delivery rejected."); return new Response("Tail installation disconnected", { status: 503 }); } const timestamp = headers.get("x-factorize-timestamp") ?? "", delivery = headers.get("x-factorize-delivery") ?? "", signature = headers.get("x-factorize-signature") ?? ""; if (!timestamp || !delivery || !signature) return new Response("Missing delivery metadata", { status: 400 }); - const verification = await verifyTailDelivery(item.config.signingSecret, timestamp, delivery, raw, signature); + const verification = await verifyTailDelivery(installation.signingSecret, timestamp, delivery, raw, signature); if (verification !== "valid") { this.recordJobEvent(jobId, "cloudflareTail", delivery, verification, "Tail delivery verification failed."); return new Response(verification === "stale" ? "Stale delivery" : "Invalid signature", { status: 401 }); } let payload: Record; try { payload = sanitizeTailEvent(JSON.parse(raw)) as Record; } catch { return new Response("Invalid JSON", { status: 400 }); } if (suppressTailEvent(payload)) { this.recordJobEvent(jobId, "cloudflareTail", delivery, "rejected", "Tail delivery was suppressed to prevent an ingestion loop."); return new Response(null, { status: 202 }); } diff --git a/packages/app/src/types.ts b/packages/app/src/types.ts index 7c9370f1..ef0e9eb7 100644 --- a/packages/app/src/types.ts +++ b/packages/app/src/types.ts @@ -56,3 +56,4 @@ export interface ExeConnectionInput { } export interface AmpConnectionInput { connectionId?: string; accessToken: string; project: string; apiBaseUrl?: string; } +export interface TailIntegrationInput { integrationId?: string; name: string; signingSecret?: string; generateSecret?: boolean; } diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index 77b4f8ca..8a52b698 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -69,13 +69,15 @@ export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${j +
`, `${uiHelpers} -const jobId=${JSON.stringify(jobId ?? null)},contextCatalog=${JSON.stringify(triggerContextCatalog)},form=$('#job'),dialog=$('#trigger-dialog'),triggerForm=$('#trigger-form');let triggers=[],editing=-1,resources={projects:[],options:{statuses:[],users:[],labels:[]},installations:[],repositories:new Map(),jobs:[]},clientId=0,reservedSlugs=new Set(); +const jobId=${JSON.stringify(jobId ?? null)},contextCatalog=${JSON.stringify(triggerContextCatalog)},form=$('#job'),dialog=$('#trigger-dialog'),triggerForm=$('#trigger-form');let triggers=[],editing=-1,resources={projects:[],options:{statuses:[],users:[],labels:[]},installations:[],tailInstallations:[],repositories:new Map(),jobs:[]},clientId=0,reservedSlugs=new Set(); const kinds={manual:'Manual',schedule:'Schedule',linear:'Linear',github:'GitHub',cloudflareTail:'Cloudflare Tail',jobLifecycle:'Job lifecycle'}; const providerKind=t=>t.kind==='webhook'?t.config.provider:t.kind; const reflection=t=>t.reflection?.paths||contextCatalog[providerKind(t)]||[]; const contextPaths=()=>triggers.flatMap(t=>reflection(t).filter(x=>x.path!=='*').map(x=>({path:t.slug+'.'+x.path,type:x.type,description:x.description}))); const nameOf=(items,id)=>items.find(x=>String(x.id)===String(id))?.name||String(id||'Not selected'); +request('/api/connections/cloudflare-tail').then(items=>{resources.tailInstallations=items;options(triggerForm.elements.tailIntegrationId,items,'name','integrationId')}).catch(()=>{}); const ruleLabels={status:'Status',label:'Label',assignee:'Assignee',creator:'Creator',owner:'Owner'}; const ruleOptions=type=>type==='status'?resources.options.statuses:type==='label'?resources.options.labels:resources.options.users; const ruleSummary=rule=>ruleLabels[rule.type]+' is '+nameOf(ruleOptions(rule.type),rule.targetId); @@ -97,7 +99,7 @@ function addLinearRule(rule={type:'status',targetId:''}){const row=document.crea function readLinearRules(){return linearRuleRows().map(row=>{const [type,target]=row.querySelectorAll('select');return {type:type.value,targetId:target.value}})} async function openEditor(kind,index=-1){const current=index>=0?triggers[index]:null,k=current?providerKind(current):kind;if(!kinds[k])throw new Error('This trigger type is no longer supported.');editing=index;const c=current?.config||{};$('#dialog-title').textContent=(current?'Edit ':'Add ')+kinds[k]+' trigger';triggerForm.reset();document.querySelectorAll('[data-panel]').forEach(x=>x.classList.add('hidden'));const panel=document.querySelector('[data-panel="'+(k==='manual'?'none':k==='schedule'?'schedule':k==='linear'?'linear':k==='github'?'github':k==='jobLifecycle'?'jobLifecycle':'webhook')+'"]');panel?.classList.remove('hidden');triggerForm.dataset.kind=k;$('#dialog-error').classList.add('hidden');$('#handler-result').textContent='';if(k==='schedule'){triggerForm.elements.cron.value=c.cron||'0 9 * * *';triggerForm.elements.timezone.value=c.timezone||'UTC'}if(k==='linear'){options(triggerForm.elements.projectId,resources.projects,'name');triggerForm.elements.projectId.value=c.projectId||resources.projects[0]?.id||'';$('#linear-rules').replaceChildren();(c.matchRules?.length?c.matchRules:[{type:'status',targetId:''}]).forEach(addLinearRule)}if(k==='github'){options(triggerForm.elements.installationId,resources.installations,'accountLogin','installationId');triggerForm.elements.installationId.value=String(c.installationId||resources.installations[0]?.installationId||'');await syncRepositories(c.repositoryId);triggerForm.elements.event.value=c.event||'pull_request';triggerForm.elements.action.value=c.action||'dequeued'}if(k==='jobLifecycle'){options(triggerForm.elements.sourceJobId,resources.jobs.filter(j=>j.id!==jobId),'name');[...triggerForm.elements.sourceJobId.options].forEach(x=>x.selected=(c.sourceJobIds||[]).includes(x.value));triggerForm.querySelectorAll('[name=lifecycleState]').forEach(x=>x.checked=(c.states||['succeeded','failed']).includes(x.value))}if(['linear','github','cloudflareTail'].includes(k))triggerForm.elements.handlerCode.value=c.handlerCode||'';dialog.showModal();if(k==='schedule')previewSchedule()} async function previewSchedule(){const body={cron:triggerForm.elements.cron.value,timezone:triggerForm.elements.timezone.value};try{const x=await request('/api/schedules/preview',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});$('#schedule-preview').textContent='Next occurrence: '+new Date(x.nextRunAt).toLocaleString()}catch(e){$('#schedule-preview').textContent=e.message}} -function configFromForm(){const k=triggerForm.dataset.kind,h=triggerForm.elements.handlerCode?.value.trim(),handler=h?{handlerCode:h}:{};if(k==='manual')return {kind:'manual',config:{}};if(k==='schedule')return {kind:'schedule',config:{cron:triggerForm.elements.cron.value.trim(),timezone:triggerForm.elements.timezone.value}};if(k==='linear')return {kind:'webhook',config:{provider:'linear',projectId:triggerForm.elements.projectId.value,matchRules:readLinearRules(),...handler}};if(k==='github')return {kind:'webhook',config:{provider:'github',installationId:Number(triggerForm.elements.installationId.value),repositoryId:Number(triggerForm.elements.repositoryId.value),event:triggerForm.elements.event.value.trim(),action:triggerForm.elements.action.value.trim(),...handler}};if(k==='cloudflareTail')return {kind:'webhook',config:{provider:k,...handler}};return {kind:'jobLifecycle',config:{sourceJobIds:[...triggerForm.elements.sourceJobId.selectedOptions].map(x=>x.value),states:[...triggerForm.querySelectorAll('[name=lifecycleState]:checked')].map(x=>x.value)}}} +function configFromForm(){const k=triggerForm.dataset.kind,h=triggerForm.elements.handlerCode?.value.trim(),handler=h?{handlerCode:h}:{};if(k==='manual')return {kind:'manual',config:{}};if(k==='schedule')return {kind:'schedule',config:{cron:triggerForm.elements.cron.value.trim(),timezone:triggerForm.elements.timezone.value}};if(k==='linear')return {kind:'webhook',config:{provider:'linear',projectId:triggerForm.elements.projectId.value,matchRules:readLinearRules(),...handler}};if(k==='github')return {kind:'webhook',config:{provider:'github',installationId:Number(triggerForm.elements.installationId.value),repositoryId:Number(triggerForm.elements.repositoryId.value),event:triggerForm.elements.event.value.trim(),action:triggerForm.elements.action.value.trim(),...handler}};if(k==='cloudflareTail')return {kind:'webhook',config:{provider:k,integrationId:triggerForm.elements.tailIntegrationId.value}};return {kind:'jobLifecycle',config:{sourceJobIds:[...triggerForm.elements.sourceJobId.selectedOptions].map(x=>x.value),states:[...triggerForm.querySelectorAll('[name=lifecycleState]:checked')].map(x=>x.value)}}} function validate(candidate){const k=providerKind(candidate);if(k==='manual'&&triggers.some((t,i)=>i!==editing&&providerKind(t)==='manual'))throw new Error('Only one Manual trigger can be configured.');if(k==='linear'&&(!candidate.config.projectId||!candidate.config.matchRules.length||candidate.config.matchRules.some(rule=>!rule.targetId)))throw new Error('Choose a Linear project and a value for every matching rule.');if(k==='github'&&(!candidate.config.installationId||!candidate.config.repositoryId))throw new Error('Choose a GitHub installation and repository.');if(k==='jobLifecycle'&&(!candidate.config.sourceJobIds[0]||!candidate.config.states.length))throw new Error('Choose a source job and at least one final state.');if(triggers.some((t,i)=>i!==editing&&JSON.stringify(t.config)===JSON.stringify(candidate.config)&&t.kind===candidate.kind))throw new Error('An identical trigger is already configured.')} $('#trigger-rows').onclick=e=>{const b=e.target.closest('button');if(!b)return;const key=['edit','remove'].find(x=>b.dataset[x]!==undefined),i=Number(b.dataset[key]);if(key==='edit')openEditor(providerKind(triggers[i]),i);if(key==='remove'){if(providerKind(triggers[i])==='manual'){const error=$('#error');error.textContent='A Job must keep its Manual trigger. Disable it if manual runs should be unavailable.';error.classList.remove('hidden');return}triggers.splice(i,1);render()}}; $('#trigger-rows').onchange=e=>{if(e.target.dataset.enable===undefined)return;triggers[Number(e.target.dataset.enable)].enabled=e.target.checked;render()};$('#add-trigger').onchange=e=>{const kind=e.target.value;e.target.value='';if(kind)openEditor(kind)};$('#add-linear-rule').onclick=()=>addLinearRule();$('#cancel-trigger').onclick=()=>dialog.close();triggerForm.elements.installationId.onchange=()=>syncRepositories();triggerForm.elements.cron.oninput=previewSchedule;triggerForm.elements.timezone.onchange=previewSchedule; @@ -121,10 +123,11 @@ ${[["integrations", "Integrations"], ["api-keys", "API Keys"]].map(([id, label]) export const settingsPage = (viewer: { email: string }) => shell("Integrations — Factorize", viewer, settingsLayout("integrations", `${dashboardHead("Integrations", "Connect every provider used by your Jobs. Stored credentials are write-only and are never displayed.")}

Available integrations

Add a provider to Factorize.

-${[["linear","Linear","Issues and projects"],["github","GitHub","Repositories and triggers"],["exe","Exe.dev","VM execution"],["amp","Amp","Cloud execution"]].map(([id,name,description])=>``).join("")} +${[["linear","Linear","Issues and projects"],["github","GitHub","Repositories and triggers"],["exe","Exe.dev","VM execution"],["amp","Amp","Cloud execution"],["tail","Cloudflare Tail","Signed Worker Tail events"]].map(([id,name,description])=>``).join("")}
+

Installed integrations

Check status and manage providers already connected to Factorize.

Loading installed integrations…
`), `${uiHelpers} const badge=(id,label,tone)=>{const el=$(id);el.textContent=label;el.className='rounded-full px-3 py-1 text-xs font-semibold '+(tone==='ok'?'bg-green-100 text-green-800 dark:bg-green-950 dark:text-green-200':tone==='warn'?'bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-200':'bg-stone-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300')}; const testButton=(kind,id)=>''; @@ -135,7 +138,8 @@ function openSetup(kind){const panel=$('#'+kind+'-setup');panel.classList.remove function bindActions(){bindTests();document.querySelectorAll('[data-open-setup]').forEach(button=>button.onclick=()=>openSetup(button.dataset.openSetup));document.querySelectorAll('[data-close-setup]').forEach(button=>button.onclick=()=>$('#'+button.dataset.closeSetup+'-setup').classList.add('hidden'));document.querySelectorAll('[data-disconnect-github]').forEach(button=>button.onclick=()=>disconnectGitHub(button.dataset.disconnectGithub).catch(e=>{const error=$('#integration-error');error.textContent=e.message;error.classList.remove('hidden')}))} function bindTests(){document.querySelectorAll('[data-test]').forEach(button=>button.onclick=async()=>{const original=button.textContent;button.disabled=true;button.textContent='Testing…';try{const kind=button.dataset.test,result=await request('/api/connections/'+kind+'/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({connectionId:button.dataset.id})});button.textContent=result.ok?'Connected':'Action required'}catch(e){button.textContent='Action required'}finally{setTimeout(()=>{button.disabled=false;button.textContent=original},1500)}})} $('#connection').onsubmit=async e=>{e.preventDefault();const d=new FormData(e.currentTarget),m=$('#settings-message');try{await request('/api/connections/exe',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify({vmName:d.get('vmName'),apiToken:d.get('apiToken'),cwd:d.get('cwd'),agentKind:d.get('agentKind'),herdrCommand:'herdr',agentCommand:''})});e.currentTarget.reset();m.textContent='Connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}}; -const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/connections/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection needs attention.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const m=$('#amp-message');try{await request('/api/connections/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});e.currentTarget.reset();m.textContent='Amp connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}};bindActions();load();`); +const ampPayload=()=>{const d=new FormData($('#amp-connection'));return {project:d.get('project'),accessToken:d.get('accessToken'),apiBaseUrl:d.get('apiBaseUrl')}};$('#test-amp').onclick=async()=>{const m=$('#amp-message');try{const x=await request('/api/connections/amp/test',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});m.textContent=x.ok?'Amp connection succeeded.':'Amp connection needs attention.'}catch(x){m.textContent=x.message}};$('#amp-connection').onsubmit=async e=>{e.preventDefault();const m=$('#amp-message');try{await request('/api/connections/amp',{method:'PUT',headers:{'content-type':'application/json'},body:JSON.stringify(ampPayload())});e.currentTarget.reset();m.textContent='Amp connection saved. The token remains write-only.';await load()}catch(x){m.textContent=x.message}}; +$('#tail-connection').onsubmit=async e=>{e.preventDefault();const d=new FormData(e.currentTarget),m=$('#tail-message');try{const x=await request('/api/connections/cloudflare-tail',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({name:d.get('name'),signingSecret:d.get('signingSecret')||undefined,generateSecret:d.get('generateSecret')==='on'})});if(x.generatedSecret){$('#tail-generated-value').textContent=x.generatedSecret;$('#tail-generated').classList.remove('hidden')}e.currentTarget.reset();m.textContent='Tail installation saved. Its secret remains write-only.';await load()}catch(x){m.textContent=x.message}};$('#copy-tail-secret').onclick=async()=>{await navigator.clipboard.writeText($('#tail-generated-value').textContent);$('#copy-tail-secret').textContent='Copied'};bindActions();load();`); export const apiKeysSettingsPage = (viewer: { email: string }) => shell("API Keys — Factorize", viewer, settingsLayout("api-keys", `${dashboardHead("API Keys", "Manage API keys for programmatic access to Factorize.")} diff --git a/packages/app/src/webhook-trigger.ts b/packages/app/src/webhook-trigger.ts index 413aa853..37fcf608 100644 --- a/packages/app/src/webhook-trigger.ts +++ b/packages/app/src/webhook-trigger.ts @@ -6,7 +6,7 @@ export type WebhookProvider = "linear" | "github" | "cloudflareTail"; export type WebhookTriggerConfig = { provider: WebhookProvider; projectId?: string; matchRules?: MatchRule[]; installationId?: number; repositoryId?: number; - event?: string; action?: string; signingSecret?: string; secret?: string; handlerCode?: string; + event?: string; action?: string; integrationId?: string; signingSecret?: string; secret?: string; handlerCode?: string; }; export interface WebhookInvocation { claimKey: string; payload: Record; diff --git a/packages/app/test/cloudflare-tail.test.ts b/packages/app/test/cloudflare-tail.test.ts index 77740485..fd490c1d 100644 --- a/packages/app/test/cloudflare-tail.test.ts +++ b/packages/app/test/cloudflare-tail.test.ts @@ -1,7 +1,12 @@ import { describe, expect, it } from "vitest"; -import { sanitizeTailEvent, signTailDelivery, suppressTailEvent, tailFingerprint, verifyTailDelivery } from "../src/cloudflare-tail"; +import { generateTailSecret, sanitizeTailEvent, signTailDelivery, suppressTailEvent, tailFingerprint, verifyTailDelivery } from "../src/cloudflare-tail"; describe("Cloudflare Tail ingestion", () => { + it("generates independent strong URL-safe installation secrets", () => { + const first = generateTailSecret(), second = generateTailSecret(); + expect(first).toMatch(/^[A-Za-z0-9_-]{43}$/); + expect(second).not.toBe(first); + }); it("signs the timestamp, delivery ID, and exact body and rejects tampering or stale requests", async () => { const body = JSON.stringify({ outcome: "exception" }), timestamp = String(Date.now()), delivery = "delivery-1", secret = "s".repeat(43); const signature = await signTailDelivery(secret, timestamp, delivery, body); diff --git a/packages/app/test/worker.test.ts b/packages/app/test/worker.test.ts index 4a3e9a06..bc65f28e 100644 --- a/packages/app/test/worker.test.ts +++ b/packages/app/test/worker.test.ts @@ -102,6 +102,14 @@ describe("Worker routes", () => { expect(JSON.stringify(body)).not.toContain("refreshToken"); }); + it("routes secret-free Cloudflare Tail installation management through the owner boundary", async () => { + const installation = { integrationId: "tail-1", name: "Production", status: "connected", secretConfigured: true, referencedJobCount: 2 }; + const response = await app.request("https://factorize.test/api/connections/cloudflare-tail", { headers: { cookie: await sessionCookie() } }, testEnv(ownerHandler({ "/connections/cloudflare-tail": Response.json([installation]) }))); + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual([installation]); + expect(JSON.stringify(installation)).not.toContain("signingSecret"); + }); + it("fails closed for removed Flow and generic webhook routes", async () => { const env = testEnv(ownerHandler({})); for (const path of ["/api/pipes", "/api/pipes/old", "/api/runs/old", "/flows", "/flows/old", "/webhooks/custom/tenant/job"]) {