From bc57fcbfe47e7fa4c50ae64ba120768dd203271a Mon Sep 17 00:00:00 2001 From: Brendan Date: Wed, 16 Sep 2026 20:31:26 +0000 Subject: [PATCH] GEN-2010 add job webhook handlers --- docs/job-trigger-context.md | 2 ++ packages/app/src/custom-handler.ts | 36 +++++++++++++++---- packages/app/src/flow-schemas.ts | 5 ++- packages/app/src/flow-service.ts | 1 + packages/app/src/protected-api.ts | 4 ++- packages/app/src/tenant.ts | 42 ++++++++++++++++++++--- packages/app/src/ui.ts | 6 ++-- packages/app/src/webhook-trigger.ts | 5 +++ packages/app/test/custom-handler.test.ts | 11 ++++-- packages/app/test/webhook-trigger.test.ts | 11 ++++-- 10 files changed, 103 insertions(+), 20 deletions(-) diff --git a/docs/job-trigger-context.md b/docs/job-trigger-context.md index 75fa52e0..18ebe0a8 100644 --- a/docs/job-trigger-context.md +++ b/docs/job-trigger-context.md @@ -25,3 +25,5 @@ The available value beneath a slug is: Manual invocation accepts `{ "prompt": "...", "idempotencyKey": "..." }`. Parameter defaults and invocation, schedule, or webhook parameter overrides are not accepted. Run inspection returns `context` as the complete persisted object and `invocation.trigger_id` as the trigger that fired. Parameter-era stored Jobs are migrated: old context and parameters are retained beneath `legacy_context` and `legacy_parameters` in the corresponding trigger context. They are not used as global template variables. + +Every webhook trigger may also define `handlerCode` containing one synchronous `function handler(webhook)` declaration. Factorize runs it only after provider authentication and trigger scoping, inside an isolated Worker with no bindings or outbound network access. Returning `false` rejects the delivery, `true` retains the default value above, and a JSON-compatible object replaces that value beneath the stable trigger slug. Timeouts, exceptions, and invalid return values are recorded in webhook activity and never create a run. REST `POST /api/v1/job-handlers/test` and MCP `test_job_webhook_handler` exercise the same isolation boundary without creating an invocation. diff --git a/packages/app/src/custom-handler.ts b/packages/app/src/custom-handler.ts index 41cb0c4a..12756a79 100644 --- a/packages/app/src/custom-handler.ts +++ b/packages/app/src/custom-handler.ts @@ -9,7 +9,7 @@ export const CUSTOM_HANDLER_COMPATIBILITY_DATE = "2026-09-10"; export const CUSTOM_HANDLER_DEADLINE_MS = 250; export type HandlerDecision = - | { ok: true; decision: boolean } + | { ok: true; decision: boolean | Record } | { ok: false; category: "handler_error" | "invalid_return" | "timeout" | "platform_error" }; const encoder = new TextEncoder(); @@ -34,21 +34,44 @@ export function validateCustomHandler(origin: unknown, handlerName: unknown, han return { origin, handlerName: handlerName.trim(), handlerCode }; } +export function validateHandlerCode(handlerCode: unknown): string { + if (typeof handlerCode !== "string" || encoder.encode(handlerCode).byteLength > CUSTOM_HANDLER_MAX_CODE_BYTES) throw new Error(`Handler code must be at most ${CUSTOM_HANDLER_MAX_CODE_BYTES} bytes.`); + if (!/^\s*function\s+handler\s*\(\s*webhook\s*\)\s*\{[\s\S]*\}\s*;?\s*$/.test(handlerCode)) throw new Error("Provide one complete function handler(webhook) declaration."); + return handlerCode; +} + export function userWorkerModule(handlerCode: string): string { return `${handlerCode}\n +const jsonCompatible = (value, seen = new Set()) => { + if (value === null || typeof value === "string" || typeof value === "boolean") return true; + if (typeof value === "number") return Number.isFinite(value); + if (typeof value !== "object" || seen.has(value)) return false; + seen.add(value); + const valid = Array.isArray(value) + ? value.every(item => jsonCompatible(item, seen)) + : (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null) && Object.values(value).every(item => jsonCompatible(item, seen)); + seen.delete(value); + return valid; +}; export default { async fetch(request) { if (request.method !== "POST") return Response.json({ ok: false, category: "handler_error" }, { status: 405 }); try { const webhook = await request.json(); const result = handler(webhook); if (result !== null && (typeof result === "object" || typeof result === "function") && typeof result.then === "function") return Response.json({ ok: false, category: "invalid_return" }); - if (typeof result !== "boolean") return Response.json({ ok: false, category: "invalid_return" }); - return Response.json({ ok: true, decision: result }); + if (typeof result === "boolean") return Response.json({ ok: true, decision: result }); + if (result === null || typeof result !== "object" || Array.isArray(result) || !jsonCompatible(result)) return Response.json({ ok: false, category: "invalid_return" }); + try { + const serialized = JSON.stringify(result); + const decision = JSON.parse(serialized); + if (decision === null || typeof decision !== "object" || Array.isArray(decision)) return Response.json({ ok: false, category: "invalid_return" }); + return Response.json({ ok: true, decision }); + } catch { return Response.json({ ok: false, category: "invalid_return" }); } } catch { return Response.json({ ok: false, category: "handler_error" }); } } };`; } -export async function invokeCustomHandler(loader: WorkerLoader, source: CustomSource, payload: unknown): Promise { +export async function invokeCustomHandler(loader: WorkerLoader, source: Pick, payload: unknown): Promise { const body = JSON.stringify(payload); if (encoder.encode(body).byteLength > CUSTOM_HANDLER_MAX_PAYLOAD_BYTES) return { ok: false, category: "platform_error" }; const controller = new AbortController(); @@ -64,8 +87,9 @@ export async function invokeCustomHandler(loader: WorkerLoader, source: CustomSo }); const response = await worker.getEntrypoint().fetch("https://handler.internal/", { method: "POST", headers: { "Content-Type": "application/json" }, body, signal: controller.signal }); if (!response.ok) return { ok: false, category: "platform_error" }; - const result = await response.json() as HandlerDecision; - return result?.ok === true && typeof result.decision === "boolean" ? result : result?.ok === false && ["handler_error", "invalid_return", "timeout", "platform_error"].includes(result.category) ? result : { ok: false, category: "platform_error" }; + const result = await response.json() as any; + const validDecision = typeof result?.decision === "boolean" || (result?.decision !== null && typeof result?.decision === "object" && !Array.isArray(result?.decision)); + return result?.ok === true && validDecision ? result : result?.ok === false && ["handler_error", "invalid_return", "timeout", "platform_error"].includes(result.category) ? result : { ok: false, category: "platform_error" }; } catch (error) { return { ok: false, category: error instanceof DOMException && error.name === "AbortError" ? "timeout" : "platform_error" }; } finally { clearTimeout(deadline); } diff --git a/packages/app/src/flow-schemas.ts b/packages/app/src/flow-schemas.ts index adb56f48..97c5348c 100644 --- a/packages/app/src/flow-schemas.ts +++ b/packages/app/src/flow-schemas.ts @@ -31,7 +31,7 @@ export const listEventsSchema = z.object({ flowId: z.string().min(1), limit: z.coerce.number().int().min(1).max(100).default(50), cursor: z.string().min(1).optional(), }); -const webhookCommonSchema = z.object({}); +const webhookCommonSchema = z.object({ handlerCode: z.string().max(16_384).optional() }); 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(), @@ -60,6 +60,9 @@ export const manualInvocationSchema = z.object({ prompt: z.string().max(50_000).default(""), idempotencyKey: z.string().trim().min(1).max(200).optional(), }).strict(); +export const jobHandlerTestSchema = z.object({ + handlerCode: z.string().max(16_384), payload: z.record(z.string(), z.unknown()), +}).strict(); export type FlowInput = z.infer; export type JobInput = z.infer; diff --git a/packages/app/src/flow-service.ts b/packages/app/src/flow-service.ts index 774399c3..59aa9848 100644 --- a/packages/app/src/flow-service.ts +++ b/packages/app/src/flow-service.ts @@ -88,6 +88,7 @@ export class FlowService { async listJobs() { return (await this.call("flows:read", "/v1/jobs") as any[]).map(value => this.publicJob(value)); } async getJob(jobId: string) { return this.publicJob(await this.call("flows:read", `/v1/jobs/${encodeURIComponent(jobId)}`)); } listJobEvents(jobId: string, limit = 50) { return this.call("runs:read", `/v1/jobs/${encodeURIComponent(jobId)}/events?limit=${limit}`); } + testJobHandler(input: { handlerCode: string; payload: Record }) { return this.call("flows:write", "/v1/job-handlers/test", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) }); } async createJob(input: JobInput) { return this.publicJob(await this.call("flows:write", "/v1/jobs", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) })); } async updateJob(jobId: string, input: JobInput) { return this.publicJob(await this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(input) })); } deleteJob(jobId: string) { return this.call("flows:write", `/v1/jobs/${encodeURIComponent(jobId)}`, { method: "DELETE" }); } diff --git a/packages/app/src/protected-api.ts b/packages/app/src/protected-api.ts index 49ab5165..ac6081e4 100644 --- a/packages/app/src/protected-api.ts +++ b/packages/app/src/protected-api.ts @@ -3,7 +3,7 @@ import { McpServer, WebStandardStreamableHTTPServerTransport } from "@modelconte import { createMcpHonoApp } from "@modelcontextprotocol/hono"; import { z } from "zod"; import { FlowService, ServiceError } from "./flow-service"; -import { flowIdSchema, flowInputSchema, jobIdSchema, jobInputSchema, listEventsSchema, listRunsSchema, manualInvocationSchema, runIdSchema } from "./flow-schemas"; +import { flowIdSchema, flowInputSchema, jobHandlerTestSchema, jobIdSchema, jobInputSchema, listEventsSchema, listRunsSchema, manualInvocationSchema, runIdSchema } from "./flow-schemas"; import type { Env, OAuthProps } from "./types"; function errorResponse(error: unknown): Response { @@ -51,6 +51,7 @@ export class ProtectedApiHandler extends WorkerEntrypoint { if (request.method === "GET" && path === "/api/v1/execution-targets") return Response.json(await service.listExecutionTargets()); 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()))); const invocationMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)\/invocations$/); if (invocationMatch && request.method === "POST") return Response.json(await service.invokeJob(decodeURIComponent(invocationMatch[1]), manualInvocationSchema.parse(await request.json())), { status: 202 }); const jobEventsMatch = path.match(/^\/api\/v1\/jobs\/([^/]+)\/events$/); @@ -98,6 +99,7 @@ export class ProtectedApiHandler extends WorkerEntrypoint { tool("disable_job", "Disable a job", jobIdSchema, ({ jobId }: any) => service.setJobEnabled(jobId, false)); tool("invoke_job", "Invoke a job's manual trigger with a prompt exposed beneath that trigger's stable slug. Manual invocations are never coalesced.", manualInvocationSchema.extend({ jobId: z.string().min(1) }), ({ jobId, ...input }: any) => service.invokeJob(jobId, input)); 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()); const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined }); await server.connect(transport); diff --git a/packages/app/src/tenant.ts b/packages/app/src/tenant.ts index 5ad7e439..683e258e 100644 --- a/packages/app/src/tenant.ts +++ b/packages/app/src/tenant.ts @@ -18,7 +18,7 @@ import { renderSourcePrompt } from "./source-lifecycle"; import { JOB_SCHEMA, renderJobPrompt } from "./job-domain"; import { normalizeExecutionState, type RunHandle } from "./execution"; import { catchUpOccurrence, nextOccurrence, validateScheduleConfig, type ScheduleConfig } from "./schedule"; -import { adaptWebhook, publicWebhookConfig, type WebhookProvider, type WebhookTriggerConfig } from "./webhook-trigger"; +import { adaptWebhook, publicWebhookConfig, validateWebhookHandler, type WebhookProvider, type WebhookTriggerConfig } from "./webhook-trigger"; export { DEFAULT_CONTEXT_TEMPLATE, linearTicketPrompt, renderContextTemplate } from "./linear-source"; @@ -190,6 +190,7 @@ export class Tenant extends DurableObject { if (request.method === "DELETE" && jobMatch) return this.deleteJob(decodeURIComponent(jobMatch[1])); const jobEventsMatch = url.pathname.match(/^\/v1\/jobs\/([^/]+)\/events$/); if (request.method === "GET" && jobEventsMatch) return this.listJobEvents(decodeURIComponent(jobEventsMatch[1]), url); + if (request.method === "POST" && url.pathname === "/v1/job-handlers/test") return await this.testJobHandler(await request.json()); if (request.method === "GET" && /^\/v1\/flows\/[^/]+$/.test(url.pathname)) return this.getFlow(decodeURIComponent(url.pathname.split("/")[3] ?? "")); if (request.method === "GET" && url.pathname === "/connections/status") return await this.connectionStatus(); if (request.method === "POST" && url.pathname === "/members") return await this.upsertMember(await request.json()); @@ -428,7 +429,10 @@ export class Tenant extends DurableObject { if (!input?.name || !input.promptTemplate) throw new Error("Job name and prompt template are required"); if (!Array.isArray(input.triggers) || input.triggers.some((trigger: any) => !["manual", "schedule", "webhook", "jobLifecycle"].includes(trigger?.kind))) throw new Error("Job triggers are invalid"); Mustache.parse(input.promptTemplate); - for (const trigger of input.triggers) if (trigger.kind === "schedule") validateScheduleConfig(trigger.config); + for (const trigger of input.triggers) { + if (trigger.kind === "schedule") validateScheduleConfig(trigger.config); + if (trigger.kind === "webhook") validateWebhookHandler(trigger.config); + } } private normalizedTriggers(input: any[], existing: Map = new Map()): any[] { @@ -843,11 +847,30 @@ export class Tenant extends DurableObject { for (const { job, triggerId, triggerSlug, config } of this.webhookJobs(provider) as any[]) { const invocation = adaptWebhook(config, provider, deliveryId, payload, eventName); if (!invocation) { this.recordJobEvent(String(job.id), provider, deliveryId, "ignored", "Webhook did not match this job trigger."); continue; } - const result = await this.signalAutomaticJob(String(job.id), "webhook", triggerId, `webhook:${triggerId}:${invocation.claimKey}`, { [triggerSlug]: invocation.payload }, { ...invocation.occurrence, metadata: { ...invocation.occurrence?.metadata, triggerId } }); + let triggerContext: Record = invocation.payload; + if (config.handlerCode) { + if (!this.env.CUSTOM_HANDLER_LOADER) { this.recordJobEvent(String(job.id), provider, deliveryId, "platform_error", "Webhook handler platform is unavailable; no run was created."); continue; } + const decision = await invokeCustomHandler(this.env.CUSTOM_HANDLER_LOADER, config as Required>, payload); + if (!decision.ok) { + const detail = decision.category === "timeout" ? "Handler exceeded its execution deadline; no run was created." : decision.category === "invalid_return" ? "Handler must synchronously return true, false, or a JSON-compatible object; no run was created." : "Handler failed closed; no run was created."; + this.recordJobEvent(String(job.id), provider, deliveryId, decision.category, detail); continue; + } + if (decision.decision === false) { this.recordJobEvent(String(job.id), provider, deliveryId, "rejected", "Handler returned false; no run was created."); continue; } + if (decision.decision !== true) triggerContext = decision.decision; + } + const result = await this.signalAutomaticJob(String(job.id), "webhook", triggerId, `webhook:${triggerId}:${invocation.claimKey}`, { [triggerSlug]: triggerContext }, { ...invocation.occurrence, metadata: { ...invocation.occurrence?.metadata, triggerId } }); this.recordJobEvent(String(job.id), provider, deliveryId, result?.duplicate ? "duplicate" : result ? "accepted" : "ignored", result?.duplicate ? "Webhook occurrence was already claimed." : result ? "Webhook occurrence queued through canonical job invocation." : "Job was unavailable."); } } + private async testJobHandler(input: { handlerCode?: unknown; payload?: unknown }): Promise { + const config: WebhookTriggerConfig = { provider: "custom", handlerCode: typeof input.handlerCode === "string" ? input.handlerCode : undefined }; + validateWebhookHandler(config); + if (!config.handlerCode) throw new Error("Handler code is required."); + if (!this.env.CUSTOM_HANDLER_LOADER) return Response.json({ ok: false, category: "platform_error" }, { status: 503 }); + return json(await invokeCustomHandler(this.env.CUSTOM_HANDLER_LOADER, { handlerCode: config.handlerCode }, input.payload)); + } + private listJobEvents(jobId: string, url: URL): Response { if (!this.one("SELECT id FROM jobs WHERE id=?", jobId)) return new Response("Not found", { status: 404 }); const limit = Math.max(1, Math.min(100, Number(url.searchParams.get("limit") ?? 50))); @@ -1056,8 +1079,17 @@ export class Tenant extends DurableObject { const payload = { ...saved, pull_request: { ...saved.pull_request, ...pull } }; const invocation = adaptWebhook(config, "github", String(verification.delivery_id), payload, "pull_request"); this.ctx.storage.sql.exec("DELETE FROM pending_verifications WHERE id=?", verification.id); - if (invocation) await this.signalAutomaticJob(String(job.id), "webhook", String(job.trigger_id), `webhook:${String(job.trigger_id)}:${invocation.claimKey}`, { [String((job as any).trigger_slug)]: invocation.payload }, invocation.occurrence); - this.recordJobEvent(String(job.id), "github", String(verification.delivery_id), invocation ? "accepted" : "ignored", invocation ? "Verified webhook queued through canonical job invocation." : "Job trigger changed while verification was pending."); + if (!invocation) { this.recordJobEvent(String(job.id), "github", String(verification.delivery_id), "ignored", "Job trigger changed while verification was pending."); continue; } + let triggerContext: Record = invocation.payload; + if (config.handlerCode) { + if (!this.env.CUSTOM_HANDLER_LOADER) { this.recordJobEvent(String(job.id), "github", String(verification.delivery_id), "platform_error", "Webhook handler platform is unavailable; no run was created."); continue; } + const decision = await invokeCustomHandler(this.env.CUSTOM_HANDLER_LOADER, { handlerCode: config.handlerCode }, payload); + if (!decision.ok) { this.recordJobEvent(String(job.id), "github", String(verification.delivery_id), decision.category, decision.category === "timeout" ? "Handler exceeded its execution deadline; no run was created." : decision.category === "invalid_return" ? "Handler must synchronously return true, false, or a JSON-compatible object; no run was created." : "Handler failed closed; no run was created."); continue; } + if (decision.decision === false) { this.recordJobEvent(String(job.id), "github", String(verification.delivery_id), "rejected", "Handler returned false; no run was created."); continue; } + if (decision.decision !== true) triggerContext = decision.decision; + } + const result = await this.signalAutomaticJob(String(job.id), "webhook", String(job.trigger_id), `webhook:${String(job.trigger_id)}:${invocation.claimKey}`, { [String((job as any).trigger_slug)]: triggerContext }, invocation.occurrence); + this.recordJobEvent(String(job.id), "github", String(verification.delivery_id), result?.duplicate ? "duplicate" : result ? "accepted" : "ignored", result?.duplicate ? "Webhook occurrence was already claimed." : result ? "Verified webhook queued through canonical job invocation." : "Job was unavailable."); continue; } const legacyPipe = pipe!; diff --git a/packages/app/src/ui.ts b/packages/app/src/ui.ts index c486ce69..22b0e51f 100644 --- a/packages/app/src/ui.ts +++ b/packages/app/src/ui.ts @@ -211,15 +211,15 @@ export const jobPage = (viewer: { email: string }, jobId?: string) => shell(`${j

