Skip to content

armgit / mso

Public Imported from GitHub
0

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.

fix(security): enforce live workflow authority

Abdurrahman Fakhrul6eb9cab2cd6c
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index b430dd23..c089c217 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -9,7 +9,7 @@ It is additive: existing deterministic project flows, RASMIC scripts and learned
- **Workflow Graph** owns automation topology, triggers, flow control, node configuration, execution history and graph versions.
- **Project registry** resolves canonical projects and real server paths at runtime. Portable graph definitions store ids/hints, never installation-specific absolute paths.
- **Integrations** own credentials and provider connections. Graphs store connection references only.
-- **Private workflow variables** provide runtime values through `{"$var":"KEY"}`. Secret variables are never returned by list APIs and exact secret values are redacted from execution receipts.
+- **Private workflow variables** provide runtime values through `{"$var":"KEY"}`. Secret variables are never returned by list APIs; short strings, scalar values and structured secret leaves are redacted from execution receipts.
- **Git** remains code SSOT; project knowledge/memory remain their existing SSOTs.
Graphs, versions, variables and execution receipts are private per authenticated principal. Source and builtin templates contain no operator-specific user, credential, path or seeded workflow.
@@ -22,7 +22,7 @@ Graphs, versions, variables and execution receipts are private per authenticated
- `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
-Trigger nodes must be roots. Activating a workflow enables its server-side schedule/webhook behavior; drafts remain inert.
+Trigger 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.
Webhook endpoint:
diff --git a/lib/capabilities/scope-policy.ts b/lib/capabilities/scope-policy.ts
new file mode 100644
index 00000000..d1742e04
--- /dev/null
+++ b/lib/capabilities/scope-policy.ts
@@ -0,0 +1,9 @@
+import { SCOPES, type Scope } from "./scope";
+
+/** Deployment ceiling shared by transports and unattended workflow execution. */
+export function configuredCapabilityCeiling(): Scope {
+ const raw = process.env.OS_MCP_MAX_SCOPE;
+ if (!raw) return "exec";
+ const scope = raw.trim();
+ return (SCOPES as readonly string[]).includes(scope) ? scope as Scope : "write";
+}
diff --git a/lib/mcp/scope.ts b/lib/mcp/scope.ts
index 135b018b..b9aabb25 100644
--- a/lib/mcp/scope.ts
+++ b/lib/mcp/scope.ts
@@ -1,6 +1,7 @@
+import { configuredCapabilityCeiling } from "@/lib/capabilities/scope-policy";
// MCP-specific policy layered on the transport-neutral capability scope.
export { SCOPES, allows, parseScope, type Scope } from "@/lib/capabilities/scope";
-import { SCOPES, scopeRank, type Scope } from "@/lib/capabilities/scope";
+import { scopeRank, type Scope } from "@/lib/capabilities/scope";
/** OAuth scope strings are cumulative so a standards-compliant host can see that an exec token also satisfies read/write tool schemes. */
export function oauthScopeString(scope: Scope, offline = false): string {
@@ -15,10 +16,7 @@ export function mcpEnabled(): boolean {
}
export function maxScope(): Scope {
- const raw = process.env.OS_MCP_MAX_SCOPE;
- if (!raw) return "exec";
- const s = String(raw).trim();
- return (SCOPES as readonly string[]).includes(s) ? (s as Scope) : "write";
+ return configuredCapabilityCeiling();
}
export function clampScope(asked: Scope): Scope {
diff --git a/lib/workflow/graph-authority.test.ts b/lib/workflow/graph-authority.test.ts
new file mode 100644
index 00000000..ff834fd7
--- /dev/null
+++ b/lib/workflow/graph-authority.test.ts
@@ -0,0 +1,34 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({ device: vi.fn() }));
+vi.mock("@/lib/auth/device-store", () => ({ getApprovedDevice: mocks.device }));
+import { requireWorkflowScope, workflowExecutionContext } from "./graph-authority";
+const context = {principal: "web:aaaaaaaaaaaaaaaa", sessionId: "s", scope: "exec" as const};
+beforeEach(() => { vi.stubEnv("OS_MCP_MAX_SCOPE", "exec"); mocks.device.mockReset(); });
+afterEach(() => vi.unstubAllEnvs());
+describe("live workflow execution authority", () => {
+ it.each([undefined, "schedule", "webhook", "channel"] as const)("caps Operator authority for %s", async type => {
+ mocks.device.mockResolvedValue({role: "operator"});
+ const effective = await workflowExecutionContext(context, type ? {type, receivedAt: new Date().toISOString()} : undefined);
+ expect(effective.scope).toBe("write");
+ expect(() => requireWorkflowScope(effective, "exec")).toThrow();
+ });
+ it("rechecks demotion and revocation without cached grants", async () => {
+ mocks.device.mockResolvedValueOnce({role: "owner"}).mockResolvedValueOnce({role: "operator"}).mockResolvedValueOnce(null);
+ expect((await workflowExecutionContext(context)).scope).toBe("exec");
+ expect((await workflowExecutionContext(context)).scope).toBe("write");
+ await expect(workflowExecutionContext(context)).rejects.toThrow(/revoked/);
+ });
+ it("does not revive Viewer execution", async () => {
+ mocks.device.mockResolvedValue({role: "viewer"});
+ await expect(workflowExecutionContext(context)).rejects.toThrow(/operator/);
+ });
+ it("preserves caller and deployment ceilings", async () => {
+ mocks.device.mockResolvedValue({role: "owner"});
+ expect((await workflowExecutionContext({...context, scope: "read"})).scope).toBe("read");
+ vi.stubEnv("OS_MCP_MAX_SCOPE", "write");
+ expect((await workflowExecutionContext(context)).scope).toBe("write");
+ });
+ it("never synthesizes unattended authority from an MCP client name", async () => {
+ await expect(workflowExecutionContext({...context, principal: "mcp:client"}, {type: "schedule", receivedAt: "now"})).rejects.toThrow(/not execution grants/);
+ });
+});
diff --git a/lib/workflow/graph-authority.ts b/lib/workflow/graph-authority.ts
new file mode 100644
index 00000000..5144cb4f
--- /dev/null
+++ b/lib/workflow/graph-authority.ts
@@ -0,0 +1,30 @@
+import { getApprovedDevice } from "@/lib/auth/device-store";
+import { allows, scopeRank, type Scope } from "@/lib/capabilities/scope";
+import type { CapabilityRunContext } from "@/lib/capabilities/tool";
+import { configuredCapabilityCeiling } from "@/lib/capabilities/scope-policy";
+import type { WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
+
+/** Stored graphs are data, not grants. Recheck device authority for every action. */
+export async function workflowExecutionContext(
+ context: CapabilityRunContext,
+ trigger?: WorkflowGraphRun["trigger"],
+): Promise<CapabilityRunContext> {
+ const principal = context.principal ?? context.actor;
+ if (!principal) throw new Error("workflow requires an authenticated principal");
+ const unattended = trigger && ["schedule", "webhook", "channel"].includes(trigger.type);
+ if (unattended && !principal.startsWith("web:")) {
+ throw new Error("unattended workflow requires a live approved device; stored client names are not execution grants");
+ }
+ let ceiling = configuredCapabilityCeiling();
+ if (principal.startsWith("web:")) {
+ const device = await getApprovedDevice(principal.slice(4));
+ if (!device || device.role === "viewer") throw new Error("workflow device is revoked or lacks operator authority");
+ const roleScope: Scope = device.role === "owner" ? "exec" : "write";
+ if (scopeRank(roleScope) < scopeRank(ceiling)) ceiling = roleScope;
+ }
+ return { ...context, scope: scopeRank(context.scope) < scopeRank(ceiling) ? context.scope : ceiling };
+}
+
+export function requireWorkflowScope(context: CapabilityRunContext, required: Scope): void {
+ if (!allows(context.scope, required)) throw new Error(`workflow requires ${required} authority`);
+}
diff --git a/lib/workflow/graph-engine.test.ts b/lib/workflow/graph-engine.test.ts
index 4909fc1b..c0456038 100644
--- a/lib/workflow/graph-engine.test.ts
+++ b/lib/workflow/graph-engine.test.ts
@@ -4,6 +4,7 @@ import os from "node:os";
import path from "node:path";
import type { CapabilityTool } from "@/lib/capabilities/tool";
+vi.mock("@/lib/auth/device-store", () => ({ getApprovedDevice: async () => ({ role: "owner" }) }));
vi.mock("@/lib/capabilities/execute", () => ({ executeCapabilityCall: async ({ tool, args, context }: { tool: CapabilityTool; args: Record<string, unknown>; context: never }) => {
try { return { kind: "success", result: await tool.run(args, context) }; } catch (error) { return { kind: "error", message: error instanceof Error ? error.message : String(error) }; }
} }));
@@ -178,12 +179,12 @@ describe("workflow graph engine", () => {
});
it("accepts secret-shaped runtime input but redacts it from persisted trigger receipts", async () => {
- const graph = await createWorkflowGraph("graph-owner", { name: "Runtime input", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
+ const graph = await createWorkflowGraph("web:aaaaaaaaaaaaaaaa", { name: "Runtime input", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [
{ id: "start-runtime", name: "Webhook", type: "webhook", position: { x: 0, y: 0 }, config: {} },
{ id: "runtime-out", name: "Out", type: "output", position: { x: 100, y: 0 }, config: { value: { ok: true } } },
], edges: [{ id: "runtime-e", source: "start-runtime", target: "runtime-out" }] });
- const started = await startWorkflowGraph(graph, { headers: { authorization: "Bearer abc" }, body: { token: "incoming-token", safe: "visible" } }, "runtime-secret-input", context, () => undefined, "graph-owner", { type: "webhook", nodeId: "start-runtime", receivedAt: new Date().toISOString() });
- const done = await workflowGraphRunStatus("graph-owner", started.id, 5000), receipt = JSON.stringify(done);
+ const started = await startWorkflowGraph(graph, { headers: { authorization: "Bearer abc" }, body: { token: "incoming-token", safe: "visible" } }, "runtime-secret-input", {...context, principal: "web:aaaaaaaaaaaaaaaa", actor: "web:aaaaaaaaaaaaaaaa"}, () => undefined, "web:aaaaaaaaaaaaaaaa", { type: "webhook", nodeId: "start-runtime", receivedAt: new Date().toISOString() });
+ const done = await workflowGraphRunStatus("web:aaaaaaaaaaaaaaaa", started.id, 5000), receipt = JSON.stringify(done);
expect(done.state).toBe("completed");
expect(receipt).not.toContain("Bearer abc"); expect(receipt).not.toContain("incoming-token"); expect(receipt).toContain("[REDACTED]"); expect(receipt).toContain("visible");
});
diff --git a/lib/workflow/graph-engine.ts b/lib/workflow/graph-engine.ts
index 7fe10632..69b5aae0 100644
--- a/lib/workflow/graph-engine.ts
+++ b/lib/workflow/graph-engine.ts
@@ -1,3 +1,5 @@
+import { workflowExecutionContext } from "./graph-authority";
+import { receiptRedactor } from "./receipt-redaction";
import { createHash, randomUUID } from "node:crypto";
import type { CapabilityRunContext, CapabilityTool } from "@/lib/capabilities/tool";
import type { WorkflowGraph, WorkflowGraphRun, WorkflowGraphRunEdgeState } from "@/lib/contracts/workflow-graph";
@@ -29,12 +31,9 @@ function assertRuntimeInput(value: unknown, depth = 0): void {
function inputObject(raw: unknown): Record<string, unknown> { if (!graphObject(raw) || Buffer.byteLength(JSON.stringify(raw)) > 64 * 1024) throw new Error("workflow graph input must be an object up to 64 KiB"); assertRuntimeInput(raw); return structuredClone(raw); }
function retryPolicy(node: WorkflowGraph["nodes"][number]) { const raw = graphObject(node.config.retry) ? node.config.retry : {}; return { maxAttempts: Math.max(1, Math.min(5, Math.trunc(Number(raw.maxAttempts) || 1))), backoffMs: Math.max(0, Math.min(30_000, Math.trunc(Number(raw.backoffMs) || 0))) }; }
function sleep(ms:number){return ms?new Promise((resolve)=>setTimeout(resolve,ms)):Promise.resolve();}
-function secretText(text:string,secrets:string[]){let out=text;for(const value of secrets)out=out.split(value).join("[REDACTED]");return out;}
-const RECEIPT_SECRET_KEY = /^(secrets?|secretValue|password|passphrase|token|apiKey|apiToken|accessToken|refreshToken|authorization|headers|cookie|cookies)$/i;
-function secretValue(value:unknown,secrets:string[],depth=0):unknown{if(depth>14)return "[TRUNCATED]";if(typeof value==="string")return secretText(value,secrets);if(Array.isArray(value))return value.map((item)=>secretValue(item,secrets,depth+1));if(value&&typeof value==="object")return Object.fromEntries(Object.entries(value).map(([key,child])=>[key,RECEIPT_SECRET_KEY.test(key)?"[REDACTED]":secretValue(child,secrets,depth+1)]));return value;}
async function execute(run: WorkflowGraphRun, graph: WorkflowGraph, input: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<void> {
- const rows = new Map(run.nodes.map((row) => [row.id, row])), outputs: Record<string, unknown> = {}, secrets = await workflowSecretValues(context.principal ?? context.actor ?? "");
+ const rows = new Map(run.nodes.map((row) => [row.id, row])), outputs: Record<string, unknown> = {}, redactor = receiptRedactor(await workflowSecretValues(context.principal ?? context.actor ?? ""));
const activeEdges = graph.edges.filter((edge) => !edge.disabled);
const edgeState = new Map(graph.edges.map((edge) => [edge.id, edge.disabled ? "disabled" as WorkflowGraphRunEdgeState : run.edges?.find((row) => row.id === edge.id)?.state ?? "pending" as WorkflowGraphRunEdgeState]));
// Keep disabled incoming edges as disabled dependencies so a node whose only route is inactive is skipped, not promoted to a new root. Outgoing resolution touches active edges only.
@@ -55,24 +54,25 @@ async function execute(run: WorkflowGraphRun, graph: WorkflowGraph, input: Recor
if(!remaining.has(node.id))continue; const deps=incoming.get(node.id)??[]; if(deps.some((edge)=>edgeState.get(edge.id)==="pending"))continue; const row=rows.get(node.id)!;
const triggerNode=["manual","schedule","webhook","channel_trigger"].includes(node.type),triggerMismatch=Boolean(triggerNode&&run.trigger?.nodeId&&run.trigger.nodeId!==node.id);if(node.disabled||triggerMismatch||(deps.length>0&&deps.every((edge)=>edgeState.get(edge.id)==="disabled"))){row.state="skipped";row.finishedAt=new Date().toISOString();row.logs.push(node.disabled?"Node disabled by workflow definition.":triggerMismatch?"Skipped because another trigger started this run.":"Skipped because no incoming branch was selected.");disableOutgoing(node.id);remaining.delete(node.id);progressed=true;run.updatedAt=new Date().toISOString();await writeWorkflowGraphRun(run);continue;}
row.state="running";row.startedAt=new Date().toISOString();row.logs.push("Node started.");run.updatedAt=row.startedAt;await writeWorkflowGraphRun(run);await sessionEvent("running",`${node.name} · ${node.type}`); const started=Date.now(),policy=retryPolicy(node); let failure:unknown;
- for(let attempt=1;attempt<=policy.maxAttempts;attempt+=1){row.attempts=attempt;try{const result=await executeNode(node,run,graph,input,outputs,context,resolve);row.output=compact(secretValue(result.output,secrets));outputs[node.id]=result.output;row.state="completed";if(result.log)row.logs.push(result.log);resolveOutgoing(node.id,result.handles);failure=undefined;break;}catch(error){failure=error;row.logs.push(`Attempt ${attempt}/${policy.maxAttempts} failed: ${secretText(redactText(error instanceof Error?error.message:"node failed",500),secrets)}`);if(attempt<policy.maxAttempts)await sleep(Math.min(30_000,policy.backoffMs*Math.max(1,2**(attempt-1))));}}
- if(failure){row.state="failed";row.error=secretText(redactText(failure instanceof Error?failure.message:"node failed",800),secrets);outputs[node.id]={error:row.error};const errorEdges=(outgoing.get(node.id)??[]).filter((edge)=>edge.sourceHandle==="error"),continueOnError=node.config.onError==="continue";if(errorEdges.length||continueOnError){handledErrors=true;resolveOutgoing(node.id,errorEdges.length?["error"]:undefined);row.logs.push(errorEdges.length?"Failure routed through error output.":"Failure continued by node policy.");}else{run.failedNodeId=node.id;run.failedNodeName=node.name;run.error=row.error;run.state="failed";for(const pendingId of remaining){if(pendingId===node.id)continue;const blocked=rows.get(pendingId)!;if(blocked.state==="queued"){blocked.state="blocked";blocked.logs.push(`Blocked by failed node ${node.name}.`);}}row.durationMs=Date.now()-started;row.finishedAt=new Date().toISOString();run.updatedAt=row.finishedAt;await writeWorkflowGraphRun(run);throw failure;}}
+ for(let attempt=1;attempt<=policy.maxAttempts;attempt+=1){row.attempts=attempt;try{const result=await executeNode(node,run,graph,input,outputs,context,resolve);row.output=compact(redactor.value(result.output));outputs[node.id]=result.output;row.state="completed";if(result.log)row.logs.push(result.log);resolveOutgoing(node.id,result.handles);failure=undefined;break;}catch(error){failure=error;row.logs.push(`Attempt ${attempt}/${policy.maxAttempts} failed: ${redactor.text(redactText(error instanceof Error?error.message:"node failed",500))}`);if(attempt<policy.maxAttempts)await sleep(Math.min(30_000,policy.backoffMs*Math.max(1,2**(attempt-1))));}}
+ if(failure){row.state="failed";row.error=redactor.text(redactText(failure instanceof Error?failure.message:"node failed",800));outputs[node.id]={error:row.error};const errorEdges=(outgoing.get(node.id)??[]).filter((edge)=>edge.sourceHandle==="error"),continueOnError=node.config.onError==="continue";if(errorEdges.length||continueOnError){handledErrors=true;resolveOutgoing(node.id,errorEdges.length?["error"]:undefined);row.logs.push(errorEdges.length?"Failure routed through error output.":"Failure continued by node policy.");}else{run.failedNodeId=node.id;run.failedNodeName=node.name;run.error=row.error;run.state="failed";for(const pendingId of remaining){if(pendingId===node.id)continue;const blocked=rows.get(pendingId)!;if(blocked.state==="queued"){blocked.state="blocked";blocked.logs.push(`Blocked by failed node ${node.name}.`);}}row.durationMs=Date.now()-started;row.finishedAt=new Date().toISOString();run.updatedAt=row.finishedAt;await writeWorkflowGraphRun(run);throw failure;}}
row.durationMs=Date.now()-started;row.finishedAt=new Date().toISOString();run.updatedAt=row.finishedAt;await writeWorkflowGraphRun(run);await sessionEvent(row.state,node.name);remaining.delete(node.id);progressed=true;
}
if(!progressed&&remaining.size)throw new Error("workflow graph could not make progress; inspect dependencies/branches");
}
run.state=handledErrors?"completed_with_errors":"completed";
- } catch(error){if(run.state!=="failed"&&run.state!=="interrupted"){run.state="failed";run.error=secretText(redactText(error instanceof Error?error.message:"workflow graph failed",800),secrets);}}
+ } catch(error){if(run.state!=="failed"&&run.state!=="interrupted"){run.state="failed";run.error=redactor.text(redactText(error instanceof Error?error.message:"workflow graph failed",800));}}
run.finishedAt=run.updatedAt=new Date().toISOString();await writeWorkflowGraphRun(run);await sessionEvent(run.state,graph.name);
}
async function maybeRunErrorWorkflow(run:WorkflowGraphRun,graph:WorkflowGraph,context:CapabilityRunContext,resolve:Resolver,principal:string){
const errorId=graph.metadata.errorWorkflowId;if(run.state!=="failed"||!errorId||errorId===graph.id)return;
const {getWorkflowGraph}=await import("./graph-store"),errorGraph=await getWorkflowGraph(principal,errorId);if(!errorGraph||errorGraph.status==="archived")return;
- await startWorkflowGraph(errorGraph,{error:{runId:run.id,graphId:graph.id,graphName:graph.name,nodeId:run.failedNodeId,nodeName:run.failedNodeName,message:run.error}},`error:${run.id}`,context,resolve,principal,{type:"system",receivedAt:new Date().toISOString()});
+ await startWorkflowGraph(errorGraph,{error:{runId:run.id,graphId:graph.id,graphName:graph.name,nodeId:run.failedNodeId,nodeName:run.failedNodeName,message:run.error}},`error:${run.id}`,context,resolve,principal,{type:"system",receivedAt:new Date().toISOString()},run.ancestry??[graph.id]);
}
export function workflowGraphRunId(owner:string,key:string){return hash(`${owner}:${key}`).slice(0,32);}
export async function startWorkflowGraph(graph: WorkflowGraph, rawInput: unknown, idempotencyKey: string, context: CapabilityRunContext, resolve: Resolver, storagePrincipal?: string, trigger?: WorkflowRunTrigger, ancestry: string[] = []) {
+ context = await workflowExecutionContext(context, trigger);
const principal=storagePrincipal??context.principal;if(!principal||!context.sessionId)throw new Error("workflow graph requires an authenticated principal/session");if(ancestry.includes(graph.id)||ancestry.length>=16)throw new Error("recursive workflow subflow detected");if(graph.status==="archived")throw new Error("archived workflow graph cannot run");if(!/^[A-Za-z0-9_.:-]{1,128}$/.test(idempotencyKey))throw new Error("idempotency_key must be 1-128 simple characters");
const owner=workflowGraphOwner(principal),input=inputObject(rawInput),fingerprint=hash(canonical({graphId:graph.id,revision:graph.revision,input})),id=workflowGraphRunId(owner,idempotencyKey);
return lockWorkflowGraphRun(owner,id,async()=>{const existing=await readWorkflowGraphRun(owner,id);if(existing){if(existing.fingerprint!==fingerprint)throw new Error("idempotency_key already identifies a different graph/input/revision");return publicWorkflowGraphRun(existing);}await pruneWorkflowGraphRuns(owner);const run:WorkflowGraphRun={version:1,id,owner,sessionId:context.sessionId!,graphId:graph.id,graphRevision:graph.revision,graphName:graph.name,idempotencyKey,fingerprint,state:"running",startedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),pid:process.pid,instance:INSTANCE,nodes:graph.nodes.map((node)=>({id:node.id,name:node.name,type:node.type,state:"queued",logs:[]})),edges:graph.edges.map((edge)=>({id:edge.id,source:edge.source,target:edge.target,...(edge.sourceHandle?{sourceHandle:edge.sourceHandle}:{}),state:edge.disabled?"disabled":"pending"})),trigger:trigger??{type:"manual",nodeId:graph.nodes.find((node)=>node.type==="manual")?.id??graph.nodes.find((node)=>["schedule","webhook","channel_trigger"].includes(node.type))?.id,receivedAt:new Date().toISOString()},ancestry:[...ancestry,graph.id],runtimeInput:structuredClone(input)};await writeWorkflowGraphRun(run);await appendAgentSessionEvent(principal,run.sessionId,{kind:"workflow",tool:"workflow_graph",state:"started",workflowId:graph.id,detail:graph.name}).catch(()=>undefined);const work=execute(run,graph,input,context,resolve).then(()=>maybeRunErrorWorkflow(run,graph,context,resolve,principal)).catch(()=>undefined).finally(()=>{pending.delete(id);cancelled.delete(id);});pending.set(id,work);return publicWorkflowGraphRun(run);});
diff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.ts
index ed081e1f..2748de87 100644
--- a/lib/workflow/graph-runtime.ts
+++ b/lib/workflow/graph-runtime.ts
@@ -1,3 +1,4 @@
+import { requireWorkflowScope, workflowExecutionContext } from "./graph-authority";
import path from "node:path";
import { promises as fs } from "node:fs";
import { capabilityReportedFailure } from "@/lib/capabilities/result-outcome";
@@ -32,6 +33,7 @@ function resultData(result: unknown): unknown {
try { return JSON.parse(text); } catch { return { text }; }
}
async function callTool(name: string, args: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<unknown> {
+ context = await workflowExecutionContext(context);
const tool = resolve(name); if (!tool) throw new Error(`workflow tool unavailable: ${name}`);
const outcome = await executeCapabilityCall({ tool, args, scope: context.scope, actor: context.actor, context });
if (outcome.kind !== "success") throw new Error(outcome.message); return resultData(outcome.result);
@@ -58,6 +60,10 @@ async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graph
const runtime = { input: graphInput, trigger: run.trigger, nodes: Object.fromEntries(Object.entries(outputs).map(([id, output]) => [id, { output }])), graph: { id: graph.id, name: graph.name, metadata: graph.metadata } };
const principal = context.principal ?? context.actor; if (!principal) throw new Error("workflow node requires principal");
const config = bindWorkflowValue(node.config, runtime, await workflowVariableValues(principal)) as Record<string, unknown>;
+ context = await workflowExecutionContext(context);
+ if (node.type === "channel_send") requireWorkflowScope(context, "exec");
+ if (node.type === "data_table" && ["insert", "update", "delete"].includes(String(config.mode))) requireWorkflowScope(context, "write");
+ if (node.type === "cache" && ["set", "get_or_set", "delete"].includes(String(config.mode))) requireWorkflowScope(context, "write");
const project = typeof config.project === "string" ? config.project : graph.metadata.project;
if (["manual", "schedule", "webhook", "channel_trigger"].includes(node.type)) return { output: graphInput, log: `${node.type} trigger accepted.` };
if (node.type === "project") return { output: await resolvedProject(config.project ?? project), log: "Canonical project resolved at runtime." };
diff --git a/lib/workflow/receipt-redaction.test.ts b/lib/workflow/receipt-redaction.test.ts
new file mode 100644
index 00000000..f71c4e73
--- /dev/null
+++ b/lib/workflow/receipt-redaction.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { receiptRedactor } from "./receipt-redaction";
+describe("typed workflow receipt secrets", () => {
+ it.each(["ab", 928731, true, null, {nested: ["tiny", 273891]}])("redacts secret values under arbitrary keys: %j", secret => {
+ const redactor = receiptRedactor([secret]);
+ const rendered = JSON.stringify(redactor.value({result: secret}));
+ expect(rendered).toContain("[REDACTED]");
+ if (typeof secret === "string" || typeof secret === "number") expect(rendered).not.toContain(String(secret));
+ });
+ it("redacts structured secret leaves and stringified numbers from error text", () => {
+ const redact = receiptRedactor([{nested: {value: "tiny"}, n: 928731}]);
+ expect(redact.text("failed tiny / 928731")).toBe("failed [REDACTED] / [REDACTED]");
+ expect(redact.value({safe: "public", data: {leaf: "tiny", count: 928731}})).toEqual({safe:"public", data:{leaf:"[REDACTED]", count:"[REDACTED]"}});
+ });
+ it("escapes regex syntax and never re-redacts its own marker", () => {
+ expect(receiptRedactor([".*", "a", "RED"]).text(".* a RED")).toBe("[REDACTED] [REDACTED] [REDACTED]");
+ });
+});
diff --git a/lib/workflow/receipt-redaction.ts b/lib/workflow/receipt-redaction.ts
new file mode 100644
index 00000000..29d1cc3e
--- /dev/null
+++ b/lib/workflow/receipt-redaction.ts
@@ -0,0 +1,31 @@
+const SECRET_KEY = /^(secrets?|secretValue|password|passphrase|token|apiKey|apiToken|accessToken|refreshToken|authorization|headers|cookie|cookies)$/i;
+
+/** Include short strings and structured/scalar secrets; receipt keys are not a trust boundary. */
+export function receiptRedactor(values: unknown[]) {
+ const scalars = new Set<unknown>();
+ const textValues = new Set<string>();
+ function collect(value: unknown, depth = 0): void {
+ if (depth > 32) return;
+ if (value && typeof value === "object") {
+ textValues.add(JSON.stringify(value));
+ for (const child of Object.values(value)) collect(child, depth + 1);
+ } else {
+ scalars.add(value);
+ if (typeof value === "string" ? value.length > 0 : value !== undefined) textValues.add(String(value));
+ }
+ }
+ values.forEach(value => collect(value));
+ const literals = [...textValues].sort((a, b) => b.length - a.length);
+ const pattern = literals.length ? new RegExp(literals.map(value => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|"), "g") : null;
+ const text = (value: string) => pattern ? value.replace(pattern, "[REDACTED]") : value;
+ function redact(value: unknown, depth = 0): unknown {
+ if (depth > 14) return "[TRUNCATED]";
+ if (scalars.has(value)) return "[REDACTED]";
+ if (typeof value === "string") return text(value);
+ if (Array.isArray(value)) return value.map(child => redact(child, depth + 1));
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, child]) =>
+ [text(key), SECRET_KEY.test(key) ? "[REDACTED]" : redact(child, depth + 1)]));
+ return value;
+ }
+ return { text, value: redact };
+}
diff --git a/lib/workflow/variables.ts b/lib/workflow/variables.ts
index 41581a9d..27de864c 100644
--- a/lib/workflow/variables.ts
+++ b/lib/workflow/variables.ts
@@ -27,4 +27,4 @@ export async function listWorkflowVariables(principal:string){ const owner=workf
export async function setWorkflowVariable(principal:string,key:string,value:unknown,secret=false){ if(!KEY.test(key)) throw new Error("workflow variable key must be A-Z, 0-9, underscore"); validValue(value); const owner=workflowGraphOwner(principal); return withSecurityStoreLock(file(owner),async()=>{const store=await read(owner); if(!Object.hasOwn(store.values,key)&&Object.keys(store.values).length>=128) throw new Error("workflow variable limit reached"); store.values[key]={value:structuredClone(value),secret:Boolean(secret),updatedAt:new Date().toISOString()}; await write(store); return {key,secret:Boolean(secret),updatedAt:store.values[key]!.updatedAt};}); }
export 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)=>row.value).filter((value):value is string=>typeof value==="string"&&value.length>=4); }
+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)); }