Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
fix(security): require authenticated workflow webhooks
Abdurrahman Fakhrul55920aaa2dba
diff --git a/app/api/v1/workflows/webhook/[...hook]/route.test.ts b/app/api/v1/workflows/webhook/[...hook]/route.test.tsnew file mode 100644index 00000000..5a23c91b--- /dev/null+++ b/app/api/v1/workflows/webhook/[...hook]/route.test.ts@@ -0,0 +1,30 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+const mocks=vi.hoisted(()=>({+ source:vi.fn(), secret:vi.fn(), untrusted:vi.fn(()=>false), privileged:vi.fn(()=>false),+ authority:vi.fn(), session:vi.fn(), start:vi.fn(), status:vi.fn(),+}));+vi.mock("@/lib/workflow/graph-triggers",()=>({findActiveWebhookSource:mocks.source}));+vi.mock("@/lib/workflow/variables",()=>({workflowWebhookSecret:mocks.secret}));+vi.mock("@/lib/host/limits-api",()=>({rateLimitedUntrusted:mocks.untrusted,rateLimited:mocks.privileged}));+vi.mock("@/lib/host/request-ip",()=>({clientIp:()=>"203.0.113.4"}));+vi.mock("@/lib/workflow/graph-authority",()=>({workflowExecutionContext:mocks.authority}));+vi.mock("@/lib/agent/session-store",()=>({createAgentSession:mocks.session}));+vi.mock("@/lib/workflow/graph-engine",()=>({startWorkflowGraph:mocks.start,workflowGraphRunStatus:mocks.status}));+vi.mock("@/lib/mcp/scope",()=>({maxScope:()=>"exec"}));+vi.mock("@/lib/mcp/capability-runtime",()=>({msoCapabilityRuntime:{}}));+vi.mock("@/lib/mcp/tools",()=>({TOOLS_BY_NAME:new Map()}));+const {POST}=await import("./route");+const webhookSecret="w".repeat(16);+const graph={id:"graph1",name:"Fixture"} as never;+const base={principal:"web:aaaaaaaaaaaaaaaa",owner:"owner",graph,node:{id:"hook1",type:"webhook",disabled:false,config:{methods:["POST"],authVariable:"WEBHOOK_TOKEN"}}};+const request=(token?:string,body="{}")=>new NextRequest("https://mso.example/api/v1/workflows/webhook/graph1/hook1",{method:"POST",headers:{"content-type":"application/json",...(token?{authorization:"Bearer "+token}:{})},body});+const ctx={params:Promise.resolve({hook:["graph1","hook1"]})};+beforeEach(()=>{vi.clearAllMocks();mocks.untrusted.mockReturnValue(false);mocks.privileged.mockReturnValue(false);mocks.source.mockResolvedValue(base);mocks.secret.mockResolvedValue(webhookSecret);mocks.authority.mockResolvedValue({principal:base.principal,actor:base.principal,scope:"exec"});mocks.session.mockResolvedValue({id:"20261007_120000_aaaaaaaa"});mocks.start.mockResolvedValue({id:"run1",state:"running"});});+describe("workflow webhook security boundary",()=>{+ it("requires an explicit secret variable",async()=>{mocks.source.mockResolvedValue({...base,node:{...base.node,config:{methods:["POST"]}}});expect((await POST(request(webhookSecret),ctx)).status).toBe(503);expect(mocks.start).not.toHaveBeenCalled();});+ it("authenticates before charging the privileged execution bucket",async()=>{const response=await POST(request("wrong"),ctx);expect(response.status).toBe(401);expect(mocks.privileged).not.toHaveBeenCalled();expect(mocks.start).not.toHaveBeenCalled();});+ it("rate-limits random lookup work before graph discovery",async()=>{mocks.untrusted.mockReturnValueOnce(true);expect((await POST(request(webhookSecret),ctx)).status).toBe(429);expect(mocks.source).not.toHaveBeenCalled();});+ it("bounds the body only after authentication",async()=>{const response=await POST(request(webhookSecret,"x".repeat(70*1024)),ctx);expect(response.status).toBe(413);expect(mocks.start).not.toHaveBeenCalled();});+ it("starts an authenticated owner workflow with live authority",async()=>{const response=await POST(request(webhookSecret),ctx);expect(response.status).toBe(202);expect(mocks.authority).toHaveBeenCalled();expect(mocks.privileged).toHaveBeenCalled();expect(mocks.start).toHaveBeenCalled();});+});diff --git a/app/api/v1/workflows/webhook/[...hook]/route.ts b/app/api/v1/workflows/webhook/[...hook]/route.tsindex 96111ca3..c554e4af 100644--- a/app/api/v1/workflows/webhook/[...hook]/route.ts+++ b/app/api/v1/workflows/webhook/[...hook]/route.ts@@ -1,15 +1,61 @@-import { timingSafeEqual } from "node:crypto";+import { randomUUID, timingSafeEqual } from "node:crypto";import { NextRequest, NextResponse } from "next/server";-import { rateLimited } from "@/lib/host/limits-api";import { createAgentSession } from "@/lib/agent/session-store";+import { rateLimited, rateLimitedUntrusted } from "@/lib/host/limits-api";+import { clientIp } from "@/lib/host/request-ip";import { maxScope } from "@/lib/mcp/scope";import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";-import { findActiveWebhookSource } from "@/lib/workflow/graph-triggers";+import { readRequestText, RequestBodyError } from "@/lib/security/request-body";+import { workflowExecutionContext } from "@/lib/workflow/graph-authority";import { startWorkflowGraph, workflowGraphRunStatus } from "@/lib/workflow/graph-engine";-import { workflowVariableValues } from "@/lib/workflow/variables";-export const runtime="nodejs";export const dynamic="force-dynamic";+import { findActiveWebhookSource } from "@/lib/workflow/graph-triggers";+import { workflowWebhookSecret } from "@/lib/workflow/variables";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";+const noStore = { "Cache-Control": "no-store" };+const reply = (error:string,status:number,extra?:HeadersInit) =>+ NextResponse.json({ error }, { status, headers: { ...noStore, ...extra } });function same(a:string,b:string){const x=Buffer.from(a),y=Buffer.from(b);return x.length===y.length&&timingSafeEqual(x,y);}-async function payload(req:NextRequest){const length=Number(req.headers.get("content-length")||0);if(length>64*1024)throw new Error("webhook body too large");let body:unknown=null;if(!["GET","HEAD"].includes(req.method)){const text=await req.text();if(Buffer.byteLength(text)>64*1024)throw new Error("webhook body too large");try{body=text?JSON.parse(text):null;}catch{body=text;}}return{method:req.method,query:Object.fromEntries(req.nextUrl.searchParams),httpHeaders:{"content-type":req.headers.get("content-type")||undefined,"user-agent":req.headers.get("user-agent")||undefined,"x-request-id":req.headers.get("x-request-id")||undefined},body};}-async function handle(req:NextRequest,ctx:{params:Promise<{hook:string[]}>}){try{const {hook}=await ctx.params;if(hook.length!==2)return NextResponse.json({error:"webhook_not_found"},{status:404});const source=await findActiveWebhookSource(hook[0]!,hook[1]!);if(!source)return NextResponse.json({error:"webhook_not_found"},{status:404});const methods=Array.isArray(source.node.config.methods)?source.node.config.methods.map(String):["POST"];if(!methods.includes(req.method))return NextResponse.json({error:"method_not_allowed"},{status:405,headers:{Allow:methods.join(", ")}});if(rateLimited(`workflow-webhook:${source.graph.id}:${source.node.id}`,120,60_000))return NextResponse.json({error:"rate_limited"},{status:429});const authVar=typeof source.node.config.authVariable==="string"?source.node.config.authVariable:"";if(authVar){const vars=await workflowVariableValues(source.principal),expected=vars[authVar];if(typeof expected!=="string")return NextResponse.json({error:"webhook_auth_not_configured"},{status:503});const raw=req.headers.get("authorization")?.replace(/^Bearer\s+/i,"")??req.headers.get("x-webhook-token")??"";if(!same(raw,expected))return NextResponse.json({error:"unauthorized"},{status:401});}- const input=await payload(req),session=await createAgentSession(source.principal,"cli",{title:`Webhook: ${source.graph.name}`,titleSource:"auto"}),{TOOLS_BY_NAME}=await import("@/lib/mcp/tools"),key=(req.headers.get("idempotency-key")||`webhook-${crypto.randomUUID()}`).slice(0,128),context={principal:source.principal,actor:source.principal,sessionId:session.id,scope:maxScope(),capabilities:msoCapabilityRuntime} as const;const started=await startWorkflowGraph(source.graph,input,key,context,(name)=>TOOLS_BY_NAME.get(name),source.principal,{type:"webhook",nodeId:source.node.id,receivedAt:new Date().toISOString()});if(source.node.config.responseMode!=="lastNode")return NextResponse.json({runId:started.id,state:started.state},{status:202});const done=await workflowGraphRunStatus(source.principal,started.id,25_000),output=[...done.nodes].reverse().find((node)=>node.type==="output"&&node.output!==undefined)?.output;return NextResponse.json({runId:done.id,state:done.state,output},{status:done.state==="failed"?500:200});}catch(error){return NextResponse.json({error:error instanceof Error?error.message.slice(0,300):"webhook_failed"},{status:400});}}+async function payload(req:NextRequest){+ let body:unknown=null;+ if(!["GET","HEAD"].includes(req.method)){+ const text=await readRequestText(req,64*1024);+ try{body=text?JSON.parse(text):null;}catch{body=text;}+ }+ return{method:req.method,query:Object.fromEntries(req.nextUrl.searchParams),httpHeaders:{"content-type":req.headers.get("content-type")||undefined,"user-agent":req.headers.get("user-agent")||undefined,"x-request-id":req.headers.get("x-request-id")||undefined},body};+}+async function handle(req:NextRequest,ctx:{params:Promise<{hook:string[]}>}){+ try{+ const {hook}=await ctx.params;+ if(hook.length!==2||hook.some((part)=>!/^[A-Za-z0-9_-]{1,96}$/.test(part)))return reply("webhook_not_found",404);+ if(rateLimitedUntrusted("workflow-webhook:ip:"+clientIp(req),30,60_000)||rateLimitedUntrusted("workflow-webhook:lookup",300,60_000))return reply("rate_limited",429,{"Retry-After":"60"});+ const source=await findActiveWebhookSource(hook[0]!,hook[1]!);+ if(!source)return reply("webhook_not_found",404);+ const methods=Array.isArray(source.node.config.methods)?source.node.config.methods.map(String):["POST"];+ if(!methods.includes(req.method))return reply("method_not_allowed",405,{Allow:methods.join(", ")});+ const authVar=typeof source.node.config.authVariable==="string"?source.node.config.authVariable:"";+ if(!authVar)return reply("webhook_auth_not_configured",503);+ const expected=await workflowWebhookSecret(source.principal,authVar);+ if(!expected)return reply("webhook_auth_not_configured",503);+ const raw=req.headers.get("authorization")?.replace(/^Bearer\s+/i,"")??req.headers.get("x-webhook-token")??"";+ if(!same(raw,expected))return reply("unauthorized",401);+ if(rateLimited("workflow-webhook:"+source.graph.id+":"+source.node.id,120,60_000))return reply("rate_limited",429,{"Retry-After":"60"});+ const trigger={type:"webhook" as const,nodeId:source.node.id,receivedAt:new Date().toISOString()};+ const authority=await workflowExecutionContext({principal:source.principal,actor:source.principal,scope:maxScope()},trigger);+ const input=await payload(req);+ const session=await createAgentSession(source.principal,"cli",{title:"Webhook: "+source.graph.name,titleSource:"auto"});+ const {TOOLS_BY_NAME}=await import("@/lib/mcp/tools");+ const key=(req.headers.get("idempotency-key")||"webhook-"+randomUUID()).slice(0,128);+ const context={...authority,sessionId:session.id,capabilities:msoCapabilityRuntime};+ const started=await startWorkflowGraph(source.graph,input,key,context,(name)=>TOOLS_BY_NAME.get(name),source.principal,trigger);+ if(source.node.config.responseMode!=="lastNode")return NextResponse.json({runId:started.id,state:started.state},{status:202,headers:noStore});+ const done=await workflowGraphRunStatus(source.principal,started.id,25_000);+ const output=[...done.nodes].reverse().find((node)=>node.type==="output"&&node.output!==undefined)?.output;+ return NextResponse.json({runId:done.id,state:done.state,output},{status:done.state==="failed"?500:200,headers:noStore});+ }catch(error){+ if(error instanceof RequestBodyError)return reply(error.message,error.status);+ return reply("webhook_failed",400);+ }+}export const GET=handle;export const POST=handle;export const PUT=handle;export const PATCH=handle;export const DELETE=handle;diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.mdindex c089c217..2dfa8f52 100644--- a/docs/WORKFLOW-GRAPH.md+++ b/docs/WORKFLOW-GRAPH.md@@ -20,7 +20,7 @@ Graphs, versions, variables and execution receipts are private per authenticated- `manual` — UI/CLI/MCP run- `schedule` — interval or five-field cron, with IANA timezone support-- `webhook` — GET/POST/PUT/PATCH/DELETE server endpoint; optional bearer token from a private secret variable+- `webhook` — GET/POST/PUT/PATCH/DELETE server endpoint; requires a bearer token from a private secret variableTrigger nodes must be roots. Activating a workflow enables its server-side schedule/webhook behavior; drafts remain inert. Stored graphs are data rather than durable privilege grants: execution rechecks the live device role and deployment scope, and unattended stored non-web principals fail closed instead of acquiring fresh exec authority.@@ -30,7 +30,7 @@ Webhook endpoint:/api/v1/workflows/webhook/<graphId>/<nodeId>```-`responseMode=onReceived` returns a run id immediately. `responseMode=lastNode` waits for bounded execution and returns only the explicit output-node result.+`responseMode=onReceived` returns a run id immediately. `responseMode=lastNode` waits for bounded execution and returns only the explicit output-node result. Active webhooks fail closed unless `authVariable` names a secret-marked string of at least 16 characters; unauthenticated lookup traffic is rate-limited before graph discovery and cannot consume the authenticated execution bucket.### Flow controldiff --git a/lib/workflow/variables.test.ts b/lib/workflow/variables.test.tsindex 33490d32..1ea823e4 100644--- a/lib/workflow/variables.test.ts+++ b/lib/workflow/variables.test.ts@@ -7,5 +7,6 @@ const vars=await import("./variables");afterAll(()=>rm(dir,{recursive:true,force:true}));beforeEach(()=>rm(path.join(dir,".workflow-variables"),{recursive:true,force:true}));describe("workflow variables",()=>{it("keeps values isolated by principal and hides secret values from listings",async()=>{await vars.setWorkflowVariable("alice","PUBLIC_VALUE",{ok:true});await vars.setWorkflowVariable("alice","API_TOKEN","top-secret-value",true);expect(await vars.listWorkflowVariables("alice")).toEqual(expect.arrayContaining([expect.objectContaining({key:"PUBLIC_VALUE",value:{ok:true},secret:false}),expect.not.objectContaining({key:"API_TOKEN",value:"top-secret-value"})]));expect(await vars.workflowVariableValues("bob")).toEqual({});expect(await vars.workflowVariableValues("alice")).toMatchObject({API_TOKEN:"top-secret-value"});});+ it("requires a long secret-marked string for webhook authentication",async()=>{await vars.setWorkflowVariable("alice","PUBLIC_TOKEN","public-value-that-is-long",false);await vars.setWorkflowVariable("alice","SHORT_SECRET","tiny",true);await vars.setWorkflowVariable("alice","WEBHOOK_TOKEN","w".repeat(16),true);expect(await vars.workflowWebhookSecret("alice","PUBLIC_TOKEN")).toBeNull();expect(await vars.workflowWebhookSecret("alice","SHORT_SECRET")).toBeNull();expect(await vars.workflowWebhookSecret("alice","WEBHOOK_TOKEN")).toBe("w".repeat(16));});it("rejects unsafe keys and oversized values",async()=>{await expect(vars.setWorkflowVariable("alice","bad-key","x")).rejects.toThrow("key");await expect(vars.setWorkflowVariable("alice","BIG","x".repeat(20_000))).rejects.toThrow("invalid");});});diff --git a/lib/workflow/variables.ts b/lib/workflow/variables.tsindex 27de864c..386fcbb8 100644--- a/lib/workflow/variables.ts+++ b/lib/workflow/variables.ts@@ -28,3 +28,4 @@ export async function setWorkflowVariable(principal:string,key:string,value:unknexport async function deleteWorkflowVariable(principal:string,key:string){ const owner=workflowGraphOwner(principal); return withSecurityStoreLock(file(owner),async()=>{const store=await read(owner); delete store.values[key]; await write(store); return {key,deleted:true};}); }export async function workflowVariableValues(principal:string){ const owner=workflowGraphOwner(principal),store=await read(owner); return Object.fromEntries(Object.entries(store.values).map(([key,row])=>[key,structuredClone(row.value)])); }export async function workflowSecretValues(principal:string){ const owner=workflowGraphOwner(principal),store=await read(owner); return Object.values(store.values).filter((row)=>row.secret).map((row)=>structuredClone(row.value)); }+export async function workflowWebhookSecret(principal:string,key:string){ const owner=workflowGraphOwner(principal),store=await read(owner),row=store.values[key]; if(!row?.secret||typeof row.value!=="string"||row.value.length<16) return null; return row.value; }