Automatic triggers

Manual invocation is always available. Configure a primary trigger and any additional triggers below.

${[["manual","Manual only","No primary automatic trigger."],["schedule","Schedule","Run automatically on a clock."],["webhook","Webhook","Run from a provider event."]].map(([v,l,d]) => ``).join("")}
-
+
`, `${uiHelpers} const jobId=${JSON.stringify(jobId ?? null)},form=$('#job'),schedule=$('#schedule'),webhook=$('#webhook'); function syncTrigger(){const kind=new FormData(form).get('triggerKind');schedule.classList.toggle('hidden',kind!=='schedule');webhook.classList.toggle('hidden',kind!=='webhook')} let previewTimer;function syncCron(){const f=form.frequency.value,advanced=f==='advanced';$('#cron-wrap').classList.toggle('hidden',!advanced);const cron=advanced?form.cron.value:f;$('#cron-output').textContent=cron;const zone=form.timezone.value;$('#next-run').textContent='Calculating next occurrence…';clearTimeout(previewTimer);previewTimer=setTimeout(async()=>{try{const x=await request('/api/schedules/preview',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({cron,timezone:zone})});$('#next-run').textContent='Next occurrence: '+new Date(x.nextRunAt).toLocaleString()+' ('+zone+')'}catch(e){$('#next-run').textContent=e.message}},150)} function syncProvider(){const p=form.provider.value;$('#linear-hook').classList.toggle('hidden',p!=='linear');$('#github-hook').classList.toggle('hidden',p!=='github');$('#managed-hook').classList.toggle('hidden',p==='linear'||p==='github')} form.onchange=e=>{if(e.target.name==='triggerKind')syncTrigger();if(['frequency','timezone','cron'].includes(e.target.name))syncCron();if(e.target.name==='provider')syncProvider()};$('#copy-cron').onclick=()=>navigator.clipboard.writeText($('#cron-output').textContent); -async function init(){const targets=await request('/api/execution-targets');form.executionTargetId.innerHTML=''+targets.map(t=>'').join('');if(!jobId)return;const j=await request('/api/jobs/'+encodeURIComponent(jobId));form.name.value=j.name;form.promptTemplate.value=j.promptTemplate;form.concurrencyLimit.value=j.concurrencyLimit;form.executionTargetId.value=j.executionTargetId;const primary=(j.triggers||[]).find(t=>t.kind==='schedule'||t.kind==='webhook'),kind=primary?.kind||'manual';form.querySelector('[value="'+kind+'"]').checked=true;form.additionalTriggers.value=JSON.stringify((j.triggers||[]).filter(t=>t!==primary),null,2);const c=primary?.config||{};if(kind==='schedule'){form.timezone.value=c.timezone;form.cron.value=c.cron;const common=[...form.frequency.options].find(o=>o.value===c.cron);form.frequency.value=common?c.cron:'advanced'}if(kind==='webhook'){form.provider.value=c.provider;form.projectId.value=c.projectId||'';form.statusId.value=c.matchRules?.[0]?.targetId||'';form.installationId.value=c.installationId||'';form.repositoryId.value=c.repositoryId||'';form.event.value=c.event||'pull_request';form.action.value=c.action||'dequeued'}form.dataset.primaryId=primary?.id||'';syncTrigger();syncCron();syncProvider()} -form.onsubmit=async e=>{e.preventDefault();const save=$('#save'),err=$('#error');err.classList.add('hidden');save.disabled=true;try{const d=new FormData(form),kind=d.get('triggerKind'),triggers=[];let trigger={id:form.dataset.primaryId||undefined,kind,enabled:true,config:{}};if(kind==='schedule')trigger.config={cron:$('#cron-output').textContent.trim(),timezone:String(d.get('timezone'))};if(kind==='webhook'){const provider=d.get('provider'),base={provider};if(provider==='linear')trigger.config={...base,projectId:String(d.get('projectId')),matchRules:[{type:'status',targetId:String(d.get('statusId'))}]};else if(provider==='github')trigger.config={...base,installationId:Number(d.get('installationId')),repositoryId:Number(d.get('repositoryId')),event:String(d.get('event')),action:String(d.get('action'))};else trigger.config=base}if(kind!=='manual')triggers.push(trigger);const additional=JSON.parse(String(d.get('additionalTriggers')||'[]'));if(!Array.isArray(additional))throw new Error('Additional triggers must be a JSON array.');triggers.push(...additional);const body={name:String(d.get('name')),promptTemplate:String(d.get('promptTemplate')),concurrencyLimit:Number(d.get('concurrencyLimit')),executionTargetId:String(d.get('executionTargetId')),triggers};const result=await request('/api/jobs'+(jobId?'/'+encodeURIComponent(jobId):''),{method:jobId?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});location.href='/jobs/'+encodeURIComponent(result.id)}catch(e){err.textContent=e.message;err.classList.remove('hidden');save.disabled=false}};init().then(()=>{syncTrigger();syncCron();syncProvider()}).catch(e=>{const err=$('#error');err.textContent=e.message;err.classList.remove('hidden')});`); +async function init(){const targets=await request('/api/execution-targets');form.executionTargetId.innerHTML=''+targets.map(t=>'').join('');if(!jobId)return;const j=await request('/api/jobs/'+encodeURIComponent(jobId));form.name.value=j.name;form.promptTemplate.value=j.promptTemplate;form.concurrencyLimit.value=j.concurrencyLimit;form.executionTargetId.value=j.executionTargetId;const primary=(j.triggers||[]).find(t=>t.kind==='schedule'||t.kind==='webhook'),kind=primary?.kind||'manual';form.querySelector('[value="'+kind+'"]').checked=true;form.additionalTriggers.value=JSON.stringify((j.triggers||[]).filter(t=>t!==primary),null,2);const c=primary?.config||{};if(kind==='schedule'){form.timezone.value=c.timezone;form.cron.value=c.cron;const common=[...form.frequency.options].find(o=>o.value===c.cron);form.frequency.value=common?c.cron:'advanced'}if(kind==='webhook'){form.provider.value=c.provider;form.projectId.value=c.projectId||'';form.statusId.value=c.matchRules?.[0]?.targetId||'';form.installationId.value=c.installationId||'';form.repositoryId.value=c.repositoryId||'';form.event.value=c.event||'pull_request';form.action.value=c.action||'dequeued';form.handlerCode.value=c.handlerCode||''}form.dataset.primaryId=primary?.id||'';syncTrigger();syncCron();syncProvider()} +form.onsubmit=async e=>{e.preventDefault();const save=$('#save'),err=$('#error');err.classList.add('hidden');save.disabled=true;try{const d=new FormData(form),kind=d.get('triggerKind'),triggers=[];let trigger={id:form.dataset.primaryId||undefined,kind,enabled:true,config:{}};if(kind==='schedule')trigger.config={cron:$('#cron-output').textContent.trim(),timezone:String(d.get('timezone'))};if(kind==='webhook'){const provider=d.get('provider'),handlerCode=String(d.get('handlerCode')||''),base={provider,...(handlerCode?{handlerCode}:{})};if(provider==='linear')trigger.config={...base,projectId:String(d.get('projectId')),matchRules:[{type:'status',targetId:String(d.get('statusId'))}]};else if(provider==='github')trigger.config={...base,installationId:Number(d.get('installationId')),repositoryId:Number(d.get('repositoryId')),event:String(d.get('event')),action:String(d.get('action'))};else trigger.config=base}if(kind!=='manual')triggers.push(trigger);const additional=JSON.parse(String(d.get('additionalTriggers')||'[]'));if(!Array.isArray(additional))throw new Error('Additional triggers must be a JSON array.');triggers.push(...additional);const body={name:String(d.get('name')),promptTemplate:String(d.get('promptTemplate')),concurrencyLimit:Number(d.get('concurrencyLimit')),executionTargetId:String(d.get('executionTargetId')),triggers};const result=await request('/api/jobs'+(jobId?'/'+encodeURIComponent(jobId):''),{method:jobId?'PUT':'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});location.href='/jobs/'+encodeURIComponent(result.id)}catch(e){err.textContent=e.message;err.classList.remove('hidden');save.disabled=false}};init().then(()=>{syncTrigger();syncCron();syncProvider()}).catch(e=>{const err=$('#error');err.textContent=e.message;err.classList.remove('hidden')});`); export const jobDetailPage = (viewer: { email: string }, jobId: string) => shell("Job — Factorize", viewer, `
← Jobs

Loading job…

`, `${uiHelpers} const id=$('#job-detail').dataset.id,root=$('#job-detail'); diff --git a/packages/app/src/webhook-trigger.ts b/packages/app/src/webhook-trigger.ts index fc7ea8af..f33361ae 100644 --- a/packages/app/src/webhook-trigger.ts +++ b/packages/app/src/webhook-trigger.ts @@ -1,5 +1,6 @@ import { matchingIssue } from "./matcher"; import type { MatchRule } from "./types"; +import { validateHandlerCode } from "./custom-handler"; export type WebhookProvider = "linear" | "github" | "cloudflareTail" | "custom"; export type WebhookTriggerConfig = { @@ -38,3 +39,7 @@ export function publicWebhookConfig(config: WebhookTriggerConfig): Record { expect(first).not.toContain("tenant"); }); - it("pins an adapter that rejects thenables and non-booleans without exposing errors", () => { + it("pins an adapter that rejects thenables and invalid return types without exposing errors", () => { const module = userWorkerModule("function handler(webhook) { return true; }"); expect(module).toContain('typeof result.then === "function"'); - expect(module).toContain('typeof result !== "boolean"'); + expect(module).toContain('typeof result === "boolean"'); + expect(module).toContain("Array.isArray(result)"); expect(module).not.toContain("error.stack"); }); @@ -71,6 +72,12 @@ describe("custom handlers", () => { await expect(runAdapter("return 1;")).resolves.toEqual({ ok: false, category: "invalid_return" }); await expect(runAdapter("return Promise.resolve(true);")).resolves.toEqual({ ok: false, category: "invalid_return" }); await expect(runAdapter("return { then() {} };")).resolves.toEqual({ ok: false, category: "invalid_return" }); + await expect(runAdapter("return { issue: { id: 'i1' } };")).resolves.toEqual({ ok: true, decision: { issue: { id: "i1" } } }); + await expect(runAdapter("return [1, 2];")).resolves.toEqual({ ok: false, category: "invalid_return" }); + await expect(runAdapter("return null;")).resolves.toEqual({ ok: false, category: "invalid_return" }); + await expect(runAdapter("return { missing: undefined };")).resolves.toEqual({ ok: false, category: "invalid_return" }); + await expect(runAdapter("return { value: NaN };")).resolves.toEqual({ ok: false, category: "invalid_return" }); + await expect(runAdapter("return { value: 1n };")).resolves.toEqual({ ok: false, category: "invalid_return" }); await expect(runAdapter("throw new Error('secret');")).resolves.toEqual({ ok: false, category: "handler_error" }); }); }); diff --git a/packages/app/test/webhook-trigger.test.ts b/packages/app/test/webhook-trigger.test.ts index ff2001d2..112072bf 100644 --- a/packages/app/test/webhook-trigger.test.ts +++ b/packages/app/test/webhook-trigger.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { adaptWebhook, publicWebhookConfig } from "../src/webhook-trigger"; +import { adaptWebhook, publicWebhookConfig, validateWebhookHandler } from "../src/webhook-trigger"; describe("webhook Job trigger adapters", () => { it("matches Linear and derives a stable claim plus string invocation inputs", () => { @@ -15,6 +15,13 @@ describe("webhook Job trigger adapters", () => { }); it("never exposes webhook secrets", () => { - expect(publicWebhookConfig({ provider: "cloudflareTail", signingSecret: "super-secret-value" })).toEqual({ provider: "cloudflareTail", secretConfigured: true }); + expect(publicWebhookConfig({ provider: "cloudflareTail", signingSecret: "super-secret-value", handlerCode: "function handler(webhook) { return true; }" })).toEqual({ provider: "cloudflareTail", handlerCode: "function handler(webhook) { return true; }", secretConfigured: true }); + }); + + it("validates optional handlers for every provider", () => { + for (const provider of ["linear", "github", "cloudflareTail", "custom"] as const) { + expect(() => validateWebhookHandler({ provider, handlerCode: "function handler(webhook) { return { id: webhook.id }; }" })).not.toThrow(); + } + expect(() => validateWebhookHandler({ provider: "custom", handlerCode: "return true" })).toThrow("complete function handler(webhook)"); }); });