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): bind receipts to authority and pin browser artifacts
Abdurrahman Fakhrulba4cdc8ddac8
diff --git a/.env.example b/.env.exampleindex 2e51fcf6..25c75c76 100644--- a/.env.example+++ b/.env.example@@ -26,7 +26,7 @@ OS_SESSION_SECRET=# --- Filesystem bounds (optional) ---# Colon-separated roots. "~" = home, "/" = whole filesystem.-# READ defaults to home + ~/projects; set "/" to browse the whole box read-only.+# READ defaults to the running checkout + ~/projects; add other roots deliberately.# OS_AGENT_VAULT_ROOT=~/mso-vaults# OS_AGENT_VAULT_PROJECT= # Optional default source repo id/name/path; private local configuration# OS_FS_READ_ROOTS=/diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.tsindex 0dbc2891..cb2dd1d8 100644--- a/app/api/v1/workflows/route.ts+++ b/app/api/v1/workflows/route.ts@@ -19,7 +19,7 @@ import { listWorkflowGraphVersions, readWorkflowGraphVersion } from "@/lib/workfimport { resolveWorkflowGraphNodeTarget } from "@/lib/workflow/graph-target";import { deleteWorkflowVariable, listWorkflowVariables, setWorkflowVariable } from "@/lib/workflow/variables";import { workflowNodeCatalog } from "@/lib/workflow/node-catalog";-import { workflowExecutionContext } from "@/lib/workflow/graph-authority";+import { requireWorkflowReceiptAuthority, workflowExecutionContext } from "@/lib/workflow/graph-authority";import { workflowTemplate, workflowTemplates } from "@/lib/workflow/templates";import { suggestWorkflowGraph } from "@/lib/workflow/ai-assist";import { workflowMatchesQuery } from "@/lib/workflow/search";@@ -88,6 +88,6 @@ export async function POST(req:NextRequest){const session=await auth("operator")if(action==="data_table_row_delete")return NextResponse.json(await deleteWorkflowDataTableRow(session.principal,body.table_id,body.row_id),{headers});if(action==="run_stop")return NextResponse.json(await requestWorkflowGraphStop(session.principal,String(body.run_id??"")),{headers});if(action==="run_delete")return NextResponse.json(await deleteWorkflowGraphRun(workflowGraphOwner(session.principal),String(body.run_id??"")),{headers});- if(action==="run_retry"){const prior=await readWorkflowGraphRun(workflowGraphOwner(session.principal),String(body.run_id??""));if(!prior)throw new Error("workflow execution not found");if(prior.state==="running")throw new Error("running execution must be stopped before retry");if(!prior.runtimeInput)throw new Error("execution predates retry input retention; run the workflow again instead");const graph=await getWorkflowGraph(session.principal,prior.graphId);if(!graph)throw new Error("workflow graph not found");if(graph.revision!==prior.graphRevision)throw new Error("workflow changed since this execution; run the current workflow instead of retrying stale input");const agentSession=await createAgentSession(session.principal,"cli",{title:`Workflow retry: ${graph.name}`,titleSource:"auto"}),context={principal:session.principal,actor:session.principal,sessionId:agentSession.id,scope:maxScope(),capabilities:msoCapabilityRuntime} as const;return NextResponse.json(await startWorkflowGraph(graph,prior.runtimeInput,String(body.idempotency_key??`retry:${prior.id}:${Date.now()}`),context,(name)=>TOOLS_BY_NAME.get(name)),{headers});}+ if(action==="run_retry"){const prior=await readWorkflowGraphRun(workflowGraphOwner(session.principal),String(body.run_id??""));if(!prior)throw new Error("workflow execution not found");await requireWorkflowReceiptAuthority(session.principal,prior);if(prior.state==="running")throw new Error("running execution must be stopped before retry");if(!prior.runtimeInput)throw new Error("execution predates retry input retention; run the workflow again instead");const graph=await getWorkflowGraph(session.principal,prior.graphId);if(!graph)throw new Error("workflow graph not found");if(graph.revision!==prior.graphRevision)throw new Error("workflow changed since this execution; run the current workflow instead of retrying stale input");const agentSession=await createAgentSession(session.principal,"cli",{title:`Workflow retry: ${graph.name}`,titleSource:"auto"}),context={principal:session.principal,actor:session.principal,sessionId:agentSession.id,scope:maxScope(),capabilities:msoCapabilityRuntime} as const;return NextResponse.json(await startWorkflowGraph(graph,prior.runtimeInput,String(body.idempotency_key??`retry:${prior.id}:${Date.now()}`),context,(name)=>TOOLS_BY_NAME.get(name)),{headers});}if(action==="run"){const graph=await getWorkflowGraph(session.principal,String(body.graph_id??""));if(!graph)throw new Error("workflow graph not found");const agentSession=await createAgentSession(session.principal,"cli",{title:`Workflow: ${graph.name}`,titleSource:"auto"}),context={principal:session.principal,actor:session.principal,sessionId:agentSession.id,scope:maxScope(),capabilities:msoCapabilityRuntime} as const;return NextResponse.json(await startWorkflowGraph(graph,body.input??{},String(body.idempotency_key??`${Date.now()}`),context,(name)=>TOOLS_BY_NAME.get(name)),{headers});}throw new Error("unknown workflow action");}catch(error){return fail(error);}}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex be1bcae3..2c08c2c0 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Fixed**+- `security` bind receipts to authority and pin browser artifacts- `security` keep connected app bootstrap code static- `security` protect public admission and OAuth registration trustdiff --git a/docs/INSTALL.md b/docs/INSTALL.mdindex 8bd996e3..2598f20d 100644--- a/docs/INSTALL.md+++ b/docs/INSTALL.md@@ -400,16 +400,20 @@ allowlist and its roles intact.## 4. Filesystem roots-Defaults allow the owner's home/project area. Override deliberately:+Read defaults cover the running checkout and `~/projects`, not the whole home. File Manager+opens the first allowed read root when Home is outside that boundary. Write defaults remain+the owner's home/project area. Override deliberately:```dotenv-OS_FS_READ_ROOTS=~:~/projects+OS_FS_READ_ROOTS=/path/to/project:~/projectsOS_FS_WRITE_ROOTS=~:~/projects````OS_FS_READ_ROOTS=/` permits broad **read** browsing subject to the process user's Unixpermissions, but write roots should stay narrow. The credential denylist still blocks MSO's-private state, `.env*`, SSH/GPG paths and other sensitive-home material.+private state, `.env*`, SSH/GPG, Terraform/PyPI/Poetry/doctl/Azure and browser credential+stores. Raw project `.mcp.json`, `.npmrc`, `.pypirc` and `.netrc` are denied; use the redacted+MCP integration inventory for project connection metadata.## 5. Service model@@ -458,9 +462,17 @@ and binary overrides are documented in `.env.example`; normal installations shou## 6. Optional Browser app — CamoufoxThe current Browser app is **Camoufox**, not the retired Playwright browser daemon. Host dependencies-include `xvfb`, `x11vnc`, `novnc`, `matchbox-window-manager`, and `websockify`; install the Camoufox-browser through its isolated Python venv/official fetch path rather than committing browser-binaries into MSO. `scripts/camoufox-vnc-service` launches:+include `xvfb`, `x11vnc`, `novnc`, `matchbox-window-manager`, `websockify` and Python 3.+Run `python3 scripts/camoufox-artifact.py install` from the canonical checkout as the service+user. The repository pins Linux x86_64/arm64 release `v156.0.1-beta.36`, its official archive+SHA-256 and the complete installed file-tree digest in `scripts/camoufox-artifact.json`.+Installation verifies the archive before extracting into a private versioned directory under+`~/.mso/private/camoufox/`; it leaves profiles and session backups intact. Every launch verifies+all browser files and libraries, ownership, private permissions and absence of symlinks or+special files. Mutable cache discovery is removed; `CAMOUFOX_BROWSER` may only name the pinned+installed executable. A missing or modified installation fails before opening the profile.+Update both reviewed archive and tree pins deliberately for a future browser release.+`scripts/camoufox-vnc-service` launches:```textXvfb -> matchbox window manager -> Camoufox -> x11vnc -> websockify/noVNCdiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex a15564d8..508dde48 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,15 @@+## 2026-10-10: Close the five findings from the 34b69798 cloud scan++Read roots default to the checkout and projects, not the whole home. Shared filesystem guards refuse additional Terraform, PyPI, Poetry, doctl, Azure and browser credential stores, plus raw project MCP/registry credentials. The dedicated project MCP inventory remains redacted. File Manager's initial listing selects an allowed root and canonicalizes its history; the sidebar no longer advertises disallowed Home paths. Explicit Owner root overrides remain available and subject to credential guards.++Workflow receipt identity includes graph and trigger node as well as principal/key. Matching legacy receipts retain their IDs; sibling graphs cannot reserve each other's namespace. Input/revision collisions still fail. Receipts retain creation scope and device role: status, waited status, stop, retry and idempotent replay recheck current authority. Owner-era receipts remain Owner-only after demotion even if their execution used a lower scope; legacy receipts require Owner/exec. Viewer inventory remains metadata-only.++Camoufox no longer selects an arbitrary executable from mutable cache. Repository pins bind the official Linux x86_64/arm64 archive checksums and complete installed file-tree digests for v156.0.1-beta.36. The installer verifies before extracting into private versioned runtime state; each launch verifies browser files/libraries, ownership, permissions and regular-file boundaries before touching authenticated profiles. Existing profiles/session snapshots remain intact; the optional service requires a reviewed installation.++Managed-app logs redact the entire Authorization value, including Basic, Digest and quoted headers. Persisted job records are scrubbed on write and historical records again on read, while ordinary update output stays readable. Regression fixtures cover credential denial through actual HTTP/MCP handlers, receipt collisions/demotion/revocation and legacy compatibility, browser artifact tamper/ownership/symlinks/special files, and current/historical log redaction.++The synthetic Google UI fixture waits for bind's replacement card before starting consent; receiving a bind request alone did not mean its reload had completed. Existing Google actions/assertions remain intact. Independent verification of the final released commit remains required.+## 2026-10-10: Give the OAuth browser fixture its own callback receiverGitHub's required browser journey reached the synthetic OAuth callback and then mounted the catch-all MSO shell, which rewrote that unknown client path to the previously focused Settings window before the URL assertion. The fixture now supplies a bounded HTML callback receiver and removes it after testing. Actual registration, exact callback validation, PKCE exchange, state, pruned/manual-client refusal and desktop/mobile checks remain unchanged; production routes and security gates are not relaxed.diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.mdindex 8809c4a9..5eec7f6f 100644--- a/docs/WORKFLOW-GRAPH.md+++ b/docs/WORKFLOW-GRAPH.md@@ -14,6 +14,13 @@ It is additive: existing deterministic project flows, RASMIC scripts and learnedGraphs, versions, variables and execution receipts are private per authenticated principal. Source and builtin templates contain no operator-specific user, credential, path or seeded workflow.+Idempotency keys are scoped to the principal, graph and trigger node; reusing a key with different+input or revision still fails. Legacy receipt IDs remain addressable and are reused only for the+same graph/trigger. Detailed receipts require their creation scope and device role on every+status, waited response, stop, retry and idempotent replay. Owner-era receipts stay Owner-only+after demotion, including runs made with a lower scope; legacy receipts require Owner/exec.+Viewer execution history remains metadata-only and never returns node outputs or logs.+Delegated write authority excludes the live MSO checkout, Git control files, user-systemd units, user-local CLI launchers, Hermes/OpenClaw runtime trees and parent directories that could replace them. These control-plane mutations require exec authority; canonical symlink targets are checked as well.## Node catalogdiff --git a/frontend/slices/files-manager/hooks/use-files.ts b/frontend/slices/files-manager/hooks/use-files.tsindex 2441f061..9498863a 100644--- a/frontend/slices/files-manager/hooks/use-files.ts+++ b/frontend/slices/files-manager/hooks/use-files.ts@@ -24,6 +24,7 @@ export function useFiles(initialPath?: string) {const api = useOsApi();const nav = usePathHistory(initialPath || "~");const { path } = nav;+ const { replaceCurrent } = nav;// Listing keyed by the request that produced it: when path/reload move on the// stale result stops matching and `entries` derives back to null (loading) —// no synchronous setState reset in the effect (react-hooks/set-state-in-effect).@@ -52,6 +53,7 @@ export function useFiles(initialPath?: string) {.list(path).then((res) => {if (!alive) return;+ if ((!path || path === "~") && res.path !== path) replaceCurrent(res.path);setListing({ key: loadKey, entries: res.entries });if (res.roots?.length) setRoots(res.roots);})@@ -72,7 +74,7 @@ export function useFiles(initialPath?: string) {return () => {alive = false;};- }, [api, path, loadKey]);+ }, [api, path, loadKey, replaceCurrent]);useEffect(() => {let alive = true;diff --git a/frontend/slices/files-manager/hooks/use-path-history.ts b/frontend/slices/files-manager/hooks/use-path-history.tsindex 4b2d34ec..4b863b31 100644--- a/frontend/slices/files-manager/hooks/use-path-history.ts+++ b/frontend/slices/files-manager/hooks/use-path-history.ts@@ -9,6 +9,11 @@ export function usePathHistory(start: string) {const [history, setHistory] = useState<string[]>([start]);const [cursor, setCursor] = useState(0);+ const replaceCurrent = useCallback((next: string) => {+ setPath(next);+ setHistory((items) => items.map((item, index) => index === cursor ? next : item));+ }, [cursor]);+const navigate = useCallback((next: string) => {setHistory((h) => {@@ -34,6 +39,7 @@ export function usePathHistory(start: string) {return {path,navigate,+ replaceCurrent,goBack,goForward,canBack: cursor > 0,diff --git a/lib/contracts/workflow-graph.ts b/lib/contracts/workflow-graph.tsindex 2f216188..3b092b83 100644--- a/lib/contracts/workflow-graph.ts+++ b/lib/contracts/workflow-graph.ts@@ -88,6 +88,9 @@ export type WorkflowGraphRun = {graphName: string;idempotencyKey: string;fingerprint: string;+ /** Missing on legacy receipts: treat their outputs as exec-only. */+ executionScope?: "read" | "write" | "exec";+ executionRole?: "operator" | "owner";state: "running" | "completed" | "completed_with_errors" | "failed" | "interrupted";startedAt: string;updatedAt: string;diff --git a/lib/host/fs-enumeration.ts b/lib/host/fs-enumeration.tsindex d600aea4..7c31214e 100644--- a/lib/host/fs-enumeration.ts+++ b/lib/host/fs-enumeration.ts@@ -2,7 +2,7 @@ import { promises as fs } from "node:fs";import path from "node:path";import type { FsList } from "@/lib/os-api/types";import { HostError } from "./host-error";-import { isCredentialPath, resolveReadable, resolveRoots } from "./paths";+import { homeDir, isUnderRoot, readRootList, isCredentialPath, resolveReadable, resolveRoots } from "./paths";import { projectAliasTarget } from "./project-aliases";import { descriptorPath, pinDirectory } from "./fs-descriptors";@@ -34,7 +34,9 @@ async function bounded<T>(signal: AbortSignal | undefined, run: (charge: (bytes?export async function listDir(requested: string, includeHidden = true, signal?: AbortSignal): Promise<FsList> {return bounded(signal, async (charge) => {charge();- const held = await pinDirectory(await resolveReadable(requested || "~"), false);+ const roots = readRootList();+ const start = (!requested || requested === "~") && !roots.some((root) => isUnderRoot(homeDir(), root)) ? roots[0] : requested || "~";+ const held = await pinDirectory(await resolveReadable(start), false);try {const real = await descriptorPath(held.handle, false);const entries: FsList["entries"] = [];diff --git a/lib/host/path-credentials.ts b/lib/host/path-credentials.tsindex 231373d7..b6932fce 100644--- a/lib/host/path-credentials.ts+++ b/lib/host/path-credentials.ts@@ -33,6 +33,9 @@ export const SENSITIVE_HOME = [".bash_history", ".zsh_history", ".python_history", ".mysql_history",// cloud / infra credentials".aws", ".config/gcloud", ".kube", ".docker", ".config/rclone",+ ".terraform.d", ".terraformrc", ".pypirc", ".config/pypoetry", ".config/doctl", ".azure",+ ".mozilla", ".config/google-chrome", ".config/chromium", ".config/BraveSoftware",+ ".config/microsoft-edge", ".cache/camoufox",".git-credentials", ".netrc", ".config/git/credentials",// AI/dev-tool + OS keyring credentials (account tokens = full account access)".claude", ".claude.json", ".config/gh", ".config/anthropic", ".local/share/keyrings",@@ -99,6 +102,7 @@ export function isCredentialPath(real: string, roots = credentialRoots()): booleif (roots.some((root) => isUnderRoot(real, root))) return true;const names = path.resolve(real).split(path.sep);if (names.some((name) => name.startsWith(".env") && name !== ".env.example")) return true;+ if (names.some((name) => [".mcp.json", ".npmrc", ".pypirc", ".netrc"].includes(name))) return true;const base = path.basename(real);// Private keys land anywhere (heredoc dumps, deploy keys, downloaded service// accounts). Their basename/extension is the reliable marker outside fixed ~/ paths.@@ -116,6 +120,6 @@ export function looseCredentialExcludes(): string[] {: PRIVATE_KEY_BASENAMES.flatMap((name) => [name, `*/${name}`]);// *.pem has historically been a hard credential boundary, independent of the// SENSITIVE_HOME escape hatch; keep that contract while extending id_* safely.- return ["*.pem", ".env*", "*/.env*", ...privateNames];+ return ["*.pem", ".env*", "*/.env*", ...[".mcp.json", ".npmrc", ".pypirc", ".netrc"].flatMap((name) => [name, `*/${name}`]), ...privateNames];}diff --git a/lib/host/path-roots.test.ts b/lib/host/path-roots.test.tsindex 46a8d617..55382c96 100644--- a/lib/host/path-roots.test.ts+++ b/lib/host/path-roots.test.ts@@ -1,8 +1,14 @@import path from "node:path";-import { describe, expect, it } from "vitest";-import { parseRootEnv } from "./path-roots";+import { afterEach, describe, expect, it, vi } from "vitest";+import { homeDir, parseRootEnv, readRootList } from "./path-roots";+afterEach(() => vi.unstubAllEnvs());describe("native filesystem root configuration", () => {+ it("defaults reads to the checkout and projects instead of the entire home", () => {+ vi.stubEnv("OS_FS_READ_ROOTS", undefined);+ expect(readRootList()).toEqual([process.cwd(), path.join(homeDir(), "projects")]);+ expect(readRootList()).not.toContain(homeDir());+ });it("does not split Windows drive letters when parsing semicolon-separated roots", () => {expect(parseRootEnv(String.raw`C:\Users\Alice;D:\Work`, path.win32.delimiter)).toEqual([String.raw`C:\Users\Alice`, String.raw`D:\Work`,diff --git a/lib/host/path-roots.ts b/lib/host/path-roots.tsindex 468f66b1..ed55a250 100644--- a/lib/host/path-roots.ts+++ b/lib/host/path-roots.ts@@ -22,7 +22,7 @@ function rootsFromEnv(name: string, fallback: string[]): string[] {export function readRootList(): string[] {const h = homeDir();- return rootsFromEnv("OS_FS_READ_ROOTS", [h, path.join(h, "projects")]);+ return rootsFromEnv("OS_FS_READ_ROOTS", [process.cwd(), path.join(h, "projects")]);}export function writeRootList(): string[] {diff --git a/lib/host/paths-credentials.test.ts b/lib/host/paths-credentials.test.tsindex 0561fb42..bb8ed89f 100644--- a/lib/host/paths-credentials.test.ts+++ b/lib/host/paths-credentials.test.ts@@ -37,6 +37,16 @@ afterAll(() => rmSync(base, { recursive: true, force: true }));afterEach(() => vi.unstubAllEnvs());describe("recursive credential guard", () => {+ it("blocks optional provider/browser stores and secret-bearing project configs", () => {+ vi.stubEnv("HOME", fakeHome);+ for (const name of [".terraform.d/credentials.tfrc.json", ".pypirc", ".config/pypoetry/auth.toml", ".config/doctl/config.yaml", ".azure/accessTokens.json", ".mozilla/firefox/profile/cookies.sqlite", ".config/google-chrome/Default/Cookies", ".config/chromium/Default/Cookies"]) {+ expect(isCredentialPath(path.join(fakeHome, name)), name).toBe(true);+ }+ for (const name of [".mcp.json", ".npmrc", ".pypirc", ".netrc"]) {+ expect(isCredentialPath(path.join(fakeHome, "safe", "project", name)), name).toBe(true);+ expect(looseCredentialExcludes()).toContain(`*/${name}`);+ }+ });it("blocks the agent credential stores added to the denylist", () => {vi.stubEnv("HOME", fakeHome);expect(isSensitivePath(path.join(fakeHome, ".codex"))).toBe(true);@@ -127,7 +137,8 @@ describe("recursive credential guard", () => {vi.stubEnv("HOME", fakeHome);vi.stubEnv("OS_FS_ALLOW_SENSITIVE", "1");expect(sensitiveExcludes(fakeHome)).toEqual([]);- expect(looseCredentialExcludes()).toEqual(["*.pem", ".env*", "*/.env*"]);+ expect(looseCredentialExcludes()).toEqual(expect.arrayContaining(["*.pem", ".env*", "*/.env*", ".mcp.json", "*/.mcp.json"]));+ expect(looseCredentialExcludes()).not.toContain("id_rsa");expect(isCredentialPath(path.join(fakeHome, "safe", "id_rsa"))).toBe(false);expect(isCredentialPath(path.join(fakeHome, "safe", "deploy.pem"))).toBe(true);expect(() => assertNoSensitiveDescendants(parent)).not.toThrow();diff --git a/lib/host/paths.ts b/lib/host/paths.tsindex d9da0b3b..361a02ae 100644--- a/lib/host/paths.ts+++ b/lib/host/paths.ts@@ -196,15 +196,16 @@ function labelFor(p: string): string {return path.basename(p) || p;}-// Sidebar jump-points: Home + Projects, plus any extra read roots (e.g. "/").+// Sidebar jump-points must stay inside the configured read roots.export function resolveRoots(): FsRoot[] {const h = homeDir();+ const configured = readRootList();const base: FsRoot[] = [{ label: "Home", path: h },{ label: "Projects", path: path.join(h, "projects") },];- const extra = readRootList()+ const extra = configured.filter((p) => p !== h && p !== path.join(h, "projects")).map((p) => ({ label: labelFor(p), path: p }));- return [...base, ...extra];+ return [...base.filter((entry) => configured.some((root) => isUnderRoot(entry.path, root))), ...extra];}diff --git a/lib/managed-apps/job-store.test.ts b/lib/managed-apps/job-store.test.tsindex c4394a8c..702c07a0 100644--- a/lib/managed-apps/job-store.test.ts+++ b/lib/managed-apps/job-store.test.ts@@ -54,6 +54,16 @@ function record(over: Partial<ManagedAppJob> = {}): ManagedAppJob {}describe("job ids are filenames, so they are validated as filenames", () => {+ it("redacts Basic credentials in persisted records and legacy transcript reads", async () => {+ const raw = record({ log: "Authorization: Basic dXNlcjpwYXNz\nordinary output", error: "Authorization: Basic dXNlcjpwYXNz" });+ await writeJobRecord(raw);+ const file = path.join(home, ".mso", "managed-app-jobs", `${raw.id}.json`);+ expect(await fs.readFile(file, "utf8")).not.toContain("dXNlcjpwYXNz");+ await fs.writeFile(file, JSON.stringify(raw), { mode: 0o600 });+ expect(JSON.stringify(await readJobRecord(raw.id))).not.toContain("dXNlcjpwYXNz");+ expect((await readJobRecord(raw.id))?.log).toContain("ordinary output");+ expect(JSON.stringify(await listJobRecords())).not.toContain("dXNlcjpwYXNz");+ });it("accepts only 24 lowercase hex chars", () => {expect(isManagedAppJobId(randomBytes(12).toString("hex"))).toBe(true);expect(isManagedAppJobId("../../../.ssh/id_ed25519")).toBe(false);diff --git a/lib/managed-apps/job-store.ts b/lib/managed-apps/job-store.tsindex 73230dd7..04e81324 100644--- a/lib/managed-apps/job-store.ts+++ b/lib/managed-apps/job-store.ts@@ -3,6 +3,7 @@ import { promises as fs } from "node:fs";import os from "node:os";import path from "node:path";import type { ManagedAppId, ManagedAppJob } from "./types";+import { redact } from "./redact";// Durable half of the job layer: one JSON file per job under// ~/.mso/managed-app-jobs/ (0700 dir, 0600 files, tmp+rename), matching how@@ -64,7 +65,7 @@ export async function writeJobRecord(record: ManagedAppJob): Promise<void> {// pid in the tmp name: two mso processes sharing $HOME must not collide on// one another's partial write.const tmp = `${file}.${process.pid}.tmp`;- await fs.writeFile(tmp, JSON.stringify(record), { encoding: "utf8", mode: 0o600 });+ await fs.writeFile(tmp, JSON.stringify({ ...record, log: record.log.split(/\r?\n/).map(redact).join("\n"), error: record.error ? redact(record.error) : record.error }), { encoding: "utf8", mode: 0o600 });await fs.rename(tmp, file);}@@ -72,7 +73,7 @@ async function parse(file: string): Promise<ManagedAppJob | null> {try {const record = JSON.parse(await fs.readFile(file, "utf8")) as ManagedAppJob;const shaped = isManagedAppJobId(record?.id) && typeof record.status === "string" && typeof record.updatedAt === "string";- return shaped ? { ...record, argv: Array.isArray(record.argv) ? record.argv : [] } : null;+ return shaped ? { ...record, argv: Array.isArray(record.argv) ? record.argv : [], log: typeof record.log === "string" ? record.log.split(/\r?\n/).map(redact).join("\n") : "", error: record.error ? redact(record.error) : record.error } : null;} catch {return null; // missing, half-written or hand-edited: not a job}diff --git a/lib/managed-apps/redact.test.ts b/lib/managed-apps/redact.test.tsindex 051f5264..a15116b1 100644--- a/lib/managed-apps/redact.test.ts+++ b/lib/managed-apps/redact.test.ts@@ -30,6 +30,17 @@ const TRANSCRIPT = [];describe("secrets that reached a persisted transcript before this widened", () => {+ it("removes complete authorization values for Basic, Digest and quoted header dumps", () => {+ for (const line of ["Authorization: Basic dXNlcjpwYXNz", "authorization=basic dXNlcjpwYXNz; status=401", '"Authorization": "Basic dXNlcjpwYXNz", "status": 401', "Authorization: Digest username=alice, response=secret", "Proxy-Authorization: Basic dXNlcjpwYXNz"]) {+ const value = redact(line);+ expect(value).toContain("[redacted]");+ expect(value).not.toContain("dXNlcjpwYXNz");+ expect(value).not.toContain("secret");+ expect(value).not.toContain("alice");+ expect(redact(value)).toBe(value);+ }+ expect(JSON.parse(redact('{"Authorization":"Basic dXNlcjpwYXNz","status":401}'))).toEqual({ Authorization: "[redacted]", status: 401 });+ });const cases: Array<[string, string, string]> = [["a bare PAT in a git error, with no key=value beside it",diff --git a/lib/managed-apps/redact.ts b/lib/managed-apps/redact.tsindex 036eb4ba..cc17ffc8 100644--- a/lib/managed-apps/redact.ts+++ b/lib/managed-apps/redact.ts@@ -64,9 +64,10 @@ const URL_CREDENTIALS = /\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s/@]+)@/gi;* through the regex. */export function redact(line: string): string {return line+ .replace(/\b(authorization["']?\s*[:=]\s*)("(?:\\.|[^"\\\r\n])*"|'(?:\\.|[^'\\\r\n])*'|[^\r\n;\]}]+)/gi, (match, prefix: string, value: string) => value === "[redacted" ? match : `${prefix}${value.startsWith('"') || value.startsWith("'") ? value[0] + "[redacted]" + value[0] : "[redacted]"}`).replace(/\bbearer\s+[^\s,;]+/gi, "Bearer [redacted]").replace(URL_CREDENTIALS, "$1$2:[redacted]@")- .replace(SECRET, "$1$2[redacted]")+ .replace(SECRET, (match, key: string, separator: string, value: string) => value === "[redacted" ? match : `${key}${separator}[redacted]`).replace(SECRET_VALUE, "[redacted]").slice(0, 8192);}diff --git a/lib/mcp/fs-credential-boundary.test.ts b/lib/mcp/fs-credential-boundary.test.tsnew file mode 100644index 00000000..05cfd0eb--- /dev/null+++ b/lib/mcp/fs-credential-boundary.test.ts@@ -0,0 +1,50 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+vi.mock("server-only", () => ({}));+vi.mock("@/lib/demo", () => ({ IS_DEMO: false }));+vi.mock("@/lib/auth/require-session", () => ({ requireSession: async (role: string) => role === "viewer" }));+import { GET } from "@/app/api/v1/fs/read/route";+import { READ_TOOLS } from "./tools-read";+import { publicProjectMcpServers, readProjectMcpServers } from "@/lib/host/project-mcp-config";+import { listDir } from "@/lib/host/fs-enumeration";+let home: string;+beforeEach(async () => {+ home = await mkdtemp(path.join(os.tmpdir(), "mso-credential-read-"));+ vi.spyOn(os, "homedir").mockReturnValue(home);+ vi.stubEnv("OS_FS_READ_ROOTS", home);+ vi.stubEnv("OS_FS_ALLOW_SENSITIVE", undefined);+});+afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); await rm(home, { recursive: true, force: true }); });+const fsRead = READ_TOOLS.find(tool => tool.name === "fs_read")!;+describe("Viewer HTTP and read-scope MCP credential boundary", () => {+ it("opens only an allowed root and omits the disallowed Home jump point", async () => {+ const project = path.join(home, "projects", "app");+ await mkdir(project, { recursive: true }); await writeFile(path.join(project, "README.md"), "public-project");+ vi.stubEnv("OS_FS_READ_ROOTS", project);+ const listing = await listDir("~");+ expect(listing.path).toBe(project);+ expect(listing.entries.map(entry => entry.name)).toContain("README.md");+ expect(listing.roots?.some(root => root.path === home)).toBe(false);+ expect(listing.parent).toBeNull();+ await expect(listDir(home)).rejects.toThrow(/outside readable roots/);+ });+ it.each([".terraform.d/credentials.tfrc.json", ".pypirc", ".config/pypoetry/auth.toml", ".config/doctl/config.yaml", ".azure/accessTokens.json", ".mozilla/firefox/profile/cookies.sqlite", ".config/google-chrome/Default/Cookies", ".config/chromium/Default/Cookies", "projects/app/.mcp.json", "projects/app/.npmrc"])("refuses %s even inside an explicitly broad read root", async name => {+ const target = path.join(home, name);+ await mkdir(path.dirname(target), { recursive: true }); await writeFile(target, "synthetic-credential", { mode: 0o600 });+ const response = await GET(new Request("http://localhost/api/v1/fs/read?" + new URLSearchParams({ path: target })));+ expect(response.status).toBeGreaterThanOrEqual(400);+ expect(await response.text()).not.toContain("synthetic-credential");+ expect(fsRead.scope).toBe("read");+ await expect(fsRead.run({ path: target }, { scope: "read", principal: "fixture" })).rejects.toThrow(/credential|sensitive/);+ });+ it("preserves the dedicated redacted MCP inventory while refusing raw config", async () => {+ const project = path.join(home, "projects", "app"); await mkdir(project, { recursive: true });+ await writeFile(path.join(project, ".mcp.json"), JSON.stringify({ mcpServers: { example: { command: "node", env: { ACCESS_TOKEN: "synthetic-private-value" } } } }), { mode: 0o600 });+ const inventory = publicProjectMcpServers(await readProjectMcpServers(project));+ expect(inventory).toMatchObject([{ name: "example", transport: "stdio" }]);+ expect(JSON.stringify(inventory)).not.toContain("synthetic-private-value");+ await expect(fsRead.run({ path: path.join(project, ".mcp.json") }, { scope: "read", principal: "fixture" })).rejects.toThrow(/credential|sensitive/);+ });+});diff --git a/lib/mcp/tools-flows.ts b/lib/mcp/tools-flows.tsindex d6086fb4..857e8d85 100644--- a/lib/mcp/tools-flows.ts+++ b/lib/mcp/tools-flows.ts@@ -17,6 +17,7 @@ import { createWorkflowDataTable, deleteWorkflowDataTable, deleteWorkflowDataTabimport { optimizeWorkflowGraph } from "@/lib/workflow/graph-optimizer";import { createResolvedJevWorkflowOptimizerEvaluator } from "@/lib/workflow/jev-evaluator";import { resolveJevIntegrationConfig } from "@/lib/workflow/jev-integration";+import { requireWorkflowReceiptAuthority } from "@/lib/workflow/graph-authority";import { requireWorkflowProjectTarget } from "./workflow-workspace-guard";const project = { type: "string", maxLength: 4096 };const flow = { type: "string", maxLength: 64 };@@ -76,11 +77,11 @@ export const FLOW_TOOLS: McpTool[] = [const principal = privateGraphPrincipal(context), action = str(a, "action");const data = a.data && typeof a.data === "object" && !Array.isArray(a.data) ? a.data as Record<string, unknown> : {};if (action === "list" || action === "search") { const graphs = await listWorkflowGraphs(principal), query = typeof data.query === "string" ? data.query : "", filters = { tag: typeof data.tag === "string" ? data.tag : undefined, status: typeof data.status === "string" ? data.status : undefined, project: typeof data.project === "string" ? data.project : undefined, folder: typeof data.folder === "string" ? data.folder : undefined, node: typeof data.node === "string" ? data.node : undefined }; return { graphs: graphs.filter((graph) => workflowMatchesQuery(graph, query, filters)).map(graph => ({ id: graph.id, name: graph.name, description: graph.description, status: graph.status, revision: graph.revision, nodeCount: graph.nodes.length, updatedAt: graph.updatedAt, provenance: graph.metadata.provenance, project: graph.metadata.project, folder: graph.metadata.folder, tags: graph.metadata.tags ?? [] })) }; }- if (action === "status") return workflowGraphRunStatus(principal, str(a, "id"), Number(a.wait_ms) || 0);+ if (action === "status") return workflowGraphRunStatus(principal, str(a, "id"), Number(a.wait_ms) || 0, context.scope);if (action === "runs") return listWorkflowGraphRuns(workflowGraphOwner(principal), { graphId: typeof data.graph_id === "string" ? data.graph_id : undefined, limit: Number(data.limit) || 30, offset: Number(data.offset) || 0 });- if (action === "stop") return requestWorkflowGraphStop(principal, str(a, "id"));+ if (action === "stop") return requestWorkflowGraphStop(principal, str(a, "id"), context.scope);if (action === "run_delete") return deleteWorkflowGraphRun(workflowGraphOwner(principal), str(a, "id"));- if (action === "retry") { const prior = await readWorkflowGraphRun(workflowGraphOwner(principal), str(a, "id")); if (!prior) throw new Error("workflow execution not found"); if (prior.state === "running") throw new Error("running execution must be stopped before retry"); if (!prior.runtimeInput) throw new Error("execution predates retry input retention; run the workflow again instead"); const graph = await getWorkflowGraph(principal, prior.graphId); if (!graph) throw new Error("workflow graph not found"); if (graph.revision !== prior.graphRevision) throw new Error("workflow changed since this execution; run current graph instead"); const key = typeof data.key === "string" ? data.key : ""; if (!key) throw new Error("data.key is required for retry idempotency"); const { TOOLS_BY_NAME } = await import("./tools"); return startWorkflowGraph(graph, prior.runtimeInput, key, context, name => TOOLS_BY_NAME.get(name), principal); }+ if (action === "retry") { const prior = await readWorkflowGraphRun(workflowGraphOwner(principal), str(a, "id")); if (!prior) throw new Error("workflow execution not found"); await requireWorkflowReceiptAuthority(principal, prior, context.scope); if (prior.state === "running") throw new Error("running execution must be stopped before retry"); if (!prior.runtimeInput) throw new Error("execution predates retry input retention; run the workflow again instead"); const graph = await getWorkflowGraph(principal, prior.graphId); if (!graph) throw new Error("workflow graph not found"); if (graph.revision !== prior.graphRevision) throw new Error("workflow changed since this execution; run current graph instead"); const key = typeof data.key === "string" ? data.key : ""; if (!key) throw new Error("data.key is required for retry idempotency"); const { TOOLS_BY_NAME } = await import("./tools"); return startWorkflowGraph(graph, prior.runtimeInput, key, context, name => TOOLS_BY_NAME.get(name), principal); }if (action === "scripts") { const hint = typeof data.project === "string" ? data.project : ""; if (!hint) throw new Error("project is required"); const project = await resolveProjectHint(hint); if (!project || project.matchedBy === "fuzzy") throw new Error("exact project not found"); const query = typeof data.query === "string" ? data.query.toLowerCase().trim() : ""; const scripts = (await listAutomationScripts(project.path)).filter((script) => !query || `${script.id} ${script.intent} ${script.status} ${script.steps.map((step) => step.tool).join(" ")}`.toLowerCase().includes(query)).map((script) => ({ id: script.id, intent: script.intent, status: script.status, stepCount: script.steps.length, updatedAt: script.updatedAt, project: script.project, tools: script.steps.map((step) => step.tool) })); return { project: project.id, scripts }; }if (action === "catalog") return { nodes: workflowNodeCatalog(typeof data.query === "string" ? data.query : "") };if (action === "templates") return { templates: workflowTemplates() };diff --git a/lib/workflow/graph-authority.ts b/lib/workflow/graph-authority.tsindex 77ca04e3..a34e730c 100644--- a/lib/workflow/graph-authority.ts+++ b/lib/workflow/graph-authority.ts@@ -1,4 +1,5 @@import { getApprovedDevice } from "@/lib/auth/device-store";+import { roleAtLeast } from "@/lib/auth/roles";import { liveCapabilityContext } from "@/lib/capabilities/live-authority";import { allows, scopeRank, type Scope } from "@/lib/capabilities/scope";import type { CapabilityRunContext } from "@/lib/capabilities/tool";@@ -40,3 +41,17 @@ export async function workflowExecutionContext(export function requireWorkflowScope(context: CapabilityRunContext, required: Scope): void {if (!allows(context.scope, required)) throw new Error(`workflow requires ${required} authority`);}++/** Receipt ownership survives demotion; access to its original authority does not. */+export async function requireWorkflowReceiptAuthority(principal: string, run: WorkflowGraphRun, scope: Scope = "exec"): Promise<void> {+ let ceiling = configuredCapabilityCeiling();+ if (principal.startsWith("web:")) {+ const device = await getApprovedDevice(principal.slice(4));+ if (!device) throw new Error("workflow receipt device is revoked");+ if (!roleAtLeast(device.role, run.executionRole ?? "owner")) throw new Error("workflow receipt requires its original execution authority");+ const roleScope: Scope = device.role === "owner" ? "exec" : device.role === "operator" ? "write" : "read";+ if (scopeRank(roleScope) < scopeRank(ceiling)) ceiling = roleScope;+ }+ const effective = scopeRank(scope) < scopeRank(ceiling) ? scope : ceiling;+ if (!allows(effective, run.executionScope ?? "exec")) throw new Error("workflow receipt requires its original execution authority");+}diff --git a/lib/workflow/graph-engine.ts b/lib/workflow/graph-engine.tsindex 69b5aae0..51d9abd7 100644--- a/lib/workflow/graph-engine.ts+++ b/lib/workflow/graph-engine.ts@@ -1,4 +1,5 @@-import { workflowExecutionContext } from "./graph-authority";+import { requireWorkflowReceiptAuthority, workflowExecutionContext } from "./graph-authority";+import { getApprovedDevice } from "@/lib/auth/device-store";import { receiptRedactor } from "./receipt-redaction";import { createHash, randomUUID } from "node:crypto";import type { CapabilityRunContext, CapabilityTool } from "@/lib/capabilities/tool";@@ -70,13 +71,14 @@ async function maybeRunErrorWorkflow(run:WorkflowGraphRun,graph:WorkflowGraph,coconst {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()},run.ancestry??[graph.id]);}-export function workflowGraphRunId(owner:string,key:string){return hash(`${owner}:${key}`).slice(0,32);}+export function workflowGraphRunId(owner:string,key:string,graphId:string,triggerNodeId=""){return hash(canonical([owner,graphId,triggerNodeId,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);});+ const triggerNodeId=trigger?.nodeId??graph.nodes.find((node)=>node.type==="manual")?.id??graph.nodes.find((node)=>["schedule","webhook","channel_trigger"].includes(node.type))?.id??"";+ const owner=workflowGraphOwner(principal),input=inputObject(rawInput),fingerprint=hash(canonical({graphId:graph.id,revision:graph.revision,input})),id=workflowGraphRunId(owner,idempotencyKey,graph.id,triggerNodeId);+ return lockWorkflowGraphRun(owner,id,async()=>{const legacy=await readWorkflowGraphRun(owner,hash(`${owner}:${idempotencyKey}`).slice(0,32));const existing=await readWorkflowGraphRun(owner,id)??(legacy?.graphId===graph.id&&(legacy.trigger?.nodeId??"")===triggerNodeId?legacy:null);if(existing){await requireWorkflowReceiptAuthority(principal,existing,context.scope);if(existing.fingerprint!==fingerprint)throw new Error("idempotency_key already identifies a different graph/input/revision");return publicWorkflowGraphRun(existing);}const device=principal.startsWith("web:")?await getApprovedDevice(principal.slice(4)):null;if(principal.startsWith("web:")&&(!device||device.role==="viewer"))throw new Error("workflow device is revoked or lacks operator authority");await pruneWorkflowGraphRuns(owner);const run:WorkflowGraphRun={version:1,id,owner,sessionId:context.sessionId!,graphId:graph.id,graphRevision:graph.revision,graphName:graph.name,idempotencyKey,fingerprint,executionScope:context.scope,executionRole:device?.role==="owner"?"owner":device?.role==="operator"?"operator":undefined,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);});}-export async function workflowGraphRunStatus(principal:string,id:string,waitMs=0){if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>25_000)throw new Error("wait_ms must be 0-25000");const owner=workflowGraphOwner(principal);let run=await readWorkflowGraphRun(owner,id);if(!run)throw new Error("workflow graph run not found for this principal");if(run.state==="running"&&pending.has(id)&&waitMs>0){let timer:ReturnType<typeof setTimeout>|undefined;await Promise.race([pending.get(id),new Promise((resolve)=>{timer=setTimeout(resolve,waitMs);})]);clearTimeout(timer);run=await readWorkflowGraphRun(owner,id)??run;}if(run.state==="running"&&run.instance!==INSTANCE){let gone=false;try{process.kill(run.pid,0);}catch(error){gone=(error as NodeJS.ErrnoException).code==="ESRCH";}if(gone){run.state="interrupted";run.updatedAt=run.finishedAt=new Date().toISOString();await writeWorkflowGraphRun(run);}}return publicWorkflowGraphRun(run);}+export async function workflowGraphRunStatus(principal:string,id:string,waitMs=0,scope:CapabilityRunContext["scope"]="exec"){if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>25_000)throw new Error("wait_ms must be 0-25000");const owner=workflowGraphOwner(principal);let run=await readWorkflowGraphRun(owner,id);if(!run)throw new Error("workflow graph run not found for this principal");await requireWorkflowReceiptAuthority(principal,run,scope);if(run.state==="running"&&pending.has(id)&&waitMs>0){let timer:ReturnType<typeof setTimeout>|undefined;await Promise.race([pending.get(id),new Promise((resolve)=>{timer=setTimeout(resolve,waitMs);})]);clearTimeout(timer);run=await readWorkflowGraphRun(owner,id)??run;}if(run.state==="running"&&run.instance!==INSTANCE){let gone=false;try{process.kill(run.pid,0);}catch(error){gone=(error as NodeJS.ErrnoException).code==="ESRCH";}if(gone){run.state="interrupted";run.updatedAt=run.finishedAt=new Date().toISOString();await writeWorkflowGraphRun(run);}}await requireWorkflowReceiptAuthority(principal,run,scope);return publicWorkflowGraphRun(run);}-export async function requestWorkflowGraphStop(principal:string,id:string){const owner=workflowGraphOwner(principal),run=await readWorkflowGraphRun(owner,id);if(!run)throw new Error("workflow graph run not found for this principal");if(run.state!=="running")return{...publicWorkflowGraphRun(run),stopRequested:false};if(run.instance!==INSTANCE||!pending.has(id))throw new Error("workflow execution is owned by another runtime; refresh its status before retrying stop");cancelled.add(id);return{...publicWorkflowGraphRun(run),stopRequested:true};}+export async function requestWorkflowGraphStop(principal:string,id:string,scope:CapabilityRunContext["scope"]="exec"){const owner=workflowGraphOwner(principal),run=await readWorkflowGraphRun(owner,id);if(!run)throw new Error("workflow graph run not found for this principal");await requireWorkflowReceiptAuthority(principal,run,scope);if(run.state!=="running")return{...publicWorkflowGraphRun(run),stopRequested:false};if(run.instance!==INSTANCE||!pending.has(id))throw new Error("workflow execution is owned by another runtime; refresh its status before retrying stop");cancelled.add(id);return{...publicWorkflowGraphRun(run),stopRequested:true};}diff --git a/lib/workflow/graph-receipt-boundary.test.ts b/lib/workflow/graph-receipt-boundary.test.tsnew file mode 100644index 00000000..6846cb41--- /dev/null+++ b/lib/workflow/graph-receipt-boundary.test.ts@@ -0,0 +1,96 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import { createHash } from "node:crypto";+import os from "node:os";+import path from "node:path";+import type { DeviceRole } from "@/lib/auth/roles";+import type { CapabilityTool } from "@/lib/capabilities/tool";+let role: DeviceRole | null = "owner";+vi.mock("@/lib/auth/device-store", () => ({ getApprovedDevice: async () => role ? { role } : null }));+import { createWorkflowGraph, workflowGraphOwner } from "./graph-store";+import { requestWorkflowGraphStop, startWorkflowGraph, workflowGraphRunStatus } from "./graph-engine";+import { listWorkflowGraphRuns, readWorkflowGraphRun, writeWorkflowGraphRun } from "./graph-run-store";+import { requireWorkflowReceiptAuthority } from "./graph-authority";+const principal = "web:11223344556677889900aabbccddeeff";+const context = { principal, actor: principal, sessionId: "fixture", scope: "exec" as const };+let dir: string;+beforeEach(async () => { dir = await mkdtemp(path.join(os.tmpdir(), "mso-receipt-boundary-")); role = "owner"; vi.stubEnv("OS_AGENT_SESSIONS_DIR", dir); vi.stubEnv("OS_MCP_MAX_SCOPE", "exec"); });+afterEach(async () => { vi.unstubAllEnvs(); await rm(dir, { recursive: true, force: true }); });+async function graph(name: string) {+ return createWorkflowGraph(principal, { name, description: "", status: "draft", inputs: {}, metadata: {}, nodes: [{ id: "start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} }, { id: "out", name: "Result", type: "output", position: { x: 100, y: 0 }, config: { value: "fixture-private-output" } }], edges: [{ id: "edge", source: "start", target: "out" }] });+}+describe("workflow receipt identity and creation authority", () => {+ it("rechecks authority after a waited execution finishes", async () => {+ let release!: () => void;+ const pending = new Promise<void>(resolve => { release = resolve; });+ let entered = false;+ const tool: CapabilityTool = { name: "fixture_wait", description: "fixture", scope: "read", inputSchema: { type: "object" }, run: async () => { entered = true; await pending; return "fixture-private-output"; } };+ const saved = await graph("Waited");+ saved.nodes[1] = { ...saved.nodes[1], type: "tool", config: { tool: tool.name, args: {} } };+ const started = await startWorkflowGraph(saved, {}, "waited-key", context, () => tool);+ await vi.waitFor(() => expect(entered).toBe(true));+ const waited = workflowGraphRunStatus(principal, started.id, 5000);+ await new Promise(resolve => setImmediate(resolve));+ role = "viewer"; release();+ await expect(waited).rejects.toThrow(/original execution authority/);+ role = "owner"; await workflowGraphRunStatus(principal, started.id, 5000);+ });+ it("separates sibling graphs and trigger nodes while preserving exact retries", async () => {+ const first = await graph("First"), second = await graph("Second");+ const a = await startWorkflowGraph(first, {}, "shared-key", context, () => undefined);+ const b = await startWorkflowGraph(second, {}, "shared-key", context, () => undefined);+ expect(b.id).not.toBe(a.id);+ expect((await workflowGraphRunStatus(principal, a.id, 5000)).state).toBe("completed");+ expect((await workflowGraphRunStatus(principal, b.id, 5000)).state).toBe("completed");+ expect((await startWorkflowGraph(first, {}, "shared-key", context, () => undefined)).id).toBe(a.id);+ await expect(startWorkflowGraph(first, { changed: true }, "shared-key", context, () => undefined)).rejects.toThrow(/different graph\/input\/revision/);+ await expect(startWorkflowGraph({ ...first, revision: "changed-revision" }, {}, "shared-key", context, () => undefined)).rejects.toThrow(/different graph\/input\/revision/);+ const trigger = await startWorkflowGraph(first, {}, "shared-key", context, () => undefined, principal, { type: "manual", nodeId: "out", receivedAt: new Date().toISOString() });+ expect(trigger.id).not.toBe(a.id); await workflowGraphRunStatus(principal, trigger.id, 5000);+ });+ it("keeps legacy receipt IDs addressable and reuses only the matching graph", async () => {+ const first = await graph("Legacy"), second = await graph("Other");+ const started = await startWorkflowGraph(first, {}, "migration-key", context, () => undefined);+ await workflowGraphRunStatus(principal, started.id, 5000);+ const owner = workflowGraphOwner(principal), stored = (await readWorkflowGraphRun(owner, started.id))!;+ const legacyId = createHash("sha256").update(`${owner}:old-key`).digest("hex").slice(0, 32);+ const legacy = { ...stored, id: legacyId, idempotencyKey: "old-key", executionScope: undefined };+ await writeWorkflowGraphRun(legacy);+ expect((await startWorkflowGraph(first, {}, "old-key", context, () => undefined)).id).toBe(legacyId);+ const other = await startWorkflowGraph(second, {}, "old-key", context, () => undefined);+ expect(other.id).not.toBe(legacyId);+ await workflowGraphRunStatus(principal, other.id, 5000);+ await workflowGraphRunStatus(principal, legacyId);+ });+ it("refuses Owner-era outputs, stop and retry authority after demotion or revoke", async () => {+ const started = await startWorkflowGraph(await graph("Private"), {}, "private-key", context, () => undefined);+ await workflowGraphRunStatus(principal, started.id, 5000);+ const receipt = (await readWorkflowGraphRun(workflowGraphOwner(principal), started.id))!;+ expect(receipt.executionScope).toBe("exec");+ for (const next of ["operator", "viewer"] as const) {+ role = next;+ await expect(workflowGraphRunStatus(principal, started.id)).rejects.toThrow(/original execution authority/);+ await expect(requestWorkflowGraphStop(principal, started.id)).rejects.toThrow(/original execution authority/);+ await expect(requireWorkflowReceiptAuthority(principal, receipt)).rejects.toThrow(/original execution authority/);+ expect(JSON.stringify(await listWorkflowGraphRuns(workflowGraphOwner(principal)))).not.toContain("fixture-private-output");+ }+ role = "owner"; expect((await workflowGraphRunStatus(principal, started.id)).nodes.find(node => node.id === "out")?.output).toEqual({ text: "fixture-private-output" });+ await expect(workflowGraphRunStatus(principal, started.id, 0, "read")).rejects.toThrow(/original execution authority/);+ role = null; await expect(workflowGraphRunStatus(principal, started.id)).rejects.toThrow(/revoked/);+ });+ it("keeps even read-scoped Owner receipts private after demotion", async () => {+ const started = await startWorkflowGraph(await graph("Read only"), {}, "read-key", { ...context, scope: "read" }, () => undefined);+ await workflowGraphRunStatus(principal, started.id, 5000);+ for (const next of ["operator", "viewer"] as const) {+ role = next;+ await expect(workflowGraphRunStatus(principal, started.id)).rejects.toThrow(/original execution authority/);+ }+ });+ it("preserves an Operator's own receipt without exposing it after Viewer demotion", async () => {+ role = "operator";+ const started = await startWorkflowGraph(await graph("Operator"), {}, "operator-key", { ...context, scope: "write" }, () => undefined);+ expect((await workflowGraphRunStatus(principal, started.id, 5000)).executionRole).toBe("operator");+ role = "viewer";+ await expect(workflowGraphRunStatus(principal, started.id)).rejects.toThrow(/original execution authority/);+ });+});diff --git a/lib/workflow/graph-triggers.ts b/lib/workflow/graph-triggers.tsindex 7feada54..add03538 100644--- a/lib/workflow/graph-triggers.ts+++ b/lib/workflow/graph-triggers.ts@@ -13,7 +13,7 @@ const g=globalThis as typeof globalThis&{__msoWorkflowScheduler?:ReturnType<typefunction key(parts:string[]){return `trigger:${createHash("sha256").update(parts.join(":" )).digest("hex").slice(0,48)}`;}type Resolver=(name:string)=>CapabilityTool|undefined;async function runScheduled(principal:string,owner:string,graph:Awaited<ReturnType<typeof listWorkflowGraphTriggerSources>>[number]["graph"],node:WorkflowGraphNode,bucket:string,resolve:Resolver,capabilities?:CapabilityRuntime){- const idempotency=key([graph.id,node.id,bucket]);if(await readWorkflowGraphRun(owner,workflowGraphRunId(owner,idempotency)))return;+ const idempotency=key([graph.id,node.id,bucket]);if(await readWorkflowGraphRun(owner,workflowGraphRunId(owner,idempotency,graph.id,node.id)))return;const session=await createAgentSession(principal,"cli",{title:`Schedule: ${graph.name}`,titleSource:"auto"});const context={principal,actor:principal,sessionId:session.id,scope:"exec" as const,...(capabilities?{capabilities}:{})};await startWorkflowGraph(graph,{trigger:{type:"schedule",nodeId:node.id,bucket,at:new Date().toISOString()}},idempotency,context,resolve,principal,{type:"schedule",nodeId:node.id,receivedAt:new Date().toISOString()});diff --git a/scripts/camoufox-artifact.json b/scripts/camoufox-artifact.jsonnew file mode 100644index 00000000..16ba42d1--- /dev/null+++ b/scripts/camoufox-artifact.json@@ -0,0 +1,18 @@+{+ "version": "v156.0.1-beta.36",+ "source": "https://github.com/daijro/camoufox/releases/tag/v156.0.1-beta.36",+ "linux": {+ "x86_64": {+ "filename": "camoufox-156.0.1-beta.36-lin.x86_64.zip",+ "url": "https://github.com/daijro/camoufox/releases/download/v156.0.1-beta.36/camoufox-156.0.1-beta.36-lin.x86_64.zip",+ "archiveSha256": "72637885ee67c93466ad377831c647192f8f08fb5c6fd9279de1320b49dd2b53",+ "treeSha256": "25c143c4b71cbc8501ee51db8019d1a7f558ef4035be3cc2ca84ea1c4be4c6aa"+ },+ "arm64": {+ "filename": "camoufox-156.0.1-beta.36-lin.arm64.zip",+ "url": "https://github.com/daijro/camoufox/releases/download/v156.0.1-beta.36/camoufox-156.0.1-beta.36-lin.arm64.zip",+ "archiveSha256": "8b5fd083721c807ee2a752265683482477105052fa0e21739388b527ae067c15",+ "treeSha256": "d59fe9fbce275c71e0628d9c8e335c379d55f995c8ac63ae48143b2fcc25d49b"+ }+ }+}diff --git a/scripts/camoufox-artifact.py b/scripts/camoufox-artifact.pynew file mode 100644index 00000000..9f6dfcd9--- /dev/null+++ b/scripts/camoufox-artifact.py@@ -0,0 +1,144 @@+#!/usr/bin/env python3+"""Install and verify the reviewed Camoufox release, including its loaded libraries."""+import hashlib+import json+import os+from pathlib import Path, PurePosixPath+import platform+import shutil+import stat+import sys+import tempfile+import urllib.request+import zipfile+++def digest(stream):+ value = hashlib.sha256()+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):+ value.update(chunk)+ return value.hexdigest()+++def private_path(target, home, create=False):+ relative = target.relative_to(home)+ item = home+ for part in [None, *relative.parts]:+ if part is not None:+ item = item / part+ if create and not item.exists() and not item.is_symlink():+ item.mkdir(mode=0o700)+ info = item.lstat()+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o022:+ raise ValueError("Camoufox directory is not privately owned or is a symlink")+ if target.stat().st_mode & 0o077:+ raise ValueError("Camoufox installation directory must be private")+++def tree_digest(root):+ entries = []+ for item in sorted(root.rglob("*")):+ info = item.lstat()+ if info.st_uid != os.getuid() or info.st_mode & 0o077:+ raise ValueError("Camoufox artifact ownership or permissions changed")+ name = item.relative_to(root).as_posix()+ if stat.S_ISDIR(info.st_mode):+ entries.append([name, "dir"])+ elif stat.S_ISREG(info.st_mode) and info.st_nlink == 1:+ with item.open("rb") as stream:+ entries.append([name, "file", bool(info.st_mode & 0o100), digest(stream)])+ else:+ raise ValueError("Camoufox artifact must contain only regular files and directories")+ return hashlib.sha256(json.dumps(entries, separators=(",", ":")).encode()).hexdigest()+++def verify(root, home, expected):+ private_path(root, home)+ if tree_digest(root) != expected:+ raise ValueError("Camoufox installation does not match the reviewed release")+ browser = root / "camoufox"+ if not browser.stat().st_mode & 0o100:+ raise ValueError("Camoufox browser is not executable")+ return browser+++def archive_entries(archive):+ entries = archive.infolist()+ names = set()+ for entry in entries:+ name = PurePosixPath(entry.filename)+ mode = entry.external_attr >> 16+ if (name.is_absolute() or ".." in name.parts or "\\" in entry.filename or+ not name.parts or str(name) in names or+ not (stat.S_ISREG(mode) or stat.S_ISDIR(mode))):+ raise ValueError("Unsafe Camoufox archive entry")+ names.add(str(name))+ return entries+++def install(root, home, pin):+ private_path(root.parent, home, create=True)+ if root.exists() or root.is_symlink():+ return verify(root, home, pin["treeSha256"])+ cache = home / ".mso/private/camoufox-artifacts"+ private_path(cache, home, create=True)+ archive_path = cache / pin["filename"]+ if not archive_path.exists():+ fd, temporary = tempfile.mkstemp(prefix="download-", dir=cache)+ try:+ with os.fdopen(fd, "wb") as output, urllib.request.urlopen(pin["url"], timeout=60) as response:+ shutil.copyfileobj(response, output)+ os.rename(temporary, archive_path)+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)+ info = archive_path.lstat()+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077 or info.st_nlink != 1:+ raise ValueError("Unsafe Camoufox archive file")+ with archive_path.open("rb") as stream:+ if digest(stream) != pin["archiveSha256"]:+ raise ValueError("Camoufox archive checksum does not match the reviewed release")+ stage = Path(tempfile.mkdtemp(prefix="install-", dir=root.parent))+ try:+ with zipfile.ZipFile(archive_path) as archive:+ for entry in archive_entries(archive):+ target = stage / entry.filename+ if entry.is_dir():+ target.mkdir(parents=True, exist_ok=True, mode=0o700)+ else:+ target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)+ with archive.open(entry) as source, target.open("xb") as output:+ shutil.copyfileobj(source, output)+ target.chmod(0o700 if entry.external_attr >> 16 & 0o111 else 0o600)+ verify(stage, home, pin["treeSha256"])+ os.rename(stage, root)+ finally:+ if stage.exists():+ shutil.rmtree(stage)+ return verify(root, home, pin["treeSha256"])+++def main():+ if sys.argv[1:] not in (["install"], ["verify"]):+ raise ValueError("Usage: camoufox-artifact.py install|verify")+ if sys.platform != "linux":+ raise ValueError("Reviewed Camoufox artifacts require Linux")+ pins = json.loads(Path(__file__).with_name("camoufox-artifact.json").read_text())+ arch = {"aarch64": "arm64", "x86_64": "x86_64"}.get(platform.machine())+ if arch not in pins["linux"]:+ raise ValueError("No reviewed Camoufox artifact for this architecture")+ home = Path.home()+ root = home / ".mso/private/camoufox" / (pins["version"] + "-" + arch)+ if os.environ.get("CAMOUFOX_BROWSER") not in (None, "", str(root / "camoufox")):+ raise ValueError("CAMOUFOX_BROWSER must name the reviewed installation; arbitrary cache executables are refused")+ pin = pins["linux"][arch]+ browser = install(root, home, pin) if sys.argv[1] == "install" else verify(root, home, pin["treeSha256"])+ print(browser)+++if __name__ == "__main__":+ try:+ main()+ except (ValueError, OSError, zipfile.BadZipFile) as error:+ print("camoufox-artifact: " + str(error), file=sys.stderr)+ sys.exit(1)diff --git a/scripts/camoufox-artifact.test.ts b/scripts/camoufox-artifact.test.tsnew file mode 100644index 00000000..af410c2b--- /dev/null+++ b/scripts/camoufox-artifact.test.ts@@ -0,0 +1,54 @@+import { spawnSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { expect, it } from "vitest";++it("accepts only a complete privately owned reviewed browser tree", () => {+ const temporary = mkdtempSync(path.join(os.tmpdir(), "mso-camoufox-artifact-"));+ try {+ const fixture = path.join(temporary, "check.py");+ writeFileSync(fixture, `import importlib.util, pathlib, os, stat, zipfile, io+from unittest.mock import patch+spec = importlib.util.spec_from_file_location('artifact', 'scripts/camoufox-artifact.py')+m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)+home = pathlib.Path(${JSON.stringify(temporary)})+root = home / 'private' / 'version'+m.private_path(root, home, create=True)+browser = root / 'camoufox'; browser.write_text('fixture-browser'); browser.chmod(0o700)+library = root / 'library.so'; library.write_text('fixture-library'); library.chmod(0o600)+expected = m.tree_digest(root)+assert m.verify(root, home, expected) == browser+def refused(action):+ try: action()+ except (ValueError, OSError): return+ raise AssertionError('unsafe artifact accepted')+library.write_text('changed'); refused(lambda: m.verify(root, home, expected)); library.write_text('fixture-library')+library.chmod(0o644); refused(lambda: m.verify(root, home, expected)); library.chmod(0o600)+with patch.object(m.os, 'getuid', return_value=os.getuid() + 1): refused(lambda: m.verify(root, home, expected))+library.unlink(); library.symlink_to(browser); refused(lambda: m.verify(root, home, expected)); library.unlink()+library.write_text('fixture-library'); library.chmod(0o600)+os.link(library, root / 'extra.so'); refused(lambda: m.verify(root, home, expected)); (root / 'extra.so').unlink()+os.mkfifo(root / 'pipe', 0o600); refused(lambda: m.verify(root, home, expected)); (root / 'pipe').unlink()+(root / 'extra').write_text('injected'); (root / 'extra').chmod(0o600); refused(lambda: m.verify(root, home, expected)); (root / 'extra').unlink()+link = home / 'link'; link.symlink_to(root, target_is_directory=True); refused(lambda: m.verify(link, home, expected))+root.chmod(0o777); refused(lambda: m.verify(root, home, expected)); root.chmod(0o700)+outside = home / 'outside'; outside.mkdir(mode=0o700)+refused(lambda: m.verify(outside, home, expected))+for name in ['../escape', '/escape', 'nested\\\\escape']:+ stream = io.BytesIO()+ with zipfile.ZipFile(stream, 'w') as archive:+ info = zipfile.ZipInfo(name); info.external_attr = (stat.S_IFREG | 0o600) << 16; archive.writestr(info, 'fixture')+ stream.seek(0)+ with zipfile.ZipFile(stream) as archive: refused(lambda: m.archive_entries(archive))+assert m.verify(root, home, expected) == browser+print('verified tree and rejected tamper, permissions, owner, symlink, hardlink, FIFO, extra files, path and unsafe ZIP')+`);+ const result = spawnSync("python3", [fixture], { encoding: "utf8", timeout: 20_000 });+ expect(result.status, result.stderr).toBe(0);+ expect(result.stdout).toContain("rejected tamper");+ const launcher = readFileSync("scripts/camoufox-vnc-service", "utf8");+ expect(launcher).toContain('camoufox-artifact.py" verify');+ expect(launcher).not.toContain('find "$HOME/.cache/camoufox');+ } finally { rmSync(temporary, { recursive: true, force: true }); }+});diff --git a/scripts/camoufox-vnc-service b/scripts/camoufox-vnc-serviceindex 597f2b23..66b6c30f 100755--- a/scripts/camoufox-vnc-service+++ b/scripts/camoufox-vnc-service@@ -17,14 +17,8 @@ PROFILE="${CAMOUFOX_PROFILE:-$HOME/.local/share/camoufox/profiles/linkedin}"# browser.startup.page=3 restores the tabs and stops there — the restored tabs come back# unloaded, so the landing state costs nothing until something is clicked.URL="${CAMOUFOX_START_URL:-}"-BROWSER="${CAMOUFOX_BROWSER:-}"-if [ -z "$BROWSER" ]; then- BROWSER="$(find "$HOME/.cache/camoufox/browsers" -type f -name camoufox -perm -u+x 2>/dev/null | sort | tail -1)"-fi-if [ -z "$BROWSER" ] || [ ! -x "$BROWSER" ]; then- echo "camoufox-vnc: no executable browser found; set CAMOUFOX_BROWSER or install Camoufox" >&2- exit 1-fi+# Verify the complete pinned release before touching the authenticated profile.+BROWSER="$(python3 "$(dirname "${BASH_SOURCE[0]}")/camoufox-artifact.py" verify)"mkdir -p "$PROFILE"# 0700, enforced every start. What is in here is a live Google session (SID,diff --git a/scripts/e2e/google-integrations.mjs b/scripts/e2e/google-integrations.mjsindex 977c31bd..23a9f9b7 100644--- a/scripts/e2e/google-integrations.mjs+++ b/scripts/e2e/google-integrations.mjs@@ -46,8 +46,11 @@ try {check(await page.getByRole("button", { name: "Connect with Google", exact: true }).isVisible(), "Native Google connect action is visible");check(await page.getByRole("textbox", { name: /Project API key/ }).count() === 0, "No Composio project-key prompt in native Google connection");await page.getByRole("combobox", { name: "Google OAuth app", exact: true }).selectOption("app");+ const priorConnect = await page.getByRole("button", { name: "Connect with Google", exact: true }).elementHandle();await page.getByRole("button", { name: "Use selected app", exact: true }).click();await expect.poll(() => requests.some(r => r.operation === "google.bind" && r.arguments?.appConnection === "app")).toBe(true);+ // Binding refreshes the card; a request receipt alone does not mean that UI has settled.+ await priorConnect.waitForElementState("hidden");check(true, "App binding uses the existing generic integration executor");await page.getByRole("button", { name: "Connect with Google", exact: true }).click();const consent = page.getByRole("link", { name: "Continue to Google", exact: true }); await expect(consent).toBeVisible();