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): resolve full assurance findings

Rahman94ce9800f80f
diff --git a/.env.example b/.env.example
index d427e93d..fa13dc15 100644
--- a/.env.example
+++ b/.env.example
@@ -58,6 +58,10 @@ OS_SESSION_SECRET=
# Official OpenAI API key. It may instead be saved through Settings → AI under
# provider OpenAI; the 0600 host credential store wins over this env fallback.
# OPENAI_API_KEY=
+# Custom provider base URLs require HTTPS and public DNS/IP destinations. Set this
+# only for an explicitly trusted loopback/LAN development endpoint; production
+# requests still apply destination validation and redirect controls.
+# OS_CUSTOM_PROVIDER_ALLOW_INSECURE_HTTP=0
#
# Provider-run tools the Codex backend may use, comma/space separated. EMPTY by
# default — no provider built-in is declared unless you name one here. Allowed:
@@ -77,8 +81,12 @@ OS_SESSION_SECRET=
# NINE_ROUTER_DASHBOARD_URL=http://127.0.0.1:20128
# Existing browser-facing 9Router URL, if the deployment already owns one. This is
# preferred for the in-shell UI; do not create a new subdomain just because MSO can.
-# Without it, MSO may use its split-origin host or the public-IP:20128 fallback.
+# Without it, MSO may use its split-origin host. There is no public-IP fallback
+# unless the operator explicitly enables the Docker bind below.
# NINE_ROUTER_PUBLIC_URL=https://9-router.example.com
+# Default 0: publish 127.0.0.1:20128 only. Set 1 only with a deliberate firewall/auth
+# decision; this exposes 9Router's credential-bearing dashboard on every interface.
+# NINE_ROUTER_EXPOSE_PUBLIC=0
# Hermes install home. Default ~/.hermes. Absolute, or "~/…" for the home of the
# user running mso. This is the tree the managed-app backup action copies.
# HERMES_HOME=/home/you/.hermes
@@ -98,9 +106,8 @@ OS_SESSION_SECRET=
# --- Embedded managed-app dashboards: optional split-origin decision ---
# Unset (default) = MSO does not EMBED vendor web UIs. Managed-app lifecycle and
-# Details still work without a domain. 9Router's Docker/VPS install can additionally
-# advertise http://<public-ip>:20128 directly; that public-IP path does not depend on
-# any variables in this section.
+# Details still work without a domain. 9Router remains loopback-only unless
+# NINE_ROUTER_EXPOSE_PUBLIC=1 is explicitly set; public-IP access is never inferred.
#
# There is no fallback to serving them under a path on the cockpit's origin. That
# mode existed and was removed: those SPAs need allow-same-origin to run at all,
@@ -113,7 +120,8 @@ OS_SESSION_SECRET=
#
# 1. NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE — `{id}` is the app id, so this
# yields hermes.mso.example.com, openclaw.mso.example.com, 9router.mso.example.com,
-# etc. Provision ONLY the explicit app hosts you actually embed; each needs its
+# and the reserved camoufox.mso.example.com viewer origin. Provision ONLY the
+# explicit hosts you use; each needs its
# own DNS record + TLS pointing at this app. On such a host the
# middleware rewrites EVERY path into that app's proxy and 404s the rest, so
# the cockpit API does not exist there.
diff --git a/README.md b/README.md
index 74f65410..bcfebe3a 100644
--- a/README.md
+++ b/README.md
@@ -58,7 +58,7 @@ For a real deployment, put MSO behind **Tailscale, a VPN, or a TLS reverse proxy
- **Manage files** — browse, upload, search, preview, rename, move, copy, zip, and delete within configured filesystem roots.
- **Inspect system health** — view live CPU, memory, disk, network, process, and uptime signals.
- **Update itself** — Settings → About shows what is on `origin/main`, lists the incoming commits, and runs the whole deploy (pull → verify the build out-of-tree → build → restart) from a button. The verification runs first on purpose: a commit that does not compile becomes a refusal, not an outage. The updater runs in the owner's systemd user manager and does not require passwordless sudo. Same thing from a shell: `mso update run`.
-- **Manage other apps on the box** — detect, start/stop/restart, health, version, logs, and state backups for separate applications you already run (Hermes, OpenClaw, 9Router), driven through their own systemd/Docker/CLI contracts. 9Router uses its configured application domain as the in-shell dashboard when available, with public IP as the no-domain fallback. See [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md).
+- **Manage other apps on the box** — detect, start/stop/restart, health, version, logs, and state backups for separate applications you already run (Hermes, OpenClaw, 9Router), driven through their own systemd/Docker/CLI contracts. 9Router uses its configured application domain or split-origin host as the in-shell dashboard; its Docker port is loopback-only unless public exposure is explicitly enabled. See [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md).
**Work** — code/text editor, browser, and media tools in the same workspace.
@@ -234,7 +234,8 @@ An authenticated MSO session can read allowed files and run commands as the user
- Approve only devices you own; device approval is an allowlist, not standards-based 2FA.
- Keep write roots narrow with `OS_FS_WRITE_ROOTS`.
- Never commit `.env.local`, API keys, or data from `~/.mso`.
-- Managed-app dashboards are not embedded by default. 9Router can use its direct public-IP port without a domain; when a application hostname is configured, that existing domain becomes its primary in-shell UI. Give each vendor UI a separate explicit hostname such as `hermes.mso.example.com`; there is no supported same-origin iframe mode.
+- Managed-app dashboards are not embedded by default. 9Router is loopback-only by default; a direct public-IP bind requires `NINE_ROUTER_EXPOSE_PUBLIC=1`, while a configured application hostname remains its preferred in-shell UI. Give each vendor UI a separate explicit hostname such as `hermes.mso.example.com`; there is no supported same-origin iframe mode.
+- Camoufox/noVNC is also never served on the cockpit origin. It uses the reserved split-origin host such as `camoufox.mso.example.com`; the legacy `/camoufox-vnc/*` path is permanently closed.
- That boundary is browser-only: a plugin installed into Hermes or OpenClaw runs inside that daemon and can run host commands according to the daemon's own trust model.
- With a model provider configured, Alfa is a tool-calling agent, not a plain chatbot. Its complete current catalog and human-approval contract are generated from `frontend/slices/assistant/host-tools/*` and documented in `frontend/slices/assistant/CONTRACT.md`; avoid copying a tool count into overview docs because the catalog changes independently of MCP.
- Everything Alfa reads — file contents, command output, process lists — is sent to your model provider, and is re-sent on every following turn of the same run. BYOK means you own the key, not that the data stays on the box.
@@ -341,7 +342,7 @@ Not currently supported:
| [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md) | Hermes/OpenClaw/9Router lifecycle, jobs, update, backup/restore and origins |
| [docs/HERMES-INTEGRATION.md](./docs/HERMES-INTEGRATION.md) | Hermes-specific managed-app behaviour |
| [docs/OPENCLAW-INTEGRATION.md](./docs/OPENCLAW-INTEGRATION.md) | OpenClaw-specific managed-app behaviour |
-| [docs/9ROUTER-INTEGRATION.md](./docs/9ROUTER-INTEGRATION.md) | 9Router server ownership, existing-domain-first in-shell UI and public-IP fallback |
+| [docs/9ROUTER-INTEGRATION.md](./docs/9ROUTER-INTEGRATION.md) | 9Router immutable-image ownership, loopback default and explicit dashboard exposure |
| [docs/MODELS-INTEGRATION.md](./docs/MODELS-INTEGRATION.md) | Alfa BYOK/custom/Codex model credentials |
| [docs/MCP.md](./docs/MCP.md) | MCP/OAuth tools, discovery, workflow memory and security internals |
| [docs/CHATGPT-PLUGIN.md](./docs/CHATGPT-PLUGIN.md) | ChatGPT custom MCP app setup + architecture/OAuth/tool/file diagrams |
diff --git a/SECURITY.md b/SECURITY.md
index 58eec965..01704c01 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -80,7 +80,7 @@ refresh the client tool snapshot when MSO's toolset signature changes. See
## Managed applications and per-app origins
-MSO can manage Hermes and OpenClaw as separate applications. They keep their own runtime,
+MSO can manage Hermes, OpenClaw and 9Router as separate applications. They keep their own runtime,
config, state and host privileges. MSO can install them, control lifecycle, read logs,
update, back up, restore and conservatively uninstall through explicit managed-app paths.
Restore is the intentional exception to the general rule that MSO should not edit another
@@ -105,6 +105,17 @@ On a managed-app hostname every request is routed only into that app's proxy and
pages/API/static chunks are not served there. Keep DNS explicit; do not point arbitrary
wildcards inside the shared cookie domain at MSO.
+Camoufox/noVNC uses the same browser-realm principle through the reserved `camoufox` host in
+that namespace. The host accepts only approved-session GET/HEAD requests, strips cockpit
+cookies/authorization before loopback noVNC, and applies a restrictive CSP. The old
+`/camoufox-vnc/*` cockpit path is permanently closed. Revoking an approved device also stops the
+Camoufox service cgroup so an already-established VNC WebSocket is evicted.
+
+Managed-app installation is also fail-closed. Hermes installer bytes and checkout commit,
+OpenClaw package bytes/version, and the 9Router image digest are committed in
+`security/managed-app-artifacts.env` and verified before execution. 9Router binds to loopback by
+default; `NINE_ROUTER_EXPOSE_PUBLIC=1` is an explicit operator exception, not an inferred fallback.
+
This is a browser-realm boundary only. A plugin installed **inside Hermes or OpenClaw**
runs with that daemon's host privileges. Installing an untrusted daemon plugin is equivalent
to trusting code with that user's capabilities; iframe origin separation does not sandbox
diff --git a/app/api/assistant/route.ts b/app/api/assistant/route.ts
index 28ab9d94..1a474160 100644
--- a/app/api/assistant/route.ts
+++ b/app/api/assistant/route.ts
@@ -11,6 +11,7 @@ import {
} from "@/lib/config/store";
import { resolveModel } from "@/lib/models";
import { streamOpenAI } from "@/lib/ai/openai-stream";
+import { safeProviderFetch } from "@/lib/host/ssrf";
import { ensureFreshCodex } from "@/lib/ai/oauth/codex";
import { streamCodex } from "@/lib/ai/codex-stream";
import { recall } from "@/lib/ai/memory";
@@ -150,6 +151,7 @@ export async function POST(req: Request) {
// Empty means "let the caller surface that nothing is selected".
const codexModel = cfg.model || "";
let resolved: Awaited<ReturnType<typeof resolveModel>> | null = null;
+ let customProvider = false;
let codexBundle: Awaited<ReturnType<typeof readOAuthBundle>> = null;
if (isCodex) {
const b = await readOAuthBundle("openai-codex");
@@ -165,6 +167,7 @@ export async function POST(req: Request) {
// Custom providers resolve against their own baseUrl+protocol; built-ins pass
// null and stay registry-pinned (a key can't be redirected to another host).
const custom = await selectedCustomConn();
+ customProvider = Boolean(custom);
resolved = await resolveModel(await resolveModelRef(), {
store: hostCredentialStore(),
baseUrl: custom?.baseUrl,
@@ -177,16 +180,17 @@ export async function POST(req: Request) {
}
// Anthropic streams via its SDK; openai-protocol providers via our adapter; Codex
// via the ChatGPT backend. All emit the same neutral delta|tool_use|done|error vocab.
- const anthropic = new Anthropic({ apiKey: resolved?.apiKey ?? "", baseURL: resolved?.baseUrl });
+ const anthropic = new Anthropic({ apiKey: resolved?.apiKey ?? "", baseURL: resolved?.baseUrl,
+ ...(customProvider ? { fetch: safeProviderFetch } : {}) });
// Host-side system augmentation: recall cross-session memory relevant to the
// latest user turn + apply the owner's token-saver style. Applies to every
// provider path (codex / anthropic / openai).
const lastUser = [...rawMessages].reverse().find((m) => m.role === "user");
const recalled = await recall(lastUser && lastUser.role === "user" ? lastUser.text : "");
- // Framed as DATA, deliberately. These lines are written by the memory.remember
- // tool, which runs without an approval card, so any file or command output Alfa
- // reads can propose a "fact" — and unlike a tool result it would then reappear in
+ // Framed as DATA, deliberately. These lines are written only after the owner
+ // approves the exact memory.remember text, but unlike a one-turn tool result they
+ // can reappear in
// the SYSTEM prompt of every later turn, in every thread. The fence does not make
// that safe, it makes it inert as an instruction.
if (recalled.length)
@@ -250,7 +254,10 @@ export async function POST(req: Request) {
// openai-protocol: the adapter POSTs {baseUrl}/chat/completions
// {stream:true} with the host-gated BYOK key and emits the same events.
// req.signal cancels the upstream fetch (billing cutoff on abort).
- await streamOpenAI({ resolved, messages: rawMessages, tools, system: sys, signal: req.signal, emit });
+ await streamOpenAI({
+ resolved, messages: rawMessages, tools, system: sys, signal: req.signal, emit,
+ ...(customProvider ? { fetchImpl: safeProviderFetch } : {}),
+ });
}
} catch (err) {
// Abort isn't an error to report — the consumer is already gone.
diff --git a/app/api/auth/devices/route.test.ts b/app/api/auth/devices/route.test.ts
new file mode 100644
index 00000000..2c2c9aed
--- /dev/null
+++ b/app/api/auth/devices/route.test.ts
@@ -0,0 +1,68 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+
+const mocks = vi.hoisted(() => ({
+ requireSession: vi.fn(async () => true),
+ approveDevice: vi.fn(async () => {}),
+ isApproved: vi.fn(async () => true),
+ revokeDevice: vi.fn(async () => {}),
+ listDevices: vi.fn(async () => ({ approved: {}, pending: {} })),
+ terminate: vi.fn(async () => {}),
+}));
+
+vi.mock("@/lib/auth/require-session", () => ({ requireSession: mocks.requireSession }));
+vi.mock("@/lib/auth/device-store", () => ({
+ approveDevice: mocks.approveDevice,
+ isApproved: mocks.isApproved,
+ revokeDevice: mocks.revokeDevice,
+ listDevices: mocks.listDevices,
+ isValidDeviceId: (value: unknown) => typeof value === "string" && /^[a-f0-9-]{16,128}$/i.test(value),
+}));
+vi.mock("@/lib/camoufox/service", () => ({ terminateCamoufoxSessions: mocks.terminate }));
+
+const DEVICE = "a".repeat(32);
+const post = (body: unknown) => new NextRequest("https://mso.example/api/auth/devices", {
+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
+});
+
+beforeEach(() => {
+ for (const mock of Object.values(mocks)) mock.mockClear();
+ mocks.requireSession.mockResolvedValue(true);
+ mocks.isApproved.mockResolvedValue(true);
+ mocks.terminate.mockResolvedValue(undefined);
+});
+
+describe("device revocation runtime teardown", () => {
+ it("revokes first, then terminates every live Camoufox socket", async () => {
+ const { POST } = await import("./route");
+ const res = await POST(post({ action: "revoke", deviceId: DEVICE }));
+ expect(res.status).toBe(200);
+ expect(mocks.revokeDevice).toHaveBeenCalledWith(DEVICE);
+ expect(mocks.terminate).toHaveBeenCalledOnce();
+ expect(mocks.revokeDevice.mock.invocationCallOrder[0]).toBeLessThan(mocks.terminate.mock.invocationCallOrder[0]);
+ });
+
+ it("does not stop the browser when removing only a pending device", async () => {
+ mocks.isApproved.mockResolvedValue(false);
+ const { POST } = await import("./route");
+ expect((await POST(post({ action: "revoke", deviceId: DEVICE }))).status).toBe(200);
+ expect(mocks.revokeDevice).toHaveBeenCalledOnce();
+ expect(mocks.terminate).not.toHaveBeenCalled();
+ });
+
+ it("reports partial failure honestly while keeping the device revoked", async () => {
+ mocks.terminate.mockRejectedValue(new Error("user bus unavailable"));
+ const { POST } = await import("./route");
+ const res = await POST(post({ action: "revoke", deviceId: DEVICE }));
+ expect(res.status).toBe(503);
+ await expect(res.json()).resolves.toEqual({ error: "device_revoked_browser_teardown_failed", revoked: true });
+ expect(mocks.revokeDevice).toHaveBeenCalledOnce();
+ });
+
+ it("does not touch browser runtime during approval", async () => {
+ const { POST } = await import("./route");
+ expect((await POST(post({ action: "approve", deviceId: DEVICE, label: "phone" }))).status).toBe(200);
+ expect(mocks.approveDevice).toHaveBeenCalledWith(DEVICE, "phone");
+ expect(mocks.terminate).not.toHaveBeenCalled();
+ });
+});
diff --git a/app/api/auth/devices/route.ts b/app/api/auth/devices/route.ts
index a1cd33ec..a7d34e10 100644
--- a/app/api/auth/devices/route.ts
+++ b/app/api/auth/devices/route.ts
@@ -1,11 +1,13 @@
import { NextRequest, NextResponse } from "next/server";
import {
approveDevice,
+ isApproved,
isValidDeviceId,
listDevices,
revokeDevice,
} from "@/lib/auth/device-store";
import { requireSession } from "@/lib/auth/require-session";
+import { terminateCamoufoxSessions } from "@/lib/camoufox/service";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
@@ -38,7 +40,20 @@ export async function POST(req: NextRequest) {
if (action === "approve") {
await approveDevice(deviceId, typeof label === "string" ? label : undefined);
} else if (action === "revoke") {
+ const wasApproved = await isApproved(deviceId);
+ // Revoke first: after this write, the target device cannot start a new viewer
+ // or reconnect. Then tear down the shared VNC unit to evict any live socket.
await revokeDevice(deviceId);
+ if (wasApproved) {
+ try {
+ await terminateCamoufoxSessions();
+ } catch {
+ return NextResponse.json(
+ { error: "device_revoked_browser_teardown_failed", revoked: true },
+ { status: 503, headers: { "Cache-Control": "no-store" } },
+ );
+ }
+ }
} else {
return NextResponse.json({ error: "action must be approve or revoke" }, { status: 400 });
}
diff --git a/app/api/config/route.ts b/app/api/config/route.ts
index 648ec8de..58add928 100644
--- a/app/api/config/route.ts
+++ b/app/api/config/route.ts
@@ -13,7 +13,7 @@ import {
removeOAuthBundle,
} from "@/lib/config/store";
import { defaultModelFor } from "@/lib/models/defaults";
-import { assertSafeUrl } from "@/lib/host/ssrf";
+import { resolveSafeProviderEndpoint } from "@/lib/host/ssrf";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
@@ -99,7 +99,7 @@ export async function POST(req: NextRequest) {
if (!c.apiKey || !c.apiKey.trim()) return NextResponse.json({ error: "API key is required" }, { status: 400 });
let safe: URL;
try {
- safe = assertSafeUrl(String(c.baseURL ?? c.baseUrl ?? ""));
+ safe = (await resolveSafeProviderEndpoint(String(c.baseURL ?? c.baseUrl ?? ""))).url;
} catch (e) {
return NextResponse.json({ error: (e as Error).message }, { status: 400 });
}
diff --git a/app/api/models/test/route.ts b/app/api/models/test/route.ts
index 27f9fbe8..8f0e2a59 100644
--- a/app/api/models/test/route.ts
+++ b/app/api/models/test/route.ts
@@ -3,6 +3,7 @@ import Anthropic from "@anthropic-ai/sdk";
import { requireSession } from "@/lib/auth/require-session";
import { resolveModelRef, hostCredentialStore, selectedCustomConn } from "@/lib/config/store";
import { resolveModel } from "@/lib/models";
+import { safeProviderFetch } from "@/lib/host/ssrf";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
@@ -14,8 +15,10 @@ export async function POST() {
if (!(await requireSession())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
let resolved;
+ let customProvider = false;
try {
const custom = await selectedCustomConn();
+ customProvider = Boolean(custom);
resolved = await resolveModel(await resolveModelRef(), {
store: hostCredentialStore(),
baseUrl: custom?.baseUrl,
@@ -27,10 +30,13 @@ export async function POST() {
try {
if (resolved.protocol === "anthropic") {
- const a = new Anthropic({ apiKey: resolved.apiKey, baseURL: resolved.baseUrl });
+ const a = new Anthropic({
+ apiKey: resolved.apiKey, baseURL: resolved.baseUrl,
+ ...(customProvider ? { fetch: safeProviderFetch } : {}),
+ });
await a.messages.create({ model: resolved.model, max_tokens: 1, messages: [{ role: "user", content: "ping" }] });
} else {
- const r = await fetch(`${resolved.baseUrl}/chat/completions`, {
+ const r = await (customProvider ? safeProviderFetch : fetch)(`${resolved.baseUrl}/chat/completions`, {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${resolved.apiKey}` },
body: JSON.stringify({ model: resolved.model, max_tokens: 1, messages: [{ role: "user", content: "ping" }] }),
diff --git a/app/api/skills/route.ts b/app/api/skills/route.ts
index 96e48b70..9198e61f 100644
--- a/app/api/skills/route.ts
+++ b/app/api/skills/route.ts
@@ -37,6 +37,7 @@ export async function GET(req: NextRequest) {
if (query) {
const { TOOLS } = await import("@/lib/mcp/tools");
return NextResponse.json(await searchSkillMemory(query, {
+ recipeAccess: { ownerView: true },
topK: Number(req.nextUrl.searchParams.get("top") ?? 8),
includeUntrusted: req.nextUrl.searchParams.get("include_untrusted") === "1",
toolDocs: TOOLS.map((t) => ({ name: t.name, description: t.description, scope: t.scope, inputSchema: t.inputSchema })),
@@ -45,7 +46,7 @@ export async function GET(req: NextRequest) {
const { skills, scan } = await catalogSkillsDetailed();
if (!name) {
- const recipes = (await listLearnedRecipes()).map((r) => ({
+ const recipes = (await listLearnedRecipes({ ownerView: true })).map((r) => ({
id: r.id, intent: r.intent, project: r.project, summary: r.summary, attempts: r.attempts,
successes: r.successes, failures: r.failures, fastestDurationMs: r.fastestDurationMs, updatedAt: r.updatedAt,
}));
diff --git a/app/mcp/route.test.ts b/app/mcp/route.test.ts
new file mode 100644
index 00000000..7908f424
--- /dev/null
+++ b/app/mcp/route.test.ts
@@ -0,0 +1,126 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ validateToken: vi.fn(),
+ touchToken: vi.fn(async () => {}),
+ dispatch: vi.fn(async () => ({ jsonrpc: "2.0", id: 1, result: {} })),
+ clampScope: vi.fn((scope: "read" | "write" | "exec") => scope),
+ rateLimited: vi.fn(() => false),
+ rateLimitedUntrusted: vi.fn(() => false),
+}));
+
+vi.mock("@/lib/mcp/store", () => ({
+ validateToken: mocks.validateToken,
+ touchToken: mocks.touchToken,
+}));
+vi.mock("@/lib/mcp/dispatch", () => ({
+ dispatch: mocks.dispatch,
+ isNotification: (body: unknown) => {
+ const v = body as { id?: unknown; method?: unknown } | null;
+ return Boolean(v && typeof v === "object" && !("id" in v) && typeof v.method === "string");
+ },
+ rpcError: (id: unknown, code: number, message: string) => ({ jsonrpc: "2.0", id, error: { code, message } }),
+ UNAUTHORIZED: -32001,
+ RATE_LIMITED: -32002,
+}));
+vi.mock("@/lib/mcp/scope", () => ({
+ mcpEnabled: () => true,
+ clampScope: mocks.clampScope,
+}));
+vi.mock("@/lib/mcp/origin", () => ({
+ publicOrigin: () => "https://mso.example.test",
+ clientIp: () => "127.0.0.1",
+}));
+vi.mock("@/lib/host", () => ({
+ rateLimited: mocks.rateLimited,
+ rateLimitedUntrusted: mocks.rateLimitedUntrusted,
+}));
+vi.mock("@/lib/mcp/tools", () => ({ TOOLS: [] }));
+vi.mock("@/lib/mcp/toolset", () => ({ toolsetInfo: () => ({}) }));
+
+function request(body: BodyInit, headers: Record<string, string> = {}) {
+ return new Request("https://mso.example.test/mcp", {
+ method: "POST",
+ headers: { authorization: "Bearer live-token", "content-type": "application/json", ...headers },
+ body,
+ // Required by Node when a ReadableStream is supplied; harmless for string bodies.
+ duplex: "half",
+ } as RequestInit & { duplex: "half" });
+}
+
+describe("/mcp request boundary", () => {
+ beforeEach(() => {
+ mocks.validateToken.mockReset();
+ mocks.touchToken.mockClear();
+ mocks.dispatch.mockClear();
+ mocks.clampScope.mockClear();
+ mocks.rateLimited.mockReturnValue(false);
+ mocks.rateLimitedUntrusted.mockReturnValue(false);
+ });
+ afterEach(() => vi.unstubAllEnvs());
+
+ it("rejects an invalid bearer before opening the request body", async () => {
+ mocks.validateToken.mockResolvedValueOnce(null);
+ const getReader = vi.fn(() => { throw new Error("body must not be read"); });
+ const req = {
+ headers: new Headers({ authorization: "Bearer invalid" }),
+ body: { getReader },
+ } as unknown as Request;
+ const { POST } = await import("./route");
+ const res = await POST(req);
+ expect(res.status).toBe(401);
+ expect(getReader).not.toHaveBeenCalled();
+ expect(mocks.dispatch).not.toHaveBeenCalled();
+ });
+
+ it("rejects a declared oversized body without opening its stream", async () => {
+ mocks.validateToken.mockResolvedValueOnce({ hash: "a".repeat(64), scope: "read" });
+ const { MAX_MCP_BODY_BYTES, POST } = await import("./route");
+ const getReader = vi.fn(() => { throw new Error("body must not be read"); });
+ const req = {
+ headers: new Headers({
+ authorization: "Bearer live-token",
+ "content-length": String(MAX_MCP_BODY_BYTES + 1),
+ }),
+ body: { getReader },
+ } as unknown as Request;
+ const res = await POST(req);
+ expect(res.status).toBe(413);
+ expect(getReader).not.toHaveBeenCalled();
+ expect(mocks.dispatch).not.toHaveBeenCalled();
+ });
+
+ it("aborts a chunked body once the byte ceiling is crossed", async () => {
+ mocks.validateToken.mockResolvedValueOnce({ hash: "b".repeat(64), scope: "read" });
+ const { MAX_MCP_BODY_BYTES, POST } = await import("./route");
+ const chunk = new Uint8Array(MAX_MCP_BODY_BYTES + 1);
+ const stream = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(chunk);
+ controller.close();
+ },
+ });
+ const res = await POST(request(stream));
+ expect(res.status).toBe(413);
+ expect(mocks.dispatch).not.toHaveBeenCalled();
+ });
+
+ it("clamps a previously issued token to the deployment ceiling on every call", async () => {
+ const token = { hash: "c".repeat(64), scope: "exec" as const };
+ mocks.validateToken.mockResolvedValueOnce(token);
+ mocks.clampScope.mockReturnValueOnce("read");
+ const { POST } = await import("./route");
+ const body = { jsonrpc: "2.0", id: 1, method: "tools/list" };
+ const res = await POST(request(JSON.stringify(body)));
+ expect(res.status).toBe(200);
+ expect(mocks.clampScope).toHaveBeenCalledWith("exec");
+ expect(mocks.dispatch).toHaveBeenCalledWith(body, "read", `mcp:${token.hash.slice(0, 16)}`);
+ });
+
+ it("does not acknowledge an unauthenticated notification", async () => {
+ mocks.validateToken.mockResolvedValueOnce(null);
+ const { POST } = await import("./route");
+ const res = await POST(request(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })));
+ expect(res.status).toBe(401);
+ });
+});
diff --git a/app/mcp/route.ts b/app/mcp/route.ts
index 1009d6f2..8d2d2110 100644
--- a/app/mcp/route.ts
+++ b/app/mcp/route.ts
@@ -1,6 +1,6 @@
import { dispatch, isNotification, rpcError, UNAUTHORIZED, RATE_LIMITED } from "@/lib/mcp/dispatch";
import { validateToken, touchToken } from "@/lib/mcp/store";
-import { mcpEnabled } from "@/lib/mcp/scope";
+import { clampScope, mcpEnabled } from "@/lib/mcp/scope";
import { publicOrigin, clientIp } from "@/lib/mcp/origin";
import { rateLimited, rateLimitedUntrusted } from "@/lib/host";
import { TOOLS } from "@/lib/mcp/tools";
@@ -16,6 +16,39 @@ export const dynamic = "force-dynamic";
const CALLS_PER_MIN = 120;
const CALLS_PER_DAY = 5_000;
const PREAUTH_PER_MIN = 240;
+export const MAX_MCP_BODY_BYTES = 2 * 1024 * 1024;
+
+class BodyTooLarge extends Error {}
+
+async function parseBoundedJson(req: Request): Promise<unknown> {
+ const rawLength = req.headers.get("content-length");
+ if (rawLength) {
+ const length = Number(rawLength);
+ if (Number.isFinite(length) && length > MAX_MCP_BODY_BYTES) throw new BodyTooLarge();
+ }
+
+ if (!req.body) return JSON.parse("");
+ const reader = req.body.getReader();
+ const decoder = new TextDecoder();
+ let total = 0;
+ let text = "";
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > MAX_MCP_BODY_BYTES) {
+ await reader.cancel("MCP request body too large").catch(() => {});
+ throw new BodyTooLarge();
+ }
+ text += decoder.decode(value, { stream: true });
+ }
+ text += decoder.decode();
+ return JSON.parse(text);
+ } finally {
+ reader.releaseLock();
+ }
+}
export async function POST(req: Request) {
const origin = publicOrigin(req);
@@ -33,19 +66,11 @@ export async function POST(req: Request) {
const bearer = (req.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim();
if (!bearer) return unauthorized("missing bearer token");
- let body: unknown;
- try {
- body = await req.json();
- } catch {
- return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } }, { status: 400 });
- }
-
- // Ack EVERY notification, not just notifications/initialized — a client that
- // sends notifications/cancelled hangs waiting for a response it will never get.
- if (isNotification(body)) return new Response(null, { status: 202 });
-
+ // Authenticate before reading any caller-controlled body. A rejected bearer must
+ // cost only the bounded token lookup, never a multi-megabyte JSON allocation.
const token = await validateToken(bearer);
if (!token) return unauthorized("invalid, revoked or expired MCP token");
+ const effectiveScope = clampScope(token.scope);
if (rateLimited(`mcp:tok:${token.hash}`, CALLS_PER_MIN, 60_000)) {
return Response.json(rpcError(null, RATE_LIMITED, "rate limited — retry in 60s"), { status: 429, headers: { "Retry-After": "60" } });
@@ -56,10 +81,27 @@ export async function POST(req: Request) {
return Response.json(rpcError(null, RATE_LIMITED, "daily call limit reached for this token"), { status: 429, headers: { "Retry-After": "3600" } });
}
+ let body: unknown;
+ try {
+ body = await parseBoundedJson(req);
+ } catch (error) {
+ if (error instanceof BodyTooLarge) {
+ return Response.json(
+ { jsonrpc: "2.0", id: null, error: { code: -32600, message: "request body too large" } },
+ { status: 413, headers: { "Cache-Control": "no-store" } },
+ );
+ }
+ return Response.json({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } }, { status: 400 });
+ }
+
+ // Ack EVERY authenticated notification, not just notifications/initialized — a
+ // client that sends notifications/cancelled hangs waiting for a response otherwise.
+ if (isNotification(body)) return new Response(null, { status: 202 });
+
void touchToken(token.hash).catch(() => {});
// Same 16-char id the Settings table and `mso mcp list` show, so an audit line
// maps straight back to the token you would revoke.
- const result = await dispatch(body as Parameters<typeof dispatch>[0], token.scope, `mcp:${token.hash.slice(0, 16)}`);
+ const result = await dispatch(body as Parameters<typeof dispatch>[0], effectiveScope, `mcp:${token.hash.slice(0, 16)}`);
return Response.json(result, { status: 200, headers: { "Cache-Control": "no-store" } });
}
diff --git a/bin/mso b/bin/mso
index f1667fc2..f07ce48a 100755
--- a/bin/mso
+++ b/bin/mso
@@ -136,7 +136,9 @@ ENVF="${ENV_OVERRIDE:-${MSO_ENV:-${OS_ENV:-$ROOT/.env.local}}}"
set -a; . "$ENVF" 2>/dev/null || true; set +a
need() { command -v "$1" >/dev/null || die "missing dependency: $1"; }
-need curl; need jq
+need curl; need jq; need realpath; need stat; need mktemp; need sha256sum
+# shellcheck source=scripts/lib/private-state.sh
+. "$ROOT/scripts/lib/private-state.sh"
# ── local ops (no HTTP, no login) ───────────────────────────────────────────
# These edit ~/.mso/auth-devices.json on THIS machine. They are deliberately local
@@ -165,8 +167,12 @@ cli_device() {
}
# Jar is per-base as well as per-user: switching --base must not reuse a cookie
-# minted for a different origin (it would 401 and look like a broken password).
-JAR="${MSO_JAR:-${TMPDIR:-/tmp}/mso-$(id -u)-$(printf '%s' "$B" | cksum | cut -d' ' -f1).jar}"
+# minted for a different origin. Live bearer material belongs only in an owner-only
+# directory, never a predictable shared /tmp name.
+PRIVATE_STATE_ROOT="${MSO_PRIVATE_STATE_DIR:-$HOME/.mso/private}"
+BASE_KEY=$(printf '%s' "$B" | sha256sum | cut -c1-32)
+JAR_REQUESTED="${MSO_JAR:-$PRIVATE_STATE_ROOT/cli/cookies/$BASE_KEY.jar}"
+JAR=$(mso_private_state_ensure_file "$JAR_REQUESTED") || die "refusing unsafe cookie jar: $JAR_REQUESTED"
# proxy.ts blocks mutating /api requests that can't prove same-origin. A browser
# proves it with Sec-Fetch-Site; the documented fallback for non-browser clients
@@ -177,12 +183,9 @@ ORIGIN=(-H "origin: $B")
login() {
local d code; d=$(cli_device)
[ -n "$PASS" ] || die "no OS_LOGIN_PASSWORD in $ENVF (or export MSO_PASSWORD)"
- # Create the jar 0600 BEFORE curl does. `curl -c` creates it 0644 & ~umask, and it
- # holds a live session cookie whose path is fully derivable (uid + cksum of base).
- # Any other account on the host could replay it against /api/v1/exec/run — which is
- # a shell as this user, bypassing every HttpOnly/Secure/SameSite/HMAC guarantee the
- # cookie itself carries.
- [ -f "$JAR" ] || { : > "$JAR"; chmod 600 "$JAR"; }
+ # Revalidate immediately before curl writes a live bearer. The private-state helper
+ # rejects symlinks, non-regular files, another owner, and any mode other than 0600.
+ JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
# Body over stdin, never argv: a `-d "$(jq …)"` expansion puts the cleartext
# password in curl's /proc/<pid>/cmdline for the life of the request.
code=$(jq -n --arg p "$PASS" --arg d "$d" '{password:$p,deviceId:$d,deviceLabel:"mso cli"}' \
@@ -197,18 +200,26 @@ login() {
# local-only and must keep working while the service is down or unapproved.
req() {
local out code body
- [ -f "$JAR" ] || login
+ JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ [ -s "$JAR" ] || login
+ JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
out=$(curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' "$@" || true)
code="${out##*$'\n'}"; body="${out%$'\n'*}"
if [ "$code" = "401" ] || [ "$code" = "403" ]; then
login
+ JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
out=$(curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' "$@" || true)
code="${out##*$'\n'}"; body="${out%$'\n'*}"
fi
case "$code" in 2*) printf '%s' "$body" ;; *) die "request failed ($code): $body" ;; esac
}
# Binary-safe variant: streams straight to stdout, no capture, no code check.
-reqraw() { [ -f "$JAR" ] || login; curl -fsS -b "$JAR" "${ORIGIN[@]}" "$@"; }
+reqraw() {
+ JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ [ -s "$JAR" ] || login
+ JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ curl -fsS -b "$JAR" "${ORIGIN[@]}" "$@"
+}
enc() { jq -rn --arg v "$1" '$v|@uri'; }
jget() { req "$B$1"; }
@@ -227,6 +238,7 @@ json_arg() { jq -e . >/dev/null 2>&1 <<<"${1-}" || die "not valid JSON: ${1-}";
secret_post() {
local route="$1" body="$2" out code payload
login
+ JAR=$(mso_private_state_validate_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
out=$(printf '%s' "$body" | curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' \
-H 'content-type: application/json' -d @- "$B$route" || true)
code="${out##*$'\n'}"; payload="${out%$'\n'*}"
@@ -548,7 +560,12 @@ case "$cmd" in
chk "device known" "dev_script --list | grep -q '$d'" "this CLI device is not approved — mso device approve $d 'mso cli'" ;;
*) echo " -- device known (skipped: --base is remote; check it on that host)" ;;
esac
- chk "session" "[ \"\$(rm -f '$JAR'; jget /api/auth/me | jq -r .authenticated)\" = true ]" "cannot sign in — see the checks above"
+ fresh_session_check() {
+ mso_private_state_remove_file "$JAR" || return 1
+ JAR=$(mso_private_state_ensure_file "$JAR") || return 1
+ [ "$(jget /api/auth/me | jq -r .authenticated)" = true ]
+ }
+ chk "session" "fresh_session_check" "cannot sign in — see the checks above"
echo
[ "$fails" -eq 0 ] && echo "all good." || echo "$fails check(s) failed."
exit $(( fails > 0 ? 1 : 0 )) ;;
@@ -711,9 +728,12 @@ case "$cmd" in
jget "/api/v1/sys/audit?$q" ;;
whoami) echo "cli device: $(cli_device)"; jget "/api/auth/me" ;;
- login) rm -f "$JAR"; login; echo "logged in as device $(cli_device)" ;;
- logout) [ -f "$JAR" ] && jpost "/api/auth/logout" >/dev/null 2>&1 || true
- rm -f "$JAR"; echo "signed out (jar cleared)" ;;
+ login) mso_private_state_remove_file "$JAR" || die "refusing unsafe cookie jar: $JAR"
+ JAR=$(mso_private_state_ensure_file "$JAR") || die "refusing unsafe cookie jar: $JAR"
+ login; echo "logged in as device $(cli_device)" ;;
+ logout) if [ -s "$JAR" ]; then jpost "/api/auth/logout" >/dev/null 2>&1 || true; fi
+ mso_private_state_remove_file "$JAR" || die "refusing unsafe cookie jar: $JAR"
+ echo "signed out (jar cleared)" ;;
# ── service (local systemd) ──────────────────────────────────────────────
service)
diff --git a/bin/mso.test.ts b/bin/mso.test.ts
index cf899abe..9124999b 100644
--- a/bin/mso.test.ts
+++ b/bin/mso.test.ts
@@ -133,7 +133,7 @@ describe("bin/mso", () => {
const withStore = (...args: string[]) =>
execFileSync(CLI, args, {
encoding: "utf8",
- env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store },
+ env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store, MSO_SYSTEMCTL_BIN: "/bin/true" },
});
// Revoking everything signs every browser out; one keystroke from `revoke <id>`.
@@ -166,7 +166,7 @@ describe("bin/mso", () => {
expect(() =>
execFileSync(CLI, ["device", "approve", id, "test"], {
encoding: "utf8",
- env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store },
+ env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store, MSO_SYSTEMCTL_BIN: "/bin/true" },
}),
).toThrow();
expect(fs.readFileSync(store, "utf8")).toBe(corrupt);
@@ -191,7 +191,7 @@ describe("bin/mso", () => {
const withStore = (...args: string[]) =>
execFileSync(CLI, args, {
encoding: "utf8",
- env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store },
+ env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store, MSO_SYSTEMCTL_BIN: "/bin/true" },
});
const list = withStore("device", "list");
@@ -219,7 +219,7 @@ describe("bin/mso", () => {
const withStore = (...args: string[]) =>
execFileSync(CLI, args, {
encoding: "utf8",
- env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store },
+ env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store, MSO_SYSTEMCTL_BIN: "/bin/true" },
});
seed();
diff --git a/claude-skills/mso-image-editor/image-editor.sh b/claude-skills/mso-image-editor/image-editor.sh
index 6a985793..3c6b481a 100755
--- a/claude-skills/mso-image-editor/image-editor.sh
+++ b/claude-skills/mso-image-editor/image-editor.sh
@@ -17,12 +17,17 @@
# sidecar, deleted 2026-08-10. Use /mso-camoufox.
#
# k=v values coerce: 12 / 1.5 → number, true/false → bool, else string.
-# Session file: $OS_EDITOR_SESSION (default $TMPDIR/mso-image-editor.session.json).
+# Session file: $OS_EDITOR_SESSION (default ~/.mso/private/image-editor/session.json).
set -euo pipefail
B="${OS_BASE:-http://127.0.0.1:4005}"
SCRIPT_REAL="$(readlink -f "$0")"
MSO_ROOT="${MSO_DIR:-$(cd "$(dirname "$SCRIPT_REAL")/../.." && pwd)}"
+for dep in curl jq realpath stat mktemp sha256sum; do
+ command -v "$dep" >/dev/null 2>&1 || { echo "missing dependency: $dep" >&2; exit 1; }
+done
+# shellcheck source=scripts/lib/private-state.sh
+. "$MSO_ROOT/scripts/lib/private-state.sh"
ENVF="${OS_ENV:-$MSO_ROOT/.env.local}"
# shellcheck disable=SC1090
set -a; . "$ENVF" 2>/dev/null || true; set +a
@@ -36,42 +41,59 @@ DEV="${OS_DEVICE:-$(cat "$HOME/.mso/cli.device.id" 2>/dev/null)}"
# proxy.ts blocks mutating /api without same-origin proof; Origin==Host is the
# documented non-browser path.
ORIGIN=(-H "origin: $B")
-SESS="${OS_EDITOR_SESSION:-${TMPDIR:-/tmp}/mso-image-editor.session.json}"
+PRIVATE_STATE_ROOT="${MSO_PRIVATE_STATE_DIR:-$HOME/.mso/private}"
+EDITOR_STATE_DIR="$PRIVATE_STATE_ROOT/image-editor"
+SESS_REQUESTED="${OS_EDITOR_SESSION:-$EDITOR_STATE_DIR/session.json}"
+SESS=$(mso_private_state_path "$SESS_REQUESTED") || { echo "refusing unsafe editor session path: $SESS_REQUESTED" >&2; exit 1; }
[ -n "$PASS" ] || { echo "no OS_LOGIN_PASSWORD in $ENVF (set OS_PASSWORD)" >&2; exit 1; }
# Persistent cookie jar reused across invocations — log in only when the session
# is missing/expired (avoids the login rate-limiter on multi-command sequences).
-JAR="${OS_EDITOR_JAR:-${TMPDIR:-/tmp}/mso-image-editor.jar}"
+BASE_KEY=$(printf '%s' "$B" | sha256sum | cut -c1-32)
+JAR_REQUESTED="${OS_EDITOR_JAR:-$EDITOR_STATE_DIR/cookies/$BASE_KEY.jar}"
+JAR=$(mso_private_state_ensure_file "$JAR_REQUESTED") || { echo "refusing unsafe editor cookie jar: $JAR_REQUESTED" >&2; exit 1; }
EXEC="$B/api/v1/editor/exec"
login() {
local code
- # Jar created 0600 before curl touches it (curl -c would make it 0644 & ~umask) —
- # it holds a live session cookie at a fixed, guessable path. Body goes over stdin
- # so the cleartext password never lands in curl's argv.
- [ -f "$JAR" ] || { : > "$JAR"; chmod 600 "$JAR"; }
+ # Validate immediately before curl writes the live owner session. Body goes over
+ # stdin so the cleartext password never lands in curl's argv.
+ JAR=$(mso_private_state_ensure_file "$JAR") || { echo "refusing unsafe editor cookie jar: $JAR" >&2; exit 1; }
code=$(jq -n --arg p "$PASS" --arg d "$DEV" '{password:$p,deviceId:$d,deviceLabel:"os-image-editor cli"}' \
| curl -sS -o /dev/null -w '%{http_code}' -c "$JAR" "${ORIGIN[@]}" -X POST "$B/api/auth/login" \
-H 'content-type: application/json' -d @- || true)
[ "$code" = "200" ] || { printf 'login failed (%s). approve device? → node "%s" "%s"\n' "$code" "$MSO_ROOT/scripts/approve-device.js" "$DEV" >&2; exit 1; }
}
-[ -f "$JAR" ] || login
+[ -s "$JAR" ] || login
# Run a request with the cached cookie; on 401 (expired) log in once + retry.
req() {
local out code body
+ JAR=$(mso_private_state_validate_file "$JAR") || { echo "refusing unsafe editor cookie jar: $JAR" >&2; exit 1; }
out=$(curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' "$@" || true)
code="${out##*$'\n'}"; body="${out%$'\n'*}"
if [ "$code" = "401" ] || [ "$code" = "403" ]; then
- login; out=$(curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' "$@" || true)
+ login
+ JAR=$(mso_private_state_validate_file "$JAR") || { echo "refusing unsafe editor cookie jar: $JAR" >&2; exit 1; }
+ out=$(curl -sS -b "$JAR" "${ORIGIN[@]}" -w $'\n%{http_code}' "$@" || true)
code="${out##*$'\n'}"; body="${out%$'\n'*}"
fi
[ "$code" = "200" ] || { echo "request failed ($code): $body" >&2; exit 1; }
printf '%s' "$body"
}
post() { local p; p=$(cat); req -H 'content-type: application/json' -d "$p" "$EXEC"; }
-have_session() { [ -f "$SESS" ] || { echo "no session — run 'open <img>' or 'new' first" >&2; exit 1; }; }
-save_doc() { jq -e '.doc' >/dev/null <<<"$1" && jq '.doc' <<<"$1" >"$SESS"; }
+have_session() {
+ [ -e "$SESS" ] || { echo "no session — run 'open <img>' or 'new' first" >&2; exit 1; }
+ SESS=$(mso_private_state_validate_file "$SESS") || { echo "refusing unsafe editor session file: $SESS" >&2; exit 1; }
+}
+save_doc() {
+ jq -e '.doc' >/dev/null <<<"$1"
+ jq '.doc' <<<"$1" | mso_private_state_atomic_write "$SESS" >/dev/null || {
+ echo "refusing unsafe editor session file: $SESS" >&2
+ exit 1
+ }
+ SESS=$(mso_private_state_validate_file "$SESS") || exit 1
+}
show_results() { jq -r '.results[]? | " \(.name) \(if .ok then "ok" else "ERR" end) — \(.result)"' <<<"$1"; }
# Build a JSON args object from k=v pairs, coercing numbers + booleans.
diff --git a/docs/9ROUTER-INTEGRATION.md b/docs/9ROUTER-INTEGRATION.md
index 2033763b..b361da14 100644
--- a/docs/9ROUTER-INTEGRATION.md
+++ b/docs/9ROUTER-INTEGRATION.md
@@ -9,7 +9,8 @@ optional MSO dashboard proxy.
Upstream publishes both:
- npm CLI: `npm install -g 9router` then `9router`;
-- Docker: `decolua/9router:latest` with port `20128` and persistent `/app/data`.
+- Docker: upstream tag `decolua/9router:latest`, resolved by MSO to the reviewed immutable
+ digest in `security/managed-app-artifacts.env`, with port `20128` and persistent `/app/data`.
MSO uses **Docker for the managed server runtime**. The upstream README recommends Docker for
server/VPS use, and one owner avoids running two 9Router servers against the same port/data.
@@ -22,21 +23,22 @@ Default container:
```text
name: 9router
-image: decolua/9router:latest
+image: decolua/9router@sha256:<reviewed digest from security/managed-app-artifacts.env>
restart: unless-stopped
-host port: 20128 -> container 20128
+host bind: 127.0.0.1:20128 -> container 20128 (0.0.0.0 only with NINE_ROUTER_EXPOSE_PUBLIC=1)
state: ~/.9router -> /app/data
DATA_DIR: /app/data
health: GET http://127.0.0.1:20128/api/health
-version/update check: GET http://127.0.0.1:20128/api/version
+health/version display: GET http://127.0.0.1:20128/api/health and /api/version
+update identity: running RepoDigest == security/managed-app-artifacts.env
```
-MSO uses loopback for trusted internal health/version calls even though Docker publishes the
-port publicly.
+MSO uses loopback for trusted internal health/version calls. Docker does not publish the
+port publicly unless the operator explicitly opts in.
-## Domain-first UI with public-IP fallback
+## Domain/split-origin UI with explicit public-IP exception
-A 9Router installation must not depend on a domain. When MSO sees a globally-routable IPv4
+A 9Router installation must not depend on a domain. Only when `NINE_ROUTER_EXPOSE_PUBLIC=1` and MSO sees a globally-routable IPv4
on the host, its managed-app view advertises:
```text
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 39d49d0e..17ec3da8 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -166,9 +166,10 @@ detect, install, start/stop/restart, read logs, update, back up, restore and con
uninstall them. Long-running install/update/uninstall/restore work is represented as jobs
with bounded logs and status.
-A domain is not a lifecycle dependency. 9Router's Docker/server form deliberately publishes
-port 20128; a configured split-origin host is the primary in-shell dashboard, while a global IPv4 lets MSO advertise `http://<public-ip>:20128` as a
-direct separate-origin UI. Hermes/OpenClaw stay loopback-only by default.
+A domain is not a lifecycle dependency. All managed-app dashboard ports are loopback-only by
+default. 9Router can expose `http://<public-ip>:20128` only when the operator explicitly sets
+`NINE_ROUTER_EXPOSE_PUBLIC=1`; otherwise a configured application URL or split-origin host is
+the only browser-facing surface.
Embedded vendor dashboards are optional. A split-origin deployment opts in by setting
`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and `OS_SESSION_COOKIE_DOMAIN`, giving each embedded
@@ -185,8 +186,10 @@ See `docs/MANAGED-APPS.md`, `docs/HERMES-INTEGRATION.md`,
## 9. Camoufox Browser
The Browser app is a real Camoufox Firefox session on a headless X display. It is streamed
-through noVNC and proxied under `/camoufox-vnc/*` after normal MSO session verification.
-The service is a systemd **user** unit and is deliberately off by default; the UI starts it
+through noVNC on a reserved split-origin host such as `camoufox.mso.example.com`. That host
+verifies the approved device, strips cockpit cookies/authorization before upstream, and maps
+every path only to loopback noVNC. The old same-origin `/camoufox-vnc/*` route always returns
+404. The service is a systemd **user** unit and is deliberately off by default; the UI starts it
when needed. `scripts/camoufox-vnc-service` owns the launch contract.
The logged-in Firefox profile is intentionally outside `~/.mso`, under the user's local
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 1ec879b1..2b99236e 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -12,6 +12,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Fixed**
+- `security` resolve full assurance findings
- `security` raise complete component scan budget
- `security` keep Codex scan state private
- `security` block recursive credential relocation
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 3970aa43..358facb3 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -171,6 +171,12 @@ The service should be a systemd **user** unit named `camoufox-vnc.service`. It i
to stay **disabled at boot**, with `Restart=no` and a finite runtime lease; the Browser UI
powers it on only when needed.
+The noVNC document is never served on the cockpit origin. Configure
+`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` plus `OS_SESSION_COOKIE_DOMAIN`, provision the reserved
+viewer host (for example `camoufox.mso.example.com`) with DNS/TLS, and keep
+`CAMOUFOX_NOVNC_URL` loopback-only. The historical `/camoufox-vnc/*` route intentionally returns
+404; the dedicated host strips cockpit cookies and authorization before forwarding to noVNC.
+
Important paths/defaults:
- persistent logged-in profile:
diff --git a/docs/MANAGED-APPS.md b/docs/MANAGED-APPS.md
index 1b478d66..6b784abd 100644
--- a/docs/MANAGED-APPS.md
+++ b/docs/MANAGED-APPS.md
@@ -104,13 +104,16 @@ There is intentionally no `/features` endpoint.
MSO installs all three apps non-interactively through `scripts/managed-app-install` and the
same persisted job layer used for updates.
-- **Hermes/OpenClaw** use their upstream installers and user-systemd lifecycle.
-- **9Router** delegates to `scripts/managed-app-9router`, pulls `decolua/9router:latest`,
- creates `~/.9router`, and runs the container with `--restart unless-stopped`,
- `-p 20128:20128`, and `~/.9router:/app/data`.
-
-A domain is **not an install prerequisite**. In particular, 9Router is usable through the
-VPS public IP immediately after its health check succeeds. Domain-provider integrations
+- **Hermes** verifies the SHA-256 of a pinned release installer and forces the checkout to
+ the reviewed upstream commit before setup.
+- **OpenClaw** verifies the SHA-512 of an exact npm tarball before lifecycle scripts can run.
+- **9Router** delegates to `scripts/managed-app-9router`, pulls and verifies the reviewed
+ multi-architecture digest, creates `~/.9router`, and runs the container with
+ `--restart unless-stopped`, `-p 127.0.0.1:20128:20128`, and `~/.9router:/app/data`.
+
+A domain is **not an install prerequisite** for lifecycle management. 9Router's dashboard is
+loopback-only after install unless a configured URL/split-origin host exists or the operator
+explicitly sets `NINE_ROUTER_EXPOSE_PUBLIC=1`. Domain-provider integrations
(Cloudflare, Hostinger, etc.) are a separate optional concern and are not called by the
managed-app installer.
@@ -262,7 +265,7 @@ the real secret verification.
- app says "not installed" but you know it exists → check systemd-user visibility/detection
evidence before rerunning an installer;
-- 9Router is healthy but its configured `*.mso...` host fails → diagnose DNS/TLS/session-cookie state; the runtime remains healthy and the direct public-IP UI is the fallback;
+- 9Router is healthy but its configured `*.mso...` host fails → diagnose DNS/TLS/session-cookie state; the runtime remains healthy and the explicitly enabled direct public-IP UI is the fallback;
- 9Router UI button has no public URL → the host has no globally-routable IPv4 on a local
interface, or the runtime was deliberately changed to loopback/private-only networking;
- dashboard frame missing but service is healthy → split-origin embedding may be absent by
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index c7042234..e6a37b71 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -9,6 +9,32 @@ Running log of what shipped each phase. Newest at top.
> [`docs/README.md`](./README.md) and [`docs/ARCHITECTURE.md`](./ARCHITECTURE.md); keep old
> entries intact as historical evidence even when their commands/counts have been superseded.
+## 2026-08-28 (security) — full-repository Codex remediation (DONE)
+
+The first terminal Codex Security component review completed all 20 tracked-repository
+partitions and produced one High, sixteen Medium and three Low groups. Every reported group
+was traced to its actual boundary and remediated rather than suppressed: MCP now authenticates
+before bounded JSON parsing and reapplies the deployment scope ceiling on every call; durable
+Alfa memory requires approval of the exact text; learned recipes are actor-isolated; skill
+discovery is symlink-safe with authenticated, bounded cursors and one bounded semantic query
+embedding; and mutation approvals disclose the complete canonical arguments.
+
+Browser and media boundaries were hardened as well. Camoufox/noVNC moved off the cockpit origin
+to a dedicated authenticated host, strips cockpit credentials, and is torn down when a device
+is revoked. Custom provider connections resolve and validate every destination and redirect
+against private, loopback, link-local and metadata ranges. Image-editor projects and Reel media
+now enforce finite dimension, byte, sample and duration budgets before canvas allocation, decode
+or export. CLI/editor cookies and documents live only under verified owner-only 0700/0600 state
+with atomic no-symlink writes. Security-store stale recovery now uses one shared acquisition gate
+across web and CLI writers, closing the check/unlink ABA race.
+
+Managed-app execution identities are immutable: Hermes installer bytes and checkout commit, the
+exact OpenClaw package, and the 9Router OCI digest are committed and verified before execution.
+9Router binds loopback unless public exposure is explicitly enabled. The release remains
+fail-closed: full regression, isolated build, all 20 Codex components, passive ZAP, scanner gates,
+push gates and exact-SHA production health must all terminate successfully before `main` is
+promoted; skipped lanes are never reported as the ultimate result.
+
## 2026-08-28 (mcp) — bounded async exec jobs (DONE)
Added `exec_job_start`, `exec_job_status`, and `exec_job_cancel` so long test/build pipelines no longer need `systemd-run`/sentinel-file orchestration around the 30-second `exec_run` request limit. Jobs reuse the cwd jail and destructive-command filter, are actor/workflow-bound, capped at 20 minutes and four concurrent jobs per actor, cap each output stream at 1 MiB, and retain completed state for 30 minutes. Toolset is now `1.6.0` / `2026.08.28.1`: **31 tools** (16 read, 10 write, 5 exec).
diff --git a/docs/README.md b/docs/README.md
index 851e3b6f..c3f65ab8 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -31,7 +31,7 @@ machine-verifiable facts. The repository quality gate runs it automatically.
| [`MANAGED-APPS.md`](./MANAGED-APPS.md) | Hermes/OpenClaw/9Router lifecycle, jobs, backup/restore and dashboard access boundary |
| [`HERMES-INTEGRATION.md`](./HERMES-INTEGRATION.md) | Hermes-specific integration behaviour |
| [`OPENCLAW-INTEGRATION.md`](./OPENCLAW-INTEGRATION.md) | OpenClaw-specific integration behaviour |
-| [`9ROUTER-INTEGRATION.md`](./9ROUTER-INTEGRATION.md) | 9Router Docker/CLI ownership, domain-first embedded UI and public-IP fallback |
+| [`9ROUTER-INTEGRATION.md`](./9ROUTER-INTEGRATION.md) | 9Router immutable Docker ownership, loopback default and explicit dashboard exposure |
| [`MODELS-INTEGRATION.md`](./MODELS-INTEGRATION.md) | Alfa BYOK/custom/Codex provider model |
| [`SLICE-CATALOG.md`](./SLICE-CATALOG.md) | Current slice/AppShell feature inventory |
| [`TROUBLESHOOTING.md`](./TROUBLESHOOTING.md) | Symptom → cause → supported recovery |
diff --git a/docs/SECURITY-ASSURANCE.md b/docs/SECURITY-ASSURANCE.md
index 53820e9f..174567b9 100644
--- a/docs/SECURITY-ASSURANCE.md
+++ b/docs/SECURITY-ASSURANCE.md
@@ -18,10 +18,11 @@ The standing baseline is informed by **OWASP ASVS 5.0.0**. MSO does not claim an
| DAST | OWASP ZAP Baseline | Passive browser-facing scan of the live HTTPS surface | Baseline scan must complete; alert policy is reviewed before promotion |
| AI-assisted code audit | OpenAI Codex Security `scan-components` | Twenty explicit component scans covering the tracked repository, followed by cross-component root-cause matching | Every component and matching must complete; High/Critical groups fail |
| Supply chain | OpenSSF Scorecard | Public repository security posture: pinned dependencies, branch protection, review process and related heuristics | Score is published as external evidence, not self-awarded |
+| Managed-app artifact integrity | SHA-256/SHA-512 verification + OCI RepoDigest checks | Hermes release installer/checkout, exact OpenClaw tarball and 9Router multi-arch image are immutable execution identities | Any mismatch fails before installer/package/image execution |
| Dependency changes | GitHub Dependency Review | Vulnerabilities newly introduced by pull requests | High/Critical introduced dependency fails |
| SBOM | Trivy CycloneDX | Machine-readable component inventory | Generated on Security Core workflow |
-All GitHub Actions referenced by the repository are pinned to immutable commit SHAs. Scanner containers used by the reproducible local gate are pinned to image digests.
+All GitHub Actions referenced by the repository are pinned to immutable commit SHAs. Scanner containers used by the reproducible local gate are pinned to image digests. Managed-app release identities are separately recorded in `security/managed-app-artifacts.env`; moving tags are never accepted as installation identities.
## GitHub security controls
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index 64891d8d..8b5d57a1 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -125,6 +125,13 @@ x11vnc, noVNC/websockify, the VNC password file and the user systemd runtime/lin
That is the expected idle state. The user unit is intentionally not enabled at boot and has
a finite lease. Start it from Browser/Settings; stop it again when done.
+### Browser reports secure embedding is unavailable
+
+The Browser requires a reserved split-origin host. Configure
+`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and `OS_SESSION_COOKIE_DOMAIN`, then provision DNS/TLS
+for the resolved Camoufox host (for example `camoufox.mso.example.com`). Do not restore the old
+same-origin `/camoufox-vnc/*` route; it is a deliberate 404 security boundary.
+
### noVNC loads but the viewer reports missing metadata/assets
MSO's launcher builds a private runtime noVNC webroot that symlinks the distribution assets
@@ -158,7 +165,7 @@ management/log/update actions remain under Details.
### 9Router is healthy, the old hostname works, but a new `9router.mso...` host does not
-Use the direct public-IP URL first. A 9Router install does not require the new hostname. The
+Verify the loopback dashboard first (`curl http://127.0.0.1:20128/api/version`). The
`*.mso...` route belongs to optional split-origin embedding and has independent DNS/TLS,
`OS_SESSION_COOKIE_DOMAIN`, build-time host-template and re-login requirements. A `401` from
that host does not mean the 9Router container is down.
@@ -168,7 +175,8 @@ that host does not mean the 9Router container is down.
Embedded dashboards are opt-in. Confirm
`NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and `OS_SESSION_COOKIE_DOMAIN`, DNS/TLS for the
explicit app hosts, and sign in again after changing the cookie domain. With those variables
-unset, no vendor iframe is served by design. 9Router can still expose its direct public-IP UI.
+unset, no vendor iframe is served by design. A direct 9Router public-IP UI exists only when
+`NINE_ROUTER_EXPOSE_PUBLIC=1` was deliberately configured.
### Update fails before invoking the upstream updater
diff --git a/frontend/slices/appshell/components/approval-card.test.tsx b/frontend/slices/appshell/components/approval-card.test.tsx
new file mode 100644
index 00000000..c6b0c1d5
--- /dev/null
+++ b/frontend/slices/appshell/components/approval-card.test.tsx
@@ -0,0 +1,41 @@
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it, vi } from "vitest";
+import { ApprovalCard, canonicalToolInput } from "./approval-card";
+import type { ChatMessage } from "./message-bubble";
+
+function card(name: string, input: Record<string, unknown>): ChatMessage {
+ return {
+ id: "approval-test",
+ role: "tool",
+ text: "",
+ tool: { name, input, effect: "mutate", status: "pending" },
+ };
+}
+
+describe("approval argument disclosure", () => {
+ it("renders the full fs.write body before the Approve button", () => {
+ const content = `prefix-${"x".repeat(4_096)}-suffix`;
+ const html = renderToStaticMarkup(<ApprovalCard message={card("fs.write", { path: "/tmp/full.txt", content })} onResolve={vi.fn()} />);
+ expect(html).toContain("prefix-");
+ expect(html).toContain("-suffix");
+ expect(html).not.toContain(`${content.slice(0, 2_000)}…`);
+ expect(html.indexOf("-suffix")).toBeLessThan(html.indexOf("Approve"));
+ });
+
+ it("renders complete copy/delete paths without summary truncation", () => {
+ const from = `/source/${"a".repeat(600)}`;
+ const to = `/destination/${"b".repeat(600)}`;
+ const copy = renderToStaticMarkup(<ApprovalCard message={card("fs.copy", { from, to })} onResolve={vi.fn()} />);
+ const del = renderToStaticMarkup(<ApprovalCard message={card("fs.delete", { path: to })} onResolve={vi.fn()} />);
+ expect(copy).toContain(from);
+ expect(copy).toContain(to);
+ expect(del).toContain(to);
+ });
+
+ it("uses the same complete canonical object representation for generic mutations", () => {
+ const input = { text: "remember this exactly", nested: { provider: "future-provider" } };
+ const html = renderToStaticMarkup(<ApprovalCard message={card("memory.remember", input)} onResolve={vi.fn()} />);
+ for (const fragment of ["remember this exactly", "future-provider"]) expect(html).toContain(fragment);
+ expect(canonicalToolInput(input)).toBe(JSON.stringify(input, null, 2));
+ });
+});
diff --git a/frontend/slices/appshell/components/approval-card.tsx b/frontend/slices/appshell/components/approval-card.tsx
index 25d45000..0d839ca7 100644
--- a/frontend/slices/appshell/components/approval-card.tsx
+++ b/frontend/slices/appshell/components/approval-card.tsx
@@ -82,41 +82,68 @@ export function ApprovalCard({
);
}
-// Tool-specific argument display: the exact shell command / file path is what the
-// user is actually approving, so surface it clearly (not raw JSON).
+// The exact input object passed to the tool is the approval artifact. Mutation-critical
+// values are never truncated; large values stay fully present inside a bounded scroll area.
+export function canonicalToolInput(input: Record<string, unknown>): string {
+ return JSON.stringify(input, null, 2);
+}
+
+function FullValue({ children }: { children: string }) {
+ return (
+ <pre className="mt-1 max-h-48 overflow-auto whitespace-pre-wrap break-all rounded bg-background/60 px-2 py-1 font-mono text-[10px]">
+ {children}
+ </pre>
+ );
+}
+
function ToolArgs({ name, input }: { name: string; input: Record<string, unknown> }) {
if (name === "exec.run") {
return (
<div className="mt-1.5 space-y-1">
- <pre className="overflow-x-auto rounded bg-background/60 px-2 py-1 font-mono text-[11px]">$ {String(input.cmd ?? "")}</pre>
- {input.cwd ? <p className="text-[10px] text-muted-foreground">in {String(input.cwd)}</p> : null}
+ <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Exact command</p>
+ <FullValue>{String(input.cmd ?? "")}</FullValue>
+ {input.cwd !== undefined ? (
+ <><p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Working directory</p><FullValue>{String(input.cwd)}</FullValue></>
+ ) : null}
</div>
);
}
if (name === "fs.write") {
const content = String(input.content ?? "");
+ const bytes = new TextEncoder().encode(content).byteLength;
return (
<div className="mt-1.5 text-[11px]">
- <p className="font-mono">
- {String(input.path ?? "")} <span className="text-muted-foreground">({content.length} bytes)</span>
- </p>
- <details className="mt-1">
- <summary className="cursor-pointer text-muted-foreground">view content</summary>
- <pre className="mt-1 max-h-40 overflow-auto rounded bg-background/60 px-2 py-1 font-mono text-[10px]">
- {content.length > 2000 ? `${content.slice(0, 2000)}…` : content}
- </pre>
- </details>
+ <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Exact destination</p>
+ <FullValue>{String(input.path ?? "")}</FullValue>
+ <p className="mt-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Full content ({bytes} bytes)</p>
+ <FullValue>{content}</FullValue>
</div>
);
}
- if (name === "fs.move") {
+ if (name === "fs.move" || name === "fs.copy") {
return (
- <p className="mt-1.5 font-mono text-[11px]">
- {String(input.from ?? "")} → {String(input.to ?? "")}
- </p>
+ <div className="mt-1.5 text-[11px]">
+ <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Exact source</p>
+ <FullValue>{String(input.from ?? "")}</FullValue>
+ <p className="mt-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Exact destination</p>
+ <FullValue>{String(input.to ?? "")}</FullValue>
+ </div>
);
}
- const s = JSON.stringify(input);
- if (s === "{}") return null;
- return <p className="mt-1.5 font-mono text-[11px] text-muted-foreground">{s.length > 200 ? `${s.slice(0, 200)}…` : s}</p>;
+ if (name === "fs.delete" || name === "fs.mkdir") {
+ return (
+ <div className="mt-1.5 text-[11px]">
+ <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Exact path</p>
+ <FullValue>{String(input.path ?? "")}</FullValue>
+ </div>
+ );
+ }
+ const canonical = canonicalToolInput(input);
+ if (canonical === "{}") return null;
+ return (
+ <div className="mt-1.5">
+ <p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">Complete arguments</p>
+ <FullValue>{canonical}</FullValue>
+ </div>
+ );
}
diff --git a/frontend/slices/assistant/components/library-grid.test.ts b/frontend/slices/assistant/components/library-grid.test.ts
new file mode 100644
index 00000000..2795a7c6
--- /dev/null
+++ b/frontend/slices/assistant/components/library-grid.test.ts
@@ -0,0 +1,16 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { HOST_AI_TOOLS } from "../host-tools/registry";
+import { OS_TOOLS } from "../lib/tools";
+
+const source = fs.readFileSync(path.join(__dirname, "library-grid.tsx"), "utf8");
+
+describe("agent library capability labels", () => {
+ it("shows the real global catalog rather than inert per-agent skill metadata", () => {
+ expect(OS_TOOLS).toHaveLength(HOST_AI_TOOLS.length);
+ expect(source).toContain('isAgent ? OS_TOOLS.length');
+ expect(source).toContain('"global tools"');
+ expect(source).not.toContain("skills.flatMap");
+ });
+});
diff --git a/frontend/slices/assistant/components/library-grid.tsx b/frontend/slices/assistant/components/library-grid.tsx
index 84e6726a..d27a4010 100644
--- a/frontend/slices/assistant/components/library-grid.tsx
+++ b/frontend/slices/assistant/components/library-grid.tsx
@@ -25,16 +25,7 @@ export function LibraryGrid({
const isAgent = kind === "agent";
const items: (Agent | Skill)[] = isAgent ? store.agents : store.skills;
- const toolCount = (it: Agent | Skill) =>
- isAgent
- ? (it as Agent).allTools
- ? OS_TOOLS.length
- : new Set(
- (it as Agent).skills.flatMap(
- (id) => store.skills.find((x) => x.id === id)?.tools ?? [],
- ),
- ).size
- : (it as Skill).tools.length;
+ const toolCount = (it: Agent | Skill) => isAgent ? OS_TOOLS.length : (it as Skill).tools.length;
return (
<ScrollArea className="flex-1">
@@ -44,7 +35,7 @@ export function LibraryGrid({
<div className="text-base font-bold tracking-tight">{isAgent ? "Agents" : "Skills"}</div>
<div className="text-xs text-muted-foreground">
{isAgent
- ? "Personas that own skills and run tools."
+ ? "Personas share one global tool catalog; skills organize instructions, not grants."
: "Bundles of tools + instructions you give to agents."}
</div>
</div>
@@ -72,7 +63,7 @@ export function LibraryGrid({
) : null}
</div>
<div className="text-[11px] text-muted-foreground">
- {toolCount(it)} tools
+ {toolCount(it)} {isAgent ? "global tools" : "tools"}
</div>
</div>
</div>
diff --git a/frontend/slices/assistant/host-tools/catalog-mutate.ts b/frontend/slices/assistant/host-tools/catalog-mutate.ts
index 1deafc33..f910f09c 100644
--- a/frontend/slices/assistant/host-tools/catalog-mutate.ts
+++ b/frontend/slices/assistant/host-tools/catalog-mutate.ts
@@ -67,6 +67,25 @@ export const MUTATE_TOOLS: HostTool[] = [
return `deleted ${a.path}`;
},
},
+ {
+ name: "memory.remember",
+ group: "agent",
+ label: "Remember",
+ effect: "mutate",
+ description:
+ "Save the exact displayed text as durable cross-session memory. It may be recalled into future chats and sent to whichever AI provider the owner selects later, so every new memory requires explicit approval.",
+ parameters: obj({ "text!": str("The exact durable fact to remember — one concise sentence") }),
+ run: async (_api, a) => {
+ const text = String(a.text ?? "").trim();
+ if (!text) return "nothing to remember (empty text)";
+ const r = await fetch("/api/memory", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ text }),
+ });
+ return r.ok ? `remembered: ${text}` : "couldn't save the memory";
+ },
+ },
{
name: "memory.forget",
group: "agent",
diff --git a/frontend/slices/assistant/host-tools/catalog.ts b/frontend/slices/assistant/host-tools/catalog.ts
index 3372ebe5..56caf710 100644
--- a/frontend/slices/assistant/host-tools/catalog.ts
+++ b/frontend/slices/assistant/host-tools/catalog.ts
@@ -177,25 +177,6 @@ const READ_TOOLS: HostTool[] = [
},
},
...SKILL_TOOLS,
- {
- name: "memory.remember",
- group: "agent",
- label: "Remember",
- effect: "read",
- description:
- "Save a durable fact about the user or their setup to long-term memory (recalled into future chats when relevant). Use it when the user states a lasting preference, fact, or instruction worth keeping — not for one-off task details.",
- parameters: obj({ "text!": str("The fact to remember — one concise sentence") }),
- run: async (_api, a) => {
- const text = String(a.text ?? "").trim();
- if (!text) return "nothing to remember (empty text)";
- const r = await fetch("/api/memory", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ text }),
- });
- return r.ok ? `remembered: ${text}` : "couldn't save the memory";
- },
- },
];
// The catalog the rest of the app sees: read tools then mutate tools, one array.
diff --git a/frontend/slices/assistant/host-tools/registry.test.ts b/frontend/slices/assistant/host-tools/registry.test.ts
index 64b921a6..1c5f25b6 100644
--- a/frontend/slices/assistant/host-tools/registry.test.ts
+++ b/frontend/slices/assistant/host-tools/registry.test.ts
@@ -15,17 +15,15 @@ import { findHostTool, HOST_AI_TOOLS, HOST_SYSTEM } from "./registry";
describe("host-tools registry", () => {
it("classifies reads as read; fs mutations + exec as mutate", () => {
const eff = (n: string) => findHostTool(n)?.effect;
- for (const n of ["fs.list", "fs.read", "fs.search", "fs.usage", "sys.stats", "sys.processes", "apps.list", "apps.logs", "browser.status", "skills.list", "skills.read", "memory.remember"]) expect(eff(n)).toBe("read");
- for (const n of ["fs.write", "fs.mkdir", "fs.move", "fs.copy", "fs.delete", "exec.run", "memory.forget", "apps.power", "browser.power"]) expect(eff(n)).toBe("mutate");
+ for (const n of ["fs.list", "fs.read", "fs.search", "fs.usage", "sys.stats", "sys.processes", "apps.list", "apps.logs", "browser.status", "skills.list", "skills.read"]) expect(eff(n)).toBe("read");
+ for (const n of ["fs.write", "fs.mkdir", "fs.move", "fs.copy", "fs.delete", "exec.run", "memory.remember", "memory.forget", "apps.power", "browser.power"]) expect(eff(n)).toBe("mutate");
});
- it("memory.forget parks a card; memory.remember does not", () => {
- // Asymmetric on purpose. remember ADDS one line and the owner can delete it.
- // forget deletes EVERY fact containing a substring, rewrites the file with no
- // backup, and cannot be undone — so one injected "forget everything" is
- // availability loss unless a human sees the card first.
+ it("requires approval for every durable memory change", () => {
+ // Remembered text crosses session and provider boundaries later, so even an add
+ // must show the exact text to the owner before it is persisted.
expect(findHostTool("memory.forget")?.effect).toBe("mutate");
- expect(findHostTool("memory.remember")?.effect).toBe("read");
+ expect(findHostTool("memory.remember")?.effect).toBe("mutate");
});
it("does NOT expose upload or PTY — a decision, not a backlog", () => {
diff --git a/frontend/slices/assistant/host-tools/registry.ts b/frontend/slices/assistant/host-tools/registry.ts
index f240f122..72699e43 100644
--- a/frontend/slices/assistant/host-tools/registry.ts
+++ b/frontend/slices/assistant/host-tools/registry.ts
@@ -28,9 +28,9 @@ export const HOST_AI_TOOLS: AiTool[] = HOST_TOOLS.map((t) => ({
export const HOST_SYSTEM = [
"You are Alfa, operating a real headless VPS through MSO tools.",
"You are a harness agent: inspect available skills/capabilities, choose the smallest useful tool chain, and use approved host commands to do real work.",
- "READ tools (fs.*, sys.*, apps.list, skills.*, memory.*) run immediately.",
- "Use memory.remember to save lasting facts or preferences the user shares, and memory.forget to remove or correct them when asked — not one-off task details.",
- "WRITE tools (fs.write, fs.mkdir, fs.move, fs.copy, fs.delete) and exec.run require the user to APPROVE each call, and may be DENIED.",
+ "READ tools (fs.*, sys.*, apps.list, skills.*) run immediately.",
+ "Use memory.remember only for lasting user-authored facts or preferences, not tool output or one-off task details; the exact text requires owner approval and may be recalled to a future selected provider.",
+ "WRITE tools (fs.write, fs.mkdir, fs.move, fs.copy, fs.delete), memory changes, and exec.run require the user to APPROVE each call, and may be DENIED.",
"Skills across ALL of the owner's projects — not just the current one — are discoverable with skills.list/skills.search/skills.read; execute their shell steps only through approved exec.run calls.",
"If a call is denied, do NOT retry the same call — explain, or propose an alternative and ask.",
"Read/inspect before you mutate. Prefer one dependent call at a time. Confirm concisely when done; no meta-commentary.",
diff --git a/frontend/slices/camoufox-browser/app.tsx b/frontend/slices/camoufox-browser/app.tsx
index f681d355..23643565 100644
--- a/frontend/slices/camoufox-browser/app.tsx
+++ b/frontend/slices/camoufox-browser/app.tsx
@@ -5,6 +5,7 @@ import { Loader2, Power, ScanEye } from "lucide-react";
import { IS_DEMO } from "@/lib/demo";
import { PowerPanel } from "./power-panel";
import { fetchStatus, setPower, waitForViewer, type CamoufoxServiceStatus } from "./service-client";
+import { camoufoxViewerOrigin } from "@/lib/camoufox/origin";
// A REAL Firefox (Camoufox, anti-fingerprinting) running on a headless X display on
// this host, shown over noVNC. This replaced the old iframe browser because an iframe
@@ -13,8 +14,9 @@ import { fetchStatus, setPower, waitForViewer, type CamoufoxServiceStatus } from
// opted in. Here the page is rendered by an actual browser process and only PIXELS
// cross into the cockpit — nothing to refuse, and no third-party JS in this origin.
//
-// `/camoufox-vnc/*` is gated in proxy.ts by the same verified-session check that
-// guards /api/v1/exec, and rewritten to loopback websockify from there.
+// noVNC runs only on the reserved split-origin viewer host. proxy.ts verifies the
+// approved device at that host, strips cockpit credentials, and maps every path only
+// to loopback websockify; the historical same-origin /camoufox-vnc path is closed.
//
// The window OWNS the host session's power (see service-client + power-panel):
// hiding this app used to leave a browser, an Xvfb and an x11vnc running for nobody,
@@ -33,11 +35,15 @@ import { fetchStatus, setPower, waitForViewer, type CamoufoxServiceStatus } from
// for 1:1 pixels and no letterbox. It only works because a window manager now runs
// on the display (see scripts/camoufox-vnc-service) — without one the browser
// window never reflows on the RANDR change and the client gets a cropped corner.
-const VIEWER = "/camoufox-vnc/vnc.html?path=camoufox-vnc/websockify&autoconnect=1&resize=remote";
+const VIEWER_ORIGIN = camoufoxViewerOrigin();
+const VIEWER = VIEWER_ORIGIN
+ ? `${VIEWER_ORIGIN}/vnc.html?path=websockify&autoconnect=1&resize=remote`
+ : null;
/** The display's VNC password, fetched for this already-authenticated session so
* noVNC does not prompt on every open. Absent = none configured; let noVNC ask. */
-async function viewerSrc(): Promise<string> {
+async function viewerSrc(): Promise<string | null> {
+ if (!VIEWER) return null;
try {
const response = await fetch("/api/v1/camoufox/session", { cache: "no-store" });
if (response.ok) {
@@ -63,7 +69,8 @@ export default function CamoufoxBrowser() {
const [error, setError] = useState<string | null>(null);
const abort = useRef<AbortController | null>(null);
- // Connect = wait for websockify to actually answer, THEN mount the iframe. Split
+ // Connect = wait for the same-origin service API to confirm loopback noVNC readiness,
+ // THEN mount the cross-origin iframe. Split
// from the power action because it is also the mount path for a session that was
// already up before this window opened.
const connect = useCallback(async (signal: AbortSignal) => {
@@ -75,7 +82,12 @@ export default function CamoufoxBrowser() {
return;
}
const source = await viewerSrc();
- if (!signal.aborted) setSrc(source);
+ if (signal.aborted) return;
+ if (!source) {
+ setError("Secure browser embedding is unavailable until the split-origin host template is configured.");
+ return;
+ }
+ setSrc(source);
}, []);
useEffect(() => {
@@ -176,7 +188,9 @@ export default function CamoufoxBrowser() {
src={src}
title="Camoufox browser"
className="min-h-0 w-full flex-1 border-0 bg-black"
- allow="clipboard-read; clipboard-write"
+ allow="clipboard-read; clipboard-write; fullscreen"
+ sandbox="allow-scripts allow-forms allow-same-origin allow-pointer-lock allow-downloads"
+ referrerPolicy="no-referrer"
allowFullScreen
/>
) : (
diff --git a/frontend/slices/camoufox-browser/mobile-layout.test.ts b/frontend/slices/camoufox-browser/mobile-layout.test.ts
index b045474a..759dd3a4 100644
--- a/frontend/slices/camoufox-browser/mobile-layout.test.ts
+++ b/frontend/slices/camoufox-browser/mobile-layout.test.ts
@@ -7,5 +7,9 @@ describe("Camoufox mobile layout", () => {
expect(src).toContain("min-h-0 w-full flex-1 border-0 bg-black");
expect(src).toContain("overflow-hidden bg-black");
expect(src).toContain("allowFullScreen");
+ expect(src).toContain("camoufoxViewerOrigin");
+ expect(src).toContain('sandbox="allow-scripts allow-forms allow-same-origin allow-pointer-lock allow-downloads"');
+ expect(src).toContain('referrerPolicy="no-referrer"');
+ expect(src).not.toContain('src="/camoufox-vnc/');
});
});
diff --git a/frontend/slices/camoufox-browser/service-client.test.ts b/frontend/slices/camoufox-browser/service-client.test.ts
new file mode 100644
index 00000000..cda3c862
--- /dev/null
+++ b/frontend/slices/camoufox-browser/service-client.test.ts
@@ -0,0 +1,23 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { waitForViewer } from "./service-client";
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe("Camoufox viewer readiness", () => {
+ it("polls only the authenticated same-origin service status", async () => {
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({
+ installed: true, running: true, enabled: false, viewerReady: true,
+ }), { status: 200, headers: { "content-type": "application/json" } }));
+ vi.stubGlobal("fetch", fetchMock);
+ await expect(waitForViewer(new AbortController().signal, 100)).resolves.toBe(true);
+ expect(fetchMock).toHaveBeenCalledWith("/api/v1/camoufox/service", expect.objectContaining({ cache: "no-store" }));
+ expect(fetchMock).not.toHaveBeenCalledWith(expect.stringContaining("/camoufox-vnc/"), expect.anything());
+ });
+
+ it("does not treat systemd running as viewer-ready", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({
+ installed: true, running: true, enabled: false, viewerReady: false,
+ }), { status: 200, headers: { "content-type": "application/json" } })));
+ await expect(waitForViewer(new AbortController().signal, 0)).resolves.toBe(false);
+ });
+});
diff --git a/frontend/slices/camoufox-browser/service-client.ts b/frontend/slices/camoufox-browser/service-client.ts
index 4e380a52..9565adcb 100644
--- a/frontend/slices/camoufox-browser/service-client.ts
+++ b/frontend/slices/camoufox-browser/service-client.ts
@@ -5,6 +5,7 @@ export interface CamoufoxServiceStatus {
running: boolean;
enabled: boolean;
installed: boolean;
+ viewerReady?: boolean;
}
export async function fetchStatus(signal?: AbortSignal): Promise<CamoufoxServiceStatus> {
@@ -29,19 +30,16 @@ export async function setPower(on: boolean, signal?: AbortSignal): Promise<Camou
return payload;
}
-/** systemd reports `active` the instant ExecStart forks, but the unit's script then
- * brings up Xvfb, a window manager, the browser, x11vnc and only LAST websockify —
- * several seconds later. Mounting the viewer on `running` alone therefore frames a
- * 502 and the user sees a dead rectangle after clicking Start. So readiness is the
- * thing the iframe actually needs: the proxied noVNC document answering 200. */
+/** systemd reports `active` before websockify/noVNC is listening. The cockpit cannot
+ * fetch the dedicated viewer origin directly without widening CORS, so the authenticated
+ * same-origin status route performs the bounded loopback probe and returns viewerReady. */
export async function waitForViewer(signal: AbortSignal, timeoutMs = 30_000): Promise<boolean> {
const deadline = Date.now() + timeoutMs;
while (!signal.aborted) {
try {
- const response = await fetch("/camoufox-vnc/vnc.html", { cache: "no-store", signal });
- if (response.ok) return true;
+ const status = await fetchStatus(signal);
+ if (status.running && status.viewerReady) return true;
} catch {
- // Aborted, or the rewrite target refused while the unit is still coming up.
if (signal.aborted) return false;
}
if (Date.now() >= deadline) return false;
diff --git a/frontend/slices/image-editor/components/menu-bar.tsx b/frontend/slices/image-editor/components/menu-bar.tsx
index d4bd1f6f..033936a0 100644
--- a/frontend/slices/image-editor/components/menu-bar.tsx
+++ b/frontend/slices/image-editor/components/menu-bar.tsx
@@ -17,7 +17,7 @@ import { ASPECT_PRESETS, createLayer } from "../lib/model";
import { fileToDataURL, loadImage } from "../lib/image-io";
import { removeImageBackground } from "../lib/bg-removal";
import { exportStage, stageToDataURL } from "../lib/export";
-import { downloadProject, parseProject } from "../lib/project";
+import { downloadProject, parseProject, readBoundedProjectFile } from "../lib/project";
import type { LayerKind } from "../lib/types";
// Photoshop-style menu bar (desktop): File · Edit · Image · Layer · Select · View,
@@ -59,7 +59,7 @@ export function MenuBar({
const w = Math.round(img.width * k), h = Math.round(img.height * k);
addLayer(createLayer("image", { name: file.name, src, t: { x: Math.round((doc.width - w) / 2), y: Math.round((doc.height - h) / 2), width: w, height: h, rotation: 0, scaleX: 1, scaleY: 1 } }));
}
- async function openProject(file: File) { const p = parseProject(await file.text()); if (p) loadProject(p); }
+ async function openProject(file: File) { const p = parseProject(await readBoundedProjectFile(file)); if (p) loadProject(p); }
async function removeBg() {
if (!selected || selected.kind !== "image" || !selected.src) return;
setBusy(true);
diff --git a/frontend/slices/image-editor/components/project-loader.tsx b/frontend/slices/image-editor/components/project-loader.tsx
index 2e57b32d..918bd835 100644
--- a/frontend/slices/image-editor/components/project-loader.tsx
+++ b/frontend/slices/image-editor/components/project-loader.tsx
@@ -3,7 +3,7 @@
import { useEffect } from "react";
import { AlertTriangle } from "lucide-react";
import { useEditor } from "../lib/store";
-import type { Project } from "../lib/project";
+import { parseProject, readBoundedProjectResponse } from "../lib/project";
// Loads a saved Doc/Project JSON from a URL into the live store on mount —
// accepts a full Project or a bare Doc (wrapped with empty paint). Renders null.
@@ -22,22 +22,12 @@ export function ProjectLoader({
useEffect(() => {
let on = true;
fetch(src)
- .then((r) => {
- if (!r.ok) throw new Error(`Failed to load project (${r.status})`);
- return r.json();
- })
- .then((j: unknown) => {
+ .then(readBoundedProjectResponse)
+ .then((text) => {
if (!on) return;
- if (!j || typeof j !== "object") throw new Error("Project file is empty or malformed");
- const o = j as { v?: number; doc?: unknown; layers?: unknown };
- const proj: Project | null =
- o.v === 1 && o.doc
- ? (o as Project)
- : Array.isArray(o.layers)
- ? { v: 1, doc: o as Project["doc"], paint: {} }
- : null;
- if (!proj) throw new Error("Unrecognized project format");
- loadProject(proj);
+ const project = parseProject(text);
+ if (!project) throw new Error("Project file is malformed, unsafe, or exceeds editor limits");
+ loadProject(project);
onDone(true);
})
.catch((err: unknown) => {
diff --git a/frontend/slices/image-editor/components/top-bar.tsx b/frontend/slices/image-editor/components/top-bar.tsx
index ece25361..fd21a344 100644
--- a/frontend/slices/image-editor/components/top-bar.tsx
+++ b/frontend/slices/image-editor/components/top-bar.tsx
@@ -30,7 +30,7 @@ import { createLayer } from "../lib/model";
import { fileToDataURL, loadImage } from "../lib/image-io";
import { removeImageBackground } from "../lib/bg-removal";
import { stageToDataURL } from "../lib/export";
-import { downloadProject, parseProject } from "../lib/project";
+import { downloadProject, parseProject, readBoundedProjectFile } from "../lib/project";
// Compact mobile command bar: a "⋯" menu folds the less-used file actions (open,
// remove BG, project open/save) so undo/redo, zoom, and Save stay one tap away.
@@ -41,7 +41,7 @@ export function TopBar({ onSave, onSaveAs }: { onSave?: (dataUrl: string) => voi
const [busy, setBusy] = useState(false);
async function openProject(file: File) {
- const p = parseProject(await file.text());
+ const p = parseProject(await readBoundedProjectFile(file));
if (p) loadProject(p);
}
diff --git a/frontend/slices/image-editor/lib/doc-ops.ts b/frontend/slices/image-editor/lib/doc-ops.ts
index 212dba8a..d5e949a8 100644
--- a/frontend/slices/image-editor/lib/doc-ops.ts
+++ b/frontend/slices/image-editor/lib/doc-ops.ts
@@ -4,6 +4,7 @@ import { useCallback } from "react";
import type { Doc, Layer } from "./types";
import { createLayer } from "./model";
import { maskKey } from "./mask";
+import { assertImageCanvasBounds } from "./project-validation";
type SetDoc = (next: Doc | ((d: Doc) => Doc), track?: boolean) => void;
@@ -84,7 +85,10 @@ export function useDocOps(
// after a size change the brush paints onto a stale-sized buffer (and the
// mask is mis-aligned). A fix needs a re-baked canvas per paint layer + a
// paired history entry — a larger change touching the undo model, deferred.
- const setDocSize = useCallback((w: number, h: number) => setDoc((d) => ({ ...d, width: w, height: h })), [setDoc]);
+ const setDocSize = useCallback((w: number, h: number) => {
+ assertImageCanvasBounds(w, h);
+ setDoc((d) => ({ ...d, width: w, height: h }));
+ }, [setDoc]);
// Crop: resize the doc to (w,h) anchored at (x,y), shift every layer by (-x,-y),
// and re-bake each paint layer's pixels into a new (w,h) canvas at the offset.
@@ -93,6 +97,8 @@ export function useDocOps(
// restores doc dimensions but NOT the pre-crop paint pixels. A correct fix
// pairs a paint snapshot with the doc step (combined action) — deferred.
const applyCrop = useCallback((x: number, y: number, w: number, h: number) => {
+ if (![x, y].every(Number.isFinite)) throw new Error("crop origin must be finite");
+ assertImageCanvasBounds(Math.round(w), Math.round(h));
setDoc((d) => {
for (const l of d.layers) {
if (l.kind !== "paint") continue;
diff --git a/frontend/slices/image-editor/lib/headless/editor-core-security.test.ts b/frontend/slices/image-editor/lib/headless/editor-core-security.test.ts
new file mode 100644
index 00000000..831a7dc5
--- /dev/null
+++ b/frontend/slices/image-editor/lib/headless/editor-core-security.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from "vitest";
+import { createHeadlessEditor } from "./editor-core";
+import { blankDoc, createLayer } from "../model";
+import { IMAGE_EDITOR_LIMITS } from "../project-validation";
+
+describe("headless editor resource boundary", () => {
+ it("rejects unsafe initial documents", () => {
+ const doc = blankDoc();
+ doc.width = Infinity;
+ expect(() => createHeadlessEditor(doc)).toThrow(/canvas width/);
+ });
+
+ it("blocks resize and crop before committing an unsafe document", () => {
+ const editor = createHeadlessEditor(blankDoc());
+ expect(() => (editor.setDocSize as (w: number, h: number) => void)(IMAGE_EDITOR_LIMITS.maxCanvasDimension + 1, 1)).toThrow();
+ expect(() => (editor.applyCrop as (x: number, y: number, w: number, h: number) => void)(0, 0, Infinity, 100)).toThrow();
+ expect(editor.doc).toMatchObject({ width: 1080, height: 1080 });
+ });
+
+ it("enforces the layer limit on command-style mutations", () => {
+ const doc = blankDoc();
+ doc.layers = Array.from({ length: IMAGE_EDITOR_LIMITS.maxLayers }, (_, i) => createLayer("paint", { name: String(i) }));
+ const editor = createHeadlessEditor(doc);
+ expect(() => (editor.addLayer as (layer: ReturnType<typeof createLayer>) => void)(createLayer("paint"))).toThrow(/layer limit/);
+ });
+});
diff --git a/frontend/slices/image-editor/lib/headless/editor-core.ts b/frontend/slices/image-editor/lib/headless/editor-core.ts
index a176e7a6..1694e490 100644
--- a/frontend/slices/image-editor/lib/headless/editor-core.ts
+++ b/frontend/slices/image-editor/lib/headless/editor-core.ts
@@ -9,6 +9,7 @@ import type {
Tool,
} from "../types";
import { createLayer } from "../model";
+import { assertImageCanvasBounds, validateImageEditorDoc } from "../project-validation";
// A React-free editor context that implements the exact subset of the store
// surface the command registry calls (see commands/*.commands.ts). It mirrors
@@ -31,7 +32,7 @@ export type HeadlessCtx = {
} & Record<string, unknown>;
export function createHeadlessEditor(initial: Doc): HeadlessCtx {
- let doc = initial;
+ let doc = validateImageEditorDoc(initial);
let selectedId: string | null = doc.layers.at(-1)?.id ?? null;
let tool: Tool = "move";
let brush = { size: 28, color: "#111827", opacity: 1, hardness: 0.8 };
@@ -46,7 +47,7 @@ export function createHeadlessEditor(initial: Doc): HeadlessCtx {
past.push(doc);
future.length = 0;
}
- doc = n;
+ doc = validateImageEditorDoc(n);
};
const mapLayer = (id: string, fn: (l: Layer) => Layer) =>
setDoc((d) => ({ ...d, layers: d.layers.map((l) => (l.id === id ? fn(l) : l)) }));
@@ -104,14 +105,20 @@ export function createHeadlessEditor(initial: Doc): HeadlessCtx {
}),
raise: (id: string) => move(id, 1),
lower: (id: string) => move(id, -1),
- setDocSize: (w: number, h: number) => setDoc((d) => ({ ...d, width: w, height: h })),
- applyCrop: (x: number, y: number, w: number, h: number) =>
+ setDocSize: (w: number, h: number) => {
+ assertImageCanvasBounds(w, h);
+ setDoc((d) => ({ ...d, width: w, height: h }));
+ },
+ applyCrop: (x: number, y: number, w: number, h: number) => {
+ if (![x, y].every(Number.isFinite)) throw new Error("crop origin must be finite");
+ assertImageCanvasBounds(Math.round(w), Math.round(h));
setDoc((d) => ({
...d,
width: Math.round(w),
height: Math.round(h),
layers: d.layers.map((l) => ({ ...l, t: { ...l.t, x: l.t.x - x, y: l.t.y - y } })),
- })),
+ }));
+ },
update: (id: string, patch: Partial<Layer>) => mapLayer(id, (l) => ({ ...l, ...patch })),
patchStyle: (id: string, p: Partial<LayerStyle>) => mapLayer(id, (l) => ({ ...l, style: { ...l.style, ...p } })),
diff --git a/frontend/slices/image-editor/lib/image-io.ts b/frontend/slices/image-editor/lib/image-io.ts
index 08f54ec7..069a6453 100644
--- a/frontend/slices/image-editor/lib/image-io.ts
+++ b/frontend/slices/image-editor/lib/image-io.ts
@@ -1,3 +1,5 @@
+import { IMAGE_EDITOR_LIMITS } from "./project-validation";
+
// Konva-free image I/O — kept OUT of konva-helpers.ts so the editor chrome (top
// bar, menu bar) that only reads a File doesn't drag the whole Konva canvas lib
// into its chunk. Konva loads with the stage (dynamic import), not the chrome.
@@ -19,6 +21,9 @@ export function loadImage(src: string): Promise<HTMLImageElement> {
// the document unloads, so it gets serialized into autosave/Save and renders null
// after a reload. Data URLs round-trip through persistence intact.
export function fileToDataURL(file: File): Promise<string> {
+ if (file.size > IMAGE_EDITOR_LIMITS.maxPickedImageBytes) {
+ return Promise.reject(new Error("image exceeds the 16 MiB import limit"));
+ }
return new Promise((resolve, reject) => {
const r = new FileReader();
r.onload = () => resolve(r.result as string);
diff --git a/frontend/slices/image-editor/lib/model.ts b/frontend/slices/image-editor/lib/model.ts
index 8367bbb2..9e711888 100644
--- a/frontend/slices/image-editor/lib/model.ts
+++ b/frontend/slices/image-editor/lib/model.ts
@@ -6,6 +6,7 @@ import type {
LayerStyle,
Transform,
} from "./types";
+import { assertImageCanvasBounds } from "./project-validation";
// ── Defaults ────────────────────────────────────────────────────────────────
export const ADJ_DEFAULT: Adjustments = {
@@ -77,6 +78,7 @@ export function createLayer(kind: LayerKind, extra: Partial<Layer> = {}): Layer
// A blank document — one empty paint layer so the brush works immediately.
export function blankDoc(width = 1080, height = 1080): Doc {
+ assertImageCanvasBounds(width, height);
return {
width,
height,
diff --git a/frontend/slices/image-editor/lib/project-validation-values.ts b/frontend/slices/image-editor/lib/project-validation-values.ts
new file mode 100644
index 00000000..518311cd
--- /dev/null
+++ b/frontend/slices/image-editor/lib/project-validation-values.ts
@@ -0,0 +1,181 @@
+import type {
+ Adjustments,
+ BlendMode,
+ DropShadow,
+ LayerStyle,
+ OuterGlow,
+ Stroke,
+ Transform,
+} from "./types";
+
+export const IMAGE_EDITOR_LIMITS = {
+ maxCanvasDimension: 4096,
+ maxCanvasPixels: 16_777_216,
+ maxLayerDimension: 32_768,
+ maxCoordinateMagnitude: 1_000_000,
+ maxScaleMagnitude: 100,
+ maxLayers: 128,
+ maxProjectBytes: 32 * 1024 * 1024,
+ maxEmbeddedAssetBytes: 24 * 1024 * 1024,
+ maxSingleAssetBytes: 16 * 1024 * 1024,
+ maxPickedImageBytes: 16 * 1024 * 1024,
+ maxTextBytes: 256 * 1024,
+ maxStringBytes: 8 * 1024,
+} as const;
+
+export type ValidationOptions = { allowBlobImages?: boolean };
+
+const BLENDS = new Set<BlendMode>([
+ "normal", "multiply", "screen", "overlay", "darken", "lighten", "color-dodge",
+ "color-burn", "hard-light", "soft-light", "difference", "exclusion", "hue",
+ "saturation", "color", "luminosity",
+]);
+const RASTER_DATA_URL = /^data:image\/(?:png|jpe?g|webp|gif|avif);base64,/i;
+
+export function isRasterDataUrl(value: string): boolean {
+ return RASTER_DATA_URL.test(value);
+}
+
+export function utf8Bytes(value: string): number {
+ return new TextEncoder().encode(value).byteLength;
+}
+
+export function record(value: unknown, label: string): Record<string, unknown> {
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object`);
+ return value as Record<string, unknown>;
+}
+
+export function bool(value: unknown, label: string): boolean {
+ if (typeof value !== "boolean") throw new Error(`${label} must be boolean`);
+ return value;
+}
+
+export function stringValue(value: unknown, label: string, maxBytes = IMAGE_EDITOR_LIMITS.maxStringBytes): string {
+ if (typeof value !== "string") throw new Error(`${label} must be a string`);
+ if (utf8Bytes(value) > maxBytes) throw new Error(`${label} exceeds its byte limit`);
+ if (value.includes("\0")) throw new Error(`${label} contains a null byte`);
+ return value;
+}
+
+export function finite(value: unknown, label: string, min = -Infinity, max = Infinity): number {
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
+ throw new Error(`${label} must be finite and between ${min} and ${max}`);
+ }
+ return value;
+}
+
+function finiteInteger(value: unknown, label: string, min: number, max: number): number {
+ const number = finite(value, label, min, max);
+ if (!Number.isSafeInteger(number)) throw new Error(`${label} must be a safe integer`);
+ return number;
+}
+
+export function assertImageCanvasBounds(width: unknown, height: unknown): asserts width is number {
+ const w = finiteInteger(width, "canvas width", 1, IMAGE_EDITOR_LIMITS.maxCanvasDimension);
+ const h = finiteInteger(height, "canvas height", 1, IMAGE_EDITOR_LIMITS.maxCanvasDimension);
+ if (w * h > IMAGE_EDITOR_LIMITS.maxCanvasPixels) throw new Error("canvas exceeds the pixel budget");
+}
+
+export function safeCanvasSize(width: unknown, height: unknown): { width: number; height: number } {
+ assertImageCanvasBounds(width, height);
+ return { width: width as number, height: height as number };
+}
+
+export function transform(value: unknown, label: string): Transform {
+ const o = record(value, label);
+ return {
+ x: finite(o.x, `${label}.x`, -IMAGE_EDITOR_LIMITS.maxCoordinateMagnitude, IMAGE_EDITOR_LIMITS.maxCoordinateMagnitude),
+ y: finite(o.y, `${label}.y`, -IMAGE_EDITOR_LIMITS.maxCoordinateMagnitude, IMAGE_EDITOR_LIMITS.maxCoordinateMagnitude),
+ width: finite(o.width, `${label}.width`, 0, IMAGE_EDITOR_LIMITS.maxLayerDimension),
+ height: finite(o.height, `${label}.height`, 0, IMAGE_EDITOR_LIMITS.maxLayerDimension),
+ rotation: finite(o.rotation, `${label}.rotation`, -IMAGE_EDITOR_LIMITS.maxCoordinateMagnitude, IMAGE_EDITOR_LIMITS.maxCoordinateMagnitude),
+ scaleX: finite(o.scaleX, `${label}.scaleX`, -IMAGE_EDITOR_LIMITS.maxScaleMagnitude, IMAGE_EDITOR_LIMITS.maxScaleMagnitude),
+ scaleY: finite(o.scaleY, `${label}.scaleY`, -IMAGE_EDITOR_LIMITS.maxScaleMagnitude, IMAGE_EDITOR_LIMITS.maxScaleMagnitude),
+ };
+}
+
+export function color(value: unknown, label: string): string {
+ return stringValue(value, label, 256);
+}
+
+function shadow(value: unknown, label: string): DropShadow {
+ const o = record(value, label);
+ return {
+ enabled: bool(o.enabled, `${label}.enabled`),
+ color: color(o.color, `${label}.color`),
+ opacity: finite(o.opacity, `${label}.opacity`, 0, 1),
+ angle: finite(o.angle, `${label}.angle`, -360_000, 360_000),
+ distance: finite(o.distance, `${label}.distance`, 0, IMAGE_EDITOR_LIMITS.maxLayerDimension),
+ size: finite(o.size, `${label}.size`, 0, IMAGE_EDITOR_LIMITS.maxCanvasDimension),
+ };
+}
+
+function glow(value: unknown, label: string): OuterGlow {
+ const o = record(value, label);
+ return {
+ enabled: bool(o.enabled, `${label}.enabled`),
+ color: color(o.color, `${label}.color`),
+ opacity: finite(o.opacity, `${label}.opacity`, 0, 1),
+ size: finite(o.size, `${label}.size`, 0, IMAGE_EDITOR_LIMITS.maxCanvasDimension),
+ };
+}
+
+function stroke(value: unknown, label: string): Stroke {
+ const o = record(value, label);
+ return {
+ enabled: bool(o.enabled, `${label}.enabled`),
+ color: color(o.color, `${label}.color`),
+ width: finite(o.width, `${label}.width`, 0, IMAGE_EDITOR_LIMITS.maxCanvasDimension),
+ };
+}
+
+export function style(value: unknown, label: string): LayerStyle {
+ const o = record(value, label);
+ const blend = stringValue(o.blend, `${label}.blend`, 64) as BlendMode;
+ if (!BLENDS.has(blend)) throw new Error(`${label}.blend is unsupported`);
+ return {
+ blend,
+ shadow: shadow(o.shadow, `${label}.shadow`),
+ glow: glow(o.glow, `${label}.glow`),
+ stroke: stroke(o.stroke, `${label}.stroke`),
+ clipBelow: bool(o.clipBelow, `${label}.clipBelow`),
+ };
+}
+
+export function adjustments(value: unknown, label: string): Adjustments {
+ const o = record(value, label);
+ return {
+ brightness: finite(o.brightness, `${label}.brightness`, -1, 1),
+ contrast: finite(o.contrast, `${label}.contrast`, -100, 100),
+ saturation: finite(o.saturation, `${label}.saturation`, -2, 10),
+ hue: finite(o.hue, `${label}.hue`, -360_000, 360_000),
+ blur: finite(o.blur, `${label}.blur`, 0, 40),
+ grayscale: bool(o.grayscale, `${label}.grayscale`),
+ invert: bool(o.invert, `${label}.invert`),
+ sepia: bool(o.sepia, `${label}.sepia`),
+ };
+}
+
+export function imageSource(value: unknown, label: string, options: ValidationOptions): string {
+ const source = stringValue(value, label, IMAGE_EDITOR_LIMITS.maxSingleAssetBytes);
+ if (source.startsWith("data:")) {
+ if (!RASTER_DATA_URL.test(source)) throw new Error(`${label} must be a base64 raster image`);
+ return source;
+ }
+ if (options.allowBlobImages && source.startsWith("blob:")) return source;
+ if (source.startsWith("/") && !source.startsWith("//")) return source;
+ let url: URL;
+ try { url = new URL(source); } catch { throw new Error(`${label} is not an allowed image URL`); }
+ if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`${label} uses an unsupported protocol`);
+ if (url.username || url.password || url.hash) throw new Error(`${label} must not contain credentials or a fragment`);
+ if (utf8Bytes(source) > IMAGE_EDITOR_LIMITS.maxStringBytes) throw new Error(`${label} URL is too long`);
+ return source;
+}
+
+export function optionalString(o: Record<string, unknown>, key: string, label: string, max = IMAGE_EDITOR_LIMITS.maxStringBytes): string | undefined {
+ return o[key] === undefined ? undefined : stringValue(o[key], `${label}.${key}`, max);
+}
+
+export function optionalFinite(o: Record<string, unknown>, key: string, label: string, min: number, max: number): number | undefined {
+ return o[key] === undefined ? undefined : finite(o[key], `${label}.${key}`, min, max);
+}
diff --git a/frontend/slices/image-editor/lib/project-validation.test.ts b/frontend/slices/image-editor/lib/project-validation.test.ts
new file mode 100644
index 00000000..1291705a
--- /dev/null
+++ b/frontend/slices/image-editor/lib/project-validation.test.ts
@@ -0,0 +1,107 @@
+import { describe, expect, it } from "vitest";
+import { blankDoc, createLayer } from "./model";
+import {
+ IMAGE_EDITOR_LIMITS,
+ assertImageCanvasBounds,
+ parseImageEditorProject,
+ readBoundedProjectResponse,
+ validateImageEditorDoc,
+ validateImageEditorProject,
+} from "./project-validation";
+
+function validProject() {
+ const doc = blankDoc(1080, 1080);
+ return { v: 1 as const, doc, paint: {} };
+}
+
+function chunked(...chunks: Uint8Array[]) {
+ return new Response(new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const chunk of chunks) controller.enqueue(chunk);
+ controller.close();
+ },
+ }));
+}
+
+describe("image-editor project validation", () => {
+ it("accepts and canonicalizes a valid full project and bare Doc", () => {
+ const full = validateImageEditorProject(validProject());
+ expect(full).toMatchObject({ v: 1, doc: { width: 1080, height: 1080 }, paint: {} });
+ const bare = validateImageEditorProject(full.doc);
+ expect(bare).toMatchObject({ v: 1, doc: { width: 1080, height: 1080 }, paint: {} });
+ });
+
+ it("rejects non-finite, fractional, zero and over-budget canvases", () => {
+ for (const [width, height] of [
+ [Infinity, 100], [NaN, 100], [100.5, 100], [0, 100], [-1, 100],
+ [IMAGE_EDITOR_LIMITS.maxCanvasDimension + 1, 1],
+ ]) expect(() => assertImageCanvasBounds(width, height)).toThrow();
+ expect(() => assertImageCanvasBounds(4096, 4096)).not.toThrow();
+ });
+
+ it("rejects excessive layers before iterating their nested content", () => {
+ const project = validProject();
+ project.doc.layers = Array.from(
+ { length: IMAGE_EDITOR_LIMITS.maxLayers + 1 },
+ (_, index) => createLayer("paint", { name: `layer-${index}` }),
+ );
+ expect(() => validateImageEditorProject(project)).toThrow(/layer limit/);
+ });
+
+ it("rejects duplicate ids and malformed nested layer objects", () => {
+ const project = validProject();
+ const duplicate = createLayer("text", { id: project.doc.layers[0]!.id });
+ // createLayer always refreshes ids, so set the duplicate after construction.
+ duplicate.id = project.doc.layers[0]!.id;
+ project.doc.layers.push(duplicate);
+ expect(() => validateImageEditorProject(project)).toThrow(/duplicate layer id/);
+
+ const malformed = validProject();
+ (malformed.doc.layers[0]!.style.shadow as unknown as { opacity: number }).opacity = 99;
+ expect(() => validateImageEditorProject(malformed)).toThrow(/opacity/);
+ });
+
+ it("rejects executable image data and paint keys that do not map to paint layers", () => {
+ const svg = validProject();
+ svg.doc.layers.push(createLayer("image", {
+ src: "data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9YWxlcnQoMSk+PC9zdmc+",
+ }));
+ expect(() => validateImageEditorProject(svg)).toThrow(/base64 raster image/);
+
+ const mismatch = validProject();
+ (mismatch.paint as Record<string, string>).unknown = "data:image/png;base64,AA==";
+ expect(() => validateImageEditorProject(mismatch)).toThrow(/non-paint layer/);
+ });
+
+ it("rejects non-finite transforms and adjustment payloads", () => {
+ const transform = validProject();
+ transform.doc.layers[0]!.t.scaleX = Infinity;
+ expect(() => validateImageEditorDoc(transform.doc)).toThrow(/scaleX/);
+
+ const adjustment = validProject();
+ adjustment.doc.layers[0]!.adj.blur = 10_000;
+ expect(() => validateImageEditorDoc(adjustment.doc)).toThrow(/blur/);
+ });
+
+ it("parses a valid project and rejects malformed JSON", () => {
+ expect(parseImageEditorProject(JSON.stringify(validProject())).doc.width).toBe(1080);
+ expect(() => parseImageEditorProject("{broken")).toThrow(/malformed/);
+ });
+
+ it("rejects a declared oversized response without opening its body", async () => {
+ const getReader = () => { throw new Error("body must not be read"); };
+ const response = {
+ ok: true,
+ status: 200,
+ headers: new Headers({ "content-length": String(IMAGE_EDITOR_LIMITS.maxProjectBytes + 1) }),
+ body: { getReader },
+ } as unknown as Response;
+ await expect(readBoundedProjectResponse(response)).rejects.toThrow(/byte limit/);
+ });
+
+ it("stops a chunked response as soon as the project byte cap is crossed", async () => {
+ const first = new Uint8Array(IMAGE_EDITOR_LIMITS.maxProjectBytes);
+ const second = new Uint8Array(1);
+ await expect(readBoundedProjectResponse(chunked(first, second))).rejects.toThrow(/byte limit/);
+ });
+});
diff --git a/frontend/slices/image-editor/lib/project-validation.ts b/frontend/slices/image-editor/lib/project-validation.ts
new file mode 100644
index 00000000..10f49213
--- /dev/null
+++ b/frontend/slices/image-editor/lib/project-validation.ts
@@ -0,0 +1,175 @@
+import type { Doc, Layer, LayerKind, ShapeKind } from "./types";
+import {
+ IMAGE_EDITOR_LIMITS,
+ adjustments,
+ bool,
+ color,
+ finite,
+ imageSource,
+ isRasterDataUrl,
+ optionalFinite,
+ optionalString,
+ record,
+ safeCanvasSize,
+ stringValue,
+ style,
+ transform,
+ utf8Bytes,
+} from "./project-validation-values";
+import type { ValidationOptions } from "./project-validation-values";
+
+export {
+ IMAGE_EDITOR_LIMITS,
+ assertImageCanvasBounds,
+ safeCanvasSize,
+} from "./project-validation-values";
+
+export type ValidatedProject = { v: 1; doc: Doc; paint: Record<string, string> };
+
+const LAYER_KINDS = new Set<LayerKind>(["image", "text", "shape", "paint", "adjustment"]);
+const SHAPES = new Set<ShapeKind>(["rect", "ellipse", "line"]);
+const ALIGNS = new Set(["left", "center", "right"] as const);
+const FILL_TYPES = new Set(["solid", "gradient"] as const);
+
+function layer(value: unknown, index: number, options: ValidationOptions): Layer {
+ const label = `doc.layers[${index}]`;
+ const o = record(value, label);
+ const kind = stringValue(o.kind, `${label}.kind`, 32) as LayerKind;
+ if (!LAYER_KINDS.has(kind)) throw new Error(`${label}.kind is unsupported`);
+ const out: Layer = {
+ id: stringValue(o.id, `${label}.id`, 256),
+ name: stringValue(o.name, `${label}.name`, 512),
+ kind,
+ visible: bool(o.visible, `${label}.visible`),
+ locked: bool(o.locked, `${label}.locked`),
+ opacity: finite(o.opacity, `${label}.opacity`, 0, 1),
+ t: transform(o.t, `${label}.t`),
+ style: style(o.style, `${label}.style`),
+ adj: adjustments(o.adj, `${label}.adj`),
+ };
+ if (!out.id.trim()) throw new Error(`${label}.id must not be empty`);
+ if (o.mask !== undefined) out.mask = bool(o.mask, `${label}.mask`);
+ if (o.src !== undefined) out.src = imageSource(o.src, `${label}.src`, options);
+ if (o.text !== undefined) out.text = stringValue(o.text, `${label}.text`, IMAGE_EDITOR_LIMITS.maxTextBytes);
+ const fontSize = optionalFinite(o, "fontSize", label, 1, IMAGE_EDITOR_LIMITS.maxCanvasDimension);
+ if (fontSize !== undefined) out.fontSize = fontSize;
+ const fontFamily = optionalString(o, "fontFamily", label, 512); if (fontFamily !== undefined) out.fontFamily = fontFamily;
+ const fontStyle = optionalString(o, "fontStyle", label, 128); if (fontStyle !== undefined) out.fontStyle = fontStyle;
+ if (o.align !== undefined) {
+ const align = stringValue(o.align, `${label}.align`, 16) as "left" | "center" | "right";
+ if (!ALIGNS.has(align)) throw new Error(`${label}.align is unsupported`);
+ out.align = align;
+ }
+ const fill = optionalString(o, "fill", label, 256); if (fill !== undefined) out.fill = fill;
+ if (o.shape !== undefined) {
+ const shape = stringValue(o.shape, `${label}.shape`, 16) as ShapeKind;
+ if (!SHAPES.has(shape)) throw new Error(`${label}.shape is unsupported`);
+ out.shape = shape;
+ }
+ const fillColor = optionalString(o, "fillColor", label, 256); if (fillColor !== undefined) out.fillColor = fillColor;
+ if (o.fillType !== undefined) {
+ const fillType = stringValue(o.fillType, `${label}.fillType`, 16) as "solid" | "gradient";
+ if (!FILL_TYPES.has(fillType)) throw new Error(`${label}.fillType is unsupported`);
+ out.fillType = fillType;
+ }
+ if (o.gradient !== undefined) {
+ const g = record(o.gradient, `${label}.gradient`);
+ out.gradient = {
+ from: color(g.from, `${label}.gradient.from`),
+ to: color(g.to, `${label}.gradient.to`),
+ angle: finite(g.angle, `${label}.gradient.angle`, -360_000, 360_000),
+ };
+ }
+ return out;
+}
+
+export function validateImageEditorDoc(value: unknown, options: ValidationOptions = {}): Doc {
+ const o = record(value, "doc");
+ const { width, height } = safeCanvasSize(o.width, o.height);
+ const layers = o.layers;
+ if (!Array.isArray(layers)) throw new Error("doc.layers must be an array");
+ if (layers.length > IMAGE_EDITOR_LIMITS.maxLayers) throw new Error("doc exceeds the layer limit");
+ const parsed = layers.map((candidate, index) => layer(candidate, index, options));
+ const ids = new Set<string>();
+ for (const candidate of parsed) {
+ if (ids.has(candidate.id)) throw new Error(`duplicate layer id: ${candidate.id}`);
+ ids.add(candidate.id);
+ }
+ return {
+ width,
+ height,
+ bg: stringValue(o.bg, "doc.bg", 256),
+ layers: parsed,
+ };
+}
+
+function embeddedBytes(source: string): number {
+ return source.startsWith("data:") ? utf8Bytes(source) : 0;
+}
+
+export function validateImageEditorProject(value: unknown): ValidatedProject {
+ const candidate = record(value, "project");
+ const full = candidate.v === 1 && candidate.doc !== undefined;
+ const doc = validateImageEditorDoc(full ? candidate.doc : candidate);
+ const paintValue = full ? candidate.paint ?? {} : {};
+ const paintRecord = record(paintValue, "project.paint");
+ const paintLayerIds = new Set(doc.layers.filter((item) => item.kind === "paint").map((item) => item.id));
+ const paint: Record<string, string> = {};
+ let assets = doc.layers.reduce((sum, item) => sum + (item.src ? embeddedBytes(item.src) : 0), 0);
+ const entries = Object.entries(paintRecord);
+ if (entries.length > IMAGE_EDITOR_LIMITS.maxLayers) throw new Error("project.paint exceeds the layer limit");
+ for (const [id, raw] of entries) {
+ if (!paintLayerIds.has(id)) throw new Error(`project.paint references a non-paint layer: ${id}`);
+ const url = imageSource(raw, `project.paint.${id}`, {});
+ if (!isRasterDataUrl(url)) throw new Error(`project.paint.${id} must be embedded raster data`);
+ assets += embeddedBytes(url);
+ if (assets > IMAGE_EDITOR_LIMITS.maxEmbeddedAssetBytes) throw new Error("project embedded assets exceed the byte budget");
+ paint[id] = url;
+ }
+ return { v: 1, doc, paint };
+}
+
+export function parseImageEditorProject(text: string): ValidatedProject {
+ if (utf8Bytes(text) > IMAGE_EDITOR_LIMITS.maxProjectBytes) throw new Error("project exceeds the byte limit");
+ let value: unknown;
+ try { value = JSON.parse(text); } catch { throw new Error("project JSON is malformed"); }
+ return validateImageEditorProject(value);
+}
+
+export async function readBoundedProjectResponse(response: Response): Promise<string> {
+ if (!response.ok) throw new Error(`Failed to load project (${response.status})`);
+ const declared = Number(response.headers.get("content-length"));
+ if (Number.isFinite(declared) && declared > IMAGE_EDITOR_LIMITS.maxProjectBytes) throw new Error("project exceeds the byte limit");
+ if (!response.body) {
+ const text = await response.text();
+ if (utf8Bytes(text) > IMAGE_EDITOR_LIMITS.maxProjectBytes) throw new Error("project exceeds the byte limit");
+ return text;
+ }
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let total = 0;
+ let text = "";
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > IMAGE_EDITOR_LIMITS.maxProjectBytes) {
+ await reader.cancel("project exceeds the byte limit").catch(() => {});
+ throw new Error("project exceeds the byte limit");
+ }
+ text += decoder.decode(value, { stream: true });
+ }
+ text += decoder.decode();
+ return text;
+ } finally {
+ reader.releaseLock();
+ }
+}
+
+export async function readBoundedProjectFile(file: File): Promise<string> {
+ if (file.size > IMAGE_EDITOR_LIMITS.maxProjectBytes) throw new Error("project exceeds the byte limit");
+ const text = await file.text();
+ if (utf8Bytes(text) > IMAGE_EDITOR_LIMITS.maxProjectBytes) throw new Error("project exceeds the byte limit");
+ return text;
+}
diff --git a/frontend/slices/image-editor/lib/project.ts b/frontend/slices/image-editor/lib/project.ts
index 891566a5..92674b51 100644
--- a/frontend/slices/image-editor/lib/project.ts
+++ b/frontend/slices/image-editor/lib/project.ts
@@ -2,76 +2,76 @@ import { useCallback } from "react";
import { saveAs } from "@/features/os-shell";
import type Konva from "konva";
import type { Doc } from "./types";
+import {
+ parseImageEditorProject,
+ readBoundedProjectFile,
+ readBoundedProjectResponse,
+ validateImageEditorProject,
+ type ValidatedProject,
+} from "./project-validation";
-// An editable project = the document + every paint layer's pixels (PNG data URL,
-// keyed by layer id). This is what Save/Load and autosave persist — distinct from
-// a flat PNG export, because it round-trips back into a fully editable canvas.
-export type Project = { v: 1; doc: Doc; paint: Record<string, string> };
+export type Project = ValidatedProject;
+export { readBoundedProjectFile, readBoundedProjectResponse };
export function buildProject(doc: Doc, canvases: Map<string, HTMLCanvasElement>): Project {
const paint: Record<string, string> = {};
- for (const l of doc.layers) {
- if (l.kind !== "paint") continue;
- const c = canvases.get(l.id);
- if (c) paint[l.id] = c.toDataURL();
+ for (const layer of doc.layers) {
+ if (layer.kind !== "paint") continue;
+ const canvas = canvases.get(layer.id);
+ if (canvas) paint[layer.id] = canvas.toDataURL("image/png");
}
- return { v: 1, doc, paint };
+ return validateImageEditorProject({ v: 1, doc, paint });
}
-// Restore paint pixels for the loaded doc into the canvas map, then redraw.
export function restorePaint(
project: Project,
canvasFor: (id: string, w: number, h: number) => HTMLCanvasElement,
redraw: () => void,
) {
- const { doc, paint } = project;
- for (const [id, url] of Object.entries(paint)) {
- const c = canvasFor(id, doc.width, doc.height);
- const ctx = c.getContext("2d");
- const img = new window.Image();
- img.onload = () => {
- ctx?.clearRect(0, 0, c.width, c.height);
- ctx?.drawImage(img, 0, 0);
+ const safe = validateImageEditorProject(project);
+ for (const [id, url] of Object.entries(safe.paint)) {
+ const canvas = canvasFor(id, safe.doc.width, safe.doc.height);
+ const ctx = canvas.getContext("2d");
+ const image = new window.Image();
+ image.onload = () => {
+ ctx?.clearRect(0, 0, canvas.width, canvas.height);
+ ctx?.drawImage(image, 0, 0);
redraw();
};
- img.src = url;
+ image.src = url;
}
redraw();
}
export function downloadProject(project: Project, name = "project") {
- const blob = new Blob([JSON.stringify(project)], { type: "application/json" });
+ const safe = validateImageEditorProject(project);
+ const blob = new Blob([JSON.stringify(safe)], { type: "application/json" });
saveAs(URL.createObjectURL(blob), `${name}.ie.json`);
}
export function parseProject(text: string): Project | null {
- try {
- const p = JSON.parse(text);
- if (p && p.v === 1 && p.doc && Array.isArray(p.doc.layers)) return p as Project;
- } catch {
- /* ignore */
- }
- return null;
+ try { return parseImageEditorProject(text); }
+ catch { return null; }
}
const KEY = "image-editor:autosave:v1";
export function saveAutosave(project: Project) {
try {
- localStorage.setItem(KEY, JSON.stringify(project));
+ const safe = validateImageEditorProject(project);
+ localStorage.setItem(KEY, JSON.stringify(safe));
} catch {
- /* quota / serialization — ignore */
+ // Invalid/oversized projects and localStorage quota failures are both fail-closed.
}
}
export function loadAutosave(): Project | null {
try {
- const t = localStorage.getItem(KEY);
- return t ? parseProject(t) : null;
+ const text = localStorage.getItem(KEY);
+ return text ? parseProject(text) : null;
} catch {
return null;
}
}
-// Save/restore the editable project, factored out of the store to keep it lean.
export function useProjectIO(deps: {
doc: Doc;
canvases: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
@@ -82,10 +82,11 @@ export function useProjectIO(deps: {
}) {
const { doc, canvases, canvasFor, setDoc, setSelected, stageRef } = deps;
const exportProject = useCallback(() => buildProject(doc, canvases.current), [doc, canvases]);
- const loadProject = useCallback((p: Project) => {
- setDoc(p.doc);
- setSelected(p.doc.layers.at(-1)?.id ?? null);
- restorePaint(p, canvasFor, () => stageRef.current?.draw());
+ const loadProject = useCallback((project: Project) => {
+ const safe = validateImageEditorProject(project);
+ setDoc(safe.doc);
+ setSelected(safe.doc.layers.at(-1)?.id ?? null);
+ restorePaint(safe, canvasFor, () => stageRef.current?.draw());
}, [setDoc, setSelected, canvasFor, stageRef]);
return { exportProject, loadProject };
}
diff --git a/frontend/slices/image-editor/lib/store.tsx b/frontend/slices/image-editor/lib/store.tsx
index 54de3093..29bc03a5 100644
--- a/frontend/slices/image-editor/lib/store.tsx
+++ b/frontend/slices/image-editor/lib/store.tsx
@@ -18,6 +18,7 @@ import { useHistory } from "./history";
import { useProjectIO } from "./project";
import { useMaskOps } from "./mask";
import type { Brush, Ctx } from "./store-types";
+import { assertImageCanvasBounds, validateImageEditorDoc } from "./project-validation";
export type { Brush, Pan } from "./store-types";
@@ -27,7 +28,7 @@ const DEFAULT_BG = "#ffffff";
const EditorContext = createContext<Ctx | null>(null);
export function EditorProvider({ initialDoc, children }: { initialDoc?: Doc; children: ReactNode }) {
- const [doc, setDocState] = useState<Doc>(() => initialDoc ?? blankDoc());
+ const [doc, setDocState] = useState<Doc>(() => validateImageEditorDoc(initialDoc ?? blankDoc(), { allowBlobImages: true }));
// Selection + mask-edit live in ONE state so their invariant (mask-editing is
// scoped to the selected layer) is enforced atomically in the setters instead
// of an effect-driven reset (react-hooks/set-state-in-effect).
@@ -103,8 +104,9 @@ export function EditorProvider({ initialDoc, children }: { initialDoc?: Doc; chi
const setDoc = useCallback((next: Doc | ((d: Doc) => Doc), track = true) => {
setDocState((prev) => {
const n = typeof next === "function" ? next(prev) : next;
- if (track) push({ type: "doc", before: prev, after: n });
- return n;
+ const safe = validateImageEditorDoc(n, { allowBlobImages: true });
+ if (track) push({ type: "doc", before: prev, after: safe });
+ return safe;
});
}, [push]);
@@ -118,6 +120,7 @@ export function EditorProvider({ initialDoc, children }: { initialDoc?: Doc; chi
const recordPaint = useCallback((id: string, before: string, after: string) => push({ type: "paint", id, before, after }), [push]);
const canvasFor = useCallback((id: string, w: number, h: number) => {
+ assertImageCanvasBounds(w, h);
let c = canvases.current.get(id);
if (!c) {
c = document.createElement("canvas");
diff --git a/frontend/slices/managed-apps/app-support.ts b/frontend/slices/managed-apps/app-support.ts
index fb39e1fb..ef21ef0f 100644
--- a/frontend/slices/managed-apps/app-support.ts
+++ b/frontend/slices/managed-apps/app-support.ts
@@ -28,8 +28,8 @@ export interface AppSupport {
pinPlaceholder: string;
/** The by-hand command, kept even though MSO now installs for real: a button
* that fails on someone else's machine and leaves them with nothing is worse
- * than the copy-paste it replaced. The automated path is
- * scripts/managed-app-install; this is what it does, written out. */
+ * than the copy-paste it replaced. These commands call the same committed,
+ * checksum-verifying installer used by the API. */
installCommand: string;
installNote: string;
uninstallCommand: string;
@@ -45,10 +45,9 @@ const SUPPORT: Record<ManagedAppId, AppSupport> = {
pinHint:
"Hermes has no version pin. `update --branch NAME` switches the checkout and auto-stashes local changes — and a restore leaves ~/.hermes dirty against an unchanged HEAD, so it would stash the files just restored. Switch the branch from the Update tab afterwards if you meant to move the code.",
pinPlaceholder: "main",
- installCommand:
- "curl -fsSL https://hermes-agent.nousresearch.com/install.sh -o /tmp/h.sh && bash /tmp/h.sh --non-interactive && hermes setup --non-interactive && hermes gateway install --start-now",
+ installCommand: "bash scripts/managed-app-install hermes install",
installNote:
- "The installer pulls uv, Python 3.11, Node and ffmpeg — expect several minutes. `--non-interactive` skips every stage that would ask a question, and `hermes setup` then takes its API key from the environment instead of a prompt.",
+ "MSO downloads the reviewed Hermes release installer from its pinned tag, verifies SHA-256, and forces the checkout to the locked upstream commit before setup. The immutable values live in security/managed-app-artifacts.env.",
uninstallCommand: "hermes uninstall --yes",
uninstallEffect:
"Removes Hermes but keeps ~/.hermes config and data (add --full to remove those too). `hermes uninstall --dry-run` prints what it would remove.",
@@ -58,12 +57,11 @@ const SUPPORT: Record<ManagedAppId, AppSupport> = {
dryRun: true,
rollbackPin: true,
pinLabel: "Version",
- pinHint: "OpenClaw pins with `update --tag` — an exact version, or one of latest/stable/extended-stable/beta/dev. Package specs (a fork, a git ref) are refused.",
+ pinHint: "Rollback accepts an exact reviewed OpenClaw version. Moving channels or mutable dist-tags is an explicit update action, not the install default.",
pinPlaceholder: "2026.7.1-2",
- installCommand:
- "npm install -g openclaw@latest && openclaw onboard --non-interactive --accept-risk --flow quickstart --gateway-auth token --gateway-bind loopback --install-daemon",
+ installCommand: "bash scripts/managed-app-install openclaw install",
installNote:
- "`npm i -g` needs no sudo where npm's prefix is a user directory. `onboard --non-interactive` requires `--accept-risk` — the acknowledgement that an agent with system access is a loaded gun — and binds the gateway to loopback unless told otherwise.",
+ "MSO downloads the exact OpenClaw tarball named in security/managed-app-artifacts.env, verifies SHA-512 before npm can run lifecycle hooks, and confirms the installed version before onboarding it on loopback.",
uninstallCommand: "openclaw uninstall --non-interactive --yes --service --state",
uninstallEffect:
"Removes the gateway service and local state; the `openclaw` CLI itself stays on PATH. `--dry-run` prints the actions, `--all` also removes the workspace.",
@@ -74,12 +72,11 @@ const SUPPORT: Record<ManagedAppId, AppSupport> = {
rollbackPin: false,
pinLabel: "Version",
pinHint:
- "9Router ships one Docker tag (latest), so there is no version pin. A rollback restores the ~/.9router data snapshot; the image stays whatever is installed. Running an older image is a by-hand `docker run` with an explicit tag.",
- pinPlaceholder: "0.5.55",
- installCommand:
- "docker run -d --name 9router --restart unless-stopped -p 20128:20128 -v ~/.9router:/app/data -e DATA_DIR=/app/data decolua/9router:latest",
+ "MSO installs one reviewed multi-architecture image digest. Update reconciles the container to the digest committed in security/managed-app-artifacts.env; rollback restores data, not an unreviewed tag.",
+ pinPlaceholder: "sha256:f00fe389…",
+ installCommand: "bash scripts/managed-app-9router install",
installNote:
- "Pulls the decolua/9router image and starts it on port 20128 with its data in ~/.9router. Needs a user in the docker group; no sudo, no systemd unit — Docker's restart policy keeps it up.",
+ "MSO pulls and verifies the committed 9Router digest, binds 20128 to loopback by default, and stores data in ~/.9router. Set NINE_ROUTER_EXPOSE_PUBLIC=1 only for an explicitly accepted public-IP deployment.",
uninstallCommand: "docker rm -f 9router",
uninstallEffect:
"Stops and removes the container. The image and ~/.9router data (providers, keys, stats) stay, so a reinstall comes back configured.",
diff --git a/frontend/slices/reel-editor/lib/composition.ts b/frontend/slices/reel-editor/lib/composition.ts
index 97f1be0d..e34c3476 100644
--- a/frontend/slices/reel-editor/lib/composition.ts
+++ b/frontend/slices/reel-editor/lib/composition.ts
@@ -12,6 +12,7 @@ import {
} from "./mock-timeline";
import { upsertKey } from "./keyframes";
import { getSettings } from "./settings";
+import { finitePositive, REEL_LIMITS } from "./limits";
export type RatioPreset = { label: string; dims: string; w: number; h: number };
@@ -101,7 +102,7 @@ export function addMediaClip(c: Composition, media: MediaRef, name: string, fram
if (!track) return c;
const start = Math.max(0, Math.round(frame));
const len =
- media.type !== "image" && media.dur
+ media.type !== "image" && finitePositive(media.dur) && media.dur <= REEL_LIMITS.maxDurationSeconds
? Math.max(1, Math.round(media.dur * c.fps))
: Math.max(6, Math.round(getSettings().imageDur * c.fps));
const clip: Clip = {
@@ -126,10 +127,15 @@ export function clampTrim(
len: number,
speed = 1,
): { srcIn: number; len: number } {
- const srcIn = durSec != null ? Math.max(0, Math.min(srcInSec, durSec)) : Math.max(0, srcInSec);
+ const safeFps = finitePositive(fps) ? Math.min(REEL_LIMITS.maxFps, fps) : 30;
+ const safeSpeed = finitePositive(speed) ? Math.min(4, Math.max(0.25, speed)) : 1;
+ const safeDuration = finitePositive(durSec) && durSec <= REEL_LIMITS.maxDurationSeconds ? durSec : undefined;
+ const safeSrcIn = Number.isFinite(srcInSec) ? srcInSec : 0;
+ const safeLen = Number.isFinite(len) ? len : 6;
+ const srcIn = safeDuration != null ? Math.max(0, Math.min(safeSrcIn, safeDuration)) : Math.max(0, safeSrcIn);
// At speed S, `len` timeline frames consume len*S/fps source seconds.
- const maxLen = durSec != null ? Math.max(6, Math.round(((durSec - srcIn) * fps) / speed)) : Infinity;
- return { srcIn, len: Math.max(6, Math.min(len, maxLen)) };
+ const maxLen = safeDuration != null ? Math.max(6, Math.round(((safeDuration - srcIn) * safeFps) / safeSpeed)) : Infinity;
+ return { srcIn, len: Math.max(6, Math.min(safeLen, maxLen)) };
}
/** Set a clip's playback speed, rescaling its timeline length so the SAME source
diff --git a/frontend/slices/reel-editor/lib/draft.ts b/frontend/slices/reel-editor/lib/draft.ts
index 427c2ef3..aca67c04 100644
--- a/frontend/slices/reel-editor/lib/draft.ts
+++ b/frontend/slices/reel-editor/lib/draft.ts
@@ -4,6 +4,7 @@
// media restores fully.
import { type Composition } from "./mock-timeline";
+import { compositionBoundsError } from "./limits";
const KEY = "reel.draft";
@@ -13,7 +14,7 @@ export function loadDraft(): Composition | null {
const raw = localStorage.getItem(KEY);
if (!raw) return null;
const c = JSON.parse(raw) as Composition;
- if (!c || !Array.isArray(c.tracks) || !Array.isArray(c.clips) || !c.w || !c.h || !c.fps) return null;
+ if (!c || !Array.isArray(c.tracks) || !Array.isArray(c.clips) || compositionBoundsError(c)) return null;
return migrateLayerOrder(c);
} catch {
return null;
diff --git a/frontend/slices/reel-editor/lib/limits.test.ts b/frontend/slices/reel-editor/lib/limits.test.ts
new file mode 100644
index 00000000..8c408ead
--- /dev/null
+++ b/frontend/slices/reel-editor/lib/limits.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+import { assertCompositionBounds, compositionBoundsError, REEL_LIMITS } from "./limits";
+import { readBoundedAudioBytes, waveformWithinDecodeBudget } from "./waveform";
+
+function streamResponse(chunks: number[]): Response {
+ return new Response(new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (const size of chunks) controller.enqueue(new Uint8Array(size));
+ controller.close();
+ },
+ }));
+}
+
+describe("reel resource limits", () => {
+ it("rejects non-finite and oversized canvas/duration values before allocation", () => {
+ expect(compositionBoundsError({ w: Infinity, h: 1080, fps: 30, duration: 300 })).toMatch(/finite/);
+ expect(compositionBoundsError({ w: REEL_LIMITS.maxCanvasDimension + 1, h: 1, fps: 30, duration: 300 })).toMatch(/dimensions/);
+ expect(compositionBoundsError({ w: 4096, h: 4096, fps: 30, duration: 300 })).toBeNull();
+ expect(() => assertCompositionBounds({ w: 1920, h: 1080, fps: 30, duration: 30 * 60 * 61 })).toThrow(/one-hour/);
+ });
+
+ it("stops a chunked waveform download when the byte cap is crossed", async () => {
+ await expect(readBoundedAudioBytes(streamResponse([REEL_LIMITS.maxWaveformBytes, 1])))
+ .rejects.toThrow(/byte limit/);
+ });
+
+ it("accepts a bounded waveform download and decode shape", async () => {
+ await expect(readBoundedAudioBytes(streamResponse([1024, 2048]))).resolves.toHaveProperty("byteLength", 3072);
+ expect(waveformWithinDecodeBudget({ duration: 180, numberOfChannels: 2, length: 8_000_000 })).toBe(true);
+ });
+
+ it("rejects non-finite, overlong, multichannel and excessive decoded waveforms", () => {
+ expect(waveformWithinDecodeBudget({ duration: Infinity, numberOfChannels: 2, length: 1 })).toBe(false);
+ expect(waveformWithinDecodeBudget({ duration: REEL_LIMITS.maxWaveformSeconds + 1, numberOfChannels: 2, length: 1 })).toBe(false);
+ expect(waveformWithinDecodeBudget({ duration: 10, numberOfChannels: 6, length: 1 })).toBe(false);
+ expect(waveformWithinDecodeBudget({ duration: 10, numberOfChannels: 2, length: REEL_LIMITS.maxWaveformSampleValues })).toBe(false);
+ });
+});
diff --git a/frontend/slices/reel-editor/lib/limits.ts b/frontend/slices/reel-editor/lib/limits.ts
new file mode 100644
index 00000000..aa9da926
--- /dev/null
+++ b/frontend/slices/reel-editor/lib/limits.ts
@@ -0,0 +1,35 @@
+import type { Composition } from "./mock-timeline";
+
+export const REEL_LIMITS = {
+ maxCanvasDimension: 4096,
+ maxCanvasPixels: 16_777_216,
+ minFps: 1,
+ maxFps: 120,
+ maxDurationSeconds: 60 * 60,
+ maxWaveformBytes: 8 * 1024 * 1024,
+ maxWaveformSeconds: 10 * 60,
+ maxWaveformSampleValues: 24_000_000,
+ maxWaveformChannels: 2,
+} as const;
+
+export function finitePositive(value: unknown): value is number {
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
+}
+
+export function compositionBoundsError(comp: Pick<Composition, "w" | "h" | "fps" | "duration">): string | null {
+ const { w, h, fps, duration } = comp;
+ if (![w, h, fps, duration].every(Number.isFinite)) return "composition dimensions, FPS and duration must be finite";
+ if (![w, h, fps, duration].every(Number.isSafeInteger)) return "composition dimensions, FPS and duration must be safe integers";
+ if (w < 1 || h < 1 || w > REEL_LIMITS.maxCanvasDimension || h > REEL_LIMITS.maxCanvasDimension) {
+ return `composition dimensions must be 1–${REEL_LIMITS.maxCanvasDimension}px`;
+ }
+ if (w * h > REEL_LIMITS.maxCanvasPixels) return "composition canvas exceeds the pixel budget";
+ if (fps < REEL_LIMITS.minFps || fps > REEL_LIMITS.maxFps) return `composition FPS must be ${REEL_LIMITS.minFps}–${REEL_LIMITS.maxFps}`;
+ if (duration < 1 || duration / fps > REEL_LIMITS.maxDurationSeconds) return "composition duration exceeds the one-hour render budget";
+ return null;
+}
+
+export function assertCompositionBounds(comp: Pick<Composition, "w" | "h" | "fps" | "duration">): void {
+ const error = compositionBoundsError(comp);
+ if (error) throw new Error(error);
+}
diff --git a/frontend/slices/reel-editor/lib/media-probe.ts b/frontend/slices/reel-editor/lib/media-probe.ts
index 90f036f0..d1c9f7ed 100644
--- a/frontend/slices/reel-editor/lib/media-probe.ts
+++ b/frontend/slices/reel-editor/lib/media-probe.ts
@@ -1,7 +1,8 @@
-// Off-screen media metadata probe — natural pixel dims + (video/audio) duration.
+// Off-screen media metadata probe — natural pixel dims + finite media duration.
// Used at import time, before a clip's element is added to the MediaCache.
import type { MediaType } from "./mock-timeline";
+import { finitePositive } from "./limits";
/** Probe a media URL for natural pixel dims + (video) duration, off-screen. */
export function probeMedia(
@@ -21,7 +22,7 @@ export function probeMedia(
const a = document.createElement("audio");
a.crossOrigin = "anonymous";
a.preload = "metadata";
- a.onloadedmetadata = () => resolve({ natW: 0, natH: 0, dur: a.duration || undefined });
+ a.onloadedmetadata = () => resolve({ natW: 0, natH: 0, dur: finitePositive(a.duration) ? a.duration : undefined });
a.onerror = () => reject(new Error("Could not load audio"));
a.src = url;
return;
@@ -31,7 +32,7 @@ export function probeMedia(
v.muted = true;
v.preload = "metadata";
v.onloadedmetadata = () =>
- resolve({ natW: v.videoWidth || 1280, natH: v.videoHeight || 720, dur: v.duration || undefined });
+ resolve({ natW: v.videoWidth || 1280, natH: v.videoHeight || 720, dur: finitePositive(v.duration) ? v.duration : undefined });
v.onerror = () => reject(new Error("Could not load video"));
v.src = url;
});
diff --git a/frontend/slices/reel-editor/lib/render.ts b/frontend/slices/reel-editor/lib/render.ts
index 10eef442..3243d877 100644
--- a/frontend/slices/reel-editor/lib/render.ts
+++ b/frontend/slices/reel-editor/lib/render.ts
@@ -7,6 +7,7 @@
import type { Composition } from "./mock-timeline";
import { drawFrame } from "./draw";
import type { MediaCache } from "./media-cache";
+import { assertCompositionBounds } from "./limits";
const VMIMES = [
"video/webm;codecs=vp9,opus",
@@ -50,6 +51,7 @@ export async function renderToWebM(
onProgress: (pct: number) => void,
signal?: AbortSignal,
): Promise<Blob> {
+ assertCompositionBounds(comp);
const canvas = document.createElement("canvas");
canvas.width = comp.w;
canvas.height = comp.h;
diff --git a/frontend/slices/reel-editor/lib/waveform.ts b/frontend/slices/reel-editor/lib/waveform.ts
index d0491261..9f41ac97 100644
--- a/frontend/slices/reel-editor/lib/waveform.ts
+++ b/frontend/slices/reel-editor/lib/waveform.ts
@@ -6,12 +6,61 @@
// stride scan bounds CPU on long files. One shared decode context, module-cached.
import { useEffect, useState } from "react";
+import { REEL_LIMITS } from "./limits";
const BUCKETS = 160;
+const MAX_CACHE_ENTRIES = 128;
const peaks = new Map<string, Uint8Array>();
const pending = new Map<string, Promise<Uint8Array | null>>();
let ctx: AudioContext | null = null;
+
+export async function readBoundedAudioBytes(response: Response): Promise<ArrayBuffer> {
+ if (!response.ok) throw new Error(`waveform source HTTP ${response.status}`);
+ const declared = Number(response.headers.get("content-length"));
+ if (Number.isFinite(declared) && declared > REEL_LIMITS.maxWaveformBytes) {
+ throw new Error("waveform source exceeds byte limit");
+ }
+ if (!response.body) {
+ const data = await response.arrayBuffer();
+ if (data.byteLength > REEL_LIMITS.maxWaveformBytes) throw new Error("waveform source exceeds byte limit");
+ return data;
+ }
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > REEL_LIMITS.maxWaveformBytes) {
+ await reader.cancel("waveform source exceeds byte limit").catch(() => {});
+ throw new Error("waveform source exceeds byte limit");
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ const out = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.byteLength; }
+ return out.buffer;
+}
+
+export function waveformWithinDecodeBudget(audio: Pick<AudioBuffer, "duration" | "numberOfChannels" | "length">): boolean {
+ return Number.isFinite(audio.duration) && audio.duration > 0 && audio.duration <= REEL_LIMITS.maxWaveformSeconds &&
+ Number.isSafeInteger(audio.numberOfChannels) && audio.numberOfChannels >= 1 && audio.numberOfChannels <= REEL_LIMITS.maxWaveformChannels &&
+ Number.isSafeInteger(audio.length) && audio.length > 0 && audio.length * audio.numberOfChannels <= REEL_LIMITS.maxWaveformSampleValues;
+}
+
+function rememberPeaks(url: string, value: Uint8Array) {
+ peaks.delete(url);
+ peaks.set(url, value);
+ while (peaks.size > MAX_CACHE_ENTRIES) peaks.delete(peaks.keys().next().value!);
+}
+
function decodeCtx(): AudioContext {
if (!ctx) {
const AC = window.AudioContext ?? (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
@@ -27,8 +76,10 @@ export function computePeaks(url: string): Promise<Uint8Array | null> {
if (inflight) return inflight;
const job = (async () => {
try {
- const buf = await fetch(url).then((r) => r.arrayBuffer());
+ const response = await fetch(url);
+ const buf = await readBoundedAudioBytes(response);
const audio = await decodeCtx().decodeAudioData(buf);
+ if (!waveformWithinDecodeBudget(audio)) return null;
const ch = audio.getChannelData(0);
const n = ch.length;
const block = Math.max(1, Math.floor(n / BUCKETS));
@@ -44,7 +95,7 @@ export function computePeaks(url: string): Promise<Uint8Array | null> {
}
out[b] = Math.min(255, Math.round(peak * 255));
}
- peaks.set(url, out); // `audio` AudioBuffer now unreferenced → GC'd
+ rememberPeaks(url, out); // `audio` AudioBuffer now unreferenced → GC'd
return out;
} catch {
return null;
diff --git a/lib/ai/openai-stream.ts b/lib/ai/openai-stream.ts
index 5527ef34..6eb9c896 100644
--- a/lib/ai/openai-stream.ts
+++ b/lib/ai/openai-stream.ts
@@ -81,11 +81,13 @@ export async function streamOpenAI(opts: {
system: string;
signal: AbortSignal;
emit: (event: "delta" | "tool_use" | "done", data: unknown) => void;
+ fetchImpl?: typeof fetch;
}): Promise<void> {
const { resolved, messages, tools, system, signal, emit } = opts;
+ const fetchImpl = opts.fetchImpl ?? fetch;
if (signal.aborted) return;
- const res = await fetch(`${resolved.baseUrl}/chat/completions`, {
+ const res = await fetchImpl(`${resolved.baseUrl}/chat/completions`, {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${resolved.apiKey}` },
body: JSON.stringify({
diff --git a/lib/camoufox/origin.test.ts b/lib/camoufox/origin.test.ts
new file mode 100644
index 00000000..2058a4f7
--- /dev/null
+++ b/lib/camoufox/origin.test.ts
@@ -0,0 +1,33 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+afterEach(() => vi.unstubAllEnvs());
+
+async function load(template: string, publicOrigin = "https://mso.example.com") {
+ vi.resetModules();
+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", template);
+ vi.stubEnv("OS_PUBLIC_ORIGIN", publicOrigin);
+ return import("./origin");
+}
+
+describe("Camoufox split origin", () => {
+ it("reserves one host in the managed-app namespace", async () => {
+ const mod = await load("{id}.mso.example.com");
+ expect(mod.camoufoxViewerHost()).toBe("camoufox.mso.example.com");
+ expect(mod.camoufoxViewerOrigin()).toBe("https://camoufox.mso.example.com");
+ expect(mod.isCamoufoxViewerHost("camoufox.mso.example.com:443")).toBe(true);
+ });
+
+ it("has no same-origin fallback when the namespace is disabled", async () => {
+ const mod = await load("");
+ expect(mod.camoufoxViewerOrigin()).toBeNull();
+ expect(mod.isCamoufoxViewerHost("mso.example.com")).toBe(false);
+ });
+
+ it("allows only the cockpit to frame the viewer and no outbound forms", async () => {
+ const mod = await load("{id}.mso.example.com");
+ const csp = mod.camoufoxViewerCsp();
+ expect(csp).toContain("frame-ancestors https://mso.example.com");
+ expect(csp).toContain("form-action 'none'");
+ expect(csp).toContain("object-src 'none'");
+ });
+});
diff --git a/lib/camoufox/origin.ts b/lib/camoufox/origin.ts
new file mode 100644
index 00000000..5bcc32c4
--- /dev/null
+++ b/lib/camoufox/origin.ts
@@ -0,0 +1,38 @@
+// noVNC is third-party code with keyboard/mouse access to a logged-in browser. It
+// must never share the cockpit origin: on its own host, window.top and every MSO API
+// are cross-origin, while middleware maps every path only to loopback noVNC.
+import { appNamespaceHost, cockpitOrigin } from "@/lib/managed-apps/origin";
+
+export const CAMOUFOX_VIEWER_LABEL = "camoufox";
+
+export function camoufoxViewerHost(): string | null {
+ return appNamespaceHost(CAMOUFOX_VIEWER_LABEL);
+}
+
+export function camoufoxViewerOrigin(): string | null {
+ const host = camoufoxViewerHost();
+ return host ? `https://${host}` : null;
+}
+
+export function isCamoufoxViewerHost(host: string | null | undefined): boolean {
+ const expected = camoufoxViewerHost();
+ if (!host || !expected) return false;
+ return host.split(":")[0].replace(/\.$/, "").toLowerCase() === expected;
+}
+
+export function camoufoxViewerCsp(): string {
+ const cockpit = cockpitOrigin();
+ return [
+ "default-src 'none'",
+ "script-src 'self'",
+ "style-src 'self' 'unsafe-inline'",
+ "img-src 'self' data:",
+ "font-src 'self' data:",
+ "connect-src 'self'",
+ "worker-src 'self' blob:",
+ "object-src 'none'",
+ "base-uri 'self'",
+ "form-action 'none'",
+ `frame-ancestors ${cockpit ?? "'none'"}`,
+ ].join("; ");
+}
diff --git a/lib/camoufox/service.test.ts b/lib/camoufox/service.test.ts
index 10a883db..f7017666 100644
--- a/lib/camoufox/service.test.ts
+++ b/lib/camoufox/service.test.ts
@@ -1,10 +1,10 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
vi.mock("@/lib/managed-apps/runner", () => ({ runProgram: vi.fn() }));
import { runProgram } from "@/lib/managed-apps/runner";
-import { camoufoxStatus, parseUnitShow, setCamoufoxEnabled } from "./service";
+import { camoufoxStatus, parseUnitShow, setCamoufoxEnabled, terminateCamoufoxSessions } from "./service";
const mockRun = vi.mocked(runProgram);
@@ -20,7 +20,11 @@ const OFF = show({ LoadState: "loaded", ActiveState: "inactive", UnitFileState:
// The steady state after a UI "on": powered up, and STILL not armed for boot.
const ON = show({ LoadState: "loaded", ActiveState: "active", UnitFileState: "disabled" });
-beforeEach(() => mockRun.mockReset());
+beforeEach(() => {
+ mockRun.mockReset();
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 200 })));
+});
+afterEach(() => vi.unstubAllGlobals());
describe("camoufox unit status parsing", () => {
it("reads a running, boot-persistent unit", () => {
@@ -75,6 +79,23 @@ describe("camoufox lifecycle", () => {
await expect(camoufoxStatus()).rejects.toThrow(/No medium found/);
});
+ it("reports viewer readiness only after the loopback document answers", async () => {
+ mockRun.mockResolvedValue(ok(RUNNING));
+ await expect(camoufoxStatus()).resolves.toMatchObject({ running: true, viewerReady: true });
+ vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("not listening"); }));
+ await expect(camoufoxStatus()).resolves.toMatchObject({ running: true, viewerReady: false });
+ });
+
+ it("never probes an off-box noVNC URL from configuration", async () => {
+ vi.stubEnv("CAMOUFOX_NOVNC_URL", "https://evil.example/vnc.html");
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+ mockRun.mockResolvedValue(ok(RUNNING));
+ await expect(camoufoxStatus()).resolves.toMatchObject({ viewerReady: false });
+ expect(fetchMock).not.toHaveBeenCalled();
+ vi.unstubAllEnvs();
+ });
+
it("powers the session without ever re-arming boot autostart", async () => {
// The bug this guards: `enable --now` made every "Turn on" click re-create
// default.target.wants, so the browser came back at every boot and sat there for a
@@ -99,4 +120,36 @@ describe("camoufox lifecycle", () => {
mockRun.mockResolvedValueOnce(ok(OFF)).mockResolvedValueOnce({ code: 5, stdout: "", stderr: "boom" });
await expect(setCamoufoxEnabled(true)).rejects.toThrow(/rc 5/);
});
+ it("tears down a running viewer and verifies that the unit is inactive", async () => {
+ mockRun.mockResolvedValueOnce(ok(ON)).mockResolvedValueOnce(ok("")).mockResolvedValueOnce(ok(OFF));
+ await expect(terminateCamoufoxSessions()).resolves.toBeUndefined();
+ expect(mockRun.mock.calls[1]![1]).toEqual(["--user", "stop", "camoufox-vnc.service"]);
+ });
+
+ it("does nothing when no viewer process exists", async () => {
+ mockRun.mockResolvedValueOnce(ok(OFF));
+ await expect(terminateCamoufoxSessions()).resolves.toBeUndefined();
+ expect(mockRun).toHaveBeenCalledTimes(1);
+ });
+
+ it("falls back to killing the service cgroup when graceful stop fails", async () => {
+ mockRun
+ .mockResolvedValueOnce(ok(ON))
+ .mockResolvedValueOnce({ code: 5, stdout: "", stderr: "stop failed" })
+ .mockResolvedValueOnce(ok(""))
+ .mockResolvedValueOnce(ok(OFF));
+ await expect(terminateCamoufoxSessions()).resolves.toBeUndefined();
+ expect(mockRun.mock.calls[2]![1]).toEqual([
+ "--user", "kill", "--kill-who=all", "--signal=SIGKILL", "camoufox-vnc.service",
+ ]);
+ });
+
+ it("fails closed when neither stop nor cgroup kill succeeds", async () => {
+ mockRun
+ .mockResolvedValueOnce(ok(ON))
+ .mockResolvedValueOnce({ code: 5, stdout: "", stderr: "stop failed" })
+ .mockResolvedValueOnce({ code: 6, stdout: "", stderr: "kill failed" });
+ await expect(terminateCamoufoxSessions()).rejects.toThrow(/stop rc 5, kill rc 6/);
+ });
+
});
diff --git a/lib/camoufox/service.ts b/lib/camoufox/service.ts
index 9197adec..6fe6568f 100644
--- a/lib/camoufox/service.ts
+++ b/lib/camoufox/service.ts
@@ -19,6 +19,8 @@ export interface CamoufoxServiceStatus {
enabled: boolean;
/** No such unit on this host — never true on a normal install. */
installed: boolean;
+ /** Loopback noVNC has finished booting and can serve the viewer document. */
+ viewerReady?: boolean;
}
/** Parses one `systemctl show -p ...` block. Split out from the spawn so the
@@ -55,8 +57,32 @@ async function show(): Promise<CamoufoxServiceStatus> {
return parseUnitShow(result.stdout);
}
+const LOOPBACK = /^(?:127(?:\.\d{1,3}){3}|\[?::1\]?)$/;
+
+async function probeViewer(): Promise<boolean> {
+ const raw = process.env.CAMOUFOX_NOVNC_URL || "http://127.0.0.1:6080";
+ let base: URL;
+ try { base = new URL(raw); } catch { return false; }
+ if ((base.protocol !== "http:" && base.protocol !== "https:") || !LOOPBACK.test(base.hostname)) return false;
+ const target = new URL(base);
+ target.pathname = "/vnc.html";
+ target.search = "";
+ try {
+ const response = await fetch(target, {
+ method: "HEAD",
+ cache: "no-store",
+ redirect: "error",
+ signal: AbortSignal.timeout(1_500),
+ });
+ return response.ok;
+ } catch {
+ return false;
+ }
+}
+
export async function camoufoxStatus(): Promise<CamoufoxServiceStatus> {
- return show();
+ const status = await show();
+ return { ...status, viewerReady: status.running ? await probeViewer() : false };
}
/** Powers the display on or off for THIS session only — plain `start`/`stop`, never
@@ -77,3 +103,36 @@ export async function setCamoufoxEnabled(on: boolean): Promise<CamoufoxServiceSt
}
return show();
}
+
+/** Revocation kill-switch. A WebSocket is authenticated only at its handshake, so
+ * removing a device from the allowlist cannot evict an already-established VNC
+ * channel by itself. Stopping the unit tears down websockify, x11vnc and the browser
+ * cgroup; a SIGKILL fallback handles a unit that refuses a graceful stop. */
+export async function terminateCamoufoxSessions(): Promise<void> {
+ let status = await show();
+ if (!status.installed || !status.running) return;
+
+ const stopped = await runProgram("systemctl", ["--user", "stop", UNIT], 30_000);
+ if (stopped.code !== 0) {
+ const killed = await runProgram(
+ "systemctl",
+ ["--user", "kill", "--kill-who=all", "--signal=SIGKILL", UNIT],
+ 15_000,
+ );
+ if (killed.code !== 0) {
+ throw new Error(`could not terminate Camoufox sessions (stop rc ${stopped.code}, kill rc ${killed.code})`);
+ }
+ }
+
+ status = await show();
+ if (status.running) {
+ const killed = await runProgram(
+ "systemctl",
+ ["--user", "kill", "--kill-who=all", "--signal=SIGKILL", UNIT],
+ 15_000,
+ );
+ if (killed.code !== 0) throw new Error(`Camoufox remained active after stop (kill rc ${killed.code})`);
+ status = await show();
+ }
+ if (status.running) throw new Error("Camoufox remained active after forced termination");
+}
diff --git a/lib/host/ssrf.test.ts b/lib/host/ssrf.test.ts
index b9f462df..dca30366 100644
--- a/lib/host/ssrf.test.ts
+++ b/lib/host/ssrf.test.ts
@@ -1,28 +1,58 @@
-import { describe, it, expect } from "vitest";
-import { assertSafeUrl } from "./ssrf";
+import { afterEach, describe, expect, it } from "vitest";
+import { assertSafeUrl, isForbiddenProviderAddress, resolveSafeProviderEndpoint } from "./ssrf";
-describe("assertSafeUrl", () => {
- it("accepts a public https endpoint", () => {
+const originalHttp = process.env.OS_CUSTOM_PROVIDER_ALLOW_INSECURE_HTTP;
+afterEach(() => {
+ if (originalHttp === undefined) delete process.env.OS_CUSTOM_PROVIDER_ALLOW_INSECURE_HTTP;
+ else process.env.OS_CUSTOM_PROVIDER_ALLOW_INSECURE_HTTP = originalHttp;
+});
+
+describe("custom-provider network boundary", () => {
+ it("accepts a public HTTPS endpoint", () => {
expect(assertSafeUrl("https://api.example.com/v1").hostname).toBe("api.example.com");
});
- it("rejects the cloud-metadata IP", () => {
- expect(() => assertSafeUrl("http://169.254.169.254/latest/meta-data")).toThrow(/not allowed/);
+ it("requires explicit opt-in for insecure HTTP", () => {
+ expect(() => assertSafeUrl("http://api.example.com/v1")).toThrow(/must use HTTPS/);
+ process.env.OS_CUSTOM_PROVIDER_ALLOW_INSECURE_HTTP = "1";
+ expect(assertSafeUrl("http://api.example.com/v1").protocol).toBe("http:");
+ });
+
+ it("rejects credentials, fragments and local hostnames", () => {
+ for (const url of [
+ "https://user:[email protected]/v1",
+ "https://example.com/v1#fragment",
+ "https://foo.internal/v1",
+ "https://service.local/v1",
+ "https://localhost/v1",
+ ]) expect(() => assertSafeUrl(url)).toThrow();
+ });
+
+ it("classifies private, metadata, documentation, multicast and mapped addresses", () => {
+ for (const address of [
+ "0.0.0.0", "10.0.0.1", "100.64.0.1", "127.0.0.1", "169.254.169.254",
+ "172.31.1.1", "192.168.1.1", "192.0.2.1", "198.18.0.1", "198.51.100.1",
+ "203.0.113.1", "224.0.0.1", "::", "::1", "fc00::1", "fe80::1", "ff02::1",
+ "2001:db8::1", "::ffff:10.0.0.1",
+ ]) expect(isForbiddenProviderAddress(address), address).toBe(true);
+ for (const address of ["1.1.1.1", "8.8.8.8", "2606:4700:4700::1111"])
+ expect(isForbiddenProviderAddress(address), address).toBe(false);
+ });
+
+ it("rejects DNS rebinding answers before any socket is opened", async () => {
+ const privateResolver = async () => [{ address: "10.0.0.7", family: 4 as const }];
+ await expect(resolveSafeProviderEndpoint("https://provider.example/v1", privateResolver))
+ .rejects.toThrow(/DNS resolved/);
});
- it("rejects loopback / private / link-local / non-http", () => {
- for (const u of [
- "http://localhost/v1",
- "http://127.0.0.1",
- "http://10.0.0.1",
- "http://192.168.1.1",
- "http://172.16.0.1",
- "http://[::1]/",
- "https://foo.internal",
- "ftp://example.com",
- "not a url",
- ]) {
- expect(() => assertSafeUrl(u)).toThrow();
- }
+ it("rejects mixed public/private DNS answers and pins a fully-public answer", async () => {
+ const mixed = async () => [
+ { address: "203.0.114.9", family: 4 as const },
+ { address: "127.0.0.1", family: 4 as const },
+ ];
+ await expect(resolveSafeProviderEndpoint("https://provider.example/v1", mixed)).rejects.toThrow(/DNS resolved/);
+ const publicResolver = async () => [{ address: "203.0.114.9", family: 4 as const }];
+ await expect(resolveSafeProviderEndpoint("https://provider.example/v1", publicResolver))
+ .resolves.toMatchObject({ address: "203.0.114.9", family: 4 });
});
});
diff --git a/lib/host/ssrf.ts b/lib/host/ssrf.ts
index 7de1f6eb..ba47d7a9 100644
--- a/lib/host/ssrf.ts
+++ b/lib/host/ssrf.ts
@@ -1,23 +1,182 @@
-// Block SSRF to loopback / private / link-local / cloud-metadata hosts for
-// user-supplied base URLs (BYOK custom providers). Hostname-literal check —
-// catches direct-IP + localhost. Ported from models-rahmanef-com (ConvexError →
-// plain Error so the API route surfaces the message).
-// ponytail: does NOT resolve DNS, so a public hostname that resolves to a private
-// IP (DNS rebinding) still slips through — upgrade to connect-time IP resolution +
-// pinning if untrusted users register at scale. Single-owner here, so literal-check is enough.
+import { lookup as dnsLookup } from "node:dns/promises";
+import { request as httpRequest } from "node:http";
+import { request as httpsRequest } from "node:https";
+import { isIP } from "node:net";
+import { Readable } from "node:stream";
+
+const FORBIDDEN_HOST_SUFFIXES = [".localhost", ".local", ".internal", ".home", ".lan"];
+const MAX_PROVIDER_URL_BYTES = 4 * 1024;
+
+type LookupAnswer = { address: string; family: number };
+type Resolver = (hostname: string, options: { all: true; verbatim: true }) => Promise<LookupAnswer[]>;
+export type PinnedEndpoint = { url: URL; address: string; family: 4 | 6 };
+
+function parseIpv4(address: string): number[] | null {
+ const parts = address.split(".");
+ if (parts.length !== 4) return null;
+ const nums = parts.map((part) => Number(part));
+ return nums.every((part) => Number.isInteger(part) && part >= 0 && part <= 255) ? nums : null;
+}
+
+function ipv6Bytes(address: string): number[] | null {
+ const zoneFree = address.toLowerCase().split("%")[0];
+ let source = zoneFree;
+ let ipv4Tail: number[] | null = null;
+ const lastColon = source.lastIndexOf(":");
+ if (source.includes(".") && lastColon >= 0) {
+ ipv4Tail = parseIpv4(source.slice(lastColon + 1));
+ if (!ipv4Tail) return null;
+ source = `${source.slice(0, lastColon)}:${((ipv4Tail[0] << 8) | ipv4Tail[1]).toString(16)}:${((ipv4Tail[2] << 8) | ipv4Tail[3]).toString(16)}`;
+ }
+ const halves = source.split("::");
+ if (halves.length > 2) return null;
+ const left = halves[0] ? halves[0].split(":") : [];
+ const right = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
+ const missing = 8 - left.length - right.length;
+ if ((halves.length === 1 && missing !== 0) || missing < 0) return null;
+ const groups = [...left, ...Array(halves.length === 2 ? missing : 0).fill("0"), ...right];
+ if (groups.length !== 8) return null;
+ const bytes: number[] = [];
+ for (const group of groups) {
+ if (!/^[0-9a-f]{1,4}$/.test(group || "0")) return null;
+ const value = Number.parseInt(group || "0", 16);
+ bytes.push(value >>> 8, value & 0xff);
+ }
+ return bytes;
+}
+
+function isForbiddenIpv4(address: string): boolean {
+ const p = parseIpv4(address);
+ if (!p) return true;
+ const [a, b, c] = p;
+ return (
+ a === 0 ||
+ a === 10 ||
+ a === 127 ||
+ (a === 100 && b >= 64 && b <= 127) ||
+ (a === 169 && b === 254) ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 0 && c === 0) ||
+ (a === 192 && b === 0 && c === 2) ||
+ (a === 192 && b === 168) ||
+ (a === 198 && (b === 18 || b === 19)) ||
+ (a === 198 && b === 51 && c === 100) ||
+ (a === 203 && b === 0 && c === 113) ||
+ a >= 224
+ );
+}
+
+function isForbiddenIpv6(address: string): boolean {
+ const bytes = ipv6Bytes(address);
+ if (!bytes) return true;
+ const allZero = bytes.every((value) => value === 0);
+ const loopback = bytes.slice(0, 15).every((value) => value === 0) && bytes[15] === 1;
+ if (allZero || loopback) return true;
+ // IPv4-compatible/mapped addresses must obey the IPv4 policy too.
+ const mapped = bytes.slice(0, 10).every((value) => value === 0) &&
+ ((bytes[10] === 0xff && bytes[11] === 0xff) || (bytes[10] === 0 && bytes[11] === 0));
+ if (mapped) return isForbiddenIpv4(`${bytes[12]}.${bytes[13]}.${bytes[14]}.${bytes[15]}`);
+ if ((bytes[0] & 0xfe) === 0xfc) return true; // fc00::/7 unique-local
+ if (bytes[0] === 0xfe && (bytes[1] & 0xc0) === 0x80) return true; // fe80::/10 link-local
+ if (bytes[0] === 0xff) return true; // multicast
+ if (bytes[0] === 0x20 && bytes[1] === 0x01 && bytes[2] === 0x0d && bytes[3] === 0xb8) return true; // docs
+ if (bytes[0] === 0x01 && bytes.slice(1, 8).every((value) => value === 0)) return true; // discard-only 100::/64
+ return false;
+}
+
+export function isForbiddenProviderAddress(address: string): boolean {
+ const family = isIP(address);
+ if (family === 4) return isForbiddenIpv4(address);
+ if (family === 6) return isForbiddenIpv6(address);
+ return true;
+}
+
+/** Syntax/literal guard used when accepting configuration. Network calls must also
+ * use resolveSafeProviderEndpoint/safeProviderFetch so DNS cannot rebind at connect. */
export function assertSafeUrl(raw: string): URL {
- let u: URL;
+ if (Buffer.byteLength(raw, "utf8") > MAX_PROVIDER_URL_BYTES) throw new Error("Base URL is too long");
+ let url: URL;
try {
- u = new URL(raw);
+ url = new URL(raw);
} catch {
throw new Error("Base URL is not a valid URL");
}
- if (u.protocol !== "https:" && u.protocol !== "http:") throw new Error("Base URL must be http or https");
- const h = u.hostname.toLowerCase().replace(/^\[|\]$/g, "");
- const bad =
- h === "localhost" || h === "0.0.0.0" || h === "::1" || h.endsWith(".local") || h.endsWith(".internal") ||
- /^127\./.test(h) || /^10\./.test(h) || /^192\.168\./.test(h) || /^169\.254\./.test(h) ||
- /^172\.(1[6-9]|2\d|3[01])\./.test(h) || /^(fc|fd)[0-9a-f]{2}:/i.test(h) || /^fe80:/i.test(h);
- if (bad) throw new Error("Base URL host not allowed (private / loopback / link-local / metadata)");
- return u;
+ const insecureAllowed = process.env.OS_CUSTOM_PROVIDER_ALLOW_INSECURE_HTTP === "1";
+ if (url.protocol !== "https:" && !(insecureAllowed && url.protocol === "http:")) {
+ throw new Error("Base URL must use HTTPS (set OS_CUSTOM_PROVIDER_ALLOW_INSECURE_HTTP=1 only for an explicitly accepted public HTTP endpoint)");
+ }
+ if (url.username || url.password) throw new Error("Base URL must not contain credentials");
+ if (url.hash) throw new Error("Base URL must not contain a fragment");
+ const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
+ if (!host || host === "localhost" || host === "0.0.0.0" || FORBIDDEN_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))) {
+ throw new Error("Base URL host not allowed (private / loopback / link-local / metadata)");
+ }
+ if (isIP(host) && isForbiddenProviderAddress(host)) {
+ throw new Error("Base URL host not allowed (private / loopback / link-local / metadata)");
+ }
+ return url;
+}
+
+export async function resolveSafeProviderEndpoint(
+ raw: string | URL,
+ resolver: Resolver = dnsLookup,
+): Promise<PinnedEndpoint> {
+ const url = assertSafeUrl(String(raw));
+ const host = url.hostname.replace(/^\[|\]$/g, "");
+ const literalFamily = isIP(host);
+ const resolved: LookupAnswer[] = literalFamily
+ ? [{ address: host, family: literalFamily as 4 | 6 }]
+ : await resolver(host, { all: true, verbatim: true });
+ if (!resolved.length) throw new Error("Base URL host did not resolve");
+ if (resolved.some((entry) => isForbiddenProviderAddress(entry.address))) {
+ throw new Error("Base URL DNS resolved to a private / loopback / link-local / metadata address");
+ }
+ const first = resolved[0];
+ if (first.family !== 4 && first.family !== 6) throw new Error("Base URL resolved to an unsupported address family");
+ return { url, address: first.address, family: first.family };
+}
+
+function responseHeaders(raw: NodeJS.Dict<string | string[]>): Headers {
+ const headers = new Headers();
+ for (const [name, value] of Object.entries(raw)) {
+ if (Array.isArray(value)) for (const item of value) headers.append(name, item);
+ else if (value !== undefined) headers.set(name, value);
+ }
+ return headers;
+}
+
+/** Fetch-compatible transport for custom AI providers. It resolves on every request,
+ * rejects any non-public answer, then pins the actual socket lookup to the reviewed IP.
+ * Redirects are deliberately not followed, so an API key cannot cross to a new host. */
+export async function safeProviderFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
+ const request = new Request(input, init);
+ const pinned = await resolveSafeProviderEndpoint(request.url);
+ const body = request.body ? Buffer.from(await request.arrayBuffer()) : undefined;
+ return await new Promise<Response>((resolve, reject) => {
+ const transport = pinned.url.protocol === "https:" ? httpsRequest : httpRequest;
+ const upstream = transport({
+ protocol: pinned.url.protocol,
+ hostname: pinned.url.hostname,
+ port: pinned.url.port || undefined,
+ path: `${pinned.url.pathname}${pinned.url.search}`,
+ method: request.method,
+ headers: Object.fromEntries(request.headers.entries()),
+ lookup: (_hostname, _options, callback) => callback(null, pinned.address, pinned.family),
+ }, (response) => {
+ const status = response.statusCode ?? 502;
+ const stream = Readable.toWeb(response) as ReadableStream<Uint8Array>;
+ resolve(new Response(stream, {
+ status,
+ statusText: response.statusMessage,
+ headers: responseHeaders(response.headers),
+ }));
+ });
+ const abort = () => upstream.destroy(new DOMException("The operation was aborted", "AbortError"));
+ if (request.signal.aborted) abort();
+ else request.signal.addEventListener("abort", abort, { once: true });
+ upstream.once("error", reject);
+ upstream.once("close", () => request.signal.removeEventListener("abort", abort));
+ if (body?.length) upstream.write(body);
+ upstream.end();
+ });
}
diff --git a/lib/managed-apps/catalog.test.ts b/lib/managed-apps/catalog.test.ts
index 3def2863..1f5f8e23 100644
--- a/lib/managed-apps/catalog.test.ts
+++ b/lib/managed-apps/catalog.test.ts
@@ -1,3 +1,4 @@
+import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { getManagedAppDefinition, isManagedAppId, listManagedAppDefinitions } from "./catalog";
import { MANAGED_APP_ACTIONS } from "./types";
@@ -25,4 +26,13 @@ describe("managed app catalog", () => {
const openclaw = getManagedAppDefinition("openclaw");
expect(hermes.serviceNames).not.toEqual(openclaw.serviceNames);
});
+ it("keeps 9Router loopback-only unless public exposure is explicitly enabled", () => {
+ const source = readFileSync(new URL("../../scripts/managed-app-9router", import.meta.url), "utf8");
+ expect(source).toContain('EXPOSE_PUBLIC="${NINE_ROUTER_EXPOSE_PUBLIC:-0}"');
+ expect(source).toContain('0) BIND=127.0.0.1');
+ expect(source).toContain('-p "$BIND:$PORT:$PORT"');
+ expect(source).not.toContain('-p "$PORT:$PORT"');
+ expect(getManagedAppDefinition("9router").publicPort).toBeUndefined();
+ });
+
});
diff --git a/lib/managed-apps/catalog.ts b/lib/managed-apps/catalog.ts
index 1db99698..6bc609a8 100644
--- a/lib/managed-apps/catalog.ts
+++ b/lib/managed-apps/catalog.ts
@@ -59,10 +59,9 @@ const definitions = {
containerNames: ["9router"],
dashboardUrl: process.env.NINE_ROUTER_DASHBOARD_URL ?? "http://127.0.0.1:20128",
healthPath: "/api/health",
- // The Docker install publishes this port on 0.0.0.0. That gives a fresh MSO
- // installation a usable UI without requiring DNS, TLS or a domain provider.
- // Embedding inside HTTPS MSO remains a separate optional split-origin feature.
- publicPort: 20128,
+ // Loopback is the secure default. Direct public-IP access is an explicit operator
+ // choice because 9Router stores provider credentials and is not an MSO auth surface.
+ publicPort: process.env.NINE_ROUTER_EXPOSE_PUBLIC === "1" ? 20128 : undefined,
publicUrl: process.env.NINE_ROUTER_PUBLIC_URL,
stateDirName: ".9router",
gradient: "linear-gradient(160deg,#0ea5e9,#2563eb)",
diff --git a/lib/managed-apps/manager.test.ts b/lib/managed-apps/manager.test.ts
index c9558d4e..0da6b4b4 100644
--- a/lib/managed-apps/manager.test.ts
+++ b/lib/managed-apps/manager.test.ts
@@ -45,7 +45,7 @@ afterEach(() => {
});
describe("public-IP dashboard fallback", () => {
- it("advertises 9Router on a globally routable host interface without requiring DNS", async () => {
+ it("does not advertise 9Router's host port without explicit public exposure", async () => {
vi.spyOn(os, "networkInterfaces").mockReturnValue({
eth0: [
{ address: "10.0.0.5", netmask: "255.0.0.0", family: "IPv4", mac: "00:00:00:00:00:00", internal: false, cidr: "10.0.0.5/8" },
@@ -63,7 +63,8 @@ describe("public-IP dashboard fallback", () => {
vi.mocked(resolveCommand).mockResolvedValue(null);
const view = await getManagedApp("9router");
- expect(view.publicDashboardUrl).toBe("http://76.13.23.37:20128");
+ expect(view.publicDashboardUrl).not.toBe("http://76.13.23.37:20128");
+ if (view.publicDashboardUrl) expect(view.publicDashboardUrl).toMatch(/^https:\/\//);
});
it("does not invent a public URL for loopback-only managed apps", async () => {
diff --git a/lib/managed-apps/origin.ts b/lib/managed-apps/origin.ts
index 54f46aeb..e4b949ee 100644
--- a/lib/managed-apps/origin.ts
+++ b/lib/managed-apps/origin.ts
@@ -28,9 +28,19 @@ const TOKEN = "{id}";
export const splitOriginEnabled = (): boolean => TEMPLATE.includes(TOKEN);
+const NAMESPACE_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
+
+/** A reserved host in the split-origin namespace. The label is code-owned, not a
+ * request value; validating it here prevents accidental host-template injection. */
+export function appNamespaceHost(label: string): string | null {
+ return splitOriginEnabled() && NAMESPACE_LABEL.test(label)
+ ? TEMPLATE.replace(TOKEN, label).toLowerCase()
+ : null;
+}
+
/** The host this app's dashboard is served from, or null when dashboard embedding is disabled. */
export function managedAppHost(id: ManagedAppId): string | null {
- return splitOriginEnabled() ? TEMPLATE.replace(TOKEN, id).toLowerCase() : null;
+ return appNamespaceHost(id);
}
/** `https://<host>` — the iframe origin. null when dashboard embedding is disabled. */
diff --git a/lib/managed-apps/update-cli.ts b/lib/managed-apps/update-cli.ts
index c13d89b1..fbf09be3 100644
--- a/lib/managed-apps/update-cli.ts
+++ b/lib/managed-apps/update-cli.ts
@@ -73,7 +73,7 @@ const ADAPTERS: Record<ManagedAppId, UpdateAdapter> = {
channel: false,
rollback: true,
uninstall: true,
- installCommand: "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",
+ installCommand: "bash scripts/managed-app-install hermes install",
uninstallCommand: null,
},
// NO rollback pin. Hermes' only pin is `--branch`, and a rollback restores
@@ -123,7 +123,7 @@ const ADAPTERS: Record<ManagedAppId, UpdateAdapter> = {
channel: true,
rollback: true,
uninstall: true,
- installCommand: "npm install -g openclaw@latest",
+ installCommand: "bash scripts/managed-app-install openclaw install",
uninstallCommand: null,
},
pin: (value) => ["--tag", assertTag(value)],
@@ -176,12 +176,11 @@ const ADAPTERS: Record<ManagedAppId, UpdateAdapter> = {
channel: false,
rollback: true,
uninstall: true,
- installCommand:
- "docker run -d --name 9router --restart unless-stopped -p 20128:20128 -v ~/.9router:/app/data -e DATA_DIR=/app/data decolua/9router:latest",
+ installCommand: "bash scripts/managed-app-9router install",
uninstallCommand: null,
},
- // No pin: the image ships one meaningful tag (latest). A rollback restores
- // the ~/.9router data snapshot; the image stays whatever is installed.
+ // The image is already pinned by reviewed digest. Rollback restores the
+ // ~/.9router data snapshot and keeps that digest in place.
pin: null,
updateArgv: (program, options) => {
if (options.dryRun) reject("dry run", "9router");
diff --git a/lib/managed-apps/update-probe.ts b/lib/managed-apps/update-probe.ts
index 5088fa38..af90784d 100644
--- a/lib/managed-apps/update-probe.ts
+++ b/lib/managed-apps/update-probe.ts
@@ -97,11 +97,11 @@ const asString = (value: unknown): string | null => (typeof value === "string" &
// --------------------------------------------------------------- 9Router ----
// The "CLI" is scripts/managed-app-9router (this repo). Its `check --json`
-// relays the app's own /api/version — {currentVersion, latestVersion,
-// hasUpdate} — which 9Router computes against Docker Hub itself.
+// compares the running image's RepoDigest with MSO's reviewed immutable digest;
+// it never asks a mutable registry tag what "latest" means.
export const NINE_ROUTER_CHANNEL_NOTE =
- "9Router ships a single Docker tag (latest); an update pulls the newest image and recreates the container with ~/.9router data intact.";
+ "9Router is pinned to the reviewed digest in security/managed-app-artifacts.env; update reconciles the container to that digest while keeping ~/.9router data intact.";
export async function probe9Router(program: string): Promise<ProbeResult> {
const channel: ManagedAppChannel = { value: null, kind: null, available: [], switchable: false, reason: NINE_ROUTER_CHANNEL_NOTE };
diff --git a/lib/managed-apps/update.test.ts b/lib/managed-apps/update.test.ts
index fb3a636e..02028f44 100644
--- a/lib/managed-apps/update.test.ts
+++ b/lib/managed-apps/update.test.ts
@@ -114,8 +114,9 @@ describe("checkUpdate normalises two CLIs that agree on nothing", () => {
expect(status.error).toContain("not installed");
expect(status.updateAvailable).toBeNull();
expect(status.capabilities).toMatchObject({ apply: false, uninstall: false });
- // Install is never automated — both installers are interactive.
- expect(status.capabilities.installCommand).toContain("install.sh");
+ // The recovery command uses MSO's committed checksum-verifying installer,
+ // never a mutable upstream curl|bash entrypoint.
+ expect(status.capabilities.installCommand).toContain("scripts/managed-app-install");
});
});
diff --git a/lib/mcp/tools-discovery-read.test.ts b/lib/mcp/tools-discovery-read.test.ts
index e94a7f3c..eb702d23 100644
--- a/lib/mcp/tools-discovery-read.test.ts
+++ b/lib/mcp/tools-discovery-read.test.ts
@@ -5,7 +5,7 @@ import os from "os";
import path from "path";
// Same fixture as tools-discovery.test.ts (see its header). This half covers
-// skills_read: exact ids, ambiguity refusal and withheld untrusted instructions.
+// skills_read: exact ids, ambiguity refusal, and fail-closed symlink roots.
//
// TWO configured containers, each holding a project called `widget`. That duplicate is
// the point: it is exactly the case that used to collapse into one row, hiding a whole
@@ -29,9 +29,8 @@ async function skill(dir: string, name: string, description: string, body = "ste
await skill(path.join(widgetA, ".claude/skills"), "widget-deploy", "Ship the widget service from root A.");
await fs.writeFile(path.join(widgetA, "package.json"), JSON.stringify({ name: "widget", version: "0.1.0" }));
await skill(path.join(widgetB, ".claude/skills"), "widget-deploy", "Ship the widget service from root B.");
-// A project whose skills ROOT escapes the project via symlink: the SKILL.md is a real
-// regular file, so it is discoverable — but containment fails, so it is untrusted and
-// its instructions are withheld.
+// A project whose skills ROOT escapes via symlink. The scanner rejects the root before
+// opening any metadata, so it is not a readable or discoverable skill.
const escaped = path.join(base, "escaped-skills");
await skill(escaped, "gadget-wild", "Unverified, outside its project.");
await fs.mkdir(path.join(gadget, ".codex"), { recursive: true });
@@ -87,12 +86,9 @@ describe("skills_read reads the exact catalog id only", () => {
expect(result.content.length).toBeGreaterThan(0);
});
- it("withholds instructions for an untrusted skill but still reports metadata", async () => {
- const result = await run("skills_read", { name: await skillId(gadget, "gadget-wild") }) as
- { instructionsWithheld: boolean; reason: string; content?: string; trust: string };
- expect(result).toMatchObject({ instructionsWithheld: true, trust: "untrusted" });
- expect(result.content).toBeUndefined();
- expect(result.reason).toContain("~/.mso/skills");
+ it("refuses an exact id whose project skill root escapes through a symlink", async () => {
+ await expect(run("skills_read", { name: await skillId(gadget, "gadget-wild") }))
+ .rejects.toThrow(/unknown skill id/);
});
it("REFUSES an ambiguous bare name and lists the exact ids", async () => {
@@ -103,10 +99,8 @@ describe("skills_read reads the exact catalog id only", () => {
await expect(run("skills_read", { name: "widget-deploy" })).rejects.toThrow(await projectId(widgetA));
});
- it("resolves an UNambiguous bare project-skill name", async () => {
- await expect(run("skills_read", { name: "gadget-wild" })).resolves.toMatchObject({
- id: await skillId(gadget, "gadget-wild"),
- });
+ it("does not resolve a bare name from a rejected symlink root", async () => {
+ await expect(run("skills_read", { name: "gadget-wild" })).rejects.toThrow(/unknown skill id/);
});
it("refuses an unknown id rather than guessing", async () => {
diff --git a/lib/mcp/tools-discovery.test.ts b/lib/mcp/tools-discovery.test.ts
index 26e210fc..eccbbe7b 100644
--- a/lib/mcp/tools-discovery.test.ts
+++ b/lib/mcp/tools-discovery.test.ts
@@ -36,9 +36,8 @@ await fs.writeFile(path.join(widgetA, ".mso/functions.json"), JSON.stringify({
}],
}));
await skill(path.join(widgetB, ".claude/skills"), "widget-deploy", "Ship the widget service from root B.");
-// A project whose skills ROOT escapes the project via symlink: the SKILL.md is a real
-// regular file, so it is discoverable — but containment fails, so it is untrusted and
-// its instructions are withheld.
+// A project whose skills ROOT escapes via symlink. The hardened scanner rejects the
+// root before opening any metadata, so the outside tree is not cataloged at all.
const escaped = path.join(base, "escaped-skills");
await skill(escaped, "gadget-wild", "Unverified, outside its project.");
await fs.mkdir(path.join(gadget, ".codex"), { recursive: true });
@@ -141,12 +140,10 @@ describe("skills_list spans global and project roots", () => {
expect(skills.map((s) => s.id)).toEqual(expect.arrayContaining([a, b]));
});
- it("marks a project skill outside its project untrusted and unreadable", async () => {
+ it("does not traverse a project skill root that escapes through a symlink", async () => {
const { skills } = await run("skills_list", { limit: 200 }) as { skills: SkillRow[] };
const wild = await skillId(gadget, "gadget-wild");
- expect(skills.find((s) => s.id === wild)).toMatchObject({
- trust: "untrusted", instructionsReadable: false,
- });
+ expect(skills.map((s) => s.id)).not.toContain(wild);
});
it("DROPS a skill whose SKILL.md is a symlink — nofollow means it is not a skill", async () => {
diff --git a/lib/mcp/tools-learning.ts b/lib/mcp/tools-learning.ts
index 9b0d3591..72650e72 100644
--- a/lib/mcp/tools-learning.ts
+++ b/lib/mcp/tools-learning.ts
@@ -27,6 +27,8 @@ export const LEARNING_TOOLS: McpTool[] = [
constraints: { type: "string", description: "Optional important constraints, such as no downtime or WebP only." },
}, ["intent"]),
run: async (a, context) => {
+ const actor = context.actor;
+ if (!actor) throw new Error("workflow memory needs an authenticated MCP actor");
const intent = str(a, "intent");
const projectHint = opt(a, "project");
const project = projectHint ? await resolveProjectHint(projectHint).catch(() => null) : null;
@@ -36,6 +38,7 @@ export const LEARNING_TOOLS: McpTool[] = [
// leave a run the client never received an id for and therefore cannot close.
const search = await searchSkillMemory(intent, {
topK: 8,
+ recipeAccess: { actor, scope: context.scope },
toolDocs: tools.map((tool) => ({
name: tool.name, description: tool.description, scope: tool.scope, inputSchema: tool.inputSchema,
})),
@@ -52,14 +55,17 @@ export const LEARNING_TOOLS: McpTool[] = [
complete: !search.catalog.truncated,
};
const started = await startWorkflow({
- actor: context.actor,
+ actor,
+ scope: context.scope,
intent,
project: project?.path ?? projectHint,
constraints: opt(a, "constraints"),
});
// Recommendation telemetry is useful, but failure to persist lastUsedAt must
// never turn a successfully-created workflow into an opaque tool failure.
- if (search.recommendedRecipe) await markRecipeUsed(search.recommendedRecipe.id).catch(() => undefined);
+ if (search.recommendedRecipe) {
+ await markRecipeUsed(search.recommendedRecipe.id, { actor, scope: context.scope }).catch(() => undefined);
+ }
return {
...started,
bootstrap: {
diff --git a/lib/mcp/tools-read.ts b/lib/mcp/tools-read.ts
index 7e120ae3..df96d7fb 100644
--- a/lib/mcp/tools-read.ts
+++ b/lib/mcp/tools-read.ts
@@ -117,9 +117,10 @@ export const READ_TOOLS: McpTool[] = [
top_k: { type: "number", minimum: 1, maximum: 20, description: "Maximum matches. Default 8." },
include_untrusted: { type: "boolean", description: "Include metadata-only matches from untrusted skill roots. Default false." },
}, ["query"]),
- run: async (a) => {
+ run: async (a, context) => {
const { TOOLS } = await import("./tools");
return searchSkillMemory(str(a, "query"), {
+ ...(context.actor ? { recipeAccess: { actor: context.actor, scope: context.scope } } : {}),
topK: typeof a.top_k === "number" ? a.top_k : undefined,
includeUntrusted: a.include_untrusted === true,
toolDocs: TOOLS.map((t) => ({ name: t.name, description: t.description, scope: t.scope, inputSchema: t.inputSchema })),
diff --git a/lib/security-store-lock.test.ts b/lib/security-store-lock.test.ts
new file mode 100644
index 00000000..d8f1905e
--- /dev/null
+++ b/lib/security-store-lock.test.ts
@@ -0,0 +1,60 @@
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { withSecurityStoreLock } from "./security-store-lock";
+
+const roots: string[] = [];
+async function tempStore() {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-lock-"));
+ roots.push(root);
+ return path.join(root, "store.json");
+}
+afterEach(async () => {
+ await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));
+});
+
+describe("security-store stale recovery", () => {
+ it("serializes simultaneous recoverers before either callback enters", async () => {
+ const store = await tempStore();
+ const lock = `${store}.lock`;
+ await fs.writeFile(lock, "999999999:abandoned", { mode: 0o600 });
+ let active = 0;
+ let maxActive = 0;
+ const entered: number[] = [];
+ await Promise.all(Array.from({ length: 24 }, (_, index) =>
+ withSecurityStoreLock(store, async () => {
+ active += 1;
+ maxActive = Math.max(maxActive, active);
+ entered.push(index);
+ await new Promise((resolve) => setTimeout(resolve, 2));
+ active -= 1;
+ }, { waitMs: 1, busyTimeoutMs: 2_000, staleMs: 1 }),
+ ));
+ expect(maxActive).toBe(1);
+ expect(entered).toHaveLength(24);
+ await expect(fs.stat(lock)).rejects.toMatchObject({ code: "ENOENT" });
+ });
+
+ it("never deletes a live lock merely because it is old", async () => {
+ const store = await tempStore();
+ const lock = `${store}.lock`;
+ await fs.writeFile(lock, `${process.pid}:live`, { mode: 0o600 });
+ const old = new Date(Date.now() - 60_000);
+ await fs.utimes(lock, old, old);
+ await expect(withSecurityStoreLock(store, async () => undefined, {
+ waitMs: 2, busyTimeoutMs: 25, staleMs: 1,
+ })).rejects.toThrow(/security store is busy/);
+ await expect(fs.readFile(lock, "utf8")).resolves.toBe(`${process.pid}:live`);
+ });
+
+ it("fails closed behind an existing recovery guard", async () => {
+ const store = await tempStore();
+ await fs.writeFile(`${store}.lock`, "999999999:abandoned", { mode: 0o600 });
+ await fs.writeFile(`${store}.lock.recovery`, `${process.pid}:guard`, { mode: 0o600 });
+ await expect(withSecurityStoreLock(store, async () => undefined, {
+ waitMs: 2, busyTimeoutMs: 25, staleMs: 1,
+ })).rejects.toThrow(/security store is busy/);
+ await expect(fs.readFile(`${store}.lock`, "utf8")).resolves.toContain("abandoned");
+ });
+});
diff --git a/lib/security-store-lock.ts b/lib/security-store-lock.ts
index adae6bbe..e3ad2fc5 100644
--- a/lib/security-store-lock.ts
+++ b/lib/security-store-lock.ts
@@ -1,20 +1,22 @@
import { randomUUID } from "node:crypto";
import { promises as fs } from "node:fs";
-import type { FileHandle } from "node:fs/promises";
import path from "node:path";
// Cross-process lock for the tiny JSON files that carry security decisions.
// Atomic rename protects one write, but not a whole read-modify-write transaction.
// The web process also serializes in-process callers; this lock covers supported
// operator-side helpers (notably `mso device ...`) that edit the same store.
-const WAIT_MS = 25;
-const BUSY_TIMEOUT_MS = 3_000;
-const STALE_MS = 30_000;
+const DEFAULTS = { waitMs: 25, busyTimeoutMs: 3_000, staleMs: 30_000 } as const;
+
+export type SecurityStoreLockTimings = {
+ waitMs?: number;
+ busyTimeoutMs?: number;
+ staleMs?: number;
+};
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
interface HeldLock {
- handle: FileHandle;
token: string;
}
@@ -27,7 +29,7 @@ function pidIsGone(pid: number): boolean {
}
}
-async function abandoned(lockPath: string): Promise<boolean> {
+async function abandoned(lockPath: string, staleMs: number): Promise<boolean> {
const stat = await fs.stat(lockPath).catch(() => null);
if (!stat) return true;
const age = Date.now() - stat.mtimeMs;
@@ -36,46 +38,104 @@ async function abandoned(lockPath: string): Promise<boolean> {
// A valid, live PID wins over age: never break mutual exclusion merely because
// the process was paused. Age is only the recovery path for malformed owner data.
if (Number.isInteger(pid) && pid > 1) return pidIsGone(pid);
- return age > STALE_MS;
+ return age > staleMs;
+}
+
+async function openExclusive(lockPath: string, token: string): Promise<HeldLock> {
+ // Build the complete owner record under a private candidate name, then publish it
+ // with one atomic hard-link. A competing recoverer can never observe an empty or
+ // partially-written live lock.
+ const candidate = `${lockPath}.${randomUUID()}.candidate`;
+ const handle = await fs.open(candidate, "wx", 0o600);
+ try {
+ await handle.writeFile(token, "utf8");
+ await handle.sync();
+ } finally {
+ await handle.close().catch(() => undefined);
+ }
+ try {
+ await fs.link(candidate, lockPath);
+ } finally {
+ await fs.unlink(candidate).catch(() => undefined);
+ }
+ return { token };
+}
+
+async function release(lockPath: string, held: HeldLock): Promise<void> {
+ const owner = await fs.readFile(lockPath, "utf8").catch(() => "");
+ // Never remove a lock that a recovery path may have handed to another process.
+ if (owner === held.token) await fs.unlink(lockPath).catch(() => undefined);
}
-async function acquire(lockPath: string): Promise<HeldLock> {
+async function acquire(lockPath: string, timings: Required<SecurityStoreLockTimings>): Promise<HeldLock> {
await fs.mkdir(path.dirname(lockPath), { recursive: true, mode: 0o700 });
const token = `${process.pid}:${randomUUID()}`;
- const deadline = Date.now() + BUSY_TIMEOUT_MS;
+ const recoveryPath = `${lockPath}.recovery`;
+ const deadline = Date.now() + timings.busyTimeoutMs;
+
while (true) {
+ // Every contender takes the recovery guard before inspecting or publishing the
+ // primary lock. Without this shared acquisition gate, a stale-lock recoverer can
+ // stat an old lock, observe ENOENT while its owner releases, then unlink a newly
+ // published live lock at the same pathname (a classic check/unlink ABA race).
+ let gate: HeldLock | null = null;
try {
- const handle = await fs.open(lockPath, "wx", 0o600);
- try {
- await handle.writeFile(token, "utf8");
- } catch (error) {
- await handle.close().catch(() => undefined);
- await fs.unlink(lockPath).catch(() => undefined);
- throw error;
- }
- return { handle, token };
+ gate = await openExclusive(recoveryPath, `${process.pid}:${randomUUID()}`);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
- if (await abandoned(lockPath)) {
- await fs.unlink(lockPath).catch(() => undefined);
- continue;
+ }
+
+ if (gate) {
+ try {
+ try {
+ // Publish the primary lock before releasing the gate. A recoverer that
+ // removes an abandoned owner therefore hands the path directly to itself;
+ // no second contender can slip into the unlink/create interval.
+ return await openExclusive(lockPath, token);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ }
+
+ if (await abandoned(lockPath, timings.staleMs)) {
+ try {
+ await fs.unlink(lockPath);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ }
+ // Still under the shared gate: either this succeeds, or an unsupported
+ // external writer raced us and we fail closed by retrying rather than
+ // deleting an unverified replacement.
+ try {
+ return await openExclusive(lockPath, token);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ }
+ }
+ } finally {
+ // Recovery guards are deliberately NOT auto-broken. A crashed guard causes
+ // an availability failure requiring manual cleanup, never a revocation-losing
+ // race. Normal acquisition holds this guard only for the short publish step.
+ await release(recoveryPath, gate);
}
- if (Date.now() >= deadline) throw new Error("security store is busy; retry the operation");
- await sleep(WAIT_MS);
}
- }
-}
-async function release(lockPath: string, held: HeldLock): Promise<void> {
- await held.handle.close().catch(() => undefined);
- const owner = await fs.readFile(lockPath, "utf8").catch(() => "");
- // Never remove a lock that a stale-lock recovery may have handed to another process.
- if (owner === held.token) await fs.unlink(lockPath).catch(() => undefined);
+ if (Date.now() >= deadline) throw new Error("security store is busy; retry the operation");
+ await sleep(timings.waitMs);
+ }
}
-export async function withSecurityStoreLock<T>(storePath: string, fn: () => Promise<T>): Promise<T> {
+export async function withSecurityStoreLock<T>(
+ storePath: string,
+ fn: () => Promise<T>,
+ options: SecurityStoreLockTimings = {},
+): Promise<T> {
+ const timings = {
+ waitMs: options.waitMs ?? DEFAULTS.waitMs,
+ busyTimeoutMs: options.busyTimeoutMs ?? DEFAULTS.busyTimeoutMs,
+ staleMs: options.staleMs ?? DEFAULTS.staleMs,
+ };
const lockPath = `${storePath}.lock`;
- const held = await acquire(lockPath);
+ const held = await acquire(lockPath, timings);
try {
return await fn();
} finally {
diff --git a/lib/security/managed-app-supply-chain.test.ts b/lib/security/managed-app-supply-chain.test.ts
new file mode 100644
index 00000000..67a64aac
--- /dev/null
+++ b/lib/security/managed-app-supply-chain.test.ts
@@ -0,0 +1,56 @@
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+const ROOT = path.join(__dirname, "../..");
+const INSTALL = path.join(ROOT, "scripts/managed-app-install");
+const ROUTER = path.join(ROOT, "scripts/managed-app-9router");
+const LOCK = path.join(ROOT, "security/managed-app-artifacts.env");
+const source = (file: string) => fs.readFileSync(file, "utf8");
+
+describe("managed-app immutable artifact contract", () => {
+ it("keeps every executable artifact identity in a reviewed lock file", () => {
+ const lock = source(LOCK);
+ expect(lock).toMatch(/HERMES_INSTALLER_TAG='v[^']+'/);
+ expect(lock).toMatch(/HERMES_INSTALLER_COMMIT='[0-9a-f]{40}'/);
+ expect(lock).toMatch(/HERMES_INSTALLER_SHA256='[0-9a-f]{64}'/);
+ expect(lock).toMatch(/OPENCLAW_VERSION='[^']+'/);
+ expect(lock).toMatch(/OPENCLAW_TARBALL_SHA512='[0-9a-f]{128}'/);
+ expect(lock).toMatch(/NINE_ROUTER_IMAGE_REF='[^']+@sha256:[0-9a-f]{64}'/);
+ });
+
+ it("verifies Hermes installer bytes and pins the repository checkout", () => {
+ const script = source(INSTALL);
+ expect(script).toContain("sha256sum -c -");
+ expect(script).toContain('--commit "$HERMES_INSTALLER_COMMIT" --force-commit');
+ expect(script).toContain("--proto '=https'");
+ expect(script).not.toContain("hermes-agent.nousresearch.com/install.sh");
+ const executable = script.split("\n").filter((line) => !line.trimStart().startsWith("#")).join("\n");
+ expect(executable).not.toMatch(/curl[^\n]+\|\s*(?:ba)?sh/);
+ });
+
+ it("verifies an exact OpenClaw tarball before lifecycle scripts can run", () => {
+ const script = source(INSTALL);
+ expect(script).toContain('npm pack "openclaw@$OPENCLAW_VERSION"');
+ expect(script).toContain('sha512sum "$tmp/$tarball"');
+ expect(script).toContain('[ "$actual" = "$OPENCLAW_TARBALL_SHA512" ]');
+ expect(script).not.toContain("openclaw@latest");
+ });
+
+ it("accepts only immutable 9Router references and verifies pulled/running digests", () => {
+ const script = source(ROUTER);
+ expect(script).toContain("@sha256:");
+ expect(script).toContain('^sha256:[0-9a-f]{64}$');
+ expect(script).toContain("image_has_expected_digest");
+ expect(script).toContain("running_image_matches_lock");
+ expect(script).not.toContain("decolua/9router:latest");
+ const check = script.slice(script.indexOf("cmd_check() {"), script.indexOf("# Pull latest"));
+ expect(check).not.toContain("$BASE/api/version");
+ });
+
+ it("keeps both lifecycle scripts syntactically valid", () => {
+ expect(() => execFileSync("bash", ["-n", INSTALL])).not.toThrow();
+ expect(() => execFileSync("bash", ["-n", ROUTER])).not.toThrow();
+ });
+});
diff --git a/lib/security/private-shell-state.test.ts b/lib/security/private-shell-state.test.ts
new file mode 100644
index 00000000..824a202b
--- /dev/null
+++ b/lib/security/private-shell-state.test.ts
@@ -0,0 +1,104 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+const ROOT = path.join(__dirname, "../..");
+const HELPER = path.join(ROOT, "scripts/lib/private-state.sh");
+const CLI = path.join(ROOT, "bin/mso");
+const EDITOR = path.join(ROOT, "claude-skills/mso-image-editor/image-editor.sh");
+const ULTIMATE = path.join(ROOT, "scripts/security-ultimate.sh");
+const roots: string[] = [];
+
+function tempRoot() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-private-state-"));
+ fs.chmodSync(root, 0o700);
+ roots.push(root);
+ return root;
+}
+
+function bash(body: string) {
+ return spawnSync("bash", ["-c", `set -euo pipefail; . ${JSON.stringify(HELPER)}; ${body}`], {
+ encoding: "utf8",
+ });
+}
+
+afterEach(() => {
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe("private shell state", () => {
+ it("creates owner-only directories and 0600 regular files", () => {
+ const root = tempRoot();
+ const file = path.join(root, "nested", "cookie.jar");
+ const run = bash(`p=$(mso_private_state_ensure_file ${JSON.stringify(file)}); printf '%s' "$p"`);
+ expect(run.status).toBe(0);
+ expect(run.stdout).toBe(file);
+ expect(fs.statSync(path.dirname(file)).mode & 0o777).toBe(0o700);
+ expect(fs.statSync(file).mode & 0o777).toBe(0o600);
+ expect(fs.statSync(file).isFile()).toBe(true);
+ });
+
+ it("refuses a pre-created symlink without touching its target", () => {
+ const root = tempRoot();
+ const dir = path.join(root, "private");
+ fs.mkdirSync(dir, { mode: 0o700 });
+ const target = path.join(root, "target");
+ fs.writeFileSync(target, "sentinel", { mode: 0o600 });
+ const file = path.join(dir, "cookie.jar");
+ fs.symlinkSync(target, file);
+ const run = bash(`mso_private_state_ensure_file ${JSON.stringify(file)}`);
+ expect(run.status).not.toBe(0);
+ expect(run.stderr).toContain("refusing symlink file");
+ expect(fs.readFileSync(target, "utf8")).toBe("sentinel");
+ });
+
+ it("refuses an existing file whose permissions are not 0600", () => {
+ const root = tempRoot();
+ const dir = path.join(root, "private");
+ fs.mkdirSync(dir, { mode: 0o700 });
+ const file = path.join(dir, "cookie.jar");
+ fs.writeFileSync(file, "exposed", { mode: 0o600 });
+ // The ultimate gate deliberately runs under umask 077. Node applies umask to
+ // the create mode, so `{ mode: 0o644 }` alone can silently create 0600 and make
+ // this negative fixture test the safe path instead. Force the post-create mode.
+ fs.chmodSync(file, 0o644);
+ expect(fs.statSync(file).mode & 0o777).toBe(0o644);
+ const run = bash(`mso_private_state_ensure_file ${JSON.stringify(file)}`);
+ expect(run.status).not.toBe(0);
+ expect(run.stderr).toContain("file must be mode 0600");
+ expect(fs.readFileSync(file, "utf8")).toBe("exposed");
+ });
+
+ it("atomically replaces only a validated regular session file", () => {
+ const root = tempRoot();
+ const file = path.join(root, "private", "session.json");
+ const first = bash(`printf '%s' '{"v":1}' | mso_private_state_atomic_write ${JSON.stringify(file)} >/dev/null`);
+ expect(first.status).toBe(0);
+ const second = bash(`printf '%s' '{"v":2}' | mso_private_state_atomic_write ${JSON.stringify(file)} >/dev/null`);
+ expect(second.status).toBe(0);
+ expect(fs.readFileSync(file, "utf8")).toBe('{"v":2}');
+ expect(fs.statSync(file).mode & 0o777).toBe(0o600);
+ });
+
+ it("wires both clients away from shared /tmp defaults and validates every bearer file", () => {
+ const cli = fs.readFileSync(CLI, "utf8");
+ const editor = fs.readFileSync(EDITOR, "utf8");
+ expect(cli).toContain("$HOME/.mso/private");
+ expect(cli).not.toContain('${TMPDIR:-/tmp}/mso-$(id -u)');
+ expect(cli).toContain('mso_private_state_validate_file "$JAR"');
+ expect(editor).toContain("$HOME/.mso/private");
+ expect(editor).not.toContain("${TMPDIR:-/tmp}/mso-image-editor.jar");
+ expect(editor).not.toContain("${TMPDIR:-/tmp}/mso-image-editor.session.json");
+ expect(editor).toContain('mso_private_state_atomic_write "$SESS"');
+ });
+
+ it("keeps shell scripts syntactically valid and the ultimate runner self-sufficient", () => {
+ for (const script of [HELPER, CLI, EDITOR, ULTIMATE]) {
+ expect(() => execFileSync("bash", ["-n", script])).not.toThrow();
+ }
+ const ultimate = fs.readFileSync(ULTIMATE, "utf8");
+ expect(ultimate).toContain('export PATH="$HOME/.bun/bin:$HOME/.local/bin:');
+ });
+});
diff --git a/lib/skills/catalog-continuation.test.ts b/lib/skills/catalog-continuation.test.ts
index 1f09cfa0..b5c837ed 100644
--- a/lib/skills/catalog-continuation.test.ts
+++ b/lib/skills/catalog-continuation.test.ts
@@ -117,3 +117,16 @@ describe("a complete catalog build reports no continuation", () => {
expect(scan.continuation).toBeUndefined();
});
});
+
+describe("continuation cursor integrity", () => {
+ it("rejects a forged offset instead of fast-forwarding the directory walk", async () => {
+ const app = await temp();
+ await skillsIn(path.join(app, "claude-skills"), 3, "f");
+ const forged = Buffer.from(JSON.stringify({
+ doneRoots: [], projectOffset: 0,
+ resume: { root: path.join(app, "claude-skills"), entriesConsumed: 10_000_000 },
+ })).toString("base64url");
+ const page = await catalogSkillsDetailed({ appDir: app, homeDir: await temp(), projects: [], cursor: forged });
+ expect(page.skills.map((s) => s.id).filter((id) => id.startsWith("f"))).toHaveLength(3);
+ });
+});
diff --git a/lib/skills/catalog-cursor.ts b/lib/skills/catalog-cursor.ts
index d08b8c87..1ababf69 100644
--- a/lib/skills/catalog-cursor.ts
+++ b/lib/skills/catalog-cursor.ts
@@ -1,25 +1,67 @@
-// Encoding for a resumable skill-catalog position. Same contract as the project walk's
-// cursor: a cap the caller cannot continue past is data loss with a label on it.
-import type { SkillScanCursor } from "./catalog-types";
+// Signed, bounded encoding for a resumable skill-catalog position. The cursor is
+// caller-controlled input even though MSO minted it; authenticity prevents a client from
+// inventing a huge fast-forward offset, while strict structural caps bound decode work.
+import { createHmac, randomBytes, timingSafeEqual } from "crypto";
+import { SKILL_SCAN_LIMITS, type SkillScanCursor } from "./catalog-types";
+
+const VERSION = "v1";
+const FALLBACK_SECRET = randomBytes(32);
+
+function secret(): Buffer {
+ const configured = process.env.OS_SESSION_SECRET;
+ return configured ? Buffer.from(configured, "utf8") : FALLBACK_SECRET;
+}
+
+function mac(payload: string): string {
+ return createHmac("sha256", secret()).update(`${VERSION}.${payload}`).digest("base64url");
+}
+
+function normalize(parsed: SkillScanCursor): SkillScanCursor | undefined {
+ if (!parsed || typeof parsed !== "object") return undefined;
+ const doneRoots = Array.isArray(parsed.doneRoots)
+ ? [...new Set(parsed.doneRoots.filter((r): r is string => typeof r === "string" && r.length > 0 && r.length <= 4096))].slice(0, 512)
+ : [];
+ const projectOffset = Number.isFinite(parsed.projectOffset)
+ ? Math.min(SKILL_SCAN_LIMITS.maxProjects, Math.max(0, Math.floor(parsed.projectOffset)))
+ : 0;
+ const root = parsed.resume && typeof parsed.resume.root === "string" && parsed.resume.root.length <= 4096
+ ? parsed.resume.root
+ : undefined;
+ const entries = parsed.resume && Number.isFinite(parsed.resume.entriesConsumed)
+ ? Math.max(0, Math.floor(parsed.resume.entriesConsumed ?? 0))
+ : 0;
+ if (entries > SKILL_SCAN_LIMITS.maxResumeEntriesPerRoot) return undefined;
+ return {
+ doneRoots,
+ projectOffset,
+ ...(root ? { resume: { root, entriesConsumed: entries } } : {}),
+ };
+}
export function encodeSkillCursor(cursor: SkillScanCursor): string {
- return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
+ const safe = normalize(cursor);
+ if (!safe) throw new Error("skill cursor exceeds structural limits");
+ const json = JSON.stringify(safe);
+ if (Buffer.byteLength(json, "utf8") > SKILL_SCAN_LIMITS.maxCursorBytes) {
+ throw new Error("skill cursor exceeds byte limit");
+ }
+ const payload = Buffer.from(json, "utf8").toString("base64url");
+ return `${VERSION}.${payload}.${mac(payload)}`;
}
export function decodeSkillCursor(raw: string | undefined): SkillScanCursor | undefined {
- if (!raw) return undefined;
+ if (!raw || raw.length > Math.ceil(SKILL_SCAN_LIMITS.maxCursorBytes * 1.5) + 128) return undefined;
+ const [version, payload, suppliedMac, extra] = raw.split(".");
+ if (version !== VERSION || !payload || !suppliedMac || extra !== undefined) return undefined;
+ const expected = mac(payload);
+ const a = Buffer.from(suppliedMac, "utf8");
+ const b = Buffer.from(expected, "utf8");
+ if (a.length !== b.length || !timingSafeEqual(a, b)) return undefined;
try {
- const parsed = JSON.parse(Buffer.from(raw, "base64url").toString("utf8")) as SkillScanCursor;
- if (!parsed || typeof parsed !== "object") return undefined;
- return {
- doneRoots: Array.isArray(parsed.doneRoots) ? parsed.doneRoots.filter((r) => typeof r === "string") : [],
- projectOffset: Number.isFinite(parsed.projectOffset) ? Math.max(0, Math.floor(parsed.projectOffset)) : 0,
- ...(parsed.resume && typeof parsed.resume.root === "string"
- ? { resume: { root: parsed.resume.root, entriesConsumed: Math.max(0, Math.floor(parsed.resume.entriesConsumed ?? 0)) } }
- : {}),
- };
+ const decoded = Buffer.from(payload, "base64url");
+ if (decoded.byteLength > SKILL_SCAN_LIMITS.maxCursorBytes) return undefined;
+ return normalize(JSON.parse(decoded.toString("utf8")) as SkillScanCursor);
} catch {
return undefined;
}
}
-
diff --git a/lib/skills/catalog-scan.ts b/lib/skills/catalog-scan.ts
index d3145a88..ba2dbd6d 100644
--- a/lib/skills/catalog-scan.ts
+++ b/lib/skills/catalog-scan.ts
@@ -98,43 +98,50 @@ export async function scanRoot(
try {
for await (const entry of handle) {
seen += 1;
- if (seen <= skipEntries) continue;
- // EVERY dirent costs budget, accepted or not — and every stop check happens before
- // the entry is processed, so `consumed` never runs ahead of the work.
+ if (seen <= skipEntries) {
+ // A continuation is signed, but directory contents may have grown. Fast-forwarding
+ // still obeys the same wall-clock guard and a hard lifetime offset cap.
+ if (seen > SKILL_SCAN_LIMITS.maxResumeEntriesPerRoot) { stop = "maxEntriesPerRoot"; break; }
+ if (Date.now() > deadlineAt) { stop = "deadline"; break; }
+ continue;
+ }
+ // EVERY new dirent costs budget, accepted or not — and every stop check happens
+ // before the entry is processed, so `consumed` never runs ahead of the work.
if (processed >= SKILL_SCAN_LIMITS.maxEntriesPerRoot) { stop = "maxEntriesPerRoot"; break; }
if (Date.now() > deadlineAt) { stop = "deadline"; break; }
if (found.length >= budget) { stop = "budget"; break; }
processed += 1;
- if (entry.isDirectory() || entry.isSymbolicLink()) {
+ // Never follow a directory symlink into an attacker-controlled tree. For project
+ // skills, containment/ownership/shape are established BEFORE SKILL.md is opened.
+ if (entry.isDirectory()) {
const dir = path.join(spec.path, entry.name);
- if ((await fs.stat(dir).catch(() => null))?.isDirectory()) {
- const md = await readSkillFile(path.join(dir, SKILL_FILE));
- if (md !== null) {
- let trust = spec.trust;
- let provenance: SkillInfo["provenance"];
- if (spec.verifyClawHub) {
- const verified = await verifiedBundledSkill(dir, md);
- trust = verified.trust;
- provenance = verified.provenance;
- } else if (spec.project) {
- // Path alone grants nothing: containment, ownership and SKILL.md shape decide.
- trust = await projectSkillTrust(dir, spec.project.path);
- }
- found.push({
- priority: spec.priority,
- skill: {
- id: spec.project ? `${spec.project.id}/${entry.name}` : entry.name,
- name: entry.name,
- path: path.join(dir, SKILL_FILE),
- description: skillDescription(md),
- source: spec.source,
- trust,
- ...(spec.project ? { project: spec.project } : {}),
- ...(provenance ? { provenance } : {}),
- },
- });
+ let trust = spec.trust;
+ if (spec.project) {
+ trust = await projectSkillTrust(dir, spec.project.path);
+ if (trust !== "local") { consumed = seen; continue; }
+ }
+ const md = await readSkillFile(path.join(dir, SKILL_FILE));
+ if (md !== null) {
+ let provenance: SkillInfo["provenance"];
+ if (spec.verifyClawHub) {
+ const verified = await verifiedBundledSkill(dir, md);
+ trust = verified.trust;
+ provenance = verified.provenance;
}
+ found.push({
+ priority: spec.priority,
+ skill: {
+ id: spec.project ? `${spec.project.id}/${entry.name}` : entry.name,
+ name: entry.name,
+ path: path.join(dir, SKILL_FILE),
+ description: skillDescription(md),
+ source: spec.source,
+ trust,
+ ...(spec.project ? { project: spec.project } : {}),
+ ...(provenance ? { provenance } : {}),
+ },
+ });
}
}
consumed = seen; // ONLY now — the entry is fully handled.
diff --git a/lib/skills/catalog-types.ts b/lib/skills/catalog-types.ts
index 044f01d7..4e0a6a34 100644
--- a/lib/skills/catalog-types.ts
+++ b/lib/skills/catalog-types.ts
@@ -15,6 +15,13 @@ export const SKILL_SCAN_LIMITS = {
maxSkillBytes: 256 * 1024,
/** Wall-clock ceiling for one whole catalog build. */
maxScanMs: 4000,
+ /** Signed continuation payload cap before base64/HMAC framing. */
+ maxCursorBytes: 64 * 1024,
+ /** A valid continuation may fast-forward only this many directory entries. */
+ maxResumeEntriesPerRoot: 5_000,
+ /** Semantic routing accepts bounded owner intent, never an unbounded embedding job. */
+ maxSemanticQueryBytes: 4 * 1024,
+ maxSemanticQueryTerms: 256,
} as const;
export type SkillTrust = "official" | "verified" | "local" | "untrusted";
diff --git a/lib/skills/memory.test.ts b/lib/skills/memory.test.ts
index dd121942..d11cb551 100644
--- a/lib/skills/memory.test.ts
+++ b/lib/skills/memory.test.ts
@@ -28,7 +28,7 @@ describe("learned workflow recipes", () => {
id: "b", tool: "screen_capture", state: "completed", args: { shell: "macos", width: 1440, height: 900 }, durationMs: 2200, ts: new Date().toISOString(),
});
const two = await memory.finishWorkflow({ actor: "mcp:test", workflowId: second.workflow.id, summary: "same result in one faster call", success: true });
- const recipes = await memory.listLearnedRecipes();
+ const recipes = await memory.listLearnedRecipes({ ownerView: true });
expect(recipes).toHaveLength(1);
expect(two.recipe.attempts).toBe(2);
expect(two.recipe.fastestDurationMs).toBe(2200);
@@ -55,7 +55,7 @@ describe("learned workflow recipes", () => {
expect(done.recipe.bestSteps[0].args).toEqual({ shell: "macos", width: 1440, height: 900 });
});
- it("stores redacted command shape rather than credential payloads", async () => {
+ it("stores only a program sequence and never command arguments or credential payloads", async () => {
const started = await memory.startWorkflow({ actor: "mcp:test", intent: "run a scoped deployment command with token=top-secret" });
expect(started.workflow.intent).not.toContain("top-secret");
await memory.recordWorkflowStep("mcp:test", started.workflow.id, {
@@ -69,7 +69,9 @@ describe("learned workflow recipes", () => {
expect(stored).not.toContain("super-secret");
expect(stored).not.toContain("token=abc");
expect(stored).not.toContain("must-not-persist");
- expect(done.recipe.bestSteps[0].args).toMatchObject({ cwd: "/home/test/project" });
+ expect(done.recipe.bestSteps[0].target).toBe("npm → curl");
+ expect(done.recipe.bestSteps[0].args).toEqual({ cwd: "/home/test/project" });
+ expect(done.recipe.bestSteps[0].args).not.toHaveProperty("command");
});
it("keeps replayable allowlisted args but never write bodies", async () => {
@@ -119,7 +121,7 @@ describe("learned workflow recipes", () => {
it("migrates a live v1 actor workflow into an exact-id v2 bucket", async () => {
const legacy: ActiveWorkflow = {
- id: "legacy-workflow", actor: "mcp:legacy", intent: "finish the pre-deploy task",
+ id: "legacy-workflow", actor: "mcp:legacy", scope: "read", intent: "finish the pre-deploy task",
project: "~/projects/mso", startedAt: new Date().toISOString(), steps: [],
};
await fs.writeFile(process.env.OS_SKILL_MEMORY_STORE!, JSON.stringify({
@@ -133,7 +135,7 @@ describe("learned workflow recipes", () => {
const stored = JSON.parse(await fs.readFile(process.env.OS_SKILL_MEMORY_STORE!, "utf8")) as {
version: number; active: Record<string, Record<string, ActiveWorkflow>>;
};
- expect(stored.version).toBe(2);
+ expect(stored.version).toBe(3);
expect(stored.active["mcp:legacy"][legacy.id]).toMatchObject({ intent: legacy.intent });
expect(stored.active["mcp:legacy"][current.workflow.id]).toMatchObject({ intent: "new parallel task" });
});
@@ -172,4 +174,62 @@ describe("learned workflow recipes", () => {
expect(done.recipe.bestSteps.some((step) => step.id === "failed")).toBe(false);
});
+ it("partitions learned recipes by actor and never escalates caller scope", async () => {
+ const execRun = await memory.startWorkflow({ actor: "mcp:actor-a", scope: "exec", intent: "deploy private service" });
+ await memory.recordWorkflowStep("mcp:actor-a", execRun.workflow.id, {
+ id: "exec", tool: "exec_run", state: "completed", target: "deploy --private",
+ args: { command: "deploy --private", cwd: "/srv/private" }, durationMs: 10, ts: new Date().toISOString(),
+ });
+ await memory.finishWorkflow({ actor: "mcp:actor-a", workflowId: execRun.workflow.id, summary: "verified", success: true });
+
+ const writeRun = await memory.startWorkflow({ actor: "mcp:actor-a", scope: "write", intent: "write release note" });
+ await memory.recordWorkflowStep("mcp:actor-a", writeRun.workflow.id, {
+ id: "write", tool: "fs_write", state: "completed", target: "/srv/note.md",
+ args: { path: "/srv/note.md", content: "private" }, durationMs: 5, ts: new Date().toISOString(),
+ });
+ await memory.finishWorkflow({ actor: "mcp:actor-a", workflowId: writeRun.workflow.id, summary: "verified", success: true });
+
+ await expect(memory.listLearnedRecipes({ actor: "mcp:actor-b", scope: "exec" })).resolves.toEqual([]);
+ const readVisible = await memory.listLearnedRecipes({ actor: "mcp:actor-a", scope: "read" });
+ expect(readVisible).toEqual([]);
+ const writeVisible = await memory.listLearnedRecipes({ actor: "mcp:actor-a", scope: "write" });
+ expect(writeVisible).toHaveLength(1);
+ expect(writeVisible[0]).toMatchObject({ actor: "mcp:actor-a", scope: "write" });
+ expect(JSON.stringify(writeVisible)).not.toContain("deploy --private");
+ const execVisible = await memory.listLearnedRecipes({ actor: "mcp:actor-a", scope: "exec" });
+ expect(execVisible.map((r) => r.scope).sort()).toEqual(["exec", "write"]);
+ });
+
+ it("scrubs legacy raw command and write-body payloads while loading the store", async () => {
+ const now = new Date().toISOString();
+ await fs.writeFile(process.env.OS_SKILL_MEMORY_STORE!, JSON.stringify({
+ version: 2,
+ active: {},
+ recipes: {
+ legacy: {
+ id: "legacy", actor: "mcp:legacy", scope: "exec", intent: "deploy safely",
+ normalizedIntent: "deploy safely", summary: "done", embeddingVersion: "old", embedding: [],
+ bestSteps: [{
+ id: "exec", tool: "exec_run", state: "completed",
+ target: "TOKEN=raw-secret npm run build && curl https://x.invalid/private-value",
+ args: { command: "TOKEN=raw-secret npm run build", cwd: "/srv/app" }, ts: now,
+ }, {
+ id: "write", tool: "fs_write", state: "completed", target: "/srv/app/.env",
+ args: { path: "/srv/app/.env", content: "API_KEY=raw-secret" }, ts: now,
+ }],
+ lastSteps: [], attempts: 1, successes: 1, failures: 0,
+ averageDurationMs: 1, lastDurationMs: 1, averageWallDurationMs: 1, lastWallDurationMs: 1,
+ createdAt: now, updatedAt: now,
+ },
+ },
+ }), { mode: 0o600 });
+ memory.resetSkillMemoryCache();
+ const [recipe] = await memory.listLearnedRecipes({ actor: "mcp:legacy", scope: "exec" });
+ const serialized = JSON.stringify(recipe);
+ expect(serialized).not.toContain("raw-secret");
+ expect(serialized).not.toContain("private-value");
+ expect(recipe.bestSteps[0]).toMatchObject({ target: "npm → curl", args: { cwd: "/srv/app" } });
+ expect(recipe.bestSteps[1].args).toEqual({ path: "/srv/app/.env" });
+ });
+
});
diff --git a/lib/skills/memory.ts b/lib/skills/memory.ts
index 77c14e8e..b785984f 100644
--- a/lib/skills/memory.ts
+++ b/lib/skills/memory.ts
@@ -4,6 +4,7 @@ import { promises as fs } from "fs";
import os from "os";
import path from "path";
import { embedSkillText, hybridSemanticScore, normalizeSemanticText, SKILL_EMBEDDING_VERSION } from "./semantic";
+import { allows, type Scope } from "@/lib/mcp/scope";
export type WorkflowStepState = "completed" | "failed" | "denied" | "rate_limited";
@@ -23,6 +24,7 @@ type WorkflowStepInput = Omit<WorkflowStep, "args"> & { args?: Record<string, un
export type ActiveWorkflow = {
id: string;
actor: string;
+ scope: Scope;
intent: string;
project?: string;
constraints?: string;
@@ -32,6 +34,8 @@ export type ActiveWorkflow = {
export type LearnedRecipe = {
id: string;
+ actor: string;
+ scope: Scope;
intent: string;
normalizedIntent: string;
project?: string;
@@ -56,7 +60,7 @@ export type LearnedRecipe = {
type ActiveWorkflowBuckets = Record<string, Record<string, ActiveWorkflow>>;
type SkillMemoryStore = {
- version: 2;
+ version: 3;
active: ActiveWorkflowBuckets;
recipes: Record<string, LearnedRecipe>;
};
@@ -75,7 +79,7 @@ export type CancelWorkflowResult = {
reason?: string;
};
-const EMPTY = (): SkillMemoryStore => ({ version: 2, active: {}, recipes: {} });
+const EMPTY = (): SkillMemoryStore => ({ version: 3, active: {}, recipes: {} });
let cache: SkillMemoryStore | null = null;
let cachePath = "";
const loadInFlight = new Map<string, Promise<SkillMemoryStore>>();
@@ -102,19 +106,64 @@ function normalizeActive(value: unknown): ActiveWorkflowBuckets {
for (const [legacyActor, candidate] of Object.entries(value as Record<string, unknown>)) {
if (isActiveWorkflow(candidate)) {
const actor = candidate.actor || legacyActor;
- (active[actor] ??= {})[candidate.id] = candidate;
+ (active[actor] ??= {})[candidate.id] = {
+ ...candidate,
+ scope: candidate.scope ?? "read",
+ intent: safeMemoryText(candidate.intent, 1000),
+ project: candidate.project ? safeMemoryText(candidate.project, 240) || undefined : undefined,
+ constraints: candidate.constraints ? safeMemoryText(candidate.constraints, 500) || undefined : undefined,
+ steps: candidate.steps.map(sanitizeStoredStep).filter((step): step is WorkflowStep => Boolean(step)),
+ };
continue;
}
if (!candidate || typeof candidate !== "object") continue;
for (const workflow of Object.values(candidate as Record<string, unknown>)) {
if (!isActiveWorkflow(workflow)) continue;
const actor = workflow.actor || legacyActor;
- (active[actor] ??= {})[workflow.id] = workflow;
+ (active[actor] ??= {})[workflow.id] = {
+ ...workflow,
+ scope: workflow.scope ?? "read",
+ intent: safeMemoryText(workflow.intent, 1000),
+ project: workflow.project ? safeMemoryText(workflow.project, 240) || undefined : undefined,
+ constraints: workflow.constraints ? safeMemoryText(workflow.constraints, 500) || undefined : undefined,
+ steps: workflow.steps.map(sanitizeStoredStep).filter((step): step is WorkflowStep => Boolean(step)),
+ };
}
}
return active;
}
+function normalizeRecipes(value: unknown): Record<string, LearnedRecipe> {
+ if (!value || typeof value !== "object") return {};
+ const out: Record<string, LearnedRecipe> = {};
+ for (const [id, candidate] of Object.entries(value as Record<string, unknown>)) {
+ if (!candidate || typeof candidate !== "object") continue;
+ const row = candidate as Partial<LearnedRecipe>;
+ if (typeof row.id !== "string" || typeof row.intent !== "string" || !Array.isArray(row.bestSteps)) continue;
+ const scope: Scope = row.scope === "write" || row.scope === "exec" ? row.scope : "read";
+ const intent = safeMemoryText(row.intent, 1000);
+ if (!intent) continue;
+ out[id] = {
+ ...(row as LearnedRecipe),
+ // Legacy global recipes remain owner-visible but are never replayed to an MCP token.
+ actor: typeof row.actor === "string" && row.actor ? row.actor : "legacy:owner",
+ scope,
+ intent,
+ project: row.project ? safeMemoryText(row.project, 240) || undefined : undefined,
+ summary: safeMemoryText(typeof row.summary === "string" ? row.summary : "completed", 1200) || "completed",
+ bestSteps: row.bestSteps.map(sanitizeStoredStep).filter((step): step is WorkflowStep => Boolean(step)),
+ lastSteps: Array.isArray(row.lastSteps)
+ ? row.lastSteps.map(sanitizeStoredStep).filter((step): step is WorkflowStep => Boolean(step))
+ : [],
+ };
+ }
+ return out;
+}
+
+export type RecipeAccess =
+ | { actor: string; scope: Scope; ownerView?: false }
+ | { ownerView: true; actor?: never; scope?: never };
+
async function loadStore(): Promise<SkillMemoryStore> {
const file = storePath();
if (cache && cachePath === file) return cache;
@@ -135,11 +184,9 @@ async function loadStore(): Promise<SkillMemoryStore> {
}
const parsed = JSON.parse(raw) as { active?: unknown; recipes?: unknown };
cache = {
- version: 2,
+ version: 3,
active: normalizeActive(parsed.active),
- recipes: parsed.recipes && typeof parsed.recipes === "object"
- ? parsed.recipes as Record<string, LearnedRecipe>
- : {},
+ recipes: normalizeRecipes(parsed.recipes),
};
cachePath = file;
return cache;
@@ -180,22 +227,30 @@ function safeMemoryText(value: string, max: number): string {
return out.length > max ? `${out.slice(0, max)}…` : out;
}
+function safeCommandShape(command: string): string | undefined {
+ const programs: string[] = [];
+ for (const segment of command.replace(/[\r\n]+/g, " ").split(/&&|\|\||[;|]/)) {
+ const tokens = segment.trim().split(/\s+/).filter(Boolean);
+ let program: string | undefined;
+ for (const token of tokens) {
+ if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)) continue;
+ if (!/^[A-Za-z0-9_./@+-]+$/.test(token) || token.startsWith("-")) continue;
+ program = path.basename(token).slice(0, 64);
+ break;
+ }
+ if (program && !programs.includes(program)) programs.push(program);
+ if (programs.length >= 8) break;
+ }
+ return programs.length ? programs.join(" → ") : undefined;
+}
+
function safeTarget(tool: string, target?: string): string | undefined {
if (!target) return undefined;
+ if (tool === "exec_run") return safeCommandShape(target);
let out = target
.replace(/([?&](?:token|key|secret|password|code)=)[^&\s]+/gi, "$1[redacted]")
.replace(/\b(?:bearer\s+)?(?:sk|pk|ghp|mso_mcp)_[a-z0-9_-]{8,}\b/gi, "[redacted]")
.replace(/\b(password|token|secret|api[_-]?key)\s*[:=]\s*\S+/gi, "$1=[redacted]");
- if (tool === "exec_run") {
- // Keep the command shape, not every argument. Quoted payloads and long opaque
- // values are where credentials most often hide.
- out = out
- .replace(/(['"])[\s\S]*?\1/g, "[value]")
- .replace(/\b[a-f0-9]{32,}\b/gi, "[id]")
- .split(/\s+/)
- .slice(0, 12)
- .join(" ");
- }
out = out.replace(new RegExp(`^${os.homedir().replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`), "~");
return out.length > 160 ? `${out.slice(0, 160)}…` : out;
}
@@ -218,7 +273,7 @@ const SAFE_TOOL_ARGS: Record<string, readonly string[]> = {
fs_copy: ["from", "to"],
fs_delete: ["path"],
apps_power: ["id", "action"],
- exec_run: ["command", "cwd"],
+ exec_run: ["cwd"],
browser_power: ["on"],
};
@@ -231,13 +286,33 @@ function safeArgs(tool: string, args?: Record<string, unknown>): Record<string,
const value = args[key];
if (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) out[key] = value;
else if (typeof value === "string" && value) {
- const safe = key === "command" ? safeTarget("exec_run", value) : safeMemoryText(value, 240);
+ const safe = safeMemoryText(value, 240);
if (safe) out[key] = safe;
}
}
return Object.keys(out).length ? out : undefined;
}
+function sanitizeStoredStep(value: unknown): WorkflowStep | null {
+ if (!value || typeof value !== "object") return null;
+ const row = value as Partial<WorkflowStepInput>;
+ if (typeof row.id !== "string" || typeof row.tool !== "string" ||
+ !["completed", "failed", "denied", "rate_limited"].includes(String(row.state)) ||
+ typeof row.ts !== "string") return null;
+ const durationMs = typeof row.durationMs === "number" && Number.isFinite(row.durationMs)
+ ? Math.max(0, Math.min(86_400_000, Math.round(row.durationMs)))
+ : undefined;
+ return {
+ id: safeMemoryText(row.id, 160),
+ tool: safeMemoryText(row.tool, 120),
+ state: row.state as WorkflowStepState,
+ target: safeTarget(row.tool, row.target),
+ args: safeArgs(row.tool, row.args),
+ ...(durationMs != null ? { durationMs } : {}),
+ ts: Number.isFinite(Date.parse(row.ts)) ? new Date(row.ts).toISOString() : new Date(0).toISOString(),
+ };
+}
+
function enrichBestSteps(best: WorkflowStep[], current: WorkflowStep[]): WorkflowStep[] {
if (best.length !== current.length || best.some((step, i) => step.tool !== current[i]?.tool)) return best;
return best.map((step, i) => ({
@@ -298,9 +373,10 @@ function recipeText(intent: string, project?: string, summary?: string): string
return [intent, project, summary].filter(Boolean).join("\n");
}
-function closestRecipe(store: SkillMemoryStore, intent: string, project?: string): LearnedRecipe | undefined {
+function closestRecipe(store: SkillMemoryStore, actor: string, scope: Scope, intent: string, project?: string): LearnedRecipe | undefined {
let best: { recipe: LearnedRecipe; score: number } | undefined;
for (const recipe of Object.values(store.recipes)) {
+ if (recipe.actor !== actor || recipe.scope !== scope) continue;
const semantic = hybridSemanticScore(recipeText(intent, project), recipeText(recipe.intent, recipe.project));
const exact = recipe.normalizedIntent === normalizeSemanticText(intent) ? 0.2 : 0;
const projectBonus = project && recipe.project && normalizeSemanticText(project) === normalizeSemanticText(recipe.project) ? 0.08 : 0;
@@ -341,11 +417,13 @@ function removeActiveWorkflow(store: SkillMemoryStore, actor: string, workflowId
export async function startWorkflow(input: {
actor?: string;
+ scope?: Scope;
intent: string;
project?: string;
constraints?: string;
}): Promise<{ workflow: ActiveWorkflow; activeWorkflowCount: number }> {
const actor = actorKey(input.actor);
+ const scope: Scope = input.scope ?? "read";
const intent = safeMemoryText(input.intent, 1000);
if (!intent) throw new Error("intent must be a non-empty string");
const store = await loadStore();
@@ -357,6 +435,7 @@ export async function startWorkflow(input: {
const workflow: ActiveWorkflow = {
id: randomUUID(),
actor,
+ scope,
intent,
project: input.project ? safeMemoryText(input.project, 240) || undefined : undefined,
constraints: input.constraints ? safeMemoryText(input.constraints, 500) || undefined : undefined,
@@ -386,11 +465,9 @@ export async function recordWorkflowStep(actor: string | undefined, workflowId:
const workflow = workflowFor(store, actor, workflowId);
if (!workflow) return;
if (["skills_search", "workflow_start", "workflow_finish", "workflow_cancel"].includes(step.tool)) return;
- workflow.steps.push({
- ...step,
- target: safeTarget(step.tool, step.target),
- args: safeArgs(step.tool, step.args),
- });
+ const sanitized = sanitizeStoredStep(step);
+ if (!sanitized) return;
+ workflow.steps.push(sanitized);
if (workflow.steps.length > 300) workflow.steps.splice(0, workflow.steps.length - 300);
await persist(store);
}
@@ -424,7 +501,7 @@ export async function finishWorkflow(input: {
const now = new Date();
const wallMs = Math.max(0, now.getTime() - new Date(workflow.startedAt).getTime());
const durationMs = elapsedMs(workflow.steps, wallMs);
- const existing = closestRecipe(store, workflow.intent, workflow.project);
+ const existing = closestRecipe(store, actor, workflow.scope, workflow.intent, workflow.project);
const previousFastestMs = existing?.fastestDurationMs;
const summary = safeMemoryText(input.summary, 1200) || (input.success ? "completed" : "failed");
const vector = embedSkillText(recipeText(workflow.intent, workflow.project, summary));
@@ -439,6 +516,8 @@ export async function finishWorkflow(input: {
const faster = input.success && (existing.fastestDurationMs == null || durationMs < existing.fastestDurationMs);
recipe = {
...existing,
+ actor,
+ scope: workflow.scope,
intent: workflow.intent,
normalizedIntent: normalizeSemanticText(workflow.intent),
project: workflow.project,
@@ -460,6 +539,8 @@ export async function finishWorkflow(input: {
} else {
recipe = {
id: randomUUID(),
+ actor,
+ scope: workflow.scope,
intent: workflow.intent,
normalizedIntent: normalizeSemanticText(workflow.intent),
project: workflow.project,
@@ -510,15 +591,18 @@ export async function finishWorkflow(input: {
};
}
-export async function listLearnedRecipes(): Promise<LearnedRecipe[]> {
+export async function listLearnedRecipes(access: RecipeAccess): Promise<LearnedRecipe[]> {
const store = await loadStore();
- return Object.values(store.recipes).sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
+ return Object.values(store.recipes)
+ .filter((recipe) => access.ownerView || (recipe.actor === access.actor && allows(access.scope, recipe.scope)))
+ .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
}
-export async function markRecipeUsed(id: string): Promise<void> {
+export async function markRecipeUsed(id: string, access: RecipeAccess): Promise<void> {
const store = await loadStore();
const recipe = store.recipes[id];
if (!recipe) return;
+ if (!access.ownerView && (recipe.actor !== access.actor || !allows(access.scope, recipe.scope))) return;
recipe.lastUsedAt = new Date().toISOString();
await persist(store);
}
diff --git a/lib/skills/project-skills.test.ts b/lib/skills/project-skills.test.ts
index fb308b06..c71d8968 100644
--- a/lib/skills/project-skills.test.ts
+++ b/lib/skills/project-skills.test.ts
@@ -106,7 +106,7 @@ describe("project skill trust is earned, not assumed", () => {
await expect(projectSkillTrust(evil, proj)).resolves.toBe("untrusted");
const rows = await catalog(await temp(), await temp(), [proj]);
- expect(rows).toEqual([expect.objectContaining({ id: idFor(proj, "escape"), trust: "untrusted", source: "project" })]);
+ expect(rows).toEqual([]);
});
it("refuses a SKILL.md that is a symlink rather than a regular file", async () => {
diff --git a/lib/skills/project-skills.ts b/lib/skills/project-skills.ts
index 63aae6c3..cfbf3fa0 100644
--- a/lib/skills/project-skills.ts
+++ b/lib/skills/project-skills.ts
@@ -95,9 +95,10 @@ export async function projectSkillRoots(projects: ProjectRef[]): Promise<{ roots
for (const project of capped) {
for (const [index, sub] of PROJECT_SKILL_DIRS.entries()) {
const root = path.join(project.path, sub);
- // A symlinked skill root is still LISTED (projectSkillTrust downgrades it to
- // untrusted); what must not happen is it silently becoming `local`.
- if (!(await fs.stat(root).catch(() => null))?.isDirectory()) continue;
+ // A project-root symlink is never traversed: otherwise metadata is opened before
+ // containment can make a trust decision.
+ const rootStat = await fs.lstat(root).catch(() => null);
+ if (!rootStat?.isDirectory() || rootStat.isSymbolicLink()) continue;
out.push({ path: root, project, priority: 60 - index });
}
}
diff --git a/lib/skills/search.ts b/lib/skills/search.ts
index 60e99690..df91c15a 100644
--- a/lib/skills/search.ts
+++ b/lib/skills/search.ts
@@ -1,6 +1,6 @@
import { catalogSkillsDetailed, readSkillFile, type ProjectRef, type SkillInfo, type SkillScanReport } from "./catalog";
-import { listLearnedRecipes, type LearnedRecipe } from "./memory";
-import { embedSkillText, hybridSemanticScore, SKILL_EMBEDDING_VERSION } from "./semantic";
+import { listLearnedRecipes, type LearnedRecipe, type RecipeAccess } from "./memory";
+import { embedSkillText, hybridSemanticScore, prepareSemanticQuery, SKILL_EMBEDDING_VERSION } from "./semantic";
export type SkillSearchToolDoc = {
name: string;
@@ -35,6 +35,8 @@ export type SkillSearchOptions = {
homeDir?: string;
/** Forwarded to catalogSkills; `[]` restricts the search to global roots. */
projects?: ProjectRef[];
+ /** Explicit recipe visibility. Omit to search skills/tools only. */
+ recipeAccess?: RecipeAccess;
};
function skillQuality(skill: SkillInfo): number {
@@ -59,13 +61,13 @@ export async function searchSkillMemory(query: string, options: SkillSearchOptio
catalog: SkillScanReport;
recommendedRecipe?: SkillSearchHit;
}> {
- const q = query.trim();
- if (!q) throw new Error("query must be a non-empty string");
+ const preparedQuery = prepareSemanticQuery(query);
+ const q = preparedQuery.raw;
const topK = Math.min(Math.max(Math.round(options.topK ?? 8), 1), 20);
const hits: SkillSearchHit[] = [];
const availableTools = options.toolDocs?.length ? new Set(options.toolDocs.map((t) => t.name)) : null;
- const recipes = await listLearnedRecipes();
+ const recipes = options.recipeAccess ? await listLearnedRecipes(options.recipeAccess) : [];
for (const recipe of recipes) {
const text = [
recipe.intent,
@@ -73,7 +75,7 @@ export async function searchSkillMemory(query: string, options: SkillSearchOptio
recipe.summary,
recipe.bestSteps.map((s) => `${s.tool} ${s.target ?? ""}`).join(" "),
].filter(Boolean).join("\n");
- const raw = hybridSemanticScore(q, text, recipe.embeddingVersion === SKILL_EMBEDDING_VERSION ? recipe.embedding : embedSkillText(text));
+ const raw = hybridSemanticScore(preparedQuery, text, recipe.embeddingVersion === SKILL_EMBEDDING_VERSION ? recipe.embedding : embedSkillText(text));
const missingTools = availableTools
? [...new Set(recipe.bestSteps.map((s) => s.tool).filter((tool) => !availableTools.has(tool)))]
: [];
@@ -103,7 +105,7 @@ export async function searchSkillMemory(query: string, options: SkillSearchOptio
id: skill.id,
name: skill.name,
...(skill.project ? { project: skill.project } : {}),
- score: Math.max(0, Math.min(1, hybridSemanticScore(q, text) + skillQuality(skill))),
+ score: Math.max(0, Math.min(1, hybridSemanticScore(preparedQuery, text) + skillQuality(skill))),
description: skill.description,
source: skill.source,
trust: skill.trust,
@@ -117,7 +119,7 @@ export async function searchSkillMemory(query: string, options: SkillSearchOptio
kind: "tool",
id: tool.name,
name: tool.name,
- score: Math.min(1, hybridSemanticScore(q, text) + 0.055),
+ score: Math.min(1, hybridSemanticScore(preparedQuery, text) + 0.055),
description: tool.description,
source: "mcp",
trust: "official",
diff --git a/lib/skills/semantic.test.ts b/lib/skills/semantic.test.ts
index b69a213d..8cf9ca46 100644
--- a/lib/skills/semantic.test.ts
+++ b/lib/skills/semantic.test.ts
@@ -14,3 +14,19 @@ describe("local skill embeddings", () => {
expect(score).toBeGreaterThan(0.25);
});
});
+
+describe("bounded prepared semantic queries", () => {
+ it("rejects oversized owner intent before embedding", async () => {
+ const { prepareSemanticQuery, MAX_SEMANTIC_QUERY_BYTES } = await import("./semantic");
+ expect(() => prepareSemanticQuery("x".repeat(MAX_SEMANTIC_QUERY_BYTES + 1))).toThrow(/byte limit/);
+ });
+
+ it("reuses one prepared query vector across candidate scoring", async () => {
+ const { prepareSemanticQuery, hybridSemanticScore } = await import("./semantic");
+ const prepared = prepareSemanticQuery("deploy mso safely");
+ const identity = prepared.vector;
+ hybridSemanticScore(prepared, "deploy release workflow");
+ hybridSemanticScore(prepared, "unrelated media editor");
+ expect(prepared.vector).toBe(identity);
+ });
+});
diff --git a/lib/skills/semantic.ts b/lib/skills/semantic.ts
index b94df54f..f8b0de82 100644
--- a/lib/skills/semantic.ts
+++ b/lib/skills/semantic.ts
@@ -10,6 +10,8 @@
*/
export const SKILL_EMBEDDING_VERSION = "mso-local-hybrid-v1";
export const SKILL_EMBEDDING_DIM = 384;
+export const MAX_SEMANTIC_QUERY_BYTES = 4 * 1024;
+export const MAX_SEMANTIC_QUERY_TERMS = 256;
const STOP = new Set([
"a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "how", "i", "in", "is", "it", "of", "on", "or", "that", "the", "this", "to", "with",
@@ -60,16 +62,34 @@ function add(vec: number[], feature: string, weight: number): void {
vec[index] += sign * weight;
}
-function terms(text: string): string[] {
+function terms(text: string, limit = Number.POSITIVE_INFINITY): string[] {
return normalizeSemanticText(text)
.split(" ")
.map((v) => v.trim())
- .filter((v) => v.length > 1 && !STOP.has(v));
+ .filter((v) => v.length > 1 && !STOP.has(v))
+ .slice(0, limit);
}
-export function embedSkillText(text: string): number[] {
+export type PreparedSemanticQuery = {
+ raw: string;
+ vector: number[];
+ terms: ReadonlySet<string>;
+};
+
+export function prepareSemanticQuery(query: string): PreparedSemanticQuery {
+ const raw = query.trim();
+ if (!raw) throw new Error("query must be a non-empty string");
+ if (Buffer.byteLength(raw, "utf8") > MAX_SEMANTIC_QUERY_BYTES) throw new Error("query exceeds byte limit");
+ return {
+ raw,
+ vector: embedSkillText(raw, MAX_SEMANTIC_QUERY_TERMS),
+ terms: new Set(terms(raw, MAX_SEMANTIC_QUERY_TERMS)),
+ };
+}
+
+export function embedSkillText(text: string, termLimit = Number.POSITIVE_INFINITY): number[] {
const vec = Array<number>(SKILL_EMBEDDING_DIM).fill(0);
- const xs = terms(text);
+ const xs = terms(text, termLimit);
for (let i = 0; i < xs.length; i += 1) {
const token = xs[i];
add(vec, `w:${token}`, token.includes("_") ? 2.2 : 1);
@@ -103,10 +123,13 @@ export function lexicalSimilarity(a: string, b: string): number {
return overlap / Math.sqrt(aa.size * bb.size);
}
-export function hybridSemanticScore(query: string, text: string, vector?: number[]): number {
- const qv = embedSkillText(query);
+export function hybridSemanticScore(query: string | PreparedSemanticQuery, text: string, vector?: number[]): number {
+ const prepared = typeof query === "string" ? prepareSemanticQuery(query) : query;
const dv = vector ?? embedSkillText(text);
- const cosine = Math.max(0, cosineSimilarity(qv, dv));
- const lexical = lexicalSimilarity(query, text);
+ const cosine = Math.max(0, cosineSimilarity(prepared.vector, dv));
+ const docTerms = new Set(terms(text));
+ let overlap = 0;
+ for (const term of prepared.terms) if (docTerms.has(term)) overlap += 1;
+ const lexical = prepared.terms.size && docTerms.size ? overlap / Math.sqrt(prepared.terms.size * docTerms.size) : 0;
return Math.max(0, Math.min(1, cosine * 0.74 + lexical * 0.26));
}
diff --git a/proxy-websocket.test.ts b/proxy-websocket.test.ts
index 4abdb5d2..91693f4d 100644
--- a/proxy-websocket.test.ts
+++ b/proxy-websocket.test.ts
@@ -168,9 +168,10 @@ describe("per-app upgrade adapters", () => {
// gate had been a check that a cookie NAMED "session" existed, which any value
// satisfied. It is open again only behind the verified check, so these tests are the
// difference between a browser app and an unauthenticated remote-control relay.
-describe("the camoufox VNC bridge", () => {
+describe("the Camoufox split-origin VNC bridge", () => {
const SECRET = "y".repeat(48);
const NOVNC = "http://127.0.0.1:6080";
+ const VIEWER_HOST = "camoufox.mso.rahmanef.com";
function session(secret = SECRET): string {
const now = Date.now();
@@ -179,14 +180,14 @@ describe("the camoufox VNC bridge", () => {
async function load(novnc = NOVNC) {
vi.stubEnv("OS_SESSION_SECRET", SECRET);
+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.rahmanef.com");
vi.stubEnv("CAMOUFOX_NOVNC_URL", novnc);
approved.value = true;
- // Single-origin mode: the bridge lives on the cockpit host, not an app host.
- return loadProxy("");
+ return loadProxy(TEMPLATE);
}
- const vnc = (cookie?: string, path = "/camoufox-vnc/vnc_lite.html", extra: Record<string, string> = {}) =>
- req("mso.rahmanef.com", path, cookie ? { cookie: `session=${cookie}`, ...extra } : extra);
+ const vnc = (cookie?: string, path = "/vnc_lite.html", extra: Record<string, string> = {}) =>
+ req(VIEWER_HOST, path, cookie ? { cookie: `session=${cookie}`, ...extra } : extra);
it("404s a request with no cookie at all", async () => {
const proxy = await load();
@@ -195,55 +196,78 @@ describe("the camoufox VNC bridge", () => {
expect(rewriteOf(res)).toBeNull();
});
- it("404s the forged cookie the old gate accepted", async () => {
+ it("404s a forged or wrongly signed cookie", async () => {
const proxy = await load();
- // `Cookie: session=anything` — this exact request used to reach websockify.
- const res = await proxy(vnc("anything"));
- expect(res.status).toBe(404);
- expect(rewriteOf(res)).toBeNull();
- });
-
- it("404s a cookie signed with the wrong secret", async () => {
- const proxy = await load();
- const res = await proxy(vnc(session("z".repeat(48))));
- expect(res.status).toBe(404);
- expect(rewriteOf(res)).toBeNull();
+ expect((await proxy(vnc("anything"))).status).toBe(404);
+ expect((await proxy(vnc(session("z".repeat(48))))).status).toBe(404);
});
- it("404s a valid signature once the device is no longer approved", async () => {
+ it("404s a valid signature once the device is revoked", async () => {
const proxy = await load();
approved.value = false;
- const res = await proxy(vnc(session()));
- expect(res.status).toBe(404);
- expect(rewriteOf(res)).toBeNull();
+ expect((await proxy(vnc(session()))).status).toBe(404);
});
- it("rewrites an authenticated request to loopback websockify, prefix stripped", async () => {
+ it("maps the dedicated host to loopback noVNC without a cockpit prefix", async () => {
const proxy = await load();
const res = await proxy(vnc(session()));
const target = new URL(rewriteOf(res)!);
expect(target.origin).toBe(NOVNC);
- expect(target.pathname).toBe("/vnc_lite.html"); // the /camoufox-vnc prefix is ours, not websockify's
+ expect(target.pathname).toBe("/vnc_lite.html");
+ expect(res.headers.get("content-security-policy")).toContain("frame-ancestors https://mso.rahmanef.com");
+ expect(res.headers.get("referrer-policy")).toBe("no-referrer");
});
- it("carries the query string, which is where noVNC's socket path lives", async () => {
+ it("maps the viewer-host root to the full noVNC UI", async () => {
const proxy = await load();
- const res = await proxy(vnc(session(), "/camoufox-vnc/vnc_lite.html?path=camoufox-vnc/websockify&scale=true"));
- expect(new URL(rewriteOf(res)!).search).toBe("?path=camoufox-vnc/websockify&scale=true");
+ expect(new URL(rewriteOf(await proxy(vnc(session(), "/")))!).pathname).toBe("/vnc.html");
});
- it("carries an authenticated upgrade — noVNC is dead without the socket", async () => {
+ it("carries only the query string noVNC needs", async () => {
const proxy = await load();
- const res = await proxy(
- vnc(session(), "/camoufox-vnc/websockify", { upgrade: "websocket", connection: "Upgrade" }),
- );
+ const res = await proxy(vnc(session(), "/vnc.html?path=websockify&resize=remote"));
+ expect(new URL(rewriteOf(res)!).search).toBe("?path=websockify&resize=remote");
+ });
+
+ it("carries an authenticated upgrade and strips cockpit credentials upstream", async () => {
+ const proxy = await load();
+ const res = await proxy(vnc(session(), "/websockify", {
+ upgrade: "websocket", connection: "Upgrade", authorization: "Bearer must-not-leak",
+ }));
expect(new URL(rewriteOf(res)!).pathname).toBe("/websockify");
+ expect(res.headers.get("x-middleware-request-cookie")).toBeNull();
+ expect(res.headers.get("x-middleware-request-authorization")).toBeNull();
});
- it("refuses an off-box destination — an env typo must not make this an open relay", async () => {
- const proxy = await load("http://evil.example");
- const res = await proxy(vnc(session()));
+ it("strips the Domain session cookie from ordinary noVNC asset requests too", async () => {
+ const proxy = await load();
+ const res = await proxy(vnc(session(), "/app/ui.js", { authorization: "Basic must-not-leak" }));
+ expect(res.headers.get("x-middleware-request-cookie")).toBeNull();
+ expect(res.headers.get("x-middleware-request-authorization")).toBeNull();
+ });
+
+ it("never exposes the old same-origin cockpit bridge", async () => {
+ const proxy = await load();
+ const res = await proxy(req("mso.rahmanef.com", "/camoufox-vnc/vnc.html", { cookie: `session=${session()}` }));
expect(res.status).toBe(404);
expect(rewriteOf(res)).toBeNull();
});
+
+ it("never maps cockpit API names on the viewer host back into MSO", async () => {
+ const proxy = await load();
+ const res = await proxy(vnc(session(), "/api/v1/exec/run"));
+ expect(new URL(rewriteOf(res)!).toString()).toBe(`${NOVNC}/api/v1/exec/run`);
+ });
+
+ it("refuses non-read methods and an off-box destination", async () => {
+ const proxy = await load();
+ const postHeaders = new Headers({ host: VIEWER_HOST, cookie: `session=${session()}` });
+ const post = new NextRequest(`https://${VIEWER_HOST}/vnc.html`, {
+ method: "POST", headers: postHeaders, body: "x",
+ });
+ expect((await proxy(post)).status).toBe(404);
+
+ const offBox = await load("http://evil.example");
+ expect((await offBox(vnc(session()))).status).toBe(404);
+ });
});
diff --git a/proxy.ts b/proxy.ts
index 84db4e76..243a0200 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -28,6 +28,10 @@ import { projectIngressDecision } from "@/lib/managed-apps/project-ingress";
import { verifySession } from "@/lib/auth/session";
import { isApproved } from "@/lib/auth/device-store";
import { IS_DEMO } from "@/lib/demo";
+import {
+ camoufoxViewerCsp,
+ isCamoufoxViewerHost,
+} from "@/lib/camoufox/origin";
const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);
@@ -151,6 +155,37 @@ export async function proxy(request: NextRequest) {
const host = request.headers.get("host") ?? request.nextUrl.host;
const managedApp = managedAppIdForHost(host);
+ // noVNC gets one reserved split-origin host. Every path on it goes ONLY to the
+ // loopback viewer; no cockpit route exists there. The Domain session cookie is
+ // used solely at this edge gate and is stripped before noVNC receives the request.
+ if (isCamoufoxViewerHost(host)) {
+ if (!(await hasApprovedSession(request))) return notFound();
+ if (request.method !== "GET" && request.method !== "HEAD") return notFound();
+ let base: URL;
+ try {
+ base = new URL(CAMOUFOX_NOVNC_URL);
+ } catch {
+ return notFound();
+ }
+ if ((base.protocol !== "http:" && base.protocol !== "https:") || !LOOPBACK_HOST.test(base.hostname)) {
+ return notFound();
+ }
+ const target = new URL(base);
+ // Assign pathname/search separately: resolving a caller path beginning `//`
+ // against base would otherwise change the destination host.
+ target.pathname = pathname === "/" ? "/vnc.html" : pathname;
+ target.search = request.nextUrl.search;
+ const response = NextResponse.rewrite(target, {
+ request: { headers: upstreamSocketHeaders(request.headers) },
+ });
+ response.headers.set("Content-Security-Policy", camoufoxViewerCsp());
+ response.headers.set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=(), serial=()");
+ response.headers.set("Referrer-Policy", "no-referrer");
+ response.headers.set("X-Content-Type-Options", "nosniff");
+ response.headers.set("Cross-Origin-Resource-Policy", "same-origin");
+ return response;
+ }
+
// Optional project integrations may expose ONE exact machine-to-machine POST
// lane on a managed-app host. Stock MSO has no routes because
// OS_PROJECT_INGRESS_ROUTES defaults to empty. The route config is fixed by the
@@ -243,35 +278,9 @@ export async function proxy(request: NextRequest) {
pathname === "/oauth/token" ||
pathname === "/oauth/register";
const isApi = pathname.startsWith("/api/") || isMcp;
- const isCamoufoxVnc = pathname.startsWith("/camoufox-vnc/");
-
- // Camoufox's VNC bridge — noVNC + websockify in front of x11vnc, i.e. live
- // keyboard and mouse on a real browser session. This was hard-403'd because its
- // only gate had been `request.cookies.get("session")`, which proves a cookie of
- // that NAME exists and nothing else: `Cookie: session=x` from anywhere on the
- // internet walked straight through. It is open again ONLY because the check is
- // now the real one — hasApprovedSession verifies the HMAC and re-checks that the
- // device is still approved, the same gate /api/v1/exec sits behind. The comment
- // that used to live here claimed middleware could not do this; it already did,
- // twelve lines up, for the managed-app socket.
- //
- // Rewritten from HERE rather than via a next.config rewrite, for two reasons:
- // a config rewrite runs AFTER middleware but bypasses route handlers, so the gate
- // would have to live here anyway — and this is the same different-origin rewrite
- // the managed-app upgrade uses, which is the one form proven to carry a WebSocket
- // (websockify needs the upgrade; noVNC is dead without it).
- if (isCamoufoxVnc) {
- if (!(await hasApprovedSession(request))) return notFound();
- const base = new URL(CAMOUFOX_NOVNC_URL);
- // Same reasoning as the managed-app hop: this rewrite LEAVES this server, so an
- // env typo pointing it off-box would turn the cockpit into an open relay.
- if (!LOOPBACK_HOST.test(base.hostname)) return notFound();
- const upstream = pathname.slice("/camoufox-vnc".length) || "/";
- const target = new URL(`${upstream}${request.nextUrl.search}`, base);
- return WEBSOCKET_UPGRADE.test(request.headers.get("upgrade") ?? "")
- ? NextResponse.rewrite(target, { request: { headers: upstreamSocketHeaders(request.headers) } })
- : NextResponse.rewrite(target);
- }
+ // The historical same-origin bridge is permanently closed. noVNC is executable
+ // third-party code and is served only from its reserved split-origin host above.
+ if (pathname.startsWith("/camoufox-vnc/")) return notFound();
// CSRF depth-2 for mutating /api (unchanged semantics). `isMcp` is excluded —
// see the note above: bearer-authenticated, so same-origin proof is meaningless
diff --git a/scripts/approve-device-lock.test.ts b/scripts/approve-device-lock.test.ts
new file mode 100644
index 00000000..86156787
--- /dev/null
+++ b/scripts/approve-device-lock.test.ts
@@ -0,0 +1,18 @@
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+const SCRIPT = path.join(process.cwd(), "scripts/approve-device.js");
+
+describe("approve-device cross-process lock protocol", () => {
+ it("publishes the primary lock only while holding the shared recovery gate", () => {
+ const source = readFileSync(SCRIPT, "utf8");
+ const acquire = source.slice(source.indexOf("function acquireLock()"), source.indexOf("function withMutation"));
+ const gate = acquire.indexOf("openExclusive(RECOVERY");
+ const primary = acquire.indexOf("openExclusive(LOCK");
+ expect(gate).toBeGreaterThanOrEqual(0);
+ expect(primary).toBeGreaterThan(gate);
+ expect(acquire).toContain("return openExclusive(LOCK, token)");
+ expect(source).not.toContain("function recoverAbandonedLock");
+ });
+});
diff --git a/scripts/approve-device.js b/scripts/approve-device.js
old mode 100644
new mode 100755
index 2ac574b8..3bd2f990
--- a/scripts/approve-device.js
+++ b/scripts/approve-device.js
@@ -13,6 +13,7 @@ const fs = require("fs");
const os = require("os");
const path = require("path");
const { randomUUID } = require("crypto");
+const { spawnSync } = require("child_process");
const STORE =
process.env.OS_DEVICE_STORE || path.join(os.homedir(), ".mso", "auth-devices.json");
@@ -39,6 +40,7 @@ function write(store) {
// lock owner is recorded so a crashed helper/server is recoverable without turning
// a stale file into a permanent authentication outage.
const LOCK = `${STORE}.lock`;
+const RECOVERY = `${LOCK}.recovery`;
const LOCK_WAIT_MS = 25;
const LOCK_TIMEOUT_MS = 3000;
const LOCK_STALE_MS = 30000;
@@ -61,33 +63,69 @@ function abandonedLock() {
throw error;
}
}
+function openExclusive(file, token) {
+ // Publish only a fully-written owner record; linkSync is the atomic create point.
+ const candidate = `${file}.${randomUUID()}.candidate`;
+ let fd;
+ try {
+ fd = fs.openSync(candidate, "wx", 0o600);
+ fs.writeFileSync(fd, token, "utf8");
+ fs.fsyncSync(fd);
+ } finally {
+ if (fd !== undefined) try { fs.closeSync(fd); } catch {}
+ }
+ try { fs.linkSync(candidate, file); }
+ finally { try { fs.unlinkSync(candidate); } catch {} }
+ return { token };
+}
+function releaseLock(file, held) {
+ let owner = "";
+ try { owner = fs.readFileSync(file, "utf8"); } catch {}
+ if (owner === held.token) { try { fs.unlinkSync(file); } catch {} }
+}
function acquireLock() {
fs.mkdirSync(path.dirname(STORE), { recursive: true, mode: 0o700 });
const token = `${process.pid}:${randomUUID()}`;
const deadline = Date.now() + LOCK_TIMEOUT_MS;
while (true) {
- try {
- const fd = fs.openSync(LOCK, "wx", 0o600);
- try { fs.writeFileSync(fd, token, "utf8"); }
- catch (error) { try { fs.closeSync(fd); } catch {} try { fs.unlinkSync(LOCK); } catch {} throw error; }
- return { fd, token };
- } catch (error) {
+ // Every process takes the recovery gate before inspecting or publishing LOCK.
+ // This closes the stat/read/unlink ABA race where a stale recoverer could delete
+ // a newly-created live lock at the same pathname.
+ let gate;
+ try { gate = openExclusive(RECOVERY, `${process.pid}:${randomUUID()}`); }
+ catch (error) {
if (!error || error.code !== "EEXIST") throw error;
- if (abandonedLock()) { try { fs.unlinkSync(LOCK); } catch {} continue; }
- if (Date.now() >= deadline) throw new Error("security store is busy; retry the operation");
- sleep(LOCK_WAIT_MS);
}
+
+ if (gate) {
+ try {
+ try { return openExclusive(LOCK, token); }
+ catch (error) { if (!error || error.code !== "EEXIST") throw error; }
+
+ if (abandonedLock()) {
+ try { fs.unlinkSync(LOCK); }
+ catch (error) { if (!error || error.code !== "ENOENT") throw error; }
+ // Publish our owner record while the recovery gate is still held. Every
+ // supported writer obeys this gate, so no contender can occupy the gap.
+ try { return openExclusive(LOCK, token); }
+ catch (error) { if (!error || error.code !== "EEXIST") throw error; }
+ }
+ } finally {
+ // Never auto-break a recovery guard. A crash fails closed until manual
+ // cleanup rather than risking a revocation-losing concurrent write.
+ releaseLock(RECOVERY, gate);
+ }
+ }
+
+ if (Date.now() >= deadline) throw new Error("security store is busy; retry the operation");
+ sleep(LOCK_WAIT_MS);
}
}
+
function withMutation(fn) {
const held = acquireLock();
try { return fn(); }
- finally {
- try { fs.closeSync(held.fd); } catch {}
- let owner = "";
- try { owner = fs.readFileSync(LOCK, "utf8"); } catch {}
- if (owner === held.token) { try { fs.unlinkSync(LOCK); } catch {} }
- }
+ finally { releaseLock(LOCK, held); }
}
const ts = (t) => (t ? new Date(t).toISOString() : "—");
@@ -97,6 +135,22 @@ const ts = (t) => (t ? new Date(t).toISOString() : "—");
const approveCmd = (id, label) => ` mso device approve ${id} ${JSON.stringify(label || "my device")}`;
const revokeCmd = (id) => ` mso device revoke ${id}`;
+// A live VNC WebSocket has already passed its session check, so changing the
+// allowlist alone cannot evict it. The local CLI applies the same kill switch as
+// the authenticated API. The binary override supports hermetic tests and unusual
+// systemctl locations; the caller is already the host owner.
+function terminateCamoufoxSessions() {
+ const systemctl = process.env.MSO_SYSTEMCTL_BIN || "systemctl";
+ const result = spawnSync(systemctl, ["--user", "stop", "camoufox-vnc.service"], {
+ encoding: "utf8",
+ timeout: 30000,
+ });
+ if (result.error) throw result.error;
+ if (result.status !== 0) {
+ throw new Error(`device was revoked, but Camoufox session teardown failed (rc ${result.status}): ${(result.stderr || "").trim().slice(0, 160)}`);
+ }
+}
+
const listApproved = (ap) => {
if (!ap.length) return void console.log(" (none)");
for (const [id, d] of ap) {
@@ -154,6 +208,7 @@ if (args[0] === "--revoke-all") {
write(current);
return currentIds;
});
+ terminateCamoufoxSessions();
console.log(`revoked ${revokedIds.length} device(s):`);
for (const id of revokedIds) console.log(` ${id}`);
console.log("\nno device can sign in until you approve one again.");
@@ -177,6 +232,7 @@ if (args[0] === "--revoke") {
process.exit(1);
}
const { label, left } = result;
+ terminateCamoufoxSessions();
// Say what is left, so the obvious follow-up (`device list`) isn't needed — and
// so revoking your last device is impossible to do without noticing.
console.log(`revoked ${id} "${label}"`);
diff --git a/scripts/lib/private-state.sh b/scripts/lib/private-state.sh
new file mode 100755
index 00000000..11a9076a
--- /dev/null
+++ b/scripts/lib/private-state.sh
@@ -0,0 +1,139 @@
+#!/usr/bin/env bash
+# Shared private-state primitives for shell clients that persist live session material.
+# Callers must already use `set -euo pipefail` and handle a non-zero return as fatal.
+
+mso_private_state_error() {
+ printf 'private state: %s\n' "$*" >&2
+ return 1
+}
+
+mso_private_state_dir() {
+ local requested="${1:-}" created=0 canonical owner mode old_umask
+ [ -n "$requested" ] || { mso_private_state_error "empty directory path"; return 1; }
+ case "$requested" in /*) ;; *) mso_private_state_error "directory must be absolute: $requested"; return 1 ;; esac
+ [ ! -L "$requested" ] || { mso_private_state_error "refusing symlink directory: $requested"; return 1; }
+
+ if [ ! -e "$requested" ]; then
+ old_umask=$(umask)
+ umask 077
+ mkdir -p -- "$requested"
+ umask "$old_umask"
+ created=1
+ fi
+ [ -d "$requested" ] && [ ! -L "$requested" ] || {
+ mso_private_state_error "not a real directory: $requested"
+ return 1
+ }
+
+ canonical=$(realpath -e -- "$requested") || {
+ mso_private_state_error "cannot resolve directory: $requested"
+ return 1
+ }
+ owner=$(stat -c '%u' -- "$canonical") || return 1
+ mode=$(stat -c '%a' -- "$canonical") || return 1
+ [ "$owner" = "$(id -u)" ] || {
+ mso_private_state_error "directory is not owned by uid $(id -u): $canonical"
+ return 1
+ }
+ if [ "$created" = 1 ]; then
+ chmod 700 -- "$canonical"
+ mode=$(stat -c '%a' -- "$canonical") || return 1
+ fi
+ [ "$mode" = 700 ] || {
+ mso_private_state_error "directory must be mode 0700, got $mode: $canonical"
+ return 1
+ }
+ printf '%s' "$canonical"
+}
+
+mso_private_state_path() {
+ local requested="${1:-}" parent name canonical_parent
+ [ -n "$requested" ] || { mso_private_state_error "empty file path"; return 1; }
+ case "$requested" in /*) ;; *) mso_private_state_error "file path must be absolute: $requested"; return 1 ;; esac
+ parent=$(dirname -- "$requested")
+ name=$(basename -- "$requested")
+ [ -n "$name" ] && [ "$name" != . ] && [ "$name" != / ] || {
+ mso_private_state_error "invalid file name: $requested"
+ return 1
+ }
+ canonical_parent=$(mso_private_state_dir "$parent") || return 1
+ printf '%s/%s' "$canonical_parent" "$name"
+}
+
+mso_private_state_validate_file() {
+ local resolved owner mode
+ resolved=$(mso_private_state_path "${1:-}") || return 1
+ [ ! -L "$resolved" ] || {
+ mso_private_state_error "refusing symlink file: $resolved"
+ return 1
+ }
+ [ -e "$resolved" ] || {
+ mso_private_state_error "file does not exist: $resolved"
+ return 1
+ }
+ [ -f "$resolved" ] || {
+ mso_private_state_error "not a regular file: $resolved"
+ return 1
+ }
+ owner=$(stat -c '%u' -- "$resolved") || return 1
+ mode=$(stat -c '%a' -- "$resolved") || return 1
+ [ "$owner" = "$(id -u)" ] || {
+ mso_private_state_error "file is not owned by uid $(id -u): $resolved"
+ return 1
+ }
+ [ "$mode" = 600 ] || {
+ mso_private_state_error "file must be mode 0600, got $mode: $resolved"
+ return 1
+ }
+ printf '%s' "$resolved"
+}
+
+mso_private_state_ensure_file() {
+ local resolved parent tmp old_umask
+ resolved=$(mso_private_state_path "${1:-}") || return 1
+ if [ -e "$resolved" ] || [ -L "$resolved" ]; then
+ mso_private_state_validate_file "$resolved"
+ return
+ fi
+
+ parent=$(dirname -- "$resolved")
+ old_umask=$(umask)
+ umask 077
+ tmp=$(mktemp "$parent/.mso-private-state.XXXXXX")
+ umask "$old_umask"
+ chmod 600 -- "$tmp"
+ if ! mv -Tn -- "$tmp" "$resolved"; then
+ rm -f -- "$tmp"
+ fi
+ mso_private_state_validate_file "$resolved"
+}
+
+mso_private_state_atomic_write() {
+ local resolved parent tmp old_umask
+ resolved=$(mso_private_state_path "${1:-}") || return 1
+ if [ -e "$resolved" ] || [ -L "$resolved" ]; then
+ mso_private_state_validate_file "$resolved" >/dev/null || return 1
+ fi
+ parent=$(dirname -- "$resolved")
+ old_umask=$(umask)
+ umask 077
+ tmp=$(mktemp "$parent/.mso-private-write.XXXXXX")
+ umask "$old_umask"
+ trap 'rm -f -- "${tmp:-}"' RETURN
+ cat >"$tmp"
+ chmod 600 -- "$tmp"
+ mv -fT -- "$tmp" "$resolved"
+ tmp=''
+ trap - RETURN
+ mso_private_state_validate_file "$resolved"
+}
+
+mso_private_state_remove_file() {
+ local resolved
+ resolved=$(mso_private_state_path "${1:-}") || return 1
+ if [ ! -e "$resolved" ] && [ ! -L "$resolved" ]; then
+ return 0
+ fi
+ mso_private_state_validate_file "$resolved" >/dev/null || return 1
+ rm -f -- "$resolved"
+}
diff --git a/scripts/managed-app-9router b/scripts/managed-app-9router
index f7f707d5..c19de57c 100755
--- a/scripts/managed-app-9router
+++ b/scripts/managed-app-9router
@@ -10,15 +10,49 @@
# Docker is called bare, not via sudo: mso runs as a user in the docker group,
# and that is already what manager.ts assumes for start/stop/restart/logs.
set -euo pipefail
+umask 077
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+ARTIFACT_LOCK="$ROOT/security/managed-app-artifacts.env"
+[ -r "$ARTIFACT_LOCK" ] || { echo "missing managed-app artifact lock: $ARTIFACT_LOCK" >&2; exit 2; }
+# shellcheck source=security/managed-app-artifacts.env
+. "$ARTIFACT_LOCK"
NAME="${NINE_ROUTER_CONTAINER:-9router}"
PORT="${NINE_ROUTER_PORT:-20128}"
-IMAGE="${NINE_ROUTER_IMAGE:-decolua/9router:latest}"
+IMAGE="${NINE_ROUTER_IMAGE:-$NINE_ROUTER_IMAGE_REF}"
+case "$IMAGE" in
+ *@sha256:????????????????????????????????????????????????????????????????) ;;
+ *) echo "NINE_ROUTER_IMAGE must be an immutable @sha256 reference" >&2; exit 2 ;;
+esac
+EXPECTED_DIGEST="${IMAGE##*@}"
+[[ "$EXPECTED_DIGEST" =~ ^sha256:[0-9a-f]{64}$ ]] || {
+ echo "NINE_ROUTER_IMAGE digest must be lowercase sha256" >&2
+ exit 2
+}
+readonly NINE_ROUTER_IMAGE_REF IMAGE EXPECTED_DIGEST
+EXPOSE_PUBLIC="${NINE_ROUTER_EXPOSE_PUBLIC:-0}"
+case "$EXPOSE_PUBLIC" in 0) BIND=127.0.0.1 ;; 1) BIND=0.0.0.0 ;; *) echo "NINE_ROUTER_EXPOSE_PUBLIC must be 0 or 1" >&2; exit 2 ;; esac
DATA="${NINE_ROUTER_DATA:-$HOME/.9router}"
BASE="http://127.0.0.1:${PORT}"
installed() { docker ps -a --format '{{.Names}}' | grep -qx "$NAME"; }
+image_has_expected_digest() {
+ local image="$1"
+ docker image inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' "$image" 2>/dev/null \
+ | grep -Eq "@${EXPECTED_DIGEST}$"
+}
+
+running_image_matches_lock() {
+ installed || return 1
+ local image_id
+ image_id="$(docker inspect --format '{{.Image}}' "$NAME" 2>/dev/null)" || return 1
+ docker image inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' "$image_id" 2>/dev/null \
+ | grep -Eq "@${EXPECTED_DIGEST}$"
+}
+
# The running image's own version label — offline, no fork of the app.
label_version() {
docker inspect --format '{{index .Config.Labels "org.opencontainers.image.version"}}' \
@@ -34,13 +68,16 @@ cmd_version() {
curl -fsS -m 5 "$BASE/api/version" | sed -n 's/.*"currentVersion":"\([^"]*\)".*/\1/p'
}
-# 9Router self-checks against Docker Hub and answers
-# {"currentVersion":"…","latestVersion":"…","hasUpdate":bool} at /api/version —
-# relayed verbatim (update-probe.ts parses exactly this shape).
+# Update availability is measured against MSO's reviewed immutable digest, never a
+# mutable registry tag or the app's own "latest" endpoint.
cmd_check() {
installed || { echo "9router container not found" >&2; exit 1; }
- curl -fsS -m 30 "$BASE/api/version" || { echo "9router is not answering on $BASE — is it running?" >&2; exit 1; }
- echo
+ local current latest has_update
+ current="$(docker inspect --format '{{.Image}}' "$NAME" 2>/dev/null | cut -c1-19)"
+ latest="${EXPECTED_DIGEST:0:19}"
+ if running_image_matches_lock; then has_update=false; else has_update=true; fi
+ printf '{"currentVersion":"%s","latestVersion":"%s","hasUpdate":%s}
+' "$current" "$latest" "$has_update"
}
# Pull latest, recreate the container, keep the data mount. Also the install:
@@ -48,6 +85,10 @@ cmd_check() {
cmd_update() {
echo "==> pull $IMAGE"
docker pull "$IMAGE"
+ image_has_expected_digest "$IMAGE" || {
+ echo "pulled 9Router image does not expose the locked digest $EXPECTED_DIGEST" >&2
+ exit 1
+ }
# Port guard: recreating onto a port some OTHER container holds would rm the
# wrong thing's ability to come back up and fail late. Named container wins.
@@ -59,12 +100,12 @@ cmd_update() {
fi
mkdir -p "$DATA"
- echo "==> recreate $NAME"
+ echo "==> recreate $NAME (bind $BIND:$PORT)"
docker rm -f "$NAME" 2>/dev/null || true
docker run -d \
--name "$NAME" \
--restart unless-stopped \
- -p "$PORT:$PORT" \
+ -p "$BIND:$PORT:$PORT" \
-v "$DATA:/app/data" \
-e DATA_DIR=/app/data \
"$IMAGE"
@@ -74,6 +115,7 @@ cmd_update() {
for i in $(seq 1 30); do
sleep 1
if curl -fsS -o /dev/null -m 3 "$BASE/api/health"; then
+ running_image_matches_lock || { echo "running 9Router image does not match the locked digest" >&2; return 1; }
echo "==> healthy after ${i}s ($(label_version))"
return 0
fi
diff --git a/scripts/managed-app-install b/scripts/managed-app-install
index f16f457e..2ef0c3a9 100755
--- a/scripts/managed-app-install
+++ b/scripts/managed-app-install
@@ -20,6 +20,23 @@
# (JOB_STDIO), so a prompt does not hang — it gets EOF and the install dies
# halfway, which is worse than not starting.
set -euo pipefail
+umask 077
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
+ARTIFACT_LOCK="$ROOT/security/managed-app-artifacts.env"
+[ -r "$ARTIFACT_LOCK" ] || { echo "missing managed-app artifact lock: $ARTIFACT_LOCK" >&2; exit 2; }
+# shellcheck source=security/managed-app-artifacts.env
+. "$ARTIFACT_LOCK"
+
+validate_artifact_lock() {
+ [[ "$HERMES_INSTALLER_URL" == "https://raw.githubusercontent.com/NousResearch/hermes-agent/$HERMES_INSTALLER_TAG/scripts/install.sh" ]] || return 1
+ [[ "$HERMES_INSTALLER_COMMIT" =~ ^[0-9a-f]{40}$ ]] || return 1
+ [[ "$HERMES_INSTALLER_SHA256" =~ ^[0-9a-f]{64}$ ]] || return 1
+ [[ "$OPENCLAW_VERSION" =~ ^[0-9][0-9A-Za-z.-]*$ ]] || return 1
+ [[ "$OPENCLAW_TARBALL_SHA512" =~ ^[0-9a-f]{128}$ ]] || return 1
+}
+validate_artifact_lock || { echo "invalid managed-app artifact lock" >&2; exit 2; }
APP="${1:-}"
# loopback by default, deliberately. This runs on machines that are not mine: a
@@ -114,9 +131,15 @@ install_hermes() {
# Downloaded, then run from a file — not `curl | bash`. The bytes that execute
# are the bytes on disk, a truncated download fails at curl instead of running
# half a script, and the job transcript can name what it fetched.
- log "downloading the Hermes installer"
- curl -fsSL --max-time 300 https://hermes-agent.nousresearch.com/install.sh -o "$tmp/install.sh"
- printf 'installer: %s bytes, sha256 %s\n' "$(wc -c <"$tmp/install.sh")" "$(sha256sum <"$tmp/install.sh" | cut -c1-16)"
+ log "downloading the pinned Hermes installer ($HERMES_INSTALLER_TAG)"
+ curl -fsSL --proto '=https' --tlsv1.2 --max-time 300 "$HERMES_INSTALLER_URL" -o "$tmp/install.sh"
+ printf '%s %s
+' "$HERMES_INSTALLER_SHA256" "$tmp/install.sh" | sha256sum -c - >/dev/null || {
+ echo "Hermes installer integrity check failed" >&2
+ return 1
+ }
+ printf 'installer: %s bytes, verified sha256 %s
+' "$(wc -c <"$tmp/install.sh")" "${HERMES_INSTALLER_SHA256:0:16}"
# The upstream installer is NOT safely re-runnable against a live install: on a
# second pass it prints "Virtual environment already exists, recreating…" and
@@ -143,7 +166,10 @@ install_hermes() {
# --non-interactive makes it skip every stage that would ask (install.sh:3211).
# It pulls uv, Python, Node and ffmpeg itself; sudo is used only to apt-get git
# and degrades to a no-op without it.
- bash "$tmp/install.sh" --non-interactive
+ # Installer bytes and checkout are independently pinned. --force-commit
+ # prevents a broken pre-existing checkout from keeping unreviewed source.
+ bash "$tmp/install.sh" --non-interactive --branch main \
+ --commit "$HERMES_INSTALLER_COMMIT" --force-commit
fi
hermes_cmd
@@ -278,14 +304,27 @@ hermes_cmd() {
# -------------------------------------------------------------- openclaw ----
install_openclaw() {
- log "installing the OpenClaw CLI"
- # No sudo: npm's prefix is a user directory on any host set up this way
- # (`npm config get prefix` → ~/.local here). A root-owned prefix is the one
- # case this cannot fix, and npm says so plainly enough to act on.
- npm install -g openclaw@latest
+ local tmp tarball actual openclaw installed_version
+ tmp="$(mktemp -d)"
+ trap 'rm -rf "$tmp"' RETURN
+
+ log "installing the pinned OpenClaw CLI ($OPENCLAW_VERSION)"
+ # Verify the exact package bytes before npm can execute lifecycle hooks.
+ tarball="$(cd "$tmp" && npm pack "openclaw@$OPENCLAW_VERSION" --silent)"
+ [ -n "$tarball" ] && [ -f "$tmp/$tarball" ] || { echo "OpenClaw package download failed" >&2; return 1; }
+ actual="$(sha512sum "$tmp/$tarball" | awk '{print $1}')"
+ [ "$actual" = "$OPENCLAW_TARBALL_SHA512" ] || {
+ echo "OpenClaw tarball integrity check failed" >&2
+ return 1
+ }
+ npm install -g "$tmp/$tarball"
- local openclaw
openclaw="$(openclaw_bin)"
+ installed_version="$("$openclaw" --version 2>/dev/null | head -1)"
+ printf '%s' "$installed_version" | grep -Fq "$OPENCLAW_VERSION" || {
+ echo "installed OpenClaw version does not match lock: $installed_version" >&2
+ return 1
+ }
local -a auth=(--auth-choice skip)
if [ -n "$KEY" ]; then
diff --git a/scripts/security-ultimate.sh b/scripts/security-ultimate.sh
index 38a8308e..ba4ca346 100755
--- a/scripts/security-ultimate.sh
+++ b/scripts/security-ultimate.sh
@@ -2,6 +2,9 @@
# Reproducible MSO security assurance gate. Scanner details stay private; stdout is a pass/fail summary.
set -euo pipefail
umask 077
+# Transient/systemd jobs do not inherit an interactive shell PATH. Keep the gate
+# reproducible when Bun was installed in its standard per-user location.
+export PATH="$HOME/.bun/bin:$HOME/.local/bin:/usr/local/bin:/usr/bin:/bin:${PATH:-}"
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" || exit 1
cd "$ROOT"
diff --git a/security/managed-app-artifacts.env b/security/managed-app-artifacts.env
new file mode 100644
index 00000000..961bec92
--- /dev/null
+++ b/security/managed-app-artifacts.env
@@ -0,0 +1,12 @@
+# Immutable upstream artifacts used by MSO-managed application installers.
+# Update only after reviewing the upstream release, then refresh the corresponding
+# hash/digest and the supply-chain contract tests in the same commit.
+HERMES_INSTALLER_TAG='v2026.8.27'
+HERMES_INSTALLER_COMMIT='5fc308a70719a83cccdbba4c0e39c23f5a8239d5'
+HERMES_INSTALLER_URL='https://raw.githubusercontent.com/NousResearch/hermes-agent/v2026.8.27/scripts/install.sh'
+HERMES_INSTALLER_SHA256='c0380bc1f78d3d662a77663ce20cc17e14cbc4bec35e61ab7a33bac5f3afed2d'
+
+OPENCLAW_VERSION='2026.7.1-2'
+OPENCLAW_TARBALL_SHA512='c9c177c8f71b8cde9b50f79a531e8c87abf37b58505a80f7093ff059c983edaf316871c745468095aabe945c4c1dfd6cb0480e0d50308e5cd8aa9dadc24619ee'
+
+NINE_ROUTER_IMAGE_REF='decolua/9router@sha256:f00fe389ef41a1999dd0d0275ad0c2955d13d176f7c4c5cb844b2f88c293c471'