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.

feat: consolidate shell-app domain provisioning and Orca integration (#138)

Abdurrahman Fakhrule25c00d70265
diff --git a/.env.example b/.env.example
index a041be68..fb0ab186 100644
--- a/.env.example
+++ b/.env.example
@@ -217,6 +217,14 @@ OS_SESSION_SECRET=
# OS_SHELL_APP_DOMAINS_STORE=~/.mso/private/shell-app-domains.json
# Advanced local CLI transport; mso domain normally derives these from its selected env and port.
# MSO_DOMAIN_ENV=/absolute/path/to/.env.local
+#
+# Orca web bridge. The dashboard URL is the managed loopback endpoint; its port is
+# the managed Orca port (default 6769) the bridge expects for the bound socket.
+# ORCA_DASHBOARD_URL=http://127.0.0.1:6769
+# Private state root defaults to ~/.local/share/mso/orca; this is MSO-owned state,
+# never the owner's personal ~/.orca. Override only with a clean absolute path. An
+# invalid value fails the bridge closed, it does not fall back.
+# ORCA_HOME=/absolute/mso-owned/orca-state
# MSO_DOMAIN_LOCAL_ORIGIN=http://127.0.0.1:4005
# OS_SESSION_COOKIE_DOMAIN is obsolete; retained only to clear legacy cookies.
# OS_SESSION_COOKIE_DOMAIN=
diff --git a/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts b/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts
index ed8c9a5e..c48f97da 100644
--- a/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts
+++ b/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts
@@ -10,10 +10,11 @@ import {
} from "@/lib/managed-apps/origin";
import { contentSecurityPolicy } from "@/lib/managed-apps/proxy-csp";
import { errorPage, wantsErrorPage } from "@/lib/managed-apps/proxy-error-page";
+import { getOrcaReadiness } from "@/lib/managed-apps/orca-readiness";
import {
buildUpstreamHeaders,
isSecureRequest,
- isServiceWorkerPath,
+ isServiceWorkerRequest,
pickResponseHeaders,
readSetCookies,
rewriteLocation,
@@ -107,13 +108,39 @@ async function proxy(req: Request, context: { params: Promise<{ id: string; path
}
// A service worker registered from proxied bytes installs on the MSO origin
// and keeps serving after the window closes. Never hand one to the browser.
- if (isServiceWorkerPath(segments)) {
+ if (isServiceWorkerRequest(segments, req.headers.get("sec-fetch-dest"))) {
return fail(req, "service workers are not proxied", 404);
}
const definition = getManagedAppDefinition(params.id);
let base: URL;
- try { base = managedAppUpstream(definition.dashboardUrl); }
- catch { return fail(req, "upstream target is not loopback", 502); }
+ if (params.id === "orca") {
+ // A valid app cookie proves WHO is asking, not WHICH runtime owns the endpoint.
+ // Re-verify the runtime on every request so a stopped, replaced, or port-taken-over
+ // Orca denies immediately instead of proxying to whoever now owns the configured port.
+ // A bridge read failure is an unavailable runtime, never an unhandled route throw.
+ let readiness: Awaited<ReturnType<typeof getOrcaReadiness>>;
+ try {
+ readiness = await getOrcaReadiness();
+ } catch {
+ return fail(req, "managed application runtime is unavailable", 503);
+ }
+ if (!readiness.available || !readiness.startTicks) {
+ return fail(req, "managed application runtime is unavailable", 503);
+ }
+ try {
+ base = new URL(readiness.boundEndpoint);
+ if (base.protocol !== "ws:" || base.username || base.password) throw new Error("invalid bound endpoint");
+ base.protocol = "http:";
+ base.pathname = "/";
+ base.search = "";
+ base.hash = "";
+ } catch {
+ return fail(req, "managed application upstream unavailable", 502);
+ }
+ } else {
+ try { base = managedAppUpstream(definition.dashboardUrl); }
+ catch { return fail(req, "upstream target is not loopback", 502); }
+ }
const target = new URL(`/${segments.map(encodeURIComponent).join("/")}`, base);
target.search = new URL(req.url).search;
const headers = buildUpstreamHeaders(req, base, params.id, "");
@@ -146,6 +173,7 @@ async function proxy(req: Request, context: { params: Promise<{ id: string; path
// browser refuses to display it at all.
contentSecurityPolicy(prefixUrl, upstream.headers.get("content-security-policy"), {
cockpitOrigin: cockpitOrigin(),
+ appId: params.id,
}),
);
if (upstream.status >= 300 && upstream.status < 400) {
diff --git a/app/api/v1/managed-apps/[id]/session/route.test.ts b/app/api/v1/managed-apps/[id]/session/route.test.ts
new file mode 100644
index 00000000..5a134999
--- /dev/null
+++ b/app/api/v1/managed-apps/[id]/session/route.test.ts
@@ -0,0 +1,144 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+const auth = vi.hoisted(() => ({ context: null as null | { session: Record<string, unknown>; role: string } }));
+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: async () => auth.context }));
+vi.mock("@/lib/demo", () => ({ IS_DEMO: false }));
+
+const orca = vi.hoisted(() => ({
+ mode: "fake" as "fake" | "real",
+ fake: { available: true, pairingUrl: "orca://pair?code=abc", webClientUrl: "https://orca.mso.example.com/web-index.html#pairing=abc", runtimeId: "rt_1", serverPid: 4242, boundEndpoint: "ws://127.0.0.1:6769", advertisedEndpoint: "wss://orca.mso.example.com" },
+}));
+type OrcaReadinessModule = typeof import("@/lib/managed-apps/orca-readiness");
+
+vi.mock("@/lib/managed-apps/orca-readiness", async (importOriginal) => {
+ const actual = (await importOriginal()) as OrcaReadinessModule;
+ return {
+ ...actual,
+ getOrcaReadiness: async (deps?: Parameters<typeof actual.getOrcaReadiness>[0]) =>
+ orca.mode === "real" ? actual.getOrcaReadiness(deps) : orca.fake,
+ };
+});
+
+vi.hoisted(() => {
+ process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com";
+ process.env.OS_PUBLIC_ORIGIN = "https://mso.example.com";
+ process.env.OS_SESSION_SECRET = "s".repeat(32);
+});
+
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+const { GET } = await import("./route");
+const { buildOrcaWebClientUrl } = await import("@/lib/managed-apps/orca-pairing");
+
+const ORIGIN = "https://orca.mso.example.com";
+function validPairingUrl(): string {
+ const payload = { v: 2, endpoint: ORIGIN.replace(/^https:/, "wss:"), deviceToken: "dev_tok_12345", publicKeyB64: "pub_key_12345", scope: "runtime" };
+ const b64 = Buffer.from(JSON.stringify(payload)).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+ return `orca://pair?code=${b64}`;
+}
+
+const ctx = (id = "orca") => ({ params: Promise.resolve({ id }) });
+const get = (id = "orca") => GET(new Request("https://mso.example.com/api/v1/managed-apps/x/session"), ctx(id));
+
+function session(role: string) {
+ auth.context = { session: { device_id: "d1", expires_at: Date.now() + 3_600_000 }, role };
+}
+
+beforeEach(() => {
+ auth.context = null;
+ orca.mode = "fake";
+ const pairingUrl = validPairingUrl();
+ orca.fake = { available: true, pairingUrl, webClientUrl: buildOrcaWebClientUrl(ORIGIN, pairingUrl), runtimeId: "rt_1", serverPid: 4242, boundEndpoint: "ws://127.0.0.1:6769", advertisedEndpoint: "wss://orca.mso.example.com" };
+});
+
+describe("managed-app session route authorization", () => {
+ it("denies unauthenticated and Viewer sessions without leaking anything", async () => {
+ const unauth = await get();
+ expect(unauth.status).toBe(401);
+ expect(unauth.headers.get("cache-control")).toContain("no-store");
+ expect(await unauth.text()).not.toContain("pairing");
+
+ session("viewer");
+ const viewer = await get();
+ expect(viewer.status).toBe(401);
+ expect(viewer.headers.get("cache-control")).toContain("no-store");
+ });
+
+ it("denies any app when no split origin is configured", async () => {
+ session("operator");
+ vi.resetModules();
+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", "");
+ const fresh = await import("./route");
+ const res = await fresh.GET(new Request("https://mso.example.com/x"), ctx("orca"));
+ expect(res.status).toBe(404);
+ vi.unstubAllEnvs();
+ vi.resetModules();
+ });
+
+ it("returns 503 with no-store and no pairing or ticket when readiness is unavailable", async () => {
+ session("operator");
+ orca.fake = { available: false, reason: "runtime_identity_missing" } as never;
+ const res = await get();
+ expect(res.status).toBe(503);
+ expect(res.headers.get("cache-control")).toContain("no-store");
+ const body = await res.text();
+ expect(body).toContain("runtime_identity_missing");
+ expect(body).not.toContain("pairing");
+ expect(body).not.toContain("ticket");
+ expect(body).not.toContain("orca://");
+ });
+
+ it("enforces a real missing identity through the route (not a mocked success)", async () => {
+ session("operator");
+ orca.mode = "real";
+ const root = await mkdtemp(path.join(os.tmpdir(), "mso-orca-session-"));
+ try {
+ process.env.ORCA_HOME = root;
+ const status = {
+ type: "orca_server_ready",
+ schemaVersion: 1,
+ runtimeId: "rt_1",
+ boundEndpoint: "ws://127.0.0.1:6769",
+ advertisedEndpoint: "wss://orca.mso.example.com",
+ pairing: { available: true, scope: "runtime", url: validPairingUrl() },
+ health: { buildVersion: "1.4.230", nodeVersion: "24.21.0", nodeAbi: "137", pid: 4242, terminalDaemon: { state: "live", ownsFreshSessions: true, selfTest: { ok: true } } },
+ };
+ await writeFile(path.join(root, "private-status.json"), JSON.stringify(status), { mode: 0o600 });
+ const res = await get();
+ expect(res.status).toBe(503);
+ expect(await res.json()).toMatchObject({ reason: "runtime_identity_missing" });
+ } finally {
+ delete process.env.ORCA_HOME;
+ await rm(root, { recursive: true, force: true });
+ }
+ });
+
+ it("returns 200 no-store with only intended fields for an authorized Orca session", async () => {
+ session("operator");
+ const res = await get();
+ expect(res.status).toBe(200);
+ expect(res.headers.get("cache-control")).toContain("no-store");
+ const body = await res.json();
+ expect(Object.keys(body).sort()).toEqual(["origin", "pairingUrl", "runtimeId", "ticket", "webClientUrl"]);
+ expect(body.origin).toBe("https://orca.mso.example.com");
+ expect(body.webClientUrl).toBe(buildOrcaWebClientUrl(ORIGIN, orca.fake.pairingUrl));
+ expect(typeof body.ticket).toBe("string");
+ });
+
+ it("still serves a non-Orca app with origin and ticket only", async () => {
+ session("operator");
+ const res = await get("hermes");
+ expect(res.status).toBe(200);
+ const body = await res.json();
+ expect(Object.keys(body).sort()).toEqual(["origin", "ticket"]);
+ expect(body.origin).toBe("https://hermes.mso.example.com");
+ });
+});
+
+afterAll(() => {
+ delete process.env.ORCA_HOME;
+});
diff --git a/app/api/v1/managed-apps/[id]/session/route.ts b/app/api/v1/managed-apps/[id]/session/route.ts
index faf229eb..d68936b3 100644
--- a/app/api/v1/managed-apps/[id]/session/route.ts
+++ b/app/api/v1/managed-apps/[id]/session/route.ts
@@ -4,13 +4,32 @@ import { roleAtLeast } from "@/lib/auth/roles";
import { isManagedAppId } from "@/lib/managed-apps/catalog";
import { managedAppOrigin } from "@/lib/managed-apps/origin";
import { createManagedAppTicket } from "@/lib/managed-apps/session";
+import { getOrcaReadiness } from "@/lib/managed-apps/orca-readiness";
import { IS_DEMO } from "@/lib/demo";
export const dynamic = "force-dynamic";
+const NO_STORE = { "cache-control": "no-store" } as const;
export async function GET(_req: Request, context: { params: Promise<{ id: string }> }) {
const session = await getSessionContext();
- if (IS_DEMO || !session || !roleAtLeast(session.role, "operator")) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
+ if (IS_DEMO || !session || !roleAtLeast(session.role, "operator")) return NextResponse.json({ error: "unauthorized" }, { status: 401, headers: NO_STORE });
const { id } = await context.params;
- if (!isManagedAppId(id) || !managedAppOrigin(id)) return NextResponse.json({ error: "unavailable" }, { status: 404 });
- return NextResponse.json({ origin: managedAppOrigin(id), ticket: createManagedAppTicket(id, session.session, process.env.OS_SESSION_SECRET ?? "") }, { headers: { "cache-control": "no-store" } });
+ if (!isManagedAppId(id) || !managedAppOrigin(id)) return NextResponse.json({ error: "unavailable" }, { status: 404, headers: NO_STORE });
+ const origin = managedAppOrigin(id)!;
+ const ticket = createManagedAppTicket(id, session.session, process.env.OS_SESSION_SECRET ?? "");
+
+ if (id === "orca") {
+ const readiness = await getOrcaReadiness();
+ if (!readiness.available) {
+ return NextResponse.json({ error: "unavailable", reason: readiness.reason }, { status: 503, headers: NO_STORE });
+ }
+ return NextResponse.json({
+ origin,
+ ticket,
+ pairingUrl: readiness.pairingUrl,
+ webClientUrl: readiness.webClientUrl,
+ runtimeId: readiness.runtimeId,
+ }, { headers: NO_STORE });
+ }
+
+ return NextResponse.json({ origin, ticket }, { headers: NO_STORE });
}
diff --git a/app/api/v1/managed-apps/proxy-orca-runtime.test.ts b/app/api/v1/managed-apps/proxy-orca-runtime.test.ts
new file mode 100644
index 00000000..46883fda
--- /dev/null
+++ b/app/api/v1/managed-apps/proxy-orca-runtime.test.ts
@@ -0,0 +1,82 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("@/lib/managed-apps/session", () => ({ managedAppSession: vi.fn(async () => ({ device_id: "test" })) }));
+vi.mock("@/lib/managed-apps/orca-readiness", () => ({ getOrcaReadiness: vi.fn() }));
+
+const fetchMock = vi.fn();
+vi.stubGlobal("fetch", fetchMock);
+
+const HOST_HEADER = "x-os-managed-app-host";
+const ctx = { params: Promise.resolve({ id: "orca", path: ["chat"] }) };
+const READY = {
+ available: true as const,
+ pairingUrl: "orca://pair?code=fixture",
+ webClientUrl: "https://orca.mso.example.com/web-index.html",
+ runtimeId: "rt_fixture",
+ serverPid: 4242,
+ startTicks: "99887766",
+ boundEndpoint: "ws://127.0.0.1:7777",
+ advertisedEndpoint: "wss://orca.mso.example.com",
+};
+
+function req(): Request {
+ return new Request("https://orca.mso.example.com/api/v1/managed-apps/orca/proxy/chat", {
+ headers: { [HOST_HEADER]: "orca", "sec-fetch-dest": "empty" },
+ });
+}
+
+beforeEach(async () => {
+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", "{id}.mso.example.com");
+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.com");
+ vi.resetModules();
+ fetchMock.mockReset();
+ fetchMock.mockResolvedValue(new Response("ok", { status: 200 }));
+ const { getOrcaReadiness } = await import("@/lib/managed-apps/orca-readiness");
+ vi.mocked(getOrcaReadiness).mockReset();
+ vi.mocked(getOrcaReadiness).mockResolvedValue(READY);
+});
+
+describe("Orca HTTP proxy runtime revalidation", () => {
+ it("re-verifies readiness on every request and proxies to the verified endpoint", async () => {
+ const { GET } = await import("./[id]/proxy/[[...path]]/route");
+ const { getOrcaReadiness } = await import("@/lib/managed-apps/orca-readiness");
+
+ expect((await GET(req(), ctx)).status).toBe(200);
+ expect((await GET(req(), ctx)).status).toBe(200);
+ expect(vi.mocked(getOrcaReadiness)).toHaveBeenCalledTimes(2);
+ expect(String(fetchMock.mock.calls[0][0])).toBe("http://127.0.0.1:7777/chat");
+ expect(String(fetchMock.mock.calls[1][0])).toBe("http://127.0.0.1:7777/chat");
+ });
+
+ it("rejects a changed or port-taken-over runtime instead of reaching the upstream", async () => {
+ const { GET } = await import("./[id]/proxy/[[...path]]/route");
+ const { getOrcaReadiness } = await import("@/lib/managed-apps/orca-readiness");
+ vi.mocked(getOrcaReadiness).mockResolvedValue({ available: false, reason: "listener_not_owned_by_process" });
+
+ const res = await GET(req(), ctx);
+ expect(res.status).toBe(503);
+ expect(await res.json()).toMatchObject({ error: "managed application runtime is unavailable" });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("turns a readiness throw into a safe 503, never an unhandled route error", async () => {
+ const { GET } = await import("./[id]/proxy/[[...path]]/route");
+ const { getOrcaReadiness } = await import("@/lib/managed-apps/orca-readiness");
+ vi.mocked(getOrcaReadiness).mockRejectedValueOnce(new Error("procfs exploded"));
+
+ const res = await GET(req(), ctx);
+ expect(res.status).toBe(503);
+ expect(await res.json()).toMatchObject({ error: "managed application runtime is unavailable" });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("rejects when the verified success lacks a kernel start tick", async () => {
+ const { GET } = await import("./[id]/proxy/[[...path]]/route");
+ const { getOrcaReadiness } = await import("@/lib/managed-apps/orca-readiness");
+ vi.mocked(getOrcaReadiness).mockResolvedValue({ ...READY, startTicks: undefined });
+
+ const res = await GET(req(), ctx);
+ expect(res.status).toBe(503);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/app/api/v1/managed-apps/proxy-split-origin.test.ts b/app/api/v1/managed-apps/proxy-split-origin.test.ts
index d1a4e15c..1fef7e18 100644
--- a/app/api/v1/managed-apps/proxy-split-origin.test.ts
+++ b/app/api/v1/managed-apps/proxy-split-origin.test.ts
@@ -10,6 +10,8 @@ type CatalogModule = typeof import("@/lib/managed-apps/catalog");
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MANAGED_APP_HOST_HEADER } from "@/lib/managed-apps/origin";
+vi.mock("server-only", () => ({}));
+
vi.mock("@/lib/managed-apps/session", () => ({ managedAppSession: vi.fn(async () => ({ device_id: "test" })) }));
const dashboardUrl = { current: "http://127.0.0.1:9119" };
diff --git a/app/api/v1/managed-apps/proxy.test.ts b/app/api/v1/managed-apps/proxy.test.ts
index 7ff1de87..dc27453c 100644
--- a/app/api/v1/managed-apps/proxy.test.ts
+++ b/app/api/v1/managed-apps/proxy.test.ts
@@ -7,6 +7,8 @@ type CatalogModule = typeof import("@/lib/managed-apps/catalog");
// proxy-containment.test.ts.
import { beforeEach, describe, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+
vi.mock("@/lib/managed-apps/session", () => ({ managedAppSession: vi.fn(async () => ({ device_id: "test" })) }));
const dashboardUrl = { current: "http://127.0.0.1:9119" };
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index d3730ee6..0ec8ef64 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -11,22 +11,36 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
- one-click install and connect converge on a shared shell-app domain step (#136)
- `settings` explain update refusals, merge Server into Devices (#135)
+**Fixed**
+
+- `orca` create temp fixtures privately and pin file reads to one descriptor
+
+**Chores**
+
+- `security` allowlist the reviewed Orca env fixture by exact line
+
## 2026-10-21
**Added**
- `cli` print the mso ai reply text instead of SSE frames
+- `shell-apps` provision public domains for shell apps
+- `app-store` converge install and connect on one domain step
+- `infra` add managed domain provider abstraction
- `infra` add Linear provider and route Composio key kinds by header
**Fixed**
-- `proxy` let the owner icon upload reach its own 8 MiB cap
-- `host` make agent worktrees owner-private regardless of umask
+- `managed-apps` make socket-policy import type only for orca readiness
+- `managed-apps` export and use deny in socket-policy fallback
+- `managed-apps` load orca readiness lazily in socket policy
+- `app-domain` wire the real provider module and single-source the domain contract
- `deps` pin vite 8.2.4 to clear GHSA-587h-7wmj-h5pm
-**Build**
+**Tests**
-- `deps` make sharp a direct dependency and add @phosphor-icons/react
+- `e2e` target close button inside form to disambiguate drawer close
+- `e2e` align shell-apps E2E with converged domain step
## 2026-10-20
@@ -34,9 +48,66 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
- `assistant` accept OpenAI-shaped {content} messages and harden recall
- `build` keep convex CLI config path out of asset tracing
+- `managed-apps` invalidate Orca integrity cache on managed actions
+- `managed-apps` statically scope personal Orca path checks
+- `managed-apps` preserve exact-owned Orca stop containment
+- `managed-apps` authorize unit replacement against caller expected configuration
+- `managed-apps` enforce fresh verification and receipt permissions on Orca mutations
+
+**Tests**
+
+- `managed-apps` finish bounded listener-owned rewrite fixture
+
+**Other**
+
+- `test` preserve bounded rewrite fixture startup cleanup
+- `test` preserve listener-owned Orca rewrite fixture
## 2026-10-19
+**Added**
+
+- `managed-apps` integrate orca web readiness parser, session pairing bridge, and bootstrap VM tests
+- `managed-apps` enforce Orca browser containment, SW rejection, and strict WS origin (checkpoint 2)
+- `managed-apps` integrate Orca web entry and identity contract (checkpoint 1)
+- `orca` add immutable pinned release acquisition for managed runtime
+- `orca` implement node runtime materializer and headless server adapter
+
+**Fixed**
+
+- `managed-apps` reject ambiguous Orca strict quiescence
+- `managed-apps` prove owned Orca unit against recorded launcher config
+- `managed-apps` harden owned Orca unit proof and strict quiescence
+- `managed-apps` align Orca root policy and refuse pairing grant claims by presence
+- `managed-apps` keep the app-host rewrite internal under a loopback hostname
+- `proxy` keep nextUrl's exact origin for the managed-app rewrite
+- `orca` reject a non-absolute argv[0] without cwd resolution
+- `managed-apps` load the server-only Orca bridge lazily in shared health
+- `orca` reject a unit reached through any symlinked ancestor
+- `orca` honor systemctl exit codes in rollback, harden owned-unit proof
+- `orca` owned-unit + verified-receipt manager ownership and install safety
+- `orca` fail-closed installer root, receipts, release containment, unit guard
+- `orca` supervise child exit and retriable teardown
+- `orca` derive slot .version from upstream raw-byte artifact identity
+- `managed-apps` fail-closed orca bridge readiness, identity and pairing
+- `orca` place bundled Node at the upstream sibling runtime path
+- `orca` harden supervised lifecycle and terminal proof
+- `orca` harden runtime paths, deb acquisition, slot validation, and lifecycle teardown
+
+**Changed**
+
+- `managed-apps` reuse orca readiness parser in bridge
+
+**Tests**
+
+- `security` allowlist reviewed historical Orca env test fixture
+- `managed-apps` pin the app-host rewrite to Next's own nextUrl origin
+- `agent` synchronize the concurrent session-turn lease test
+- `host` keep delegated-write positive fixture out of protected TMPDIR
+- `orca` avoid generic calls the pinned scanner cannot parse
+- `config` exempt Orca fixture and private handoff env vars
+- `orca` split oversized acquisition tests into cohesive suites
+
**Build**
- `deps` bump the production-minor-patch group across 1 directory with 15 updates
@@ -44,6 +115,11 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
- `deps` bump the actions-minor-patch group with 6 updates
- `deps-dev` bump the development-minor-patch group with 3 updates
+**Other**
+
+- `managed-apps` preserve reviewed Orca runtime binding checkpoint
+- `orca` drop trailing blank line at EOF in managed-rollback test
+
## 2026-10-18
**Added**
diff --git a/docs/ORCA-INTEGRATION.md b/docs/ORCA-INTEGRATION.md
new file mode 100644
index 00000000..1c8af811
--- /dev/null
+++ b/docs/ORCA-INTEGRATION.md
@@ -0,0 +1,128 @@
+# Orca Web Integration Architecture & Security Contracts
+
+Status: **local development candidate** on the task branch. Not merged, released, or
+deployed, and not claimed live: no real Orca runtime, browser journey, or upstream install has
+been executed as part of this worktree. The MSO-owned installer/adapter, the pinned-release
+lifecycle, and the manager ownership rule below are implemented and covered by dry-run/unit
+fixtures; the live service install remains the operator's explicit action.
+
+Target: Orca IDE v1.4.230, Node-only headless `orcad` server.
+
+---
+
+## 1. Split-origin requirement
+
+MSO embeds vendor web dashboards strictly through dedicated subdomains/hosts (e.g.
+`orca.mso.example.com`) defined by `NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE="{id}.mso.example.com"`:
+
+- **Cross-origin boundary**: the iframe runs with `allow-same-origin` so the Orca web
+ client can use its own cookies, IndexedDB, and Web Workers. Because it runs on a host
+ separate from the cockpit, `window.top` is opaque and `/api/v1/exec` does not exist on
+ that origin.
+- **No same-origin fallback**: a deployment without a host template disables iframe
+ embedding; MSO falls back to the CLI view. There is deliberately no path-on-cockpit mode.
+
+## 2. Shared operator workspace & terminal semantics
+
+Per `PAIRING-DECISION.md`:
+
+- **Single Unix principal**: all MSO Operators share the one running `orcad` workspace and
+ terminals.
+- **Upstream authorization gap**: Orca v1.4.230 has no per-device revocation or multi-tenant
+ RPC authorization. MSO does not invent one.
+- **Outer gate**: HTTP and WebSocket access require a live Operator/Owner role and an active
+ MSO device session; active sockets are re-authorized on the existing chunk/idle timer.
+ Viewer or revoked devices are denied at the proxy and upgrade boundaries. Retaining an
+ upstream key does not bypass the MSO gate. This is **not** upstream row deletion and is not
+ a per-device upstream grant surface.
+
+## 3. Runtime readiness (fail closed)
+
+`getOrcaReadiness()` is unavailable unless **all** of the following hold. There is no static
+fallback and no "live PID" shortcut.
+
+- `private-status.json` carries the exact tag `type: "orca_server_ready"`, `schemaVersion: 1`,
+ a non-empty `runtimeId`, `health.buildVersion === "1.4.230"`, `health.nodeVersion === "24.21.0"`,
+ `health.nodeAbi === "137"`, a positive `health.pid`, and a live terminal daemon
+ (`state: "live"`, `ownsFreshSessions: true`, `selfTest.ok: true`). An `artifactVersion`
+ field can never override the real `health.buildVersion`.
+- The bound endpoint is `ws://127.0.0.1:<managed-port>` — loopback, no credentials, path,
+ query, or fragment. The managed port comes from config (default 6769); the user's existing
+ 6768 listener is never adopted.
+- The advertised endpoint is the exact configured WSS origin with no credentials, path,
+ query, or fragment.
+- Pairing is available with an **explicit** `scope: "runtime"` and a valid offer (section 6).
+
+## 4. Private state root and identity receipt
+
+- Managed root is MSO-owned state: `~/.local/share/mso/orca`, or a clean absolute `ORCA_HOME`.
+ An invalid `ORCA_HOME` fails the bridge closed; it never falls back to the owner's personal
+ `~/.orca`/`~/.orca-remote`.
+- `private-status.json` is 0600 under a 0700 owner directory. Reads reject symlinked ancestors
+ and symlinked leaves, open `O_NOFOLLOW`, bound the size before any byte moves, and re-check
+ file identity after reading.
+- `runtime-identity.json` is **mandatory** (schema 1): `runtimeId`, `version`, `serverPid`,
+ `serverStartTicks`, `nodeBinary`, `serverEntry`, `userData`, `boundEndpoint`,
+ `advertisedEndpoint`, `readyAt`. Its paths must be contained in the managed root
+ (release slot under `releases/`, profile at `runtime/user-data`).
+
+## 5. Process identity
+
+The receipt's `serverPid` must equal `private-status.health.pid` and resolve to the exact
+owned kernel process. Verification reads only `/proc/PID/stat` (field 22 start time,
+comm-safe parsing), `/proc/PID` owner UID, `/proc/PID/exe`, and `/proc/PID/cmdline` — **never**
+`/proc/PID/environ` or credentials. PID, start ticks, UID, canonical executable, and server
+script argv must all match. A missing, reused, foreign, unreadable, or EPERM process yields
+`unavailable`, never a blessing.
+
+## 6. Pairing offer and delivery
+
+- The offer must be scope `runtime`, bound to the **exact** configured WSS origin (no relay,
+ no userinfo/path/query/fragment), with well-formed token/key material. Absent scope (the
+ upstream legacy/mobile shape), relay offers, and any grant claim are refused. Upstream does
+ not encode grants in this offer, so MSO cannot and does not certify upstream permissions.
+- MSO constructs the one frameable URL itself:
+ `https://<app-origin>/web-index.html#pairing=<encodeURIComponent(pairingUrl)>`. An
+ upstream-provided `webClientUrl` is never trusted. The credential lives in the fragment
+ only — never a query, a log, or a cookie.
+- Non-Orca managed apps never accept a server-supplied navigation URL; a `webClientUrl` on
+ another app's response is refused.
+
+## 7. Session route and UI
+
+`GET /api/v1/managed-apps/[id]/session` returns `no-store` always. Non-Operator/Viewer/
+unauthenticated callers get 401; a missing split origin gets 404; an unavailable Orca gets
+503 with a safe reason enum and no pairing/ticket material. The client aborts a stale in-flight
+authorization and invalidates prior authorization before resolving, so a revoked or refreshed
+session cannot remount an old frame. A revoked MSO session fails at the live proxy; the client
+does not delete upstream rows.
+
+> The Managed Apps panel's `healthy` flag still reflects static HTTP reachability of
+> `/web-index.html`. That is a liveness hint only. Browser pairing is gated by the full
+> readiness/identity check above, not by that flag.
+
+## 8. Containment & unsupported capabilities
+
+- **Service workers**: rejected at the proxy boundary (`Sec-Fetch-Dest: serviceworker` → 404,
+ any path).
+- **CSP**: `worker-src` limited to the app root plus `blob:`; `script-src` allows
+ `'wasm-unsafe-eval'` (never `'unsafe-eval'`).
+- **WebSocket upgrade**: exact same-origin HTTPS `Origin` matching the configured Orca host.
+- **Lifecycle**: install is offered only through MSO's own managed installer
+ (`installBackends: ["user-systemd"]`); update/uninstall/desktop-control remain disabled and
+ `commandProvesInstall: false`. Pairing offers claiming desktop control are refused.
+- **Manager ownership (fail closed)**: the manager treats Orca as installed ONLY when the exact
+ USER unit `~/.config/systemd/user/mso-orca.service` is a regular, owner-owned file (no
+ symlink) carrying MSO's marker + fixed `scripts/orca/cli.mjs run --managed-root …` argv AND a
+ verified install receipt (`managed-install.json`, rehashed through the adapter). A same-name
+ SYSTEM unit, a wrong-scope unit, or a missing/invalid receipt is `not-installed` with a
+ diagnostic; start/stop/restart/logs act on the user unit only and never fall through to a
+ foreign system unit.
+- **First-install rollback**: a first install that fails after writing the unit stops only the
+ exact unit MSO created, restores/removes the prior owned config/unit/receipt, and — if that
+ rollback cannot finish — leaves an explicit `partial-install.json` marker so the next install
+ refuses rather than adopt a half state. An absent unit is published with an exclusive
+ hardlink, so a foreign unit created at the last instant is never overwritten.
+- **Not verified here**: pinned installer execution, live browser/worker/WASM journey, and
+ end-to-end runtime start are out of this slice and must be proven with real artifacts before
+ any "verified" claim.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 15cca5ea..7489bc6b 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -28,6 +28,70 @@ Evidence at the committed candidate: 13/13 targeted tests, `tsc --noEmit`, `esli
provider union and record shape; the browser copy in
`frontend/slices/app-store/lib/app-domain.ts` mirrors it and a parity test fails on drift.
+## 2026-10-21: Shell-app domain provisioning (phase 1, worker B)
+
+New `lib/surfaces/app-domain-provision.ts` provisions a public hostname for a shell-app entry:
+loopback probe → DNS write → route → verify, persisting every phase in an owner-only
+`~/.mso/private/shell-app-domains.json` (0600/0700, `O_NOFOLLOW`, uid-checked, locked) so a failed
+run resumes at the phase it reached instead of restarting from `pending`. Hostnames equal to,
+domain-matching, or containing the cockpit name, names inside `OS_SESSION_COOKIE_DOMAIN`, and
+anything `externalSurfaceSharesSession` blocks are rejected with a precise error — never
+substituted. Owner-only `POST`/`GET /api/v1/shell-apps/[id]/domain` mirror the existing shell-app
+gate order, rate limit, `Cache-Control: no-store, private` and audit trail. New CLI verbs
+`mso mapp shell-domain <id>` and `mso mapp shell-domain-save <id> <JSON|@file>` keep every route
+reachable from a shell.
+
+Contract 1 is `lib/infra/managed-domain-providers.ts`; provisioning imports its three boundary
+functions directly, so there is no injection seam in the shipped composition root. The genuine
+`provider_unavailable` case is a configured provider with no stored credentials, which that
+module raises itself. `lib/contracts/app-domain.ts` is the single server-side spelling of the
+provider union and record shape; the browser copy in
+`frontend/slices/app-store/lib/app-domain.ts` mirrors it and a parity test fails on drift.
+
+## 2026-10-19: Orca bridge corrective checkpoint (local development candidate)
+
+Local candidate on `feat/orca-web-20261019`. Not merged, released, or deployed. This pass fixes
+fail-open defects in the earlier Checkpoint 3 readiness/pairing/session/UI bridge; the runtime
+installer/lifecycle slice (`scripts/orca`) is owned separately and untouched here.
+
+- **Readiness is now fail closed** (`lib/managed-apps/orca-readiness.ts`): requires the exact
+ `orca_server_ready` schema-1 tag, `health.buildVersion` 1.4.230 (an `artifactVersion` cannot
+ override it), pinned Node 24.21.0 ABI 137, live terminal daemon, `ws` loopback bound endpoint
+ on the managed port, exact configured `wss` advertised endpoint, and explicit runtime pairing.
+- **Mandatory identity receipt + process identity** (`lib/managed-apps/orca-process-identity.ts`):
+ `runtime-identity.json` is required; PID/startTicks/UID/exe/cmdline must match via `/proc`
+ (never environ). Missing/reused/foreign/unreadable/EPERM identity denies. A real disposable
+ same-task node process is exercised in tests; the test runner's PID is refused.
+- **Symlink-proof bounded private reads** (`lib/managed-apps/orca-private-fs.ts`): rejects
+ symlinked ancestors/leaves, opens `O_NOFOLLOW`, bounds size before reading, re-checks identity,
+ and never touches the owner's personal `~/.orca`. Invalid `ORCA_HOME` fails closed instead of
+ silently falling back.
+- **Strict pairing + canonical web client** (`lib/managed-apps/orca-pairing.ts`): explicit
+ runtime scope only, exact trusted WSS endpoint with no relay/userinfo/path/query, and a
+ server-constructed `…/web-index.html#pairing=<encoded>` fragment. Upstream grants are not
+ certified; arbitrary `webClientUrl` is never trusted.
+- **Session route** returns `no-store` on every outcome and 503 with a safe reason when readiness
+ is missing (`app/api/v1/managed-apps/[id]/session/route.test.ts`).
+- **UI authorization pipeline** (`frontend/slices/managed-apps/app-authorization.ts`,
+ `feature-app.tsx`): Orca-only URL override, stale-request abort, prior-authorization
+ invalidation; tested with real `Response`/`AbortController`.
+- **Honest docs**: `docs/ORCA-INTEGRATION.md` corrected and classified in `docs/README.md`;
+ no real browser/runtime/install verification is claimed.
+
+## 2026-10-19: Orca web integration Checkpoint 3 (local development candidate)
+
+Local development candidate on `feat/orca-web-20261019`. This is an in-progress worktree candidate, not merged to main, not released, and not deployed.
+
+**Scope implemented:**
+- Verified bootstrap JavaScript execution inside an isolated VM browser DOM sandbox (`lib/managed-apps/orca-bootstrap.test.ts`), proving credential exchange, pairing fragment preservation in the hash, ticket removal, and error handling without query parameter leakage.
+- Enforced arbitrary-path `Sec-Fetch-Dest: serviceworker` rejection at the reverse proxy boundary without upstream invocation, and verified that dedicated/shared workers are forwarded only under live Operator authentication.
+- Server-only Orca private readiness parser and bridge (`lib/managed-apps/orca-readiness.ts`), strictly enforcing fixed managed root (`~/.local/share/mso/orca` or `ORCA_HOME`), 0700/0600 file modes, 64KB size limit, no symlinks, process liveness check, version 1.4.230 check, port 6769 loopback bind, live terminal daemon state, and pairing offer invariants.
+- Upstream pairing offer decoder and validator (`lib/managed-apps/orca-pairing.ts`) conforming to Orca v1.4.230 schema, validating same-origin WSS endpoint, runtime scope, and absence of desktop-control grants.
+- Session route bridge (`app/api/v1/managed-apps/[id]/session/route.ts`) returning safe pairing payload `{ origin, ticket, pairingUrl, webClientUrl, runtimeId }` exclusively for live Operator sessions with `Cache-Control: no-store`; rejecting unauthenticated or Viewer callers with 401 and unavailable Orca instances with 503.
+- Orca UI component and state tests (`frontend/slices/managed-apps/orca-ui.test.tsx`), validating initial loading presentation, disabled installer when `installBackends` is empty, fragment resolution without query secrets, and rejection of Viewer roles without credential leakage.
+- Catalog configuration updated to repo-owned adapter path `scripts/managed-app-orca` with `commandProvesInstall: false`, service `mso-orca.service`, no generic container detection, default port 6769, health path `/web-index.html`, and state dir `orca`.
+- Added portable documentation `docs/ORCA-INTEGRATION.md`.
+
## 2026-10-18: MSO deep QA stopped at the user's request
Work and active QA were stopped on 18 October 2026 at the user's explicit request. This is a progress checkpoint directly on main, not a release of the development candidate. Resume implementation, validation or deployment only after a new user instruction.
diff --git a/docs/README.md b/docs/README.md
index dd1bb5fb..893db205 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -72,6 +72,7 @@ evidence and review freshness. The repository quality gate runs both automatical
| [`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 immutable Docker ownership, loopback default and explicit dashboard exposure |
+| [`ORCA-INTEGRATION.md`](./ORCA-INTEGRATION.md) | Orca web bridge readiness/identity contract, private state root and shared-runtime operator limits |
| [`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/frontend/slices/app-store/components/connect-app-form.tsx b/frontend/slices/app-store/components/connect-app-form.tsx
index 5aa433cd..881b1eb8 100644
--- a/frontend/slices/app-store/components/connect-app-form.tsx
+++ b/frontend/slices/app-store/components/connect-app-form.tsx
@@ -25,7 +25,11 @@ export function ConnectAppForm({ existing, manifest, onClose }: { existing?: She
setBusy(true); setError("");
try {
await mutate(manifest ? { action: "import", manifest, binding: { id: app.id, url: app.url, mode: app.mode } } : { action: existing ? "update" : "add", app });
- setConnected({ id: app.id, title: app.title, url: app.url });
+ if (existing) {
+ onClose();
+ } else {
+ setConnected({ id: app.id, title: app.title, url: app.url });
+ }
}
catch (reason) { setError(reason instanceof Error ? reason.message : "Could not connect app."); }
finally { setBusy(false); }
diff --git a/frontend/slices/managed-apps/app-authorization.ts b/frontend/slices/managed-apps/app-authorization.ts
new file mode 100644
index 00000000..90a69c20
--- /dev/null
+++ b/frontend/slices/managed-apps/app-authorization.ts
@@ -0,0 +1,62 @@
+/** Client-side authorization pipeline for managed-app frames.
+ *
+ * Split out of the React component so the real behavior — an actual fetch of the
+ * session route plus abort semantics — is testable without a DOM renderer.
+ *
+ * Only the Orca bridge may choose a different framed document: the server builds
+ * the canonical `…/web-index.html#pairing=…` URL. Every other app frames its own
+ * fixed origin root, and a server-supplied `webClientUrl` for them is refused
+ * rather than navigated to (no untrusted same-origin navigation path).
+ */
+export interface AuthorizedFrame {
+ source: string;
+ url: string;
+}
+
+export async function resolveAuthorizedFrame(response: Response, embeddedSource: string, appId: string): Promise<AuthorizedFrame> {
+ if (!response.ok) throw new Error("authorization failed");
+ const data = await response.json();
+ const expectedOrigin = new URL(embeddedSource).origin;
+ if (data.origin !== expectedOrigin || typeof data.ticket !== "string" || data.ticket.length === 0) {
+ throw new Error("authorization origin mismatch");
+ }
+
+ let targetSource = embeddedSource;
+ if (appId === "orca") {
+ if (typeof data.webClientUrl !== "string") throw new Error("authorization origin mismatch");
+ const candidate = new URL(data.webClientUrl);
+ if (candidate.origin !== expectedOrigin || candidate.pathname !== "/web-index.html" || candidate.search !== "") {
+ throw new Error("authorization origin mismatch");
+ }
+ if (!candidate.hash.startsWith("#pairing=")) throw new Error("authorization origin mismatch");
+ targetSource = data.webClientUrl;
+ } else if (data.webClientUrl !== undefined && data.webClientUrl !== null) {
+ throw new Error("authorization origin mismatch");
+ }
+
+ const url = new URL(targetSource);
+ if (url.origin !== expectedOrigin) throw new Error("authorization origin mismatch");
+ const fragment = new URLSearchParams(url.hash.slice(1));
+ fragment.set("app_ticket", data.ticket);
+ url.hash = fragment.toString();
+ return { source: embeddedSource, url: url.toString() };
+}
+
+export async function requestAuthorizedFrame(appId: string, embeddedSource: string, signal: AbortSignal): Promise<AuthorizedFrame> {
+ const response = await fetch(`/api/v1/managed-apps/${appId}/session`, { cache: "no-store", signal });
+ return resolveAuthorizedFrame(response, embeddedSource, appId);
+}
+
+export interface FrameAuthState {
+ generation: number;
+ auth: AuthorizedFrame | null;
+ error: boolean;
+}
+
+/** Select the frame URL for the CURRENT generation. A result stamped with an older
+ * generation (a stale response that raced a refresh/remount) is ignored, so an old
+ * authorized frame can never be re-mounted. */
+export function selectAuthorizedFrame(state: FrameAuthState, generation: number, embeddedSource: string): { url: string | null; error: boolean } {
+ if (state.generation !== generation) return { url: null, error: false };
+ return { url: state.auth?.source === embeddedSource ? state.auth.url : null, error: state.error };
+}
diff --git a/frontend/slices/managed-apps/app-meta.tsx b/frontend/slices/managed-apps/app-meta.tsx
new file mode 100644
index 00000000..e39dfe03
--- /dev/null
+++ b/frontend/slices/managed-apps/app-meta.tsx
@@ -0,0 +1,77 @@
+import { Bot, SquareCode, Workflow, type LucideIcon } from "lucide-react";
+import React, { createElement } from "react";
+import type { AppIconComponent } from "@/features/appshell";
+import type { ManagedAppId } from "@/lib/managed-apps/types";
+
+export const NineRouterIcon: AppIconComponent = ({ className }) =>
+ createElement("img", {
+ src: "/brand/official/9router.webp",
+ alt: "",
+ "aria-hidden": true,
+ className: className ?? "size-full object-contain",
+ draggable: false,
+ });
+
+export interface ManagedAppMeta {
+ title: string;
+ gradient: string;
+ loader: "HermesApp" | "OpenClawApp" | "NineRouterApp" | "OrcaApp";
+ icon: LucideIcon | AppIconComponent;
+ artwork?: string;
+ tone?: string;
+}
+
+export const MANAGED_APP_META: Record<ManagedAppId, ManagedAppMeta> = {
+ hermes: {
+ title: "Hermes",
+ gradient: "linear-gradient(160deg,#8b5cf6,#4f46e5)",
+ loader: "HermesApp",
+ icon: Bot,
+ tone: "text-violet-400",
+ },
+ openclaw: {
+ title: "OpenClaw",
+ gradient: "linear-gradient(160deg,#f97316,#dc2626)",
+ loader: "OpenClawApp",
+ icon: Workflow,
+ tone: "text-orange-400",
+ },
+ "9router": {
+ title: "9Router",
+ gradient: "linear-gradient(160deg,#0ea5e9,#2563eb)",
+ loader: "NineRouterApp",
+ icon: NineRouterIcon,
+ artwork: "/brand/official/9router.webp",
+ },
+ orca: {
+ title: "Orca",
+ gradient: "linear-gradient(160deg,#0284c7,#1e3a8a)",
+ loader: "OrcaApp",
+ icon: SquareCode,
+ tone: "text-sky-400",
+ },
+};
+
+export const MANAGED_APP_NAMES: Record<ManagedAppId, string> = {
+ hermes: MANAGED_APP_META.hermes.title,
+ openclaw: MANAGED_APP_META.openclaw.title,
+ "9router": MANAGED_APP_META["9router"].title,
+ orca: MANAGED_APP_META.orca.title,
+};
+
+export function AppMark({ id, className }: { id: ManagedAppId; className?: string }) {
+ const meta = MANAGED_APP_META[id];
+ if (meta.artwork) {
+ // eslint-disable-next-line @next/next/no-img-element
+ return <img src={meta.artwork} alt="" aria-hidden className={`${className ?? "size-4"} object-contain`} draggable={false} />;
+ }
+ const Icon = meta.icon as LucideIcon;
+ return <Icon className={`${className ?? "size-4"} ${meta.tone ?? ""}`} />;
+}
+
+export const MANAGED_APP_ICONS: Record<ManagedAppId, React.ReactNode> = {
+ hermes: <AppMark id="hermes" />,
+ openclaw: <AppMark id="openclaw" />,
+ "9router": <AppMark id="9router" />,
+ orca: <AppMark id="orca" />,
+};
diff --git a/frontend/slices/managed-apps/app-support.ts b/frontend/slices/managed-apps/app-support.ts
index ef21ef0f..3ad2e96f 100644
--- a/frontend/slices/managed-apps/app-support.ts
+++ b/frontend/slices/managed-apps/app-support.ts
@@ -82,6 +82,19 @@ const SUPPORT: Record<ManagedAppId, AppSupport> = {
"Stops and removes the container. The image and ~/.9router data (providers, keys, stats) stay, so a reinstall comes back configured.",
stateDir: "~/.9router",
},
+ orca: {
+ dryRun: false,
+ rollbackPin: false,
+ pinLabel: "Version",
+ pinHint: "Orca update and rollback are not available yet; only the pinned 1.4.230 web runtime installs.",
+ pinPlaceholder: "",
+ installCommand: "bash scripts/managed-app-install orca install",
+ installNote:
+ "MSO verifies and installs the pinned Orca 1.4.230 web/Node release into ~/.local/share/mso/orca and starts the MSO-owned mso-orca.service user unit on loopback. It takes no provider key, and it requires a configured split app origin (NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE) so the browser can frame it — there is no same-origin fallback.",
+ uninstallCommand: "",
+ uninstallEffect: "Orca uninstall is not available yet.",
+ stateDir: "~/.local/share/mso/orca",
+ },
};
export const supportFor = (id: ManagedAppId): AppSupport => SUPPORT[id];
diff --git a/frontend/slices/managed-apps/app.tsx b/frontend/slices/managed-apps/app.tsx
index ce852430..937d585d 100644
--- a/frontend/slices/managed-apps/app.tsx
+++ b/frontend/slices/managed-apps/app.tsx
@@ -1,9 +1,10 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
-import { Bot, FileText, Loader2, Play, RefreshCw, Save, SlidersHorizontal, Square, Workflow, type LucideIcon } from "lucide-react";
+import { FileText, Loader2, Play, RefreshCw, Save, SlidersHorizontal, Square } from "lucide-react";
import { Button } from "@/components/ui/button";
import type { ManagedAppAction, ManagedAppId, ManagedAppView } from "@/lib/managed-apps/types";
+import { AppMark, MANAGED_APP_ICONS as ICON, MANAGED_APP_NAMES as NAME } from "./app-meta";
import { dashboardFeature } from "./feature-cli";
import { ManagedFeatureApp } from "./feature-app";
import { Hero, InstallSurface, UpdateCentrePanel } from "./update-panel";
@@ -83,31 +84,10 @@ export function NineRouterApp() {
return <ManagedAppsSurface focus="9router" />;
}
-const NAME: Record<ManagedAppId, string> = { hermes: "Hermes", openclaw: "OpenClaw", "9router": "9Router" };
-
-const MARK: Record<ManagedAppId, { Icon?: LucideIcon; tone?: string; artwork?: string }> = {
- hermes: { Icon: Bot, tone: "text-violet-400" },
- openclaw: { Icon: Workflow, tone: "text-orange-400" },
- "9router": { artwork: "/brand/official/9router.webp" },
-};
-
-function AppMark({ id, className }: { id: ManagedAppId; className?: string }) {
- const mark = MARK[id];
- if (mark.artwork) {
- // Official upstream artwork; keep it identical across every shell and Details card.
- // eslint-disable-next-line @next/next/no-img-element
- return <img src={mark.artwork} alt="" aria-hidden className={`${className ?? "size-4"} object-contain`} draggable={false} />;
- }
- const Icon = mark.Icon!;
- return <Icon className={`${className ?? "size-4"} ${mark.tone ?? ""}`} />;
+export function OrcaApp() {
+ return <ManagedAppsSurface focus="orca" />;
}
-const ICON: Record<ManagedAppId, React.ReactNode> = {
- hermes: <AppMark id="hermes" />,
- openclaw: <AppMark id="openclaw" />,
- "9router": <AppMark id="9router" />,
-};
-
/** ONE surface, and what it shows is the thing itself: the app's own dashboard when the
* app is there, and an install button when it is not. There used to be a
* `dashboard | manage` tab pair, which got both cases wrong — an absent app still mounted
diff --git a/frontend/slices/managed-apps/feature-app.tsx b/frontend/slices/managed-apps/feature-app.tsx
index 40d411c3..43d9e598 100644
--- a/frontend/slices/managed-apps/feature-app.tsx
+++ b/frontend/slices/managed-apps/feature-app.tsx
@@ -5,6 +5,7 @@ import { Suspense, useCallback, useEffect, useState } from "react";
import type { AppProps } from "@/features/appshell";
import { Terminal } from "@/features/os-terminal";
import type { ManagedAppFeature } from "@/lib/managed-apps/types";
+import { requestAuthorizedFrame, selectAuthorizedFrame } from "./app-authorization";
import { cliCommand, dashboardSurfaceSource, featureSource } from "./feature-cli";
export function ManagedFeatureApp({ feature, publicDashboardUrl }: AppProps & { feature: ManagedAppFeature; publicDashboardUrl?: string | null }) {
@@ -18,26 +19,24 @@ export function ManagedFeatureApp({ feature, publicDashboardUrl }: AppProps & {
// not iframe an http:// public IP inside an https:// cockpit (mixed content), and we
// never fall back to a same-origin vendor iframe.
const [generation, setGeneration] = useState(0);
- const [authorization, setAuthorization] = useState<{ source: string; url: string } | null>(null);
- const [authorizationError, setAuthorizationError] = useState(false);
+ // Result is keyed by generation so a refresh/remount invalidates the previous
+ // authorization by derivation — no synchronous setState in the effect, and a
+ // stale in-flight response can never re-mount the old frame.
+ const [authState, setAuthState] = useState<{ generation: number; auth: { source: string; url: string } | null; error: boolean }>({ generation: -1, auth: null, error: false });
const [view, setView] = useState<"ui" | "cli">(() => (uiAvailable ? "ui" : "cli"));
const reload = useCallback(() => setGeneration((value) => value + 1), []);
useEffect(() => {
if (surface.kind !== "embedded" || !embeddedSource) return;
const controller = new AbortController();
- void fetch(`/api/v1/managed-apps/${feature.applicationId}/session`, { cache: "no-store", signal: controller.signal }).then(async response => {
- if (!response.ok) throw new Error("authorization failed");
- const data = await response.json();
- const url = new URL(embeddedSource);
- if (url.origin !== data.origin || typeof data.ticket !== "string") throw new Error("authorization origin mismatch");
- const fragment = new URLSearchParams(url.hash.slice(1));
- fragment.set("app_ticket", data.ticket); url.hash = fragment.toString();
- setAuthorization({ source: embeddedSource, url: url.toString() }); setAuthorizationError(false);
- }).catch(() => { if (!controller.signal.aborted) setAuthorizationError(true); });
+ void requestAuthorizedFrame(feature.applicationId, embeddedSource, controller.signal)
+ .then((auth) => { if (!controller.signal.aborted) setAuthState({ generation, auth, error: false }); })
+ .catch(() => { if (!controller.signal.aborted) setAuthState({ generation, auth: null, error: true }); });
return () => controller.abort();
}, [embeddedSource, feature.applicationId, generation, surface.kind]);
- const authorizedSource = authorization?.source === embeddedSource ? authorization.url : null;
+ const current = embeddedSource ? selectAuthorizedFrame(authState, generation, embeddedSource) : { url: null, error: false };
+ const authorizedSource = current.url;
+ const authorizationError = current.error;
return (
<div className="flex h-full min-h-0 flex-col bg-background text-foreground">
diff --git a/frontend/slices/managed-apps/feature-cli.ts b/frontend/slices/managed-apps/feature-cli.ts
index 5ce5f6bb..2d0267ab 100644
--- a/frontend/slices/managed-apps/feature-cli.ts
+++ b/frontend/slices/managed-apps/feature-cli.ts
@@ -19,6 +19,7 @@ export function dashboardFeature(id: ManagedAppId, title: string): ManagedAppFea
export function cliCommand(feature: ManagedAppFeature): string {
if (feature.applicationId === "hermes") return "hermes";
if (feature.applicationId === "9router") return "docker logs --tail 80 9router";
+ if (feature.applicationId === "orca") return "journalctl --user -u mso-orca.service -n 80";
return `${feature.applicationId} status`;
}
diff --git a/frontend/slices/managed-apps/index.ts b/frontend/slices/managed-apps/index.ts
index bc0fc28f..346d0e73 100644
--- a/frontend/slices/managed-apps/index.ts
+++ b/frontend/slices/managed-apps/index.ts
@@ -1,40 +1,18 @@
-import { Bot, Workflow, type LucideIcon } from "lucide-react";
-import { createElement } from "react";
-import type { AppDescriptor, AppIconComponent } from "@/features/appshell";
+import type { AppDescriptor } from "@/features/appshell";
+import type { ManagedAppId } from "@/lib/managed-apps/types";
+import { MANAGED_APP_META } from "./app-meta";
-const NineRouterIcon: AppIconComponent = ({ className }) =>
- // Exact upstream 9Router artwork, copied from the managed Docker image. This file is
- // intentionally .ts (not .tsx), so use createElement rather than adding a JSX-only rename.
- createElement("img", {
- src: "/brand/official/9router.webp",
- alt: "",
- "aria-hidden": true,
- className: className ?? "size-full object-contain",
- draggable: false,
- });
-
-type ManagedApp = "hermes" | "openclaw" | "9router";
-
-const LOOK: Record<ManagedApp, { title: string; icon: LucideIcon | AppIconComponent; gradient: string; loader: string }> = {
- hermes: { title: "Hermes", icon: Bot, gradient: "linear-gradient(160deg,#8b5cf6,#4f46e5)", loader: "HermesApp" },
- openclaw: { title: "OpenClaw", icon: Workflow, gradient: "linear-gradient(160deg,#f97316,#dc2626)", loader: "OpenClawApp" },
- "9router": { title: "9Router", icon: NineRouterIcon, gradient: "linear-gradient(160deg,#0ea5e9,#2563eb)", loader: "NineRouterApp" },
-};
-
-// Ordinary apps, dock and all. They were `noDock` while MSO could swap its whole shell
-// into a Hermes/OpenClaw "workspace mode" that opened them by itself — that is gone: each
-// ships its own sidebar, so re-hosting its navigation bought nothing. One window per app.
-function managedDescriptor(app: ManagedApp): AppDescriptor {
- const look = LOOK[app];
+function managedDescriptor(app: ManagedAppId): AppDescriptor {
+ const meta = MANAGED_APP_META[app];
return {
id: app,
- title: look.title,
- icon: look.icon,
- gradient: look.gradient,
+ title: meta.title,
+ icon: meta.icon,
+ gradient: meta.gradient,
prefetch: "never",
load: async () => {
const loaded = await import("./app");
- return { default: loaded[look.loader as "HermesApp" | "OpenClawApp" | "NineRouterApp"] };
+ return { default: loaded[meta.loader] };
},
defaultSize: { w: 1100, h: 720 },
};
@@ -43,3 +21,4 @@ function managedDescriptor(app: ManagedApp): AppDescriptor {
export const hermesApp = managedDescriptor("hermes");
export const openclawApp = managedDescriptor("openclaw");
export const nineRouterApp = managedDescriptor("9router");
+export const orcaApp = managedDescriptor("orca");
diff --git a/frontend/slices/managed-apps/orca-app.test.tsx b/frontend/slices/managed-apps/orca-app.test.tsx
new file mode 100644
index 00000000..4ae593ef
--- /dev/null
+++ b/frontend/slices/managed-apps/orca-app.test.tsx
@@ -0,0 +1,117 @@
+import { describe, expect, it, vi } from "vitest";
+import { join } from "node:path";
+import { renderToStaticMarkup } from "react-dom/server";
+
+vi.mock("server-only", () => ({}));
+
+vi.hoisted(() => {
+ process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com";
+});
+
+import { MANAGED_APP_IDS } from "@/lib/managed-apps/types";
+import { getManagedAppDefinition, isManagedAppId, listManagedAppDefinitions } from "@/lib/managed-apps/catalog";
+import { BUILTIN_APPS } from "@/frontend/slices/os-shell/shell.manifest";
+import { parseAppCatalog } from "@/lib/contracts/app-catalog";
+import { appAllowedForRole } from "@/lib/auth/app-access";
+import { managedAppHost, managedAppOrigin, managedAppIdForHost } from "@/lib/managed-apps/origin";
+import { updateAdapter } from "@/lib/managed-apps/update-cli";
+import { managedAppInstallSupport } from "@/lib/managed-apps/host-compatibility";
+import { orcaApp } from "./index";
+import { OrcaApp } from "./app";
+
+describe("Orca checkpoint 1 identity and presentation", () => {
+ it("includes orca in typed MANAGED_APP_IDS and catalog SSOT", () => {
+ expect(MANAGED_APP_IDS).toContain("orca");
+ expect(isManagedAppId("orca")).toBe(true);
+ const defs = listManagedAppDefinitions();
+ const orcaDef = defs.find((d) => d.id === "orca");
+ expect(orcaDef).toBeDefined();
+ expect(orcaDef?.name).toBe("Orca");
+ expect(orcaDef?.command).toBe(join(process.cwd(), "scripts", "managed-app-orca"));
+ expect(orcaDef?.commandProvesInstall).toBe(false);
+ expect(orcaDef?.serviceNames).toEqual(["mso-orca.service"]);
+ expect(orcaDef?.containerNames).toEqual([]);
+ expect(orcaDef?.dashboardUrl).toMatch(/6769/);
+ expect(orcaDef?.healthPath).toBe("/web-index.html");
+ expect(orcaDef?.stateDirName).toBe("orca");
+ expect(orcaDef?.installBackends).toEqual(["user-systemd"]);
+ expect(getManagedAppDefinition("orca" as any)).toEqual(orcaDef);
+ });
+
+ it("registers Orca as a built-in shell application with /orca route", () => {
+ expect(orcaApp).toBeDefined();
+ expect(orcaApp.id).toBe("orca");
+ expect(orcaApp.title).toBe("Orca");
+ const shellEntry = BUILTIN_APPS.find((app) => app.id === "orca");
+ expect(shellEntry).toBeDefined();
+ expect(shellEntry?.slug).toBe("orca");
+ expect(shellEntry?.title).toBe("Orca");
+ });
+
+ it("accepts orca in app-catalog projection and rejects unknown apps", () => {
+ const raw = JSON.stringify({
+ schema: "urn:manef:app-catalog:v1",
+ schemaVersion: 1,
+ entries: [{ kind: "managed", id: "orca" }],
+ });
+ const parsed = parseAppCatalog(raw);
+ expect(parsed.entries).toEqual([{ kind: "managed", id: "orca" }]);
+
+ const unknownRaw = JSON.stringify({
+ schema: "urn:manef:app-catalog:v1",
+ schemaVersion: 1,
+ entries: [{ kind: "managed", id: "not-an-app" }],
+ });
+ expect(() => parseAppCatalog(unknownRaw)).toThrow("unknown managed adapter");
+ });
+
+ it("enforces role isolation: Viewer denied, Operator and Owner allowed", () => {
+ expect(appAllowedForRole("orca", "viewer")).toBe(false);
+ expect(appAllowedForRole("orca", "operator")).toBe(true);
+ expect(appAllowedForRole("orca", "owner")).toBe(true);
+ expect(appAllowedForRole("orca", null)).toBe(false);
+ });
+
+ it("isolates Orca origin under split-origin configuration", () => {
+ expect(managedAppHost("orca" as any)).toBe("orca.mso.example.com");
+ expect(managedAppOrigin("orca" as any)).toBe("https://orca.mso.example.com");
+ expect(managedAppIdForHost("orca.mso.example.com")).toBe("orca");
+ expect(managedAppIdForHost("unknown.mso.example.com")).toBeNull();
+ });
+
+ it("requires a proven x64 glibc host to install while update/uninstall stay unsupported", async () => {
+ const def = getManagedAppDefinition("orca" as any);
+
+ // The pinned release is linux-x64-glibc only: an unproven host fails closed
+ // with a specific reason instead of promising an install that cannot run.
+ const unproven = managedAppInstallSupport(def, { platform: "linux", userSystemd: true, docker: true });
+ expect(unproven.supported).toBe(false);
+ expect(unproven.reason).toMatch(/x64|glibc/i);
+
+ const proven = managedAppInstallSupport(def, {
+ platform: "linux",
+ arch: "x64",
+ glibc: true,
+ userSystemd: true,
+ docker: true,
+ });
+ expect(proven.supported).toBe(true);
+ expect(proven.backend).toBe("user-systemd");
+
+ const adapter = updateAdapter("orca" as any);
+ expect(adapter.capabilities.check).toBe(false);
+ expect(adapter.capabilities.apply).toBe(false);
+ expect(adapter.capabilities.uninstall).toBe(false);
+ expect(adapter.capabilities.rollback).toBe(false);
+ expect(() => adapter.updateArgv("orca-ide", {})).toThrow(/not supported for orca/);
+ expect(() => adapter.uninstallArgv("orca-ide", false)).toThrow(/not supported for orca/);
+ });
+
+ it("exports OrcaApp component and renders initial loading presentation", () => {
+ expect(typeof OrcaApp).toBe("function");
+ const html = renderToStaticMarkup(<OrcaApp />);
+ expect(html).toContain("Orca");
+ expect(html).toContain("Detecting Orca");
+ expect(html).toContain("Details");
+ });
+});
diff --git a/frontend/slices/managed-apps/orca-ui.test.tsx b/frontend/slices/managed-apps/orca-ui.test.tsx
new file mode 100644
index 00000000..2d38d542
--- /dev/null
+++ b/frontend/slices/managed-apps/orca-ui.test.tsx
@@ -0,0 +1,112 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.hoisted(() => {
+ process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com";
+});
+
+import { renderToStaticMarkup } from "react-dom/server";
+import { getManagedAppDefinition } from "@/lib/managed-apps/catalog";
+import { supportFor } from "./app-support";
+import { requestAuthorizedFrame, resolveAuthorizedFrame, selectAuthorizedFrame } from "./app-authorization";
+import { ManagedFeatureApp } from "./feature-app";
+import { OrcaApp } from "./app";
+
+const ORIGIN = "https://orca.mso.example.com";
+const WEB_CLIENT_URL = `${ORIGIN}/web-index.html#pairing=orca%3A%2F%2Fpair%3Fcode%3Dabc`;
+
+function okResponse(body: Record<string, unknown>): Response {
+ return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
+}
+
+describe("Orca UI state and installer availability", () => {
+ it("renders initial loading state while app detection is pending", () => {
+ const html = renderToStaticMarkup(<OrcaApp />);
+ expect(html).toContain("Orca");
+ expect(html).toContain("Detecting Orca");
+ });
+
+ it("exposes the real verified installer adapter while update/uninstall stay unsupported", () => {
+ const def = getManagedAppDefinition("orca");
+ expect(def.installBackends).toEqual(["user-systemd"]);
+ const support = supportFor("orca");
+ expect(support.installCommand).toContain("scripts/managed-app-install orca");
+ expect(support.installNote).toMatch(/mso-orca\.service/);
+ expect(support.stateDir).toBe("~/.local/share/mso/orca");
+ expect(support.uninstallCommand).toBe("");
+ expect(support.uninstallEffect).toMatch(/not available/i);
+ });
+});
+
+describe("managed-app authorization pipeline (real Response, real abort)", () => {
+ it("frames the canonical Orca web client with the app ticket in the fragment only", async () => {
+ const resolved = await resolveAuthorizedFrame(
+ okResponse({ origin: ORIGIN, ticket: "ticket_xyz123", pairingUrl: "orca://pair?code=abc", webClientUrl: WEB_CLIENT_URL, runtimeId: "rt_1234" }),
+ `${ORIGIN}/`,
+ "orca",
+ );
+ const parsed = new URL(resolved.url);
+ expect(parsed.origin).toBe(ORIGIN);
+ expect(parsed.pathname).toBe("/web-index.html");
+ expect(parsed.search).toBe("");
+ expect(parsed.hash).toContain("pairing=");
+ expect(parsed.hash).toContain("app_ticket=ticket_xyz123");
+ });
+
+ it("refuses an Orca web client that carries a query secret, wrong path, or unrelated origin", async () => {
+ await expect(resolveAuthorizedFrame(okResponse({ origin: ORIGIN, ticket: "t", webClientUrl: `${ORIGIN}/web-index.html?token=leak#pairing=x` }), `${ORIGIN}/`, "orca")).rejects.toThrow("authorization origin mismatch");
+ await expect(resolveAuthorizedFrame(okResponse({ origin: ORIGIN, ticket: "t", webClientUrl: `${ORIGIN}/other.html#pairing=x` }), `${ORIGIN}/`, "orca")).rejects.toThrow("authorization origin mismatch");
+ await expect(resolveAuthorizedFrame(okResponse({ origin: ORIGIN, ticket: "t", webClientUrl: "https://evil.example.com/web-index.html#pairing=x" }), `${ORIGIN}/`, "orca")).rejects.toThrow("authorization origin mismatch");
+ await expect(resolveAuthorizedFrame(okResponse({ origin: ORIGIN, ticket: "t" }), `${ORIGIN}/`, "orca")).rejects.toThrow("authorization origin mismatch");
+ });
+
+ it("never lets a non-Orca app navigate to a server-supplied web client URL", async () => {
+ const resolved = await resolveAuthorizedFrame(okResponse({ origin: "https://hermes.mso.example.com", ticket: "t" }), "https://hermes.mso.example.com/", "hermes");
+ expect(new URL(resolved.url).pathname).toBe("/");
+ await expect(
+ resolveAuthorizedFrame(okResponse({ origin: "https://hermes.mso.example.com", ticket: "t", webClientUrl: "https://hermes.mso.example.com/other" }), "https://hermes.mso.example.com/", "hermes"),
+ ).rejects.toThrow("authorization origin mismatch");
+ });
+
+ it("rejects 401 and mismatched-origin responses without producing a frame URL", async () => {
+ await expect(resolveAuthorizedFrame(new Response(JSON.stringify({ error: "unauthorized" }), { status: 401 }), `${ORIGIN}/`, "orca")).rejects.toThrow("authorization failed");
+ await expect(resolveAuthorizedFrame(okResponse({ origin: "https://evil.example.com", ticket: "t", webClientUrl: WEB_CLIENT_URL }), `${ORIGIN}/`, "orca")).rejects.toThrow("authorization origin mismatch");
+ });
+
+ it("aborts a stale in-flight authorization request so it cannot mount an old frame", async () => {
+ vi.stubGlobal("fetch", vi.fn((_url: string, init?: RequestInit) => new Promise((_resolve, reject) => {
+ const signal = init?.signal as AbortSignal;
+ signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")));
+ })));
+ const controller = new AbortController();
+ const pending = requestAuthorizedFrame("orca", `${ORIGIN}/`, controller.signal);
+ controller.abort();
+ await expect(pending).rejects.toMatchObject({ name: "AbortError" });
+ vi.unstubAllGlobals();
+ });
+
+ it("ignores a result stamped with an older generation after a refresh", () => {
+ const frame = { source: `${ORIGIN}/`, url: `${WEB_CLIENT_URL}&app_ticket=old` };
+ const stale = { generation: 0, auth: frame, error: false };
+ expect(selectAuthorizedFrame(stale, 1, `${ORIGIN}/`)).toEqual({ url: null, error: false });
+ expect(selectAuthorizedFrame({ generation: 1, auth: frame, error: false }, 1, `${ORIGIN}/`)).toEqual({ url: frame.url, error: false });
+ expect(selectAuthorizedFrame({ generation: 1, auth: null, error: true }, 1, `${ORIGIN}/`)).toEqual({ url: null, error: true });
+ });
+});
+
+describe("Orca frame surface safety (SSR branches)", () => {
+ it("shows no iframe and leaks no token before authorization completes", () => {
+ const html = renderToStaticMarkup(
+ <ManagedFeatureApp
+ feature={{ id: "orca:overview", applicationId: "orca", title: "Orca", route: "/", source: "nav-bundle", available: true }}
+ />,
+ );
+ expect(html).not.toContain("<iframe");
+ expect(html).not.toContain("pairing");
+ expect(html).not.toContain("ticket");
+ expect(html).toContain("Authorizing application");
+ });
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
diff --git a/frontend/slices/os-shell/shell.manifest.ts b/frontend/slices/os-shell/shell.manifest.ts
index 087c056a..b9642288 100644
--- a/frontend/slices/os-shell/shell.manifest.ts
+++ b/frontend/slices/os-shell/shell.manifest.ts
@@ -16,7 +16,7 @@ import { appStoreApp } from "@/features/app-store";
import { createAppApp } from "@/features/create-app";
import { systemMonitorApp } from "@/features/system-monitor";
import { assistantApp } from "@/features/assistant";
-import { hermesApp, nineRouterApp, openclawApp } from "@/features/managed-apps";
+import { hermesApp, nineRouterApp, openclawApp, orcaApp } from "@/features/managed-apps";
import { osSettingsApp, updateShellBadgeFeature } from "@/features/os-settings";
import { quicklinksApp } from "@/features/quicklinks";
import { docsApp } from "@/features/docs";
@@ -90,6 +90,7 @@ export const BUILTIN_APPS: AppDescriptor[] = [
withSlug(withArtwork(agentGroupApp), "agent-groups"),
withSlug(withArtwork(quicklinksApp), "links"),
withSlug(withArtwork(createAppApp), "create"),
+ withSlug(withArtwork(orcaApp), "orca"),
];
// Shell features — the generic brand-free set now lives INSIDE the appshell
diff --git a/lib/agent/session-turn.test.ts b/lib/agent/session-turn.test.ts
index 74e19cbf..b3375fae 100644
--- a/lib/agent/session-turn.test.ts
+++ b/lib/agent/session-turn.test.ts
@@ -125,7 +125,14 @@ describe("durable session turn runner", () => {
const turn1Pending = new Promise((resolve) => {
resolveTurn1 = resolve;
});
- mockHandoff.mockImplementationOnce(() => turn1Pending);
+ let signalHandoffEntered!: () => void;
+ const handoffEntered = new Promise<void>((resolve) => {
+ signalHandoffEntered = resolve;
+ });
+ mockHandoff.mockImplementationOnce(() => {
+ signalHandoffEntered();
+ return turn1Pending;
+ });
const turn1Promise = runDurableSessionTurn({
principal: "principal:alice",
@@ -134,19 +141,32 @@ describe("durable session turn runner", () => {
capabilities,
});
- const turn2Promise = runDurableSessionTurn({
- principal: "principal:alice",
- sessionRef: session.id,
- objective: "turn 2 objective",
- capabilities,
- });
-
- await expect(turn2Promise).rejects.toThrow(/already in progress/);
+ // Deterministic: the handoff is the only point after `acquireSessionTurnLease`,
+ // so waiting for turn 1 to ENTER it proves turn 1 holds the lease before the
+ // contender starts. Without this barrier the two turns race after their
+ // `resolveAgentSessionRef` awaits and the contender can win instead — leaving
+ // turn 2 pending and turn 1's rejection unhandled.
+ await handoffEntered;
+
+ try {
+ await expect(
+ runDurableSessionTurn({
+ principal: "principal:alice",
+ sessionRef: session.id,
+ objective: "turn 2 objective",
+ capabilities,
+ }),
+ ).rejects.toThrow(/already in progress/);
+ } finally {
+ // Release turn 1 even if the rejection assertion above fails, so its pending
+ // turn (and any unhandled rejection it would otherwise strand) is not left
+ // behind for the next test.
+ resolveTurn1({
+ session,
+ task: { artifacts: [{ parts: [{ text: "turn 1 result" }] }] },
+ });
+ }
- resolveTurn1({
- session,
- task: { artifacts: [{ parts: [{ text: "turn 1 result" }] }] },
- });
const turn1Result = await turn1Promise;
expect(turn1Result.text).toBe("turn 1 result");
diff --git a/lib/auth/app-access.test.ts b/lib/auth/app-access.test.ts
index 95b3445a..4a86c504 100644
--- a/lib/auth/app-access.test.ts
+++ b/lib/auth/app-access.test.ts
@@ -6,13 +6,13 @@ describe("role-aware app catalog", () => {
for (const id of ["files-manager", "system-monitor", "media-viewer", "quicklinks", "docs", "os-settings"]) {
expect(appAllowedForRole(id, "viewer"), id).toBe(true);
}
- for (const id of ["os-terminal", "code-editor", "assistant", "hermes", "camoufox-browser"]) {
+ for (const id of ["os-terminal", "code-editor", "assistant", "hermes", "camoufox-browser", "orca"]) {
expect(appAllowedForRole(id, "viewer"), id).toBe(false);
}
});
it("adds only bounded operational apps for Operator", () => {
- for (const id of ["camoufox-browser", "hermes", "openclaw", "9router"]) {
+ for (const id of ["camoufox-browser", "hermes", "openclaw", "9router", "orca"]) {
expect(appAllowedForRole(id, "operator"), id).toBe(true);
}
for (const id of ["os-terminal", "code-editor", "assistant", "app-store", "create-app"]) {
diff --git a/lib/auth/app-access.ts b/lib/auth/app-access.ts
index d4706dc8..3b1e3a79 100644
--- a/lib/auth/app-access.ts
+++ b/lib/auth/app-access.ts
@@ -14,6 +14,7 @@ const OPERATOR_APPS = new Set([
"hermes",
"openclaw",
"9router",
+ "orca",
]);
/** Unknown/runtime apps fail closed for delegated devices until explicitly classified. */
diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.ts
index 484ee92e..56388e47 100644
--- a/lib/config/env-example.test.ts
+++ b/lib/config/env-example.test.ts
@@ -45,6 +45,24 @@ const NOT_A_KNOB: Record<string, string> = {
// systemd's, read by instrumentation for the watchdog handshake.
NOTIFY_SOCKET: "systemd's",
WATCHDOG_USEC: "systemd's",
+ // Orca lifecycle test fixtures. scripts/orca/fixtures/*.mjs are disposable
+ // stand-ins for the real server, daemon, and CLI; these select fake behavior.
+ FAKE_ADVERTISED: "Orca test fixture only: fake server's advertised pairing endpoint",
+ FAKE_CLI_LOG: "Orca test fixture only: fixture CLI invocation log path",
+ FAKE_CLI_MODE: "Orca test fixture only: fixture CLI behavior selector",
+ FAKE_CLI_TOKEN: "Orca test fixture only: fixture CLI echo token",
+ FAKE_CRASH_DELAY_MS: "Orca test fixture only: fake server's delayed-crash timing",
+ FAKE_DAEMON_DELAY_MS: "Orca test fixture only: fake daemon's pid-record delay",
+ FAKE_DAEMON_ENTRY: "Orca test fixture only: fake server's daemon entry path",
+ FAKE_MODE: "Orca test fixture only: fake server scenario selector",
+ FAKE_READY_DELAY_MS: "Orca test fixture only: fake server's delay before readiness output",
+ // Private installer handoff. lib/managed-apps/install.ts derives these from
+ // operator-facing install options and passes them to the install scripts.
+ MSO_INSTALL_APP_ORIGIN: "private MSO installer-to-app handoff for the configured split app origin; not an operator knob",
+ MSO_INSTALL_GATEWAY_BIND: "private MSO installer-to-app handoff for the validated gateway bind mode; not an operator knob",
+ // Private Orca runtime environment. scripts/orca/env.mjs writes this into the
+ // isolated child env so the runtime uses the scratch user-data directory.
+ ORCA_USER_DATA: "private isolated Orca runtime env set by scripts/orca/env.mjs; not a deployment knob",
// Test + tooling only, never part of a deployment.
E2E_BASE_URL: "test harness",
MSO_SCREENSHOT_DIR: "injected per-session artifact staging path for browser tooling; never persistent app configuration",
diff --git a/lib/host/delegated-write.test.ts b/lib/host/delegated-write.test.ts
index 577eb255..8bb14d92 100644
--- a/lib/host/delegated-write.test.ts
+++ b/lib/host/delegated-write.test.ts
@@ -17,7 +17,10 @@ describe("delegated write control-plane guard", () => {
await expect(assertDelegatedWritePath(path.join(os.homedir(), ".config/systemd/user/evil.service"))).rejects.toThrow(/control-plane/);
});
it("allows ordinary project content", async () => {
- await expect(assertDelegatedWritePath(path.join(os.tmpdir(), "project", "src", "index.ts"))).resolves.toBeUndefined();
+ // Positive fixture: a prospective path in the real projects root, never created.
+ // os.tmpdir() is not portable here — under Hermes it lives inside ~/.hermes,
+ // which is a protected control-plane input, so that path belongs to the negative cases.
+ await expect(assertDelegatedWritePath(path.join(os.homedir(), "projects", "mso-delegated-write-fixture", "src", "index.ts"))).resolves.toBeUndefined();
});
it("blocks CLI launchers used by managed-app probes", async () => {
for (const dir of [".local/bin", ".bun/bin", ".hermes", ".openclaw"]) {
diff --git a/lib/managed-apps/catalog.test.ts b/lib/managed-apps/catalog.test.ts
index 4a9978de..3930473e 100644
--- a/lib/managed-apps/catalog.test.ts
+++ b/lib/managed-apps/catalog.test.ts
@@ -1,19 +1,21 @@
import { readFileSync } from "node:fs";
+import path from "node:path";
import { describe, expect, it } from "vitest";
import { getManagedAppDefinition, isManagedAppId, listManagedAppDefinitions } from "./catalog";
import { MANAGED_APP_ACTIONS } from "./types";
describe("managed app catalog", () => {
- it("uses one shared catalog for exactly Hermes, OpenClaw and 9Router", () => {
+ it("uses one shared catalog for Hermes, OpenClaw, 9Router and Orca", () => {
const definitions = listManagedAppDefinitions();
- expect(definitions.map((item) => item.id)).toEqual(["hermes", "openclaw", "9router"]);
- expect(new Set(definitions.map((item) => item.id)).size).toBe(3);
+ expect(definitions.map((item) => item.id)).toEqual(["hermes", "openclaw", "9router", "orca"]);
+ expect(new Set(definitions.map((item) => item.id)).size).toBe(4);
});
it("rejects arbitrary application ids and commands", () => {
expect(isManagedAppId("hermes")).toBe(true);
expect(isManagedAppId("openclaw")).toBe(true);
expect(isManagedAppId("9router")).toBe(true);
+ expect(isManagedAppId("orca")).toBe(true);
expect(isManagedAppId("hermes;rm -rf /")).toBe(false);
expect(MANAGED_APP_ACTIONS).toEqual(["start", "stop", "restart", "backup"]);
});
@@ -38,4 +40,16 @@ describe("managed app catalog", () => {
expect(getManagedAppDefinition("9router").publicPort).toBeUndefined();
});
+ it("wires Orca to the repo-owned adapter and the systemd user backend", () => {
+ const orca = getManagedAppDefinition("orca");
+ // The reviewed adapter ships in this repo, so its presence must not count as
+ // an install; the exact unit + a verified receipt do.
+ expect(orca.installBackends).toEqual(["user-systemd"]);
+ expect(orca.command).toBe(path.join(process.cwd(), "scripts", "managed-app-orca"));
+ expect(orca.commandProvesInstall).toBe(false);
+ expect(orca.serviceNames).toEqual(["mso-orca.service"]);
+ // The managed root is MSO-owned state, never the operator's personal ~/.orca.
+ expect(orca.homeDir).toMatch(/mso[/\\]orca$/);
+ });
+
});
diff --git a/lib/managed-apps/catalog.ts b/lib/managed-apps/catalog.ts
index 8ad901c9..29ea13ab 100644
--- a/lib/managed-apps/catalog.ts
+++ b/lib/managed-apps/catalog.ts
@@ -1,5 +1,5 @@
import { homedir } from "node:os";
-import { join } from "node:path";
+import { isAbsolute, join, normalize, sep } from "node:path";
import { MANAGED_APP_IDS, type ManagedAppDefinition, type ManagedAppId } from "./types";
/** Env overrides are hand-written, so a leading `~` is expected — `join()` alone would
@@ -10,6 +10,20 @@ export function expandHome(value: string | undefined): string {
return value.startsWith("~/") ? join(homedir(), value.slice(2)) : value;
}
+/** Orca's managed root is MSO-owned state (`~/.local/share/mso/orca`), never the
+ * operator's personal `~/.orca`. Mirrors the bridge (`orca-private-fs.ts`) so
+ * backup/restore reads the same directory the runtime writes; an invalid
+ * ORCA_HOME override falls back to the portable default here, while the bridge
+ * itself fails closed on it. */
+function orcaManagedRoot(): string {
+ const fallback = join(homedir(), ".local", "share", "mso", "orca");
+ const raw = process.env.ORCA_HOME;
+ if (!raw || raw.trim() === "" || raw.includes("\0") || !isAbsolute(raw)) return fallback;
+ const normalized = normalize(raw);
+ if (normalized !== raw || normalized.split(sep).includes("..")) return fallback;
+ return normalized;
+}
+
const definitions = {
hermes: {
id: "hermes",
@@ -69,6 +83,25 @@ const definitions = {
stateDirName: ".9router",
gradient: "linear-gradient(160deg,#0ea5e9,#2563eb)",
},
+ orca: {
+ id: "orca",
+ // Orca is installed as the MSO-owned `mso-orca.service` user unit from the
+ // pinned web/Node release (linux x64 glibc). It is not a Docker app.
+ installBackends: ["user-systemd"],
+ name: "Orca",
+ description: "Orca web workspace and coding environment",
+ // The lifecycle/update adapter ships in THIS repo, so its presence proves
+ // nothing; only the exact unit plus a verified install receipt count.
+ command: join(process.cwd(), "scripts", "managed-app-orca"),
+ commandProvesInstall: false,
+ serviceNames: ["mso-orca.service"],
+ containerNames: [],
+ dashboardUrl: process.env.ORCA_DASHBOARD_URL ?? "http://127.0.0.1:6769",
+ healthPath: "/web-index.html",
+ stateDirName: "orca",
+ homeDir: orcaManagedRoot(),
+ gradient: "linear-gradient(160deg,#0284c7,#1e3a8a)",
+ },
} as const satisfies Record<ManagedAppId, ManagedAppDefinition>;
export function isManagedAppId(value: string): value is ManagedAppId {
diff --git a/lib/managed-apps/health.ts b/lib/managed-apps/health.ts
index 6dd23ecd..c4e79183 100644
--- a/lib/managed-apps/health.ts
+++ b/lib/managed-apps/health.ts
@@ -1,7 +1,26 @@
import { managedAppUpstream } from "./upstream-target";
import type { ManagedAppDefinition } from "./types";
+/** A static 200 on the web bundle proves reachability, not ownership. Orca's
+ * health is the bridge's fail-closed live reading: the exact readiness tag, the
+ * runtime-identity receipt, and the verified owned kernel process must agree.
+ *
+ * The bridge is server-only (it reads the private store and `/proc`). It is
+ * loaded on demand rather than at module top level so the shared domain CLI
+ * (`mso domain status`/`help`) does not pull the Next-only `server-only` marker
+ * into its Bun/Node import graph. Where the bridge cannot load in that runtime,
+ * health fails closed as `null` instead of crashing. */
+async function orcaHealth(): Promise<boolean | null> {
+ try {
+ const { getOrcaReadiness } = await import("./orca-readiness");
+ return (await getOrcaReadiness()).available;
+ } catch {
+ return null;
+ }
+}
+
export async function managedAppHealth(definition: ManagedAppDefinition): Promise<boolean | null> {
+ if (definition.id === "orca") return orcaHealth();
try {
const base = managedAppUpstream(definition.dashboardUrl);
const target = new URL(definition.healthPath ?? "/health", base);
diff --git a/lib/managed-apps/host-compatibility.test.ts b/lib/managed-apps/host-compatibility.test.ts
index 9dfa7aed..5672497e 100644
--- a/lib/managed-apps/host-compatibility.test.ts
+++ b/lib/managed-apps/host-compatibility.test.ts
@@ -4,22 +4,34 @@ import { managedAppInstallSupport } from "./host-compatibility";
describe("managed app install compatibility", () => {
const host = (userSystemd: boolean, docker: boolean) =>
- ({ platform: "linux" as const, userSystemd, docker });
+ ({ platform: "linux" as const, arch: "x64", glibc: true, userSystemd, docker });
it("selects only reviewed backends supported by the current Linux host", () => {
expect(managedAppInstallSupport(getManagedAppDefinition("hermes"), host(false, true)).backend).toBe("docker");
expect(managedAppInstallSupport(getManagedAppDefinition("openclaw"), host(true, true)).backend).toBe("user-systemd");
expect(managedAppInstallSupport(getManagedAppDefinition("9router"), host(true, true)).backend).toBe("docker");
+ expect(managedAppInstallSupport(getManagedAppDefinition("orca"), host(true, true)).backend).toBe("user-systemd");
});
it("blocks app combinations without the required backend before installing", () => {
- for (const id of ["hermes", "openclaw", "9router"] as const) {
+ for (const id of ["hermes", "openclaw", "9router", "orca"] as const) {
const result = managedAppInstallSupport(getManagedAppDefinition(id), host(false, false));
expect(result.supported).toBe(false);
expect(result.reason).toMatch(/requires/);
}
expect(managedAppInstallSupport(getManagedAppDefinition("openclaw"), host(false, true)).supported).toBe(false);
expect(managedAppInstallSupport(getManagedAppDefinition("9router"), host(true, false)).supported).toBe(false);
+ expect(managedAppInstallSupport(getManagedAppDefinition("orca"), host(false, false)).supported).toBe(false);
+ });
+
+ it("requires a linux x64 glibc host for Orca's pinned release", () => {
+ const orca = getManagedAppDefinition("orca");
+ // Only x64 glibc has a reviewed build; a musl or non-x64 host must fail closed.
+ expect(managedAppInstallSupport(orca, { platform: "linux", arch: "arm64", glibc: true, userSystemd: true, docker: false })).toMatchObject({
+ supported: false, backend: null,
+ });
+ expect(managedAppInstallSupport(orca, { platform: "linux", arch: "x64", glibc: false, userSystemd: true, docker: false }).reason).toMatch(/x64 glibc/);
+ expect(managedAppInstallSupport(orca, { platform: "linux", arch: "x64", glibc: true, userSystemd: true, docker: false }).supported).toBe(true);
});
it("requires a Linux runtime even when a daemon is reported by the host", () => {
diff --git a/lib/managed-apps/host-compatibility.ts b/lib/managed-apps/host-compatibility.ts
index da2d61d2..ea58ba38 100644
--- a/lib/managed-apps/host-compatibility.ts
+++ b/lib/managed-apps/host-compatibility.ts
@@ -4,6 +4,10 @@ export type ManagedAppHostCapabilities = {
platform: NodeJS.Platform;
userSystemd: boolean;
docker: boolean;
+ /** CPU architecture. Only Orca's pinned release is arch-specific today. */
+ arch?: string;
+ /** True only when a glibc runtime is proven; Orca has no musl build. */
+ glibc?: boolean;
};
export type ManagedAppInstallSupport = {
@@ -20,10 +24,22 @@ export function managedAppInstallSupport(
if (host.platform !== "linux") {
return { supported: false, backend: null, reason: "Managed app installers require a Linux runtime on this host." };
}
+ // Orca's pinned release is linux-x64-glibc only. Fail closed when the arch is
+ // unknown or a musl host, rather than starting an install that cannot run.
+ if (definition.id === "orca" && (host.arch !== "x64" || host.glibc !== true)) {
+ return {
+ supported: false,
+ backend: null,
+ reason: "Orca requires a Linux x64 glibc host; the pinned release has no other build.",
+ };
+ }
for (const backend of definition.installBackends) {
if (backend === "user-systemd" && host.userSystemd) return { supported: true, backend, reason: null };
if (backend === "docker" && host.docker) return { supported: true, backend, reason: null };
}
+ if (definition.installBackends.length === 0) {
+ return { supported: false, backend: null, reason: `${definition.name} installer is not available yet.` };
+ }
const required = definition.installBackends.includes("user-systemd")
? definition.installBackends.includes("docker") ? "a working user systemd bus or Docker daemon" : "a working user systemd bus"
: "a working Docker daemon";
diff --git a/lib/managed-apps/install-orca.test.ts b/lib/managed-apps/install-orca.test.ts
new file mode 100644
index 00000000..c37500a3
--- /dev/null
+++ b/lib/managed-apps/install-orca.test.ts
@@ -0,0 +1,100 @@
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// Single-origin by default; split-origin tests reset modules and stub the
+// template explicitly, exactly like install.test.ts.
+vi.hoisted(() => {
+ process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "";
+});
+
+vi.mock("server-only", () => ({}));
+vi.mock("./manager", () => ({ getManagedApp: vi.fn() }));
+vi.mock("./jobs", () => ({ startManagedAppJob: vi.fn() }));
+vi.mock("./docker", () => ({ dockerUsable: vi.fn() }));
+vi.mock("./user-bus", () => ({ userBusUnavailable: vi.fn() }));
+import { startManagedAppJob } from "./jobs";
+import { getManagedApp } from "./manager";
+import { dockerUsable } from "./docker";
+import { userBusUnavailable } from "./user-bus";
+import { startInstall } from "./install";
+import type { ManagedAppView } from "./types";
+
+const mockStart = vi.mocked(startManagedAppJob);
+const mockGet = vi.mocked(getManagedApp);
+
+const view = (installed: boolean): ManagedAppView =>
+ ({
+ id: "orca",
+ name: "Orca",
+ description: "",
+ installed,
+ installationType: installed ? "systemd" : "not-installed",
+ state: installed ? "running" : "not-installed",
+ healthy: null,
+ version: null,
+ dashboardAvailable: false,
+ publicDashboardUrl: null,
+ diagnostic: null,
+ supportedActions: [],
+ }) as ManagedAppView;
+
+const started = () => mockStart.mock.calls[0]![0];
+
+beforeEach(() => {
+ mockStart.mockReset();
+ mockGet.mockReset();
+ mockStart.mockResolvedValue({} as never);
+ mockGet.mockResolvedValue(view(false));
+ vi.mocked(dockerUsable).mockResolvedValue(true);
+ vi.mocked(userBusUnavailable).mockReturnValue(false);
+});
+
+describe("Orca install uses the reviewed adapter, never a raw key", () => {
+ it("refuses to install without a configured split origin", async () => {
+ await expect(startInstall("orca")).rejects.toThrow(/split app origin/);
+ expect(mockStart).not.toHaveBeenCalled();
+ });
+
+ it("refuses a provider key, which Orca cannot store or use", async () => {
+ await expect(startInstall("orca", { provider: "anthropic", apiKey: "sk-ant-x" })).rejects.toThrow(/does not accept a provider/);
+ expect(mockStart).not.toHaveBeenCalled();
+ });
+
+ it("refuses a non-loopback bind even though siblings allow it", async () => {
+ await expect(startInstall("orca", { bind: "lan" })).rejects.toThrow(/loopback only/);
+ expect(mockStart).not.toHaveBeenCalled();
+ });
+
+ it("dispatches the repo script with the configured origin and no secret", async () => {
+ vi.resetModules();
+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", "{id}.mso.example.com");
+ const fresh = await import("./install");
+ await fresh.startInstall("orca");
+ const { argv, env, kind, applicationId } = started();
+ expect(kind).toBe("install");
+ expect(applicationId).toBe("orca");
+ expect(argv).toEqual([expect.stringMatching(/scripts\/managed-app-install$/), "orca"]);
+ expect(env?.MSO_INSTALL_GATEWAY_BIND).toBe("loopback");
+ expect(env?.MSO_INSTALL_APP_ORIGIN).toBe("https://orca.mso.example.com");
+ expect(env).not.toHaveProperty("MSO_INSTALL_API_KEY");
+ expect(env).not.toHaveProperty("MSO_INSTALL_PROVIDER");
+ vi.unstubAllEnvs();
+ });
+});
+
+describe("the install script routes Orca to the reviewed adapter", () => {
+ const script = readFileSync(path.join(process.cwd(), "scripts", "managed-app-install"), "utf8");
+
+ it("dispatches orca before the linger preflight that would change access", () => {
+ // Orca's adapter performs its own user-bus check and must NOT ride the
+ // Hermes/OpenClaw preflight, which calls `loginctl enable-linger` (an access
+ // change) and would send Orca through a caller it does not need.
+ const dispatch = script.indexOf('if [ "$APP" = "orca" ]');
+ const linger = script.indexOf('loginctl enable-linger "');
+ expect(dispatch).toBeGreaterThan(-1);
+ expect(linger).toBeGreaterThan(-1);
+ expect(dispatch).toBeLessThan(linger);
+ expect(script.slice(dispatch, linger)).toContain("managed-app-orca");
+ });
+});
diff --git a/lib/managed-apps/install.ts b/lib/managed-apps/install.ts
index c087af17..fa7612d3 100644
--- a/lib/managed-apps/install.ts
+++ b/lib/managed-apps/install.ts
@@ -31,7 +31,7 @@ const INSTALL_SCRIPT = path.join(process.cwd(), "scripts", "managed-app-install"
/** Hermes fetches uv, a Python, Node and ffmpeg before it does anything of its
* own, so it needs a budget several times OpenClaw's `npm i -g`. Both stay
* under the job layer's 1 h ceiling. */
-const INSTALL_TIMEOUT_MS: Record<ManagedAppId, number> = { hermes: 2_700_000, openclaw: 900_000, "9router": 900_000 };
+const INSTALL_TIMEOUT_MS: Record<ManagedAppId, number> = { hermes: 2_700_000, openclaw: 900_000, "9router": 900_000, orca: 900_000 };
/** A key is never inspected beyond this: it is opaque upstream credential
* material, so the only questions worth asking are "could it break the
@@ -53,6 +53,17 @@ export interface InstallOptions {
const BINDS = new Set(["loopback", "lan", "tailnet", "auto"]);
+/** Orca's pinned release is linux-x64-glibc only, so the support gate must prove
+ * glibc rather than assume it. `process.report` is Node's own reading. */
+function hostUsesGlibc(): boolean {
+ try {
+ const report = process.report?.getReport() as { header?: { glibcVersionRuntime?: string } } | undefined;
+ return typeof report?.header?.glibcVersionRuntime === "string";
+ } catch {
+ return false;
+ }
+}
+
/** Start an install job. Refuses when the app is already installed: the upstream
* installers are re-runnable, but "install" arriving at a live app is a UI bug
* or a stale page, and re-running one restarts services under whoever is using
@@ -63,6 +74,8 @@ export async function startInstall(id: ManagedAppId, options: InstallOptions = {
if (view.installed) throw new Error(`${definition.name} is already installed — use Update instead`);
const support = managedAppInstallSupport(definition, {
platform: process.platform,
+ arch: process.arch,
+ glibc: hostUsesGlibc(),
userSystemd: !userBusUnavailable(),
docker: definition.installBackends.includes("docker") && await dockerUsable(),
});
@@ -81,16 +94,28 @@ export async function startInstall(id: ManagedAppId, options: InstallOptions = {
const env: Record<string, string> = {};
const bind = options.bind ?? "loopback";
if (!BINDS.has(bind)) throw new Error("unsupported gateway bind mode");
+ // Orca's browser client is only ever framed through the split-origin proxy, so
+ // a non-loopback bind would expose the runtime directly. Refuse it explicitly
+ // even though sibling installers accept LAN/tailnet binds.
+ if (id === "orca" && bind !== "loopback") throw new Error("Orca install supports loopback only; refusing a non-loopback bind");
env.MSO_INSTALL_GATEWAY_BIND = bind;
+ const key = options.apiKey?.trim();
+ // Orca ships no provider configuration and stores no API key; a key would only
+ // be silently dropped, so refuse rather than claim a configured install.
+ if (id === "orca" && (key || options.provider)) throw new Error("Orca does not accept a provider or API key");
+
// Where MSO will frame this app. OpenClaw's Control UI keeps its own origin
// allowlist and rejects the socket before it opens otherwise — a healthy gateway
- // that the dashboard cannot talk to. Absent in single-origin deployments, where
- // the frame is same-origin with the cockpit and there is nothing to allow.
+ // that the dashboard cannot talk to. Orca needs the same origin: the managed
+ // runtime advertises exactly this WSS endpoint, and there is NO same-origin
+ // fallback, so an install without it cannot produce a usable browser session.
const appOrigin = managedAppOrigin(id);
+ if (id === "orca" && !appOrigin) {
+ throw new Error("Orca install requires a configured split app origin (NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE); refusing to install a runtime the browser cannot reach");
+ }
if (appOrigin) env.MSO_INSTALL_APP_ORIGIN = appOrigin;
- const key = options.apiKey?.trim();
if (key) {
const provider = findProvider(options.provider);
if (!provider) throw new Error("unsupported provider");
diff --git a/lib/managed-apps/manager.ts b/lib/managed-apps/manager.ts
index 9c2d3393..39ff0983 100644
--- a/lib/managed-apps/manager.ts
+++ b/lib/managed-apps/manager.ts
@@ -8,40 +8,25 @@ import { provisionDomainAfterStart, readManagedDomainView } from "./domain-lifec
import { acquireOperation, activeOperation, releaseOperation, withManagedAppOperationLease } from "./lock";
import { redact } from "./redact";
import { listJobRecords } from "./job-store";
+import { detectOrca, detectOwnedOrcaForStop, invalidateOrcaIntegrityCache, orcaUnknownDiagnostic, ORCA_SERVICE, type ManagedInstallation } from "./orca-installation";
import { commandExists, resolveCommand, runProgram } from "./runner";
+import { managedRunState, running, systemdState } from "./service-state";
import { userBusEnv, userBusUnavailable } from "./user-bus";
import type { ManagedAppAction, ManagedAppDefinition, ManagedAppId, ManagedAppLogs, ManagedAppView } from "./types";
-interface Installation {
- type: "systemd" | "docker" | "package" | "not-installed";
- serviceName?: string; serviceNames?: string[];
- containerName?: string; containerNames?: string[];
-}
-
-// `is-active` cannot tell "this unit is stopped" from "this unit does not exist":
-// `show -p LoadState` distinguishes absent units from installed stopped units.
-async function systemdState(service: string, strict = false): Promise<"active" | "inactive" | "missing"> {
- let present = false;
- for (const scope of [["--user"], []]) {
- // The user scope needs a bus address. mso.service is a SYSTEM unit with
- // `User=`, which inherits no login session and therefore no
- // XDG_RUNTIME_DIR, so without this every `--user` probe below answered
- // "Failed to connect to bus: No medium found" and the whole scope was
- // silently skipped — the app then looked absent no matter what was running.
- const env = scope.length ? userBusEnv() : undefined;
- const result = await runProgram("systemctl", [...scope, "show", "-p", "LoadState", "-p", "ActiveState", service], 10_000, env);
- // Non-zero here is no systemctl at all, or no user bus — not an answer about
- // the unit, so try the next scope rather than concluding anything.
- if (result.code !== 0) { if (strict) throw new Error("Cannot confirm all managed-app service states"); continue; }
- const load = /LoadState=(\S+)/.exec(result.stdout)?.[1];
- if (!load || load === "not-found") continue;
- present = true;
- if (/ActiveState=(?:active|activating|deactivating|reloading)\b/.test(result.stdout)) return "active";
+async function detect(definition: ManagedAppDefinition, strict = false): Promise<ManagedInstallation> {
+ // Orca is MSO-owned state: only the exact owned USER unit plus a verified
+ // install receipt counts, in a single scope. The generic path below cannot
+ // prove either, so it must never run for Orca.
+ // Strict check must fail closed when Orca is not installed or has ambiguous/stale state,
+ // as absence cannot be proven without an owned stopped unit.
+ if (definition.id === "orca") {
+ const result = await detectOrca({ adapterPath: definition.command, freshVerification: strict });
+ if (strict && result.type === "not-installed") {
+ throw new Error(result.diagnostic ?? "Cannot confirm Orca is stopped: install state cannot prove absence");
+ }
+ return result;
}
- return present ? "inactive" : "missing";
-}
-
-async function detect(definition: ManagedAppDefinition, strict = false): Promise<Installation> {
const serviceNames: string[] = [];
for (const serviceName of definition.serviceNames) {
if (await systemdState(serviceName, strict) !== "missing") serviceNames.push(serviceName);
@@ -58,16 +43,6 @@ async function detect(definition: ManagedAppDefinition, strict = false): Promise
return { type: "not-installed" };
}
-async function running(installation: Installation, strict = false): Promise<boolean> {
- if (installation.serviceNames && (await Promise.all(installation.serviceNames.map(name => systemdState(name, strict)))).some((state) => state === "active")) return true;
- for (const containerName of installation.containerNames ?? []) {
- const result = await runDocker(["inspect", "--format", "{{.State.Running}}", containerName], 10_000);
- if (result.code !== 0 || !["true", "false"].includes(result.stdout.trim())) throw new Error("Cannot confirm managed-app container state");
- if (result.stdout.trim() === "true") return true;
- }
- return false;
-}
-
/** Globally-routable IPv4 only. Private/CGNAT/link-local addresses are useful for
* MSO's internal proxy but are not the "works without a domain" address a user
* can open from their own browser. No external IP-discovery service is called. */
@@ -131,7 +106,7 @@ async function version(definition: ManagedAppDefinition): Promise<string | null>
return value;
}
-function actionsFor(installation: Installation): ManagedAppAction[] {
+function actionsFor(installation: ManagedInstallation): ManagedAppAction[] {
if (installation.type === "systemd" || installation.type === "docker") return ["start", "stop", "restart", "backup"];
if (installation.type === "package") return ["backup"];
return [];
@@ -140,18 +115,23 @@ function actionsFor(installation: Installation): ManagedAppAction[] {
export async function getManagedApp(id: ManagedAppId): Promise<ManagedAppView> {
const definition = getManagedAppDefinition(id);
const installation = await detect(definition);
- const isRunning = await running(installation);
- const isHealthy = isRunning ? await managedAppHealth(definition) : null;
+ let runState = await managedRunState(installation);
+ let stopOnlyOwned = false;
+ if (id === "orca" && installation.type === "not-installed") {
+ const stopInstall = await detectOwnedOrcaForStop();
+ if (stopInstall.owned) {
+ stopOnlyOwned = true;
+ runState = await managedRunState(stopInstall);
+ }
+ }
+ const isRunning = runState === "running";
+ const isHealthy = isRunning && !stopOnlyOwned ? await managedAppHealth(definition) : null;
const operation = activeOperation(id);
const state = operation === "start"
? "starting"
- : installation.type === "not-installed"
+ : installation.type === "not-installed" && !stopOnlyOwned
? "not-installed"
- : isHealthy === false
- ? "unhealthy"
- : isRunning
- ? "running"
- : "stopped";
+ : runState === "unknown" ? "error" : isHealthy === false ? "unhealthy" : isRunning ? "running" : "stopped";
const dockerInstallAvailable = definition.installBackends.includes("docker") && installation.type === "not-installed" && await dockerUsable();
const domainView = await readManagedDomainView(id);
return {
@@ -163,18 +143,19 @@ export async function getManagedApp(id: ManagedAppId): Promise<ManagedAppView> {
state,
healthy: isHealthy,
version: await version(definition),
- dashboardAvailable: isRunning && isHealthy !== false,
+ dashboardAvailable: isRunning && isHealthy !== false && !stopOnlyOwned,
publicDashboardUrl: domainView.domain?.phase === "ready" ? `https://${domainView.domain.hostname}` : directDashboardUrl(definition),
...domainView,
- supportedActions: actionsFor(installation),
+ supportedActions: stopOnlyOwned ? ["stop"] : actionsFor(installation),
// Only ever attached to a NEGATIVE reading. An app detected as present has
// been seen, and nothing about the bus can make that observation wrong.
diagnostic:
- installation.type === "not-installed" && userBusUnavailable()
- ? dockerInstallAvailable
- ? null
- : "MSO cannot reach this user's systemd bus, so it cannot see user services. On a systemd host enable user linger and provide XDG_RUNTIME_DIR; on a systemd-less/container host use a supported Docker runtime."
- : null,
+ installation.diagnostic ??
+ (runState === "unknown" && (installation.serviceName ?? (stopOnlyOwned ? ORCA_SERVICE : undefined))
+ ? orcaUnknownDiagnostic(installation.serviceName ?? ORCA_SERVICE)
+ : installation.type === "not-installed" && userBusUnavailable()
+ ? dockerInstallAvailable ? null : "MSO cannot reach this user's systemd bus, so it cannot see user services. On a systemd host enable user linger and provide XDG_RUNTIME_DIR; on a systemd-less/container host use a supported Docker runtime."
+ : null),
};
}
@@ -188,7 +169,17 @@ export async function assertManagedAppStopped(id: ManagedAppId): Promise<void> {
if (await running(await detect(getManagedAppDefinition(id), true), true)) throw new Error("Cannot confirm app is stopped; stop all app services before backup or restore");
}
-async function runLifecycle(installation: Installation, action: "start" | "stop" | "restart"): Promise<void> {
+async function runLifecycle(installation: ManagedInstallation, action: "start" | "stop" | "restart"): Promise<void> {
+ // Owned Orca runs as a USER unit under MSO's control. Act on exactly that unit
+ // and never fall through to a same-name system unit.
+ if (installation.owned && installation.serviceName) {
+ const result = await runProgram("systemctl", ["--user", action, installation.serviceName], 30_000, userBusEnv());
+ if (result.code !== 0) {
+ const detail = result.stderr.trim() || result.stdout.trim() || `systemctl exited ${result.code}`;
+ throw new Error(`systemctl --user ${action} ${installation.serviceName} failed: ${detail.slice(0, 300)}`);
+ }
+ return;
+ }
if (installation.serviceNames || installation.containerNames) {
for (const serviceName of installation.serviceNames ?? []) await runLifecycle({ type: "systemd", serviceName }, action);
for (const containerName of installation.containerNames ?? []) await runLifecycle({ type: "docker", containerName }, action);
@@ -225,13 +216,17 @@ export async function performManagedAppAction(id: ManagedAppId, action: ManagedA
if (!acquireOperation(id, action)) throw new Error("another operation is already running");
try {
const definition = getManagedAppDefinition(id);
- const installation = await detect(definition);
- if (!actionsFor(installation).includes(action)) throw new Error("operation unsupported for detected installation type");
+ const isOrcaStop = id === "orca" && action === "stop";
+ const installation = isOrcaStop ? await detectOwnedOrcaForStop() : await detect(definition, id === "orca");
+ if (isOrcaStop ? (!installation.owned || installation.type === "not-installed") : !actionsFor(installation).includes(action)) {
+ throw new Error(installation.diagnostic ?? "operation unsupported for detected installation type");
+ }
if (action === "backup") await createBackup(definition, "manual", () => assertManagedAppStopped(id));
else await runLifecycle(installation, action);
} finally {
releaseOperation(id);
versionCache.delete(id);
+ if (id === "orca") invalidateOrcaIntegrityCache();
}
});
const domain = action === "start" || action === "restart" ? await provisionDomainAfterStart(id) : null;
@@ -245,7 +240,8 @@ export async function getManagedAppLogs(id: ManagedAppId): Promise<ManagedAppLog
let result = null;
if (installation.type === "systemd" && installation.serviceName) {
result = await runProgram("journalctl", ["--user", "-u", installation.serviceName, "-n", "100", "--no-pager", "-o", "short-iso"], 15_000);
- if (result.code !== 0) result = await runProgram("journalctl", ["-u", installation.serviceName, "-n", "100", "--no-pager", "-o", "short-iso"], 15_000);
+ // Owned Orca logs are user-scope only: a system fallback could read a foreign unit.
+ if (result.code !== 0 && !installation.owned) result = await runProgram("journalctl", ["-u", installation.serviceName, "-n", "100", "--no-pager", "-o", "short-iso"], 15_000);
} else if (installation.type === "docker" && installation.containerName) {
result = await runDocker(["logs", "--tail", "100", installation.containerName], 15_000);
}
diff --git a/lib/managed-apps/orca-bootstrap.test.ts b/lib/managed-apps/orca-bootstrap.test.ts
new file mode 100644
index 00000000..b7034e20
--- /dev/null
+++ b/lib/managed-apps/orca-bootstrap.test.ts
@@ -0,0 +1,199 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import vm from "node:vm";
+import { NextRequest } from "next/server";
+
+vi.mock("server-only", () => ({}));
+vi.mock("@/lib/managed-apps/orca-readiness", () => ({
+ getOrcaReadiness: vi.fn(async () => ({
+ available: true,
+ pairingUrl: "orca://pair?code=fixture",
+ webClientUrl: "https://orca.mso.example.com/web-index.html",
+ runtimeId: "rt_fixture",
+ serverPid: 4242,
+ startTicks: "123456",
+ boundEndpoint: "ws://127.0.0.1:6769",
+ advertisedEndpoint: "wss://orca.mso.example.com",
+ })),
+}));
+
+vi.hoisted(() => {
+ process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com";
+ process.env.OS_PUBLIC_ORIGIN = "https://mso.example.com";
+});
+
+import { gateManagedApp } from "./session";
+import { MANAGED_APP_HOST_HEADER } from "./origin";
+
+const sessionMock = vi.fn();
+type ManagedAppSessionModule = typeof import("@/lib/managed-apps/session");
+
+vi.mock("@/lib/managed-apps/session", async (importOriginal) => {
+ const actual = (await importOriginal()) as ManagedAppSessionModule;
+ return {
+ ...actual,
+ managedAppSession: (req: Request, id: string) => sessionMock(req, id),
+ };
+});
+
+const fetchMock = vi.fn();
+vi.stubGlobal("fetch", fetchMock);
+
+const TEMPLATE = "{id}.mso.example.com";
+const APP_HOST = "orca.mso.example.com";
+const PREFIX = "/api/v1/managed-apps/orca/proxy";
+
+async function getProxyRoute() {
+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", TEMPLATE);
+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.com");
+ return import("@/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route");
+}
+
+function proxyReq(path: string, init: RequestInit = {}): Request {
+ const headers = new Headers(init.headers);
+ headers.set("host", APP_HOST);
+ headers.set("x-forwarded-proto", "https");
+ headers.set(MANAGED_APP_HOST_HEADER, "orca");
+ return new Request(`https://${APP_HOST}${PREFIX}/${path}`, { ...init, headers });
+}
+
+const proxyCtx = (path: string[]) => ({ params: Promise.resolve({ id: "orca", path }) });
+
+describe("gateManagedApp actual bootstrap JS execution in isolated VM", () => {
+ it("executes the actual gate script: validates fetch, strips ticket, preserves pairing, and reloads", async () => {
+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", TEMPLATE);
+ const req = new NextRequest("https://orca.mso.example.com/__mso_app_bootstrap.js");
+ const res = await gateManagedApp(req, "orca");
+ expect(res).not.toBeNull();
+ expect(res?.status).toBe(200);
+ expect(res?.headers.get("content-type")).toContain("application/javascript");
+
+ const scriptSource = await res!.text();
+ expect(scriptSource).toContain("app_ticket");
+
+ const reloadMock = vi.fn();
+ const fetchApiMock = vi.fn(async (_url: string, _init?: RequestInit) => ({
+ ok: true,
+ status: 204,
+ }));
+
+ const sandbox = {
+ location: {
+ pathname: "/editor",
+ search: "",
+ hash: "#pairing=enc_v1_secret_code_xyz&app_ticket=bearer_ticket_token_123",
+ reload: reloadMock,
+ },
+ history: {
+ replaceState: vi.fn((_state: unknown, _title: string, url: string) => {
+ const u = new URL(url, "https://orca.mso.example.com");
+ sandbox.location.pathname = u.pathname;
+ sandbox.location.search = u.search;
+ sandbox.location.hash = u.hash;
+ }),
+ },
+ document: {
+ body: { textContent: "" },
+ },
+ fetch: fetchApiMock,
+ URL,
+ URLSearchParams,
+ };
+
+ const context = vm.createContext(sandbox);
+ vm.runInContext(scriptSource, context);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(fetchApiMock).toHaveBeenCalledTimes(1);
+ const [authUrl, authInit] = fetchApiMock.mock.calls[0] as [string, RequestInit];
+ expect(authUrl).toBe("/__mso_app_auth");
+ expect(authInit.method).toBe("POST");
+ expect((authInit.headers as Record<string, string>)?.authorization).toBe("Bearer bearer_ticket_token_123");
+ expect(authInit.credentials).toBe("include");
+ expect(authInit.cache).toBe("no-store");
+
+ expect(sandbox.location.hash).toBe("#pairing=enc_v1_secret_code_xyz");
+ expect(sandbox.location.hash).not.toContain("app_ticket");
+ expect(sandbox.location.search).toBe("");
+ expect(reloadMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("fails closed on auth failure: shows error message and does not reload", async () => {
+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", TEMPLATE);
+ const req = new NextRequest("https://orca.mso.example.com/__mso_app_bootstrap.js");
+ const res = await gateManagedApp(req, "orca");
+ const scriptSource = await res!.text();
+
+ const reloadMock = vi.fn();
+ const sandbox = {
+ location: {
+ pathname: "/",
+ search: "",
+ hash: "#pairing=key&app_ticket=bad_ticket",
+ reload: reloadMock,
+ },
+ history: { replaceState: vi.fn() },
+ document: { body: { textContent: "" } },
+ fetch: vi.fn(async () => ({ ok: false, status: 401 })),
+ URL,
+ URLSearchParams,
+ };
+
+ const context = vm.createContext(sandbox);
+ vm.runInContext(scriptSource, context);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ expect(reloadMock).not.toHaveBeenCalled();
+ expect(sandbox.document.body.textContent).toContain("Application authorization failed");
+ });
+});
+
+describe("Actual proxy route worker and service worker enforcement", () => {
+ beforeEach(() => {
+ fetchMock.mockReset();
+ sessionMock.mockReset();
+ });
+
+ it("denies Sec-Fetch-Dest serviceworker on arbitrary path without calling upstream fetch", async () => {
+ sessionMock.mockResolvedValueOnce({ device_id: "test" });
+ const { GET } = await getProxyRoute();
+ const request = proxyReq("assets/foo.js", {
+ headers: {
+ "sec-fetch-dest": "serviceworker",
+ cookie: "__Host-mapp_orca_session=valid",
+ },
+ });
+
+ const res = await GET(request, proxyCtx(["assets", "foo.js"]));
+ expect(res.status).toBe(404);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("denies dedicated worker if unauthenticated, and forwards to upstream when authenticated", async () => {
+ sessionMock.mockResolvedValueOnce(null);
+ const { GET } = await getProxyRoute();
+ const unauthReq = proxyReq("assets/editor.worker.js", {
+ headers: { "sec-fetch-dest": "worker" },
+ });
+ const unauthRes = await GET(unauthReq, proxyCtx(["assets", "editor.worker.js"]));
+ expect(unauthRes.status).toBe(401);
+ expect(fetchMock).not.toHaveBeenCalled();
+
+ sessionMock.mockResolvedValueOnce({ device_id: "test" });
+ fetchMock.mockResolvedValueOnce(
+ new Response("/* worker code */", {
+ status: 200,
+ headers: { "content-type": "application/javascript" },
+ }),
+ );
+ const authReq = proxyReq("assets/editor.worker.js", {
+ headers: {
+ "sec-fetch-dest": "worker",
+ cookie: "__Host-mapp_orca_session=valid_cookie",
+ },
+ });
+ const authRes = await GET(authReq, proxyCtx(["assets", "editor.worker.js"]));
+ expect(authRes.status).toBe(200);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(await authRes.text()).toBe("/* worker code */");
+ });
+});
diff --git a/lib/managed-apps/orca-containment.test.ts b/lib/managed-apps/orca-containment.test.ts
new file mode 100644
index 00000000..7d876a25
--- /dev/null
+++ b/lib/managed-apps/orca-containment.test.ts
@@ -0,0 +1,209 @@
+import { describe, expect, it, afterAll, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+import { mkdtemp, rm } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { NextRequest } from "next/server";
+
+const testDir = await mkdtemp(path.join(os.tmpdir(), "mso-orca-test-"));
+process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com";
+process.env.OS_DEVICE_STORE = path.join(testDir, "devices.json");
+process.env.OS_SESSION_SECRET = "s".repeat(32);
+
+const { contentSecurityPolicy } = await import("./proxy-csp");
+const { isServiceWorkerRequest } = await import("./proxy-headers");
+const { socketPolicy } = await import("./socket-policy");
+const { createManagedAppCookie } = await import("./session");
+const devices = await import("@/lib/auth/device-store");
+
+describe("Orca CSP containment and capabilities", () => {
+ const PREFIX_URL = "https://orca.mso.example.com/";
+ const COCKPIT = "https://mso.example.com";
+
+ it("adds worker-src app root and wasm-unsafe-eval for Orca only", () => {
+ const csp = contentSecurityPolicy(PREFIX_URL, undefined, {
+ cockpitOrigin: COCKPIT,
+ appId: "orca",
+ });
+
+ // Orca must allow its app root for dedicated/shared workers, plus blob:
+ expect(csp).toContain(`worker-src ${PREFIX_URL} blob:`);
+ // Orca must allow wasm-unsafe-eval in script-src
+ expect(csp).toContain(`script-src ${PREFIX_URL} 'unsafe-inline' blob: 'wasm-unsafe-eval'`);
+ // Orca must NEVER allow unsafe-eval
+ expect(csp).not.toContain("'unsafe-eval'");
+ });
+
+ it("preserves strict blob-only worker-src and no wasm for non-Orca apps", () => {
+ const hermesCsp = contentSecurityPolicy("https://hermes.mso.example.com/", undefined, {
+ cockpitOrigin: COCKPIT,
+ appId: "hermes",
+ });
+ expect(hermesCsp).toContain("worker-src blob:");
+ expect(hermesCsp).not.toContain("https://hermes.mso.example.com/ blob:");
+ expect(hermesCsp).not.toContain("wasm-unsafe-eval");
+ expect(hermesCsp).not.toContain("unsafe-eval");
+
+ const defaultCsp = contentSecurityPolicy(PREFIX_URL, undefined, {
+ cockpitOrigin: COCKPIT,
+ });
+ expect(defaultCsp).toContain("worker-src blob:");
+ expect(defaultCsp).not.toContain("wasm-unsafe-eval");
+ });
+
+ it("refuses upstream attempts to widen Orca script-src with unsafe-eval", () => {
+ const upstreamWithEval = "default-src 'self'; script-src 'self' 'unsafe-eval' https://evil.example";
+ const csp = contentSecurityPolicy(PREFIX_URL, upstreamWithEval, {
+ cockpitOrigin: COCKPIT,
+ appId: "orca",
+ });
+ expect(csp).not.toContain("'unsafe-eval'");
+ expect(csp).not.toContain("https://evil.example");
+ });
+});
+
+describe("Service Worker fetch rejection", () => {
+ it("rejects Sec-Fetch-Dest serviceworker regardless of requested path or extension", () => {
+ expect(isServiceWorkerRequest(["assets", "foo.js"], "serviceworker")).toBe(true);
+ expect(isServiceWorkerRequest(["assets", "bundle.min.js"], "ServiceWorker")).toBe(true);
+ expect(isServiceWorkerRequest(["main.wasm"], "serviceworker")).toBe(true);
+ });
+
+ it("retains conventional filename defense even without Sec-Fetch-Dest", () => {
+ expect(isServiceWorkerRequest(["sw.js"], null)).toBe(true);
+ expect(isServiceWorkerRequest(["service-worker.js"], undefined)).toBe(true);
+ expect(isServiceWorkerRequest(["serviceworker.js"], "")).toBe(true);
+ });
+
+ it("permits regular dedicated and shared worker requests for Orca", () => {
+ expect(isServiceWorkerRequest(["assets", "editor.worker.js"], "worker")).toBe(false);
+ expect(isServiceWorkerRequest(["shared.js"], "sharedworker")).toBe(false);
+ expect(isServiceWorkerRequest(["assets", "normal.js"], "script")).toBe(false);
+ });
+});
+
+describe("Orca WebSocket upgrade Origin validation", () => {
+ afterAll(async () => {
+ delete process.env.OS_DEVICE_STORE;
+ delete process.env.OS_SESSION_SECRET;
+ delete process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE;
+ await rm(testDir, { recursive: true, force: true });
+ });
+
+ it("permits Orca WS upgrade only with exact same-origin HTTPS Origin", async () => {
+ const ownerId = "o".repeat(32);
+ await devices.approveDevice(ownerId, "owner", "owner");
+ const id = "d".repeat(32);
+ await devices.approveDevice(id, "operator", "operator");
+ const issued = Date.now();
+ const policy = await devices.currentSessionPolicy("host");
+ const cookie = createManagedAppCookie("orca", {
+ device_id: id,
+ issued_at: issued,
+ expires_at: issued + 60_000,
+ cookie_scope: policy.scope,
+ cookie_epoch: policy.epoch,
+ }, process.env.OS_SESSION_SECRET!);
+
+ // Valid same-origin request
+ const valid = new NextRequest("https://orca.mso.example.com/socket?orca-client=web", {
+ headers: {
+ host: "orca.mso.example.com",
+ origin: "https://orca.mso.example.com",
+ upgrade: "websocket",
+ connection: "Upgrade",
+ cookie: `__Host-mso-managed-app=${cookie}`,
+ authorization: "bearer-token-should-be-stripped",
+ },
+ });
+ const ready = {
+ available: true as const,
+ pairingUrl: "orca://pair?code=fixture",
+ webClientUrl: "https://orca.mso.example.com/web-index.html",
+ runtimeId: "rt_fixture",
+ serverPid: 4242,
+ startTicks: "99887766",
+ listenerInode: "12345",
+ boundEndpoint: "ws://127.0.0.1:6769",
+ advertisedEndpoint: "wss://orca.mso.example.com",
+ };
+ const deps = { getOrcaReadiness: async () => ready };
+
+ const decision = await socketPolicy(valid, deps);
+ expect(decision).not.toBeNull();
+ expect(JSON.parse(decision!.identity!)).toMatchObject({ device: id, runtimeId: "rt_fixture" });
+ expect(decision?.target).toContain("orca-client=web");
+ expect(decision?.headers.cookie).toBeUndefined();
+ expect(decision?.headers.authorization).toBeUndefined();
+
+ // Absent Origin -> denied
+ const missingOrigin = new NextRequest("https://orca.mso.example.com/socket?orca-client=web", {
+ headers: {
+ host: "orca.mso.example.com",
+ upgrade: "websocket",
+ connection: "Upgrade",
+ cookie: `__Host-mso-managed-app=${cookie}`,
+ },
+ });
+ expect(await socketPolicy(missingOrigin)).toBeNull();
+
+ // Sibling Origin -> denied
+ const siblingOrigin = new NextRequest("https://orca.mso.example.com/socket?orca-client=web", {
+ headers: {
+ host: "orca.mso.example.com",
+ origin: "https://hermes.mso.example.com",
+ upgrade: "websocket",
+ connection: "Upgrade",
+ cookie: `__Host-mso-managed-app=${cookie}`,
+ },
+ });
+ expect(await socketPolicy(siblingOrigin)).toBeNull();
+
+ // Wrong scheme (wss://) -> denied
+ const wrongScheme = new NextRequest("https://orca.mso.example.com/socket?orca-client=web", {
+ headers: {
+ host: "orca.mso.example.com",
+ origin: "wss://orca.mso.example.com",
+ upgrade: "websocket",
+ connection: "Upgrade",
+ cookie: `__Host-mso-managed-app=${cookie}`,
+ },
+ });
+ expect(await socketPolicy(wrongScheme)).toBeNull();
+
+ // Viewer role -> denied
+ await devices.setDeviceRole(id, "viewer");
+ expect(await socketPolicy(valid)).toBeNull();
+
+ // Revoked / invalidated session -> denied even with valid-looking cookie
+ await devices.setDeviceRole(id, "operator");
+ await devices.invalidateDeviceSessions(id);
+ expect(await socketPolicy(valid)).toBeNull();
+
+ // Generic non-Orca clients (e.g. hermes) do NOT require Origin header
+ const freshId = "e".repeat(32);
+ await devices.approveDevice(freshId, "operator", "operator");
+ const freshPolicy = await devices.currentSessionPolicy("host");
+ const now = Date.now();
+ const freshHermesCookie = createManagedAppCookie("hermes", {
+ device_id: freshId,
+ issued_at: now,
+ expires_at: now + 60_000,
+ cookie_scope: freshPolicy.scope,
+ cookie_epoch: freshPolicy.epoch,
+ }, process.env.OS_SESSION_SECRET!);
+ const freshHermesNoOrigin = new NextRequest("https://hermes.mso.example.com/socket", {
+ headers: {
+ host: "hermes.mso.example.com",
+ upgrade: "websocket",
+ connection: "Upgrade",
+ cookie: `__Host-mso-managed-app=${freshHermesCookie}`,
+ },
+ });
+ const hermesDecision = await socketPolicy(freshHermesNoOrigin);
+ expect(hermesDecision).not.toBeNull();
+ expect(hermesDecision?.identity).toBe(freshId);
+ });
+});
diff --git a/lib/managed-apps/orca-installation.ts b/lib/managed-apps/orca-installation.ts
new file mode 100644
index 00000000..76e80eaa
--- /dev/null
+++ b/lib/managed-apps/orca-installation.ts
@@ -0,0 +1,200 @@
+import "server-only";
+import { promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { ownerUidMatches, proveOwnedOrcaUnit, readOrcaUnitText, type OrcaUnitProof } from "./orca-unit-proof";
+import { resolveOrcaManagedRoot } from "./orca-private-fs";
+import { runProgram } from "./runner";
+import { userBusEnv } from "./user-bus";
+
+export { ORCA_UNIT_MARKER } from "./orca-unit-proof";
+
+/**
+ * MSO-owned Orca installation ownership.
+ *
+ * Orca is installed by MSO as ONE exact USER unit at a fixed path, next to a
+ * verified install receipt. The generic manager cannot prove that: `systemctl
+ * show` answers for a same-name unit in EITHER scope, so an unrelated system
+ * `mso-orca.service` looked "installed" and an Operator stop would signal a unit
+ * MSO never created. This module narrows the proof to:
+ * 1. the exact USER unit file at `~/.config/systemd/user/mso-orca.service` —
+ * read symlink-proof and bounded (`realpath` ancestor check + `O_NOFOLLOW`
+ * fd read, mirroring `orca-private-fs`), a regular owner-owned file whose
+ * `ExecStart` names this repo's canonical `scripts/orca/cli.mjs` AND the
+ * resolved managed root, and
+ * 2. a verified install receipt, read by invoking the adapter's exact
+ * `readInstalledOrcaRelease` contract (`--version`), which rehashes the
+ * immutable release and prints the pinned version.
+ * Anything else (foreign unit, wrong root/cli, wrong version, missing/invalid
+ * receipt) is `not-installed` + a diagnostic, and mutation/install is refused.
+ */
+
+export type ManagedInstallation = {
+ type: "systemd" | "docker" | "package" | "not-installed";
+ serviceName?: string;
+ serviceNames?: string[];
+ containerName?: string;
+ containerNames?: string[];
+ /** True only for MSO's exact owned USER unit (fixed path, marker + argv, no symlink). */
+ owned?: boolean;
+ /** Operator-facing reason a same-name/partial install was refused. */
+ diagnostic?: string | null;
+};
+
+export const ORCA_SERVICE = "mso-orca.service";
+/** Mirrors `scripts/orca/constants.mjs` `ORCA_VERSION`; a receipt must match it. */
+export const EXPECTED_ORCA_VERSION = "1.4.230";
+const INSTALL_RECEIPT = "managed-install.json";
+const VERSION_TIMEOUT_MS = 20_000;
+
+export function orcaUserUnitPath(home: string = os.homedir()): string {
+ return path.join(home, ".config", "systemd", "user", ORCA_SERVICE);
+}
+
+/** This repository's canonical CLI entry point, as `renderOrcaServiceUnit` writes it. */
+export function canonicalOrcaCliPath(cwd: string = process.cwd()): string {
+ return path.join(cwd, "scripts", "orca", "cli.mjs");
+}
+
+/** Exact generated ownership, read bounded/symlink-proof via `orca-unit-files`.
+ * `reinstall-required` is an old MSO unit whose receipt predates the recorded
+ * launcher identity: it is never silently adopted. */
+async function orcaUnitProof(unitPath: string, root: string): Promise<OrcaUnitProof> {
+ const text = await readOrcaUnitText(unitPath);
+ return text === null ? "not-owned" : proveOwnedOrcaUnit(text, root, canonicalOrcaCliPath());
+}
+
+/**
+ * User-scope unit state only. Never falls through to the system scope: an Orca
+ * action must never signal a foreign system unit of the same name.
+ */
+export async function userUnitState(service: string = ORCA_SERVICE): Promise<"active" | "inactive" | "missing" | "unavailable"> {
+ const result = await runProgram("systemctl", ["--user", "show", "-p", "LoadState", "-p", "ActiveState", service], 10_000, userBusEnv());
+ if (result.code !== 0) return "unavailable";
+ const load = /LoadState=(\S+)/.exec(result.stdout)?.[1];
+ if (!load || load === "not-found") return "missing";
+ return /ActiveState=(?:active|activating|deactivating|reloading)\b/.test(result.stdout) ? "active" : "inactive";
+}
+
+export type OrcaRunState = "running" | "stopped" | "unknown";
+
+/** User-scope only. A `--user` bus outage (`unavailable`) or an owned unit systemd
+ * does not load (`missing`) is `unknown`: never silently equal to `stopped`. */
+export async function orcaRunState(service: string = ORCA_SERVICE): Promise<OrcaRunState> {
+ const state = await userUnitState(service);
+ if (state === "active") return "running";
+ if (state === "inactive") return "stopped";
+ return "unknown";
+}
+
+/** Attached to a view whose owned unit state MSO could not confirm. */
+export function orcaUnknownDiagnostic(service: string): string {
+ return `Cannot confirm whether ${service} is running: its user-scope systemd state is unknown (no user systemd bus, or the unit is not loaded). It is not reported as stopped.`;
+}
+
+/** A same-name unit that exists in either scope — used only to explain a refusal. */
+async function sameNamePresent(service: string): Promise<boolean> {
+ for (const scope of [["--user"], []] as const) {
+ const result = await runProgram("systemctl", [...scope, "show", "-p", "LoadState", service], 10_000, scope.length ? userBusEnv() : undefined);
+ const load = result.code === 0 ? /LoadState=(\S+)/.exec(result.stdout)?.[1] : undefined;
+ if (load && load !== "not-found") return true;
+ }
+ return false;
+}
+
+const RECEIPT_CACHE_TTL_MS = 30_000;
+
+// Rehashing the whole release on every poll is unbounded work. Cache the verified
+// version against the receipt file's identity and security metadata: a rewrite/replace (tamper)
+// changes the key and forces a fresh adapter verification. Read status cache max 30s.
+let receiptCache: { root: string; key: string; version: string | null; cachedAt: number } | null = null;
+
+export function invalidateOrcaIntegrityCache(): void {
+ receiptCache = null;
+}
+
+async function verifiedInstallVersion(root: string, adapterPath: string, fresh = false): Promise<string | null> {
+ const receiptPath = path.join(root, INSTALL_RECEIPT);
+ let key: string;
+ try {
+ const info = await fs.lstat(receiptPath);
+ if (info.isSymbolicLink() || !info.isFile()) return null;
+ if (!ownerUidMatches(info.uid)) return null;
+ if ((info.mode & 0o077) !== 0) return null;
+ key = `${adapterPath}:${info.uid}:${info.mode}:${info.ctimeMs}:${info.ino}:${info.size}:${info.mtimeMs}`;
+ } catch {
+ return null;
+ }
+ if (!fresh && receiptCache && receiptCache.root === root && receiptCache.key === key && Date.now() - receiptCache.cachedAt < RECEIPT_CACHE_TTL_MS) {
+ return receiptCache.version;
+ }
+ const result = await runProgram(adapterPath, ["--version"], VERSION_TIMEOUT_MS, { ORCA_HOME: root });
+ const printed = result.code === 0 ? result.stdout.trim().split(/\r?\n/)[0] : "";
+ // The adapter prints the pinned version only for a release it rehashed and
+ // validated; any other non-empty string is not proof.
+ const version = printed === EXPECTED_ORCA_VERSION ? printed : null;
+ receiptCache = { root, key, version, cachedAt: Date.now() };
+ return version;
+}
+
+export interface OrcaDetectionDeps {
+ env?: NodeJS.ProcessEnv;
+ home?: string;
+ /** This repo's `scripts/managed-app-orca`, invoked with the fixed `--version` argv. */
+ adapterPath: string;
+ freshVerification?: boolean;
+}
+
+export async function detectOrca({ env = process.env, home = os.homedir(), adapterPath, freshVerification = false }: OrcaDetectionDeps): Promise<ManagedInstallation> {
+ const rootResult = resolveOrcaManagedRoot(env);
+ const root = rootResult.ok ? rootResult.root : null;
+ const proof = root !== null ? await orcaUnitProof(orcaUserUnitPath(home), root) : "not-owned";
+ const unitIsOurs = proof === "owned";
+ const version = root !== null ? await verifiedInstallVersion(root, adapterPath, freshVerification) : null;
+
+ if (unitIsOurs && version) {
+ return { type: "systemd", serviceName: ORCA_SERVICE, serviceNames: [ORCA_SERVICE], owned: true };
+ }
+
+ const diagnostic = !rootResult.ok
+ ? "Orca's managed root (ORCA_HOME) is invalid, so no mso-orca.service can be treated as MSO-installed."
+ : proof === "reinstall-required"
+ ? "mso-orca.service was installed by an older MSO release that did not record its launcher identity; reinstall Orca with this MSO version to manage it."
+ : unitIsOurs && !version
+ ? "mso-orca.service is MSO-owned but has no verified install receipt; refusing to manage it."
+ : (await sameNamePresent(ORCA_SERVICE))
+ ? "A mso-orca.service exists that MSO did not create (foreign unit or wrong scope); refusing to manage it."
+ : null;
+ return { type: "not-installed", diagnostic };
+}
+
+export interface OrcaStopDetectionDeps {
+ env?: NodeJS.ProcessEnv;
+ home?: string;
+}
+
+/**
+ * Narrow ownership proof for stop containment ONLY.
+ * Verifies exact USER unit and trusted launcher config without requiring release integrity,
+ * allowing an operator to safely stop/contain a running daemon even when the release is corrupt.
+ */
+export async function detectOwnedOrcaForStop({
+ env = process.env,
+ home = os.homedir(),
+}: OrcaStopDetectionDeps = {}): Promise<ManagedInstallation> {
+ const rootResult = resolveOrcaManagedRoot(env);
+ const root = rootResult.ok ? rootResult.root : null;
+ const proof = root !== null ? await orcaUnitProof(orcaUserUnitPath(home), root) : "not-owned";
+ if (proof === "owned") {
+ return { type: "systemd", serviceName: ORCA_SERVICE, serviceNames: [ORCA_SERVICE], owned: true };
+ }
+
+ const diagnostic = !rootResult.ok
+ ? "Orca's managed root (ORCA_HOME) is invalid, so no mso-orca.service can be treated as MSO-installed."
+ : proof === "reinstall-required"
+ ? "mso-orca.service was installed by an older MSO release that did not record its launcher identity; reinstall Orca with this MSO version to manage it."
+ : (await sameNamePresent(ORCA_SERVICE))
+ ? "A mso-orca.service exists that MSO did not create (foreign unit or wrong scope); refusing to manage it."
+ : null;
+ return { type: "not-installed", diagnostic };
+}
diff --git a/lib/managed-apps/orca-integrity-cache.test.ts b/lib/managed-apps/orca-integrity-cache.test.ts
new file mode 100644
index 00000000..aebf1829
--- /dev/null
+++ b/lib/managed-apps/orca-integrity-cache.test.ts
@@ -0,0 +1,151 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+vi.mock("server-only", () => ({}));
+vi.mock("./runner", () => ({
+ runProgram: vi.fn(),
+ commandExists: vi.fn().mockResolvedValue(false),
+ resolveCommand: vi.fn().mockResolvedValue(null),
+ requireProgram: vi.fn(),
+}));
+vi.mock("./user-bus", () => ({
+ userBusEnv: vi.fn(() => ({ XDG_RUNTIME_DIR: "/run/user/1000" })),
+ userBusUnavailable: vi.fn(() => false),
+}));
+vi.mock("./orca-readiness", () => ({ getOrcaReadiness: vi.fn() }));
+
+const { runProgram } = await import("./runner");
+const { getManagedApp, performManagedAppAction, assertManagedAppStopped } = await import("./manager");
+const { getManagedAppDefinition } = await import("./catalog");
+const { renderOrcaServiceUnit } = (await import("../../scripts/orca/systemd-unit.mjs")) as {
+ renderOrcaServiceUnit: (options: Record<string, unknown>) => string;
+};
+const { buildPlannedConfig, buildServiceConfig } = await import("../../scripts/orca/managed-config.mjs");
+
+const ADAPTER = getManagedAppDefinition("orca").command;
+const STOPPED = "LoadState=loaded\nActiveState=inactive\n";
+type Result = { code: number; stdout: string; stderr: string };
+const ok = (stdout = ""): Result => ({ code: 0, stdout, stderr: "" });
+
+let home = "";
+const root = () => path.join(home, ".local", "share", "mso", "orca");
+const unitPath = () => path.join(home, ".config", "systemd", "user", "mso-orca.service");
+const hostNode = () => path.join(home, "bin", "host-node");
+const releaseNode = () => path.join(home, "release", "node");
+const receiptPath = () => path.join(root(), "managed-install.json");
+
+const CLI = path.join(process.cwd(), "scripts", "orca", "cli.mjs");
+const ADVERTISED = "wss://orca.mso.example.com";
+
+function unitText() {
+ return renderOrcaServiceUnit({
+ hostNode: hostNode(),
+ cliScript: CLI,
+ managedRoot: root(),
+ port: 6769,
+ advertisedEndpoint: ADVERTISED,
+ });
+}
+
+const configFor = () =>
+ buildServiceConfig({
+ plannedConfig: buildPlannedConfig({ root: root(), unitPath: unitPath(), fixedPort: 6769, advertised: ADVERTISED }),
+ prepared: {
+ releaseRoot: path.join(root(), "r"), slotDir: path.join(root(), "r", "slot"), webDir: path.join(root(), "r", "web"),
+ nodeBinary: releaseNode(), receiptPath: path.join(root(), "r", "receipt.json"), receipt: { release: { contentId: "fixture" } },
+ },
+ installedAt: "2026-01-01T00:00:00.000Z",
+ hostNode: hostNode(),
+ cliScript: CLI,
+ });
+
+async function writeOwnedFixture() {
+ await mkdir(path.dirname(unitPath()), { recursive: true });
+ await writeFile(unitPath(), unitText(), { mode: 0o644 });
+ await writeFile(path.join(root(), "managed-service.json"), JSON.stringify(configFor()), { mode: 0o600 });
+ await writeFile(receiptPath(), "{}", { mode: 0o600 });
+}
+
+let adapterResult: Result = ok("1.4.230\n");
+
+function setupRunnerMock() {
+ vi.mocked(runProgram).mockImplementation(async (command: string, args: readonly string[]) => {
+ if (command === "systemctl") {
+ if (args.includes("show")) return ok(STOPPED);
+ return ok();
+ }
+ if (command === ADAPTER) return adapterResult;
+ return ok();
+ });
+}
+
+const callLog = () => vi.mocked(runProgram).mock.calls as Array<[string, string[]]>;
+const lifecycleCalls = () => callLog().filter(([c, a]) => c === "systemctl" && !a.includes("show"));
+
+describe("Orca cache integrity and mutation regression", () => {
+ beforeEach(async () => {
+ home = await mkdtemp(path.join(tmpdir(), "orca-cache-"));
+ process.env.HOME = home;
+ delete process.env.ORCA_HOME;
+ await mkdir(root(), { recursive: true, mode: 0o700 });
+ await mkdir(path.dirname(hostNode()), { recursive: true, mode: 0o700 });
+ await mkdir(path.dirname(releaseNode()), { recursive: true, mode: 0o700 });
+ await writeFile(hostNode(), "#!/bin/sh\n", { mode: 0o755 });
+ await writeFile(releaseNode(), "#!/bin/sh\n", { mode: 0o755 });
+ await chmod(hostNode(), 0o755);
+ await chmod(releaseNode(), 0o755);
+ vi.mocked(runProgram).mockReset();
+ adapterResult = ok("1.4.230\n");
+ setupRunnerMock();
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await rm(home, { recursive: true, force: true });
+ });
+
+ it("primes status cache then refuses start without systemctl when adapter returns invalid", async () => {
+ await writeOwnedFixture();
+
+ // 1. Prime real detectOrca path status cache with valid generated unit and private config
+ const initialView = await getManagedApp("orca");
+ expect(initialView.installed).toBe(true);
+ expect(initialView.state).toBe("stopped");
+
+ // 2. Adapter returns invalid without changing receipt
+ adapterResult = { code: 1, stdout: "", stderr: "checksum mismatch / corrupt" };
+
+ // 3. performManagedAppAction('orca', 'start') must refuse before systemctl
+ await expect(performManagedAppAction("orca", "start")).rejects.toThrow(/install receipt|cannot prove absence/i);
+ expect(lifecycleCalls()).toEqual([]);
+ });
+
+ it("rejects install receipt with 0666 permissions", async () => {
+ await writeOwnedFixture();
+ await chmod(receiptPath(), 0o666);
+
+ const view = await getManagedApp("orca");
+ expect(view.installed).toBe(false);
+ expect(view.diagnostic).toMatch(/install receipt/i);
+
+ await expect(performManagedAppAction("orca", "start")).rejects.toThrow(/install receipt/i);
+ expect(lifecycleCalls()).toEqual([]);
+ });
+
+ it("strict assertManagedAppStopped performs fresh verification even with primed cache", async () => {
+ await writeOwnedFixture();
+
+ // Prime status cache
+ const initialView = await getManagedApp("orca");
+ expect(initialView.installed).toBe(true);
+ expect(initialView.state).toBe("stopped");
+
+ // Adapter now fails without receipt file change
+ adapterResult = { code: 1, stdout: "", stderr: "tampered" };
+
+ // Strict stopped check must fail closed via fresh verification
+ await expect(assertManagedAppStopped("orca")).rejects.toThrow(/install receipt|cannot prove absence/i);
+ });
+});
diff --git a/lib/managed-apps/orca-manager.test.ts b/lib/managed-apps/orca-manager.test.ts
new file mode 100644
index 00000000..3c428453
--- /dev/null
+++ b/lib/managed-apps/orca-manager.test.ts
@@ -0,0 +1,219 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+vi.mock("server-only", () => ({}));
+vi.mock("./runner", () => ({
+ runProgram: vi.fn(),
+ commandExists: vi.fn().mockResolvedValue(false),
+ resolveCommand: vi.fn().mockResolvedValue(null),
+ requireProgram: vi.fn(),
+}));
+vi.mock("./user-bus", () => ({
+ userBusEnv: vi.fn(() => ({ XDG_RUNTIME_DIR: "/run/user/1000" })),
+ userBusUnavailable: vi.fn(() => false),
+}));
+vi.mock("./orca-readiness", () => ({ getOrcaReadiness: vi.fn() }));
+
+const { runProgram } = await import("./runner");
+const { getOrcaReadiness } = await import("./orca-readiness");
+const { getManagedApp, performManagedAppAction } = await import("./manager");
+const { getManagedAppDefinition } = await import("./catalog");
+const { renderOrcaServiceUnit } = (await import("../../scripts/orca/systemd-unit.mjs")) as {
+ renderOrcaServiceUnit: (options: Record<string, unknown>) => string;
+};
+const { buildPlannedConfig, buildServiceConfig } = await import("../../scripts/orca/managed-config.mjs");
+
+const ADAPTER = getManagedAppDefinition("orca").command;
+const READY = {
+ available: true as const, pairingUrl: "orca://pair?code=private", webClientUrl: "http://127.0.0.1:6769/web-index.html",
+ runtimeId: "runtime-abc", serverPid: 4242, boundEndpoint: "ws://127.0.0.1:6769", advertisedEndpoint: "wss://orca.mso.example.com",
+};
+const ACTIVE = "LoadState=loaded\nActiveState=active\n";
+const STOPPED = "LoadState=loaded\nActiveState=inactive\n";
+const NOT_FOUND = "LoadState=not-found\nActiveState=inactive\n";
+type Result = { code: number; stdout: string; stderr: string };
+const ok = (stdout = ""): Result => ({ code: 0, stdout, stderr: "" });
+
+let home = "";
+const root = () => path.join(home, ".local", "share", "mso", "orca");
+const unitPath = () => path.join(home, ".config", "systemd", "user", "mso-orca.service");
+const hostNode = () => path.join(home, "bin", "host-node");
+const releaseNode = () => path.join(home, "release", "node");
+
+// The exact unit `renderOrcaServiceUnit` writes for this repo's canonical CLI
+// and the resolved managed root. The launcher node is the host node the
+// installer actually rendered, deliberately DIFFERENT from release.nodeBinary.
+const CLI = path.join(process.cwd(), "scripts", "orca", "cli.mjs");
+const ADVERTISED = "wss://orca.mso.example.com";
+function unitText({ cli = CLI, managedRoot = root() } = {}) {
+ return renderOrcaServiceUnit({
+ hostNode: hostNode(),
+ cliScript: cli,
+ managedRoot,
+ port: 6769,
+ advertisedEndpoint: ADVERTISED,
+ });
+}
+const configFor = () =>
+ buildServiceConfig({
+ plannedConfig: buildPlannedConfig({ root: root(), unitPath: unitPath(), fixedPort: 6769, advertised: ADVERTISED }),
+ prepared: {
+ releaseRoot: path.join(root(), "r"), slotDir: path.join(root(), "r", "slot"), webDir: path.join(root(), "r", "web"),
+ nodeBinary: releaseNode(), receiptPath: path.join(root(), "r", "receipt.json"), receipt: { release: { contentId: "fixture" } },
+ },
+ installedAt: "2026-01-01T00:00:00.000Z",
+ hostNode: hostNode(),
+ cliScript: CLI,
+ });
+async function writeOwnedUnit(overrides = {}) {
+ await mkdir(path.dirname(unitPath()), { recursive: true });
+ await writeFile(unitPath(), unitText(overrides), { mode: 0o644 });
+ await writeFile(path.join(root(), "managed-service.json"), JSON.stringify(configFor()), { mode: 0o600 });
+}
+const writeReceipt = () => writeFile(path.join(root(), "managed-install.json"), "{}", { mode: 0o600 });
+
+/** user/system scope unit stdout + adapter `--version` outcome, per test. */
+function programs({ user = NOT_FOUND, system = NOT_FOUND, adapter }: { user?: Result | string; system?: Result | string; adapter?: Result }) {
+ const asResult = (v: Result | string): Result => (typeof v === "string" ? ok(v) : v);
+ vi.mocked(runProgram).mockImplementation(async (command: string, args: readonly string[]) => {
+ if (command === "systemctl") {
+ if (args.includes("show")) return args[0] === "--user" ? asResult(user) : asResult(system);
+ // A real user-bus outage fails every `--user` call, not just `show`.
+ return args[0] === "--user" ? asResult(user) : asResult(system);
+ }
+ if (command === ADAPTER) return adapter ?? { code: 1, stdout: "", stderr: "not installed" };
+ return ok();
+ });
+}
+const callLog = () => vi.mocked(runProgram).mock.calls as Array<[string, string[]]>;
+const lifecycleCalls = () => callLog().filter(([c, a]) => c === "systemctl" && !a.includes("show"));
+
+beforeEach(async () => {
+ home = await mkdtemp(path.join(tmpdir(), "orca-mgr-"));
+ process.env.HOME = home;
+ delete process.env.ORCA_HOME;
+ await mkdir(root(), { recursive: true, mode: 0o700 });
+ await mkdir(path.dirname(hostNode()), { recursive: true, mode: 0o700 });
+ await mkdir(path.dirname(releaseNode()), { recursive: true, mode: 0o700 });
+ await writeFile(hostNode(), "#!/bin/sh\n", { mode: 0o755 });
+ await writeFile(releaseNode(), "#!/bin/sh\n", { mode: 0o755 });
+ await chmod(hostNode(), 0o755);
+ await chmod(releaseNode(), 0o755);
+ vi.mocked(runProgram).mockReset();
+ vi.mocked(getOrcaReadiness).mockReset();
+});
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await rm(home, { recursive: true, force: true });
+});
+
+describe("Orca manager ownership", () => {
+ it("refuses an unrelated same-name SYSTEM unit instead of calling it installed", async () => {
+ programs({ user: NOT_FOUND, system: ACTIVE });
+ const view = await getManagedApp("orca");
+ expect(view.installed).toBe(false);
+ expect(view.state).toBe("not-installed");
+ expect(view.supportedActions).toEqual([]);
+ expect(view.diagnostic).toMatch(/did not create|foreign/i);
+
+ await expect(performManagedAppAction("orca", "stop")).rejects.toThrow(/did not create|foreign/i);
+ expect(lifecycleCalls()).toEqual([]);
+ });
+
+ it("does not treat a Docker container or a PATH binary as an Orca install", async () => {
+ programs({});
+ await expect(getManagedApp("orca")).resolves.toMatchObject({ state: "not-installed" });
+ expect(lifecycleCalls()).toEqual([]);
+ });
+
+ it("requires a verified install receipt: missing and invalid both stay not-installed", async () => {
+ await writeOwnedUnit();
+ programs({ user: ACTIVE });
+ expect((await getManagedApp("orca")).diagnostic).toMatch(/install receipt/i);
+
+ await writeReceipt();
+ programs({ user: ACTIVE, adapter: { code: 1, stdout: "", stderr: "not installed" } });
+ expect((await getManagedApp("orca")).diagnostic).toMatch(/install receipt/i);
+ });
+
+ it("reports a stopped MSO-owned USER unit (verified receipt) as stopped, not running", async () => {
+ await writeOwnedUnit();
+ await writeReceipt();
+ programs({ user: STOPPED, adapter: ok("1.4.230\n") });
+ const view = await getManagedApp("orca");
+ expect(view.installed).toBe(true);
+ expect(view.state).toBe("stopped");
+ expect(view.supportedActions).toContain("start");
+ });
+
+ it("reports a running MSO-owned USER unit as running only when readiness verifies", async () => {
+ await writeOwnedUnit();
+ await writeReceipt();
+ programs({ user: ACTIVE, adapter: ok("1.4.230\n") });
+ vi.mocked(getOrcaReadiness).mockResolvedValue(READY);
+ expect(await getManagedApp("orca")).toMatchObject({ state: "running", healthy: true });
+ });
+
+ it("uses the exact USER unit argv for actions and never the system scope", async () => {
+ await writeOwnedUnit();
+ await writeReceipt();
+ programs({ user: ACTIVE, adapter: ok("1.4.230\n") });
+ await performManagedAppAction("orca", "stop");
+ const stops = lifecycleCalls().filter(([, a]) => a.includes("stop"));
+ expect(stops.length).toBeGreaterThan(0);
+ for (const [, args] of stops) expect(args).toEqual(["--user", "stop", "mso-orca.service"]);
+ expect(callLog().some(([c, a]) => c === "systemctl" && a[0] === "stop")).toBe(false);
+ });
+
+ it("keeps a user-bus outage user-scope only: refuses without touching the system unit", async () => {
+ await writeOwnedUnit();
+ await writeReceipt();
+ programs({ user: { code: 1, stdout: "", stderr: "Failed to connect to bus" }, system: ACTIVE, adapter: ok("1.4.230\n") });
+ const view = await getManagedApp("orca");
+ expect(view.installed).toBe(true);
+
+ await expect(performManagedAppAction("orca", "start")).rejects.toThrow(/systemctl --user start/);
+ expect(callLog().some(([c, a]) => c === "systemctl" && a[0] === "start")).toBe(false);
+ });
+
+ it("leaves generic apps on the generic detection path", async () => {
+ programs({ system: ACTIVE });
+ const hermes = await getManagedApp("hermes");
+ expect(hermes.installed).toBe(true);
+ });
+
+ it("refuses a unit reached through a symlinked ancestor", async () => {
+ const real = path.join(home, "realconfig");
+ await mkdir(path.join(real, "systemd", "user"), { recursive: true });
+ await writeFile(path.join(real, "systemd", "user", "mso-orca.service"), unitText(), { mode: 0o644 });
+ await symlink(real, path.join(home, ".config"));
+ await writeReceipt();
+ programs({ user: ACTIVE, adapter: ok("1.4.230\n") });
+ const view = await getManagedApp("orca");
+ expect(view.installed).toBe(false);
+ expect(view.state).toBe("not-installed");
+ expect(view.supportedActions).toEqual([]);
+ });
+
+ it("refuses a unit whose marker regex alone matches but points at another root or CLI", async () => {
+ await writeOwnedUnit({ managedRoot: path.join(home, "other-root") });
+ await writeReceipt();
+ programs({ user: ACTIVE, adapter: ok("1.4.230\n") });
+ expect((await getManagedApp("orca")).installed).toBe(false);
+
+ await writeOwnedUnit({ cli: "/tmp/evil/cli.mjs" });
+ programs({ user: ACTIVE, adapter: ok("1.4.230\n") });
+ expect((await getManagedApp("orca")).installed).toBe(false);
+ });
+
+ it("refuses a receipt whose adapter version is not the pinned one", async () => {
+ await writeOwnedUnit();
+ await writeReceipt();
+ programs({ user: ACTIVE, adapter: ok("1.9.9\n") });
+ const view = await getManagedApp("orca");
+ expect(view.installed).toBe(false);
+ expect(view.diagnostic).toMatch(/install receipt/i);
+ });
+});
diff --git a/lib/managed-apps/orca-pairing.test.ts b/lib/managed-apps/orca-pairing.test.ts
new file mode 100644
index 00000000..f6ffe3c4
--- /dev/null
+++ b/lib/managed-apps/orca-pairing.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from "vitest";
+import { buildOrcaWebClientUrl, parsePairingCodeFromUrl, validateOrcaPairingUrl } from "./orca-pairing";
+
+const ORIGIN = "https://orca.mso.example.com";
+// The trusted managed endpoint is the exact configured split origin, nothing else:
+// no path, no query, no userinfo. The browser adds `?orca-client=web` when it opens
+// the socket itself; the OFFER must not smuggle one in.
+const WSS_ENDPOINT = "wss://orca.mso.example.com";
+
+function encode(payload: Record<string, unknown>): string {
+ const b64 = Buffer.from(JSON.stringify(payload), "utf-8")
+ .toString("base64")
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=+$/, "");
+ return `orca://pair?code=${b64}`;
+}
+
+function offer(overrides: Record<string, unknown> = {}): string {
+ return encode({
+ v: 2,
+ endpoint: WSS_ENDPOINT,
+ deviceToken: "token_1234567890abcdef",
+ publicKeyB64: "pubkey_b64_xyz123",
+ scope: "runtime",
+ ...overrides,
+ });
+}
+
+describe("Orca pairing offer validation", () => {
+ it("accepts a v2 runtime offer bound to the exact configured WSS origin", () => {
+ const validated = validateOrcaPairingUrl(offer(), ORIGIN);
+ expect(validated).not.toBeNull();
+ expect(validated?.endpoint).toBe(WSS_ENDPOINT);
+ expect(validated?.deviceToken).toBe("token_1234567890abcdef");
+ expect(validated?.scope).toBe("runtime");
+ });
+
+ it("accepts the pairing code passed as a bare URL fragment", () => {
+ const code = parsePairingCodeFromUrl(offer());
+ expect(code).not.toBeNull();
+ const validated = validateOrcaPairingUrl(`orca://pair#${code}`, ORIGIN);
+ expect(validated?.endpoint).toBe(WSS_ENDPOINT);
+ });
+
+ it("requires scope to be explicitly runtime (absent upstream scope is the mobile/legacy shape)", () => {
+ expect(validateOrcaPairingUrl(offer({ scope: undefined }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ scope: "mobile" }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ scope: "relay" }), ORIGIN)).toBeNull();
+ });
+
+ it("rejects relay offers even when the endpoint origin looks correct", () => {
+ expect(validateOrcaPairingUrl(offer({ relay: { url: "wss://relay.example.com" } }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ relayUrl: "wss://relay.example.com" }), ORIGIN)).toBeNull();
+ });
+
+ it("rejects endpoints with a path, query, fragment, or userinfo", () => {
+ expect(validateOrcaPairingUrl(offer({ endpoint: `${WSS_ENDPOINT}/socket` }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ endpoint: `${WSS_ENDPOINT}?orca-client=web` }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ endpoint: `${WSS_ENDPOINT}#frag` }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ endpoint: "wss://user:[email protected]" }), ORIGIN)).toBeNull();
+ });
+
+ it("rejects wrong origin, sibling app host, non-WSS scheme, and non-HTTPS configured prefix", () => {
+ expect(validateOrcaPairingUrl(offer({ endpoint: "wss://evil.example.com" }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ endpoint: "wss://hermes.mso.example.com" }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ endpoint: "ws://orca.mso.example.com" }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ endpoint: "https://orca.mso.example.com" }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer(), "http://orca.mso.example.com")).toBeNull();
+ });
+
+ it("rejects malformed, empty, or oversized tokens and keys", () => {
+ expect(validateOrcaPairingUrl(offer({ deviceToken: "" }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ deviceToken: "x".repeat(600) }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ deviceToken: "has space" }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ publicKeyB64: "" }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ publicKeyB64: "x".repeat(3000) }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ publicKeyB64: "not base64!!" }), ORIGIN)).toBeNull();
+ });
+
+ it("rejects desktop-control grants defensively", () => {
+ expect(validateOrcaPairingUrl(offer({ grants: ["desktop-control"] }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ grantDesktopControl: true }), ORIGIN)).toBeNull();
+ });
+
+ it("rejects versions other than 2 and malformed or oversized input", () => {
+ expect(validateOrcaPairingUrl(offer({ v: 1 }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl("orca://pair?code=not_base64!!!", ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl("https://orca.mso.example.com/pair", ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(`orca://pair?${"a".repeat(5000)}`, ORIGIN)).toBeNull();
+ // Duplicate code parameters are ambiguous: never pick one.
+ const dup = `${offer()}&code=${parsePairingCodeFromUrl(offer())}`;
+ expect(parsePairingCodeFromUrl(dup)).toBeNull();
+ });
+});
+
+describe("canonical Orca web client URL", () => {
+ it("builds https://app/web-index.html#pairing=<encoded> with no query or extra fragment", () => {
+ const pairingUrl = "orca://pair?code=abc-123_XYZ";
+ const web = buildOrcaWebClientUrl(ORIGIN, pairingUrl);
+ const parsed = new URL(web);
+ expect(parsed.origin).toBe(ORIGIN);
+ expect(parsed.pathname).toBe("/web-index.html");
+ expect(parsed.search).toBe("");
+ expect(parsed.hash).toBe(`#pairing=${encodeURIComponent(pairingUrl)}`);
+ expect(parsed.hash).not.toContain("token");
+ });
+});
diff --git a/lib/managed-apps/orca-pairing.ts b/lib/managed-apps/orca-pairing.ts
new file mode 100644
index 00000000..a80d599c
--- /dev/null
+++ b/lib/managed-apps/orca-pairing.ts
@@ -0,0 +1,132 @@
+/**
+ * Upstream Orca pairing URL parser and validator.
+ *
+ * The offer is opaque credential material produced by the upstream runtime. This
+ * module decides only whether MSO may hand it to a browser: the endpoint must be
+ * the EXACT configured managed WSS origin (no path, query, fragment, or userinfo),
+ * scope must be an explicit `runtime`, and relay / desktop-control shapes are
+ * refused. It does not — and cannot — certify the real upstream permission set:
+ * upstream does not encode grants here, so any grant claim is refused rather than
+ * trusted. The outer MSO Operator gate remains the authorization boundary.
+ */
+const MAX_PAIRING_INPUT = 4096;
+const MAX_PAIRING_CODE = 2048;
+const MIN_KEY_LEN = 4;
+const MAX_KEY_LEN = 2048;
+const CANONICAL_B64URL = /^[A-Za-z0-9_-]+$/;
+const TOKEN_PATTERN = /^[A-Za-z0-9._~+/=-]{1,512}$/;
+const KEY_PATTERN = /^[A-Za-z0-9+/_-]+={0,2}$/;
+
+export interface ValidatedPairingOffer {
+ v: 2;
+ endpoint: string;
+ deviceToken: string;
+ publicKeyB64: string;
+ scope: "runtime";
+ pairedDeviceId?: string;
+}
+
+/** `https://host[:port]` → `wss://host[:port]`, or null when the configured
+ * managed origin is not HTTPS (an insecure deployment cannot carry a WSS offer). */
+function expectedWebSocketOrigin(origin: string): string | null {
+ try {
+ const url = new URL(origin);
+ if (url.protocol !== "https:") return null;
+ return `wss://${url.host.toLowerCase()}`;
+ } catch {
+ return null;
+ }
+}
+
+function endpointMatchesExpected(endpoint: string, expectedWs: string): boolean {
+ let url: URL;
+ try {
+ url = new URL(endpoint);
+ } catch {
+ return false;
+ }
+ if (url.protocol !== "wss:") return false;
+ if (url.username || url.password) return false;
+ if (url.search || url.hash) return false;
+ if (url.pathname !== "" && url.pathname !== "/") return false;
+ return url.origin.toLowerCase() === expectedWs;
+}
+
+export function parsePairingCodeFromUrl(url: string): string | null {
+ if (typeof url !== "string" || url.length === 0 || url.length > MAX_PAIRING_INPUT) return null;
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return null;
+ }
+ if (parsed.protocol !== "orca:" || parsed.hostname !== "pair") return null;
+ if (parsed.pathname !== "" && parsed.pathname !== "/") return null;
+ if (parsed.username || parsed.password) return null;
+ const codes = parsed.searchParams.getAll("code");
+ const fragment = parsed.hash ? parsed.hash.slice(1) : "";
+ // A query code and a fragment code together are ambiguous; so are duplicates.
+ if (codes.length > 1 || (codes.length === 1 && fragment)) return null;
+ if (codes.length === 1) return codes[0] ? codes[0] : null;
+ if (!fragment) return null;
+ // Fragment form is a single bare token, never another key=value pair.
+ if (fragment.includes("&") || fragment.includes("=")) return null;
+ return fragment;
+}
+
+export function decodePairingBase64(code: string): Record<string, unknown> | null {
+ if (!code || code.length > MAX_PAIRING_CODE || !CANONICAL_B64URL.test(code)) return null;
+ try {
+ const base64 = code.replace(/-/g, "+").replace(/_/g, "/");
+ const parsed = JSON.parse(Buffer.from(base64, "base64").toString("utf-8"));
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
+ ? (parsed as Record<string, unknown>)
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+export function validateOrcaPairingUrl(url: string, expectedOrigin: string): ValidatedPairingOffer | null {
+ const expectedWs = expectedWebSocketOrigin(expectedOrigin);
+ if (!expectedWs) return null;
+
+ const code = parsePairingCodeFromUrl(url);
+ if (!code) return null;
+ const raw = decodePairingBase64(code);
+ if (!raw) return null;
+
+ if (raw.v !== 2) return null;
+ // Absent scope is the mobile/legacy shape upstream sent historically: refuse it.
+ if (raw.scope !== "runtime") return null;
+ // Relay offers never route through MSO's own split origin.
+ if ("relay" in raw || "relayUrl" in raw) return null;
+ // Upstream does not encode grants in this offer, so a grant claim is refused
+ // rather than trusted. Refuse PROPERTY PRESENCE, not truthiness: `false`,
+ // `null`, an empty array, a string, or an object is still an unverifiable
+ // claim about authority, and desktop control is refused for the record too.
+ if ("grants" in raw || "desktopControl" in raw || "grantDesktopControl" in raw) return null;
+
+ if (typeof raw.endpoint !== "string" || !endpointMatchesExpected(raw.endpoint, expectedWs)) return null;
+ if (typeof raw.deviceToken !== "string" || !TOKEN_PATTERN.test(raw.deviceToken)) return null;
+ if (typeof raw.publicKeyB64 !== "string") return null;
+ if (raw.publicKeyB64.length < MIN_KEY_LEN || raw.publicKeyB64.length > MAX_KEY_LEN) return null;
+ if (!KEY_PATTERN.test(raw.publicKeyB64)) return null;
+
+ return {
+ v: 2,
+ endpoint: raw.endpoint,
+ deviceToken: raw.deviceToken,
+ publicKeyB64: raw.publicKeyB64,
+ scope: "runtime",
+ pairedDeviceId: typeof raw.pairedDeviceId === "string" ? raw.pairedDeviceId : undefined,
+ };
+}
+
+/** The one URL MSO will ever frame: the app's own web client on the exact configured
+ * origin, carrying the validated pairing URL in the FRAGMENT only. Never trust an
+ * upstream-provided web client URL, and never place credential material in a query. */
+export function buildOrcaWebClientUrl(origin: string, pairingUrl: string): string {
+ const base = new URL(origin);
+ return `${base.origin}/web-index.html#pairing=${encodeURIComponent(pairingUrl)}`;
+}
diff --git a/lib/managed-apps/orca-private-fs.test.ts b/lib/managed-apps/orca-private-fs.test.ts
new file mode 100644
index 00000000..f2970a86
--- /dev/null
+++ b/lib/managed-apps/orca-private-fs.test.ts
@@ -0,0 +1,96 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { readOrcaPrivateFile, resolveOrcaManagedRoot } from "./orca-private-fs";
+
+const roots: string[] = [];
+async function makeRoot(mode = 0o700): Promise<string> {
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "mso-orca-fs-"));
+ await chmod(tmp, mode);
+ roots.push(tmp);
+ return tmp;
+}
+
+afterEach(async () => {
+ while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });
+});
+
+describe("resolveOrcaManagedRoot", () => {
+ it("uses the portable default under the owner home, never the personal ~/.orca", () => {
+ const result = resolveOrcaManagedRoot({});
+ expect(result.ok).toBe(true);
+ if (result.ok) {
+ expect(result.root).toBe(path.join(os.homedir(), ".local", "share", "mso", "orca"));
+ expect(result.root).not.toContain(`${path.sep}.orca-remote`);
+ expect(path.basename(result.root)).not.toBe(".orca");
+ }
+ });
+
+ it("accepts a clean absolute ORCA_HOME and rejects relative, dot-dot, and NUL config", () => {
+ const abs = resolveOrcaManagedRoot({ ORCA_HOME: "/var/lib/mso/orca" });
+ expect(abs).toEqual({ ok: true, root: "/var/lib/mso/orca" });
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "relative/orca" }).ok).toBe(false);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "/var/lib/../../etc/orca" }).ok).toBe(false);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: " " })).toEqual({ ok: false, reason: "managed_root_invalid" });
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "/var\0lib" }).ok).toBe(false);
+ });
+});
+
+describe("readOrcaPrivateFile", () => {
+ it("reads a 0600 regular file inside a 0700 owner directory", async () => {
+ const root = await makeRoot();
+ await writeFile(path.join(root, "runtime-identity.json"), `{"a":1}`, { mode: 0o600 });
+ const result = await readOrcaPrivateFile(root, "runtime-identity.json");
+ expect(result).toEqual({ ok: true, text: `{"a":1}` });
+ });
+
+ it("reports missing for an absent file or absent root", async () => {
+ const root = await makeRoot();
+ expect(await readOrcaPrivateFile(root, "private-status.json")).toEqual({ ok: false, reason: "missing" });
+ expect(await readOrcaPrivateFile(path.join(root, "nope"), "private-status.json")).toEqual({ ok: false, reason: "missing" });
+ });
+
+ it("rejects a group/other-readable file and a group/other-accessible directory", async () => {
+ const root = await makeRoot();
+ const file = path.join(root, "private-status.json");
+ await writeFile(file, "{}", { mode: 0o600 });
+ await chmod(file, 0o644);
+ expect(await readOrcaPrivateFile(root, "private-status.json")).toEqual({ ok: false, reason: "insecure" });
+
+ await chmod(file, 0o600);
+ await chmod(root, 0o755);
+ expect(await readOrcaPrivateFile(root, "private-status.json")).toEqual({ ok: false, reason: "insecure" });
+ });
+
+ it("rejects a symlinked final component instead of following it", async () => {
+ const root = await makeRoot();
+ await writeFile(path.join(root, "real.json"), "{}", { mode: 0o600 });
+ await symlink(path.join(root, "real.json"), path.join(root, "private-status.json"));
+ expect(await readOrcaPrivateFile(root, "private-status.json")).toEqual({ ok: false, reason: "insecure" });
+ });
+
+ it("rejects a symlinked ancestor directory", async () => {
+ const parent = await makeRoot();
+ const real = path.join(parent, "real");
+ await mkdir(real, { mode: 0o700 });
+ await symlink(real, path.join(parent, "link"));
+ await writeFile(path.join(real, "private-status.json"), "{}", { mode: 0o600 });
+ expect(await readOrcaPrivateFile(path.join(parent, "link"), "private-status.json")).toEqual({ ok: false, reason: "insecure" });
+ });
+
+ it("refuses to read an unknown filename", async () => {
+ const root = await makeRoot();
+ await writeFile(path.join(root, "anything.json"), "{}", { mode: 0o600 });
+ expect(await readOrcaPrivateFile(root, "anything.json")).toEqual({ ok: false, reason: "insecure" });
+ });
+
+ it("refuses a file larger than the bounded cap before reading bytes", async () => {
+ const root = await makeRoot();
+ await writeFile(path.join(root, "private-status.json"), "x".repeat(70000), { mode: 0o600 });
+ expect(await readOrcaPrivateFile(root, "private-status.json")).toEqual({ ok: false, reason: "insecure" });
+ });
+});
diff --git a/lib/managed-apps/orca-private-fs.ts b/lib/managed-apps/orca-private-fs.ts
new file mode 100644
index 00000000..18caa2b3
--- /dev/null
+++ b/lib/managed-apps/orca-private-fs.ts
@@ -0,0 +1,116 @@
+import "server-only";
+import { constants, promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+/**
+ * The ONLY way the Orca bridge reads MSO's private runtime metadata.
+ *
+ * The managed root is MSO-owned state, not the owner's `~/.orca` profile. The
+ * receipt/status files carry live credential material, so a read must be
+ * symlink-proof, owner-only, and bounded — `lstat`-then-`readFile` is a TOCTOU
+ * race and an unbounded `readFile` is a memory primitive. The root's canonical
+ * path must equal its configured spelling (no symlink ancestor), the final
+ * component is opened `O_NOFOLLOW`, and the cap is enforced from `fstat` before
+ * any byte moves.
+ */
+export const ORCA_PRIVATE_MAX_BYTES = 64 * 1024;
+const PRIVATE_FILES = new Set(["private-status.json", "runtime-identity.json"]);
+const CONTROL = /[\0\r\n]/;
+
+export type ManagedRootResult = { ok: true; root: string } | { ok: false; reason: "managed_root_invalid" };
+export type PrivateReadResult = { ok: true; text: string } | { ok: false; reason: "missing" | "insecure" };
+
+/** Portable default is MSO-managed state, never the owner's personal `~/.orca`. */
+export function defaultOrcaManagedRoot(home: string = os.homedir()): string {
+ return path.join(home, ".local", "share", "mso", "orca");
+}
+
+/** Resolve ORCA_HOME strictly, with the same policy as `scripts/orca/managed-paths.mjs`:
+ * an invalid override fails the bridge instead of silently falling back to the
+ * owner's default directory. `home` is injectable for parity tests only. */
+export function resolveOrcaManagedRoot(
+ env: Record<string, string | undefined> = process.env,
+ home: string = os.homedir(),
+): ManagedRootResult {
+ const invalid: ManagedRootResult = { ok: false, reason: "managed_root_invalid" };
+ const raw = env.ORCA_HOME;
+ if (raw === undefined) return { ok: true, root: defaultOrcaManagedRoot(home) };
+ // A SET but empty/relative/dirty override is a misconfiguration, not "unset":
+ // fail the bridge clearly instead of falling back to the owner's default.
+ if (typeof raw !== "string" || raw.trim() === "" || CONTROL.test(raw) || !path.isAbsolute(raw)) return invalid;
+ const normalized = path.normalize(raw);
+ // A trailing slash, `//`, or a `.`/`..` segment changes the canonical spelling;
+ // refuse it instead of quietly rewriting the operator's config.
+ if (normalized !== raw || (raw.length > 1 && raw.endsWith(path.sep))) return invalid;
+ if (normalized.split(/[\\/]/).includes("..")) return invalid;
+ const resolvedHome = path.normalize(home);
+ // Never manage the filesystem root or the owner home itself.
+ if (normalized === path.sep || normalized === resolvedHome) return invalid;
+ // Never reuse the operator's personal Orca state, including any subtree.
+ const personalOrca = path.join(resolvedHome, ".orca");
+ const personalOrcaRemote = path.join(resolvedHome, ".orca-remote");
+ for (const prefix of [personalOrca, personalOrcaRemote]) {
+ if (normalized === prefix || normalized.startsWith(`${prefix}${path.sep}`)) return invalid;
+ }
+ return { ok: true, root: normalized };
+}
+
+function uidMatches(uid: number): boolean {
+ return typeof process.getuid !== "function" || uid === process.getuid();
+}
+
+export async function readOrcaPrivateFile(root: string, filename: string): Promise<PrivateReadResult> {
+ if (!PRIVATE_FILES.has(filename)) return { ok: false, reason: "insecure" };
+
+ let canonicalRoot: string;
+ try {
+ canonicalRoot = await fs.realpath(root);
+ } catch {
+ return { ok: false, reason: "missing" };
+ }
+ // A symlinked ancestor changes the canonical path; refuse rather than follow it.
+ if (canonicalRoot !== path.resolve(root)) return { ok: false, reason: "insecure" };
+
+ let directory;
+ try {
+ directory = await fs.open(canonicalRoot, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
+ } catch {
+ return { ok: false, reason: "missing" };
+ }
+ try {
+ const rootStat = await directory.stat();
+ if (!rootStat.isDirectory() || (rootStat.mode & 0o077) !== 0 || !uidMatches(rootStat.uid)) {
+ return { ok: false, reason: "insecure" };
+ }
+
+ let handle;
+ try {
+ // Pin the verified directory inode and open the leaf by basename only.
+ handle = await fs.open(`/proc/self/fd/${directory.fd}/${filename}`, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ } catch (err) {
+ return { ok: false, reason: (err as NodeJS.ErrnoException)?.code === "ENOENT" ? "missing" : "insecure" };
+ }
+ try {
+ const before = await handle.stat();
+ if (!before.isFile() || (before.mode & 0o077) !== 0 || !uidMatches(before.uid)) return { ok: false, reason: "insecure" };
+ if (before.size > ORCA_PRIVATE_MAX_BYTES) return { ok: false, reason: "insecure" };
+ const buffer = Buffer.alloc(Number(before.size));
+ let offset = 0;
+ while (offset < buffer.length) {
+ const { bytesRead } = await handle.read(buffer, offset, buffer.length - offset, offset);
+ if (!bytesRead) return { ok: false, reason: "insecure" };
+ offset += bytesRead;
+ }
+ const after = await handle.stat();
+ if (after.size !== before.size || after.ino !== before.ino || after.mtimeMs !== before.mtimeMs) {
+ return { ok: false, reason: "insecure" };
+ }
+ return { ok: true, text: buffer.toString("utf-8") };
+ } finally {
+ await handle.close();
+ }
+ } finally {
+ await directory.close();
+ }
+}
diff --git a/lib/managed-apps/orca-process-identity.test.ts b/lib/managed-apps/orca-process-identity.test.ts
new file mode 100644
index 00000000..c72f6f5f
--- /dev/null
+++ b/lib/managed-apps/orca-process-identity.test.ts
@@ -0,0 +1,199 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { spawn } from "node:child_process";
+import {
+ parseOrcaRuntimeReceipt,
+ parseProcStatStartTicks,
+ readLinuxProcessSnapshot,
+ readProcessSnapshot,
+ receiptPathsAreContained,
+ verifyOrcaProcessIdentity,
+ type OrcaProcReads,
+ type OrcaProcessSnapshot,
+ type OrcaRuntimeReceipt,
+} from "./orca-process-identity";
+
+const root = "/home/owner/.local/share/mso/orca";
+const validReceipt: OrcaRuntimeReceipt = {
+ schemaVersion: 1,
+ runtimeId: "rt_abcd1234",
+ version: "1.4.230",
+ serverPid: 4242,
+ serverStartTicks: "99887766",
+ nodeBinary: `${root}/runtimes/node-24.21.0/bin/node`,
+ serverEntry: `${root}/releases/1.4.230-abcd/orcad-server.js`,
+ userData: `${root}/runtime/user-data`,
+ boundEndpoint: "ws://127.0.0.1:6769",
+ advertisedEndpoint: "wss://orca.mso.example.com",
+ readyAt: "2026-10-19T10:00:00.000Z",
+};
+
+function snapshot(over: Partial<OrcaProcessSnapshot> = {}): OrcaProcessSnapshot {
+ return {
+ pid: 4242,
+ startTicks: "99887766",
+ uid: typeof process.getuid === "function" ? process.getuid() : 1000,
+ exe: validReceipt.nodeBinary,
+ argv: [validReceipt.nodeBinary, validReceipt.serverEntry, "--bind", "127.0.0.1", "--port", "6769", "--json"],
+ ...over,
+ };
+}
+
+describe("parseProcStatStartTicks", () => {
+ it("parses field 22 even when comm contains spaces and parentheses", () => {
+ const rest = ["S", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "424242"];
+ const stat = `123 (node (weird ) name) ${rest.join(" ")}`;
+ expect(parseProcStatStartTicks(stat)).toBe("424242");
+ expect(parseProcStatStartTicks("not a stat line")).toBeNull();
+ expect(parseProcStatStartTicks("1 (x) S 1")).toBeNull();
+ });
+});
+
+describe("readLinuxProcessSnapshot", () => {
+ it("reads the current process identity from /proc without environ", async () => {
+ const snap = await readLinuxProcessSnapshot(process.pid);
+ expect(snap).not.toBeNull();
+ expect(snap?.pid).toBe(process.pid);
+ expect(snap?.startTicks).toMatch(/^\d+$/);
+ expect(snap?.exe.length).toBeGreaterThan(0);
+ expect(snap?.argv.length).toBeGreaterThan(0);
+ if (typeof process.getuid === "function") expect(snap?.uid).toBe(process.getuid());
+ });
+
+ it("returns null (deny, not bless) for system/dead/foreign PIDs", async () => {
+ expect(await readLinuxProcessSnapshot(1)).toBeNull();
+ expect(await readLinuxProcessSnapshot(0)).toBeNull();
+ expect(await readLinuxProcessSnapshot(99999999)).toBeNull();
+ });
+});
+
+describe("parseOrcaRuntimeReceipt", () => {
+ it("accepts an exact schema-1 receipt", () => {
+ expect(parseOrcaRuntimeReceipt(JSON.stringify(validReceipt))).toEqual(validReceipt);
+ });
+
+ it("rejects missing, wrong-version, relative-path, and non-decimal-start receipts", () => {
+ expect(parseOrcaRuntimeReceipt("not json")).toBeNull();
+ expect(parseOrcaRuntimeReceipt(JSON.stringify({ ...validReceipt, schemaVersion: 2 }))).toBeNull();
+ expect(parseOrcaRuntimeReceipt(JSON.stringify({ ...validReceipt, version: "1.4.229" }))).toBeNull();
+ expect(parseOrcaRuntimeReceipt(JSON.stringify({ ...validReceipt, serverPid: 0 }))).toBeNull();
+ expect(parseOrcaRuntimeReceipt(JSON.stringify({ ...validReceipt, serverStartTicks: "abc" }))).toBeNull();
+ expect(parseOrcaRuntimeReceipt(JSON.stringify({ ...validReceipt, serverEntry: "relative.js" }))).toBeNull();
+ expect(parseOrcaRuntimeReceipt(JSON.stringify({ ...validReceipt, nodeBinary: undefined }))).toBeNull();
+ expect(parseOrcaRuntimeReceipt(JSON.stringify({ ...validReceipt, runtimeId: "" }))).toBeNull();
+ });
+});
+
+describe("readProcessSnapshot PID-reuse guard", () => {
+ const statLine = (start: string) => `1 (node) ${["S", ...Array(18).fill("0"), start].join(" ")}`;
+ const reads = (starts: string[]): OrcaProcReads => {
+ let index = 0;
+ return {
+ stat: async () => statLine(starts[Math.min(index++, starts.length - 1)]),
+ uid: async () => 1000,
+ exe: async () => "/owned/node",
+ argv: async () => ["/owned/node", "/owned/server.js"],
+ };
+ };
+
+ it("rejects a PID whose start ticks changed between snapshot and confirmation", async () => {
+ expect(await readProcessSnapshot(77, reads(["100", "200"]))).toBeNull();
+ });
+
+ it("accepts a stable start time across the same two reads", async () => {
+ expect(await readProcessSnapshot(77, reads(["100", "100"]))).toMatchObject({ pid: 77, startTicks: "100" });
+ });
+});
+
+describe("receipt containment and process identity", () => {
+ it("enforces root/profile/release containment", () => {
+ expect(receiptPathsAreContained(validReceipt, root)).toBe(true);
+ expect(receiptPathsAreContained({ ...validReceipt, serverEntry: "/tmp/orcad-server.js" }, root)).toBe(false);
+ expect(receiptPathsAreContained({ ...validReceipt, serverEntry: `${root}/other/orcad-server.js` }, root)).toBe(false);
+ expect(receiptPathsAreContained({ ...validReceipt, userData: `${root}/runtime/other` }, root)).toBe(false);
+ expect(receiptPathsAreContained({ ...validReceipt, nodeBinary: "/usr/bin/node" }, root)).toBe(false);
+ });
+
+ it("requires the actual owned process to match exactly", () => {
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot(), root)).toBe(true);
+ expect(verifyOrcaProcessIdentity(validReceipt, null, root)).toBe(false);
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ pid: 999 }), root)).toBe(false);
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ startTicks: "1" }), root)).toBe(false);
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ uid: 0 }), root)).toBe(false);
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ exe: "/usr/bin/node" }), root)).toBe(false);
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ argv: ["/usr/bin/node", "other.js"] }), root)).toBe(false);
+ });
+
+ it("requires the exact server entry at argv[1], not merely somewhere in argv", () => {
+ const nodeBinary = validReceipt.nodeBinary;
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ argv: [nodeBinary, validReceipt.serverEntry, "--json"] }), root)).toBe(true);
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ argv: [nodeBinary, "/tmp/other.js", validReceipt.serverEntry] }), root)).toBe(false);
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ argv: [nodeBinary, validReceipt.serverEntry] }), root)).toBe(true);
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ argv: [nodeBinary] }), root)).toBe(false);
+ });
+
+ it("refuses a missing or relative argv[0] before any normalization", () => {
+ // The exact node binary must be named by an absolute argv[0]; a missing or
+ // relative value is refused instead of being resolved against the cwd.
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ argv: [] }), root)).toBe(false);
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ argv: [undefined as unknown as string, validReceipt.serverEntry] }), root)).toBe(false);
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ argv: ["node", validReceipt.serverEntry] }), root)).toBe(false);
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ argv: ["./node", validReceipt.serverEntry] }), root)).toBe(false);
+ // An absolute, non-canonical argv[0] is normalized and matches the node binary.
+ const dotted = `${root}/runtimes/node-24.21.0/bin/../bin/node`;
+ expect(verifyOrcaProcessIdentity(validReceipt, snapshot({ argv: [dotted, validReceipt.serverEntry, "--json"] }), root)).toBe(true);
+ });
+});
+
+describe("actual disposable same-task node process", () => {
+ const tmpRoots: string[] = [];
+ const children: ReturnType<typeof spawn>[] = [];
+ afterAll(async () => {
+ for (const child of children) { try { child.kill("SIGKILL"); } catch { /* ignore */ } }
+ while (tmpRoots.length) await rm(tmpRoots.pop()!, { recursive: true, force: true });
+ });
+
+ it("verifies a real node process spawned from the pinned shape", async () => {
+ const managed = await mkdtemp(path.join(os.tmpdir(), "mso-orca-proc-"));
+ tmpRoots.push(managed);
+ const releases = path.join(managed, "releases", "slot");
+ const runtime = path.join(managed, "runtime");
+ await mkdir(releases, { recursive: true, mode: 0o700 });
+ await mkdir(path.join(runtime, "user-data"), { recursive: true, mode: 0o700 });
+ const entry = path.join(releases, "orcad-server.js");
+ await writeFile(entry, "setTimeout(()=>{}, 30000);", { mode: 0o600 });
+ // The pinned node runtime lives inside the managed root; place a real executable
+ // there (hardlink, else copy) so the receipt's containment and exe match hold.
+ const nodeDir = path.join(managed, "runtimes", "node-24.21.0", "bin");
+ await mkdir(nodeDir, { recursive: true, mode: 0o700 });
+ const nodePath = path.join(nodeDir, "node");
+ try {
+ await import("node:fs").then((fs) => fs.promises.link(process.execPath, nodePath));
+ } catch {
+ await import("node:fs").then((fs) => fs.promises.copyFile(process.execPath, nodePath));
+ }
+ const exe = await import("node:fs").then((fs) => fs.promises.realpath(nodePath));
+
+ const child = spawn(exe, [entry, "--bind", "127.0.0.1", "--port", "6769", "--json"], { stdio: "ignore" });
+ children.push(child);
+ await new Promise((resolve) => setTimeout(resolve, 150));
+
+ const snap = await readLinuxProcessSnapshot(child.pid!);
+ expect(snap).not.toBeNull();
+ const receipt: OrcaRuntimeReceipt = {
+ ...validReceipt,
+ serverPid: child.pid!,
+ serverStartTicks: snap!.startTicks,
+ nodeBinary: exe,
+ serverEntry: entry,
+ userData: path.join(runtime, "user-data"),
+ };
+ expect(receiptPathsAreContained(receipt, managed)).toBe(true);
+ expect(verifyOrcaProcessIdentity(receipt, snap, managed)).toBe(true);
+ });
+});
diff --git a/lib/managed-apps/orca-process-identity.ts b/lib/managed-apps/orca-process-identity.ts
new file mode 100644
index 00000000..57ed8257
--- /dev/null
+++ b/lib/managed-apps/orca-process-identity.ts
@@ -0,0 +1,149 @@
+import "server-only";
+import { promises as fs } from "node:fs";
+import path from "node:path";
+import {
+ parseProcStatStartTicks,
+ defaultProcReads,
+ readProcessSnapshot,
+ readLinuxProcessSnapshot,
+ type OrcaProcessSnapshot,
+ type OrcaProcessReader,
+ type OrcaProcReads,
+} from "./orca-process-reader";
+
+export type { OrcaProcessSnapshot, OrcaProcessReader, OrcaProcReads };
+export {
+ parseProcStatStartTicks,
+ defaultProcReads,
+ readProcessSnapshot,
+ readLinuxProcessSnapshot,
+};
+
+export interface OrcaRuntimeReceipt {
+ schemaVersion: 1;
+ runtimeId: string;
+ version: "1.4.230";
+ serverPid: number;
+ serverStartTicks: string;
+ nodeBinary: string;
+ serverEntry: string;
+ userData: string;
+ boundEndpoint: string;
+ advertisedEndpoint: string;
+ readyAt: string;
+}
+
+function absolutePath(value: unknown): string | null {
+ return typeof value === "string" && value.length > 0 && !value.includes("\0") && path.isAbsolute(value) ? value : null;
+}
+
+export function parseOrcaRuntimeReceipt(content: string): OrcaRuntimeReceipt | null {
+ let data: Record<string, unknown>;
+ try {
+ const parsed = JSON.parse(content);
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
+ data = parsed as Record<string, unknown>;
+ } catch {
+ return null;
+ }
+ if (data.schemaVersion !== 1) return null;
+ if (typeof data.runtimeId !== "string" || data.runtimeId.length === 0) return null;
+ if (data.version !== "1.4.230") return null;
+ if (typeof data.serverPid !== "number" || !Number.isInteger(data.serverPid) || data.serverPid <= 1) return null;
+ if (typeof data.serverStartTicks !== "string" || !/^\d+$/.test(data.serverStartTicks)) return null;
+ const nodeBinary = absolutePath(data.nodeBinary);
+ const serverEntry = absolutePath(data.serverEntry);
+ const userData = absolutePath(data.userData);
+ if (!nodeBinary || !serverEntry || !userData) return null;
+ if (typeof data.boundEndpoint !== "string" || typeof data.advertisedEndpoint !== "string") return null;
+ if (typeof data.readyAt !== "string" || data.readyAt.length === 0) return null;
+ return {
+ schemaVersion: 1,
+ runtimeId: data.runtimeId,
+ version: "1.4.230",
+ serverPid: data.serverPid,
+ serverStartTicks: data.serverStartTicks,
+ nodeBinary,
+ serverEntry,
+ userData,
+ boundEndpoint: data.boundEndpoint,
+ advertisedEndpoint: data.advertisedEndpoint,
+ readyAt: data.readyAt,
+ };
+}
+
+function isStrictlyInside(root: string, target: string): boolean {
+ const relative = path.relative(path.resolve(root), path.resolve(target));
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
+}
+
+/** Every receipt path must live inside the MSO-managed root: the release slot,
+ * the pinned node runtime, and the profile user-data directory. Nothing may point
+ * at a foreign process, a bare `node` on PATH, or the owner's personal profile. */
+export function receiptPathsAreContained(receipt: OrcaRuntimeReceipt, managedRoot: string): boolean {
+ if (!isStrictlyInside(managedRoot, receipt.serverEntry)) return false;
+ if (!isStrictlyInside(path.join(managedRoot, "releases"), receipt.serverEntry)) return false;
+ if (!isStrictlyInside(managedRoot, receipt.nodeBinary)) return false;
+ if (path.resolve(receipt.userData) !== path.join(path.resolve(managedRoot), "runtime", "user-data")) return false;
+ return true;
+}
+
+/** Lexical containment is not enough: a symlink inside `releases/` can still
+ * resolve to a foreign script. Resolve the receipt entry, the launched argv[1],
+ * the node binary, and the profile once, then require the real targets to remain
+ * inside the managed root/release slot and entry/argv to be the same file. */
+export async function verifyOrcaCanonicalIdentity(
+ receipt: OrcaRuntimeReceipt,
+ snapshot: OrcaProcessSnapshot | null,
+ managedRoot: string,
+): Promise<boolean> {
+ if (!snapshot || !receiptPathsAreContained(receipt, managedRoot)) return false;
+ const argv1 = snapshot.argv[1];
+ if (typeof argv1 !== "string" || !path.isAbsolute(argv1)) return false;
+ try {
+ const rootReal = await fs.realpath(managedRoot);
+ const [entryReal, argvReal, nodeReal, userReal] = await Promise.all([
+ fs.realpath(receipt.serverEntry),
+ fs.realpath(argv1),
+ fs.realpath(receipt.nodeBinary),
+ fs.realpath(receipt.userData),
+ ]);
+ return isStrictlyInside(rootReal, entryReal) &&
+ isStrictlyInside(path.join(rootReal, "releases"), entryReal) &&
+ entryReal === argvReal &&
+ isStrictlyInside(rootReal, nodeReal) &&
+ userReal === path.join(rootReal, "runtime", "user-data");
+ } catch {
+ return false;
+ }
+}
+
+/** PID, start time, owner UID, executable, and server script must all match. A
+ * reused or foreign PID that merely happens to be alive is refused. */
+export function verifyOrcaProcessIdentity(
+ receipt: OrcaRuntimeReceipt,
+ snapshot: OrcaProcessSnapshot | null,
+ managedRoot: string,
+): boolean {
+ if (!snapshot) return false;
+ if (!receiptPathsAreContained(receipt, managedRoot)) return false;
+ if (snapshot.pid !== receipt.serverPid) return false;
+ if (snapshot.startTicks !== receipt.serverStartTicks) return false;
+ if (typeof process.getuid === "function" && snapshot.uid !== process.getuid()) return false;
+
+ const expectedExe = path.resolve(receipt.nodeBinary);
+ const actualExe = path.resolve(snapshot.exe.replace(/ \(deleted\)$/, ""));
+ if (actualExe !== expectedExe) return false;
+ // argv[0] must be the exact node binary. Reject a missing or relative argv[0]
+ // BEFORE normalizing: `path.resolve` on an empty/relative value would consult
+ // the cwd and make the bundler trace the whole project.
+ const argv0 = snapshot.argv[0];
+ if (typeof argv0 !== "string" || !path.isAbsolute(argv0)) return false;
+ if (path.normalize(argv0) !== expectedExe) return false;
+ // The launched shape is `node <serverEntry> --bind ...`; an entry that appears
+ // anywhere else in argv is not proof of what this process was started to run.
+ const argv1 = snapshot.argv[1];
+ if (typeof argv1 !== "string" || !path.isAbsolute(argv1)) return false;
+ if (path.resolve(argv1) !== path.resolve(receipt.serverEntry)) return false;
+ return true;
+}
diff --git a/lib/managed-apps/orca-process-reader.ts b/lib/managed-apps/orca-process-reader.ts
new file mode 100644
index 00000000..be3e0892
--- /dev/null
+++ b/lib/managed-apps/orca-process-reader.ts
@@ -0,0 +1,113 @@
+import "server-only";
+import { promises as fs } from "node:fs";
+
+/**
+ * Kernel-level proof that the process named in the runtime-identity receipt is the
+ * exact owned node process MSO launched — not just "a live PID".
+ *
+ * Reads only /proc/PID/stat (comm-aware field 22), /proc/PID (owner uid), /proc/PID/exe
+ * and /proc/PID/cmdline. Never /proc/PID/environ or credentials. Any read failure
+ * (ENOENT, EPERM, hidepid) returns null: no proof ⇒ the bridge stays unavailable.
+ */
+export interface OrcaProcessSnapshot {
+ pid: number;
+ /** /proc/PID/stat field 22 — start time in clock ticks; changes on PID reuse. */
+ startTicks: string;
+ uid: number;
+ /** Canonical executable from /proc/PID/exe, `" (deleted)"` suffix stripped. */
+ exe: string;
+ /** /proc/PID/cmdline split on NUL, empty entries dropped. */
+ argv: string[];
+}
+
+export type OrcaProcessReader = (pid: number) => Promise<OrcaProcessSnapshot | null>;
+
+export interface OrcaProcReads {
+ stat: (pid: number) => Promise<string | null>;
+ uid: (pid: number) => Promise<number | null>;
+ exe: (pid: number) => Promise<string | null>;
+ argv: (pid: number) => Promise<string[] | null>;
+}
+
+/** Field 22 (`starttime`) of /proc/PID/stat. `comm` (field 2) is wrapped in
+ * parentheses and may itself contain spaces and `)` — parse from the LAST `)`. */
+export function parseProcStatStartTicks(stat: string): string | null {
+ const close = stat.lastIndexOf(")");
+ if (close < 0) return null;
+ const rest = stat.slice(close + 1).trim().split(/\s+/);
+ const value = rest[19];
+ return value && /^\d+$/.test(value) ? value : null;
+}
+
+const MAX_PROC_BYTES = 1_048_576;
+const MAX_ARGV_ENTRIES = 4096;
+
+async function readBounded(path: string, maxBytes = MAX_PROC_BYTES): Promise<string | null> {
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
+ try {
+ handle = await fs.open(path, "r");
+ const chunks: Buffer[] = [];
+ let total = 0;
+ for (;;) {
+ const chunk = Buffer.alloc(65_536);
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
+ if (bytesRead === 0) break;
+ total += bytesRead;
+ if (total > maxBytes) return null;
+ chunks.push(chunk.subarray(0, bytesRead));
+ }
+ return Buffer.concat(chunks).toString("utf-8");
+ } catch {
+ return null;
+ } finally {
+ await handle?.close().catch(() => {});
+ }
+}
+
+export const defaultProcReads: OrcaProcReads = {
+ stat: (pid) => readBounded(`/proc/${pid}/stat`),
+ uid: async (pid) => {
+ try {
+ return (await fs.stat(`/proc/${pid}`)).uid;
+ } catch {
+ return null;
+ }
+ },
+ exe: async (pid) => {
+ try {
+ return await fs.readlink(`/proc/${pid}/exe`);
+ } catch {
+ return null;
+ }
+ },
+ argv: async (pid) => {
+ const raw = await readBounded(`/proc/${pid}/cmdline`);
+ if (raw === null) return null;
+ const argv = raw.split("\0").filter((argument) => argument.length > 0);
+ return argv.length === 0 || argv.length > MAX_ARGV_ENTRIES ? null : argv;
+ },
+};
+
+/** Re-read /proc/PID/stat after the metadata snapshot so a PID reused mid-read can
+ * never produce a composite identity. Injectable only for the reuse regression test. */
+export async function readProcessSnapshot(
+ pid: number,
+ reads: OrcaProcReads = defaultProcReads,
+): Promise<OrcaProcessSnapshot | null> {
+ if (!Number.isInteger(pid) || pid <= 1) return null;
+ const stat = await reads.stat(pid).catch(() => null);
+ const startTicks = stat ? parseProcStatStartTicks(stat) : null;
+ if (!startTicks) return null;
+ const [uid, exe, argv] = await Promise.all([
+ reads.uid(pid).catch(() => null),
+ reads.exe(pid).catch(() => null),
+ reads.argv(pid).catch(() => null),
+ ]);
+ if (uid === null || exe === null || argv === null) return null;
+ const confirm = await reads.stat(pid).catch(() => null);
+ if (!confirm || parseProcStatStartTicks(confirm) !== startTicks) return null;
+ return { pid, startTicks, uid, exe: exe.replace(/ \(deleted\)$/, ""), argv };
+}
+
+export const readLinuxProcessSnapshot: OrcaProcessReader = (pid) =>
+ readProcessSnapshot(pid, defaultProcReads);
diff --git a/lib/managed-apps/orca-readiness-identity.test.ts b/lib/managed-apps/orca-readiness-identity.test.ts
new file mode 100644
index 00000000..cd362e78
--- /dev/null
+++ b/lib/managed-apps/orca-readiness-identity.test.ts
@@ -0,0 +1,215 @@
+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { getOrcaReadiness, type OrcaReadinessDeps } from "./orca-readiness";
+import { buildOrcaWebClientUrl } from "./orca-pairing";
+import type { OrcaProcessReader, OrcaProcessSnapshot } from "./orca-process-identity";
+
+vi.hoisted(() => {
+ process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com";
+ process.env.OS_PUBLIC_ORIGIN = "https://mso.example.com";
+ process.env.OS_SESSION_SECRET = "s".repeat(32);
+});
+
+const ORIGIN = "https://orca.mso.example.com";
+
+function pairingUrl(): string {
+ const payload = { v: 2, endpoint: "wss://orca.mso.example.com", deviceToken: "dev_tok_12345", publicKeyB64: "pub_key_12345", scope: "runtime" };
+ const b64 = Buffer.from(JSON.stringify(payload)).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+ return `orca://pair?code=${b64}`;
+}
+
+function statusPayload(overrides: Record<string, any> = {}): Record<string, any> {
+ return {
+ type: "orca_server_ready",
+ schemaVersion: 1,
+ runtimeId: "rt_abcd1234efgh5678",
+ boundEndpoint: "ws://127.0.0.1:6769",
+ advertisedEndpoint: "wss://orca.mso.example.com",
+ pairing: { available: true, scope: "runtime", url: pairingUrl() },
+ health: {
+ buildVersion: "1.4.230",
+ nodeVersion: "24.21.0",
+ nodeAbi: "137",
+ pid: 4242,
+ terminalDaemon: { state: "live", ownsFreshSessions: true, selfTest: { ok: true, verdict: "healthy" } },
+ },
+ ...overrides,
+ };
+}
+
+describe("getOrcaReadiness filesystem and process identity gate", () => {
+ let root: string;
+ const snapshots = new Map<number, OrcaProcessSnapshot>();
+ const reader: OrcaProcessReader = async (pid) => snapshots.get(pid) ?? null;
+ const binding = async () => ({
+ ok: true as const,
+ binding: { family: "ipv4" as const, address: "127.0.0.1", port: 6769, inode: "424242" },
+ });
+ const deps = (over: OrcaReadinessDeps = {}): OrcaReadinessDeps => ({
+ readProcess: reader,
+ readBinding: binding,
+ ...over,
+ });
+
+ function validReceipt(over: Record<string, unknown> = {}): Record<string, unknown> {
+ return {
+ schemaVersion: 1,
+ runtimeId: "rt_abcd1234efgh5678",
+ version: "1.4.230",
+ serverPid: 4242,
+ serverStartTicks: "99887766",
+ nodeBinary: path.join(root, "runtimes", "node-24.21.0", "bin", "node"),
+ serverEntry: path.join(root, "releases", "1.4.230", "orcad-server.js"),
+ userData: path.join(root, "runtime", "user-data"),
+ boundEndpoint: "ws://127.0.0.1:6769",
+ advertisedEndpoint: "wss://orca.mso.example.com",
+ readyAt: "2026-10-19T10:00:00.000Z",
+ ...over,
+ };
+ }
+
+ function snapshot(over: Partial<OrcaProcessSnapshot> = {}): OrcaProcessSnapshot {
+ const nodeBinary = path.join(root, "runtimes", "node-24.21.0", "bin", "node");
+ return {
+ pid: 4242,
+ startTicks: "99887766",
+ uid: typeof process.getuid === "function" ? process.getuid() : 1000,
+ exe: nodeBinary,
+ argv: [nodeBinary, path.join(root, "releases", "1.4.230", "orcad-server.js"), "--json"],
+ ...over,
+ };
+ }
+
+ const writeStatus = (content: unknown) => writeFile(path.join(root, "private-status.json"), JSON.stringify(content), { mode: 0o600 });
+ const writeReceipt = (content: unknown) => writeFile(path.join(root, "runtime-identity.json"), JSON.stringify(content), { mode: 0o600 });
+
+ beforeEach(async () => {
+ root = await mkdtemp(path.join(os.tmpdir(), "mso-orca-readiness-"));
+ await chmod(root, 0o700);
+ // The canonical identity proof resolves these receipt paths, so they must exist.
+ await mkdir(path.join(root, "runtimes", "node-24.21.0", "bin"), { recursive: true });
+ await writeFile(path.join(root, "runtimes", "node-24.21.0", "bin", "node"), "", { mode: 0o755 });
+ await mkdir(path.join(root, "releases", "1.4.230"), { recursive: true });
+ await writeFile(path.join(root, "releases", "1.4.230", "orcad-server.js"), "", { mode: 0o600 });
+ await mkdir(path.join(root, "runtime", "user-data"), { recursive: true });
+ process.env.ORCA_HOME = root;
+ snapshots.clear();
+ snapshots.set(4242, snapshot());
+ });
+
+ afterAll(async () => {
+ delete process.env.ORCA_HOME;
+ if (root) await rm(root, { recursive: true, force: true });
+ });
+
+ it("returns available only with a valid status, valid receipt, and matching owned process", async () => {
+ await writeStatus(statusPayload());
+ await writeReceipt(validReceipt());
+ const res = await getOrcaReadiness(deps());
+ expect(res.available).toBe(true);
+ if (res.available) {
+ expect(res.webClientUrl).toBe(buildOrcaWebClientUrl(ORIGIN, pairingUrl()));
+ expect(res.startTicks).toBe("99887766");
+ }
+ });
+
+ it("rejects a release entry that symlinks to a foreign script", async () => {
+ const entry = path.join(root, "releases", "1.4.230", "orcad-server.js");
+ const foreign = path.join(root, "foreign.js");
+ await writeFile(foreign, "", { mode: 0o600 });
+ await rm(entry);
+ await symlink(foreign, entry);
+ await writeStatus(statusPayload());
+ await writeReceipt(validReceipt());
+ expect(await getOrcaReadiness(deps())).toMatchObject({
+ available: false,
+ reason: "process_identity_mismatch",
+ });
+ });
+
+ it("denies when the owned process does not own the exact LISTEN socket", async () => {
+ await writeStatus(statusPayload());
+ await writeReceipt(validReceipt());
+ const res = await getOrcaReadiness(deps({
+ readBinding: async () => ({ ok: false, reason: "listener_not_owned_by_process" }),
+ }));
+ expect(res).toMatchObject({ available: false, reason: "listener_not_owned_by_process" });
+ });
+
+ it("fails with a clear reason when ORCA_HOME is invalid (no silent fallback)", async () => {
+ process.env.ORCA_HOME = "relative/orca";
+ await expect(getOrcaReadiness(deps())).resolves.toMatchObject({ available: false, reason: "managed_root_invalid" });
+ process.env.ORCA_HOME = root;
+ });
+
+ it("denies a missing or insecure status file", async () => {
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "status_file_missing" });
+ await writeStatus({});
+ await chmod(path.join(root, "private-status.json"), 0o644);
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "status_file_insecure" });
+ });
+
+ it("requires a mandatory secure runtime-identity.json (never optional)", async () => {
+ await writeStatus(statusPayload());
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "runtime_identity_missing" });
+ await writeReceipt(validReceipt());
+ await chmod(path.join(root, "runtime-identity.json"), 0o644);
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "runtime_identity_insecure" });
+ });
+
+ it("rejects a receipt that does not match the status or the managed root", async () => {
+ await writeStatus(statusPayload());
+ await writeReceipt(validReceipt({ runtimeId: "rt_other" }));
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "runtime_identity_mismatch" });
+ await writeReceipt(validReceipt({ serverEntry: "/tmp/orcad-server.js" }));
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "runtime_identity_mismatch" });
+ await writeReceipt(validReceipt({ advertisedEndpoint: "wss://evil.example.com" }));
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "runtime_identity_mismatch" });
+ });
+
+ it("denies when the process identity cannot be read, or is reused/foreign/mismatched", async () => {
+ await writeStatus(statusPayload());
+ await writeReceipt(validReceipt());
+ snapshots.clear();
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "process_identity_unavailable" });
+ snapshots.set(4242, snapshot({ startTicks: "1" }));
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "process_identity_mismatch" });
+ snapshots.set(4242, snapshot({ exe: "/usr/bin/node" }));
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "process_identity_mismatch" });
+ });
+
+ it("binds receipt.serverPid to status.health.pid", async () => {
+ await writeStatus(statusPayload());
+ await writeReceipt(validReceipt({ serverPid: 5555 }));
+ snapshots.set(5555, snapshot({ pid: 5555 }));
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "runtime_identity_mismatch" });
+ });
+
+ it("fails closed on a symlinked status file", async () => {
+ const target = path.join(root, "real-status.json");
+ await writeFile(target, JSON.stringify(statusPayload()), { mode: 0o600 });
+ await symlink(target, path.join(root, "private-status.json"));
+ expect(await getOrcaReadiness(deps())).toMatchObject({ available: false, reason: "status_file_insecure" });
+ });
+
+ it("ignores the test runner's own PID as an Orca identity", async () => {
+ const runnerPayload = statusPayload();
+ runnerPayload.health.pid = process.pid;
+ await writeStatus(runnerPayload);
+ const receipt = validReceipt({ serverPid: process.pid });
+ await writeReceipt(receipt);
+ const runnerReader: OrcaProcessReader = async () => ({
+ pid: process.pid,
+ startTicks: "99887766",
+ uid: typeof process.getuid === "function" ? process.getuid() : 1000,
+ exe: process.execPath,
+ argv: [process.execPath, receipt.serverEntry as string, "--json"],
+ });
+ expect(await getOrcaReadiness(deps({ readProcess: runnerReader }))).toMatchObject({ available: false, reason: "process_identity_mismatch" });
+ });
+});
diff --git a/lib/managed-apps/orca-readiness-parse.ts b/lib/managed-apps/orca-readiness-parse.ts
new file mode 100644
index 00000000..35707697
--- /dev/null
+++ b/lib/managed-apps/orca-readiness-parse.ts
@@ -0,0 +1,131 @@
+import "server-only";
+import { buildOrcaWebClientUrl, validateOrcaPairingUrl } from "./orca-pairing";
+
+export interface OrcaReadinessSuccess {
+ available: true;
+ pairingUrl: string;
+ webClientUrl: string;
+ runtimeId: string;
+ serverPid: number;
+ /** Kernel start ticks for `serverPid`; present on verified readiness. */
+ startTicks?: string;
+ /** LISTEN socket inode bound to `serverPid`; present on verified readiness. */
+ listenerInode?: string;
+ boundEndpoint: string;
+ advertisedEndpoint: string;
+}
+
+export interface OrcaReadinessUnavailable {
+ available: false;
+ reason: string;
+}
+
+export type OrcaReadinessResult = OrcaReadinessSuccess | OrcaReadinessUnavailable;
+
+export const ORCA_VERSION = "1.4.230";
+export const ORCA_NODE_VERSION = "24.21.0";
+export const ORCA_NODE_ABI = "137";
+export const DEFAULT_MANAGED_PORT = 6769;
+const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
+
+export const deny = (reason: string): OrcaReadinessUnavailable => ({ available: false, reason });
+
+/** Managed port comes from config (default 6769), never a hardcoded user-port block. */
+export function orcaManagedPort(env: Record<string, string | undefined> = process.env): number {
+ const raw = env.ORCA_DASHBOARD_URL;
+ if (raw) {
+ try {
+ const url = new URL(raw);
+ const port = Number(url.port || (url.protocol === "https:" ? 443 : url.protocol === "http:" ? 80 : NaN));
+ if (Number.isInteger(port) && port > 0 && port <= 65535) return port;
+ } catch {
+ /* fall through to the default */
+ }
+ }
+ return DEFAULT_MANAGED_PORT;
+}
+
+function parseLoopbackWs(value: unknown, managedPort: number): "ok" | "malformed" | "non_loopback" | "bad_port" {
+ if (typeof value !== "string") return "malformed";
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return "malformed";
+ }
+ if (url.protocol !== "ws:" || url.username || url.password) return "malformed";
+ if ((url.pathname !== "" && url.pathname !== "/") || url.search || url.hash) return "malformed";
+ if (!LOOPBACK_HOSTS.has(url.hostname.toLowerCase())) return "non_loopback";
+ if (Number(url.port) !== managedPort) return "bad_port";
+ return "ok";
+}
+
+function advertisedMatches(value: unknown, origin: string): "ok" | "malformed" | "mismatch" {
+ if (typeof value !== "string") return "malformed";
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return "malformed";
+ }
+ if (url.protocol !== "wss:" || url.username || url.password) return "mismatch";
+ if ((url.pathname !== "" && url.pathname !== "/") || url.search || url.hash) return "mismatch";
+ const expected = `${new URL(origin).host.toLowerCase()}`;
+ return url.host.toLowerCase() === expected ? "ok" : "mismatch";
+}
+
+export async function parseOrcaPrivateStatus(
+ content: string,
+ origin: string,
+ managedPort: number = orcaManagedPort(),
+): Promise<OrcaReadinessResult> {
+ let data: Record<string, any>;
+ try {
+ const parsed = JSON.parse(content);
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return deny("invalid_json");
+ data = parsed as Record<string, any>;
+ } catch {
+ return deny("invalid_json");
+ }
+
+ if (data.type !== "orca_server_ready") return deny("unexpected_status_type");
+ if (data.schemaVersion !== 1) return deny("unsupported_status_schema");
+ if (typeof data.runtimeId !== "string" || !data.runtimeId.trim()) return deny("missing_runtime_id");
+
+ const health = data.health;
+ if (!health || typeof health !== "object") return deny("incompatible_version");
+ // The REAL health buildVersion is authoritative; `artifactVersion` never overrides it.
+ if (health.buildVersion !== ORCA_VERSION) return deny("incompatible_version");
+ if (String(health.nodeVersion) !== ORCA_NODE_VERSION) return deny("incompatible_node_version");
+ if (String(health.nodeAbi) !== ORCA_NODE_ABI) return deny("incompatible_node_abi");
+ if (!Number.isInteger(health.pid) || health.pid <= 1) return deny("missing_health_pid");
+ const daemon = health.terminalDaemon;
+ if (!daemon || daemon.state !== "live" || daemon.ownsFreshSessions !== true || daemon.selfTest?.ok !== true) {
+ return deny("terminal_daemon_unhealthy");
+ }
+
+ const bound = parseLoopbackWs(data.boundEndpoint, managedPort);
+ if (bound === "malformed") return deny("malformed_bound_endpoint");
+ if (bound === "non_loopback") return deny("non_loopback_bound_endpoint");
+ if (bound === "bad_port") return deny("unexpected_bound_port");
+
+ if (data.advertisedEndpoint === undefined) return deny("missing_advertised_endpoint");
+ const advertised = advertisedMatches(data.advertisedEndpoint, origin);
+ if (advertised === "malformed") return deny("malformed_advertised_endpoint");
+ if (advertised === "mismatch") return deny("advertised_origin_mismatch");
+
+ const pairing = data.pairing;
+ if (!pairing || pairing.available !== true || pairing.scope !== "runtime") return deny("pairing_unavailable");
+ if (typeof pairing.url !== "string") return deny("missing_pairing_url");
+ if (!validateOrcaPairingUrl(pairing.url, origin)) return deny("invalid_pairing_offer");
+
+ return {
+ available: true,
+ pairingUrl: pairing.url,
+ webClientUrl: buildOrcaWebClientUrl(origin, pairing.url),
+ runtimeId: data.runtimeId,
+ serverPid: health.pid,
+ boundEndpoint: data.boundEndpoint,
+ advertisedEndpoint: data.advertisedEndpoint,
+ };
+}
diff --git a/lib/managed-apps/orca-readiness.test.ts b/lib/managed-apps/orca-readiness.test.ts
new file mode 100644
index 00000000..a6073c6a
--- /dev/null
+++ b/lib/managed-apps/orca-readiness.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+vi.hoisted(() => {
+ process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com";
+ process.env.OS_PUBLIC_ORIGIN = "https://mso.example.com";
+ process.env.OS_SESSION_SECRET = "s".repeat(32);
+});
+
+import { parseOrcaPrivateStatus } from "./orca-readiness";
+import { buildOrcaWebClientUrl } from "./orca-pairing";
+
+const ORIGIN = "https://orca.mso.example.com";
+
+function pairingUrl(): string {
+ const payload = { v: 2, endpoint: "wss://orca.mso.example.com", deviceToken: "dev_tok_12345", publicKeyB64: "pub_key_12345", scope: "runtime" };
+ const b64 = Buffer.from(JSON.stringify(payload)).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+ return `orca://pair?code=${b64}`;
+}
+
+function payload(overrides: Record<string, any> = {}): Record<string, any> {
+ return {
+ type: "orca_server_ready",
+ schemaVersion: 1,
+ runtimeId: "rt_abcd1234efgh5678",
+ boundEndpoint: "ws://127.0.0.1:6769",
+ advertisedEndpoint: "wss://orca.mso.example.com",
+ pairing: { available: true, scope: "runtime", url: pairingUrl(), webClientUrl: "https://orca.mso.example.com/?token=leak" },
+ health: {
+ buildVersion: "1.4.230",
+ nodeVersion: "24.21.0",
+ nodeAbi: "137",
+ pid: 4242,
+ terminalDaemon: { state: "live", ownsFreshSessions: true, selfTest: { ok: true, verdict: "healthy" } },
+ },
+ ...overrides,
+ };
+}
+
+describe("parseOrcaPrivateStatus schema and endpoint invariants", () => {
+ it("accepts the exact tagged schema and ignores artifactVersion as an override", async () => {
+ const res = await parseOrcaPrivateStatus(JSON.stringify(payload({ artifactVersion: "9.9.9" })), ORIGIN);
+ expect(res.available).toBe(true);
+ if (res.available) {
+ expect(res.runtimeId).toBe("rt_abcd1234efgh5678");
+ expect(res.serverPid).toBe(4242);
+ expect(res.webClientUrl).toBe(buildOrcaWebClientUrl(ORIGIN, pairingUrl()));
+ }
+ });
+
+ it("requires the exact readiness tag and health buildVersion (no artifactVersion fallback)", async () => {
+ expect(await parseOrcaPrivateStatus(JSON.stringify(payload({ type: "orca_other" })), ORIGIN)).toMatchObject({ available: false, reason: "unexpected_status_type" });
+ expect(await parseOrcaPrivateStatus(JSON.stringify(payload({ schemaVersion: 2 })), ORIGIN)).toMatchObject({ available: false, reason: "unsupported_status_schema" });
+ const forged = payload({ artifactVersion: "1.4.230" });
+ forged.health.buildVersion = "1.4.229";
+ expect(await parseOrcaPrivateStatus(JSON.stringify(forged), ORIGIN)).toMatchObject({ available: false, reason: "incompatible_version" });
+ });
+
+ it("requires the pinned Node version and ABI", async () => {
+ const badNode = payload();
+ badNode.health.nodeVersion = "26.7.0";
+ expect(await parseOrcaPrivateStatus(JSON.stringify(badNode), ORIGIN)).toMatchObject({ available: false, reason: "incompatible_node_version" });
+ const badAbi = payload();
+ badAbi.health.nodeAbi = "115";
+ expect(await parseOrcaPrivateStatus(JSON.stringify(badAbi), ORIGIN)).toMatchObject({ available: false, reason: "incompatible_node_abi" });
+ });
+
+ it("requires a ws loopback bound endpoint with no credentials, path, query, or hash", async () => {
+ expect(await parseOrcaPrivateStatus(JSON.stringify(payload()), ORIGIN)).toMatchObject({ available: true });
+ for (const boundEndpoint of ["http://127.0.0.1:6769", "ws://127.0.0.1:6769/foo", "ws://u:[email protected]:6769", "ws://127.0.0.1:6769?x=1", "ws://127.0.0.1:6769#f"]) {
+ expect(await parseOrcaPrivateStatus(JSON.stringify(payload({ boundEndpoint })), ORIGIN)).toMatchObject({ available: false, reason: "malformed_bound_endpoint" });
+ }
+ expect(await parseOrcaPrivateStatus(JSON.stringify(payload({ boundEndpoint: "ws://0.0.0.0:6769" })), ORIGIN)).toMatchObject({ available: false, reason: "non_loopback_bound_endpoint" });
+ expect(await parseOrcaPrivateStatus(JSON.stringify(payload({ boundEndpoint: "ws://127.0.0.1:6768" })), ORIGIN)).toMatchObject({ available: false, reason: "unexpected_bound_port" });
+ });
+
+ it("requires an exact wss advertised endpoint on the configured origin", async () => {
+ const cases: Array<[string, string]> = [
+ ["ws://orca.mso.example.com", "advertised_origin_mismatch"],
+ ["https://orca.mso.example.com", "advertised_origin_mismatch"],
+ ["wss://evil.example.com", "advertised_origin_mismatch"],
+ ["wss://orca.mso.example.com/socket", "advertised_origin_mismatch"],
+ ["wss://orca.mso.example.com?x=1", "advertised_origin_mismatch"],
+ ["wss://[email protected]", "advertised_origin_mismatch"],
+ ["not a url", "malformed_advertised_endpoint"],
+ ];
+ for (const [advertisedEndpoint, reason] of cases) {
+ expect(await parseOrcaPrivateStatus(JSON.stringify(payload({ advertisedEndpoint })), ORIGIN)).toMatchObject({ available: false, reason });
+ }
+ });
+
+ it("requires live terminal daemon and explicit runtime pairing scope", async () => {
+ const degraded = payload();
+ degraded.health.terminalDaemon.state = "degraded";
+ expect(await parseOrcaPrivateStatus(JSON.stringify(degraded), ORIGIN)).toMatchObject({ available: false, reason: "terminal_daemon_unhealthy" });
+ expect(await parseOrcaPrivateStatus(JSON.stringify(payload({ pairing: { available: false, scope: "runtime", url: pairingUrl() } })), ORIGIN)).toMatchObject({ available: false, reason: "pairing_unavailable" });
+ expect(await parseOrcaPrivateStatus(JSON.stringify(payload({ pairing: { available: true, url: pairingUrl() } })), ORIGIN)).toMatchObject({ available: false, reason: "pairing_unavailable" });
+ expect(await parseOrcaPrivateStatus(JSON.stringify(payload({ pairing: { available: true, scope: "mobile", url: pairingUrl() } })), ORIGIN)).toMatchObject({ available: false, reason: "pairing_unavailable" });
+ });
+
+ it("never trusts an upstream webClientUrl and never exposes a query secret", async () => {
+ const res = await parseOrcaPrivateStatus(JSON.stringify(payload()), ORIGIN);
+ expect(res.available).toBe(true);
+ if (res.available) {
+ const parsed = new URL(res.webClientUrl);
+ expect(parsed.pathname).toBe("/web-index.html");
+ expect(parsed.search).toBe("");
+ expect(res.webClientUrl).not.toContain("token=leak");
+ }
+ });
+});
diff --git a/lib/managed-apps/orca-readiness.ts b/lib/managed-apps/orca-readiness.ts
new file mode 100644
index 00000000..17aa15fe
--- /dev/null
+++ b/lib/managed-apps/orca-readiness.ts
@@ -0,0 +1,120 @@
+/**
+ * Server-only Orca private readiness parser and bridge.
+ *
+ * Fail-closed: the bridge is available ONLY when the upstream `orca_server_ready`
+ * readiness tag, the MSO runtime-identity receipt, and the actual owned kernel
+ * process all agree. Any missing, stale, reused, foreign, or unreadable identity
+ * denies. No fallback to a static asset check, a bare live PID, or a personal
+ * `~/.orca` profile.
+ */
+import "server-only";
+import { managedAppOrigin } from "./origin";
+import { readOrcaPrivateFile, resolveOrcaManagedRoot } from "./orca-private-fs";
+import {
+ parseOrcaRuntimeReceipt,
+ readLinuxProcessSnapshot,
+ receiptPathsAreContained,
+ verifyOrcaProcessIdentity,
+ verifyOrcaCanonicalIdentity,
+ type OrcaProcessReader,
+} from "./orca-process-identity";
+import { verifyOrcaListenerBinding, type OrcaListenerBindingResult } from "./orca-runtime-binding";
+import {
+ ORCA_VERSION,
+ deny,
+ orcaManagedPort,
+ parseOrcaPrivateStatus,
+ type OrcaReadinessResult,
+} from "./orca-readiness-parse";
+
+export {
+ DEFAULT_MANAGED_PORT,
+ ORCA_NODE_ABI,
+ ORCA_NODE_VERSION,
+ ORCA_VERSION,
+ deny,
+ orcaManagedPort,
+ parseOrcaPrivateStatus,
+ type OrcaReadinessResult,
+ type OrcaReadinessSuccess,
+ type OrcaReadinessUnavailable,
+} from "./orca-readiness-parse";
+
+export interface OrcaBindingInput {
+ pid: number;
+ startTicks: string;
+ boundEndpoint: string;
+}
+export type OrcaBindingReader = (input: OrcaBindingInput) => Promise<OrcaListenerBindingResult>;
+export interface OrcaReadinessDeps {
+ env?: NodeJS.ProcessEnv;
+ readProcess?: OrcaProcessReader;
+ readBinding?: OrcaBindingReader;
+}
+
+/** The verified bound endpoint's literal numeric loopback listener must be owned by
+ * the receipt PID. A named host (`localhost`) is never resolved as a fallback. */
+const defaultBindingReader: OrcaBindingReader = async ({ pid, startTicks, boundEndpoint }) => {
+ let url: URL;
+ try {
+ url = new URL(boundEndpoint);
+ } catch {
+ return { ok: false, reason: "bound_endpoint_invalid" };
+ }
+ if (url.protocol !== "ws:" || url.username || url.password) {
+ return { ok: false, reason: "bound_endpoint_invalid" };
+ }
+ return verifyOrcaListenerBinding({ pid, startTicks, host: url.hostname, port: Number(url.port) });
+};
+
+export async function getOrcaReadiness(deps: OrcaReadinessDeps = {}): Promise<OrcaReadinessResult> {
+ const origin = managedAppOrigin("orca");
+ if (!origin) return deny("origin_unavailable");
+ const env = deps.env ?? process.env;
+
+ const rootResult = resolveOrcaManagedRoot(env);
+ if (!rootResult.ok) return deny("managed_root_invalid");
+ const root = rootResult.root;
+
+ const statusRead = await readOrcaPrivateFile(root, "private-status.json");
+ if (!statusRead.ok) return deny(statusRead.reason === "missing" ? "status_file_missing" : "status_file_insecure");
+ const managedPort = orcaManagedPort(env);
+ const parsed = await parseOrcaPrivateStatus(statusRead.text, origin, managedPort);
+ if (!parsed.available) return parsed;
+
+ // The runtime-identity receipt is MANDATORY: a readiness file alone is not ownership proof.
+ const identityRead = await readOrcaPrivateFile(root, "runtime-identity.json");
+ if (!identityRead.ok) return deny(identityRead.reason === "missing" ? "runtime_identity_missing" : "runtime_identity_insecure");
+ const receipt = parseOrcaRuntimeReceipt(identityRead.text);
+ if (!receipt) return deny("runtime_identity_invalid");
+ if (!receiptPathsAreContained(receipt, root)) return deny("runtime_identity_mismatch");
+ if (receipt.runtimeId !== parsed.runtimeId || receipt.version !== ORCA_VERSION) return deny("runtime_identity_mismatch");
+ if (receipt.serverPid !== parsed.serverPid) return deny("runtime_identity_mismatch");
+ if (receipt.boundEndpoint !== parsed.boundEndpoint || receipt.advertisedEndpoint !== parsed.advertisedEndpoint) {
+ return deny("runtime_identity_mismatch");
+ }
+
+ const readProcess = deps.readProcess ?? readLinuxProcessSnapshot;
+ const snapshot = await readProcess(receipt.serverPid);
+ if (!snapshot) return deny("process_identity_unavailable");
+ if (!verifyOrcaProcessIdentity(receipt, snapshot, root)) return deny("process_identity_mismatch");
+ if (!await verifyOrcaCanonicalIdentity(receipt, snapshot, root)) return deny("process_identity_mismatch");
+
+ const readBinding = deps.readBinding ?? defaultBindingReader;
+ const binding = await readBinding({
+ pid: snapshot.pid,
+ startTicks: snapshot.startTicks,
+ boundEndpoint: parsed.boundEndpoint,
+ });
+ if (!binding.ok) return deny(binding.reason);
+
+ // The listener proof has its own process checks, but readiness must not return a
+ // stale composite: re-read the exact process (exe, argv, uid, canonical entry) and
+ // require the same start ticks before claiming the runtime.
+ const confirmed = await readProcess(receipt.serverPid);
+ if (!confirmed || confirmed.startTicks !== snapshot.startTicks) return deny("process_identity_unavailable");
+ if (!verifyOrcaProcessIdentity(receipt, confirmed, root)) return deny("process_identity_mismatch");
+ if (!await verifyOrcaCanonicalIdentity(receipt, confirmed, root)) return deny("process_identity_mismatch");
+
+ return { ...parsed, startTicks: confirmed.startTicks, listenerInode: binding.binding.inode };
+}
diff --git a/lib/managed-apps/orca-reviewed-schema.test.ts b/lib/managed-apps/orca-reviewed-schema.test.ts
new file mode 100644
index 00000000..e730eee5
--- /dev/null
+++ b/lib/managed-apps/orca-reviewed-schema.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+import os from "node:os";
+import path from "node:path";
+import { resolveOrcaManagedRoot } from "./orca-private-fs";
+import { validateOrcaPairingUrl } from "./orca-pairing";
+
+const HOME = os.homedir();
+const INVALID_ROOT = { ok: false, reason: "managed_root_invalid" } as const;
+
+describe("Orca managed root parity with scripts/orca/managed-paths.mjs", () => {
+ it("keeps the portable default inside the owner home but outside personal Orca state", () => {
+ expect(resolveOrcaManagedRoot({})).toEqual({
+ ok: true,
+ root: path.join(HOME, ".local", "share", "mso", "orca"),
+ });
+ });
+
+ it("accepts a clean absolute ORCA_HOME", () => {
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "/srv/mso/orca" })).toEqual({
+ ok: true,
+ root: "/srv/mso/orca",
+ });
+ });
+
+ it.each([
+ ["filesystem root", "/"],
+ ["home directory", HOME],
+ ["personal .orca", path.join(HOME, ".orca")],
+ ["personal .orca subtree", path.join(HOME, ".orca", "nested")],
+ ["personal .orca-remote", path.join(HOME, ".orca-remote")],
+ ["personal .orca-remote subtree", path.join(HOME, ".orca-remote", "nested")],
+ ["relative path", "relative/orca"],
+ ["dot-dot traversal", "/srv/../etc/orca"],
+ ["empty override", ""],
+ ["blank override", " "],
+ ])("refuses the unsafe %s", (_label, root) => {
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: root })).toEqual(INVALID_ROOT);
+ });
+
+ it.each([
+ ["trailing slash", "/srv/mso/orca/"],
+ ["duplicate slash", "/srv//mso/orca"],
+ ["dot segment", "/srv/mso/./orca"],
+ ["newline control character", "/srv/orca\n"],
+ ["carriage-return control character", "/srv/orca\r"],
+ ["NUL control character", "/srv\0orca"],
+ ])("refuses the dirty %s spelling", (_label, root) => {
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: root })).toEqual(INVALID_ROOT);
+ });
+});
+
+const ORIGIN = "https://orca.mso.example.com";
+const WSS_ENDPOINT = "wss://orca.mso.example.com";
+
+function encode(payload: Record<string, unknown>): string {
+ const b64 = Buffer.from(JSON.stringify(payload), "utf-8")
+ .toString("base64")
+ .replace(/\+/g, "-")
+ .replace(/\//g, "_")
+ .replace(/=+$/, "");
+ return `orca://pair?code=${b64}`;
+}
+
+function offer(overrides: Record<string, unknown> = {}): string {
+ return encode({
+ v: 2,
+ endpoint: WSS_ENDPOINT,
+ deviceToken: "token_1234567890abcdef",
+ publicKeyB64: "pubkey_b64_xyz123",
+ scope: "runtime",
+ ...overrides,
+ });
+}
+
+describe("Orca pairing schema refuses grant claims by property presence", () => {
+ it("still accepts the existing runtime offer with no optional fields", () => {
+ expect(validateOrcaPairingUrl(offer(), ORIGIN)).not.toBeNull();
+ });
+
+ it.each([
+ ["true", true],
+ ["false", false],
+ ["null", null],
+ ["string", "desktop-control"],
+ ["object", { desktop: true }],
+ ["empty array", []],
+ ["non-empty array", ["desktop-control"]],
+ ])("refuses a %s grants property instead of truthiness-checking it", (_label, grants) => {
+ expect(validateOrcaPairingUrl(offer({ grants }), ORIGIN)).toBeNull();
+ });
+
+ it.each([
+ ["true", true],
+ ["false", false],
+ ["null", null],
+ ["string", "false"],
+ ["object", {}],
+ ["empty array", []],
+ ])("refuses a %s desktopControl property instead of truthiness-checking it", (_label, desktopControl) => {
+ expect(validateOrcaPairingUrl(offer({ desktopControl }), ORIGIN)).toBeNull();
+ });
+
+ it.each([
+ ["true", true],
+ ["false", false],
+ ["null", null],
+ ["string", "no"],
+ ["object", { enabled: false }],
+ ["empty array", []],
+ ])("refuses a %s grantDesktopControl property instead of truthiness-checking it", (_label, grantDesktopControl) => {
+ expect(validateOrcaPairingUrl(offer({ grantDesktopControl }), ORIGIN)).toBeNull();
+ });
+
+ it("still refuses relay offers by property presence", () => {
+ expect(validateOrcaPairingUrl(offer({ relay: { url: "wss://relay.example.com" } }), ORIGIN)).toBeNull();
+ expect(validateOrcaPairingUrl(offer({ relayUrl: "" }), ORIGIN)).toBeNull();
+ });
+});
diff --git a/lib/managed-apps/orca-reviewed-unit.test.ts b/lib/managed-apps/orca-reviewed-unit.test.ts
new file mode 100644
index 00000000..7474bf81
--- /dev/null
+++ b/lib/managed-apps/orca-reviewed-unit.test.ts
@@ -0,0 +1,208 @@
+// Regressions for the exact MSO-owned Orca unit proof and strict quiescence.
+// Fixtures use the REAL renderer + REAL installer config builder, with a
+// launcher hostNode deliberately different from release.nodeBinary.
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+vi.mock("server-only", () => ({}));
+vi.mock("./runner", () => ({ runProgram: vi.fn(), commandExists: vi.fn().mockResolvedValue(false), resolveCommand: vi.fn().mockResolvedValue(null), requireProgram: vi.fn() }));
+vi.mock("./user-bus", () => ({ userBusEnv: vi.fn(() => ({ XDG_RUNTIME_DIR: "/run/user/1000" })), userBusUnavailable: vi.fn(() => false) }));
+vi.mock("./orca-readiness", () => ({ getOrcaReadiness: vi.fn() }));
+
+const { runProgram } = await import("./runner");
+const { getManagedApp, performManagedAppAction, assertManagedAppStopped } = await import("./manager");
+const { getManagedAppDefinition } = await import("./catalog");
+const { isOwnedOrcaUnit, proveOwnedOrcaUnit } = await import("./orca-unit-proof");
+const { renderOrcaServiceUnit } = (await import("../../scripts/orca/systemd-unit.mjs")) as {
+ renderOrcaServiceUnit: (options: Record<string, unknown>) => string;
+};
+const { buildPlannedConfig, buildServiceConfig } = await import("../../scripts/orca/managed-config.mjs");
+
+const CLI = path.join(process.cwd(), "scripts", "orca", "cli.mjs");
+const ADVERTISED = "wss://orca.mso.example.com";
+let base = "";
+const root = () => path.join(base, ".local", "share", "mso", "orca");
+const unitPath = () => path.join(base, ".config", "systemd", "user", "mso-orca.service");
+const configPath = () => path.join(root(), "managed-service.json");
+const hostNode = () => path.join(base, "bin", "host-node");
+const releaseNode = () => path.join(base, "release", "node");
+const renderFor = (over: Record<string, unknown> = {}) =>
+ renderOrcaServiceUnit({ hostNode: hostNode(), cliScript: CLI, managedRoot: root(), port: 6769, advertisedEndpoint: ADVERTISED, ...over });
+const configFor = (over: Record<string, unknown> = {}) =>
+ buildServiceConfig({
+ plannedConfig: buildPlannedConfig({ root: root(), unitPath: unitPath(), fixedPort: 6769, advertised: ADVERTISED }),
+ prepared: {
+ releaseRoot: path.join(root(), "r"), slotDir: path.join(root(), "r", "slot"), webDir: path.join(root(), "r", "web"),
+ nodeBinary: releaseNode(), receiptPath: path.join(root(), "r", "receipt.json"), receipt: { release: { contentId: "fixture" } },
+ },
+ installedAt: "2026-01-01T00:00:00.000Z",
+ hostNode: hostNode(),
+ cliScript: CLI,
+ ...over,
+ });
+const writeConfig = (over: Record<string, unknown> = {}) => writeFile(configPath(), JSON.stringify(configFor(over)), { mode: 0o600 });
+const tamperConfig = async (patch: Record<string, unknown>) => {
+ const raw = JSON.parse(await readFile(configPath(), "utf8"));
+ await writeFile(configPath(), JSON.stringify({ ...raw, ...patch }), { mode: 0o600 });
+};
+const writeStaleConfig = () => {
+ const { hostNode: _host, cliScript: _cli, ...old } = configFor();
+ return writeFile(configPath(), JSON.stringify(old), { mode: 0o600 });
+};
+const writeOwned = async (over: Record<string, unknown> = {}, mode = 0o644) => {
+ await mkdir(path.dirname(unitPath()), { recursive: true });
+ await writeFile(unitPath(), renderFor(over), { mode });
+ await writeConfig();
+ await writeFile(path.join(root(), "managed-install.json"), "{}", { mode: 0o600 });
+};
+
+type Result = { code: number; stdout: string; stderr: string };
+const ok = (stdout = ""): Result => ({ code: 0, stdout, stderr: "" });
+const ACTIVE = "LoadState=loaded\nActiveState=active\n";
+const STOPPED = "LoadState=loaded\nActiveState=inactive\n";
+const NOT_FOUND = "LoadState=not-found\nActiveState=inactive\n";
+const BUS_DOWN: Result = { code: 1, stdout: "", stderr: "Failed to connect to bus" };
+const ADAPTER = getManagedAppDefinition("orca").command;
+function programs(user: Result | string) {
+ const asResult = (v: Result | string): Result => (typeof v === "string" ? ok(v) : v);
+ vi.mocked(runProgram).mockImplementation(async (command: string, _args: readonly string[]) => {
+ if (command === "systemctl") return asResult(user);
+ if (command === ADAPTER) return ok("1.4.230\n");
+ return ok();
+ });
+}
+const lifecycleCalls = () => vi.mocked(runProgram).mock.calls.filter(([c, a]) => c === "systemctl" && !(a as string[]).includes("show"));
+
+beforeEach(async () => {
+ base = await mkdtemp(path.join(tmpdir(), "orca-unit-"));
+ process.env.HOME = base;
+ delete process.env.ORCA_HOME;
+ await mkdir(root(), { recursive: true, mode: 0o700 });
+ await chmod(root(), 0o700);
+ for (const node of [hostNode(), releaseNode()]) {
+ await mkdir(path.dirname(node), { recursive: true, mode: 0o700 });
+ await writeFile(node, "#!/bin/sh\n", { mode: 0o755 });
+ await chmod(node, 0o755);
+ }
+ vi.mocked(runProgram).mockReset();
+});
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await rm(base, { recursive: true, force: true });
+});
+
+describe("isOwnedOrcaUnit accepts only the exact generated unit", () => {
+ it("accepts the unit the real renderer writes for the real config builder", async () => {
+ await writeConfig();
+ const built = configFor() as { hostNode?: string; release?: { nodeBinary?: string } };
+ expect(built.hostNode).not.toBe(built.release?.nodeBinary);
+ expect(await isOwnedOrcaUnit(renderFor(), root(), CLI)).toBe(true);
+ });
+ it("rejects an arbitrary /tmp node even when it is named node", async () => {
+ await writeConfig();
+ expect(await isOwnedOrcaUnit(renderFor({ hostNode: "/tmp/node" }), root(), CLI)).toBe(false);
+ await writeConfig({ hostNode: "/tmp/node" });
+ expect(await isOwnedOrcaUnit(renderFor({ hostNode: "/tmp/node" }), root(), CLI)).toBe(false);
+ });
+ it("rejects altered WorkingDirectory, EnvironmentFile, or User directives", async () => {
+ await writeConfig();
+ const unit = renderFor();
+ expect(await isOwnedOrcaUnit(unit.replace(/^WorkingDirectory=.*$/m, 'WorkingDirectory="/tmp/evil"'), root(), CLI)).toBe(false);
+ expect(await isOwnedOrcaUnit(unit.replace("[Service]", "[Service]\nEnvironmentFile=/tmp/evil"), root(), CLI)).toBe(false);
+ expect(await isOwnedOrcaUnit(unit.replace("[Service]", "[Service]\nUser=root"), root(), CLI)).toBe(false);
+ });
+ it("rejects duplicate sections, an extra Exec hook, or a runtime flag", async () => {
+ await writeConfig();
+ const unit = renderFor();
+ expect(await isOwnedOrcaUnit(unit.replace("[Service]", "[Service]\n[Service]"), root(), CLI)).toBe(false);
+ expect(await isOwnedOrcaUnit(unit.replace("[Service]", "[Service]\nExecStartPre=/tmp/evil"), root(), CLI)).toBe(false);
+ expect(await isOwnedOrcaUnit(unit.replace(/^ExecStart=(.*)$/m, (_m, line) => `ExecStart=${line} "--bind" "0.0.0.0"`), root(), CLI)).toBe(false);
+ expect(await isOwnedOrcaUnit(`${unit}UnknownDirective=1\n`, root(), CLI)).toBe(false);
+ });
+ it("rejects another root, CLI, port, missing endpoint, or CRLF", async () => {
+ await writeConfig();
+ const unit = renderFor();
+ expect(await isOwnedOrcaUnit(renderFor({ managedRoot: path.join(base, "other") }), root(), CLI)).toBe(false);
+ expect(await isOwnedOrcaUnit(renderFor({ cliScript: "/tmp/evil/cli.mjs" }), root(), CLI)).toBe(false);
+ expect(await isOwnedOrcaUnit(unit.replace('"--port" "6769"', '"--port" "70000"'), root(), CLI)).toBe(false);
+ expect(await isOwnedOrcaUnit(unit.replace(/ "--advertised-endpoint" "[^"]+"/, ""), root(), CLI)).toBe(false);
+ expect(await isOwnedOrcaUnit(unit.replace(/\n/g, "\r\n"), root(), CLI)).toBe(false);
+ });
+ it("refuses an absent, world-readable, mismatched, or unknown-node receipt", async () => {
+ expect(await isOwnedOrcaUnit(renderFor(), root(), CLI)).toBe(false);
+ await writeConfig();
+ await chmod(configPath(), 0o644);
+ expect(await isOwnedOrcaUnit(renderFor(), root(), CLI)).toBe(false);
+ await writeConfig();
+ await tamperConfig({ managedRoot: path.join(base, "other") });
+ expect(await isOwnedOrcaUnit(renderFor(), root(), CLI)).toBe(false);
+ await writeConfig();
+ await tamperConfig({ port: 70000 });
+ expect(await isOwnedOrcaUnit(renderFor(), root(), CLI)).toBe(false);
+ await writeConfig({ hostNode: path.join(base, "unknown-node") });
+ expect(await isOwnedOrcaUnit(renderFor(), root(), CLI)).toBe(false);
+ });
+ it("demands a reinstall for an old receipt without launcher identity", async () => {
+ await writeOwned();
+ await writeStaleConfig();
+ expect(await proveOwnedOrcaUnit(renderFor(), root(), CLI)).toBe("reinstall-required");
+ programs(ACTIVE);
+ const view = await getManagedApp("orca");
+ expect(view.installed).toBe(false);
+ expect(view.diagnostic).toMatch(/reinstall/i);
+ });
+});
+
+describe("owned Orca unit file guards", () => {
+ it("rejects a world-writable unit file", async () => {
+ await writeOwned();
+ await chmod(unitPath(), 0o666);
+ programs(ACTIVE);
+ expect((await getManagedApp("orca")).installed).toBe(false);
+ });
+ it("rejects a unit in a writable containing directory", async () => {
+ await writeOwned();
+ await chmod(path.dirname(unitPath()), 0o777);
+ programs(ACTIVE);
+ expect((await getManagedApp("orca")).installed).toBe(false);
+ });
+ it("rejects a unit that does not match the trusted receipt", async () => {
+ await writeOwned();
+ await writeFile(unitPath(), renderFor({ managedRoot: path.join(base, "other") }), { mode: 0o644 });
+ programs(ACTIVE);
+ expect((await getManagedApp("orca")).installed).toBe(false);
+ });
+});
+
+describe("strict quiescence never reads an unknown state as stopped", () => {
+ it("refuses a backup while the user bus is unavailable", async () => {
+ await writeOwned();
+ programs(BUS_DOWN);
+ const view = await getManagedApp("orca");
+ expect(view.installed).toBe(true);
+ expect(view.state).toBe("error");
+ expect(view.diagnostic).toMatch(/unknown|not reported as stopped/i);
+ await expect(assertManagedAppStopped("orca")).rejects.toThrow(/unknown/i);
+ await expect(performManagedAppAction("orca", "backup")).rejects.toThrow(/unknown/i);
+ });
+ it("treats an owned unit systemd cannot load as ambiguous, not stopped", async () => {
+ await writeOwned();
+ programs(NOT_FOUND);
+ expect((await getManagedApp("orca")).state).toBe("error");
+ await expect(assertManagedAppStopped("orca")).rejects.toThrow(/unknown/i);
+ });
+});
+
+describe("ordinary owned lifecycle is unchanged", () => {
+ it("reports a stopped unit as stopped and starts only the USER unit", async () => {
+ await writeOwned();
+ programs(STOPPED);
+ const view = await getManagedApp("orca");
+ expect(view).toMatchObject({ installed: true, state: "stopped" });
+ expect(view.supportedActions).toContain("start");
+ await performManagedAppAction("orca", "start");
+ for (const call of lifecycleCalls()) expect(call[1]).toEqual(["--user", "start", "mso-orca.service"]);
+ });
+});
diff --git a/lib/managed-apps/orca-root-tracing.test.ts b/lib/managed-apps/orca-root-tracing.test.ts
new file mode 100644
index 00000000..ad6de1fd
--- /dev/null
+++ b/lib/managed-apps/orca-root-tracing.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+import os from "node:os";
+import path from "node:path";
+import { defaultOrcaManagedRoot, resolveOrcaManagedRoot } from "./orca-private-fs";
+
+const INVALID = { ok: false, reason: "managed_root_invalid" } as const;
+
+describe("orca root tracing and personal profile denial", () => {
+ const customHome = "/home/operator";
+
+ it("resolves default managed root under home without referencing personal profile", () => {
+ const def = defaultOrcaManagedRoot(customHome);
+ expect(def).toBe(path.join(customHome, ".local", "share", "mso", "orca"));
+ expect(resolveOrcaManagedRoot({}, customHome)).toEqual({
+ ok: true,
+ root: path.join(customHome, ".local", "share", "mso", "orca"),
+ });
+ });
+
+ it("accepts a normal canonical absolute ORCA_HOME", () => {
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "/opt/mso/orca" }, customHome)).toEqual({
+ ok: true,
+ root: "/opt/mso/orca",
+ });
+ });
+
+ it("denies personal .orca and .orca-remote exactly and all descendant paths", () => {
+ const personalOrca = path.join(customHome, ".orca");
+ const personalRemote = path.join(customHome, ".orca-remote");
+
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: personalOrca }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: path.join(personalOrca, "profiles") }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: path.join(personalOrca, "deep", "nested", "state") }, customHome)).toEqual(INVALID);
+
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: personalRemote }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: path.join(personalRemote, "config") }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: path.join(personalRemote, "deep", "nested", "state") }, customHome)).toEqual(INVALID);
+ });
+
+ it("denies home itself and filesystem root", () => {
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: customHome }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "/" }, customHome)).toEqual(INVALID);
+ });
+
+ it("denies dirty, relative, traversal, and NUL/control character inputs", () => {
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "/opt/mso/orca/" }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "/opt//mso/orca" }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "/opt/mso/../orca" }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "relative/path" }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "" }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: " " }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "/opt/mso\0orca" }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "/opt/mso\norca" }, customHome)).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: "/opt/mso\rorca" }, customHome)).toEqual(INVALID);
+ });
+
+ it("preserves identical denial behavior with default os.homedir()", () => {
+ const defHome = os.homedir();
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: path.join(defHome, ".orca") })).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: path.join(defHome, ".orca", "child") })).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: path.join(defHome, ".orca-remote") })).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: path.join(defHome, ".orca-remote", "child") })).toEqual(INVALID);
+ expect(resolveOrcaManagedRoot({ ORCA_HOME: defHome })).toEqual(INVALID);
+ });
+});
diff --git a/lib/managed-apps/orca-runtime-binding-proc.ts b/lib/managed-apps/orca-runtime-binding-proc.ts
new file mode 100644
index 00000000..6e38bd79
--- /dev/null
+++ b/lib/managed-apps/orca-runtime-binding-proc.ts
@@ -0,0 +1,167 @@
+import "server-only";
+import { promises as fs } from "node:fs";
+import { isIP } from "node:net";
+
+/** Bounded Linux procfs reads/parsers for the Orca listener-binding proof. */
+const MAX_PROC_BYTES = 1_048_576;
+const MAX_FD_ENTRIES = 4096;
+const FD_BATCH = 64;
+const MAX_LINK_BYTES = 4096;
+
+export interface OrcaListenerCandidate {
+ family: "ipv4" | "ipv6";
+ address: string;
+ port: number;
+ inode: string;
+}
+
+export interface OrcaListenerBinding {
+ family: "ipv4" | "ipv6";
+ address: string;
+ port: number;
+ inode: string;
+}
+
+/** `/proc/net/tcp{,6}` are seq files: one read can stop at an internal buffer
+ * boundary. Loop to EOF (with a hard cap) or refuse the whole table as incomplete. */
+async function readBounded(path: string, maxBytes = MAX_PROC_BYTES): Promise<string | null> {
+ let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
+ try {
+ handle = await fs.open(path, "r");
+ const chunks: Buffer[] = [];
+ let total = 0;
+ for (;;) {
+ const chunk = Buffer.alloc(65_536);
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
+ if (bytesRead === 0) break;
+ total += bytesRead;
+ if (total > maxBytes) return null;
+ chunks.push(chunk.subarray(0, bytesRead));
+ }
+ return Buffer.concat(chunks).toString("utf-8");
+ } catch {
+ return null;
+ } finally {
+ await handle?.close().catch(() => {});
+ }
+}
+
+function decodeIpv4(hex: string): string | null {
+ if (!/^[0-9A-Fa-f]{8}$/.test(hex)) return null;
+ return Buffer.from(hex, "hex").reverse().join(".");
+}
+
+/** /proc/net/tcp6 stores four little-endian 32-bit words. */
+function decodeIpv6(hex: string): string | null {
+ if (!/^[0-9A-Fa-f]{32}$/.test(hex)) return null;
+ const groups = hex.match(/.{8}/g);
+ if (!groups || groups.length !== 4) return null;
+ const bytes = groups.flatMap((group) => [...Buffer.from(group, "hex")].reverse());
+ const segments: number[] = [];
+ for (let index = 0; index < 16; index += 2) segments.push((bytes[index] << 8) | bytes[index + 1]);
+ let bestStart = -1;
+ let bestLength = 0;
+ for (let index = 0; index < segments.length; ) {
+ if (segments[index] !== 0) {
+ index += 1;
+ continue;
+ }
+ let end = index;
+ while (end < segments.length && segments[end] === 0) end += 1;
+ if (end - index > bestLength) {
+ bestStart = index;
+ bestLength = end - index;
+ }
+ index = end;
+ }
+ const words = segments.map((segment) => segment.toString(16));
+ if (bestLength > 1) {
+ return `${words.slice(0, bestStart).join(":")}::${words.slice(bestStart + bestLength).join(":")}`;
+ }
+ return words.join(":");
+}
+
+export function parseProcNetListeners(
+ content: string,
+ family: "ipv4" | "ipv6",
+): OrcaListenerCandidate[] {
+ const listeners: OrcaListenerCandidate[] = [];
+ for (const line of content.split("\n").slice(1)) {
+ const fields = line.trim().split(/\s+/);
+ if (fields.length < 10 || fields[3] !== "0A") continue;
+ const [rawAddress, rawPort] = fields[1].split(":");
+ if (!rawAddress || !rawPort) continue;
+ const port = Number.parseInt(rawPort, 16);
+ if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
+ const inode = fields[9];
+ if (!/^\d+$/.test(inode)) continue;
+ const address = family === "ipv4" ? decodeIpv4(rawAddress) : decodeIpv6(rawAddress);
+ if (!address) continue;
+ listeners.push({ family, address, port, inode });
+ }
+ return listeners;
+}
+
+export async function readLinuxListeners(
+ family: "ipv4" | "ipv6",
+): Promise<OrcaListenerCandidate[] | null> {
+ const content = await readBounded(family === "ipv4" ? "/proc/net/tcp" : "/proc/net/tcp6");
+ return content === null ? null : parseProcNetListeners(content, family);
+}
+
+/** Iterate `/proc/PID/fd` with the cap applied while iterating, never after an
+ * unbounded readdir. Any non-ENOENT read failure denies the whole proof. */
+export async function readProcessSocketInodes(
+ pid: number,
+ limit = MAX_FD_ENTRIES,
+): Promise<Set<string> | null> {
+ const inodes = new Set<string>();
+ let directory: Awaited<ReturnType<typeof fs.opendir>>;
+ try {
+ directory = await fs.opendir(`/proc/${pid}/fd`);
+ } catch {
+ return null;
+ }
+ try {
+ let batch: string[] = [];
+ let processed = 0;
+ for await (const entry of directory) {
+ processed += 1;
+ if (processed > limit) return null;
+ batch.push(entry.name);
+ if (batch.length < FD_BATCH) continue;
+ if (!(await readBatch(pid, batch, inodes))) return null;
+ batch = [];
+ }
+ if (batch.length && !(await readBatch(pid, batch, inodes))) return null;
+ return inodes;
+ } finally {
+ await directory.close().catch(() => {});
+ }
+}
+
+async function readBatch(pid: number, names: string[], inodes: Set<string>): Promise<boolean> {
+ const links = await Promise.all(
+ names.map((name) =>
+ fs
+ .readlink(`/proc/${pid}/fd/${name}`)
+ .then((link) => (link.length <= MAX_LINK_BYTES ? link : null))
+ // An fd may close between readdir and readlink; the listener-table re-read
+ // still has to match. EPERM/hidepid denies the whole proof.
+ .catch((error: NodeJS.ErrnoException) => (error?.code === "ENOENT" ? "" : null)),
+ ),
+ );
+ if (links.some((link) => link === null)) return false;
+ for (const link of links) {
+ const match = /^socket:\[(\d+)\]$/.exec(link!);
+ if (match) inodes.add(match[1]);
+ }
+ return true;
+}
+
+/** Literal loopback only: a DNS name such as `localhost` is never resolved here. */
+export function numericLoopbackAddress(hostname: string): string | null {
+ const host = hostname.startsWith("[") && hostname.endsWith("]") ? hostname.slice(1, -1) : hostname;
+ if (host === "::1") return host;
+ return isIP(host) === 4 && host.startsWith("127.") ? host : null;
+}
diff --git a/lib/managed-apps/orca-runtime-binding.test.ts b/lib/managed-apps/orca-runtime-binding.test.ts
new file mode 100644
index 00000000..ef15fb00
--- /dev/null
+++ b/lib/managed-apps/orca-runtime-binding.test.ts
@@ -0,0 +1,149 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { spawn, type ChildProcess } from "node:child_process";
+import { createServer as createNetServer, type Server as NetServer } from "node:net";
+import { once } from "node:events";
+import os from "node:os";
+import path from "node:path";
+import { readLinuxProcessSnapshot, type OrcaProcessSnapshot } from "./orca-process-identity";
+import {
+ numericLoopbackAddress,
+ parseProcNetListeners,
+ verifyOrcaListenerBinding,
+ type OrcaListenerCandidate,
+ type OrcaListenerBindingDeps,
+} from "./orca-runtime-binding";
+
+const V4_ROW = " 0: 0100007F:1A71 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1000 0 12345 1 0000000000000000 100 0 0 10 0";
+const V6_ROW = " 0: 00000000000000000000000001000000:1A71 00000000000000000000000000000000:0000 0A 00000000000000000000000000000000:00000000 00:00000000 00000000 1000 0 67890 1 0000000000000000 100 0 0 10 0";
+
+function snapshot(over: Partial<OrcaProcessSnapshot> = {}): OrcaProcessSnapshot {
+ return { pid: 77, startTicks: "100", uid: 1000, exe: "/owned/node", argv: ["/owned/node", "/owned/server.js"], ...over };
+}
+
+describe("proc/net listener parsing", () => {
+ it("decodes exact IPv4 and IPv6 LISTEN rows and ignores non-listeners", () => {
+ expect(parseProcNetListeners(`header\n${V4_ROW}`, "ipv4")).toEqual([
+ { family: "ipv4", address: "127.0.0.1", port: 6769, inode: "12345" },
+ ]);
+ expect(parseProcNetListeners(`header\n${V6_ROW}`, "ipv6")).toEqual([
+ { family: "ipv6", address: "::1", port: 6769, inode: "67890" },
+ ]);
+ expect(parseProcNetListeners(`header\n${V4_ROW.replace(" 0A ", " 01 ")}`, "ipv4")).toEqual([]);
+ expect(parseProcNetListeners(`header\n${V4_ROW.replace(":1A71 ", ":1A70 ")}`, "ipv4")).toEqual([
+ { family: "ipv4", address: "127.0.0.1", port: 6768, inode: "12345" },
+ ]);
+ });
+
+ it("accepts only literal numeric loopback hosts, never DNS fallback", () => {
+ expect(numericLoopbackAddress("127.0.0.1")).toBe("127.0.0.1");
+ expect(numericLoopbackAddress("[::1]")).toBe("::1");
+ expect(numericLoopbackAddress("localhost")).toBeNull();
+ expect(numericLoopbackAddress("0.0.0.0")).toBeNull();
+ expect(numericLoopbackAddress("::")).toBeNull();
+ });
+});
+
+describe("verifyOrcaListenerBinding fail-closed decisions", () => {
+ const listeners = (over: Partial<OrcaListenerCandidate>[] = []): OrcaListenerCandidate[] => [
+ { family: "ipv4", address: "127.0.0.1", port: 6769, inode: "12345", ...over[0] },
+ ];
+ const deps = (over: Partial<OrcaListenerBindingDeps> = {}): OrcaListenerBindingDeps => ({
+ platform: "linux",
+ readProcess: async () => snapshot(),
+ readListeners: async () => listeners(),
+ readSocketInodes: async () => new Set(["12345"]),
+ ...over,
+ });
+ const input = { pid: 77, startTicks: "100", host: "127.0.0.1", port: 6769 };
+
+ it("binds the exact LISTEN inode to the owned process", async () => {
+ await expect(verifyOrcaListenerBinding(input, deps())).resolves.toMatchObject({
+ ok: true,
+ binding: { address: "127.0.0.1", port: 6769, inode: "12345" },
+ });
+ });
+
+ it("denies unsupported platforms, unreadable tables/fds, and non-numeric hosts", async () => {
+ const platform = await verifyOrcaListenerBinding(input, deps({ platform: "darwin" }));
+ expect(platform).toMatchObject({ ok: false, reason: "listener_proof_unsupported_platform" });
+ const table = await verifyOrcaListenerBinding(input, deps({ readListeners: async () => null }));
+ expect(table).toMatchObject({ ok: false, reason: "listener_table_unreadable" });
+ const fds = await verifyOrcaListenerBinding(input, deps({ readSocketInodes: async () => null }));
+ expect(fds).toMatchObject({ ok: false, reason: "process_socket_fds_unreadable" });
+ const named = await verifyOrcaListenerBinding({ ...input, host: "localhost" }, deps());
+ expect(named).toMatchObject({ ok: false, reason: "listener_host_not_numeric_loopback" });
+ });
+
+ it("denies a port owned by another process, an ambiguous listener, or a changed PID", async () => {
+ const foreign = await verifyOrcaListenerBinding(input, deps({ readSocketInodes: async () => new Set(["999"]) }));
+ expect(foreign).toMatchObject({ ok: false, reason: "listener_not_owned_by_process" });
+ const ambiguous = await verifyOrcaListenerBinding(input, deps({
+ readListeners: async () => [...listeners(), { family: "ipv4", address: "127.0.0.1", port: 6769, inode: "22222" }],
+ }));
+ expect(ambiguous).toMatchObject({ ok: false, reason: "listener_ambiguous" });
+ const changed = await verifyOrcaListenerBinding(input, deps({ readProcess: async () => snapshot({ startTicks: "101" }) }));
+ expect(changed).toMatchObject({ ok: false, reason: "listener_process_changed" });
+ let call = 0;
+ const swapped = await verifyOrcaListenerBinding(input, deps({
+ readListeners: async () => listeners([{ inode: call++ === 0 ? "12345" : "33333" }]),
+ }));
+ expect(swapped).toMatchObject({ ok: false, reason: "listener_changed" });
+ });
+});
+
+describe("actual task-fixture listener ownership", () => {
+ const roots: string[] = [];
+ const children: ChildProcess[] = [];
+ const servers: NetServer[] = [];
+ afterAll(async () => {
+ for (const child of children) { try { child.kill("SIGKILL"); } catch { /* already gone */ } }
+ for (const server of servers) await new Promise<void>((resolve) => server.close(() => resolve()));
+ while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });
+ });
+
+ async function freePort(): Promise<number> {
+ const probe = createNetServer();
+ await new Promise<void>((resolve) => probe.listen(0, "127.0.0.1", resolve));
+ const port = (probe.address() as { port: number }).port;
+ await new Promise<void>((resolve) => probe.close(() => resolve()));
+ return port;
+ }
+
+ it("proves the owned PID owns the LISTEN inode, and rejects a live port takeover", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "mso-orca-bind-"));
+ roots.push(dir);
+ const script = path.join(dir, "holder.js");
+ await writeFile(script, [
+ "const net = require('node:net');",
+ "const port = Number(process.argv[2]);",
+ "const server = net.createServer((socket) => socket.end());",
+ "server.listen(port, '127.0.0.1', () => process.send && process.send('listening'));",
+ "process.on('message', (message) => { if (message === 'close') server.close(() => process.send && process.send('closed')); });",
+ "setInterval(() => {}, 1 << 30);",
+ ].join("\n"), { mode: 0o600 });
+ await chmod(script, 0o600);
+ const port = await freePort();
+ const child = spawn(process.execPath, [script, String(port)], { stdio: ["ignore", "ignore", "ignore", "ipc"], env: { NODE_ENV: "test" } });
+ children.push(child);
+ const pid = child.pid!;
+ expect((await once(child, "message"))[0]).toBe("listening");
+ const snap = await readLinuxProcessSnapshot(pid);
+ expect(snap).not.toBeNull();
+
+ const first = await verifyOrcaListenerBinding({ pid, startTicks: snap!.startTicks, host: "127.0.0.1", port });
+ expect(first).toMatchObject({ ok: true, binding: { address: "127.0.0.1", port } });
+
+ child.send("close");
+ expect((await once(child, "message"))[0]).toBe("closed");
+ const taker = createNetServer((socket) => socket.end());
+ servers.push(taker);
+ await new Promise<void>((resolve) => taker.listen(port, "127.0.0.1", resolve));
+ expect(() => process.kill(pid, 0)).not.toThrow();
+ await expect(verifyOrcaListenerBinding({ pid, startTicks: snap!.startTicks, host: "127.0.0.1", port }))
+ .resolves.toMatchObject({ ok: false, reason: "listener_not_owned_by_process" });
+ });
+});
diff --git a/lib/managed-apps/orca-runtime-binding.ts b/lib/managed-apps/orca-runtime-binding.ts
new file mode 100644
index 00000000..ff8d333e
--- /dev/null
+++ b/lib/managed-apps/orca-runtime-binding.ts
@@ -0,0 +1,85 @@
+import "server-only";
+import { readLinuxProcessSnapshot, type OrcaProcessReader } from "./orca-process-identity";
+import {
+ readLinuxListeners,
+ readProcessSocketInodes,
+ numericLoopbackAddress,
+ type OrcaListenerBinding,
+ type OrcaListenerCandidate,
+} from "./orca-runtime-binding-proc";
+
+export {
+ numericLoopbackAddress,
+ parseProcNetListeners,
+ readLinuxListeners,
+ readProcessSocketInodes,
+} from "./orca-runtime-binding-proc";
+export type { OrcaListenerBinding, OrcaListenerCandidate } from "./orca-runtime-binding-proc";
+
+/**
+ * The owned server PID must be the process LISTENing on the configured loopback
+ * endpoint. Liveness plus a port probe is not proof: another process can own the
+ * port while the receipt PID stays alive. This is a point-in-time inode association,
+ * not a kernel guarantee that a later accept() reaches the same process.
+ */
+export type OrcaListenerBindingResult =
+ | { ok: true; binding: OrcaListenerBinding }
+ | { ok: false; reason: string };
+
+export interface OrcaListenerBindingInput {
+ pid: number;
+ startTicks: string;
+ host: string;
+ port: number;
+}
+
+export interface OrcaListenerBindingDeps {
+ platform?: NodeJS.Platform;
+ readProcess?: OrcaProcessReader;
+ readListeners?: (family: "ipv4" | "ipv6") => Promise<OrcaListenerCandidate[] | null>;
+ readSocketInodes?: (pid: number) => Promise<Set<string> | null>;
+}
+
+const deny = (reason: string): OrcaListenerBindingResult => ({ ok: false, reason });
+
+export async function verifyOrcaListenerBinding(
+ input: OrcaListenerBindingInput,
+ deps: OrcaListenerBindingDeps = {},
+): Promise<OrcaListenerBindingResult> {
+ if ((deps.platform ?? process.platform) !== "linux") return deny("listener_proof_unsupported_platform");
+ const { pid, startTicks, port } = input;
+ if (!Number.isInteger(pid) || pid <= 1) return deny("listener_process_invalid");
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return deny("listener_port_invalid");
+ const address = numericLoopbackAddress(input.host);
+ if (!address) return deny("listener_host_not_numeric_loopback");
+ const family = address === "::1" ? "ipv6" : "ipv4";
+ const readProcess = deps.readProcess ?? readLinuxProcessSnapshot;
+ const readListeners = deps.readListeners ?? readLinuxListeners;
+ const readInodes = deps.readSocketInodes ?? readProcessSocketInodes;
+
+ const before = await readProcess(pid).catch(() => null);
+ if (!before || before.pid !== pid || before.startTicks !== startTicks) return deny("listener_process_changed");
+ const listenersBefore = await readListeners(family).catch(() => null);
+ if (listenersBefore === null) return deny("listener_table_unreadable");
+ const matching = listenersBefore.filter(
+ (listener) => listener.family === family && listener.address === address && listener.port === port,
+ );
+ if (matching.length === 0) return deny("listener_not_found");
+ // SO_REUSEPORT would hand connections to a second owner; refuse ambiguity.
+ if (matching.length !== 1) return deny("listener_ambiguous");
+ const binding = matching[0];
+
+ const inodes = await readInodes(pid).catch(() => null);
+ if (inodes === null) return deny("process_socket_fds_unreadable");
+ if (!inodes.has(binding.inode)) return deny("listener_not_owned_by_process");
+
+ const after = await readProcess(pid).catch(() => null);
+ if (!after || after.pid !== pid || after.startTicks !== startTicks) return deny("listener_process_changed");
+ const listenersAfter = await readListeners(family).catch(() => null);
+ if (listenersAfter === null) return deny("listener_table_unreadable");
+ const still = listenersAfter.filter(
+ (listener) => listener.family === family && listener.address === address && listener.port === port,
+ );
+ if (still.length !== 1 || still[0].inode !== binding.inode) return deny("listener_changed");
+ return { ok: true, binding };
+}
diff --git a/lib/managed-apps/orca-runtime-readiness.test.ts b/lib/managed-apps/orca-runtime-readiness.test.ts
new file mode 100644
index 00000000..aad7c256
--- /dev/null
+++ b/lib/managed-apps/orca-runtime-readiness.test.ts
@@ -0,0 +1,130 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+vi.hoisted(() => {
+ process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com";
+ process.env.OS_PUBLIC_ORIGIN = "https://mso.example.com";
+});
+
+import { chmod, copyFile, link, mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
+import { createServer as createNetServer, type Server as NetServer } from "node:net";
+import { spawn, type ChildProcess } from "node:child_process";
+import { once } from "node:events";
+import os from "node:os";
+import path from "node:path";
+import { getOrcaReadiness } from "./orca-readiness";
+import { readLinuxProcessSnapshot } from "./orca-process-identity";
+
+function pairingUrl(): string {
+ const payload = { v: 2, endpoint: "wss://orca.mso.example.com", deviceToken: "dev_tok_12345", publicKeyB64: "pub_key_12345", scope: "runtime" };
+ return `orca://pair?code=${Buffer.from(JSON.stringify(payload)).toString("base64url")}`;
+}
+
+function statusPayload(pid: number, port: number): Record<string, unknown> {
+ return {
+ type: "orca_server_ready",
+ schemaVersion: 1,
+ runtimeId: "rt_listener_binding",
+ boundEndpoint: `ws://127.0.0.1:${port}`,
+ advertisedEndpoint: "wss://orca.mso.example.com",
+ pairing: { available: true, scope: "runtime", url: pairingUrl() },
+ health: {
+ buildVersion: "1.4.230",
+ nodeVersion: "24.21.0",
+ nodeAbi: "137",
+ pid,
+ terminalDaemon: { state: "live", ownsFreshSessions: true, selfTest: { ok: true, verdict: "healthy" } },
+ },
+ };
+}
+
+describe("getOrcaReadiness binds the verified runtime to its LISTEN socket", () => {
+ const roots: string[] = [];
+ const children: ChildProcess[] = [];
+ const servers: NetServer[] = [];
+ afterAll(async () => {
+ for (const child of children) { try { child.kill("SIGKILL"); } catch { /* already gone */ } }
+ for (const server of servers) await new Promise<void>((resolve) => server.close(() => resolve()));
+ while (roots.length) await rm(roots.pop()!, { recursive: true, force: true });
+ });
+
+ async function freePort(): Promise<number> {
+ const probe = createNetServer();
+ await new Promise<void>((resolve) => probe.listen(0, "127.0.0.1", resolve));
+ const port = (probe.address() as { port: number }).port;
+ await new Promise<void>((resolve) => probe.close(() => resolve()));
+ return port;
+ }
+
+ it("accepts an owned fixture listener and denies after a live port takeover", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "mso-orca-ready-"));
+ roots.push(root);
+ await chmod(root, 0o700);
+ const release = path.join(root, "releases", "1.4.230");
+ const nodeBin = path.join(root, "runtimes", "node-24.21.0", "bin");
+ const userData = path.join(root, "runtime", "user-data");
+ await mkdir(release, { recursive: true, mode: 0o700 });
+ await mkdir(nodeBin, { recursive: true, mode: 0o700 });
+ await mkdir(userData, { recursive: true, mode: 0o700 });
+ const nodePath = path.join(nodeBin, "node");
+ try { await link(process.execPath, nodePath); } catch { await copyFile(process.execPath, nodePath); }
+ await chmod(nodePath, 0o755);
+ const nodeBinary = await realpath(nodePath);
+ const serverEntry = path.join(release, "orcad-server.js");
+ await writeFile(serverEntry, [
+ "const net = require('node:net');",
+ "const args = process.argv.slice(2);",
+ "const port = Number(args[args.indexOf('--port') + 1]);",
+ "const server = net.createServer((socket) => socket.end());",
+ "server.listen(port, '127.0.0.1', () => process.send && process.send('listening'));",
+ "process.on('message', (message) => { if (message === 'close') server.close(() => process.send && process.send('closed')); });",
+ "setInterval(() => {}, 1 << 30);",
+ ].join("\n"), { mode: 0o600 });
+
+ const port = await freePort();
+ const child = spawn(nodeBinary, [serverEntry, "--bind", "127.0.0.1", "--port", String(port), "--json"], {
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
+ env: { NODE_ENV: "test" },
+ });
+ children.push(child);
+ const pid = child.pid!;
+ expect((await once(child, "message"))[0]).toBe("listening");
+ const snap = await readLinuxProcessSnapshot(pid);
+ expect(snap).not.toBeNull();
+ await writeFile(path.join(root, "private-status.json"), JSON.stringify(statusPayload(pid, port)), { mode: 0o600 });
+ await writeFile(path.join(root, "runtime-identity.json"), JSON.stringify({
+ schemaVersion: 1,
+ runtimeId: "rt_listener_binding",
+ version: "1.4.230",
+ serverPid: pid,
+ serverStartTicks: snap!.startTicks,
+ nodeBinary,
+ serverEntry,
+ userData,
+ boundEndpoint: `ws://127.0.0.1:${port}`,
+ advertisedEndpoint: "wss://orca.mso.example.com",
+ readyAt: new Date().toISOString(),
+ }), { mode: 0o600 });
+ const env: NodeJS.ProcessEnv = { NODE_ENV: "test", ORCA_HOME: root, ORCA_DASHBOARD_URL: `http://127.0.0.1:${port}` };
+
+ const ready = await getOrcaReadiness({ env });
+ expect(ready.available).toBe(true);
+ if (ready.available) {
+ expect(ready.serverPid).toBe(pid);
+ expect(ready.startTicks).toBe(snap!.startTicks);
+ expect(ready.boundEndpoint).toBe(`ws://127.0.0.1:${port}`);
+ }
+
+ child.send("close");
+ expect((await once(child, "message"))[0]).toBe("closed");
+ const taker = createNetServer((socket) => socket.end());
+ servers.push(taker);
+ await new Promise<void>((resolve) => taker.listen(port, "127.0.0.1", resolve));
+ expect(() => process.kill(pid, 0)).not.toThrow();
+ await expect(getOrcaReadiness({ env })).resolves.toMatchObject({
+ available: false,
+ reason: "listener_not_owned_by_process",
+ });
+ }, 10_000);
+});
diff --git a/lib/managed-apps/orca-socket-runtime.test.ts b/lib/managed-apps/orca-socket-runtime.test.ts
new file mode 100644
index 00000000..4eff9985
--- /dev/null
+++ b/lib/managed-apps/orca-socket-runtime.test.ts
@@ -0,0 +1,133 @@
+import { afterAll, afterEach, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+import { mkdtemp, rm } from "node:fs/promises";
+import { createServer, type Server } from "node:http";
+import { connect, type Socket } from "node:net";
+import { once } from "node:events";
+import os from "node:os";
+import path from "node:path";
+import { NextRequest } from "next/server";
+import { attachSocketProxy } from "../../scripts/server-sockets.mjs";
+
+const root = await mkdtemp(path.join(os.tmpdir(), "mso-orca-socket-"));
+process.env.OS_DEVICE_STORE = path.join(root, "devices.json");
+process.env.OS_SESSION_SECRET = "s".repeat(32);
+process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com";
+process.env.OS_PUBLIC_ORIGIN = "https://mso.example.com";
+const devices = await import("@/lib/auth/device-store");
+const { socketPolicy } = await import("./socket-policy");
+const { createManagedAppCookie } = await import("./session");
+
+const servers: Server[] = [];
+const sockets: Socket[] = [];
+afterEach(async () => {
+ for (const socket of sockets.splice(0)) socket.destroy();
+ await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));
+});
+afterAll(async () => {
+ for (const key of ["OS_DEVICE_STORE", "OS_SESSION_SECRET", "NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", "OS_PUBLIC_ORIGIN"]) delete process.env[key];
+ await rm(root, { recursive: true, force: true });
+});
+
+async function listen(server: Server): Promise<number> {
+ servers.push(server);
+ server.listen(0, "127.0.0.1");
+ await once(server, "listening");
+ return (server.address() as { port: number }).port;
+}
+
+it("revalidates the verified Orca runtime for every socket decision and closes on change", async () => {
+ const id = "f".repeat(32);
+ await devices.approveDevice(id, "operator", "operator");
+ const issued = Date.now();
+ const policy = await devices.currentSessionPolicy("host");
+ const cookie = createManagedAppCookie("orca", {
+ device_id: id,
+ issued_at: issued,
+ expires_at: issued + 60_000,
+ cookie_scope: policy.scope,
+ cookie_epoch: policy.epoch,
+ }, process.env.OS_SESSION_SECRET!);
+
+ const upstream = createServer();
+ let remote: Socket | undefined;
+ upstream.on("upgrade", (_request, socket) => {
+ remote = socket as Socket;
+ sockets.push(remote);
+ socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n");
+ socket.on("data", (chunk) => socket.write(chunk));
+ });
+ const upstreamPort = await listen(upstream);
+ const request = new NextRequest("https://orca.mso.example.com/socket?orca-client=web", {
+ headers: {
+ host: "orca.mso.example.com",
+ origin: "https://orca.mso.example.com",
+ upgrade: "websocket",
+ connection: "Upgrade",
+ cookie: `__Host-mso-managed-app=${cookie}`,
+ authorization: "must-not-reach-upstream",
+ },
+ });
+ let current: {
+ available: true;
+ runtimeId: string;
+ serverPid: number;
+ startTicks: string;
+ listenerInode: string;
+ boundEndpoint: string;
+ } | { available: false; reason: string } = {
+ available: true,
+ runtimeId: "rt_fixture",
+ serverPid: 4242,
+ startTicks: "99887766",
+ listenerInode: "11111",
+ boundEndpoint: `ws://127.0.0.1:${upstreamPort}`,
+ };
+ const authorize = () => socketPolicy(request, { getOrcaReadiness: async () => current as never });
+
+ const decision = await authorize();
+ expect(decision?.identity).toBeDefined();
+ expect(JSON.parse(decision!.identity!)).toMatchObject({
+ device: id,
+ runtimeId: "rt_fixture",
+ serverPid: 4242,
+ startTicks: "99887766",
+ listenerInode: "11111",
+ });
+ expect(decision?.target).toBe(`http://127.0.0.1:${upstreamPort}/socket?orca-client=web`);
+ expect(decision?.headers.cookie).toBeUndefined();
+ expect(decision?.headers.authorization).toBeUndefined();
+
+ const proxy = createServer();
+ attachSocketProxy(proxy, authorize);
+ const proxyPort = await listen(proxy);
+ const client = connect(proxyPort, "127.0.0.1");
+ sockets.push(client);
+ const handshake = once(client, "data");
+ client.write("GET /socket HTTP/1.1\r\nHost: orca.mso.example.com\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n");
+ expect((await handshake)[0].toString()).toContain("101 Switching Protocols");
+ const echo = once(client, "data");
+ client.write("permitted");
+ expect((await echo)[0].toString()).toBe("permitted");
+
+ current = {
+ available: true,
+ runtimeId: "rt_replaced",
+ serverPid: 4242,
+ startTicks: "99887767",
+ listenerInode: "22222",
+ boundEndpoint: `ws://127.0.0.1:${upstreamPort}`,
+ };
+ const replaced = await authorize();
+ expect(replaced).not.toBeNull();
+ expect(replaced!.identity).not.toBe(decision!.identity);
+ expect(replaced!.target).toBe(decision!.target);
+ const closed = once(client, "close");
+ remote!.write("runtime-changed");
+ await closed;
+
+ current = { available: false, reason: "listener_not_owned_by_process" };
+ expect(await authorize()).toBeNull();
+}, 5000);
diff --git a/lib/managed-apps/orca-stop-containment.test.ts b/lib/managed-apps/orca-stop-containment.test.ts
new file mode 100644
index 00000000..0d2a87bf
--- /dev/null
+++ b/lib/managed-apps/orca-stop-containment.test.ts
@@ -0,0 +1,210 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { chmod, mkdir, mkdtemp, rm, writeFile, unlink } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+vi.mock("server-only", () => ({}));
+vi.mock("./runner", () => ({
+ runProgram: vi.fn(),
+ commandExists: vi.fn().mockResolvedValue(false),
+ resolveCommand: vi.fn().mockResolvedValue(null),
+ requireProgram: vi.fn(),
+}));
+vi.mock("./user-bus", () => ({
+ userBusEnv: vi.fn(() => ({ XDG_RUNTIME_DIR: "/run/user/1000" })),
+ userBusUnavailable: vi.fn(() => false),
+}));
+vi.mock("./orca-readiness", () => ({ getOrcaReadiness: vi.fn() }));
+
+const { runProgram } = await import("./runner");
+const { getManagedApp, performManagedAppAction, assertManagedAppStopped } = await import("./manager");
+const { getManagedAppDefinition } = await import("./catalog");
+const { renderOrcaServiceUnit } = (await import("../../scripts/orca/systemd-unit.mjs")) as {
+ renderOrcaServiceUnit: (options: Record<string, unknown>) => string;
+};
+const { buildPlannedConfig, buildServiceConfig } = await import("../../scripts/orca/managed-config.mjs");
+
+const ADAPTER = getManagedAppDefinition("orca").command;
+const RUNNING = "LoadState=loaded\nActiveState=active\n";
+const STOPPED = "LoadState=loaded\nActiveState=inactive\n";
+type Result = { code: number; stdout: string; stderr: string };
+const ok = (stdout = ""): Result => ({ code: 0, stdout, stderr: "" });
+
+let home = "";
+const root = () => path.join(home, ".local", "share", "mso", "orca");
+const unitPath = () => path.join(home, ".config", "systemd", "user", "mso-orca.service");
+const hostNode = () => path.join(home, "bin", "host-node");
+const releaseNode = () => path.join(home, "release", "node");
+const receiptPath = () => path.join(root(), "managed-install.json");
+
+const CLI = path.join(process.cwd(), "scripts", "orca", "cli.mjs");
+const ADVERTISED = "wss://orca.mso.example.com";
+
+function unitText() {
+ return renderOrcaServiceUnit({
+ hostNode: hostNode(),
+ cliScript: CLI,
+ managedRoot: root(),
+ port: 6769,
+ advertisedEndpoint: ADVERTISED,
+ });
+}
+
+const configFor = () =>
+ buildServiceConfig({
+ plannedConfig: buildPlannedConfig({ root: root(), unitPath: unitPath(), fixedPort: 6769, advertised: ADVERTISED }),
+ prepared: {
+ releaseRoot: path.join(root(), "r"),
+ slotDir: path.join(root(), "r", "slot"),
+ webDir: path.join(root(), "r", "web"),
+ nodeBinary: releaseNode(),
+ receiptPath: path.join(root(), "r", "receipt.json"),
+ receipt: { release: { contentId: "fixture" } },
+ },
+ installedAt: "2026-01-01T00:00:00.000Z",
+ hostNode: hostNode(),
+ cliScript: CLI,
+ });
+
+async function writeOwnedFixture() {
+ await mkdir(path.dirname(unitPath()), { recursive: true });
+ await writeFile(unitPath(), unitText(), { mode: 0o644 });
+ await writeFile(path.join(root(), "managed-service.json"), JSON.stringify(configFor()), { mode: 0o600 });
+ await writeFile(receiptPath(), "{}", { mode: 0o600 });
+}
+
+let adapterResult: Result = ok("1.4.230\n");
+let isRunning = true;
+
+function setupRunnerMock() {
+ vi.mocked(runProgram).mockImplementation(async (command: string, args: readonly string[]) => {
+ if (command === "systemctl") {
+ if (args.includes("show")) {
+ return ok(isRunning ? RUNNING : STOPPED);
+ }
+ if (args.includes("stop")) {
+ isRunning = false;
+ return ok();
+ }
+ return ok();
+ }
+ if (command === ADAPTER) return adapterResult;
+ return ok();
+ });
+}
+
+const callLog = () => vi.mocked(runProgram).mock.calls as Array<[string, string[], number?, Record<string, string>?]>;
+const lifecycleCalls = () =>
+ callLog()
+ .filter(([c, a]) => c === "systemctl" && !a.includes("show"))
+ .map(([c, a]) => [c, a]);
+
+describe("Orca stop containment despite corrupt release", () => {
+ beforeEach(async () => {
+ home = await mkdtemp(path.join(tmpdir(), "orca-stop-"));
+ process.env.HOME = home;
+ delete process.env.ORCA_HOME;
+ await mkdir(root(), { recursive: true, mode: 0o700 });
+ await mkdir(path.dirname(hostNode()), { recursive: true, mode: 0o700 });
+ await mkdir(path.dirname(releaseNode()), { recursive: true, mode: 0o700 });
+ await writeFile(hostNode(), "#!/bin/sh\n", { mode: 0o755 });
+ await writeFile(releaseNode(), "#!/bin/sh\n", { mode: 0o755 });
+ await chmod(hostNode(), 0o755);
+ await chmod(releaseNode(), 0o755);
+ vi.mocked(runProgram).mockReset();
+ adapterResult = ok("1.4.230\n");
+ isRunning = true;
+ setupRunnerMock();
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await rm(home, { recursive: true, force: true });
+ });
+
+ it("after primed valid status adapter fail: start/restart/backup deny, but stop succeeds once and reports integrity diagnostic", async () => {
+ await writeOwnedFixture();
+
+ // 1. Prime valid status
+ const initialView = await getManagedApp("orca");
+ expect(initialView.installed).toBe(true);
+ expect(initialView.state).toBe("running");
+ expect(initialView.supportedActions).toContain("stop");
+
+ // 2. Adapter fails (checksum mismatch / corrupt release)
+ adapterResult = { code: 1, stdout: "", stderr: "checksum mismatch / corrupt release" };
+
+ // 3. start, restart, backup deny; strict backup remains refused
+ await expect(performManagedAppAction("orca", "start")).rejects.toThrow(/install receipt|cannot prove absence/i);
+ await expect(performManagedAppAction("orca", "restart")).rejects.toThrow(/install receipt|cannot prove absence/i);
+ await expect(performManagedAppAction("orca", "backup")).rejects.toThrow(/install receipt|cannot prove absence/i);
+ await expect(assertManagedAppStopped("orca")).rejects.toThrow(/install receipt|cannot prove absence/i);
+ expect(lifecycleCalls()).toEqual([]);
+
+ // 4. UI view offers stop with meaningful minimal state without marking install fully verified
+ const unverifiedView = await getManagedApp("orca");
+ expect(unverifiedView.installed).toBe(false);
+ expect(unverifiedView.state).toBe("running");
+ expect(unverifiedView.supportedActions).toEqual(["stop"]);
+ expect(unverifiedView.diagnostic).toMatch(/install receipt/i);
+
+ // 5. stop containment succeeds and invokes exact systemctl --user stop mso-orca.service once
+ const stopView = await performManagedAppAction("orca", "stop");
+ expect(lifecycleCalls()).toEqual([["systemctl", ["--user", "stop", "mso-orca.service"]]]);
+ expect(stopView.installed).toBe(false);
+ expect(stopView.state).toBe("stopped");
+ expect(stopView.diagnostic).toMatch(/install receipt/i);
+ expect(stopView.supportedActions).toEqual(["stop"]);
+
+ // Strict backup still refused even after stop
+ await expect(assertManagedAppStopped("orca")).rejects.toThrow(/install receipt|cannot prove absence/i);
+ });
+
+ it("direct stop with corrupt release invalidates stale verification cache and reflects integrity failure", async () => {
+ await writeOwnedFixture();
+
+ // 1. Prime valid status
+ const initialView = await getManagedApp("orca");
+ expect(initialView.installed).toBe(true);
+ expect(initialView.state).toBe("running");
+
+ // 2. Corrupt release / checksum failure
+ adapterResult = { code: 1, stdout: "", stderr: "checksum mismatch / corrupt release" };
+
+ // 3. Direct stop without failed start/restart/backup beforehand
+ const stopView = await performManagedAppAction("orca", "stop");
+
+ // 4. Assert exact owned user stop once, installed false, integrity diagnostic, supportedActions exactly ['stop'], no start/restart side effects
+ expect(lifecycleCalls()).toEqual([["systemctl", ["--user", "stop", "mso-orca.service"]]]);
+ expect(stopView.installed).toBe(false);
+ expect(stopView.state).toBe("stopped");
+ expect(stopView.diagnostic).toMatch(/install receipt/i);
+ expect(stopView.supportedActions).toEqual(["stop"]);
+ });
+
+ it("foreign unit denies stop and never invokes systemctl stop", async () => {
+ await writeOwnedFixture();
+ // Tamper unit with foreign content (missing MSO marker)
+ await writeFile(unitPath(), "[Unit]\nDescription=Foreign\n[Service]\nExecStart=/bin/sleep 100\n", { mode: 0o644 });
+
+ const view = await getManagedApp("orca");
+ expect(view.installed).toBe(false);
+ expect(view.supportedActions).not.toContain("stop");
+
+ await expect(performManagedAppAction("orca", "stop")).rejects.toThrow(/refusing to manage|operation unsupported|not an MSO-owned/i);
+ expect(lifecycleCalls()).toEqual([]);
+ });
+
+ it("metadata ownership loss denies stop and never invokes systemctl stop", async () => {
+ await writeOwnedFixture();
+ // Remove trusted config (managed-service.json)
+ await unlink(path.join(root(), "managed-service.json"));
+
+ const view = await getManagedApp("orca");
+ expect(view.installed).toBe(false);
+ expect(view.supportedActions).not.toContain("stop");
+
+ await expect(performManagedAppAction("orca", "stop")).rejects.toThrow(/reinstall|refusing to manage|operation unsupported|not an MSO-owned/i);
+ expect(lifecycleCalls()).toEqual([]);
+ });
+});
diff --git a/lib/managed-apps/orca-strict-recheck.test.ts b/lib/managed-apps/orca-strict-recheck.test.ts
new file mode 100644
index 00000000..64696701
--- /dev/null
+++ b/lib/managed-apps/orca-strict-recheck.test.ts
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+vi.mock("./runner", () => ({
+ runProgram: vi.fn(),
+ commandExists: vi.fn().mockResolvedValue(false),
+ resolveCommand: vi.fn().mockResolvedValue(null),
+ requireProgram: vi.fn(),
+}));
+vi.mock("./user-bus", () => ({
+ userBusEnv: vi.fn(() => ({ XDG_RUNTIME_DIR: "/run/user/1000" })),
+ userBusUnavailable: vi.fn(() => false),
+}));
+type OrcaInstallationModule = typeof import("./orca-installation");
+
+vi.mock("./orca-installation", async (importOriginal) => {
+ const actual = (await importOriginal()) as OrcaInstallationModule;
+ return {
+ ...actual,
+ detectOrca: vi.fn(),
+ };
+});
+
+const { runProgram } = await import("./runner");
+const { detectOrca } = await import("./orca-installation");
+const { assertManagedAppStopped } = await import("./manager");
+
+describe("assertManagedAppStopped strict Orca recheck", () => {
+ beforeEach(() => {
+ vi.mocked(runProgram).mockReset();
+ vi.mocked(detectOrca).mockReset();
+ });
+
+ it("passes when Orca is owned and systemd confirms it is stopped", async () => {
+ vi.mocked(detectOrca).mockResolvedValue({
+ type: "systemd",
+ serviceName: "mso-orca.service",
+ serviceNames: ["mso-orca.service"],
+ owned: true,
+ });
+ vi.mocked(runProgram).mockImplementation(async (cmd: string, args: readonly string[]) => {
+ if (cmd === "systemctl" && args.includes("show")) {
+ return { code: 0, stdout: "LoadState=loaded\nActiveState=inactive\n", stderr: "" };
+ }
+ return { code: 0, stdout: "", stderr: "" };
+ });
+
+ await expect(assertManagedAppStopped("orca")).resolves.toBeUndefined();
+ });
+
+ it("fails when Orca is not installed with a reinstall-required diagnostic", async () => {
+ const diag =
+ "mso-orca.service was installed by an older MSO release that did not record its launcher identity; reinstall Orca with this MSO version to manage it.";
+ vi.mocked(detectOrca).mockResolvedValue({
+ type: "not-installed",
+ diagnostic: diag,
+ });
+
+ await expect(assertManagedAppStopped("orca")).rejects.toThrow(/reinstall Orca with this MSO version/);
+ });
+
+ it("fails closed when Orca has not-installed without diagnostic", async () => {
+ vi.mocked(detectOrca).mockResolvedValue({
+ type: "not-installed",
+ diagnostic: null,
+ });
+
+ await expect(assertManagedAppStopped("orca")).rejects.toThrow(/install state cannot prove absence/);
+ });
+});
diff --git a/lib/managed-apps/orca-unit-files.ts b/lib/managed-apps/orca-unit-files.ts
new file mode 100644
index 00000000..1ccffa71
--- /dev/null
+++ b/lib/managed-apps/orca-unit-files.ts
@@ -0,0 +1,182 @@
+import "server-only";
+import { constants, promises as fs } from "node:fs";
+import type { FileHandle } from "node:fs/promises";
+import path from "node:path";
+
+/**
+ * Bounded, symlink-proof filesystem reads for the MSO-owned Orca unit proof.
+ *
+ * Both the unit file and the trusted `managed-service.json` receipt are opened
+ * through a pinned directory fd with `O_NOFOLLOW`, capped from `fstat` before a
+ * single byte is read (the read loop stops at cap+1, so a growing file cannot
+ * allocate or return unbounded data), and re-`stat`ed to reject an in-flight
+ * replacement. The receipt is 0600 inside the 0700 managed root.
+ */
+
+export const ORCA_UNIT_MARKER = "# mso-managed-app: orca";
+const UNIT_MAX_BYTES = 32 * 1024;
+const CONFIG_MAX_BYTES = 64 * 1024;
+const SERVICE_CONFIG = "managed-service.json";
+const CONTROL = /[\0\r\n]/;
+const LOOPBACK_HOSTS = new Set(["localhost", "::1", "[::1]", "0.0.0.0", "[::]", "::"]);
+
+export type TrustedOrcaConfig = {
+ hostNode: string;
+ cliScript: string;
+ managedRoot: string;
+ port: number;
+ advertisedEndpoint: string;
+};
+
+export type TrustedConfigRead =
+ | { state: "ok"; config: TrustedOrcaConfig }
+ | { state: "missing" }
+ | { state: "stale" }
+ | { state: "invalid" };
+
+export function ownerUidMatches(uid: number): boolean {
+ return typeof process.getuid !== "function" || uid === process.getuid();
+}
+
+/** Read at most `maxBytes`; a file that reaches cap+1 is refused. */
+async function readBounded(handle: FileHandle, maxBytes: number): Promise<Buffer | null> {
+ const chunks: Buffer[] = [];
+ let total = 0;
+ for (;;) {
+ const remaining = maxBytes + 1 - total;
+ if (remaining <= 0) return null;
+ const chunk = Buffer.alloc(Math.min(remaining, 16 * 1024));
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null);
+ if (bytesRead === 0) break;
+ total += bytesRead;
+ if (total > maxBytes) return null;
+ chunks.push(chunk.subarray(0, bytesRead));
+ }
+ return Buffer.concat(chunks, total);
+}
+
+async function readOwnedFile(dir: string, filename: string, maxBytes: number, privateMode: boolean): Promise<string | null> {
+ let canonicalDir: string;
+ try {
+ canonicalDir = await fs.realpath(dir);
+ } catch {
+ return null;
+ }
+ if (canonicalDir !== path.resolve(dir)) return null;
+ let directory;
+ try {
+ directory = await fs.open(canonicalDir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
+ } catch {
+ return null;
+ }
+ try {
+ const dirStat = await directory.stat();
+ if (!dirStat.isDirectory() || !ownerUidMatches(dirStat.uid) || (dirStat.mode & 0o022) !== 0) return null;
+ let handle;
+ try {
+ handle = await fs.open(`/proc/self/fd/${directory.fd}/${filename}`, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
+ } catch {
+ return null;
+ }
+ try {
+ const before = await handle.stat();
+ const modeReject = privateMode ? (before.mode & 0o077) !== 0 : (before.mode & 0o022) !== 0;
+ if (!before.isFile() || !ownerUidMatches(before.uid) || modeReject || before.size > maxBytes) return null;
+ const buffer = await readBounded(handle, maxBytes);
+ if (buffer === null) return null;
+ const after = await handle.stat();
+ if (after.size !== buffer.length || after.ino !== before.ino || after.mtimeMs !== before.mtimeMs || after.mode !== before.mode) return null;
+ return buffer.toString("utf-8");
+ } finally {
+ await handle.close();
+ }
+ } finally {
+ await directory.close();
+ }
+}
+
+export async function readOrcaUnitText(unitPath: string): Promise<string | null> {
+ return readOwnedFile(path.dirname(unitPath), path.basename(unitPath), UNIT_MAX_BYTES, false);
+}
+
+function isAdvertisedEndpoint(value: unknown): value is string {
+ if (typeof value !== "string" || value.length === 0) return false;
+ let url: URL;
+ try {
+ url = new URL(value);
+ } catch {
+ return false;
+ }
+ if (url.protocol !== "wss:" || url.username || url.password || url.search || url.hash) return false;
+ return !LOOPBACK_HOSTS.has(url.hostname) && !/^127\./.test(url.hostname);
+}
+
+/** A recorded launcher node is trusted only if it is a real, non-replaceable
+ * executable. Sticky world-writable directories (e.g. `/tmp`) may host a file
+ * this user already owns; a non-sticky writable ancestor may not. */
+async function isTrustedHostNode(node: unknown): Promise<boolean> {
+ if (typeof node !== "string" || !path.isAbsolute(node) || CONTROL.test(node)) return false;
+ let info;
+ try {
+ info = await fs.lstat(node);
+ } catch {
+ return false;
+ }
+ if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o111) === 0 || (info.mode & 0o022) !== 0) return false;
+ if (info.uid !== 0 && !ownerUidMatches(info.uid)) return false;
+ let dir = path.dirname(node);
+ for (;;) {
+ let dirInfo;
+ try {
+ dirInfo = await fs.lstat(dir);
+ } catch {
+ return false;
+ }
+ if (!dirInfo.isDirectory() || dirInfo.isSymbolicLink()) return false;
+ if ((dirInfo.mode & 0o002) !== 0 && (dirInfo.mode & 0o1000) === 0) return false;
+ const parent = path.dirname(dir);
+ if (parent === dir) return true;
+ dir = parent;
+ }
+}
+
+/**
+ * The trusted installation configuration written by the installer. `hostNode`
+ * and `cliScript` are the exact launcher the unit was rendered with; there is
+ * deliberately no `release.nodeBinary` fallback (that is the pinned child
+ * runtime). A config from an older MSO release without these fields is
+ * `stale`, so the consumer can demand a reinstall instead of silently adopting
+ * a unit it cannot reproduce.
+ */
+export async function readTrustedConfig(root: string): Promise<TrustedConfigRead> {
+ const text = await readOwnedFile(root, SERVICE_CONFIG, CONFIG_MAX_BYTES, true);
+ if (text === null) return { state: "missing" };
+ let raw: unknown;
+ try {
+ raw = JSON.parse(text);
+ } catch {
+ return { state: "invalid" };
+ }
+ if (!raw || typeof raw !== "object") return { state: "invalid" };
+ const config = raw as Record<string, unknown>;
+ if (config.schemaVersion !== 1 || config.applicationId !== "orca" || config.unitIdentity !== ORCA_UNIT_MARKER) {
+ return { state: "invalid" };
+ }
+ if (config.managedRoot !== root) return { state: "invalid" };
+ if (typeof config.hostNode !== "string" || typeof config.cliScript !== "string") return { state: "stale" };
+ if (!path.isAbsolute(config.cliScript) || CONTROL.test(config.cliScript)) return { state: "invalid" };
+ const port = config.port;
+ if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) return { state: "invalid" };
+ if (!isAdvertisedEndpoint(config.advertisedEndpoint)) return { state: "invalid" };
+ if (!(await isTrustedHostNode(config.hostNode))) return { state: "invalid" };
+ return {
+ state: "ok",
+ config: {
+ hostNode: config.hostNode,
+ cliScript: config.cliScript,
+ managedRoot: root,
+ port,
+ advertisedEndpoint: config.advertisedEndpoint
+ }
+ };
+}
diff --git a/lib/managed-apps/orca-unit-proof.ts b/lib/managed-apps/orca-unit-proof.ts
new file mode 100644
index 00000000..118b5ebb
--- /dev/null
+++ b/lib/managed-apps/orca-unit-proof.ts
@@ -0,0 +1,54 @@
+import "server-only";
+import path from "node:path";
+import { renderUnitText, systemdQuote } from "../../scripts/orca/unit-render.mjs";
+import { ORCA_UNIT_MARKER, readTrustedConfig } from "./orca-unit-files";
+
+export { ORCA_UNIT_MARKER, ownerUidMatches, readOrcaUnitText } from "./orca-unit-files";
+
+const SERVICE_NAME = "mso-orca.service";
+const CONTROL = /[\0\r\n]/;
+
+/**
+ * Exact proof that a unit file is the MSO-owned Orca USER unit.
+ *
+ * Ownership is granted only when the on-disk text is byte-for-byte the unit the
+ * real installer renders from the trusted `managed-service.json` receipt. That
+ * single comparison covers required sections/directives, `WorkingDirectory`,
+ * `User`, `EnvironmentFile` (never rendered), duplicate sections, `Exec*` hooks,
+ * runtime flags, the 1..65535 port, and the mandatory advertised endpoint.
+ *
+ * The expected `hostNode` is the exact launcher recorded by the installer, not
+ * `release.nodeBinary` (the pinned child runtime) and not a basename guess.
+ */
+export type OrcaUnitProof = "owned" | "reinstall-required" | "not-owned";
+
+/** Diagnostic-only shape check. This never grants ownership; it only lets the
+ * consumer say "old MSO unit, reinstall" instead of "foreign unit". */
+function looksLikeMsoUnit(text: string, root: string, cliScript: string): boolean {
+ if (!text.startsWith(`${ORCA_UNIT_MARKER}\n`)) return false;
+ return text.includes(` ${systemdQuote(cliScript)} "run" "--managed-root" ${systemdQuote(root)}`);
+}
+
+export async function proveOwnedOrcaUnit(text: string, root: string, cliScript: string): Promise<OrcaUnitProof> {
+ if (typeof text !== "string" || !path.isAbsolute(cliScript) || CONTROL.test(cliScript)) return "not-owned";
+ const read = await readTrustedConfig(root);
+ if (read.state === "missing" || read.state === "stale") {
+ return looksLikeMsoUnit(text, root, cliScript) ? "reinstall-required" : "not-owned";
+ }
+ if (read.state !== "ok" || read.config.cliScript !== cliScript) return "not-owned";
+ const { config } = read;
+ const expected = renderUnitText({
+ marker: ORCA_UNIT_MARKER,
+ serviceName: SERVICE_NAME,
+ hostNode: config.hostNode,
+ cliScript,
+ managedRoot: config.managedRoot,
+ port: config.port,
+ advertisedEndpoint: config.advertisedEndpoint
+ });
+ return text === expected ? "owned" : "not-owned";
+}
+
+export async function isOwnedOrcaUnit(text: string, root: string, cliScript: string): Promise<boolean> {
+ return (await proveOwnedOrcaUnit(text, root, cliScript)) === "owned";
+}
diff --git a/lib/managed-apps/proxy-csp.ts b/lib/managed-apps/proxy-csp.ts
index a45dfda4..9c5f754d 100644
--- a/lib/managed-apps/proxy-csp.ts
+++ b/lib/managed-apps/proxy-csp.ts
@@ -1,17 +1,13 @@
// The containment policy the managed-app proxy puts on the iframe, and the merge
// that keeps the upstream's own hardening instead of replacing it with ours.
-//
// Ours is the only policy the browser sees: the response allowlist in
// proxy-headers.ts never copies the upstream `content-security-policy` (it carries
// `frame-ancestors 'none'`, which would un-frame the app). Dropping it wholesale
// also threw away real hardening — live OpenClaw pins its two inline scripts by
// sha256 and grants no 'unsafe-inline' at all — so the upstream policy is now
// INTERSECTED into ours per directive: a source survives only if BOTH policies
-// allow it, and the emitted directive is the tighter of the two. Hermes sends no
-// policy, so for Hermes the result is ours, unchanged.
-//
-// Server-only (it pins the injected shim by hash, via node:crypto).
-// proxy-headers.ts must not import it.
+// allow it, and the emitted directive is the tighter of the two.
+// Server-only (pins injected shim by hash via node:crypto). proxy-headers.ts must not import it.
type Policy = Map<string, string[]>;
@@ -27,6 +23,8 @@ export interface PolicyMount {
* because a frame that will not display is a visible failure while a guessed
* framer is a silent invitation. */
cockpitOrigin?: string | null;
+ /** App ID for app-scoped capability adjustments (e.g. wasm-unsafe-eval for Orca). */
+ appId?: string | null;
}
// Containment for the iframe: it runs on the mso origin with
@@ -77,14 +75,15 @@ function frameAncestors(mount: PolicyMount): string[] {
const socketOrigin = (url: string): string => url.replace(/^https:/i, "wss:").replace(/^http:/i, "ws:");
function ourPolicy(prefixUrl: string, mount: PolicyMount): Policy {
+ const isOrca = mount.appId === "orca";
return new Map([
["default-src", [prefixUrl]],
- ["script-src", [prefixUrl, "'unsafe-inline'", "blob:"]],
+ ["script-src", isOrca ? [prefixUrl, "'unsafe-inline'", "blob:", "'wasm-unsafe-eval'"] : [prefixUrl, "'unsafe-inline'", "blob:"]],
["style-src", [prefixUrl, "'unsafe-inline'"]],
["img-src", [prefixUrl, "data:", "blob:"]],
["font-src", [prefixUrl, "data:", "https:"]],
["media-src", [prefixUrl, "data:", "blob:"]],
- ["worker-src", ["blob:"]],
+ ["worker-src", isOrca ? [prefixUrl, "blob:"] : ["blob:"]],
["connect-src", [prefixUrl, socketOrigin(prefixUrl), "data:", "blob:"]],
["frame-src", [prefixUrl]],
["form-action", [prefixUrl]],
@@ -105,15 +104,8 @@ const oursWin = (name: string): boolean => name === "frame-ancestors";
// `default-src 'self'` constrains our frame-src too. form-action/base-uri/
// frame-ancestors never fall back: an upstream that omits them constrains nothing.
const FALLS_BACK = new Set([
- "script-src",
- "style-src",
- "img-src",
- "font-src",
- "media-src",
- "connect-src",
- "worker-src",
- "frame-src",
- "object-src",
+ "script-src", "style-src", "img-src", "font-src", "media-src",
+ "connect-src", "worker-src", "frame-src", "object-src",
]);
// Where an upstream-declared external host is honoured rather than blocked: the
diff --git a/lib/managed-apps/proxy-headers.ts b/lib/managed-apps/proxy-headers.ts
index 0804fb35..c62d8427 100644
--- a/lib/managed-apps/proxy-headers.ts
+++ b/lib/managed-apps/proxy-headers.ts
@@ -10,13 +10,8 @@
// mso origin and then preemptively attach that Authorization header to other
// mso paths, which we would forward onward.
const REQUEST_HEADERS = [
- "accept",
- "accept-language",
- "content-type",
- "range",
- "if-none-match",
- "if-modified-since",
- "x-requested-with",
+ "accept", "accept-language", "content-type", "range",
+ "if-none-match", "if-modified-since", "x-requested-with",
];
// Per-app additions to the list above. Kept separate because each entry IS one
@@ -43,14 +38,8 @@ const APP_REQUEST_HEADERS: Record<string, readonly string[]> = {
// upstream policy is not echoed but it is not ignored either — proxy-csp.ts
// intersects it into ours, so its hardening survives without its frame rules.
const RESPONSE_HEADERS = [
- "content-type",
- "cache-control",
- "etag",
- "last-modified",
- "content-range",
- "accept-ranges",
- "content-disposition",
- "vary",
+ "content-type", "cache-control", "etag", "last-modified",
+ "content-range", "accept-ranges", "content-disposition", "vary",
];
// Cookie NAMESPACE, not a path. Load-bearing on an app host too: the cockpit
@@ -246,6 +235,11 @@ export function isServiceWorkerPath(segments: string[]): boolean {
return last !== undefined && SERVICE_WORKER_SCRIPTS.has(last.toLowerCase());
}
+export function isServiceWorkerRequest(segments: string[], secFetchDest?: string | null): boolean {
+ if (secFetchDest?.trim().toLowerCase() === "serviceworker") return true;
+ return isServiceWorkerPath(segments);
+}
+
// The policy itself lives in proxy-csp.ts: building it needs node:crypto (it pins
// the injected shim by hash). Both modules are server-only — nothing under
// frontend/ imports either one.
diff --git a/lib/managed-apps/proxy-rewrite-origin.test.ts b/lib/managed-apps/proxy-rewrite-origin.test.ts
new file mode 100644
index 00000000..835f5f04
--- /dev/null
+++ b/lib/managed-apps/proxy-rewrite-origin.test.ts
@@ -0,0 +1,75 @@
+// The production request shape for an app host, and the Next 16 rewrite-origin rule.
+//
+// Traefik passes `Host: <app>.mso.example.com` through (passHostHeader) while
+// `x-forwarded-proto: https` makes Next describe its OWN plain-HTTP listener with a
+// synthetic `https://localhost:PORT` nextUrl. Next (verified on 16.3.8:
+// resolve-routes getRelativeURL compares the rewrite origin against initUrl by exact
+// equality) resolves the rewrite internally ONLY when the destination origin equals
+// that nextUrl origin.
+//
+// The old code downgraded the loopback scheme to `http:` before building the target.
+// The destination then had a different origin than initUrl, so Next classified the
+// rewrite as external, self-hopped it over the network against the public Host, and
+// middleware re-ran there as a NON-app host — stripping the managed-app marker and
+// 404ing the proxy route. proxy.ts now builds the destination from nextUrl.origin.
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+vi.mock("@/lib/managed-apps/session", () => ({ gateManagedApp: vi.fn(async () => null) }));
+
+const TEMPLATE = "{id}.mso.example.com";
+const APP_HOST_HEADER = "x-os-managed-app-host";
+
+async function loadProxy(template: string) {
+ vi.resetModules();
+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", template);
+ return (await import("../../proxy")).proxy;
+}
+
+/** As it reaches middleware behind a TLS-terminating proxy: Host is the app name and
+ * nextUrl is a synthetic https loopback derived from x-forwarded-proto. */
+function proxyReq(
+ host: string,
+ path: string,
+ init: { method?: string; headers?: HeadersInit; body?: string } = {},
+): NextRequest {
+ const headers = new Headers(init.headers);
+ headers.set("host", host);
+ headers.set("x-forwarded-proto", "https");
+ return new NextRequest(`https://127.0.0.1:3000${path}`, { ...init, headers });
+}
+
+const rewriteOf = (res: Response) => res.headers.get("x-middleware-rewrite");
+const stampedHost = (res: Response) =>
+ res.headers.get(`x-middleware-request-${APP_HOST_HEADER}`);
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe("the app-host rewrite keeps nextUrl's exact origin (Next 16)", () => {
+ it("classifies the rewrite as same-origin instead of downgrading to http", async () => {
+ const proxy = await loadProxy(TEMPLATE);
+ const request = proxyReq("orca.mso.example.com", "/web-index.html?tab=1");
+ // Guard the fixture: the whole point is a synthetic https loopback nextUrl.
+ expect(request.nextUrl.origin).toBe("https://localhost:3000");
+ const res = await proxy(request);
+ const dest = new URL(rewriteOf(res)!);
+ // Equal origin to initUrl is what makes Next resolve the rewrite internally;
+ // the old `http://localhost:3000` differed and became an external self-hop.
+ expect(dest.origin).toBe(request.nextUrl.origin);
+ expect(dest.protocol).toBe("https:");
+ expect(dest.pathname).toBe("/api/v1/managed-apps/orca/proxy/web-index.html");
+ expect(dest.search).toBe("?tab=1");
+ });
+
+ it("still overwrites the client marker when the nextUrl host is loopback", async () => {
+ const proxy = await loadProxy(TEMPLATE);
+ const res = await proxy(
+ proxyReq("orca.mso.example.com", "/", {
+ headers: { [APP_HOST_HEADER]: "hermes" },
+ }),
+ );
+ expect(stampedHost(res)).toBe("orca");
+ expect(new URL(rewriteOf(res)!).origin).toBe("https://localhost:3000");
+ });
+});
diff --git a/lib/managed-apps/service-state.ts b/lib/managed-apps/service-state.ts
new file mode 100644
index 00000000..8ddc1f5a
--- /dev/null
+++ b/lib/managed-apps/service-state.ts
@@ -0,0 +1,61 @@
+import "server-only";
+import { runDocker } from "./docker";
+import { orcaRunState, type ManagedInstallation } from "./orca-installation";
+import { runProgram } from "./runner";
+import { userBusEnv } from "./user-bus";
+
+/**
+ * Service/container run-state detection for managed apps.
+ *
+ * `is-active` cannot tell "this unit is stopped" from "this unit does not
+ * exist", so `show -p LoadState` distinguishes absent units from installed
+ * stopped ones. An owned Orca unit is additionally tri-valued: systemd not
+ * answering is `unknown`, never `stopped`.
+ */
+export async function systemdState(service: string, strict = false): Promise<"active" | "inactive" | "missing"> {
+ let present = false;
+ for (const scope of [["--user"], []]) {
+ // The user scope needs a bus address. mso.service is a SYSTEM unit with
+ // `User=`, which inherits no login session and therefore no
+ // XDG_RUNTIME_DIR, so without this every `--user` probe below answered
+ // "Failed to connect to bus: No medium found" and the whole scope was
+ // silently skipped — the app then looked absent no matter what was running.
+ const env = scope.length ? userBusEnv() : undefined;
+ const result = await runProgram("systemctl", [...scope, "show", "-p", "LoadState", "-p", "ActiveState", service], 10_000, env);
+ // Non-zero here is no systemctl at all, or no user bus — not an answer about
+ // the unit, so try the next scope rather than concluding anything.
+ if (result.code !== 0) { if (strict) throw new Error("Cannot confirm all managed-app service states"); continue; }
+ const load = /LoadState=(\S+)/.exec(result.stdout)?.[1];
+ if (!load || load === "not-found") continue;
+ present = true;
+ if (/ActiveState=(?:active|activating|deactivating|reloading)\b/.test(result.stdout)) return "active";
+ }
+ return present ? "inactive" : "missing";
+}
+
+/** `unknown` means systemd gave no definite answer about an owned Orca unit —
+ * never silently equal to "stopped". */
+type ManagedRunState = "running" | "stopped" | "unknown";
+
+export async function managedRunState(installation: ManagedInstallation, strict = false): Promise<ManagedRunState> {
+ // Owned Orca: user scope only. A system unit of the same name is never ours.
+ if (installation.owned && installation.serviceName) {
+ const state = await orcaRunState(installation.serviceName);
+ if (state !== "unknown") return state;
+ // A strict quiescence check must never read "no bus"/"not loaded" as
+ // "stopped"; a normal read surfaces it as unknown, not a silent stop.
+ if (strict) throw new Error(`Cannot confirm ${installation.serviceName} is stopped: its user-scope systemd state is unknown`);
+ return "unknown";
+ }
+ if (installation.serviceNames && (await Promise.all(installation.serviceNames.map(name => systemdState(name, strict)))).some((state) => state === "active")) return "running";
+ for (const containerName of installation.containerNames ?? []) {
+ const result = await runDocker(["inspect", "--format", "{{.State.Running}}", containerName], 10_000);
+ if (result.code !== 0 || !["true", "false"].includes(result.stdout.trim())) throw new Error("Cannot confirm managed-app container state");
+ if (result.stdout.trim() === "true") return "running";
+ }
+ return "stopped";
+}
+
+export async function running(installation: ManagedInstallation, strict = false): Promise<boolean> {
+ return (await managedRunState(installation, strict)) === "running";
+}
diff --git a/lib/managed-apps/socket-policy.test.ts b/lib/managed-apps/socket-policy.test.ts
index 7532f97d..52b8cbd1 100644
--- a/lib/managed-apps/socket-policy.test.ts
+++ b/lib/managed-apps/socket-policy.test.ts
@@ -1,4 +1,6 @@
import { afterAll, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
import { mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
diff --git a/lib/managed-apps/socket-policy.ts b/lib/managed-apps/socket-policy.ts
index c53bd6d7..93b266af 100644
--- a/lib/managed-apps/socket-policy.ts
+++ b/lib/managed-apps/socket-policy.ts
@@ -7,20 +7,42 @@ import { deviceSessionValid } from "@/lib/auth/live-session";
import { roleAtLeast } from "@/lib/auth/roles";
import { isCamoufoxViewerHost } from "@/lib/camoufox/origin";
import { camoufoxViewerUpstreamPath } from "@/lib/camoufox/viewer-gate";
-import { managedAppIdForHost } from "./origin";
+import { managedAppIdForHost, managedAppOrigin } from "./origin";
import { getManagedAppDefinition } from "./catalog";
import { managedAppUpstream } from "./upstream-target";
import { upstreamSocketHeaders } from "./proxy-headers";
import { IS_DEMO } from "@/lib/demo";
import { shellAppSocketPolicy } from "@/lib/surfaces/socket-policy";
+import type { OrcaReadinessResult } from "./orca-readiness-parse";
-export async function socketPolicy(request: NextRequest) {
+export interface SocketPolicyDeps {
+ getOrcaReadiness?: () => Promise<OrcaReadinessResult>;
+}
+
+const denyUnavailable = (reason: string): OrcaReadinessResult => ({ available: false, reason });
+
+async function defaultOrcaReadiness(): Promise<OrcaReadinessResult> {
+ try {
+ const { getOrcaReadiness } = await import("./orca-readiness");
+ return await getOrcaReadiness();
+ } catch {
+ return denyUnavailable("bridge_unavailable");
+ }
+}
+
+export async function socketPolicy(request: NextRequest, deps: SocketPolicyDeps = {}) {
if (IS_DEMO || request.method !== "GET") return null;
const host = request.headers.get("host") ?? "", origin = request.headers.get("origin");
if (origin) { try { if (new URL(origin).host !== host) return null; } catch { return null; } }
if (!/(?:^|,)\s*websocket\s*(?:,|$)/i.test(request.headers.get("upgrade") ?? "")) return null;
const viewer = isCamoufoxViewerHost(host), app = managedAppIdForHost(host);
if (!viewer && !app) return shellAppSocketPolicy(request);
+ if (app === "orca") {
+ if (!origin || origin === "null") return null;
+ const expected = managedAppOrigin("orca");
+ if (!expected) return null;
+ try { if (new URL(origin).origin.toLowerCase() !== expected.toLowerCase()) return null; } catch { return null; }
+ }
const secret = process.env.OS_SESSION_SECRET ?? "";
let identity: string | undefined;
for (const { value } of request.cookies.getAll(viewer ? CAMOUFOX_VIEWER_COOKIE : MANAGED_APP_SESSION_COOKIE)) {
@@ -33,10 +55,36 @@ export async function socketPolicy(request: NextRequest) {
identity = session.device_id; break;
}
if (!identity) return null;
+ let socketIdentity = identity;
let base: URL;
- try { base = managedAppUpstream(viewer ? process.env.CAMOUFOX_NOVNC_URL ?? "http://127.0.0.1:6080" : getManagedAppDefinition(app!).dashboardUrl); } catch { return null; }
+ try {
+ if (viewer) {
+ base = managedAppUpstream(process.env.CAMOUFOX_NOVNC_URL ?? "http://127.0.0.1:6080");
+ } else if (app === "orca") {
+ // Re-verify readiness on every authorization (initial and each revalidation):
+ // the session proves WHO, not that the owned runtime still owns the endpoint.
+ // The identity also binds device to the exact runtime/PID/start ticks/inode so a
+ // same-device runtime swap changes identity and closes the live socket.
+ const readiness = await (deps.getOrcaReadiness ?? defaultOrcaReadiness)();
+ if (!readiness.available || !readiness.runtimeId || !readiness.startTicks) return null;
+ socketIdentity = JSON.stringify({
+ device: identity,
+ runtimeId: readiness.runtimeId,
+ serverPid: readiness.serverPid,
+ startTicks: readiness.startTicks,
+ listenerInode: readiness.listenerInode ?? null,
+ });
+ base = new URL(readiness.boundEndpoint);
+ if (base.protocol !== "ws:" || base.username || base.password) return null;
+ base.protocol = "http:";
+ } else {
+ base = managedAppUpstream(getManagedAppDefinition(app!).dashboardUrl);
+ }
+ } catch {
+ return null;
+ }
const pathname = viewer ? camoufoxViewerUpstreamPath(request.nextUrl.pathname) : request.nextUrl.pathname;
if (!pathname || pathname.startsWith("/_next")) return null;
const target = new URL(base); target.pathname = pathname; target.search = request.nextUrl.search;
- return { identity, target: target.toString(), headers: Object.fromEntries(upstreamSocketHeaders(request.headers, app ?? undefined, base)) };
+ return { identity: socketIdentity, target: target.toString(), headers: Object.fromEntries(upstreamSocketHeaders(request.headers, app ?? undefined, base)) };
}
diff --git a/lib/managed-apps/types.ts b/lib/managed-apps/types.ts
index 69f76331..a42dfd0c 100644
--- a/lib/managed-apps/types.ts
+++ b/lib/managed-apps/types.ts
@@ -1,6 +1,6 @@
import type { ManagedDomainRecord } from "@/lib/contracts/managed-domains";
-export const MANAGED_APP_IDS = ["hermes", "openclaw", "9router"] as const;
+export const MANAGED_APP_IDS = ["hermes", "openclaw", "9router", "orca"] as const;
export type ManagedAppId = (typeof MANAGED_APP_IDS)[number];
export const MANAGED_APP_ACTIONS = ["start", "stop", "restart", "backup"] as const;
diff --git a/lib/managed-apps/update-cli.test.ts b/lib/managed-apps/update-cli.test.ts
index d268ebdd..7cea5c7e 100644
--- a/lib/managed-apps/update-cli.test.ts
+++ b/lib/managed-apps/update-cli.test.ts
@@ -177,3 +177,17 @@ describe("the 9Router wrapper argv", () => {
expect(updateAdapter("9router").pin).toBeNull();
});
});
+
+describe("the Orca unverified adapter scaffolding", () => {
+ it("rejects update, uninstall and probe until verified adapter exists", async () => {
+ const adapter = updateAdapter("orca");
+ expect(adapter.capabilities.check).toBe(false);
+ expect(adapter.capabilities.apply).toBe(false);
+ expect(adapter.capabilities.uninstall).toBe(false);
+ expect(adapter.capabilities.rollback).toBe(false);
+ expect(adapter.pin).toBeNull();
+ expect(() => adapter.updateArgv("orca-ide", {})).toThrow("update is not supported for orca");
+ expect(() => adapter.uninstallArgv("orca-ide", false)).toThrow("uninstall is not supported for orca");
+ await expect(adapter.probe("orca-ide")).rejects.toThrow("update probing is not supported for orca");
+ });
+});
diff --git a/lib/managed-apps/update-cli.ts b/lib/managed-apps/update-cli.ts
index fbf09be3..975d943e 100644
--- a/lib/managed-apps/update-cli.ts
+++ b/lib/managed-apps/update-cli.ts
@@ -193,6 +193,22 @@ const ADAPTERS: Record<ManagedAppId, UpdateAdapter> = {
uninstallArgv: (program, dryRun) => [program, "uninstall", "--yes", ...(dryRun ? [UNINSTALL_PREVIEW_FLAG] : [])],
probe: probe9Router,
},
+ orca: {
+ capabilities: {
+ check: false,
+ apply: false,
+ dryRun: false,
+ channel: false,
+ rollback: false,
+ uninstall: false,
+ installCommand: null,
+ uninstallCommand: null,
+ },
+ pin: null,
+ updateArgv: () => reject("update", "orca"),
+ uninstallArgv: () => reject("uninstall", "orca"),
+ probe: async () => reject("update probing", "orca"),
+ },
};
export function updateAdapter(id: ManagedAppId): UpdateAdapter {
diff --git a/lib/managed-apps/update.test.ts b/lib/managed-apps/update.test.ts
index 69951574..50537ff5 100644
--- a/lib/managed-apps/update.test.ts
+++ b/lib/managed-apps/update.test.ts
@@ -142,6 +142,10 @@ describe("mutable upstream updates fail closed", () => {
expect(job.status).toBe("succeeded");
expect(await recorded("9router")).toEqual(["update", "--yes"]);
});
+
+ it("refuses orca update before any reviewed immutable target is committed", async () => {
+ await expect(startUpdate("orca")).rejects.toThrow("orca automated update is disabled until a reviewed immutable artifact target and digest are committed");
+ });
});
describe("uninstall needs the operator to type the app id", () => {
diff --git a/lib/managed-apps/update.ts b/lib/managed-apps/update.ts
index 21d0a972..f2cecc65 100644
--- a/lib/managed-apps/update.ts
+++ b/lib/managed-apps/update.ts
@@ -12,8 +12,6 @@ import type { ManagedAppDefinition, ManagedAppId, ManagedAppJob } from "./types"
import { assertChannel, updateAdapter, UNINSTALL_PREVIEW_FLAG } from "./update-cli";
import type { ManagedAppBackup, ManagedAppUpdateOptions, ManagedAppUpdateStatus } from "./update-types";
-// Validate, snapshot inside the operation, then submit guarded fixed argv.
-
/** OpenClaw's own per-STEP timeout is 1800 s and a run has several steps, so a
* 30-minute wall clock would kill a healthy update mid-step. An hour is the
* job layer's ceiling; upstream's own step timeout fires long before it. */
@@ -61,7 +59,7 @@ function unavailable(id: ManagedAppId, error: string): ManagedAppUpdateStatus {
channel: { value: null, kind: null, available: [], switchable: false, reason: null },
installKind: null,
// File-based rollback survives a missing CLI; execution controls do not.
- capabilities: { ...safeCapabilities(id, capabilities), check: false, apply: false, dryRun: false, channel: false, uninstall: false, rollback: true },
+ capabilities: { ...safeCapabilities(id, capabilities), check: false, apply: false, dryRun: false, channel: false, uninstall: false, rollback: capabilities.rollback ? true : false },
checkedAt: new Date().toISOString(),
error,
};
@@ -203,6 +201,7 @@ export async function startUninstall(id: ManagedAppId, confirmation: unknown, dr
export async function startRollback(id: ManagedAppId, backupId: string, pin?: string): Promise<ManagedAppJob> {
if (!isManagedAppBackupId(backupId)) throw new Error("unknown backup");
const adapter = updateAdapter(id);
+ if (!adapter.capabilities.rollback) throw new Error(`rollback is not supported for ${id}`);
// Refused rather than silently dropped: for Hermes the pin IS a branch switch,
// which auto-stashes the very files the restore just wrote back (update-cli.ts)
// — a rollback that quietly undoes itself and still reports success.
diff --git a/proxy.ts b/proxy.ts
index 31e81978..e76a3387 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -79,17 +79,6 @@ function notFound() {
});
}
-// Reverse proxies correctly preserve the public HTTPS scheme in x-forwarded-proto,
-// and Next folds that into nextUrl.origin even though this Next process itself is
-// listening on plain HTTP loopback. Rewriting to that synthetic https://localhost
-// origin makes Next open TLS to its own HTTP socket and fail with EPROTO. Keep the
-// public scheme everywhere else, but use the actual transport for a loopback rewrite.
-function internalRewriteOrigin(request: NextRequest): URL {
- const origin = new URL(request.nextUrl.origin);
- if (LOOPBACK_HOST.test(origin.hostname)) origin.protocol = "http:";
- return origin;
-}
-
// Extracted so the app-host branch can apply the SAME rule: after its rewrite the
// path starts with /api/, i.e. past the point where this gate would have run.
function crossOriginMutation(request: NextRequest): boolean {
@@ -259,15 +248,18 @@ export async function proxy(request: NextRequest) {
// trailing slash away before middleware even runs, and re-adding one here would
// send that redirect back to this host to be rewritten a second time, one prefix
// deeper. Two traps in building this URL:
- // • use the local transport for a loopback nextUrl origin. Reverse proxies set
- // x-forwarded-proto=https, which can make Next describe its own plain-HTTP
- // listener as https://localhost:PORT. internalRewriteOrigin() corrects only
- // that loopback mismatch; a real public/non-loopback origin keeps its scheme.
+ // • use nextUrl.origin EXACTLY. A reverse proxy sets x-forwarded-proto, so Next
+ // describes its own plain-HTTP listener with a synthetic https://loopback origin
+ // (verified on Next 16.3.8: resolve-routes getRelativeURL compares the rewrite
+ // origin against initUrl by exact equality). Any other origin — e.g. downgrading
+ // the loopback scheme to match the socket — is classified EXTERNAL and self-hopped
+ // over the network against the public Host, where middleware re-runs as a non-app
+ // host, strips the marker below, and 404s the proxy route.
// • a plain URL, not nextUrl.clone(): NextURL remembers the incoming trailing
// slash and puts it back when the pathname is reassigned.
const path = `${proxyPrefix(managedApp)}${pathname.replace(/\/+$/, "")}`;
return NextResponse.rewrite(
- new URL(`${path}${request.nextUrl.search}`, internalRewriteOrigin(request)),
+ new URL(`${path}${request.nextUrl.search}`, request.nextUrl.origin),
{
request: { headers },
},
diff --git a/scripts/cli/managed-apps.sh b/scripts/cli/managed-apps.sh
index 954b75af..b2813444 100644
--- a/scripts/cli/managed-apps.sh
+++ b/scripts/cli/managed-apps.sh
@@ -20,8 +20,8 @@ mso_mapp_enable() {
local id="${1:?application ID required}" response job
shift
case "$id" in
- hermes|openclaw|9router) ;;
- *) die "choose hermes, openclaw or 9router" ;;
+ hermes|openclaw|9router|orca) ;;
+ *) die "choose hermes, openclaw, 9router or orca" ;;
esac
response="$(jget "/api/v1/managed-apps/$(enc "$id")")"
if ! jq -e '.app.installed == true' <<<"$response" >/dev/null; then
diff --git a/scripts/domain-cli.test.ts b/scripts/domain-cli.test.ts
index 56e6ee51..b834f0e3 100644
--- a/scripts/domain-cli.test.ts
+++ b/scripts/domain-cli.test.ts
@@ -27,6 +27,15 @@ it("rejects incomplete/unknown/credential arguments before any setup write", asy
}
expect(await fs.stat(path.join(directory, "domains.json")).catch(() => null)).toBeNull();
});
+it("loads the shared domain CLI graph without the Next-only server-only marker", () => {
+ // The Orca bridge is server-only; the shared health module must reach it lazily
+ // so this Bun graph never tries to resolve the Next bundler alias `server-only`.
+ for (const args of [["status"], ["help"]]) {
+ const result = run(...args);
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stderr).not.toMatch(/server-only/i);
+ }
+});
it("prints a usable help contract and returns attention for an unconfigured ensure", () => {
const help = run("help");
expect(help.status, help.stderr).toBe(0);
diff --git a/scripts/e2e/orca-rewrite-harness.mjs b/scripts/e2e/orca-rewrite-harness.mjs
new file mode 100644
index 00000000..f4e2a4ad
--- /dev/null
+++ b/scripts/e2e/orca-rewrite-harness.mjs
@@ -0,0 +1,200 @@
+// Synthetic, loopback-only harness for the managed-app internal-rewrite regression.
+//
+// Nothing here touches owner state, services, DNS, or real credentials: a fake Orca
+// upstream plus an owner-only Orca managed root (status + runtime-identity files and
+// a real owned `node` process so the readiness bridge can verify process identity).
+// The fake upstream child process itself owns the actual HTTP upstream listener socket,
+// so its kernel PID matches the server-identity receipt.
+// The fake upstream proves the server-side rewrite reaches the upstream instead of
+// self-hopping; it is explicitly NOT evidence of E2E Orca/browser acceptance.
+import { writeFileSync } from "node:fs";
+import { spawn } from "node:child_process";
+import { chmod, copyFile, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { once } from "node:events";
+import os from "node:os";
+import path from "node:path";
+import { SERVER_SOURCE } from "./orca-rewrite-server-source.mjs";
+
+export const COCKPIT = "https://cockpit.example.test";
+export const APP_HOST = "orca.mso.example.com";
+export const APP_ORIGIN = `https://${APP_HOST}`;
+export const ORCA_VERSION = "1.4.230";
+export const RUNTIME_ID = "fixture-orca-runtime";
+
+/** Strip every credential-shaped value before anything is printed or persisted. */
+export const redact = (text) => String(text)
+ .replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer <redacted>")
+ .replace(/(__Host-[A-Za-z0-9_-]+=)[^;,\s"]+/gi, "$1<redacted>")
+ .replace(/(app_ticket=)[A-Za-z0-9._-]+/gi, "$1<redacted>")
+ .replace(/orca:\/\/pair#[A-Za-z0-9_-]+/gi, "orca://pair#<redacted>")
+ .replace(/((?:cookie|authorization|set-cookie)"?\s*[:=]\s*"?)[^\n"]+/gi, "$1<redacted>");
+
+/** Create temporary fixture directory under os.tmpdir(). */
+export async function createFixtureDirectory(prefix = "mso-orca-rewrite-") {
+ const dir = await mkdtemp(path.join(os.tmpdir(), prefix));
+ await chmod(dir, 0o700);
+ return dir;
+}
+
+/** Create the MSO-owned Orca root the readiness bridge verifies.
+ * The spawned child process itself creates and owns the HTTP upstream listener,
+ * reports its chosen port 0 over IPC, and records request hits (safe url/host only).
+ * The runtime-identity and status receipts record this exact child listener PID. */
+export async function seedOrcaRuntime(root, options = {}) {
+ const opts = typeof options === "object" && options !== null ? options : {};
+ const binDir = path.join(root, "node", "bin");
+ const releaseDir = path.join(root, "releases", ORCA_VERSION);
+ const userData = path.join(root, "runtime", "user-data");
+ await mkdir(binDir, { recursive: true, mode: 0o700 });
+ await mkdir(releaseDir, { recursive: true, mode: 0o700 });
+ await mkdir(userData, { recursive: true, mode: 0o700 });
+
+ const nodeBinary = path.join(binDir, "node");
+ const serverEntry = path.join(releaseDir, "orca-server.js");
+ await copyFile(process.execPath, nodeBinary);
+ await chmod(nodeBinary, 0o755);
+ await writeFile(serverEntry, SERVER_SOURCE, { mode: 0o600 });
+
+ const hits = [];
+ const hitListeners = new Set();
+ const child = spawn(nodeBinary, [serverEntry], {
+ stdio: ["ignore", "ignore", "ignore", "ipc"], env: { NODE_ENV: "test" },
+ });
+ if (typeof opts.onSpawn === "function") {
+ try { opts.onSpawn(child); } catch { /* caller callback error */ }
+ }
+
+ let closed = false;
+ const close = async () => {
+ if (closed) return;
+ closed = true;
+ if (child.exitCode === null && child.signalCode === null) {
+ const exitPromise = once(child, "exit");
+ try { if (child.connected) child.send("close"); else child.kill("SIGTERM"); } catch { child.kill("SIGTERM"); }
+ const killTimer = setTimeout(() => { try { child.kill("SIGKILL"); } catch { /* safe */ } }, 2000);
+ killTimer.unref?.();
+ try { await exitPromise; } finally { clearTimeout(killTimer); }
+ }
+ };
+
+ const waitForHits = async (expectedCount, timeoutMs = 2000) => {
+ if (hits.length >= expectedCount) return hits;
+ return new Promise((resolve) => {
+ const timer = setTimeout(() => { cleanup(); resolve(hits); }, timeoutMs);
+ timer.unref?.();
+ const onHit = () => { if (hits.length >= expectedCount) { cleanup(); resolve(hits); } };
+ const cleanup = () => { clearTimeout(timer); hitListeners.delete(onHit); };
+ hitListeners.add(onHit);
+ });
+ };
+
+ try {
+ let upstreamPort = 0;
+ await new Promise((resolve, reject) => {
+ let resolved = false;
+ const timer = setTimeout(() => {
+ cleanup();
+ reject(new Error("timeout waiting for fixture runtime IPC listening"));
+ }, 5000);
+ timer.unref?.();
+ const onMsg = (msg) => {
+ if (typeof msg === "object" && msg !== null) {
+ if (msg.type === "listening" && !resolved) {
+ upstreamPort = Number(msg.port);
+ resolved = true;
+ cleanup();
+ resolve(upstreamPort);
+ } else if (msg.type === "hit" && msg.hit) {
+ hits.push({ url: String(msg.hit.url), host: String(msg.hit.host) });
+ for (const listener of hitListeners) listener();
+ }
+ }
+ };
+ const onErr = (err) => { cleanup(); reject(err); };
+ const onExit = (code, sig) => {
+ cleanup();
+ reject(new Error(`child exited before listening (code=${code}, sig=${sig})`));
+ };
+ function cleanup() {
+ clearTimeout(timer);
+ child.removeListener("error", onErr);
+ child.removeListener("exit", onExit);
+ }
+ child.on("message", onMsg);
+ child.once("error", onErr);
+ child.once("exit", onExit);
+ });
+
+ const pid = child.pid;
+ let startTicks = "";
+ for (let i = 0; i < 100 && !startTicks; i++) {
+ try {
+ const stat = await readFile(`/proc/${pid}/stat`, "utf8");
+ const rest = stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/);
+ if (rest[19] && /^\d+$/.test(rest[19])) startTicks = rest[19];
+ } catch { /* waiting for proc stat */ }
+ if (!startTicks) await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ if (!startTicks) throw new Error("could not read start ticks for fixture runtime process");
+
+ const receiptPid = opts.wrongPid ? (typeof opts.wrongPid === "number" ? opts.wrongPid : pid + 999999) : pid;
+ const receiptPort = opts.wrongPort ? (typeof opts.wrongPort === "number" ? opts.wrongPort : upstreamPort + 1) : upstreamPort;
+ const pairingCode = Buffer.from(JSON.stringify({
+ v: 2, scope: "runtime", endpoint: `wss://${APP_HOST}`,
+ deviceToken: "fixture-device-token", publicKeyB64: "Zml4dHVyZS1rZXk",
+ })).toString("base64url");
+ const boundEndpoint = `ws://127.0.0.1:${receiptPort}`;
+ const writeReceipt = typeof opts.writeReceipt === "function" ? opts.writeReceipt : writeFile;
+
+ await writeReceipt(path.join(root, "private-status.json"), JSON.stringify({
+ type: "orca_server_ready", schemaVersion: 1, runtimeId: RUNTIME_ID,
+ health: {
+ buildVersion: ORCA_VERSION, nodeVersion: "24.21.0", nodeAbi: 137, pid: receiptPid,
+ terminalDaemon: { state: "live", ownsFreshSessions: true, selfTest: { ok: true } },
+ },
+ boundEndpoint, advertisedEndpoint: `wss://${APP_HOST}`,
+ pairing: { available: true, scope: "runtime", url: `orca://pair#${pairingCode}` },
+ }), { mode: 0o600 });
+
+ await writeReceipt(path.join(root, "runtime-identity.json"), JSON.stringify({
+ schemaVersion: 1, runtimeId: RUNTIME_ID, version: ORCA_VERSION,
+ serverPid: receiptPid, serverStartTicks: startTicks,
+ nodeBinary, serverEntry, userData, boundEndpoint, advertisedEndpoint: `wss://${APP_HOST}`, readyAt: new Date().toISOString(),
+ }), { mode: 0o600 });
+
+ return { pid, port: upstreamPort, url: `http://127.0.0.1:${upstreamPort}`, hits, waitForHits, close, kill: close };
+ } catch (err) {
+ await close();
+ throw err;
+ }
+}
+
+/** Backward-compatible alias for starting fake Orca upstream fixture. */
+export async function startOrcaUpstream(existingRoot) {
+ const root = existingRoot ?? await createFixtureDirectory("mso-orca-upstream-");
+ return seedOrcaRuntime(root);
+}
+
+/** Emit bounded, credential-free response metadata and retain the redacted server
+ * log at an explicit private path, BEFORE an assertion fires, so a non-200 is
+ * diagnosable without leaking cookies/tickets/pairing codes. */
+export function createDiagnostics({ file, getPhase, hits, getLog }) {
+ return function dump(label, res) {
+ const safeHits = typeof hits === "function" ? hits() : (Array.isArray(hits) ? hits : []);
+ const safePhase = typeof getPhase === "function" ? getPhase() : String(getPhase ?? "");
+ const safeLog = redact(typeof getLog === "function" ? getLog() : String(getLog ?? "")).slice(-4000);
+ const targetFile = typeof file === "function" ? file() : file;
+ const safe = {
+ phase: safePhase, label, status: res?.status,
+ headerNames: res?.headers && typeof res.headers === "object" ? Object.keys(res.headers).sort() : [],
+ body: redact(res?.text ?? "").slice(0, 400),
+ upstreamHits: safeHits.length,
+ upstreamHosts: safeHits.slice(-5).map((hit) => hit.host),
+ };
+ if (targetFile) {
+ try { writeFileSync(targetFile, `phase=${safePhase}\n${JSON.stringify(safe, null, 2)}\n--- mso server log (redacted, tail) ---\n${safeLog}\n`, { mode: 0o600 }); } catch { /* diagnostics are best-effort */ }
+ }
+ console.error("DIAG " + label + " " + JSON.stringify(safe));
+ console.error("DIAG mso server log (redacted, tail):\n" + safeLog);
+ };
+}
diff --git a/scripts/e2e/orca-rewrite-harness.test.ts b/scripts/e2e/orca-rewrite-harness.test.ts
new file mode 100644
index 00000000..6048bda8
--- /dev/null
+++ b/scripts/e2e/orca-rewrite-harness.test.ts
@@ -0,0 +1,147 @@
+import { afterAll, describe, expect, it, vi } from "vitest";
+
+vi.mock("server-only", () => ({}));
+
+vi.hoisted(() => {
+ process.env.NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE = "{id}.mso.example.com";
+ process.env.OS_PUBLIC_ORIGIN = "https://mso.example.com";
+});
+
+import type { ChildProcess } from "node:child_process";
+import { rm } from "node:fs/promises";
+import http from "node:http";
+import net from "node:net";
+import { getOrcaReadiness } from "../../lib/managed-apps/orca-readiness";
+import { createFixtureDirectory, seedOrcaRuntime } from "./orca-rewrite-harness.mjs";
+
+function get(url: string): Promise<{ status: number; text: string }> {
+ return new Promise((resolve, reject) => {
+ http.get(url, (res) => {
+ let text = "";
+ res.setEncoding("utf8");
+ res.on("data", (chunk) => { text += chunk; });
+ res.on("end", () => resolve({ status: res.statusCode ?? 0, text }));
+ }).on("error", reject);
+ });
+}
+
+describe("orca-rewrite-harness built-server fixture", () => {
+ const cleanupDirs: string[] = [];
+
+ afterAll(async () => {
+ while (cleanupDirs.length > 0) {
+ const dir = cleanupDirs.pop()!;
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
+ }
+ });
+
+ it("denies readiness when receipt serverPid does not own the listener socket", async () => {
+ const root = await createFixtureDirectory("mso-orca-test-red-");
+ cleanupDirs.push(root);
+
+ const runtime = await seedOrcaRuntime(root, { wrongPid: true });
+ try {
+ const env: NodeJS.ProcessEnv = {
+ NODE_ENV: "test",
+ ORCA_HOME: root,
+ ORCA_DASHBOARD_URL: runtime.url,
+ };
+ const readiness = await getOrcaReadiness({ env });
+ expect(readiness.available).toBe(false);
+ if (!readiness.available) {
+ expect(["listener_not_owned_by_process", "process_identity_unavailable"]).toContain(readiness.reason);
+ }
+ } finally {
+ await runtime.close();
+ }
+ });
+
+ it("denies readiness when receipt claims a different loopback port not listened by child", async () => {
+ const root = await createFixtureDirectory("mso-orca-test-port-");
+ cleanupDirs.push(root);
+
+ const server = net.createServer();
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
+ const wrongPort = (server.address() as net.AddressInfo).port;
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+
+ const runtime = await seedOrcaRuntime(root, { wrongPort });
+ try {
+ const env: NodeJS.ProcessEnv = {
+ NODE_ENV: "test",
+ ORCA_HOME: root,
+ ORCA_DASHBOARD_URL: `http://127.0.0.1:${wrongPort}`,
+ };
+ const readiness = await getOrcaReadiness({ env });
+ expect(readiness.available).toBe(false);
+ if (!readiness.available) {
+ expect(["listener_not_found", "listener_not_owned_by_process"]).toContain(readiness.reason);
+ }
+ } finally {
+ await runtime.close();
+ }
+ });
+
+ it("cleans up child process when receipt write fails", async () => {
+ const root = await createFixtureDirectory("mso-orca-test-fail-");
+ cleanupDirs.push(root);
+
+ let pid: number | undefined;
+ await expect(
+ seedOrcaRuntime(root, {
+ onSpawn(child: ChildProcess) {
+ pid = child.pid;
+ },
+ writeReceipt: async () => {
+ throw new Error("fixture receipt failure");
+ },
+ }),
+ ).rejects.toThrow("fixture receipt failure");
+
+ expect(pid).toBeDefined();
+ expect(pid).toBeGreaterThan(1);
+ expect(() => process.kill(pid!, 0)).toThrow();
+ });
+
+ it("proves fixture child owns actual upstream listener with same PID and handles requests", async () => {
+ const root = await createFixtureDirectory("mso-orca-test-green-");
+ cleanupDirs.push(root);
+
+ const runtime = await seedOrcaRuntime(root);
+ try {
+ expect(runtime.pid).toBeGreaterThan(1);
+ expect(runtime.port).toBeGreaterThan(0);
+ expect(runtime.url).toBe(`http://127.0.0.1:${runtime.port}`);
+
+ const env: NodeJS.ProcessEnv = {
+ NODE_ENV: "test",
+ ORCA_HOME: root,
+ ORCA_DASHBOARD_URL: runtime.url,
+ };
+ const readiness = await getOrcaReadiness({ env });
+ expect(readiness.available).toBe(true);
+ if (readiness.available) {
+ expect(readiness.serverPid).toBe(runtime.pid);
+ expect(readiness.boundEndpoint).toBe(`ws://127.0.0.1:${runtime.port}`);
+ }
+
+ const res200 = await get(`${runtime.url}/web-index.html`);
+ expect(res200.status).toBe(200);
+ expect(res200.text).toContain("orca-fixture-upstream");
+
+ const res404 = await get(`${runtime.url}/not-found`);
+ expect(res404.status).toBe(404);
+
+ // Brief wait for IPC hit event propagation
+ for (let i = 0; i < 50 && runtime.hits.length < 2; i++) {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ expect(runtime.hits.length).toBe(2);
+ expect(runtime.hits[0].url).toBe("/web-index.html");
+ } finally {
+ await runtime.close();
+ // Ensure child process is no longer running
+ expect(() => process.kill(runtime.pid!, 0)).toThrow();
+ }
+ });
+});
diff --git a/scripts/e2e/orca-rewrite-server-source.mjs b/scripts/e2e/orca-rewrite-server-source.mjs
new file mode 100644
index 00000000..95977672
--- /dev/null
+++ b/scripts/e2e/orca-rewrite-server-source.mjs
@@ -0,0 +1,26 @@
+export const SERVER_SOURCE = `// Fake Orca upstream listener child. Explicitly NOT real Orca acceptance.
+const http = require("node:http");
+const server = http.createServer((req, res) => {
+ if (process.send) process.send({ type: "hit", hit: { url: req.url || "", host: req.headers.host || "" } });
+ if ((req.url || "").split("?")[0] === "/web-index.html") {
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
+ res.end("<!doctype html><title>Orca fixture</title>orca-fixture-upstream\\n");
+ return;
+ }
+ res.writeHead(404, { "content-type": "text/plain" });
+ res.end("upstream: no such path\\n");
+});
+server.listen(0, "127.0.0.1", () => {
+ const a = server.address();
+ if (process.send) process.send({ type: "listening", port: typeof a === "object" && a ? a.port : 0 });
+});
+function shutdown() {
+ server.closeAllConnections?.();
+ server.close(() => process.exit(0));
+ setTimeout(() => process.exit(0), 1000).unref();
+}
+process.on("message", (m) => { if (m === "close" || m?.type === "close") shutdown(); });
+process.on("SIGTERM", shutdown);
+process.on("SIGINT", shutdown);
+setInterval(() => {}, 1 << 30);
+`;
diff --git a/scripts/e2e/orca-rewrite.mjs b/scripts/e2e/orca-rewrite.mjs
new file mode 100644
index 00000000..f0c61f2c
--- /dev/null
+++ b/scripts/e2e/orca-rewrite.mjs
@@ -0,0 +1,152 @@
+// Actual built-server regression for the managed-app internal rewrite origin.
+//
+// Root cause this pins (Next 16.3.8): a reverse proxy passes `Host: <app>` through
+// while `x-forwarded-proto: https` makes Next describe its own plain-HTTP listener
+// with a synthetic `https://localhost:PORT` nextUrl. The app-host branch used to
+// downgrade that loopback scheme to `http:` before building the rewrite target, so the
+// destination origin no longer equalled `initUrl`. Next classified the rewrite as
+// EXTERNAL and self-hopped it over the network against the public Host, where middleware
+// re-ran as a non-host, stripped the managed-app marker, and 404'd (or 500'd over TLS).
+//
+// The engine computes `initUrl` from the launcher's hostname while its NextURL canonicalizes
+// a bare loopback IP to `localhost`, so `scripts/server.mjs` must hand Next the canonical
+// loopback name; the app-host branch must in turn rewrite to `request.nextUrl.origin`
+// exactly. Both halves are exercised here. Harness (fake upstream child listener,
+// synthetic readiness root, redacting diagnostics) lives in ./orca-rewrite-harness.mjs.
+import assert from "node:assert/strict";
+import { request } from "node:http";
+import { rm } from "node:fs/promises";
+import path from "node:path";
+import { releaseFixture } from "./release-fixture.mjs";
+import {
+ APP_HOST,
+ APP_ORIGIN,
+ COCKPIT,
+ createDiagnostics,
+ createFixtureDirectory,
+ seedOrcaRuntime,
+} from "./orca-rewrite-harness.mjs";
+
+const orcaRoot = await createFixtureDirectory("mso-orca-rewrite-fixture-");
+// Diagnostics go to a private scratch dir, never into the worktree/repo tree.
+const diagDir = await createFixtureDirectory("mso-orca-rewrite-diag-");
+const diagFile = path.join(diagDir, "rewrite-diagnostics.log");
+
+process.env.ORCA_HOME = orcaRoot;
+let runtime;
+
+let phase = "startup";
+let serverLog = ""; // Bounded, redacted tail only.
+let fixture;
+let ok = false;
+
+/** Raw HTTP hop to the fixture server with an explicit Host header (fetch cannot set it). */
+const hop = (pathname, { host, headers = {}, method = "GET" } = {}) =>
+ new Promise((resolve, reject) => {
+ const req = request(fixture.base + pathname, { method, headers: { host, ...headers } }, (res) => {
+ let text = "";
+ res.setEncoding("utf8");
+ res.on("data", (chunk) => { text += chunk; });
+ res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, text }));
+ });
+ req.once("error", reject);
+ req.end();
+ });
+
+const dumpDiagnostics = createDiagnostics({
+ file: diagFile, getPhase: () => phase, hits: () => runtime?.hits ?? [], getLog: () => serverLog,
+});
+
+try {
+ runtime = await seedOrcaRuntime(orcaRoot);
+ process.env.ORCA_DASHBOARD_URL = runtime.url;
+
+ fixture = await releaseFixture({
+ publicOrigin: COCKPIT,
+ onLog: (stream, text) => { serverLog = (serverLog + `[${stream}] ${text}`).slice(-8000); },
+ });
+ phase = "login";
+
+ const login = await fetch(fixture.base + "/api/auth/login", {
+ method: "POST", headers: { "content-type": "application/json", origin: fixture.base },
+ body: JSON.stringify({ password: fixture.password, deviceId: fixture.device }),
+ });
+ assert.equal(login.status, 200, "owner login must succeed");
+ const sessionCookie = login.headers.get("set-cookie").split(";")[0];
+
+ const session = await fetch(fixture.base + "/api/v1/managed-apps/orca/session", { headers: { cookie: sessionCookie } });
+ assert.equal(session.status, 200, "orca session ticket must be issued from the synthetic readiness root");
+ const { ticket, origin } = await session.json();
+ assert.equal(origin, APP_ORIGIN, "the ticket is bound to the orca split origin");
+
+ const grant = await hop("/__mso_app_auth", {
+ host: APP_HOST, method: "POST",
+ headers: { origin: APP_ORIGIN, authorization: `Bearer ${ticket}`, "x-forwarded-proto": "https" },
+ });
+ assert.equal(grant.status, 204, "legit ticket exchange mints the app cookie");
+ const appCookie = (grant.headers["set-cookie"] ?? [])[0]?.split(";")[0] ?? "";
+ assert.match(appCookie, /^__Host-mso-managed-app=/);
+
+ // THE REGRESSION: forwarded HTTPS to the app host must reach the real upstream.
+ phase = "https-index";
+ const httpsIndex = await hop("/web-index.html?tab=1", {
+ host: APP_HOST, headers: { cookie: appCookie, "x-forwarded-proto": "https" },
+ });
+ if (httpsIndex.status !== 200) {
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ dumpDiagnostics("forwarded-HTTPS app-host", httpsIndex);
+ }
+ assert.equal(httpsIndex.status, 200, "forwarded-HTTPS app-host fetch must reach the upstream, not self-hop");
+ assert.equal(httpsIndex.headers["x-managed-app"], "orca");
+ assert.match(httpsIndex.text, /orca-fixture-upstream/);
+
+ // HTTP control: no x-forwarded-proto, so nextUrl's origin is the real http loopback.
+ phase = "http-control";
+ const httpIndex = await hop("/web-index.html", { host: APP_HOST, headers: { cookie: appCookie } });
+ if (httpIndex.status !== 200) dumpDiagnostics("HTTP control app-host", httpIndex);
+ assert.equal(httpIndex.status, 200, "the HTTP control still reaches the upstream");
+ assert.match(httpIndex.text, /orca-fixture-upstream/);
+ assert.equal(httpIndex.headers["x-managed-app"], "orca");
+
+ // Unauthenticated forwarded-HTTPS still reaches the gate (not a rewrite 404).
+ phase = "unauthed";
+ const unauthed = await hop("/web-index.html", { host: APP_HOST, headers: { "x-forwarded-proto": "https" } });
+ if (unauthed.status !== 401) dumpDiagnostics("unauthenticated app-host", unauthed);
+ assert.equal(unauthed.status, 401, "unauthenticated app-host fetch is 401");
+ assert.doesNotMatch(unauthed.text, /orca-fixture-upstream/);
+
+ // The iframe/document bootstrap shell is served, but never upstream bytes.
+ phase = "bootstrap";
+ const bootstrap = await hop("/web-index.html", {
+ host: APP_HOST, headers: { "x-forwarded-proto": "https", "sec-fetch-dest": "iframe" },
+ });
+ assert.equal(bootstrap.status, 200, "the unauthenticated bootstrap shell is served");
+ assert.match(bootstrap.text, /__mso_app_bootstrap\.js/);
+ assert.doesNotMatch(bootstrap.text, /orca-fixture-upstream/);
+
+ // A forged marker on the COCKPIT origin must not reopen the same-origin hole.
+ phase = "forged";
+ const forged = await hop("/api/v1/managed-apps/orca/proxy/web-index.html", {
+ host: new URL(COCKPIT).host, headers: { "x-os-managed-app-host": "orca", cookie: appCookie },
+ });
+ if (forged.status !== 404) dumpDiagnostics("forged cockpit marker", forged);
+ assert.equal(forged.status, 404, "a forged marker on the cockpit origin must 404");
+
+ // Every upstream byte was fetched directly on loopback, never via the public Host.
+ await runtime.waitForHits(2);
+ assert.equal(runtime.hits.length, 2, "the upstream is fetched once per authenticated app-host request");
+ assert.ok(runtime.hits.every((hit) => /^127\.0\.0\.1:/.test(hit.host)), "upstream Host is loopback");
+
+ console.log("orca-rewrite: PASS " + JSON.stringify({
+ https: httpsIndex.status, http: httpIndex.status, unauthed: unauthed.status,
+ bootstrap: bootstrap.status, forged: forged.status, upstreamHits: runtime.hits.length,
+ }));
+ ok = true;
+} finally {
+ if (fixture) await fixture.close();
+ if (runtime) await runtime.close();
+ await rm(orcaRoot, { recursive: true, force: true });
+ // Keep the redacted diagnostic when it matters; drop it on pass so runs stay clean.
+ if (ok) await rm(diagDir, { recursive: true, force: true });
+ else console.error(`orca-rewrite: diagnostic retained at ${diagFile}`);
+}
diff --git a/scripts/e2e/release-fixture.mjs b/scripts/e2e/release-fixture.mjs
index 26feafc0..2e41b52d 100644
--- a/scripts/e2e/release-fixture.mjs
+++ b/scripts/e2e/release-fixture.mjs
@@ -6,7 +6,7 @@ import { createServer } from "node:http";
import { createHash, randomUUID, randomBytes } from "node:crypto";
import { spawn } from "node:child_process";
-export async function releaseFixture({ live = false, surfaceApps = [], publicOrigin } = {}) {
+export async function releaseFixture({ live = false, surfaceApps = [], publicOrigin, onLog } = {}) {
const dir = await mkdtemp(path.join(tmpdir(), "mso-release-e2e-"));
let providerStatus = 200;
const provider = createServer((req, res) => {
@@ -77,6 +77,9 @@ export async function releaseFixture({ live = false, surfaceApps = [], publicOri
let logs = "";
const capture = chunk => { logs = (logs + chunk.toString()).slice(-8000); };
server.stdout.on("data", capture); server.stderr.on("data", capture);
+ // Narrow optional sink for diagnostics; absent by default so every existing caller
+ // is byte-for-byte unchanged.
+ if (onLog) { server.stdout.on("data", c => onLog("stdout", c.toString())); server.stderr.on("data", c => onLog("stderr", c.toString())); }
const close = async () => {
server.kill("SIGTERM");
await Promise.race([new Promise(resolve => server.once("exit", resolve)), new Promise(resolve => setTimeout(resolve, 3000))]);
diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjs
index 8782bdb3..9e11923f 100644
--- a/scripts/e2e/release.mjs
+++ b/scripts/e2e/release.mjs
@@ -23,6 +23,7 @@ execFileSync(process.execPath, ["scripts/e2e/workflow-embeds.mjs"], { stdio: "in
execFileSync(process.execPath, ["scripts/e2e/organization-flow.mjs"], { stdio: "inherit" });
execFileSync(process.execPath, ["scripts/e2e/graph-custom.mjs"], { stdio: "inherit" });
execFileSync(process.execPath, ["scripts/e2e/nakama-slices.mjs"], { stdio: "inherit" });
+execFileSync(process.execPath, ["scripts/e2e/orca-rewrite.mjs"], { stdio: "inherit", timeout: 120000 });
const fixture = await releaseFixture();
let browser;
try {
diff --git a/scripts/e2e/shell-apps.mjs b/scripts/e2e/shell-apps.mjs
index 75b4dcc6..ce6f4e29 100644
--- a/scripts/e2e/shell-apps.mjs
+++ b/scripts/e2e/shell-apps.mjs
@@ -65,11 +65,7 @@ try {
await card.getByRole("button", { name: "Edit", exact: true }).click();
await page.getByRole("dialog").getByLabel("App URL", { exact: true }).fill("http://192.0.2.10:5678/");
await page.getByRole("button", { name: "Save changes", exact: true }).click();
- // A save also lands on the domain step; dismiss it, the edit is already stored.
- const savedDomain = page.getByRole("dialog");
- await expect(savedDomain.getByRole("heading", { name: "Domain for Fixture tool", exact: true })).toBeVisible();
- await savedDomain.locator("form").getByRole("button", { name: "Close", exact: true }).click();
- await expect(savedDomain).toHaveCount(0);
+ await expect(page.getByRole("dialog")).toHaveCount(0);
await card.getByRole("button", { name: "Open", exact: true }).click();
await expect(page.getByRole("link", { name: "Open Fixture tool", exact: true })).toHaveAttribute("href", "http://192.0.2.10:5678/");
await expect(iframe).toHaveCount(0);
diff --git a/scripts/managed-app-install b/scripts/managed-app-install
index 9dcaa54d..8b0e0a1b 100644
--- a/scripts/managed-app-install
+++ b/scripts/managed-app-install
@@ -50,9 +50,9 @@ APP_ORIGIN="${MSO_INSTALL_APP_ORIGIN:-}"
log() { printf '\n=== %s\n' "$*"; }
case "$APP" in
-hermes | openclaw | 9router) ;;
+hermes | openclaw | 9router | orca) ;;
*)
- echo "usage: managed-app-install <hermes|openclaw|9router>" >&2
+ echo "usage: managed-app-install <hermes|openclaw|9router|orca>" >&2
exit 2
;;
esac
@@ -65,6 +65,15 @@ if [ "$APP" = "9router" ]; then
exec "$(dirname "$0")/managed-app-9router" install
fi
+# Orca is the MSO-owned web/Node runtime installed as `mso-orca.service`. Its
+# adapter verifies the pinned release, the user bus (without enabling linger or
+# any other access change), the fixed loopback port and the configured split
+# origin itself, so it must NOT run through the Hermes/OpenClaw preflight below
+# (which calls `loginctl enable-linger`). Dispatch before it and stop here.
+if [ "$APP" = "orca" ]; then
+ exec "$(dirname "$0")/managed-app-orca" install
+fi
+
# Both apps are installed as systemd USER units, and `systemctl --user` finds the
# user's systemd instance through XDG_RUNTIME_DIR. MSO may be running as a systemd
# SYSTEM unit with `User=`, which inherits no login session and therefore no such
diff --git a/scripts/managed-app-loopback.test.ts b/scripts/managed-app-loopback.test.ts
index 91cf2b26..13e6f6b6 100644
--- a/scripts/managed-app-loopback.test.ts
+++ b/scripts/managed-app-loopback.test.ts
@@ -1,10 +1,14 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
+// The engine's own relativizer, so this test pins Next's real classification rule
+// instead of reimplementing it.
+import { parseRelativeURL } from "next/dist/shared/lib/router/utils/relativize-url";
vi.mock("@/lib/managed-apps/session", () => ({ gateManagedApp: vi.fn(async () => null) }));
const TEMPLATE = "{id}.mso.example.com";
const HERMES = "/api/v1/managed-apps/hermes/proxy";
-const rewriteOf = (res: Response) => res.headers.get("x-middleware-rewrite");
+const MARKER = "x-middleware-request-x-os-managed-app-host";
+const rewriteOf = (res: Response) => res.headers.get("x-middleware-rewrite") ?? "";
async function loadProxy(template: string) {
vi.resetModules();
vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", template);
@@ -12,16 +16,34 @@ async function loadProxy(template: string) {
}
afterEach(() => vi.unstubAllEnvs());
-describe("managed-app internal transport behind HTTPS termination", () => {
- it.each(["localhost", "127.0.0.1", "[::1]"])("keeps reverse-proxy rewrites to %s on local HTTP", async host => {
- const proxy = await loadProxy(TEMPLATE);
- for (const protocol of ["http", "https"]) {
- const request = new NextRequest(`${protocol}://${host}:4005/chat?from=edge`, {
- headers: { host: "hermes.mso.example.com", "x-forwarded-proto": "https" },
- });
- const res = await proxy(request);
- expect(rewriteOf(res)).toBe(`http://${request.nextUrl.host}${HERMES}/chat?from=edge`);
- }
- });
+describe("managed-app internal rewrite keeps the engine's own origin", () => {
+ // A TLS-terminating proxy passes x-forwarded-proto: https, so Next describes its
+ // plain-HTTP loopback listener as a synthetic https origin. Downgrading that origin
+ // to http: (the old transport shim) made Next treat the rewrite as EXTERNAL and
+ // self-hop it over the network: 500 over TLS, or a 404 after the marker was stripped.
+ it.each(["localhost", "127.0.0.1", "[::1]"])(
+ "preserves request.nextUrl.origin for %s over http and https",
+ async host => {
+ const proxy = await loadProxy(TEMPLATE);
+ for (const protocol of ["http", "https"]) {
+ const request = new NextRequest(`${protocol}://${host}:4005/chat?from=edge`, {
+ headers: { host: "hermes.mso.example.com", "x-forwarded-proto": "https" },
+ });
+ const res = await proxy(request);
+ const rewrite = rewriteOf(res);
+ // The rewrite origin must equal nextUrl's origin EXACTLY, scheme included.
+ expect(rewrite).toBe(`${request.nextUrl.origin}${HERMES}/chat?from=edge`);
+ expect(new URL(rewrite).origin).toBe(request.nextUrl.origin);
+
+ // The internal managed-app marker still rides the rewritten request.
+ expect(res.headers.get(MARKER)).toBe("hermes");
+
+ // Next's actual relativizer (not a copy) resolves this as in-process.
+ const destination = parseRelativeURL(rewrite, `${request.nextUrl.origin}/chat?from=edge`);
+ expect(destination.isRelative).toBe(true);
+ expect(destination.url).toBe(`${HERMES}/chat?from=edge`);
+ }
+ },
+ );
});
diff --git a/scripts/managed-app-orca b/scripts/managed-app-orca
new file mode 100755
index 00000000..cf33daa9
--- /dev/null
+++ b/scripts/managed-app-orca
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+# MSO's lifecycle adapter entry for the Orca web runtime. `lib/managed-apps`
+# drives every managed app through one adapter contract (--version / check /
+# status / install / update / uninstall); the reviewed implementation lives in
+# scripts/orca/managed-app-orca.mjs so it can be unit-tested directly.
+#
+# This wrapper only locates the implementation. It consumes no request value:
+# argv is exactly what the job layer spawned, and the fixed app id arrives as
+# $1. Nothing here reads the operator's ~/.orca state or port 6768.
+set -euo pipefail
+umask 077
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+exec node "$SCRIPT_DIR/orca/managed-app-orca.mjs" "$@"
diff --git a/scripts/mso-domain.ts b/scripts/mso-domain.ts
index c2d3162e..ac88f9fd 100644
--- a/scripts/mso-domain.ts
+++ b/scripts/mso-domain.ts
@@ -52,7 +52,7 @@ function fail(message: string): never { process.stderr.write(`mso domain: ${reda
function emit(value: unknown) { process.stdout.write(JSON.stringify(value, null, 2) + "\n"); }
function str(key: string) { return typeof options[key] === "string" ? options[key] as string : undefined; }
function selectedApp(): ManagedAppId {
- if (!(MANAGED_APP_IDS as readonly string[]).includes(appId ?? "")) fail("choose hermes, openclaw or 9router");
+ if (!(MANAGED_APP_IDS as readonly string[]).includes(appId ?? "")) fail(`choose ${MANAGED_APP_IDS.join(", ")}`);
return appId as ManagedAppId;
}
function envFile() { return path.resolve(process.env.MSO_DOMAIN_ENV ?? path.join(process.cwd(), ".env.local")); }
diff --git a/scripts/orca/artifact-source.mjs b/scripts/orca/artifact-source.mjs
new file mode 100644
index 00000000..33b8e36f
--- /dev/null
+++ b/scripts/orca/artifact-source.mjs
@@ -0,0 +1,200 @@
+/**
+ * Orca release artifact (.deb) acquisition and data-only extraction.
+ *
+ * The fixed published .deb digest is the trust anchor. Every acquisition re-verifies the
+ * file, reads package identity with `dpkg-deb -f`, and extracts into a fresh private
+ * staging directory with `dpkg-deb -x` (data only: no maintainer scripts, apt, root,
+ * graphical execution) and never trusts or overwrites an existing directory.
+ */
+
+import { randomUUID } from 'node:crypto'
+import { mkdir, rename, rm } from 'node:fs/promises'
+import { basename, dirname, join } from 'node:path'
+import {
+ ORCA_APP_ASAR_PATH,
+ ORCA_APP_ASAR_SHA256,
+ ORCA_DEB_ARCHITECTURE,
+ ORCA_DEB_FILENAME,
+ ORCA_DEB_PACKAGE,
+ ORCA_DEB_SHA256,
+ ORCA_DEB_SIZE,
+ ORCA_DEB_TEMPLATE_DIR,
+ ORCA_DEB_URL,
+ ORCA_DEB_WEB_DIR,
+ ORCA_DOWNLOAD_REDIRECT_HOSTS,
+ ORCA_VERSION
+} from './constants.mjs'
+import { downloadToFile } from './download.mjs'
+import { fileSha256 } from './node-runtime.mjs'
+import { runBoundedProcess } from './bounded-process.mjs'
+import {
+ assertNoSymlinkAncestors,
+ assertOwnedRegularFile,
+ ensurePrivateDirTree,
+ lstatOrNull
+} from './safe-paths.mjs'
+
+export async function verifyDebHash(
+ filePath,
+ expected = ORCA_DEB_SHA256,
+ { expectedSize = ORCA_DEB_SIZE } = {}
+) {
+ const s = await assertOwnedRegularFile(filePath)
+ if (expectedSize !== undefined && s.size !== expectedSize) {
+ throw new Error(`Deb archive size mismatch: expected ${expectedSize}, got ${s.size}`)
+ }
+ const actual = await fileSha256(filePath)
+ if (actual !== expected) {
+ throw new Error(`Deb archive checksum mismatch: expected ${expected}, got ${actual}`)
+ }
+ return actual
+}
+
+export async function downloadDebArchive({
+ destination,
+ signal,
+ timeoutMs = 300000,
+ fetchImpl,
+ allowedRedirectHosts = ORCA_DOWNLOAD_REDIRECT_HOSTS
+} = {}) {
+ const result = await downloadToFile({
+ url: ORCA_DEB_URL,
+ expectedUrl: ORCA_DEB_URL,
+ destination,
+ expectedSha256: ORCA_DEB_SHA256,
+ expectedSize: ORCA_DEB_SIZE,
+ maxBytes: ORCA_DEB_SIZE,
+ signal,
+ timeoutMs,
+ fetchImpl,
+ allowedRedirectHosts
+ })
+ return result.path
+}
+
+function parseControl(text) {
+ const fields = {}
+ for (const line of text.split('\n')) {
+ const match = /^([A-Za-z][A-Za-z0-9-]*):\s*(.*)$/.exec(line.trimEnd())
+ if (match) fields[match[1].toLowerCase()] = match[2].trim()
+ }
+ return fields
+}
+
+export async function readDebControl({ debPath, signal, timeoutMs = 30000 } = {}) {
+ await assertOwnedRegularFile(debPath)
+ const res = await runBoundedProcess({
+ command: 'dpkg-deb',
+ args: ['-f', debPath, 'Package', 'Version', 'Architecture'],
+ timeoutMs,
+ signal,
+ maxStdoutBytes: 8192,
+ maxStderrBytes: 8192
+ })
+ if (res.code !== 0) {
+ throw new Error(`dpkg-deb -f failed with code ${res.code}: ${res.stderr}`)
+ }
+ const fields = parseControl(res.stdout)
+ const control = {
+ package: fields.package,
+ version: fields.version,
+ architecture: fields.architecture
+ }
+ if (control.package !== ORCA_DEB_PACKAGE) {
+ throw new Error(`Deb package identity mismatch: expected ${ORCA_DEB_PACKAGE}, got ${control.package}`)
+ }
+ if (control.version !== ORCA_VERSION) {
+ throw new Error(`Deb version identity mismatch: expected ${ORCA_VERSION}, got ${control.version}`)
+ }
+ if (control.architecture !== ORCA_DEB_ARCHITECTURE) {
+ throw new Error(
+ `Deb architecture identity mismatch: expected ${ORCA_DEB_ARCHITECTURE}, got ${control.architecture}`
+ )
+ }
+ return control
+}
+
+async function assertRequiredSource(extractDir, debSha256, control) {
+ const templateDir = join(extractDir, ORCA_DEB_TEMPLATE_DIR)
+ const webDir = join(extractDir, ORCA_DEB_WEB_DIR)
+ const appAsarPath = join(extractDir, ORCA_APP_ASAR_PATH)
+ for (const dir of [templateDir, webDir]) {
+ await assertNoSymlinkAncestors(dir)
+ const s = await lstatOrNull(dir)
+ if (!s || !s.isDirectory() || s.isSymbolicLink()) {
+ throw new Error(`Extracted deb is missing a real directory: ${dir}`)
+ }
+ }
+ const asarStat = await assertOwnedRegularFile(appAsarPath)
+ const asarSha256 = await fileSha256(appAsarPath)
+ if (asarSha256 !== ORCA_APP_ASAR_SHA256) {
+ throw new Error(`app.asar checksum mismatch: expected ${ORCA_APP_ASAR_SHA256}, got ${asarSha256}`)
+ }
+ return {
+ appAsarSize: asarStat.size,
+ debSha256,
+ debSize: ORCA_DEB_SIZE,
+ debUrl: ORCA_DEB_URL,
+ ...control
+ }
+}
+
+export async function acquireAndExtractDeb({
+ debPath,
+ extractDir,
+ signal,
+ allowDownload = false,
+ timeoutMs = 120000,
+ fetchImpl
+} = {}) {
+ if (typeof extractDir !== 'string' || !extractDir.startsWith('/')) {
+ throw new Error(`extractDir must be absolute: ${extractDir}`)
+ }
+ await assertNoSymlinkAncestors(extractDir)
+ if (await lstatOrNull(extractDir)) {
+ throw new Error(`Refusing to reuse or overwrite an existing extraction: ${extractDir}`)
+ }
+ await ensurePrivateDirTree(dirname(extractDir))
+
+ let resolvedDeb = debPath
+ if (!resolvedDeb) {
+ if (!allowDownload) throw new Error('debPath is required when download is not permitted')
+ resolvedDeb = join(dirname(extractDir), ORCA_DEB_FILENAME)
+ if (!(await lstatOrNull(resolvedDeb))) {
+ await downloadDebArchive({ destination: resolvedDeb, signal, fetchImpl })
+ }
+ }
+
+ const debSha256 = await verifyDebHash(resolvedDeb)
+ const control = await readDebControl({ debPath: resolvedDeb, signal })
+
+ const stagingDir = join(dirname(extractDir), `.extract-${basename(extractDir)}-${process.pid}-${randomUUID()}`)
+ await assertNoSymlinkAncestors(stagingDir)
+ await mkdir(stagingDir, { recursive: false, mode: 0o700 })
+ try {
+ const res = await runBoundedProcess({
+ command: 'dpkg-deb',
+ args: ['-x', resolvedDeb, stagingDir],
+ timeoutMs,
+ signal,
+ maxStdoutBytes: 1024 * 1024,
+ maxStderrBytes: 65536
+ })
+ if (res.code !== 0) {
+ throw new Error(`dpkg-deb -x failed with code ${res.code}: ${res.stderr}`)
+ }
+ const source = await assertRequiredSource(stagingDir, debSha256, control)
+ if (await lstatOrNull(extractDir)) {
+ throw new Error(`Refusing to overwrite an extraction created concurrently: ${extractDir}`)
+ }
+ await rename(stagingDir, extractDir)
+ return {
+ ...source,
+ templateDir: join(extractDir, ORCA_DEB_TEMPLATE_DIR),
+ webDir: join(extractDir, ORCA_DEB_WEB_DIR),
+ appAsarPath: join(extractDir, ORCA_APP_ASAR_PATH)
+ }
+ } finally {
+ await rm(stagingDir, { recursive: true, force: true }).catch(() => {})
+ }
+}
diff --git a/scripts/orca/artifact-source.test.mjs b/scripts/orca/artifact-source.test.mjs
new file mode 100644
index 00000000..dfde9f6f
--- /dev/null
+++ b/scripts/orca/artifact-source.test.mjs
@@ -0,0 +1,88 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { join } from 'node:path'
+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { ORCA_DEB_SHA256, ORCA_DEB_SIZE, ORCA_DEB_URL } from './constants.mjs'
+import { acquireAndExtractDeb, verifyDebHash } from './artifact-source.mjs'
+
+// mkdtemp creates the directory 0700 atomically, so no predictable name is
+// ever created in the shared temp root.
+async function scratch(name) {
+ return mkdtemp(join(tmpdir(), `orca-deb-${name}-`))
+}
+
+describe('artifact-source deb verification & extraction', () => {
+ it('pins the official deb URL, size, and sha256', () => {
+ assert.equal(ORCA_DEB_SHA256, '7758be00e6564c14e5793b6a61ffe1bb0e84749583d76013a129454835788e24')
+ assert.equal(ORCA_DEB_SIZE, 209670608)
+ assert.match(ORCA_DEB_URL, /^https:\/\/github\.com\/stablyai\/orca\/releases\/download\//)
+ })
+
+ it('rejects a corrupt/unrelated deb before extraction', async () => {
+ const root = await scratch('corrupt')
+ try {
+ const fakeDeb = join(root, 'fake.deb')
+ await writeFile(fakeDeb, 'corrupt deb content', { mode: 0o600 })
+ await assert.rejects(verifyDebHash(fakeDeb), /mismatch/i)
+ await assert.rejects(
+ acquireAndExtractDeb({ debPath: fakeDeb, extractDir: join(root, 'extracted') }),
+ /mismatch/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects a symlinked deb and any symlink ancestor', async () => {
+ const root = await scratch('symlink')
+ try {
+ const real = join(root, 'real.deb')
+ await writeFile(real, 'content', { mode: 0o600 })
+ const link = join(root, 'link.deb')
+ await symlink(real, link)
+ await assert.rejects(verifyDebHash(link), /symlink/i)
+
+ const linkDir = join(root, 'link-dir')
+ await symlink(root, linkDir)
+ await assert.rejects(verifyDebHash(join(linkDir, 'real.deb')), /symlink/i)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects a non-regular deb path', async () => {
+ const root = await scratch('type')
+ try {
+ await assert.rejects(verifyDebHash(root), /regular file/i)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('refuses to reuse or overwrite an existing extraction directory', async () => {
+ const root = await scratch('existing')
+ try {
+ const extractDir = join(root, 'extracted')
+ await mkdir(extractDir, { recursive: true, mode: 0o700 })
+ await assert.rejects(
+ acquireAndExtractDeb({ debPath: join(root, 'missing.deb'), extractDir }),
+ /refusing to reuse or overwrite/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('requires a deb path when download is not permitted', async () => {
+ const root = await scratch('nodownload')
+ try {
+ await assert.rejects(
+ acquireAndExtractDeb({ extractDir: join(root, 'extracted') }),
+ /debPath is required/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/asar-license.mjs b/scripts/orca/asar-license.mjs
new file mode 100644
index 00000000..f62dbd2c
--- /dev/null
+++ b/scripts/orca/asar-license.mjs
@@ -0,0 +1,92 @@
+/**
+ * Read a single bounded entry from an Electron `app.asar` archive.
+ *
+ * Only a fixed relative entry name is accepted. Header/file offsets, sizes, and
+ * archive bounds are validated before allocation; the extracted bytes are
+ * verified against the pinned SHA-256 and written with a private mode.
+ */
+
+import { constants } from 'node:fs'
+import { createHash } from 'node:crypto'
+import { open, writeFile } from 'node:fs/promises'
+import { assertNoSymlinkAncestors, isSafeRelativePath } from './safe-paths.mjs'
+
+const MAX_HEADER_BYTES = 16 * 1024 * 1024
+const MAX_ENTRY_BYTES = 4 * 1024 * 1024
+
+function sha256(buffer) {
+ return createHash('sha256').update(buffer).digest('hex')
+}
+
+export async function readAsarEntry({
+ asarPath,
+ entryName,
+ expectedSha256,
+ maxBytes = MAX_ENTRY_BYTES
+} = {}) {
+ if (!isSafeRelativePath(entryName)) throw new Error(`Unsafe asar entry name: ${entryName}`)
+ await assertNoSymlinkAncestors(asarPath)
+ // O_NOFOLLOW closes the check-then-open window: the archive that is read is the
+ // inode the descriptor refers to, and the descriptor is what we validate below.
+ const handle = await open(asarPath, constants.O_RDONLY | constants.O_NOFOLLOW, 0o600)
+ try {
+ const archiveStat = await handle.stat()
+ if (!archiveStat.isFile()) throw new Error(`Expected a regular file: ${asarPath}`)
+ if (typeof process.getuid === 'function' && archiveStat.uid !== process.getuid()) {
+ throw new Error(`File is not owned by the current user: ${asarPath}`)
+ }
+ const head = Buffer.alloc(16)
+ await handle.read(head, 0, head.length, 0)
+ if (head.readUInt32LE(0) !== 4) throw new Error('Unsupported asar header')
+ const headerSize = head.readUInt32LE(4)
+ const headerJsonSize = head.readUInt32LE(12)
+ if (headerJsonSize <= 0 || headerJsonSize > MAX_HEADER_BYTES) {
+ throw new Error(`Invalid asar header size: ${headerJsonSize}`)
+ }
+ if (16 + headerJsonSize > archiveStat.size) throw new Error('Asar header exceeds archive bounds')
+ const headerBytes = Buffer.alloc(headerJsonSize)
+ await handle.read(headerBytes, 0, headerBytes.length, 16)
+ const header = JSON.parse(headerBytes.toString('utf8'))
+ let node = header
+ for (const segment of entryName.split('/')) {
+ node = node?.files?.[segment]
+ if (!node) throw new Error(`Asar entry not found: ${entryName}`)
+ }
+ const size = node.size
+ const offset = Number(node.offset)
+ if (!Number.isSafeInteger(size) || size < 0 || size > maxBytes) {
+ throw new Error(`Invalid asar entry size for ${entryName}: ${size}`)
+ }
+ if (!Number.isSafeInteger(offset) || offset < 0) {
+ throw new Error(`Invalid asar entry offset for ${entryName}: ${node.offset}`)
+ }
+ const dataStart = 8 + headerSize
+ const start = dataStart + offset
+ const end = start + size
+ if (end > archiveStat.size) throw new Error(`Asar entry exceeds archive bounds: ${entryName}`)
+ const data = Buffer.alloc(size)
+ await handle.read(data, 0, size, start)
+ const actual = sha256(data)
+ if (node.integrity?.hash && node.integrity.hash !== actual) {
+ throw new Error(`Asar entry integrity mismatch: ${entryName}`)
+ }
+ if (expectedSha256 !== undefined && actual !== expectedSha256) {
+ throw new Error(`Asar entry checksum mismatch: expected ${expectedSha256}, got ${actual}`)
+ }
+ return { data, sha256: actual, size }
+ } finally {
+ await handle.close()
+ }
+}
+
+export async function extractAsarEntry({
+ asarPath,
+ entryName,
+ destination,
+ expectedSha256
+} = {}) {
+ await assertNoSymlinkAncestors(destination)
+ const entry = await readAsarEntry({ asarPath, entryName, expectedSha256 })
+ await writeFile(destination, entry.data, { mode: 0o600, flag: 'wx' })
+ return { path: destination, sha256: entry.sha256, size: entry.size }
+}
diff --git a/scripts/orca/bounded-proc.mjs b/scripts/orca/bounded-proc.mjs
new file mode 100644
index 00000000..e1f19dc0
--- /dev/null
+++ b/scripts/orca/bounded-proc.mjs
@@ -0,0 +1,148 @@
+/**
+ * Bounded, leak-free subprocess execution for Orca CLI/RPC calls.
+ * Captures capped stdout/stderr, enforces a deadline and byte caps, and always
+ * reaps the owned child (and its process group) before returning or throwing.
+ */
+
+import { spawn } from 'node:child_process'
+
+const DEFAULT_TIMEOUT_MS = 30000
+const DEFAULT_MAX_STDOUT = 4 * 1024 * 1024
+const DEFAULT_MAX_STDERR = 64 * 1024
+const KILL_GRACE_MS = 500
+
+const SENSITIVE_PATTERNS = [
+ [/orca:\/\/pair[^\s"']*/gi, '[redacted-pairing-url]'],
+ [/([?&#\s](?:token|code|pairing|key|secret)=)[^&\s"'#]+/gi, '$1REDACTED'],
+ [/(ORCA_(?:PAIRING_CODE|REMOTE_PAIRING|REMOTE_AUTH_TOKEN)\s*[=:]\s*)\S+/gi, '$1REDACTED'],
+ [/(authorization:\s*bearer\s+)\S+/gi, '$1REDACTED']
+]
+
+/** Remove bearer/pairing material from any diagnostic string. */
+export function redactSensitiveText(text) {
+ if (typeof text !== 'string') return ''
+ let out = text
+ for (const [pattern, replacement] of SENSITIVE_PATTERNS) out = out.replace(pattern, replacement)
+ return out
+}
+
+function killTree(pid) {
+ if (!pid) return
+ try {
+ process.kill(-pid, 'SIGKILL')
+ } catch {
+ try {
+ process.kill(pid, 'SIGKILL')
+ } catch {}
+ }
+}
+
+/**
+ * Run one command to completion with hard bounds.
+ * Resolves { code, signal, stdout, stderr }; rejects on spawn error, timeout,
+ * or output overflow, after the child is confirmed dead.
+ */
+export function runBounded({
+ cmd,
+ args = [],
+ env,
+ cwd,
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+ maxStdoutBytes = DEFAULT_MAX_STDOUT,
+ maxStderrBytes = DEFAULT_MAX_STDERR
+}) {
+ if (typeof cmd !== 'string' || cmd.length === 0) {
+ return Promise.reject(new Error('runBounded requires a command'))
+ }
+ return new Promise((resolve, reject) => {
+ const child = spawn(cmd, args, {
+ env,
+ cwd,
+ detached: true,
+ stdio: ['ignore', 'pipe', 'pipe']
+ })
+
+ const stdout = []
+ const stderr = []
+ let stdoutBytes = 0
+ let stderrBytes = 0
+ let settled = false
+ let timer = null
+ let pendingError = null
+
+ const settle = (error, result) => {
+ if (settled) return
+ settled = true
+ if (timer) clearTimeout(timer)
+ if (error) reject(error)
+ else resolve(result)
+ }
+
+ // Kill the owned group and wait for the real close before settling.
+ const abort = (error) => {
+ if (settled || pendingError) return
+ pendingError = error
+ if (timer) clearTimeout(timer)
+ killTree(child.pid)
+ const force = setTimeout(() => settle(pendingError), KILL_GRACE_MS)
+ force.unref?.()
+ }
+
+ child.stdout.on('data', (chunk) => {
+ stdoutBytes += chunk.length
+ if (stdoutBytes > maxStdoutBytes) {
+ abort(new Error(`stdout exceeded ${maxStdoutBytes} bytes`))
+ return
+ }
+ stdout.push(chunk)
+ })
+
+ child.stderr.on('data', (chunk) => {
+ stderrBytes += chunk.length
+ if (stderrBytes > maxStderrBytes) {
+ abort(new Error(`stderr exceeded ${maxStderrBytes} bytes`))
+ return
+ }
+ stderr.push(chunk)
+ })
+
+ child.on('error', (err) => {
+ if (pendingError) return settle(pendingError)
+ settle(err)
+ })
+
+ child.on('close', (code, signal) => {
+ if (pendingError) return settle(pendingError)
+ settle(null, {
+ code,
+ signal,
+ stdout: Buffer.concat(stdout).toString('utf8'),
+ stderr: Buffer.concat(stderr).toString('utf8')
+ })
+ })
+
+ if (timeoutMs > 0) {
+ timer = setTimeout(() => {
+ abort(new Error(`command timed out after ${timeoutMs}ms: ${cmd} ${args.join(' ')}`))
+ }, timeoutMs)
+ timer.unref?.()
+ }
+ })
+}
+
+/** Graceful-then-forced kill of a detached child; awaits real exit. */
+export async function reapBoundedChild(child, { graceMs = KILL_GRACE_MS } = {}) {
+ if (!child || child.exitCode !== null || child.signalCode !== null) return true
+ try {
+ child.kill('SIGTERM')
+ } catch {}
+ const exited = await new Promise((resolve) => {
+ const timer = setTimeout(() => resolve(false), graceMs)
+ child.once('exit', () => {
+ clearTimeout(timer)
+ resolve(true)
+ })
+ })
+ if (!exited) killTree(child.pid)
+ return exited
+}
diff --git a/scripts/orca/bounded-proc.test.mjs b/scripts/orca/bounded-proc.test.mjs
new file mode 100644
index 00000000..4a4da41a
--- /dev/null
+++ b/scripts/orca/bounded-proc.test.mjs
@@ -0,0 +1,96 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { runBounded, redactSensitiveText } from './bounded-proc.mjs'
+
+const NODE = process.execPath
+
+function alive(pid) {
+ try {
+ process.kill(pid, 0)
+ return true
+ } catch {
+ return false
+ }
+}
+
+async function waitGone(pid, timeoutMs = 3000) {
+ const start = Date.now()
+ while (Date.now() - start < timeoutMs) {
+ if (!alive(pid)) return true
+ await new Promise((r) => setTimeout(r, 25))
+ }
+ return !alive(pid)
+}
+
+describe('bounded subprocess execution', () => {
+ it('captures bounded stdout/stderr and the real exit code', async () => {
+ const res = await runBounded({
+ cmd: NODE,
+ args: ['-e', 'process.stdout.write("out"); process.stderr.write("err"); process.exit(3)']
+ })
+ assert.equal(res.code, 3)
+ assert.equal(res.stdout, 'out')
+ assert.equal(res.stderr, 'err')
+ })
+
+ it('rejects a spawn error instead of hanging', async () => {
+ await assert.rejects(
+ () => runBounded({ cmd: '/definitely/not/a/binary-orca', args: [] }),
+ (err) => err.code === 'ENOENT' || /ENOENT/.test(err.message)
+ )
+ })
+
+ it('times out, kills the child, and never leaves it alive', async () => {
+ await assert.rejects(
+ () =>
+ runBounded({
+ cmd: NODE,
+ args: ['-e', 'process.stdout.write(String(process.pid)); setInterval(() => {}, 1000)'],
+ timeoutMs: 250
+ }),
+ /timed out/i
+ )
+ })
+
+ it('kills the child when stdout exceeds the byte cap', async () => {
+ await assert.rejects(
+ () =>
+ runBounded({
+ cmd: NODE,
+ args: ['-e', 'process.stdout.write("x".repeat(200000)); setInterval(() => {}, 1000)'],
+ maxStdoutBytes: 1024
+ }),
+ /exceeded/i
+ )
+ })
+
+ it('kills the child when stderr exceeds the byte cap', async () => {
+ await assert.rejects(
+ () =>
+ runBounded({
+ cmd: NODE,
+ args: ['-e', 'process.stderr.write("y".repeat(200000)); setInterval(() => {}, 1000)'],
+ maxStderrBytes: 1024
+ }),
+ /exceeded/i
+ )
+ })
+
+ it('passes only the caller-provided private environment', async () => {
+ const res = await runBounded({
+ cmd: NODE,
+ args: ['-e', 'process.stdout.write(JSON.stringify({foo: process.env.FOO, home: process.env.HOME ?? null}))'],
+ env: { FOO: 'bar', PATH: '/usr/bin:/bin' }
+ })
+ assert.deepEqual(JSON.parse(res.stdout), { foo: 'bar', home: null })
+ })
+
+ it('redacts bearer/code/pairing material from diagnostic text', () => {
+ const text = 'ws://127.0.0.1:1/?token=SECRET code=ABC #pairing=orca%3A%2F%2Fpair orca://pair?code=XYZ'
+ const out = redactSensitiveText(text)
+ assert.equal(out.includes('SECRET'), false)
+ assert.equal(out.includes('ABC'), false)
+ assert.equal(out.includes('XYZ'), false)
+ assert.equal(out.includes('orca://pair'), false)
+ })
+})
diff --git a/scripts/orca/bounded-process.mjs b/scripts/orca/bounded-process.mjs
new file mode 100644
index 00000000..c306995d
--- /dev/null
+++ b/scripts/orca/bounded-process.mjs
@@ -0,0 +1,144 @@
+/**
+ * Bounded child-process execution for data-only upstream tooling.
+ *
+ * Guarantees:
+ * - stdout/stderr are drained and capped in memory (never unbounded arrays);
+ * - an optional stdout sink receives chunks with backpressure;
+ * - timeout and caller abort escalate SIGTERM -> SIGKILL and await `close`;
+ * - timers/listeners are always cleared, so a cancelled run leaves no handle.
+ */
+
+import { spawn } from 'node:child_process'
+
+function abortError(message) {
+ const err = new Error(message)
+ err.name = 'AbortError'
+ return err
+}
+
+function timeoutError(message) {
+ const err = new Error(message)
+ err.name = 'TimeoutError'
+ return err
+}
+
+export async function runBoundedProcess({
+ command,
+ args = [],
+ timeoutMs = 60000,
+ signal,
+ maxStdoutBytes = 0,
+ maxStderrBytes = 65536,
+ onStdout,
+ stdoutFd,
+ graceMs = 2000
+} = {}) {
+ if (typeof command !== 'string' || command.length === 0) {
+ throw new Error('command is required')
+ }
+ if (stdoutFd !== undefined && typeof stdoutFd !== 'number') {
+ throw new Error('stdoutFd must be a file descriptor number')
+ }
+ if (signal?.aborted) throw abortError('Process aborted before it started')
+
+ const child = spawn(command, args, {
+ stdio: ['ignore', stdoutFd === undefined ? 'pipe' : stdoutFd, 'pipe']
+ })
+ const stderrChunks = []
+ const stdoutChunks = []
+ let stderrBytes = 0
+ let stderrTruncated = false
+ let stdoutBytes = 0
+ let timedOut = false
+ let aborted = false
+ let sinkFailure = null
+ let closed = false
+
+ const stop = () => {
+ try {
+ child.kill('SIGTERM')
+ } catch {}
+ const killTimer = setTimeout(() => {
+ if (closed) return
+ try {
+ child.kill('SIGKILL')
+ } catch {}
+ }, graceMs)
+ killTimer.unref?.()
+ }
+
+ const onAbort = () => {
+ aborted = true
+ stop()
+ }
+ signal?.addEventListener('abort', onAbort, { once: true })
+ const timer = setTimeout(() => {
+ timedOut = true
+ stop()
+ }, timeoutMs)
+ timer.unref?.()
+
+ child.stderr.on('data', (chunk) => {
+ stderrBytes += chunk.length
+ if (stderrBytes > maxStderrBytes) {
+ stderrTruncated = true
+ return
+ }
+ stderrChunks.push(chunk)
+ })
+
+ if (child.stdout) child.stdout.on('data', (chunk) => {
+ stdoutBytes += chunk.length
+ if (maxStdoutBytes > 0 && stdoutBytes > maxStdoutBytes) {
+ sinkFailure = new Error(`Process stdout exceeded the cap of ${maxStdoutBytes} bytes`)
+ stop()
+ return
+ }
+ if (!onStdout) {
+ if (maxStdoutBytes > 0) stdoutChunks.push(chunk)
+ return
+ }
+ child.stdout.pause()
+ Promise.resolve(onStdout(chunk)).then(
+ () => {
+ if (!closed) child.stdout.resume()
+ },
+ (err) => {
+ sinkFailure = err
+ stop()
+ }
+ )
+ })
+ if (child.stdout) child.stdout.on('error', (err) => {
+ sinkFailure = err
+ stop()
+ })
+
+ const spawnError = await new Promise((resolve) => {
+ child.once('error', resolve)
+ child.once('close', () => resolve(null))
+ }).then((err) => {
+ closed = true
+ return err
+ })
+
+ child.removeAllListeners('error')
+ clearTimeout(timer)
+ signal?.removeEventListener('abort', onAbort)
+ if (child.stdout && !child.stdout.destroyed) child.stdout.resume()
+ if (child.stderr && !child.stderr.destroyed) child.stderr.resume()
+
+ if (timedOut) throw timeoutError(`Process timed out after ${timeoutMs}ms: ${command}`)
+ if (aborted) throw abortError(`Process aborted: ${command}`)
+ if (spawnError) throw spawnError
+ if (sinkFailure) throw sinkFailure
+
+ return {
+ code: child.exitCode,
+ signal: child.signalCode,
+ stdoutBytes,
+ stdout: Buffer.concat(stdoutChunks).toString('utf8'),
+ stderr: Buffer.concat(stderrChunks).toString('utf8'),
+ stderrTruncated
+ }
+}
diff --git a/scripts/orca/bounded-process.test.mjs b/scripts/orca/bounded-process.test.mjs
new file mode 100644
index 00000000..5edf3c3e
--- /dev/null
+++ b/scripts/orca/bounded-process.test.mjs
@@ -0,0 +1,70 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { runBoundedProcess } from './bounded-process.mjs'
+
+describe('bounded child process', () => {
+ it('returns exit code and bounded stderr for a normal command', async () => {
+ const res = await runBoundedProcess({
+ command: process.execPath,
+ args: ['-e', 'process.stderr.write("warning\\n")'],
+ maxStderrBytes: 1024
+ })
+ assert.equal(res.code, 0)
+ assert.equal(res.stderr, 'warning\n')
+ assert.equal(res.stderrTruncated, false)
+ })
+
+ it('caps retained stderr while still draining the pipe', async () => {
+ const res = await runBoundedProcess({
+ command: process.execPath,
+ args: ['-e', 'process.stderr.write("x".repeat(4096))'],
+ maxStderrBytes: 64
+ })
+ assert.equal(res.code, 0)
+ assert.equal(res.stderrTruncated, true)
+ assert.ok(res.stderr.length <= 64)
+ })
+
+ it('streams stdout through the sink', async () => {
+ const chunks = []
+ const res = await runBoundedProcess({
+ command: process.execPath,
+ args: ['-e', 'process.stdout.write("abc");process.stdout.write("def")'],
+ onStdout: (chunk) => chunks.push(Buffer.from(chunk))
+ })
+ assert.equal(res.code, 0)
+ assert.equal(Buffer.concat(chunks).toString('utf8'), 'abcdef')
+ })
+
+ it('kills a hung child on timeout and rejects', async () => {
+ await assert.rejects(
+ runBoundedProcess({
+ command: process.execPath,
+ args: ['-e', 'setInterval(() => {}, 1000)'],
+ timeoutMs: 60,
+ graceMs: 50
+ }),
+ { name: 'TimeoutError' }
+ )
+ })
+
+ it('kills a child when the stdout cap is exceeded', async () => {
+ await assert.rejects(
+ runBoundedProcess({
+ command: process.execPath,
+ args: ['-e', 'process.stdout.write("x".repeat(4096))'],
+ maxStdoutBytes: 32
+ }),
+ /stdout exceeded/i
+ )
+ })
+
+ it('supports a pre-aborted signal without spawning', async () => {
+ const controller = new AbortController()
+ controller.abort()
+ await assert.rejects(
+ runBoundedProcess({ command: process.execPath, args: ['-e', ''], signal: controller.signal }),
+ { name: 'AbortError' }
+ )
+ })
+})
diff --git a/scripts/orca/bounded-stream.mjs b/scripts/orca/bounded-stream.mjs
new file mode 100644
index 00000000..aa045621
--- /dev/null
+++ b/scripts/orca/bounded-stream.mjs
@@ -0,0 +1,89 @@
+/**
+ * Bounded stream consumption. No unbounded buffering: callers cap per-line,
+ * total, and rolling bytes, and can switch to discard-drain after readiness.
+ */
+
+export function createBoundedLineReader(stream, {
+ maxLineBytes = 256 * 1024,
+ maxTotalBytes = 4 * 1024 * 1024,
+ onLine,
+ onOverflow
+} = {}) {
+ let buffer = Buffer.alloc(0)
+ let total = 0
+ let discarding = false
+ let failed = false
+
+ const fail = (message) => {
+ if (failed || discarding) return
+ failed = true
+ onOverflow?.(new Error(message))
+ }
+
+ const onData = (chunk) => {
+ if (discarding) return
+ if (failed) return
+ total += chunk.length
+ if (total > maxTotalBytes) return fail(`stdout exceeded ${maxTotalBytes} bytes before readiness`)
+ buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk])
+ let newline
+ while ((newline = buffer.indexOf(0x0a)) >= 0) {
+ const line = buffer.subarray(0, newline)
+ buffer = buffer.subarray(newline + 1)
+ if (line.length > maxLineBytes) return fail(`stdout line exceeded ${maxLineBytes} bytes`)
+ onLine?.(line.toString('utf8').replace(/\r$/, ''))
+ if (failed) return
+ }
+ if (buffer.length > maxLineBytes) fail(`stdout line exceeded ${maxLineBytes} bytes`)
+ }
+
+ stream.on('data', onData)
+ return {
+ /** Stop parsing; keep consuming so the child pipe never backpressures. */
+ discard() {
+ discarding = true
+ buffer = Buffer.alloc(0)
+ },
+ detach() {
+ discarding = true
+ buffer = Buffer.alloc(0)
+ stream.removeListener('data', onData)
+ stream.resume()
+ }
+ }
+}
+
+/** Rolling byte-capped text sink (keeps the tail, drops the head). */
+export function createRollingTextSink(stream, { maxBytes = 64 * 1024 } = {}) {
+ const chunks = []
+ let total = 0
+ const onData = (chunk) => {
+ chunks.push(chunk)
+ total += chunk.length
+ while (total > maxBytes) {
+ const excess = total - maxBytes
+ if (chunks[0].length <= excess) {
+ total -= chunks[0].length
+ chunks.shift()
+ } else {
+ chunks[0] = chunks[0].subarray(excess)
+ total -= excess
+ break
+ }
+ }
+ }
+ stream.on('data', onData)
+ return {
+ text: () => Buffer.concat(chunks).toString('utf8'),
+ detach() {
+ stream.removeListener('data', onData)
+ stream.resume()
+ }
+ }
+}
+
+/** Keep draining an already-attached stream without retaining data. */
+export function drain(stream) {
+ stream.on('data', () => {})
+ stream.resume()
+}
diff --git a/scripts/orca/bounded-stream.test.mjs b/scripts/orca/bounded-stream.test.mjs
new file mode 100644
index 00000000..13014c6d
--- /dev/null
+++ b/scripts/orca/bounded-stream.test.mjs
@@ -0,0 +1,68 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { PassThrough } from 'node:stream'
+import { createBoundedLineReader, createRollingTextSink, drain } from './bounded-stream.mjs'
+
+async function flush() {
+ await new Promise((r) => setImmediate(r))
+}
+
+describe('bounded stream consumption', () => {
+ it('delivers complete lines and caps an oversized line', async () => {
+ const stream = new PassThrough()
+ const lines = []
+ const errors = []
+ createBoundedLineReader(stream, {
+ maxLineBytes: 16,
+ onLine: (line) => lines.push(line),
+ onOverflow: (err) => errors.push(err)
+ })
+ stream.write('ok\r\npartial')
+ stream.write(' line\n')
+ await flush()
+ assert.deepEqual(lines, ['ok', 'partial line'])
+
+ stream.write('x'.repeat(64))
+ await flush()
+ assert.equal(errors.length, 1)
+ assert.match(errors[0].message, /line exceeded/i)
+ })
+
+ it('caps total bytes before readiness and stops parsing after detach', async () => {
+ const stream = new PassThrough()
+ const errors = []
+ const lines = []
+ const reader = createBoundedLineReader(stream, {
+ maxTotalBytes: 16,
+ onLine: (line) => lines.push(line),
+ onOverflow: (err) => errors.push(err)
+ })
+ stream.write('y'.repeat(32))
+ await flush()
+ assert.match(errors[0].message, /stdout exceeded/i)
+
+ const second = new PassThrough()
+ const seen = []
+ const reader2 = createBoundedLineReader(second, { onLine: (line) => seen.push(line) })
+ reader2.detach()
+ second.write('ignored\n')
+ await flush()
+ assert.deepEqual(seen, [])
+ reader.detach()
+ })
+
+ it('keeps only the rolling tail of stderr and drains without retaining', async () => {
+ const stream = new PassThrough()
+ const sink = createRollingTextSink(stream, { maxBytes: 8 })
+ stream.write('123456')
+ stream.write('7890')
+ await flush()
+ assert.equal(sink.text().endsWith('34567890'), true)
+ assert.equal(sink.text().length <= 8, true)
+ sink.detach()
+
+ const drained = new PassThrough()
+ drain(drained)
+ drained.write('discarded')
+ })
+})
diff --git a/scripts/orca/cli.mjs b/scripts/orca/cli.mjs
new file mode 100644
index 00000000..765b5191
--- /dev/null
+++ b/scripts/orca/cli.mjs
@@ -0,0 +1,143 @@
+#!/usr/bin/env node
+/**
+ * Hardened Orca runtime CLI: strict argument parsing, pinned-release
+ * preparation, disposable smoke proof (PTY echo), and a real persistent
+ * supervised run. There is no unchecked `--template`/`--web` bypass.
+ */
+
+import { prepareRelease } from './lifecycle-release.mjs'
+import { runSmokeProof } from './smoke.mjs'
+import { runSupervisedRuntime } from './supervision.mjs'
+import { assertConfiguredAdvertisedEndpoint, assertPersistentPort } from './supervision.mjs'
+import { redactSensitiveText } from './bounded-proc.mjs'
+
+const COMMANDS = new Set(['materialize', 'smoke', 'run', 'help'])
+
+const VALUE_FLAGS = new Map([
+ ['--managed-root', 'managedRoot'],
+ ['--port', 'port'],
+ ['--bind', 'bind'],
+ ['--advertised-endpoint', 'advertisedEndpoint'],
+ ['--deb', 'deb']
+])
+
+const BOOLEAN_FLAGS = new Map([['--allow-download', 'allowDownload']])
+
+const USAGE = `Usage: node scripts/orca/cli.mjs <command> --managed-root <dir> [flags]
+
+Commands:
+ materialize Prepare and verify the pinned release slot + Node runtime.
+ smoke Disposable loopback launch, web probe, and real PTY echo proof.
+ Cleans the task-owned server and terminal daemon.
+ run Persistent supervised server on a fixed port; stays alive until
+ the server dies or SIGINT/SIGTERM, then preserves the daemon.
+ help Show this message.
+
+Flags:
+ --managed-root <dir> Absolute MSO-owned state root (required).
+ --port <n> Port 1-65535 for run; 0 is smoke-only.
+ --bind <ip> Loopback bind address (default 127.0.0.1).
+ --advertised-endpoint <url> Configured public wss URL (required for run).
+ --deb <path> Already-verified Orca .deb for acquisition.
+ --allow-download Permit the pinned deb/Node download.
+`
+
+export function parseArgs(argv) {
+ if (!Array.isArray(argv) || argv.length < 2) throw new Error('invalid argv')
+ const command = argv[2] ?? 'help'
+ if (command.startsWith('-')) throw new Error(`missing command before ${command}`)
+ if (!COMMANDS.has(command)) throw new Error(`unknown command: ${command}`)
+
+ const args = { command }
+ const seen = new Set()
+ for (let i = 3; i < argv.length; i += 1) {
+ const token = argv[i]
+ if (!token.startsWith('--')) throw new Error(`unexpected argument: ${token}`)
+ if (seen.has(token)) throw new Error(`duplicate flag: ${token}`)
+ seen.add(token)
+
+ if (BOOLEAN_FLAGS.has(token)) {
+ args[BOOLEAN_FLAGS.get(token)] = true
+ continue
+ }
+ if (!VALUE_FLAGS.has(token)) throw new Error(`unknown flag: ${token}`)
+ const value = argv[i + 1]
+ if (value === undefined || value.startsWith('--')) throw new Error(`missing value for ${token}`)
+ i += 1
+ if (token === '--port') {
+ if (!/^\d+$/.test(value)) throw new Error(`port must be an integer, got: ${value}`)
+ args.port = Number(value)
+ } else {
+ args[VALUE_FLAGS.get(token)] = value
+ }
+ }
+ return args
+}
+
+function requireManagedRoot(args) {
+ if (!args.managedRoot) throw new Error(`${args.command} requires --managed-root <dir>`)
+ return args.managedRoot
+}
+
+export async function main(argv, { log = console } = {}) {
+ const args = parseArgs(argv)
+ if (args.command === 'help') {
+ log.log(USAGE.trimEnd())
+ return { command: 'help' }
+ }
+
+ const managedRoot = requireManagedRoot(args)
+ // Validate the run-only configuration BEFORE acquisition: a bad advertised
+ // endpoint must not trigger a download or rehash first.
+ if (args.command === 'run') {
+ assertPersistentPort(args.port)
+ assertConfiguredAdvertisedEndpoint(args.advertisedEndpoint)
+ }
+
+ const release = await prepareRelease({
+ managedRoot,
+ debPath: args.deb,
+ allowDownload: args.allowDownload === true
+ })
+
+ if (args.command === 'materialize') {
+ log.log(JSON.stringify({
+ version: release.version,
+ releaseRoot: release.releaseRoot,
+ slotDir: release.slotDir,
+ nodeBinary: release.nodeBinary,
+ webDir: release.webDir
+ }, null, 2))
+ return { command: 'materialize', release }
+ }
+
+ if (args.command === 'smoke') {
+ const result = await runSmokeProof({
+ release,
+ managedRoot,
+ port: args.port ?? 0,
+ bind: args.bind,
+ advertisedEndpoint: args.advertisedEndpoint,
+ log
+ })
+ log.log(`[orca-cli] Smoke proof PASSED (${result.version})`)
+ return { command: 'smoke', release, result }
+ }
+
+ const result = await runSupervisedRuntime({
+ release,
+ managedRoot,
+ port: args.port,
+ bind: args.bind,
+ advertisedEndpoint: args.advertisedEndpoint,
+ log
+ })
+ return { command: 'run', release, result }
+}
+
+if (process.argv[1] && process.argv[1].endsWith('cli.mjs')) {
+ main(process.argv).catch((err) => {
+ console.error(`[orca-cli] Fatal error: ${redactSensitiveText(err.message)}`)
+ process.exitCode = 1
+ })
+}
diff --git a/scripts/orca/cli.test.mjs b/scripts/orca/cli.test.mjs
new file mode 100644
index 00000000..b35d6a0d
--- /dev/null
+++ b/scripts/orca/cli.test.mjs
@@ -0,0 +1,78 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { parseArgs, main } from './cli.mjs'
+import { assertConfiguredAdvertisedEndpoint, assertPersistentPort } from './supervision.mjs'
+
+const argv = (...rest) => ['node', 'cli.mjs', ...rest]
+
+describe('strict CLI argument parsing', () => {
+ it('parses every supported flag and defaults to help', () => {
+ const res = parseArgs(argv(
+ 'smoke', '--managed-root', '/srv/orca', '--port', '6769', '--bind', '127.0.0.1',
+ '--advertised-endpoint', 'wss://orca.example.test', '--deb', '/tmp/orca.deb',
+ '--allow-download'
+ ))
+ assert.equal(res.command, 'smoke')
+ assert.equal(res.managedRoot, '/srv/orca')
+ assert.equal(res.port, 6769)
+ assert.equal(res.bind, '127.0.0.1')
+ assert.equal(res.advertisedEndpoint, 'wss://orca.example.test')
+ assert.equal(res.deb, '/tmp/orca.deb')
+ assert.equal(res.allowDownload, true)
+ assert.equal(parseArgs(['node', 'cli.mjs']).command, 'help')
+ })
+
+ it('rejects unknown, duplicate, positional, and valueless flags', () => {
+ assert.throws(() => parseArgs(argv('smoke', '--managed-root', '/srv', '--nope')), /unknown flag/i)
+ assert.throws(() => parseArgs(argv('smoke', '--managed-root', '/srv', '--port', '1', '--port', '2')), /duplicate flag/i)
+ assert.throws(() => parseArgs(argv('smoke', '--managed-root', '/srv', 'stray')), /unexpected argument/i)
+ assert.throws(() => parseArgs(argv('smoke', '--managed-root')), /missing value/i)
+ assert.throws(() => parseArgs(argv('smoke', '--managed-root', '--port', '6769')), /missing value/i)
+ assert.throws(() => parseArgs(argv('smoke', '--managed-root', '/srv', '--port', '6769x')), /port must be an integer/i)
+ assert.throws(() => parseArgs(argv('launch')), /unknown command/i)
+ assert.throws(() => parseArgs(['node', 'cli.mjs', '--managed-root', '/srv']), /missing command/i)
+ })
+
+ it('has no unchecked template/web acquisition bypass', () => {
+ for (const flag of ['--template', '--web']) {
+ assert.throws(
+ () => parseArgs(argv('materialize', '--managed-root', '/srv', flag, '/tmp/upstream')),
+ /unknown flag/i
+ )
+ }
+ })
+
+ it('requires --managed-root before running a command', async () => {
+ await assert.rejects(() => main(argv('materialize')), /requires --managed-root/i)
+ })
+
+ it('prints usage without preparing a release', async () => {
+ const lines = []
+ const result = await main(argv('help'), { log: { log: (line) => lines.push(line) } })
+ assert.equal(result.command, 'help')
+ assert.match(lines.join('\n'), /Usage: node scripts\/orca\/cli.mjs/)
+ })
+})
+
+describe('persistent run configuration', () => {
+ it('accepts only a non-loopback wss advertised endpoint', () => {
+ assert.equal(assertConfiguredAdvertisedEndpoint('wss://orca.example.test'), 'wss://orca.example.test')
+ assert.equal(
+ assertConfiguredAdvertisedEndpoint('wss://orca.example.test/runtime/'),
+ 'wss://orca.example.test/runtime'
+ )
+ assert.throws(() => assertConfiguredAdvertisedEndpoint('ws://orca.example.test'), /wss/i)
+ assert.throws(() => assertConfiguredAdvertisedEndpoint('wss://127.0.0.1:6769'), /loopback/i)
+ assert.throws(() => assertConfiguredAdvertisedEndpoint('wss://localhost:6769'), /loopback/i)
+ assert.throws(() => assertConfiguredAdvertisedEndpoint('wss://orca.example.test/?token=x'), /credentials|query/i)
+ assert.throws(() => assertConfiguredAdvertisedEndpoint('not a url'), /valid URL/i)
+ assert.throws(() => assertConfiguredAdvertisedEndpoint(''), /requires/i)
+ })
+
+ it('rejects dynamic and out-of-range persistent ports', () => {
+ assert.equal(assertPersistentPort(6769), 6769)
+ assert.throws(() => assertPersistentPort(0), /fixed port/i)
+ assert.throws(() => assertPersistentPort(65536), /fixed port/i)
+ assert.throws(() => assertPersistentPort('6769x'), /fixed port/i)
+ })
+})
diff --git a/scripts/orca/constants.mjs b/scripts/orca/constants.mjs
new file mode 100644
index 00000000..e4514401
--- /dev/null
+++ b/scripts/orca/constants.mjs
@@ -0,0 +1,165 @@
+/**
+ * Orca acquisition constants and portable pins.
+ *
+ * All digests here are release facts measured from the official v1.4.230
+ * artifacts (GitHub release .deb + nodejs.org Node tarball) and the tagged
+ * upstream source tree. No operator-specific absolute paths belong here.
+ */
+
+export const SUPPORTED_TARGET = 'linux-x64-glibc'
+
+export function isSupportedTarget(target) {
+ return target === SUPPORTED_TARGET
+}
+
+/**
+ * Fail early on hosts we have no verified binary for. `platform`/`arch`/`report`
+ * are injectable so the pure test can exercise rejection without lying about
+ * the running process; production callers pass nothing.
+ */
+export function assertSupportedHostPlatform({
+ platform = process.platform,
+ arch = process.arch,
+ report
+} = {}) {
+ if (platform !== 'linux' || arch !== 'x64') {
+ throw new Error(
+ `Unsupported host platform ${platform}-${arch}; Orca acquisition supports ${SUPPORTED_TARGET} only`
+ )
+ }
+ const resolved = report ?? process.report?.getReport?.()
+ const glibcVersion = resolved?.header?.glibcVersionRuntime
+ if (typeof glibcVersion !== 'string' || glibcVersion.length === 0) {
+ throw new Error(
+ `Unsupported libc on ${platform}-${arch}; Orca acquisition requires glibc (${SUPPORTED_TARGET})`
+ )
+ }
+ return { platform, arch, libc: 'glibc', glibcVersion }
+}
+
+export const PINNED_NODE = Object.freeze({
+ version: '24.21.0',
+ archiveSha256: '6e1db87ef58b8819e5d5402eff1536491b18edd8eb7bee5ef7897876e88dc5ff',
+ archiveSize: 58088022,
+ executableSha256: '7fde7b8afa198da66257f42ee2001d874c7355631e6d1579a5fb5ef1f246df4c',
+ archiveUrl: 'https://nodejs.org/dist/v24.21.0/node-v24.21.0-linux-x64.tar.gz',
+ tarMember: 'node-v24.21.0-linux-x64/bin/node'
+})
+
+export const ORCAD_VERSION = '0.1.0'
+export const ORCA_VERSION = '1.4.230'
+
+export const DEFAULT_PORT = 6769
+export const DEFAULT_BIND = '127.0.0.1'
+
+export const ORCA_DEB_URL =
+ 'https://github.com/stablyai/orca/releases/download/v1.4.230/orca-ide_1.4.230_amd64.deb'
+export const ORCA_DEB_FILENAME = 'orca-ide_1.4.230_amd64.deb'
+export const ORCA_DEB_SHA256 =
+ '7758be00e6564c14e5793b6a61ffe1bb0e84749583d76013a129454835788e24'
+export const ORCA_DEB_SIZE = 209670608
+export const ORCA_DEB_PACKAGE = 'orca-ide'
+export const ORCA_DEB_ARCHITECTURE = 'amd64'
+
+/** GitHub release downloads redirect to release assets; nothing else is allowed. */
+export const ORCA_DOWNLOAD_REDIRECT_HOSTS = Object.freeze([
+ 'github.com',
+ 'objects.githubusercontent.com',
+ 'release-assets.githubusercontent.com',
+ 'github-releases.githubusercontent.com'
+])
+
+/** Tagged upstream source that produced the .deb (MIT license + notices). */
+export const ORCA_SOURCE_COMMIT = 'b2879bd5aaac5d27c101ccf4171faa25d9f0bb1e'
+export const ORCA_SOURCE_URL =
+ 'https://github.com/stablyai/orca/archive/b2879bd5aaac5d27c101ccf4171faa25d9f0bb1e.tar.gz'
+export const ORCA_LICENSE_SHA256 =
+ 'ff1b611f80580d49f4b97e93a97b24eb050b0671b26b8afe16341fab699112f3'
+export const ORCA_LICENSE_SIZE = 1070
+export const ORCA_THIRD_PARTY_NOTICES_SHA256 =
+ '1e039dc5567ff96b755c80a384dd626a00a0c46c49e9994c86cb599efcc435fd'
+export const ORCA_THIRD_PARTY_NOTICES_SIZE = 4675
+export const ORCA_THIRD_PARTY_NOTICES_URL =
+ 'https://raw.githubusercontent.com/stablyai/orca/b2879bd5aaac5d27c101ccf4171faa25d9f0bb1e/docs/site/THIRD_PARTY_NOTICES.md'
+export const ORCA_THIRD_PARTY_NOTICES_RELATIVE_PATH = 'docs/site/THIRD_PARTY_NOTICES.md'
+
+/** Packaged Electron app.asar inside the verified .deb; used for MIT LICENSE. */
+export const ORCA_APP_ASAR_PATH = 'opt/Orca/resources/app.asar'
+export const ORCA_APP_ASAR_SHA256 =
+ 'b663113cb9549de55e70a2daaf1759ec59f5c744ebf7715798bbaaaf3d3e6988'
+
+export const ORCAD_SERVER_TARGET_FILENAME = '.server-target'
+export const ORCAD_NODE_RUNTIME_MARKER_FILENAME = '.runtime-node'
+export const ORCAD_VERSION_FILENAME = '.version'
+export const ORCAD_TEMPLATE_MANIFEST_FILENAME = 'orcad-template.json'
+export const ORCAD_TEMPLATE_TARGETS_DIR = 'targets'
+export const ORCAD_SERVER_ENTRY_FILENAME = 'orcad-server.js'
+export const ORCAD_RUNTIMES_DIRNAME = 'runtimes'
+export const ORCAD_NODE_RUNTIME_DIR_PREFIX = 'node-'
+export const ORCAD_NODE_RUNTIME_POSIX_EXECUTABLE = 'bin/node'
+export const WEB_CLIENT_INDEX_FILENAME = 'web-index.html'
+
+/** Directory layout inside the upstream .deb (data-only, never apt scripts). */
+export const ORCA_DEB_TEMPLATE_DIR = 'opt/Orca/resources/orcad-template'
+export const ORCA_DEB_WEB_DIR = 'opt/Orca/resources/app.asar.unpacked/out/web'
+
+/**
+ * The exact upstream common artifact list (order is part of the slot contract).
+ * `out/mobile-web/*` assets beyond manifest.json are discovered from the
+ * authenticated manifest and sorted, so the final slot is always 175 files.
+ */
+export const ORCAD_COMMON_FILES = Object.freeze([
+ 'out/cli/index.js',
+ 'out/package.json',
+ 'orcad.js',
+ 'orcad-server.js',
+ 'parcel-watcher-process-entry.js',
+ 'daemon-entry.js',
+ 'profile-state-writer-worker-entry.js',
+ 'profile-state-backup-worker-entry.js',
+ 'foreign-sqlite-reader-entry.js',
+ 'port-scan-command-worker-entry.js',
+ 'session-scanner-service-entry.js',
+ 'worker-thread-child-process-entry.js',
+ 'claude-profile-setup-worker-entry.js',
+ 'node_modules/@parcel/watcher/index.js',
+ 'node_modules/emojibase-data/en/shortcodes/emojibase.json',
+ 'node_modules/@linear/sdk/index.js',
+ 'node_modules/node-pty/package.json',
+ 'node_modules/node-pty/lib/conpty_console_list_agent.js',
+ 'node_modules/node-pty/lib/eventEmitter2.js',
+ 'node_modules/node-pty/lib/index.js',
+ 'node_modules/node-pty/lib/interfaces.js',
+ 'node_modules/node-pty/lib/shared/conout.js',
+ 'node_modules/node-pty/lib/terminal.js',
+ 'node_modules/node-pty/lib/types.js',
+ 'node_modules/node-pty/lib/unixTerminal.js',
+ 'node_modules/node-pty/lib/utils.js',
+ 'node_modules/node-pty/lib/windowsConoutConnection.js',
+ 'node_modules/node-pty/lib/windowsPtyAgent.js',
+ 'node_modules/node-pty/lib/windowsTerminal.js',
+ 'node_modules/node-pty/lib/worker/conoutSocketWorker.js',
+ 'ripgrep/licenses/JEMALLOC-COPYING',
+ 'ripgrep/licenses/LICENSE-MIT',
+ 'ripgrep/licenses/LLVM-LIBUNWIND-LICENSE.TXT',
+ 'ripgrep/licenses/MUSL-COPYRIGHT',
+ 'ripgrep/licenses/PCRE2-LICENCE.md',
+ 'ripgrep/licenses/README.md',
+ 'ripgrep/licenses/RUST-CRATE-NOTICES.txt',
+ 'ripgrep/licenses/SLJIT-LICENSE',
+ 'ripgrep/licenses/UNLICENSE',
+ 'native-chat-visuals/.claude-plugin/plugin.json',
+ 'native-chat-visuals/skills/orca-chat-visuals/SKILL.md',
+ 'out/mobile-web/manifest.json'
+])
+
+/** linux-x64-glibc target-specific artifacts, in slot order. */
+export const ORCAD_TARGET_FILES = Object.freeze([
+ ORCAD_SERVER_TARGET_FILENAME,
+ ORCAD_NODE_RUNTIME_MARKER_FILENAME,
+ 'node_modules/@parcel/watcher/watcher.node',
+ 'node_modules/node-pty/build/Release/pty.node',
+ 'ripgrep/linux-x64/rg'
+])
+
+export const ORCAD_SLOT_FILE_COUNT = 175
diff --git a/scripts/orca/daemon-identity.mjs b/scripts/orca/daemon-identity.mjs
new file mode 100644
index 00000000..29d29ad6
--- /dev/null
+++ b/scripts/orca/daemon-identity.mjs
@@ -0,0 +1,126 @@
+/**
+ * Verify an Orca terminal daemon using kernel identity only: uid, executable,
+ * daemon-entry.js script path, a canonical protocol socket inside the private
+ * daemon directory, and canonical pid records sorted by protocol version.
+ */
+
+import { lstat, readFile, readdir, realpath } from 'node:fs/promises'
+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
+import { readProcessIdentity, verifyProcessIdentity } from './proc-identity.mjs'
+import { parseDaemonPid } from './launcher.mjs'
+
+const PID_RECORD_RE = /^daemon-v(\d+)\.pid$/
+const SOCKET_RE = /^daemon-v\d+\.sock$/
+
+async function realpathOr(path) {
+ try {
+ return await realpath(path)
+ } catch {
+ return path
+ }
+}
+
+/** Canonical daemon socket: real parent, protocol filename, no symlink components. */
+export async function canonicalDaemonSocket(argv, { userData }) {
+ const idx = argv.indexOf('--socket')
+ const socketArg = idx >= 0 ? argv[idx + 1] : null
+ if (!socketArg || !isAbsolute(socketArg) || !SOCKET_RE.test(basename(socketArg))) return null
+ try {
+ const userReal = await realpath(userData)
+ const daemonDir = join(userData, 'daemon')
+ const daemonReal = await realpath(daemonDir)
+ const socketReal = await realpath(socketArg)
+ if (daemonReal !== join(userReal, 'daemon')) return null
+ if (dirname(socketReal) !== daemonReal) return null
+ const socketInfo = await lstat(socketArg)
+ if (socketInfo.isSymbolicLink() || !socketInfo.isSocket()) return null
+ for (const path of [userData, daemonDir]) {
+ const info = await lstat(path)
+ if (info.isSymbolicLink() || !info.isDirectory()) return null
+ }
+ // Lexical socket parent must be under user-data with no symlink component,
+ // so a `daemon-link/daemon-vN.sock` alias cannot impersonate the real dir.
+ const socketAbs = resolve(socketArg)
+ const rel = relative(resolve(userData), socketAbs)
+ if (rel.startsWith('..') || isAbsolute(rel)) return null
+ let current = resolve(userData)
+ for (const part of rel.split(sep).slice(0, -1)) {
+ current = join(current, part)
+ if ((await lstat(current)).isSymbolicLink()) return null
+ }
+ return socketReal
+ } catch {
+ return null
+ }
+}
+
+export async function verifyDaemon(pid, { nodeBinary, daemonEntryPath, userData }) {
+ if (!Number.isInteger(pid) || pid <= 1) return null
+ const actual = await readProcessIdentity(pid)
+ if (!actual) return null
+ if (!(await canonicalDaemonSocket(actual.argv, { userData }))) return null
+ const expected = {
+ pid,
+ startTicks: actual.startTicks,
+ uid: process.getuid(),
+ exe: await realpathOr(nodeBinary),
+ scriptPath: daemonEntryPath
+ }
+ if (!(await verifyProcessIdentity(actual, expected))) return null
+ return actual
+}
+
+/** Bounded retry for a daemon that is spawning while readiness is published. */
+export async function waitForDaemon(pid, options, { timeoutMs = 3000, pollMs = 50 } = {}) {
+ const deadline = Date.now() + timeoutMs
+ for (;;) {
+ const identity = await verifyDaemon(pid, options)
+ if (identity) return identity
+ if (Date.now() >= deadline) return null
+ await new Promise((resolve) => setTimeout(resolve, pollMs))
+ }
+}
+
+function protocolVersion(name) {
+ const match = PID_RECORD_RE.exec(name)
+ return match ? Number(match[1]) : -1
+}
+
+async function scanOwnedDaemon({ userData, nodeBinary, daemonEntryPath }) {
+ let files
+ try {
+ files = await readdir(join(userData, 'daemon'))
+ } catch {
+ return null
+ }
+ const records = files.filter((name) => PID_RECORD_RE.test(name)).sort((a, b) => protocolVersion(b) - protocolVersion(a))
+ for (const name of records) {
+ const raw = await readFile(join(userData, 'daemon', name), 'utf8').catch(() => '')
+ const pid = parseDaemonPid(raw)
+ const identity = pid ? await verifyDaemon(pid, { nodeBinary, daemonEntryPath, userData }) : null
+ if (identity) return identity
+ }
+ return null
+}
+
+/**
+ * Bounded discovery: poll for a canonical pid record published after spawn,
+ * without an arbitrary first-N cap or a process census.
+ */
+export async function discoverOwnedDaemon({
+ userData,
+ nodeBinary,
+ daemonEntryPath,
+ waitMs = 0,
+ pollMs = 100
+}) {
+ if (!userData) return null
+ const deadline = Date.now() + Math.max(0, waitMs)
+ for (;;) {
+ const identity = await scanOwnedDaemon({ userData, nodeBinary, daemonEntryPath })
+ if (identity) return identity
+ const remaining = deadline - Date.now()
+ if (remaining <= 0) return null
+ await new Promise((resolve) => setTimeout(resolve, Math.min(pollMs, remaining)))
+ }
+}
diff --git a/scripts/orca/daemon-identity.test.mjs b/scripts/orca/daemon-identity.test.mjs
new file mode 100644
index 00000000..28c94e70
--- /dev/null
+++ b/scripts/orca/daemon-identity.test.mjs
@@ -0,0 +1,125 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { spawn } from 'node:child_process'
+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { canonicalDaemonSocket, discoverOwnedDaemon, verifyDaemon } from './daemon-identity.mjs'
+import { ensureIsolatedDirectories } from './env.mjs'
+import { readProcessIdentity, terminateVerifiedProcess } from './proc-identity.mjs'
+
+const FIXTURES = fileURLToPath(new URL('./fixtures/', import.meta.url))
+const FAKE_DAEMON = join(FIXTURES, 'fake-daemon.mjs')
+const NODE = process.execPath
+
+async function makeRoot() {
+ const root = await mkdtemp(join(tmpdir(), 'orca-daemon-'))
+ await ensureIsolatedDirectories(root)
+ return root
+}
+
+async function spawnDaemon({ socketPath, pidRecord, delayMs = 0, env = {} }) {
+ const child = spawn(NODE, [FAKE_DAEMON, '--socket', socketPath, '--pid-record', pidRecord], {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, FAKE_DAEMON_DELAY_MS: String(delayMs), ...env }
+ })
+ child.stderr.resume()
+ await new Promise((resolve, reject) => {
+ let buffered = ''
+ child.stdout.on('data', (chunk) => {
+ buffered += chunk.toString('utf8')
+ if (buffered.includes('ready')) resolve()
+ })
+ child.once('exit', () => reject(new Error('fake daemon exited before ready')))
+ })
+ child.stdout.resume()
+ return child
+}
+
+async function stopFixture(child) {
+ if (child.exitCode !== null || child.signalCode !== null) return
+ child.kill('SIGKILL')
+ await new Promise((resolve) => child.once('exit', resolve))
+}
+
+describe('owned daemon discovery from canonical protocol records', () => {
+ it('finds a delayed canonical record despite more than eight stale entries', async () => {
+ const root = await makeRoot()
+ const userData = join(root, 'runtime', 'user-data')
+ const daemonDir = join(userData, 'daemon')
+ await mkdir(daemonDir, { recursive: true, mode: 0o700 })
+ for (let version = 1; version <= 12; version += 1) {
+ await writeFile(join(daemonDir, `daemon-v${version}.pid`), JSON.stringify({ pid: 999999 }))
+ }
+ const socketPath = join(daemonDir, 'daemon-v49.sock')
+ const pidRecord = join(daemonDir, 'daemon-v49.pid')
+ const child = await spawnDaemon({ socketPath, pidRecord, delayMs: 700 })
+ const options = { userData, nodeBinary: NODE, daemonEntryPath: FAKE_DAEMON }
+ try {
+ assert.equal(await discoverOwnedDaemon({ ...options, waitMs: 100, pollMs: 25 }), null)
+ const identity = await discoverOwnedDaemon({ ...options, waitMs: 3000, pollMs: 25 })
+ assert.ok(identity)
+ assert.equal(identity.pid, child.pid)
+ assert.equal(identity.uid, process.getuid())
+ assert.equal(await terminateVerifiedProcess(identity, { timeoutMs: 3000 }).then((r) => r.exited), true)
+ } finally {
+ await stopFixture(child)
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects a non-socket protocol path even when the filename is canonical', async () => {
+ const root = await makeRoot()
+ const userData = join(root, 'runtime', 'user-data')
+ const daemonDir = join(userData, 'daemon')
+ await mkdir(daemonDir, { recursive: true, mode: 0o700 })
+ const fakeSocket = join(daemonDir, 'daemon-v49.sock')
+ await writeFile(fakeSocket, 'not a socket')
+ try {
+ assert.equal(await canonicalDaemonSocket(['--socket', fakeSocket], { userData }), null)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects a protocol socket outside the private daemon directory', async () => {
+ const root = await makeRoot()
+ const userData = join(root, 'runtime', 'user-data')
+ const foreignDir = join(userData, 'foreign')
+ await mkdir(foreignDir, { recursive: true, mode: 0o700 })
+ const socketPath = join(foreignDir, 'daemon-v49.sock')
+ const pidRecord = join(foreignDir, 'daemon-v49.pid')
+ const child = await spawnDaemon({ socketPath, pidRecord })
+ try {
+ const actual = await readProcessIdentity(child.pid)
+ assert.ok(actual)
+ assert.equal(await canonicalDaemonSocket(actual.argv, { userData }), null)
+ assert.equal(await verifyDaemon(child.pid, { userData, nodeBinary: NODE, daemonEntryPath: FAKE_DAEMON }), null)
+ } finally {
+ await stopFixture(child)
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects a canonical socket reached through a symlinked ancestor', async () => {
+ const root = await makeRoot()
+ const userData = join(root, 'runtime', 'user-data')
+ const daemonDir = join(userData, 'daemon')
+ await mkdir(daemonDir, { recursive: true, mode: 0o700 })
+ const alias = join(userData, 'daemon-link')
+ await symlink(daemonDir, alias)
+ const socketPath = join(alias, 'daemon-v49.sock')
+ const pidRecord = join(alias, 'daemon-v49.pid')
+ const child = await spawnDaemon({ socketPath, pidRecord })
+ try {
+ const actual = await readProcessIdentity(child.pid)
+ assert.ok(actual)
+ assert.equal(await canonicalDaemonSocket(actual.argv, { userData }), null)
+ assert.equal(await verifyDaemon(child.pid, { userData, nodeBinary: NODE, daemonEntryPath: FAKE_DAEMON }), null)
+ } finally {
+ await stopFixture(child)
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/download-fixtures.mjs b/scripts/orca/download-fixtures.mjs
new file mode 100644
index 00000000..7e431316
--- /dev/null
+++ b/scripts/orca/download-fixtures.mjs
@@ -0,0 +1,48 @@
+import { mkdtemp } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+export const FIXED_URL = 'https://example.invalid/fixed-artifact.bin'
+
+export function responseFor(chunks, { ok = true, status = 200, contentLength, url = FIXED_URL } = {}) {
+ let index = 0
+ return {
+ ok,
+ status,
+ statusText: ok ? 'OK' : 'ERR',
+ url,
+ redirected: false,
+ headers: {
+ get: (name) => (name.toLowerCase() === 'content-length' && contentLength !== undefined ? String(contentLength) : null)
+ },
+ body: {
+ [Symbol.asyncIterator]() {
+ return this
+ },
+ async next() {
+ if (index >= chunks.length) return { done: true, value: undefined }
+ return { done: false, value: Buffer.from(chunks[index++]) }
+ },
+ async return() {
+ index = chunks.length
+ return { done: true, value: undefined }
+ }
+ }
+ }
+}
+
+export function redirectFor(location, status = 302) {
+ return {
+ ok: false,
+ status,
+ statusText: 'Found',
+ url: undefined,
+ redirected: false,
+ headers: { get: (name) => (name.toLowerCase() === 'location' ? location : null) },
+ body: { cancel: async () => {} }
+ }
+}
+
+export async function scratch(name) {
+ return mkdtemp(join(tmpdir(), `orca-download-${name}-`))
+}
diff --git a/scripts/orca/download-request.mjs b/scripts/orca/download-request.mjs
new file mode 100644
index 00000000..f2723ad7
--- /dev/null
+++ b/scripts/orca/download-request.mjs
@@ -0,0 +1,84 @@
+/**
+ * Pinned HTTPS request policy shared by artifact downloads.
+ *
+ * A fixed URL is the only accepted entry point. Redirects are refused unless
+ * the caller opts into an explicit host allow-list (GitHub release assets);
+ * even then every hop must stay on HTTPS with no credentials or odd ports.
+ */
+
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])
+
+export function assertFixedUrl(url, expectedUrl) {
+ if (typeof expectedUrl !== 'string' || !expectedUrl.startsWith('https://')) {
+ throw new Error(`Fixed artifact URL must be https: ${expectedUrl}`)
+ }
+ if (typeof url !== 'string' || !url.startsWith('https://')) {
+ throw new Error(`Refusing non-https artifact URL: ${url}`)
+ }
+ if (url !== expectedUrl) {
+ throw new Error(`Refusing download from a non-fixed artifact URL: ${url}`)
+ }
+}
+
+async function assertAllowedRedirect(nextUrl, allowedHosts, previousUrl) {
+ let parsed
+ try {
+ parsed = new URL(nextUrl, previousUrl)
+ } catch {
+ throw new Error(`Refusing invalid redirect target: ${nextUrl}`)
+ }
+ if (parsed.protocol !== 'https:') {
+ throw new Error(`Refusing non-https redirect target: ${parsed.href}`)
+ }
+ if (parsed.username || parsed.password) {
+ throw new Error(`Refusing redirect target with credentials: ${parsed.href}`)
+ }
+ if (parsed.port && parsed.port !== '443') {
+ throw new Error(`Refusing redirect target with a non-443 port: ${parsed.href}`)
+ }
+ if (!allowedHosts.includes(parsed.hostname)) {
+ throw new Error(`Refusing redirect to a non-allowlisted host: ${parsed.hostname}`)
+ }
+ return parsed.href
+}
+
+export async function fetchPinnedResponse({
+ url,
+ expectedUrl,
+ allowedRedirectHosts,
+ fetchImpl,
+ signal
+}) {
+ assertFixedUrl(url, expectedUrl)
+ let current = url
+ for (let hop = 0; hop <= 5; hop += 1) {
+ const res = await fetchImpl(current, {
+ signal,
+ redirect: allowedRedirectHosts ? 'manual' : 'error'
+ })
+ if (!res || typeof res !== 'object') throw new Error('Artifact fetch returned no response')
+ if (res.redirected) {
+ throw new Error(`Refusing redirected artifact response: ${res.url ?? 'unknown'}`)
+ }
+ if (REDIRECT_STATUSES.has(res.status) && allowedRedirectHosts) {
+ await res.body?.cancel?.().catch?.(() => {})
+ const location = res.headers?.get?.('location')
+ if (typeof location !== 'string' || location.length === 0) {
+ throw new Error(`Redirect response ${res.status} has no location`)
+ }
+ current = await assertAllowedRedirect(location, allowedRedirectHosts, current)
+ continue
+ }
+ if (!res.ok) {
+ throw new Error(`Failed to download artifact: HTTP ${res.status} ${res.statusText ?? ''}`.trim())
+ }
+ if (current !== expectedUrl && !allowedRedirectHosts) {
+ throw new Error(`Refusing download from a non-fixed artifact URL: ${current}`)
+ }
+ if (res.url !== undefined && res.url !== current) {
+ throw new Error(`Refusing redirected artifact response: ${res.url}`)
+ }
+ return res
+ }
+ throw new Error('Refusing artifact download with too many redirects')
+}
diff --git a/scripts/orca/download-stream.test.mjs b/scripts/orca/download-stream.test.mjs
new file mode 100644
index 00000000..ee23410b
--- /dev/null
+++ b/scripts/orca/download-stream.test.mjs
@@ -0,0 +1,165 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { createHash } from 'node:crypto'
+import { join } from 'node:path'
+import { readFile, rm, stat } from 'node:fs/promises'
+import { downloadToFile } from './download.mjs'
+import { FIXED_URL, responseFor, scratch } from './download-fixtures.mjs'
+
+describe('bounded streamed download', () => {
+ it('streams to a private file and verifies hash and size', async () => {
+ const dir = await scratch('ok')
+ try {
+ const dest = join(dir, 'artifact.bin')
+ const chunks = [Buffer.from('hello '), Buffer.from('orca')]
+ const expected = createHash('sha256').update(Buffer.concat(chunks)).digest('hex')
+ const result = await downloadToFile({
+ url: FIXED_URL,
+ expectedUrl: FIXED_URL,
+ destination: dest,
+ expectedSha256: expected,
+ expectedSize: 10,
+ maxBytes: 10,
+ fetchImpl: async () => responseFor(chunks, { contentLength: 10 })
+ })
+ assert.equal(result.size, 10)
+ assert.equal(result.sha256, expected)
+ assert.equal((await readFile(dest, 'utf8')), 'hello orca')
+ assert.equal((await stat(dest)).mode & 0o077, 0)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('aborts before allocating when the stream exceeds the cap', async () => {
+ const dir = await scratch('cap')
+ try {
+ const dest = join(dir, 'artifact.bin')
+ const chunks = [Buffer.alloc(8), Buffer.alloc(8)]
+ let pulled = 0
+ const response = responseFor(chunks)
+ const iterator = response.body[Symbol.asyncIterator]()
+ response.body[Symbol.asyncIterator] = () => ({
+ next: async () => {
+ pulled += 1
+ return iterator.next()
+ },
+ return: () => iterator.return()
+ })
+ await assert.rejects(
+ downloadToFile({
+ url: FIXED_URL,
+ expectedUrl: FIXED_URL,
+ destination: dest,
+ maxBytes: 10,
+ fetchImpl: async () => response
+ }),
+ /exceeds/i
+ )
+ assert.equal(pulled, 2)
+ await assert.rejects(stat(dest), /ENOENT/)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects oversized content-length before reading the body', async () => {
+ const dir = await scratch('length')
+ try {
+ let pulled = 0
+ const response = responseFor([Buffer.alloc(4)], { contentLength: 1024 })
+ response.body[Symbol.asyncIterator] = () => ({
+ next: async () => {
+ pulled += 1
+ return { done: true, value: undefined }
+ }
+ })
+ await assert.rejects(
+ downloadToFile({
+ url: FIXED_URL,
+ expectedUrl: FIXED_URL,
+ destination: join(dir, 'a.bin'),
+ maxBytes: 32,
+ fetchImpl: async () => response
+ }),
+ /content-length|exceeds/i
+ )
+ assert.equal(pulled, 0)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('supports pre-aborted signals without invoking fetch', async () => {
+ const dir = await scratch('abort')
+ try {
+ let called = false
+ const controller = new AbortController()
+ controller.abort()
+ await assert.rejects(
+ downloadToFile({
+ url: FIXED_URL,
+ expectedUrl: FIXED_URL,
+ destination: join(dir, 'a.bin'),
+ maxBytes: 16,
+ signal: controller.signal,
+ fetchImpl: async () => {
+ called = true
+ return responseFor([])
+ }
+ }),
+ { name: 'AbortError' }
+ )
+ assert.equal(called, false)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('times out and removes partial files', async () => {
+ const dir = await scratch('timeout')
+ try {
+ const dest = join(dir, 'a.bin')
+ const response = responseFor([])
+ response.body[Symbol.asyncIterator] = () => ({
+ next: () => new Promise((resolve) => setTimeout(() => resolve({ done: true }), 500)),
+ return: async () => ({ done: true })
+ })
+ await assert.rejects(
+ downloadToFile({
+ url: FIXED_URL,
+ expectedUrl: FIXED_URL,
+ destination: dest,
+ maxBytes: 16,
+ timeoutMs: 40,
+ fetchImpl: async () => response
+ }),
+ /timed out/i
+ )
+ await assert.rejects(stat(dest), /ENOENT/)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('removes the partial file when the digest does not match', async () => {
+ const dir = await scratch('digest')
+ try {
+ const dest = join(dir, 'a.bin')
+ await assert.rejects(
+ downloadToFile({
+ url: FIXED_URL,
+ expectedUrl: FIXED_URL,
+ destination: dest,
+ expectedSha256: '0'.repeat(64),
+ maxBytes: 16,
+ fetchImpl: async () => responseFor([Buffer.from('abc')])
+ }),
+ /checksum/i
+ )
+ await assert.rejects(stat(dest), /ENOENT/)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/download-url.test.mjs b/scripts/orca/download-url.test.mjs
new file mode 100644
index 00000000..1eea0446
--- /dev/null
+++ b/scripts/orca/download-url.test.mjs
@@ -0,0 +1,85 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { join } from 'node:path'
+import { readFile, rm } from 'node:fs/promises'
+import { downloadToFile } from './download.mjs'
+import { FIXED_URL, redirectFor, responseFor, scratch } from './download-fixtures.mjs'
+
+describe('bounded download url and redirect policy', () => {
+ it('rejects url drift, redirects, and non-https transport', async () => {
+ const dir = await scratch('url')
+ try {
+ const base = { destination: join(dir, 'a.bin'), maxBytes: 16 }
+ await assert.rejects(
+ downloadToFile({ ...base, url: 'http://example.invalid/x', expectedUrl: FIXED_URL, fetchImpl: async () => responseFor([]) }),
+ /https/i
+ )
+ await assert.rejects(
+ downloadToFile({ ...base, url: 'https://evil.invalid/x', expectedUrl: FIXED_URL, fetchImpl: async () => responseFor([]) }),
+ /fixed artifact url/i
+ )
+ await assert.rejects(
+ downloadToFile({ ...base, url: FIXED_URL, expectedUrl: FIXED_URL, fetchImpl: async () => ({ ...responseFor([]), redirected: true }) }),
+ /redirect/i
+ )
+ await assert.rejects(
+ downloadToFile({
+ ...base,
+ url: FIXED_URL,
+ expectedUrl: FIXED_URL,
+ fetchImpl: async () => responseFor([], { url: 'https://evil.invalid/x' })
+ }),
+ /redirect|url/i
+ )
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('follows an allow-listed HTTPS redirect and verifies the final bytes', async () => {
+ const dir = await scratch('redirect-ok')
+ try {
+ const allowed = 'https://objects.githubusercontent.com/asset'
+ const dest = join(dir, 'f.bin')
+ const result = await downloadToFile({
+ url: FIXED_URL,
+ expectedUrl: FIXED_URL,
+ destination: dest,
+ maxBytes: 16,
+ allowedRedirectHosts: ['objects.githubusercontent.com'],
+ fetchImpl: async (url) =>
+ url === FIXED_URL ? redirectFor(allowed) : responseFor([Buffer.from('ok')], { url })
+ })
+ assert.equal(result.size, 2)
+ assert.equal(await readFile(dest, 'utf8'), 'ok')
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('refuses redirects to non-allowlisted, plaintext, or private hosts', async () => {
+ const dir = await scratch('redirect-deny')
+ try {
+ const base = {
+ url: FIXED_URL,
+ expectedUrl: FIXED_URL,
+ destination: join(dir, 'f.bin'),
+ maxBytes: 16,
+ allowedRedirectHosts: ['objects.githubusercontent.com']
+ }
+ for (const location of [
+ 'https://evil.invalid/asset',
+ 'http://objects.githubusercontent.com/asset',
+ 'https://127.0.0.1/asset',
+ 'https://user:[email protected]/asset'
+ ]) {
+ await assert.rejects(
+ downloadToFile({ ...base, fetchImpl: async () => redirectFor(location) }),
+ /redirect/i
+ )
+ }
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/download.mjs b/scripts/orca/download.mjs
new file mode 100644
index 00000000..947d72b1
--- /dev/null
+++ b/scripts/orca/download.mjs
@@ -0,0 +1,183 @@
+/**
+ * Bounded, streamed HTTPS download of a single fixed artifact.
+ *
+ * Guarantees:
+ * - only the exact pinned https URL is accepted (no caller-supplied overrides
+ * in production, no redirect that changes the target, no downgrade to http);
+ * - bytes are written incrementally with a hard cap, so an oversized or
+ * endless response never lands in memory or on disk in full;
+ * - timeout + caller abort cancel the fetch and remove the partial file;
+ * - the finished file is renamed into place only after digest/size checks.
+ */
+
+import { createHash, randomUUID } from 'node:crypto'
+import { createWriteStream } from 'node:fs'
+import { rename, rm } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+import { assertNoSymlinkAncestors, ensurePrivateDirTree, lstatOrNull } from './safe-paths.mjs'
+import { assertFixedUrl, fetchPinnedResponse } from './download-request.mjs'
+
+const DEFAULT_TIMEOUT_MS = 120000
+
+function abortError(message) {
+ const err = new Error(message)
+ err.name = 'AbortError'
+ return err
+}
+
+function closeStream(stream) {
+ return new Promise((resolve) => {
+ stream.once('close', resolve)
+ stream.destroy()
+ })
+}
+
+function writeChunk(stream, chunk) {
+ return new Promise((resolve, reject) => {
+ const cleanup = () => {
+ stream.removeListener('drain', onDrain)
+ stream.removeListener('error', onError)
+ }
+ const onDrain = () => {
+ cleanup()
+ resolve()
+ }
+ const onError = (err) => {
+ cleanup()
+ reject(err)
+ }
+ if (stream.write(chunk)) return resolve()
+ stream.once('drain', onDrain)
+ stream.once('error', onError)
+ })
+}
+
+export async function downloadToFile({
+ url,
+ expectedUrl,
+ destination,
+ expectedSha256,
+ expectedSize,
+ maxBytes,
+ signal,
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+ fetchImpl = globalThis.fetch,
+ allowedRedirectHosts
+} = {}) {
+ await assertFixedUrl(url, expectedUrl)
+ if (!Number.isInteger(maxBytes) || maxBytes <= 0) {
+ throw new Error(`maxBytes must be a positive integer, got ${maxBytes}`)
+ }
+ if (expectedSize !== undefined && expectedSize > maxBytes) {
+ throw new Error(`Expected size ${expectedSize} exceeds the download cap ${maxBytes}`)
+ }
+ if (signal?.aborted) throw abortError('Download aborted before it started')
+
+ await ensurePrivateDirTree(dirname(destination))
+ await assertNoSymlinkAncestors(destination)
+ const staging = join(dirname(destination), `.download-${process.pid}-${randomUUID()}`)
+ await assertNoSymlinkAncestors(staging)
+
+ const controller = new AbortController()
+ let timedOut = false
+ const onAbort = () => controller.abort()
+ signal?.addEventListener('abort', onAbort, { once: true })
+ const timer = setTimeout(() => {
+ timedOut = true
+ controller.abort()
+ }, timeoutMs)
+ timer.unref?.()
+
+ let stream
+ try {
+ const res = await fetchPinnedResponse({
+ url,
+ expectedUrl,
+ allowedRedirectHosts,
+ fetchImpl,
+ signal: controller.signal
+ })
+
+ const declared = Number(res.headers?.get?.('content-length'))
+ if (Number.isFinite(declared) && declared > maxBytes) {
+ throw new Error(`Declared content-length ${declared} exceeds the download cap ${maxBytes}`)
+ }
+
+ stream = createWriteStream(staging, { mode: 0o600, flags: 'wx' })
+ const hash = createHash('sha256')
+ let total = 0
+
+ const body = res.body
+ if (!body || typeof body[Symbol.asyncIterator] !== 'function') {
+ throw new Error('Artifact response has no readable body')
+ }
+ const iterator = body[Symbol.asyncIterator]()
+ // Abort must interrupt a pending read, not just the fetch handshake.
+ const abortPromise = new Promise((_, reject) => {
+ controller.signal.addEventListener(
+ 'abort',
+ () => {
+ const err = timedOut
+ ? new Error(`Artifact download timed out after ${timeoutMs}ms`)
+ : abortError('Artifact download aborted')
+ if (timedOut) err.name = 'TimeoutError'
+ reject(err)
+ },
+ { once: true }
+ )
+ })
+ abortPromise.catch(() => {})
+ try {
+ for (;;) {
+ const step = await Promise.race([iterator.next(), abortPromise])
+ if (step.done) break
+ const buf = Buffer.isBuffer(step.value) ? step.value : Buffer.from(step.value)
+ total += buf.length
+ if (total > maxBytes) {
+ throw new Error(`Artifact download exceeds the cap of ${maxBytes} bytes`)
+ }
+ hash.update(buf)
+ await writeChunk(stream, buf)
+ }
+ } finally {
+ await iterator.return?.().catch?.(() => {})
+ }
+ await new Promise((resolve, reject) => {
+ stream.once('finish', resolve)
+ stream.once('error', reject)
+ stream.end()
+ })
+ stream = undefined
+
+ const actualSha256 = hash.digest('hex')
+ if (expectedSha256 !== undefined && actualSha256 !== expectedSha256) {
+ throw new Error(
+ `Artifact checksum mismatch: expected ${expectedSha256}, got ${actualSha256}`
+ )
+ }
+ if (expectedSize !== undefined && total !== expectedSize) {
+ throw new Error(`Artifact size mismatch: expected ${expectedSize}, got ${total}`)
+ }
+
+ await assertNoSymlinkAncestors(destination)
+ if (await lstatOrNull(destination)) {
+ throw new Error(`Refusing to overwrite existing artifact: ${destination}`)
+ }
+ await rename(staging, destination)
+ return { path: destination, sha256: actualSha256, size: total }
+ } catch (err) {
+ if (timedOut) {
+ const timeoutErr = new Error(`Artifact download timed out after ${timeoutMs}ms`)
+ timeoutErr.name = 'TimeoutError'
+ throw timeoutErr
+ }
+ if (controller.signal.aborted && !signal?.aborted) throw err
+ if (signal?.aborted) throw abortError('Artifact download aborted')
+ throw err
+ } finally {
+ clearTimeout(timer)
+ signal?.removeEventListener('abort', onAbort)
+ if (stream) await closeStream(stream)
+ await rm(staging, { force: true }).catch(() => {})
+ }
+}
diff --git a/scripts/orca/env.mjs b/scripts/orca/env.mjs
new file mode 100644
index 00000000..2474b763
--- /dev/null
+++ b/scripts/orca/env.mjs
@@ -0,0 +1,112 @@
+/**
+ * Isolated process environment for Orca runtime execution.
+ * Strict allowlist, private HOME/XDG/TMP/HISTFILE, and safe scratch-root fencing.
+ * This is environment isolation (same Unix account), not an OS sandbox.
+ */
+
+import { chmod, lstat } from 'node:fs/promises'
+import { lstatSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { isAbsolute, join, resolve, sep } from 'node:path'
+import { ORCA_VERSION } from './constants.mjs'
+import { ensureManagedRoot } from './private-store.mjs'
+
+const ALLOWLISTED_PARENT_KEYS = ['LANG', 'LANGUAGE', 'TERM', 'TZ']
+const ALLOWLISTED_PREFIXES = ['LC_']
+const SAFE_PATH = '/usr/local/bin:/usr/bin:/bin'
+
+function allowedKey(key) {
+ return ALLOWLISTED_PARENT_KEYS.includes(key) || ALLOWLISTED_PREFIXES.some((p) => key.startsWith(p))
+}
+
+function cleanValue(value) {
+ if (typeof value !== 'string' || value.length > 128) return null
+ if (/[\0\r\n]/.test(value)) return null
+ return value
+}
+
+export function createIsolatedEnv({ scratchDir, baseEnv = process.env } = {}) {
+ if (!scratchDir) throw new Error('scratchDir is required for isolated environment creation')
+ const runtimeRoot = join(resolve(scratchDir), 'runtime')
+ const env = {}
+ for (const key of Object.keys(baseEnv)) {
+ if (!allowedKey(key)) continue
+ const value = cleanValue(baseEnv[key])
+ if (value !== null) env[key] = value
+ }
+ env.PATH = SAFE_PATH
+ env.SHELL = '/bin/bash'
+ env.HOME = join(runtimeRoot, 'home')
+ env.HISTFILE = join(env.HOME, '.bash_history')
+ env.ORCA_USER_DATA = join(runtimeRoot, 'user-data')
+ env.ORCA_USER_DATA_PATH = env.ORCA_USER_DATA
+ env.TMPDIR = join(runtimeRoot, 'tmp')
+ env.XDG_CONFIG_HOME = join(env.HOME, '.config')
+ env.XDG_DATA_HOME = join(env.HOME, '.local', 'share')
+ env.XDG_CACHE_HOME = join(env.HOME, '.cache')
+ env.XDG_STATE_HOME = join(env.HOME, '.local', 'state')
+ env.DO_NOT_TRACK = '1'
+ env.ORCA_TELEMETRY_DISABLED = '1'
+ env.ORCA_DIAGNOSTICS_DISABLED = '1'
+ env.ORCA_VERSION = ORCA_VERSION
+ return env
+}
+
+const DENIED_HOME_PATHS = ['.orca', '.orca-remote', '.codex', '.claude', '.ssh', '.gnupg', '.config']
+
+/** Reject canonical/worktree roots and credential-storage locations. */
+export function assertSafeScratchRoot(scratchDir) {
+ const abs = resolve(scratchDir)
+ if (!isAbsolute(abs)) throw new Error(`scratch root must be absolute: ${scratchDir}`)
+ if (abs === sep) throw new Error('refusing filesystem root as scratch root')
+ const home = resolve(homedir())
+ if (abs === home) throw new Error('refusing home directory as scratch root')
+ for (const denied of DENIED_HOME_PATHS) {
+ const prefix = join(home, denied)
+ if (abs === prefix || abs.startsWith(`${prefix}${sep}`)) {
+ throw new Error(`refusing credential/user-state path as scratch root: ${abs}`)
+ }
+ }
+ const hermes = join(home, '.hermes')
+ const hermesScratch = join(hermes, 'cache', 'scratch')
+ if ((abs === hermes || abs.startsWith(`${hermes}${sep}`)) && abs !== hermesScratch && !abs.startsWith(`${hermesScratch}${sep}`)) {
+ throw new Error(`refusing .hermes credential storage as scratch root: ${abs}`)
+ }
+ // Reject a git checkout/worktree root (canonical or registered).
+ let current = abs
+ for (;;) {
+ if (lstatSync(join(current, '.git'), { throwIfNoEntry: false })) {
+ throw new Error(`refusing git worktree/repository path as scratch root: ${abs}`)
+ }
+ const parent = resolve(current, '..')
+ if (parent === current) break
+ current = parent
+ }
+ return abs
+}
+
+/** Create the private directory tree: 0700, owned, no symlinked ancestors. */
+export async function ensureIsolatedDirectories(scratchDir) {
+ const root = assertSafeScratchRoot(scratchDir)
+ await ensureManagedRoot(root)
+ const dirs = [
+ join(root, 'runtime'),
+ join(root, 'runtime', 'home'),
+ join(root, 'runtime', 'home', '.config'),
+ join(root, 'runtime', 'home', '.local', 'share'),
+ join(root, 'runtime', 'home', '.local', 'state'),
+ join(root, 'runtime', 'home', '.cache'),
+ join(root, 'runtime', 'user-data'),
+ join(root, 'runtime', 'tmp'),
+ join(root, 'slots'),
+ join(root, 'runtimes')
+ ]
+ for (const dir of dirs) {
+ await ensureManagedRoot(dir)
+ const info = await lstat(dir)
+ if (info.isSymbolicLink()) throw new Error(`refusing symlink directory: ${dir}`)
+ if (info.uid !== process.getuid()) throw new Error(`directory is not owned by this user: ${dir}`)
+ if ((info.mode & 0o077) !== 0) await chmod(dir, 0o700)
+ }
+ return root
+}
diff --git a/scripts/orca/env.test.mjs b/scripts/orca/env.test.mjs
new file mode 100644
index 00000000..743f43a5
--- /dev/null
+++ b/scripts/orca/env.test.mjs
@@ -0,0 +1,101 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { join } from 'node:path'
+import { mkdir, mkdtemp, symlink, rm, stat, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { createIsolatedEnv, ensureIsolatedDirectories, assertSafeScratchRoot } from './env.mjs'
+
+describe('isolated environment with strict allowlist', () => {
+ it('inherits only locale/terminal vars and fences every writable path', () => {
+ const parentEnv = {
+ PATH: '/custom/bin:/usr/local/bin:/usr/bin:/bin',
+ HOME: '/home/antinrml',
+ USER: 'antinrml',
+ LANG: 'en_US.UTF-8',
+ LC_ALL: 'en_US.UTF-8',
+ TERM: 'xterm-256color',
+ DISPLAY: ':0',
+ NODE_OPTIONS: '--inspect=0.0.0.0',
+ NODE_PATH: '/malicious/node_modules',
+ LD_PRELOAD: '/malicious/lib.so',
+ LD_LIBRARY_PATH: '/malicious/lib',
+ BASH_ENV: '/malicious/bashrc',
+ ENV: '/malicious/env',
+ PYTHONPATH: '/malicious/python',
+ CODEX_HOME: '/home/antinrml/.codex',
+ CLAUDE_CONFIG_DIR: '/home/antinrml/.claude',
+ SSH_AUTH_SOCK: '/tmp/ssh-agent.sock',
+ ORCA_SECRET_INHERITED: 'leak',
+ OPENAI_API_KEY: 'sk-secret123',
+ LANG_EVIL: 'nope'
+ }
+
+ const scratchDir = '/tmp/scratch-test'
+ const env = createIsolatedEnv({ scratchDir, baseEnv: parentEnv })
+
+ assert.equal(env.LANG, 'en_US.UTF-8')
+ assert.equal(env.LC_ALL, 'en_US.UTF-8')
+ assert.equal(env.TERM, 'xterm-256color')
+
+ for (const key of [
+ 'NODE_OPTIONS', 'NODE_PATH', 'LD_PRELOAD', 'LD_LIBRARY_PATH', 'BASH_ENV', 'ENV',
+ 'PYTHONPATH', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'SSH_AUTH_SOCK',
+ 'ORCA_SECRET_INHERITED', 'DISPLAY', 'OPENAI_API_KEY', 'LANG_EVIL'
+ ]) {
+ assert.equal(env[key], undefined, `${key} leaked into the isolated env`)
+ }
+
+ assert.equal(env.PATH, '/usr/local/bin:/usr/bin:/bin')
+ assert.equal(env.HOME, '/tmp/scratch-test/runtime/home')
+ assert.equal(env.ORCA_USER_DATA, '/tmp/scratch-test/runtime/user-data')
+ assert.equal(env.TMPDIR, '/tmp/scratch-test/runtime/tmp')
+ assert.equal(env.HISTFILE, '/tmp/scratch-test/runtime/home/.bash_history')
+ assert.equal(env.ORCA_VERSION, '1.4.230')
+ assert.equal(env.DO_NOT_TRACK, '1')
+ })
+
+ it('rejects symlinked scratch roots and symlinked ancestors', async () => {
+ const testDir = await mkdtemp(join(tmpdir(), 'orca-scratch-'))
+ const realDir = join(testDir, 'real')
+ await mkdir(realDir, { mode: 0o700 })
+ const link = join(testDir, 'link-scratch')
+ await symlink(realDir, link)
+ await assert.rejects(() => ensureIsolatedDirectories(link), /symlink/i)
+
+ const nested = join(link, 'nested')
+ await assert.rejects(() => ensureIsolatedDirectories(nested), /symlink/i)
+
+ await rm(testDir, { recursive: true, force: true })
+ })
+
+ it('refuses git worktree roots and credential/user-state paths', async () => {
+ const testDir = await mkdtemp(join(tmpdir(), 'orca-scratch-git-'))
+ await mkdir(join(testDir, '.git'))
+ assert.throws(() => assertSafeScratchRoot(testDir), /git worktree/i)
+
+ assert.throws(() => assertSafeScratchRoot('/'), /filesystem root/i)
+ assert.throws(() => assertSafeScratchRoot(join(process.env.HOME, '.orca')), /credential|user-state/i)
+ assert.throws(() => assertSafeScratchRoot(join(process.env.HOME, '.hermes')), /credential/i)
+ assert.doesNotThrow(() => assertSafeScratchRoot(join(process.env.HOME, '.hermes', 'cache', 'scratch', 'x')))
+
+ await rm(testDir, { recursive: true, force: true })
+ })
+
+ it('creates the private runtime tree at 0700 and tightens loose existing dirs', async () => {
+ const root = join(await mkdtemp(join(tmpdir(), 'orca-scratch-tree-')), 'root')
+ try {
+ await ensureIsolatedDirectories(root)
+ for (const dir of ['', 'runtime', 'runtime/home', 'runtime/user-data', 'runtime/tmp']) {
+ assert.equal((await stat(join(root, dir))).mode & 0o777, 0o700, `${dir || 'root'} is not 0700`)
+ }
+
+ const loose = join(root, 'runtime', 'tmp')
+ await import('node:fs/promises').then((fs) => fs.chmod(loose, 0o755))
+ await ensureIsolatedDirectories(root)
+ assert.equal((await stat(loose)).mode & 0o777, 0o700)
+ await writeFile(join(loose, 'probe.txt'), 'ok', { mode: 0o600 })
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/fixtures/daemon-entry.js b/scripts/orca/fixtures/daemon-entry.js
new file mode 100644
index 00000000..e6027b39
--- /dev/null
+++ b/scripts/orca/fixtures/daemon-entry.js
@@ -0,0 +1 @@
+import './fake-daemon.mjs'
diff --git a/scripts/orca/fixtures/fake-daemon.mjs b/scripts/orca/fixtures/fake-daemon.mjs
new file mode 100644
index 00000000..ca382440
--- /dev/null
+++ b/scripts/orca/fixtures/fake-daemon.mjs
@@ -0,0 +1,38 @@
+// Test fixture: a disposable stand-in for an Orca terminal daemon.
+// Creates a canonical protocol socket and writes a canonical JSON pid record,
+// optionally delayed to exercise bounded discovery barriers.
+import { createServer } from 'node:net'
+import { chmodSync, mkdirSync, unlinkSync, writeFileSync } from 'node:fs'
+import { dirname } from 'node:path'
+
+const args = process.argv.slice(2)
+const value = (name, fallback) => {
+ const i = args.indexOf(name)
+ return i >= 0 && args[i + 1] !== undefined ? args[i + 1] : fallback
+}
+
+const socketPath = value('--socket')
+const pidRecord = value('--pid-record')
+const delayMs = Number(value('--pid-delay-ms', process.env.FAKE_DAEMON_DELAY_MS || '0'))
+if (!socketPath || !pidRecord) {
+ process.stderr.write('fake daemon requires --socket and --pid-record\n')
+ process.exit(2)
+}
+
+mkdirSync(dirname(socketPath), { recursive: true, mode: 0o700 })
+const server = createServer((socket) => socket.end())
+server.listen(socketPath, () => {
+ chmodSync(socketPath, 0o600)
+ const record = JSON.stringify({ pid: process.pid, startedAtMs: Date.now(), entryPath: process.argv[1] })
+ setTimeout(() => writeFileSync(pidRecord, record, { mode: 0o600 }), Math.max(0, delayMs))
+ process.stdout.write('ready\n')
+})
+
+const shutdown = () => {
+ server.close(() => {
+ try { unlinkSync(socketPath) } catch {}
+ process.exit(0)
+ })
+}
+process.on('SIGTERM', shutdown)
+setInterval(() => {}, 1000)
diff --git a/scripts/orca/fixtures/fake-orca-cli.mjs b/scripts/orca/fixtures/fake-orca-cli.mjs
new file mode 100644
index 00000000..da021eaa
--- /dev/null
+++ b/scripts/orca/fixtures/fake-orca-cli.mjs
@@ -0,0 +1,39 @@
+// Test fixture: disposable stand-in for the Orca CLI RPC (`out/cli/index.js`).
+// Every invocation appends its argv and pid to FAKE_CLI_LOG so tests can prove
+// the exact terminal handle was created and closed.
+import { appendFileSync } from 'node:fs'
+
+const args = process.argv.slice(2)
+const mode = process.env.FAKE_CLI_MODE || 'normal'
+const token = process.env.FAKE_CLI_TOKEN || 'TOKEN'
+const log = process.env.FAKE_CLI_LOG
+
+if (log) appendFileSync(log, `pid:${process.pid} ${args.join(' ')}\n`, { mode: 0o600 })
+
+const reply = (payload, code = 0) => {
+ process.stdout.write(`${JSON.stringify(payload)}\n`)
+ process.exit(code)
+}
+
+if (mode === 'hang') {
+ setInterval(() => {}, 1000)
+} else if (mode === 'exit-nonzero') {
+ process.stderr.write('fake cli rejected the pairing code\n')
+ process.exit(4)
+} else if (mode === 'invalid-json') {
+ process.stdout.write('this is not json\n')
+} else if (args[0] === 'repo' && args[1] === 'add') {
+ if (mode === 'repo-fail') reply({ ok: false, error: { message: 'repo denied' } })
+ reply({ ok: true, result: { repo: { id: 'repo-1' } } })
+} else if (args[0] === 'terminal' && args[1] === 'create') {
+ if (mode === 'create-fail') reply({ ok: false, error: { message: 'create denied' } })
+ reply({ ok: true, result: { terminal: { handle: 'term-abc' } } })
+} else if (args[0] === 'terminal' && args[1] === 'read') {
+ const tail = mode === 'no-echo' ? [`$ echo ${token}`] : [`$ echo ${token}`, token, '']
+ reply({ ok: true, result: { terminal: { handle: 'term-abc', tail } } })
+} else if (args[0] === 'terminal' && args[1] === 'close') {
+ if (mode === 'close-fail') reply({ ok: false, error: { message: 'close denied' } })
+ reply({ ok: true, result: { terminal: { handle: 'term-abc', closed: true } } })
+} else {
+ reply({ ok: false, error: { message: `unsupported command: ${args.join(' ')}` } })
+}
diff --git a/scripts/orca/fixtures/fake-orcad-server.mjs b/scripts/orca/fixtures/fake-orcad-server.mjs
new file mode 100644
index 00000000..d6cd6917
--- /dev/null
+++ b/scripts/orca/fixtures/fake-orcad-server.mjs
@@ -0,0 +1,100 @@
+// Test fixture: disposable stand-in for orcad-server.
+// Emits a real readiness line and spawns a real detached daemon that creates a
+// canonical socket and pid record, so owned-child cleanup is exercised for real.
+import { spawn } from 'node:child_process'
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const args = process.argv.slice(2)
+const value = (name, fallback) => {
+ const i = args.indexOf(name)
+ return i >= 0 && args[i + 1] !== undefined ? args[i + 1] : fallback
+}
+
+const bind = value('--bind', '127.0.0.1')
+const port = Number(value('--port', '0'))
+const mode = process.env.FAKE_MODE || 'normal'
+const userData = process.env.ORCA_USER_DATA
+const daemonEntry = process.env.FAKE_DAEMON_ENTRY || join(dirname(fileURLToPath(import.meta.url)), 'daemon-entry.js')
+const advertised = value('--pairing-address', process.env.FAKE_ADVERTISED || `ws://${bind}:${port}`)
+
+let daemonPid = 0
+if (mode !== 'exit' && mode !== 'no-daemon' && userData) {
+ const daemonDir = join(userData, 'daemon')
+ const socketPath = join(daemonDir, 'daemon-v49.sock')
+ const pidPath = join(daemonDir, 'daemon-v49.pid')
+ mkdirSync(daemonDir, { recursive: true, mode: 0o700 })
+ const daemon = spawn(process.execPath, [daemonEntry, '--socket', socketPath, '--pid-record', pidPath], {
+ detached: true,
+ stdio: 'ignore',
+ env: process.env
+ })
+ daemon.unref()
+ daemonPid = daemon.pid
+ writeFileSync(join(userData, 'fake-pids.json'), JSON.stringify({ serverPid: process.pid, daemonPid }), {
+ mode: 0o600
+ })
+}
+
+if (mode === 'ignore-term') process.on('SIGTERM', () => {})
+
+if (mode === 'exit') {
+ process.stderr.write('fixture exiting early\n')
+ process.exit(7)
+}
+
+if (mode === 'stderr-flood') {
+ process.stderr.write(`pairing failed: orca://pair?code=SECRET_PAIRING_CODE\n${'x'.repeat(300000)}`)
+}
+
+function emitReadiness() {
+ if (mode === 'silent' || mode === 'stderr-flood') return
+ const pid = mode === 'forged-pid' ? 999999 : process.pid
+ const reportedDaemonPid = mode === 'daemon-forged-pid' ? 999999 : daemonPid
+ const version = mode === 'wrong-version' ? '0.0.0-orcad' : '1.4.230'
+ const payload = {
+ type: 'orca_server_ready',
+ schemaVersion: 1,
+ runtimeId: 'fixture-runtime-id',
+ boundEndpoint: `ws://${bind}:${port}`,
+ advertisedEndpoint: mode === 'bad-endpoint' ? 'wss://evil.example' : advertised,
+ pairing: {
+ available: true,
+ url: 'orca://pair?code=SECRET_PAIRING_CODE',
+ endpoint: `ws://${bind}:${port}`,
+ deviceId: 'fixture-device',
+ webClientUrl: `http://${bind}:${port}/?token=SECRET_WEB_TOKEN`,
+ scope: 'runtime',
+ qr: null
+ },
+ health: {
+ buildVersion: version,
+ nodeVersion: '24.21.0',
+ nodeAbi: '137',
+ pid,
+ terminalDaemon: {
+ state: mode === 'daemon-down' ? 'down' : 'live',
+ ownsFreshSessions: true,
+ pid: reportedDaemonPid,
+ entryPath: daemonEntry,
+ selfTest: { ok: true, verdict: 'healthy', coverage: 'pty-spawn' }
+ }
+ }
+ }
+ process.stdout.write(`${JSON.stringify(payload)}\n`)
+}
+
+const readyDelayMs = mode === 'delayed-ready' ? Number(process.env.FAKE_READY_DELAY_MS || '1200') : 0
+setTimeout(emitReadiness, readyDelayMs)
+
+if (mode === 'crash-after-ready') {
+ setTimeout(() => process.exit(42), readyDelayMs + Number(process.env.FAKE_CRASH_DELAY_MS || '300')).unref()
+}
+
+if (mode === 'stdout-flood') {
+ const timer = setInterval(() => process.stdout.write('x'.repeat(65536)), 5)
+ timer.unref()
+}
+
+setInterval(() => {}, 1000)
diff --git a/scripts/orca/fixtures/hold-child.mjs b/scripts/orca/fixtures/hold-child.mjs
new file mode 100644
index 00000000..857ffdec
--- /dev/null
+++ b/scripts/orca/fixtures/hold-child.mjs
@@ -0,0 +1,5 @@
+// Test fixture: a disposable child that stays alive until SIGTERM/SIGKILL.
+// Prints "ready" once handlers are installed so tests never race the signal.
+process.on('SIGTERM', () => process.exit(0))
+process.stdout.write('ready\n')
+setInterval(() => {}, 1000)
diff --git a/scripts/orca/fixtures/stubborn-child.mjs b/scripts/orca/fixtures/stubborn-child.mjs
new file mode 100644
index 00000000..32d8fb1d
--- /dev/null
+++ b/scripts/orca/fixtures/stubborn-child.mjs
@@ -0,0 +1,5 @@
+// Test fixture: a disposable child that ignores SIGTERM so forced-kill paths are testable.
+// Prints "ready" once the handler is installed so tests never race the signal.
+process.on('SIGTERM', () => {})
+process.stdout.write('ready\n')
+setInterval(() => {}, 1000)
diff --git a/scripts/orca/launcher.mjs b/scripts/orca/launcher.mjs
new file mode 100644
index 00000000..efedfc1a
--- /dev/null
+++ b/scripts/orca/launcher.mjs
@@ -0,0 +1,190 @@
+/**
+ * Orca launcher validation, readiness contract, private receipt publication.
+ * Process signalling lives in lifecycle.mjs and always uses proc-identity.mjs.
+ */
+
+import { existsSync } from 'node:fs'
+import { isAbsolute, join } from 'node:path'
+import { isIP } from 'node:net'
+import { DEFAULT_BIND, DEFAULT_PORT, ORCA_VERSION, PINNED_NODE, WEB_CLIENT_INDEX_FILENAME } from './constants.mjs'
+
+const EXPECTED_NODE_VERSION = PINNED_NODE.version
+const EXPECTED_NODE_ABI = '137'
+const RUNTIME_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/
+
+export function validateLauncherArgs({ bind = DEFAULT_BIND, port = DEFAULT_PORT, webClientRoot } = {}) {
+ if (!isIP(bind)) throw new Error(`bind host must be a valid IP address, got: ${bind}`)
+ if (bind !== '127.0.0.1' && bind !== '::1' && !bind.startsWith('127.')) {
+ throw new Error(`bind host must be a loopback address, got: ${bind}`)
+ }
+ const portNum = Number(port)
+ if (typeof port === 'string' && !/^\d+$/.test(port)) throw new Error(`port must be an integer, got: ${port}`)
+ if (!Number.isInteger(portNum) || portNum < 0 || portNum > 65535) {
+ throw new Error(`port must be an integer 0-65535, got: ${port}`)
+ }
+ if (webClientRoot && !existsSync(join(webClientRoot, WEB_CLIENT_INDEX_FILENAME))) {
+ throw new Error(`webClientRoot missing ${WEB_CLIENT_INDEX_FILENAME}`)
+ }
+}
+
+export function sanitizeEndpoint(value) {
+ if (typeof value !== 'string' || value.length === 0 || value.length > 2048) return null
+ try {
+ const url = new URL(value)
+ if (url.username || url.password || url.search || url.hash) return null
+ if (url.protocol !== 'ws:' && url.protocol !== 'wss:') return null
+ return `${url.protocol}//${url.host}${url.pathname.replace(/\/$/, '')}`
+ } catch {
+ return null
+ }
+}
+
+function isLoopbackHost(hostname) {
+ if (hostname === '::1' || hostname === '[::1]') return true
+ return isIP(hostname) === 4 && hostname.startsWith('127.')
+}
+
+function parseWsEndpoint(value) {
+ const clean = sanitizeEndpoint(value)
+ if (!clean) return null
+ const url = new URL(clean)
+ return { url, protocol: url.protocol, hostname: url.hostname, port: Number(url.port || 0) }
+}
+
+export function validateServerReadiness(payload, {
+ expectedChildPid,
+ bind = DEFAULT_BIND,
+ port = DEFAULT_PORT,
+ advertisedEndpoint,
+ allowLoopbackAdvertised = false
+} = {}) {
+ if (!payload || typeof payload !== 'object') throw new Error('Readiness payload is not an object')
+ if (payload.type !== 'orca_server_ready' || payload.schemaVersion !== 1) {
+ throw new Error(`Invalid readiness payload: ${payload.type} v${payload.schemaVersion}`)
+ }
+ if (typeof payload.runtimeId !== 'string' || !RUNTIME_ID_RE.test(payload.runtimeId)) {
+ throw new Error('Readiness runtimeId is missing or malformed')
+ }
+ const health = payload.health
+ if (!health || typeof health !== 'object') throw new Error('Readiness health block missing')
+ if (health.buildVersion !== ORCA_VERSION) {
+ throw new Error(`buildVersion mismatch: expected ${ORCA_VERSION}, got ${health.buildVersion}`)
+ }
+ if (health.nodeVersion !== EXPECTED_NODE_VERSION) {
+ throw new Error(`nodeVersion mismatch: expected ${EXPECTED_NODE_VERSION}, got ${health.nodeVersion}`)
+ }
+ if (String(health.nodeAbi) !== EXPECTED_NODE_ABI) {
+ throw new Error(`nodeAbi mismatch: expected ${EXPECTED_NODE_ABI}, got ${health.nodeAbi}`)
+ }
+ if (!Number.isInteger(expectedChildPid) || health.pid !== expectedChildPid) {
+ throw new Error(`Health PID mismatch: expected child PID ${expectedChildPid}, got ${health.pid}`)
+ }
+
+ const bound = parseWsEndpoint(payload.boundEndpoint ?? payload.endpoint)
+ if (!bound) throw new Error('bound endpoint is missing or malformed')
+ if (bound.hostname !== bind) {
+ throw new Error(`bound endpoint host mismatch: expected ${bind}, got ${bound.hostname}`)
+ }
+ if (bound.protocol !== 'ws:') throw new Error(`bound endpoint must be ws:// on loopback, got ${bound.protocol}`)
+ const requestedPort = Number(port)
+ if (requestedPort !== 0 && bound.port !== requestedPort) {
+ throw new Error(`bound endpoint port mismatch: expected ${requestedPort}, got ${bound.port}`)
+ }
+ if (!Number.isInteger(bound.port) || bound.port < 1 || bound.port > 65535) {
+ throw new Error(`bound endpoint port is invalid: ${bound.port}`)
+ }
+
+ const advertised = parseWsEndpoint(payload.advertisedEndpoint)
+ if (!advertised) throw new Error('advertised endpoint is missing or malformed')
+ const expectedAdvertised = advertisedEndpoint ? parseWsEndpoint(advertisedEndpoint) : null
+ if (expectedAdvertised) {
+ if (advertised.url.href !== expectedAdvertised.url.href) {
+ throw new Error(`advertised endpoint mismatch: expected ${expectedAdvertised.url.href}, got ${advertised.url.href}`)
+ }
+ } else if (allowLoopbackAdvertised) {
+ if (advertised.protocol !== 'ws:' && advertised.protocol !== 'wss:') {
+ throw new Error(`advertised endpoint protocol unsupported: ${advertised.protocol}`)
+ }
+ } else if (advertised.protocol !== 'wss:' || isLoopbackHost(advertised.hostname)) {
+ throw new Error('advertised endpoint must be the configured non-loopback wss URL')
+ }
+
+ const daemon = health.terminalDaemon
+ if (!daemon || typeof daemon !== 'object') throw new Error('terminal daemon block missing')
+ if (daemon.state !== 'live' || daemon.ownsFreshSessions !== true) {
+ throw new Error(`terminal daemon is not live/owning sessions: ${daemon.state}`)
+ }
+ if (!Number.isInteger(daemon.pid) || daemon.pid <= 1) {
+ throw new Error(`terminal daemon pid is invalid: ${daemon.pid}`)
+ }
+ if (typeof daemon.entryPath !== 'string' || !isAbsolute(daemon.entryPath)) {
+ throw new Error('terminal daemon entryPath must be absolute')
+ }
+ if (!daemon.selfTest || daemon.selfTest.ok !== true) {
+ throw new Error(`terminal daemon selfTest failed: ${daemon.selfTest?.verdict ?? 'missing'}`)
+ }
+}
+
+export function redactServerReadiness(payload) {
+ const health = payload?.health ?? {}
+ const daemon = health.terminalDaemon ?? {}
+ return {
+ type: 'orca_server_ready',
+ schemaVersion: 1,
+ runtimeId: typeof payload?.runtimeId === 'string' ? payload.runtimeId : null,
+ version: typeof health.buildVersion === 'string' ? health.buildVersion : null,
+ nodeVersion: typeof health.nodeVersion === 'string' ? health.nodeVersion : null,
+ nodeAbi: typeof health.nodeAbi === 'string' ? health.nodeAbi : null,
+ boundEndpoint: sanitizeEndpoint(payload?.boundEndpoint ?? payload?.endpoint),
+ advertisedEndpoint: sanitizeEndpoint(payload?.advertisedEndpoint),
+ pairingAvailable: Boolean(payload?.pairing?.available),
+ serverPid: Number.isInteger(health.pid) ? health.pid : null,
+ daemonPid: Number.isInteger(daemon.pid) ? daemon.pid : null,
+ healthState: typeof daemon.state === 'string' ? daemon.state : null,
+ selfTestVerdict: typeof daemon.selfTest?.verdict === 'string' ? daemon.selfTest.verdict : null
+ }
+}
+
+export function parseDaemonPid(raw) {
+ if (!raw || typeof raw !== 'string') return null
+ const num = Number(raw.trim())
+ if (Number.isInteger(num) && num > 1) return num
+ try {
+ const parsed = JSON.parse(raw.trim())
+ if (parsed && Number.isInteger(parsed.pid) && parsed.pid > 1) return parsed.pid
+ } catch {}
+ return null
+}
+
+export function createRuntimeIdentity({
+ readyPayload,
+ serverIdentity,
+ nodeBinary,
+ serverEntry,
+ userData,
+ boundEndpoint,
+ advertisedEndpoint,
+ readyAt = new Date().toISOString()
+}) {
+ if (!serverIdentity || !Number.isInteger(serverIdentity.pid) || !serverIdentity.startTicks) {
+ throw new Error('createRuntimeIdentity requires a verified server identity (pid + startTicks)')
+ }
+ for (const [label, p] of [['nodeBinary', nodeBinary], ['serverEntry', serverEntry], ['userData', userData]]) {
+ if (typeof p !== 'string' || !isAbsolute(p)) throw new Error(`${label} must be an absolute path`)
+ }
+ return {
+ schemaVersion: 1,
+ runtimeId: readyPayload.runtimeId,
+ version: ORCA_VERSION,
+ serverPid: serverIdentity.pid,
+ serverStartTicks: String(serverIdentity.startTicks),
+ nodeBinary,
+ serverEntry,
+ userData,
+ boundEndpoint: sanitizeEndpoint(boundEndpoint) ?? boundEndpoint,
+ advertisedEndpoint: sanitizeEndpoint(advertisedEndpoint) ?? advertisedEndpoint,
+ readyAt
+ }
+}
+
+export { ensureManagedRoot, writePrivateFile, readPrivateJson } from './private-store.mjs'
diff --git a/scripts/orca/launcher.test.mjs b/scripts/orca/launcher.test.mjs
new file mode 100644
index 00000000..0aa29f1d
--- /dev/null
+++ b/scripts/orca/launcher.test.mjs
@@ -0,0 +1,211 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { join } from 'node:path'
+import { mkdir, mkdtemp, writeFile, symlink, rm, readdir, stat } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import {
+ validateLauncherArgs,
+ validateServerReadiness,
+ redactServerReadiness,
+ createRuntimeIdentity,
+ ensureManagedRoot,
+ writePrivateFile,
+ parseDaemonPid
+} from './launcher.mjs'
+
+const READY = {
+ type: 'orca_server_ready',
+ schemaVersion: 1,
+ runtimeId: 'runtime-abc',
+ boundEndpoint: 'ws://127.0.0.1:6769',
+ advertisedEndpoint: 'wss://orca.example.ts.net',
+ pairing: { available: true, url: 'orca://pair?code=SECRET', endpoint: 'ws://127.0.0.1:6769' },
+ health: {
+ buildVersion: '1.4.230',
+ nodeVersion: '24.21.0',
+ nodeAbi: '137',
+ pid: 12345,
+ terminalDaemon: {
+ state: 'live',
+ ownsFreshSessions: true,
+ pid: 12346,
+ entryPath: '/slot/daemon-entry.js',
+ selfTest: { ok: true, verdict: 'healthy' }
+ }
+ }
+}
+
+const clone = (v) => JSON.parse(JSON.stringify(v))
+const opts = (extra = {}) => ({
+ expectedChildPid: 12345,
+ bind: '127.0.0.1',
+ port: 6769,
+ allowLoopbackAdvertised: false,
+ ...extra
+})
+
+describe('launcher argument and readiness validation', () => {
+ it('accepts loopback binds and rejects malformed, non-loopback, and out-of-range values', () => {
+ assert.doesNotThrow(() => validateLauncherArgs({ bind: '127.0.0.1', port: 6769 }))
+ assert.doesNotThrow(() => validateLauncherArgs({ bind: '127.0.0.2', port: 0 }))
+ assert.doesNotThrow(() => validateLauncherArgs({ bind: '::1', port: 6769 }))
+ assert.throws(() => validateLauncherArgs({ bind: '127.evil.com', port: 6769 }), /valid IP/i)
+ assert.throws(() => validateLauncherArgs({ bind: '0.0.0.0', port: 6769 }), /loopback/i)
+ assert.throws(() => validateLauncherArgs({ bind: '127.0.0.1', port: 70000 }), /0-65535|port/i)
+ assert.throws(() => validateLauncherArgs({ bind: '127.0.0.1', port: -1 }), /port/i)
+ assert.throws(() => validateLauncherArgs({ bind: '127.0.0.1', port: '6769x' }), /port/i)
+ })
+
+ it('does not hardcode a host port claim: a configured port is only rejected by the kernel', () => {
+ // Any literal port is structurally valid; real occupancy is enforced at bind time.
+ assert.doesNotThrow(() => validateLauncherArgs({ bind: '127.0.0.1', port: 6768 }))
+ })
+
+ it('accepts a fully consistent readiness payload', () => {
+ assert.doesNotThrow(() => validateServerReadiness(READY, opts()))
+ })
+
+ it('rejects forged pid, wrong version, wrong ABI, dead daemon, and forged daemon pid', () => {
+ const forged = clone(READY)
+ forged.health.pid = 999999
+ assert.throws(() => validateServerReadiness(forged, opts()), /PID mismatch/i)
+
+ const old = clone(READY)
+ old.health.buildVersion = '0.0.0-orcad'
+ assert.throws(() => validateServerReadiness(old, opts()), /buildVersion mismatch/i)
+
+ const abi = clone(READY)
+ abi.health.nodeAbi = '127'
+ assert.throws(() => validateServerReadiness(abi, opts()), /ABI/i)
+
+ const down = clone(READY)
+ down.health.terminalDaemon.state = 'down'
+ assert.throws(() => validateServerReadiness(down, opts()), /daemon/i)
+
+ const noSelfTest = clone(READY)
+ noSelfTest.health.terminalDaemon.selfTest = { ok: false, verdict: 'failed' }
+ assert.throws(() => validateServerReadiness(noSelfTest, opts()), /selfTest/i)
+
+ const noDaemonPid = clone(READY)
+ noDaemonPid.health.terminalDaemon.pid = 0
+ assert.throws(() => validateServerReadiness(noDaemonPid, opts()), /daemon/i)
+ })
+
+ it('rejects endpoints that do not match the requested loopback bind and port', () => {
+ const wrongHost = clone(READY)
+ wrongHost.boundEndpoint = 'ws://10.0.0.5:6769'
+ assert.throws(() => validateServerReadiness(wrongHost, opts()), /bound endpoint/i)
+
+ const wrongPort = clone(READY)
+ wrongPort.boundEndpoint = 'ws://127.0.0.1:7777'
+ assert.throws(() => validateServerReadiness(wrongPort, opts()), /bound endpoint/i)
+
+ const advertisedMismatch = clone(READY)
+ advertisedMismatch.advertisedEndpoint = 'wss://other.example'
+ assert.throws(
+ () => validateServerReadiness(advertisedMismatch, opts({ advertisedEndpoint: 'wss://orca.example.ts.net' })),
+ /advertised endpoint/i
+ )
+
+ const plainLoopback = clone(READY)
+ plainLoopback.advertisedEndpoint = 'ws://127.0.0.1:6769'
+ assert.throws(() => validateServerReadiness(plainLoopback, opts({ allowLoopbackAdvertised: false })), /advertised endpoint/i)
+ assert.doesNotThrow(() => validateServerReadiness(plainLoopback, opts({ allowLoopbackAdvertised: true })))
+
+ const badRuntime = clone(READY)
+ badRuntime.runtimeId = ''
+ assert.throws(() => validateServerReadiness(badRuntime, opts()), /runtimeId/i)
+ })
+
+ it('redacts every bearer/pairing field from safe metadata', () => {
+ const redacted = redactServerReadiness(READY)
+ const serialized = JSON.stringify(redacted)
+ assert.equal(serialized.includes('SECRET'), false)
+ assert.equal(redacted.pairingAvailable, true)
+ assert.equal(redacted.serverPid, 12345)
+ assert.equal(redacted.daemonPid, 12346)
+ assert.equal(redacted.boundEndpoint, 'ws://127.0.0.1:6769')
+ assert.equal(redacted.version, '1.4.230')
+ })
+
+ it('builds a schema-1 identity receipt from the owned child, not from health alone', () => {
+ const receipt = createRuntimeIdentity({
+ readyPayload: READY,
+ serverIdentity: { pid: 12345, startTicks: '555' },
+ nodeBinary: '/slot/runtimes/node/bin/node',
+ serverEntry: '/slot/orcad-server.js',
+ userData: '/root/runtime/user-data',
+ boundEndpoint: 'ws://127.0.0.1:6769',
+ advertisedEndpoint: 'wss://orca.example.ts.net',
+ readyAt: '2026-10-19T00:00:00.000Z'
+ })
+ assert.deepEqual(Object.keys(receipt).sort(), [
+ 'advertisedEndpoint',
+ 'boundEndpoint',
+ 'nodeBinary',
+ 'readyAt',
+ 'runtimeId',
+ 'schemaVersion',
+ 'serverEntry',
+ 'serverPid',
+ 'serverStartTicks',
+ 'userData',
+ 'version'
+ ])
+ assert.equal(receipt.schemaVersion, 1)
+ assert.equal(receipt.serverPid, 12345)
+ assert.equal(receipt.serverStartTicks, '555')
+ assert.equal(receipt.version, '1.4.230')
+ })
+})
+
+describe('managed root publication safety', () => {
+ it('creates a 0700 owned root and refuses symlinked ancestors or loose modes', async () => {
+ const base = await mkdtemp(join(tmpdir(), 'orca-root-'))
+ const root = join(base, 'managed')
+ await ensureManagedRoot(root)
+ assert.equal((await stat(root)).mode & 0o777, 0o700)
+
+ const loose = join(base, 'loose')
+ await mkdir(loose, { mode: 0o755 })
+ await ensureManagedRoot(loose)
+ assert.equal((await stat(loose)).mode & 0o777, 0o700)
+
+ const link = join(base, 'link')
+ await symlink(root, link)
+ await assert.rejects(() => ensureManagedRoot(link), /symlink/i)
+
+ const nested = join(link, 'child')
+ await assert.rejects(() => ensureManagedRoot(nested), /symlink/i)
+
+ await rm(base, { recursive: true, force: true })
+ })
+
+ it('writes private files atomically at 0600 with no temp residue', async () => {
+ const base = await mkdtemp(join(tmpdir(), 'orca-write-'))
+ await ensureManagedRoot(base)
+ const file = join(base, 'private-status.json')
+ await writePrivateFile(file, { ok: true }, { root: base })
+ assert.equal((await stat(file)).mode & 0o777, 0o600)
+ assert.deepEqual(await readdir(base), ['private-status.json'])
+
+ await assert.rejects(() => writePrivateFile(join(base, '..', 'escape.json'), { ok: true }, { root: base }), /outside/i)
+
+ const linkTarget = join(base, 'target.json')
+ await writeFile(linkTarget, '{}', { mode: 0o600 })
+ const link = join(base, 'link.json')
+ await symlink(linkTarget, link)
+ await assert.rejects(() => writePrivateFile(link, { ok: true }, { root: base }), /symlink/i)
+ assert.deepEqual((await readdir(base)).sort(), ['link.json', 'private-status.json', 'target.json'])
+
+ await rm(base, { recursive: true, force: true })
+ })
+
+ it('parses daemon pid records and rejects garbage', () => {
+ assert.equal(parseDaemonPid('12345\n'), 12345)
+ assert.equal(parseDaemonPid(JSON.stringify({ pid: 54321 })), 54321)
+ assert.equal(parseDaemonPid(''), null)
+ assert.equal(parseDaemonPid('not-a-number'), null)
+ assert.equal(parseDaemonPid('0'), null)
+ })
+})
diff --git a/scripts/orca/lifecycle-release.mjs b/scripts/orca/lifecycle-release.mjs
new file mode 100644
index 00000000..e4e148ec
--- /dev/null
+++ b/scripts/orca/lifecycle-release.mjs
@@ -0,0 +1,54 @@
+/**
+ * MSO's release-preparation wrapper.
+ *
+ * There is exactly one acquisition path: the reviewed `preparePinnedRelease`
+ * API in release.mjs, which verifies the pinned .deb digest, extracts a
+ * data-only slot, pins Node, and publishes an immutable release. This wrapper
+ * adds only managed-root isolation and the SAME release-shape guard the install
+ * adapter uses; it deliberately has no `--template`/`--web` bypass, so
+ * production cannot be pointed at unreviewed upstream bytes.
+ */
+
+import { isAbsolute } from 'node:path'
+import { ensureIsolatedDirectories } from './env.mjs'
+import { assertPreparedRelease } from './managed-preflight.mjs'
+import { assertManagedRootFitsUnixSocket, resolveManagedRoot } from './managed-paths.mjs'
+import { preparePinnedRelease } from './release.mjs'
+
+/**
+ * @param allowDownload explicit opt-in. Default false: an already-installed
+ * release is reused after a full rehash and a missing one fails clearly
+ * instead of silently reaching the network.
+ */
+export async function prepareRelease({
+ managedRoot,
+ verifiedDebCache,
+ debPath,
+ allowDownload = false,
+ signal,
+ prepare = preparePinnedRelease
+} = {}) {
+ if (typeof managedRoot !== 'string' || !isAbsolute(managedRoot)) {
+ throw new Error('managedRoot must be an absolute path')
+ }
+ // Fail closed and IDENTICAL to the install adapter (managed-install.mjs):
+ // refuse a non-canonical, traversal, home, filesystem-root, or operator
+ // `.orca`/`.orca-remote` ORCA_HOME spelling, and refuse a root too deep for the
+ // runtime's Unix socket. Both checks run BEFORE ensureIsolatedDirectories, so a
+ // misconfigured root creates nothing.
+ const root = resolveManagedRoot({ env: { ORCA_HOME: managedRoot } })
+ assertManagedRootFitsUnixSocket(root)
+ await ensureIsolatedDirectories(root)
+ const verified = verifiedDebCache ?? debPath
+ const prepared = await prepare({
+ installRoot: root,
+ ...(verified ? { verifiedDebCache: verified } : {}),
+ allowDownload: allowDownload === true,
+ signal
+ })
+ // One guard, not two: this is the exact `assertPreparedRelease` the install
+ // adapter calls, so the CLI and the adapter cannot diverge on what a valid
+ // pinned release is (the previous local copy accepted a lexical
+ // `root/../foreign` releaseRoot that the shared guard rejects).
+ return assertPreparedRelease(prepared, root)
+}
diff --git a/scripts/orca/lifecycle-release.test.mjs b/scripts/orca/lifecycle-release.test.mjs
new file mode 100644
index 00000000..81d0da06
--- /dev/null
+++ b/scripts/orca/lifecycle-release.test.mjs
@@ -0,0 +1,81 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { lstat, mkdtemp, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { prepareRelease } from './lifecycle-release.mjs'
+import { getReleaseContentId, getReleaseIdentity } from './release-identity.mjs'
+
+const ID = getReleaseContentId()
+const NODE_REL = getReleaseIdentity().node.executablePath
+
+function shape(root, overrides = {}) {
+ const releaseRoot = join(root, 'releases', `1.4.230+${ID}`)
+ return {
+ releaseRoot,
+ slotDir: join(releaseRoot, 'slot'),
+ nodeBinary: join(releaseRoot, NODE_REL),
+ webDir: join(releaseRoot, 'web'),
+ receiptPath: join(releaseRoot, 'receipt.json'),
+ version: '1.4.230',
+ receipt: { release: { contentId: ID } },
+ ...overrides
+ }
+}
+
+async function base() {
+ const baseDir = await mkdtemp(join(tmpdir(), 'oi-'))
+ return { baseDir, root: join(baseDir, 'root'), cleanup: () => rm(baseDir, { recursive: true, force: true }) }
+}
+
+describe('prepareRelease shares the exact install-adapter release guard', () => {
+ it('accepts a canonical pinned release and rejects a lexical `root/../foreign` releaseRoot', async () => {
+ const d = await base()
+ try {
+ const release = shape(d.root)
+ const prepared = await prepareRelease({ managedRoot: d.root, prepare: async () => release })
+ assert.equal(prepared.releaseRoot, release.releaseRoot)
+
+ // The old local guard accepted this spelling; the shared guard does not.
+ await assert.rejects(
+ () =>
+ prepareRelease({
+ managedRoot: d.root,
+ prepare: async () => shape(d.root, { releaseRoot: `${d.root}/../foreign` })
+ }),
+ /immutable release root|not a canonical path/
+ )
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('fails closed on a dirty managed root and never creates it', async () => {
+ const d = await base()
+ try {
+ for (const dirty of ['relative/root', `${d.root}/`, `${d.root}/../evil`]) {
+ await assert.rejects(
+ () => prepareRelease({ managedRoot: dirty, prepare: async () => shape(d.root) }),
+ /managedRoot must be an absolute path|ORCA_HOME/
+ )
+ }
+ await assert.rejects(() => lstat(d.root), { code: 'ENOENT' })
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('refuses an over-deep root BEFORE creating anything', async () => {
+ const d = await base()
+ try {
+ const deep = join(d.baseDir, 'x'.repeat(120))
+ await assert.rejects(
+ () => prepareRelease({ managedRoot: deep, prepare: async () => shape(deep) }),
+ /too deep/
+ )
+ await assert.rejects(() => lstat(deep), { code: 'ENOENT' })
+ } finally {
+ await d.cleanup()
+ }
+ })
+})
diff --git a/scripts/orca/lifecycle-teardown.mjs b/scripts/orca/lifecycle-teardown.mjs
new file mode 100644
index 00000000..7d38fa01
--- /dev/null
+++ b/scripts/orca/lifecycle-teardown.mjs
@@ -0,0 +1,140 @@
+/**
+ * Retriable teardown for one owned Orca server/daemon pair. Discovery barriers
+ * are bounded, cleanup never claims a stale identity exited, and receipts are
+ * cleared only after the server is confirmed stopped.
+ */
+
+import { readProcessIdentity, terminateVerifiedProcess, verifyProcessIdentity } from './proc-identity.mjs'
+import { discoverOwnedDaemon } from './daemon-identity.mjs'
+import { clearPrivatePairIfMatch } from './private-store.mjs'
+
+const PRE_STOP_DISCOVERY_MS = 500
+const POST_STOP_DISCOVERY_MS = 3000
+const PRESERVE_DISCOVERY_MS = 1000
+
+export function createLifecycleTeardown({
+ root,
+ userData,
+ nodeBinary,
+ daemonEntryPath,
+ discoveryWaitMs,
+ getServerIdentity,
+ getReceiptPaths,
+ getExpectedIdentity
+}) {
+ let daemonIdentity = null
+ let stopPromise = null
+ let stopResult = null
+
+ const ownDaemonScan = (waitMs) =>
+ discoverOwnedDaemon({ userData, nodeBinary, daemonEntryPath, waitMs })
+
+ const cleanup = async () => {
+ const failures = []
+ const preDaemon =
+ daemonIdentity ?? (await ownDaemonScan(discoveryWaitMs ?? PRE_STOP_DISCOVERY_MS))
+ if (preDaemon) daemonIdentity = preDaemon
+ const serverIdentity = getServerIdentity()
+ if (serverIdentity) {
+ const result = await terminateVerifiedProcess(serverIdentity, { timeoutMs: 2000, killTimeoutMs: 3000 })
+ if (!result.exited && !result.stale) failures.push(`server ${serverIdentity.pid} did not exit`)
+ }
+ const daemon =
+ preDaemon ?? (await ownDaemonScan(Math.max(discoveryWaitMs ?? 0, POST_STOP_DISCOVERY_MS)))
+ if (daemon) {
+ daemonIdentity = daemon
+ const result = await terminateVerifiedProcess(daemon, { timeoutMs: 2000, killTimeoutMs: 3000 })
+ if (!result.exited && !result.stale) failures.push(`daemon ${daemon.pid} did not exit`)
+ }
+ return failures
+ }
+
+ const stop = (stopOptions = {}) => {
+ if (stopResult) return Promise.resolve(stopResult)
+ if (stopPromise) return stopPromise
+ const attempt = (async () => {
+ const { cleanDaemon = true, timeoutMs = 5000 } = stopOptions
+ const serverIdentity = getServerIdentity()
+ const preDaemon = cleanDaemon
+ ? daemonIdentity ?? (await ownDaemonScan(discoveryWaitMs ?? PRE_STOP_DISCOVERY_MS))
+ : null
+
+ const serverResult = await terminateVerifiedProcess(serverIdentity, {
+ timeoutMs,
+ killTimeoutMs: 3000
+ })
+ if (!serverResult.exited && !serverResult.stale) {
+ throw new Error(`stop failed: server ${serverIdentity.pid} is still alive`)
+ }
+
+ let daemonResult = { exited: false, stale: false, forced: false }
+ let daemonPreserved = null
+ let daemonKnown = Boolean(daemonIdentity || preDaemon)
+ let daemonCleanup = cleanDaemon ? 'unknown' : 'preserved'
+ if (cleanDaemon) {
+ const daemon =
+ preDaemon ?? (await ownDaemonScan(Math.max(discoveryWaitMs ?? 0, POST_STOP_DISCOVERY_MS)))
+ if (daemon) {
+ daemonIdentity = daemon
+ daemonKnown = true
+ daemonResult = await terminateVerifiedProcess(daemon, { timeoutMs, killTimeoutMs: 3000 })
+ if (!daemonResult.exited && !daemonResult.stale) {
+ throw new Error(`stop failed: daemon ${daemon.pid} is still alive`)
+ }
+ daemonCleanup = daemonResult.exited ? 'verified' : 'unknown'
+ }
+ } else {
+ const daemon = daemonIdentity ?? (await ownDaemonScan(PRESERVE_DISCOVERY_MS))
+ if (daemon) {
+ const actual = await readProcessIdentity(daemon.pid)
+ const alive = Boolean(actual && actual.state !== 'Z' && (await verifyProcessIdentity(actual, daemon)))
+ daemonPreserved = alive
+ daemonKnown = true
+ if (alive) daemonIdentity = daemon
+ } else {
+ daemonPreserved = 'unknown'
+ }
+ }
+
+ const { preserved } = await clearPrivatePairIfMatch({
+ root,
+ matches: getReceiptPaths().map((path) => ({
+ path,
+ predicate: getExpectedIdentity()
+ }))
+ })
+
+ return {
+ exited: true,
+ daemonExited: Boolean(cleanDaemon && daemonResult.exited),
+ daemonPreserved,
+ daemonKnown,
+ daemonCleanup,
+ forced: Boolean(serverResult.forced || daemonResult.forced),
+ receiptsCleared: true,
+ preservedReceipts: preserved
+ }
+ })()
+ const tracked = attempt.then(
+ (value) => {
+ stopResult = value
+ return value
+ },
+ (err) => {
+ stopPromise = null
+ throw err
+ }
+ )
+ stopPromise = tracked
+ return tracked
+ }
+
+ return {
+ cleanup,
+ stop,
+ getDaemonIdentity: () => daemonIdentity,
+ setDaemonIdentity: (identity) => {
+ daemonIdentity = identity
+ }
+ }
+}
diff --git a/scripts/orca/lifecycle-teardown.test.mjs b/scripts/orca/lifecycle-teardown.test.mjs
new file mode 100644
index 00000000..3af1f3ad
--- /dev/null
+++ b/scripts/orca/lifecycle-teardown.test.mjs
@@ -0,0 +1,115 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { terminateVerifiedProcess } from './proc-identity.mjs'
+import { launch, makeRoot, recordedDaemonPid, waitGone } from './lifecycle-test-helpers.mjs'
+
+describe('retriable lifecycle teardown and receipt ownership', () => {
+ it('preserves the daemon for a persistent run and only stops the server', async () => {
+ const root = await makeRoot()
+ const instance = await launch(root)
+ const daemonIdentity = { ...instance.daemonIdentity }
+ try {
+ const result = await instance.stop({ cleanDaemon: false, timeoutMs: 4000 })
+ assert.equal(result.exited, true)
+ assert.equal(result.daemonExited, false)
+ assert.equal(result.daemonPreserved, true)
+ assert.equal(await waitGone(instance.child.pid), true)
+ assert.equal(await waitGone(daemonIdentity.pid, 1000), false)
+ } finally {
+ await terminateVerifiedProcess(daemonIdentity, { timeoutMs: 3000 }).catch(() => {})
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('is idempotent and never signals a stale daemon identity', async () => {
+ const root = await makeRoot()
+ const instance = await launch(root)
+ const daemonIdentity = { ...instance.daemonIdentity }
+ try {
+ instance.daemonIdentity.startTicks = '1'
+ const result = await instance.stop({ cleanDaemon: true, timeoutMs: 1000 })
+ assert.equal(result.exited, true)
+ assert.equal(result.daemonExited, false)
+ assert.equal(result.daemonCleanup, 'unknown')
+ assert.equal(await waitGone(daemonIdentity.pid, 1000), false)
+
+ const again = await instance.stop({ cleanDaemon: true, timeoutMs: 1000 })
+ assert.equal(again.exited, true)
+ } finally {
+ await terminateVerifiedProcess(daemonIdentity, { timeoutMs: 3000 }).catch(() => {})
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('finds a delayed daemon record after an aborted startup', async () => {
+ const root = await makeRoot()
+ const controller = new AbortController()
+ try {
+ const pending = launch(root, {
+ signal: controller.signal,
+ env: {
+ FAKE_MODE: 'delayed-ready',
+ FAKE_READY_DELAY_MS: '5000',
+ FAKE_DAEMON_DELAY_MS: '1200'
+ }
+ })
+ const pidsFile = join(root, 'runtime', 'user-data', 'fake-pids.json')
+ const deadline = Date.now() + 4000
+ while (true) {
+ try {
+ await readFile(pidsFile, 'utf8')
+ break
+ } catch {
+ if (Date.now() >= deadline) throw new Error('fake daemon was not spawned')
+ await new Promise((resolve) => setTimeout(resolve, 25))
+ }
+ }
+ controller.abort(new Error('startup cancelled'))
+ await assert.rejects(pending, /cancelled/i)
+ const pids = JSON.parse(await readFile(pidsFile, 'utf8'))
+ assert.equal(await waitGone(pids.serverPid), true)
+ assert.equal(await waitGone(pids.daemonPid), true)
+ assert.ok(await recordedDaemonPid(root), 'delayed daemon record was never published')
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('keeps teardown retriable after a receipt-cleanup failure', async () => {
+ const root = await makeRoot()
+ const identityPath = join(root, 'runtime-identity.json')
+ const instance = await launch(root)
+ try {
+ await rm(identityPath)
+ await mkdir(identityPath, { mode: 0o700 })
+ await assert.rejects(() => instance.stop({ cleanDaemon: true, timeoutMs: 3000 }), /not a regular file/i)
+ await rm(identityPath, { recursive: true, force: true })
+ const retried = await instance.stop({ cleanDaemon: true, timeoutMs: 3000 })
+ assert.equal(retried.exited, true)
+ await assert.rejects(lstat(join(root, 'private-status.json')))
+ await assert.rejects(lstat(identityPath))
+ } finally {
+ await instance.stop({ cleanDaemon: true, timeoutMs: 2000 }).catch(() => {})
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('never clears a receipt replaced by another runtime', async () => {
+ const root = await makeRoot()
+ const identityPath = join(root, 'runtime-identity.json')
+ const instance = await launch(root)
+ try {
+ await writeFile(identityPath, JSON.stringify({ runtimeId: 'another-runtime', serverStartTicks: '1' }))
+ const result = await instance.stop({ cleanDaemon: true, timeoutMs: 3000 })
+ assert.equal(result.receiptsCleared, true)
+ assert.deepEqual(result.preservedReceipts, [identityPath])
+ await assert.rejects(lstat(join(root, 'private-status.json')))
+ assert.equal(JSON.parse(await readFile(identityPath, 'utf8')).runtimeId, 'another-runtime')
+ } finally {
+ await instance.stop({ cleanDaemon: true, timeoutMs: 2000 }).catch(() => {})
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/lifecycle-test-helpers.mjs b/scripts/orca/lifecycle-test-helpers.mjs
new file mode 100644
index 00000000..fefcfc78
--- /dev/null
+++ b/scripts/orca/lifecycle-test-helpers.mjs
@@ -0,0 +1,90 @@
+import { mkdtemp, readFile, readdir } from 'node:fs/promises'
+import { createServer } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { launchOrcadServer } from './lifecycle.mjs'
+import { ensureIsolatedDirectories, createIsolatedEnv } from './env.mjs'
+
+export const FIXTURES = fileURLToPath(new URL('./fixtures/', import.meta.url))
+export const FAKE_SERVER = join(FIXTURES, 'fake-orcad-server.mjs')
+export const DAEMON_ENTRY = join(FIXTURES, 'daemon-entry.js')
+export const NODE = process.execPath
+
+export function alive(pid) {
+ try {
+ process.kill(pid, 0)
+ return true
+ } catch {
+ return false
+ }
+}
+
+export async function waitGone(pid, timeoutMs = 4000) {
+ const start = Date.now()
+ while (Date.now() - start < timeoutMs) {
+ if (!alive(pid)) return true
+ await new Promise((r) => setTimeout(r, 50))
+ }
+ return !alive(pid)
+}
+
+export async function freePort() {
+ return new Promise((resolve, reject) => {
+ const server = createServer()
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', () => {
+ const { port } = server.address()
+ server.close(() => resolve(port))
+ })
+ })
+}
+
+export async function makeRoot() {
+ const root = await mkdtemp(join(tmpdir(), 'orca-lifecycle-'))
+ await ensureIsolatedDirectories(root)
+ return root
+}
+
+export async function launch(root, extra = {}) {
+ const port = extra.port ?? (await freePort())
+ const env = {
+ ...createIsolatedEnv({ scratchDir: root }),
+ FAKE_DAEMON_ENTRY: DAEMON_ENTRY,
+ FAKE_ADVERTISED: `ws://127.0.0.1:${port}`,
+ ...(extra.env || {})
+ }
+ return launchOrcadServer({
+ nodeBinary: NODE,
+ slotDir: FIXTURES,
+ serverEntry: FAKE_SERVER,
+ daemonEntryPath: DAEMON_ENTRY,
+ options: {
+ bind: '127.0.0.1',
+ port,
+ allowLoopbackAdvertised: true,
+ ...(extra.options || {})
+ },
+ env,
+ managedRoot: root,
+ privateStatusPath: extra.privateStatusPath ?? join(root, 'private-status.json'),
+ runtimeIdentityPath: extra.runtimeIdentityPath ?? join(root, 'runtime-identity.json'),
+ timeoutMs: extra.timeoutMs ?? extra.options?.timeoutMs ?? 5000,
+ signal: extra.signal
+ })
+}
+
+export async function recordedDaemonPid(root) {
+ const dir = join(root, 'runtime', 'user-data', 'daemon')
+ const files = await readdir(dir).catch(() => [])
+ const pidFile = files.find((f) => /^daemon-v\d+\.pid$/.test(f))
+ if (!pidFile) return null
+ const raw = await readFile(join(dir, pidFile), 'utf8')
+ let pid
+ try {
+ pid = JSON.parse(raw).pid
+ } catch {
+ pid = Number(raw.trim())
+ }
+ return Number.isInteger(pid) && pid > 1 ? pid : null
+}
diff --git a/scripts/orca/lifecycle.mjs b/scripts/orca/lifecycle.mjs
new file mode 100644
index 00000000..9f14736f
--- /dev/null
+++ b/scripts/orca/lifecycle.mjs
@@ -0,0 +1,170 @@
+/**
+ * Supervised Orca server lifecycle: spawn, bounded readiness, verified owned
+ * child/daemon identities, transactional receipts, and retriable teardown.
+ * Smoke cleans the task-owned daemon; a persistent run preserves it.
+ */
+
+import { spawn } from 'node:child_process'
+import { realpath } from 'node:fs/promises'
+import { join, resolve } from 'node:path'
+import {
+ createRuntimeIdentity,
+ redactServerReadiness,
+ sanitizeEndpoint,
+ validateLauncherArgs,
+ validateServerReadiness
+} from './launcher.mjs'
+import { createRollingTextSink } from './bounded-stream.mjs'
+import { waitForProcessIdentity } from './proc-identity.mjs'
+import { redactSensitiveText } from './bounded-proc.mjs'
+import { waitForDaemon } from './daemon-identity.mjs'
+import { waitForReadiness } from './readiness-wait.mjs'
+import { publishPrivatePair, writePrivateFile } from './private-store.mjs'
+import { createLifecycleTeardown } from './lifecycle-teardown.mjs'
+
+function delay(ms) {
+ return new Promise((resolveDelay) => setTimeout(resolveDelay, ms))
+}
+
+export async function launchOrcadServer({
+ nodeBinary,
+ slotDir,
+ serverEntry,
+ options = {},
+ env,
+ managedRoot,
+ timeoutMs = 30000,
+ privateStatusPath,
+ runtimeIdentityPath,
+ daemonEntryPath,
+ signal,
+ discoveryWaitMs
+}) {
+ validateLauncherArgs(options)
+ if (!nodeBinary || !slotDir) throw new Error('nodeBinary and slotDir are required')
+ if (!env?.ORCA_USER_DATA) throw new Error('isolated env with ORCA_USER_DATA is required')
+ const root = managedRoot ?? env.ORCA_MANAGED_ROOT
+ if (!root) throw new Error('managedRoot is required to publish private receipts')
+ if (signal?.aborted) throw new Error('startup cancelled before spawn')
+ const bind = options.bind ?? '127.0.0.1'
+ const port = options.port ?? 0
+ const entry = resolve(serverEntry ?? join(slotDir, 'orcad-server.js'))
+ const daemonEntry = resolve(daemonEntryPath ?? join(slotDir, 'daemon-entry.js'))
+ const userData = env.ORCA_USER_DATA
+ const args = [entry, '--bind', bind, '--port', String(port), '--json']
+ if (options.webClientRoot) args.push('--web-client-root', options.webClientRoot)
+ if (options.pairingAddress) args.push('--pairing-address', options.pairingAddress)
+
+ const serverExe = await realpath(nodeBinary).catch(() => nodeBinary)
+ if (signal?.aborted) throw new Error('startup cancelled before spawn')
+ const child = spawn(nodeBinary, args, { env, stdio: ['ignore', 'pipe', 'pipe'] })
+ const childExit = new Promise((resolveExit) => {
+ child.once('exit', (code, exitSignal) => resolveExit({ code, signal: exitSignal }))
+ })
+ const stderrSink = createRollingTextSink(child.stderr)
+ const receiptPaths = []
+ let stdoutReader = null
+ let serverIdentity = null
+ let daemonIdentity = null
+ let expectedIdentity = () => false
+ const teardown = createLifecycleTeardown({
+ root,
+ userData,
+ nodeBinary: serverExe,
+ daemonEntryPath: daemonEntry,
+ discoveryWaitMs,
+ getServerIdentity: () => serverIdentity,
+ getReceiptPaths: () => receiptPaths,
+ getExpectedIdentity: () => expectedIdentity
+ })
+
+ const cleanup = async () => {
+ stdoutReader?.detach()
+ if (!serverIdentity && child.pid && child.exitCode === null && child.signalCode === null) {
+ // Only signal the tracked ChildProcess handle, never a raw reusable PID.
+ try {
+ child.kill('SIGKILL')
+ } catch {}
+ await Promise.race([childExit, delay(3000)])
+ }
+ return teardown.cleanup()
+ }
+
+ try {
+ const ready = await waitForReadiness({ child, timeoutMs, stderrSink, signal })
+ stdoutReader = ready.reader
+ // Keep consuming stdout (discard) so a chatty server can never stall the pipe.
+ stdoutReader.discard()
+ const payload = ready.payload
+ validateServerReadiness(payload, {
+ expectedChildPid: child.pid,
+ bind,
+ port,
+ advertisedEndpoint: options.advertisedEndpoint,
+ allowLoopbackAdvertised: options.allowLoopbackAdvertised === true
+ })
+
+ serverIdentity = await waitForProcessIdentity(child.pid, {
+ exe: serverExe,
+ scriptPath: entry,
+ uid: process.getuid()
+ })
+ if (!serverIdentity) throw new Error('server child identity could not be verified against procfs')
+
+ daemonIdentity = await waitForDaemon(payload.health.terminalDaemon.pid, {
+ nodeBinary: serverExe,
+ daemonEntryPath: daemonEntry,
+ userData
+ })
+ if (!daemonIdentity) throw new Error('daemon identity could not be verified against procfs')
+ teardown.setDaemonIdentity(daemonIdentity)
+
+ const identity = createRuntimeIdentity({
+ readyPayload: payload,
+ serverIdentity,
+ nodeBinary: serverExe,
+ serverEntry: entry,
+ userData,
+ boundEndpoint: payload.boundEndpoint ?? payload.endpoint,
+ advertisedEndpoint: sanitizeEndpoint(payload.advertisedEndpoint) ?? payload.advertisedEndpoint
+ })
+ const entries = []
+ if (privateStatusPath) {
+ receiptPaths.push(privateStatusPath)
+ entries.push({ path: privateStatusPath, data: payload })
+ }
+ if (runtimeIdentityPath) {
+ receiptPaths.push(runtimeIdentityPath)
+ entries.push({ path: runtimeIdentityPath, data: identity })
+ }
+ if (entries.length === 1) await writePrivateFile(entries[0].path, entries[0].data, { root })
+ else if (entries.length > 1) await publishPrivatePair({ root, entries })
+
+ expectedIdentity = (receipt) => {
+ if (receipt?.runtimeId !== payload.runtimeId) return false
+ if (receipt.serverStartTicks !== undefined) {
+ return String(receipt.serverStartTicks) === String(serverIdentity.startTicks)
+ }
+ return receipt?.health?.pid === serverIdentity.pid
+ }
+
+ return {
+ child,
+ childExit,
+ readyPayload: payload,
+ redacted: redactServerReadiness(payload),
+ identity,
+ serverIdentity,
+ daemonIdentity: teardown.getDaemonIdentity(),
+ stop: teardown.stop
+ }
+ } catch (err) {
+ const failures = await cleanup()
+ const suffix = failures.length > 0 ? `; cleanup failures: ${failures.join(', ')}` : ''
+ throw new Error(`${redactSensitiveText(err.message)}${suffix}`)
+ } finally {
+ stderrSink.detach()
+ // Keep stdout flowing until the child exits; stop() detaches explicitly.
+ if (child.exitCode !== null || child.signalCode !== null) child.stdout.resume()
+ }
+}
diff --git a/scripts/orca/lifecycle.test.mjs b/scripts/orca/lifecycle.test.mjs
new file mode 100644
index 00000000..6e2b84ea
--- /dev/null
+++ b/scripts/orca/lifecycle.test.mjs
@@ -0,0 +1,114 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'
+import { realpath } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { readProcessIdentity } from './proc-identity.mjs'
+import { DAEMON_ENTRY, NODE, launch, makeRoot, recordedDaemonPid, waitGone } from './lifecycle-test-helpers.mjs'
+
+describe('supervised launch, owned identity, and scoped teardown', () => {
+ it('launches a real child, publishes private receipts, and stops both owned processes', async () => {
+ const root = await makeRoot()
+ const instance = await launch(root)
+ try {
+ const serverIdentity = await readProcessIdentity(instance.child.pid)
+ assert.ok(serverIdentity)
+ assert.equal(instance.identity.serverPid, instance.child.pid)
+ assert.equal(instance.identity.serverStartTicks, serverIdentity.startTicks)
+ assert.equal(instance.identity.version, '1.4.230')
+ assert.equal(instance.identity.nodeBinary, await realpath(NODE))
+
+ assert.equal((await stat(join(root, 'private-status.json'))).mode & 0o777, 0o600)
+ assert.equal((await stat(join(root, 'runtime-identity.json'))).mode & 0o777, 0o600)
+ assert.equal((await readFile(join(root, 'runtime-identity.json'), 'utf8')).includes('SECRET'), false)
+
+ assert.ok(instance.daemonIdentity)
+ assert.equal(instance.daemonIdentity.uid, process.getuid())
+ assert.ok(instance.daemonIdentity.argv.includes(DAEMON_ENTRY))
+ assert.ok(instance.daemonIdentity.argv.some((a) => a.endsWith('daemon-v49.sock')))
+
+ const daemonPid = instance.daemonIdentity.pid
+ const result = await instance.stop({ cleanDaemon: true, timeoutMs: 4000 })
+ assert.equal(result.exited, true)
+ assert.equal(result.daemonExited, true)
+ assert.equal(await waitGone(instance.child.pid), true)
+ assert.equal(await waitGone(daemonPid), true)
+ } finally {
+ await instance.stop({ cleanDaemon: true, timeoutMs: 2000 }).catch(() => {})
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('reaps child and daemon on every failed-readiness path', async () => {
+ const cases = [
+ { env: { FAKE_MODE: 'forged-pid' }, match: /PID mismatch/i },
+ { env: { FAKE_MODE: 'wrong-version' }, match: /buildVersion mismatch/i },
+ { env: { FAKE_MODE: 'daemon-down' }, match: /daemon/i },
+ { env: { FAKE_MODE: 'bad-endpoint' }, match: /advertised endpoint/i, options: { advertisedEndpoint: 'wss://orca.example.ts.net' } },
+ { env: { FAKE_MODE: 'daemon-forged-pid' }, match: /daemon identity/i },
+ { env: { FAKE_MODE: 'exit' }, match: /exited prematurely/i },
+ { env: { FAKE_MODE: 'silent' }, match: /timed out/i, timeoutMs: 400 }
+ ]
+ for (const testCase of cases) {
+ const root = await makeRoot()
+ try {
+ const before = Date.now()
+ await assert.rejects(() => launch(root, testCase), testCase.match)
+ assert.ok(Date.now() - before < 15000, 'failure path did not settle promptly')
+ const daemonPid = await recordedDaemonPid(root)
+ if (daemonPid) {
+ assert.equal(await waitGone(daemonPid), true, `daemon ${daemonPid} survived ${testCase.env.FAKE_MODE}`)
+ }
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ }
+ })
+
+ it('cleans up when the private receipt write is rejected outside the managed root', async () => {
+ const root = await makeRoot()
+ const outside = await mkdtemp(join(tmpdir(), 'orca-outside-'))
+ try {
+ await assert.rejects(
+ () => launch(root, { privateStatusPath: join(outside, 'status.json') }),
+ /outside/i
+ )
+ const daemonPid = await recordedDaemonPid(root)
+ if (daemonPid) assert.equal(await waitGone(daemonPid), true)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ await rm(outside, { recursive: true, force: true })
+ }
+ })
+
+ it('keeps draining capped stdout after readiness instead of stalling', async () => {
+ const root = await makeRoot()
+ const instance = await launch(root, { env: { FAKE_MODE: 'stdout-flood' } })
+ try {
+ await new Promise((r) => setTimeout(r, 300))
+ const result = await instance.stop({ cleanDaemon: true, timeoutMs: 4000 })
+ assert.equal(result.exited, true)
+ assert.equal(result.daemonExited, true)
+ } finally {
+ await instance.stop({ cleanDaemon: true, timeoutMs: 2000 }).catch(() => {})
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('caps stderr and never leaks pairing material in the failure message', async () => {
+ const root = await makeRoot()
+ try {
+ await assert.rejects(
+ () => launch(root, { env: { FAKE_MODE: 'stderr-flood' }, timeoutMs: 700 }),
+ (err) => {
+ assert.equal(err.message.length < 20000, true, 'error message is unbounded')
+ assert.equal(err.message.includes('SECRET_PAIRING_CODE'), false)
+ return /timed out|stderr|exited/i.test(err.message)
+ }
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/managed-app-orca.mjs b/scripts/orca/managed-app-orca.mjs
new file mode 100755
index 00000000..69267aaf
--- /dev/null
+++ b/scripts/orca/managed-app-orca.mjs
@@ -0,0 +1,136 @@
+#!/usr/bin/env node
+/**
+ * Reviewed lifecycle adapter for the MSO-owned Orca web runtime.
+ *
+ * Fixed grammar only: `--version`, `status [--json]`, `check [--json]`,
+ * `install [--dry-run]`, `update`, `uninstall`. No arbitrary request value ever
+ * becomes part of the service argv. Update/uninstall/rollback deliberately fail
+ * closed rather than pretend to be implemented.
+ */
+
+import { ORCA_VERSION } from './constants.mjs'
+import { redactSensitiveText } from './bounded-proc.mjs'
+import { installManagedOrca, toWssEndpoint } from './managed-install.mjs'
+import { resolveManagedRoot, SERVICE_NAME } from './managed-paths.mjs'
+import { readInstalledOrcaRelease } from './managed-receipt.mjs'
+import { readManagedOrcaStatus } from './managed-status.mjs'
+
+const USAGE = `usage: managed-app-orca <command>
+
+Commands:
+ --version Print ${ORCA_VERSION} only when a verified managed release is installed.
+ status [--json] Safe local status; never includes pairing material.
+ check [--json] Update probe; Orca updates are not implemented yet.
+ install [--dry-run] Install the pinned Orca web runtime and ${SERVICE_NAME}.
+ update --yes Not implemented; fails closed.
+ uninstall --yes Not implemented; fails closed.
+`
+
+function fail(message, code) {
+ process.stderr.write(`${redactSensitiveText(String(message))}\n`)
+ process.exitCode = code
+}
+
+function printLine(text) {
+ process.stdout.write(`${text}\n`)
+}
+
+async function commandVersion() {
+ const release = await readInstalledOrcaRelease()
+ if (!release.installed) {
+ fail(`orca is not installed (${release.reason})`, 1)
+ return
+ }
+ printLine(release.version)
+}
+
+async function commandStatus(rest) {
+ const status = await readManagedOrcaStatus()
+ if (rest.includes('--json')) {
+ printLine(JSON.stringify(status))
+ return
+ }
+ if (!status.available) {
+ printLine(`not ready: ${status.reason}`)
+ return
+ }
+ printLine(`${status.version} ready on ${status.boundEndpoint} (advertised ${status.advertisedEndpoint})`)
+}
+
+async function commandCheck(rest) {
+ const release = await readInstalledOrcaRelease()
+ if (!release.installed) {
+ fail(`orca is not installed (${release.reason})`, 1)
+ return
+ }
+ const payload = {
+ currentVersion: release.version,
+ latestVersion: ORCA_VERSION,
+ hasUpdate: false,
+ updateSupported: false
+ }
+ printLine(rest.includes('--json') ? JSON.stringify(payload) : `current ${release.version}; updates not implemented`)
+}
+
+async function commandInstall(rest) {
+ const unknown = rest.filter((arg) => arg !== '--dry-run')
+ if (unknown.length) {
+ fail(`unsupported install option: ${unknown[0]}`, 2)
+ return
+ }
+ const bind = process.env.MSO_INSTALL_GATEWAY_BIND || 'loopback'
+ if (bind !== 'loopback') {
+ fail(`Orca install supports loopback only; refusing bind mode '${bind}'`, 2)
+ return
+ }
+ let advertised
+ try {
+ advertised = toWssEndpoint(process.env.MSO_INSTALL_APP_ORIGIN)
+ } catch (err) {
+ fail(err.message, 2)
+ return
+ }
+ const dryRun = rest.includes('--dry-run')
+ const result = await installManagedOrca({ advertisedEndpoint: advertised, dryRun })
+ const root = resolveManagedRoot()
+ if (dryRun) {
+ printLine(`==> dry run: would install Orca ${ORCA_VERSION} into ${root}`)
+ printLine(`==> dry run: would write ${result.unitPath} and start ${SERVICE_NAME}`)
+ return
+ }
+ printLine(`==> Orca ${ORCA_VERSION} ready on ${result.boundEndpoint} (advertised ${result.advertisedEndpoint})`)
+ printLine(`==> managed by ${SERVICE_NAME}; root ${root}`)
+}
+
+async function main(argv) {
+ const command = argv[2] ?? ''
+ const rest = argv.slice(3)
+ switch (command) {
+ case '--version':
+ return commandVersion()
+ case 'status':
+ return commandStatus(rest)
+ case 'check':
+ return commandCheck(rest)
+ case 'install':
+ return commandInstall(rest)
+ case 'update':
+ fail('orca update is not implemented; no change was made', 1)
+ return
+ case 'uninstall':
+ return rest[0] === '--help'
+ ? void printLine(USAGE.trimEnd())
+ : fail('orca uninstall is not implemented; no change was made', 1)
+ default:
+ fail(USAGE.trimEnd(), 2)
+ }
+}
+
+if (process.argv[1] && process.argv[1].endsWith('managed-app-orca.mjs')) {
+ main(process.argv).catch((err) => {
+ process.stderr.write(`${redactSensitiveText(err?.message ?? 'orca adapter failed')}\n`)
+ process.exitCode = 1
+ })
+}
+
+export { main }
diff --git a/scripts/orca/managed-app-orca.test.mjs b/scripts/orca/managed-app-orca.test.mjs
new file mode 100644
index 00000000..732369f7
--- /dev/null
+++ b/scripts/orca/managed-app-orca.test.mjs
@@ -0,0 +1,144 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import { chmod, mkdir, mkdtemp, rm } from 'node:fs/promises'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { installReceiptPath } from './managed-paths.mjs'
+import { writePrivateFile } from './private-store.mjs'
+import { readInstalledOrcaRelease } from './managed-receipt.mjs'
+import { getReleaseContentId } from './release-identity.mjs'
+
+const WRAPPER = fileURLToPath(new URL('../managed-app-orca', import.meta.url))
+const SCRATCH = '/home/antinrml/.hermes/cache/scratch/opencode'
+
+function adapter(args, env = {}) {
+ return spawnSync(WRAPPER, args, {
+ encoding: 'utf8',
+ env: { ...process.env, ...env },
+ timeout: 30_000
+ })
+}
+
+async function makeDirs() {
+ const base = await mkdtemp(`${SCRATCH}/orca-adapter-`)
+ const root = join(base, 'orca')
+ const home = join(base, 'home')
+ await mkdir(home, { recursive: true, mode: 0o700 })
+ await chmod(WRAPPER, 0o755)
+ return { base, root, home, env: { ORCA_HOME: root, HOME: home }, cleanup: () => rm(base, { recursive: true, force: true }) }
+}
+
+describe('managed-app-orca adapter grammar', () => {
+ it('reports not installed rather than a pinned version from wrapper presence alone', async () => {
+ const d = await makeDirs()
+ try {
+ const result = adapter(['--version'], d.env)
+ assert.equal(result.status, 1)
+ assert.match(result.stderr, /not installed/)
+ assert.equal(result.stdout.trim(), '')
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('renders an install dry run without pairing material or a browser-dependent surprise', async () => {
+ const d = await makeDirs()
+ try {
+ const result = adapter(['install', '--dry-run'], {
+ ...d.env,
+ MSO_INSTALL_GATEWAY_BIND: 'loopback',
+ MSO_INSTALL_APP_ORIGIN: 'https://orca.mso.example.com'
+ })
+ assert.equal(result.status, 0, result.stderr)
+ assert.match(result.stdout, /dry run/)
+ assert.match(result.stdout, /mso-orca\.service/)
+ assert.equal(/pairing|token|ticket|secret/i.test(result.stdout), false)
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('refuses non-loopback binds and a missing split origin explicitly', async () => {
+ const d = await makeDirs()
+ try {
+ const lan = adapter(['install'], { ...d.env, MSO_INSTALL_GATEWAY_BIND: 'lan', MSO_INSTALL_APP_ORIGIN: 'https://orca.mso.example.com' })
+ assert.equal(lan.status, 2)
+ assert.match(lan.stderr, /loopback only/)
+
+ const noOrigin = adapter(['install'], { ...d.env, MSO_INSTALL_APP_ORIGIN: '' })
+ assert.equal(noOrigin.status, 2)
+ assert.match(noOrigin.stderr, /MSO_INSTALL_APP_ORIGIN/)
+
+ const unknown = adapter(['install', '--force'], { ...d.env, MSO_INSTALL_APP_ORIGIN: 'https://orca.mso.example.com' })
+ assert.equal(unknown.status, 2)
+ assert.match(unknown.stderr, /unsupported install option/)
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('fails update and uninstall closed, but keeps uninstall --help', async () => {
+ const d = await makeDirs()
+ try {
+ const update = adapter(['update', '--yes'], d.env)
+ assert.equal(update.status, 1)
+ assert.match(update.stderr, /not implemented/)
+
+ const uninstall = adapter(['uninstall', '--yes'], d.env)
+ assert.equal(uninstall.status, 1)
+ assert.match(uninstall.stderr, /not implemented/)
+
+ const help = adapter(['uninstall', '--help'], d.env)
+ assert.equal(help.status, 0)
+ assert.match(help.stdout, /uninstall/)
+
+ const usage = adapter([], d.env)
+ assert.equal(usage.status, 2)
+ assert.match(usage.stderr, /usage: managed-app-orca/)
+ } finally {
+ await d.cleanup()
+ }
+ })
+})
+
+describe('installed release receipt gate', () => {
+ const identity = { release: { contentId: getReleaseContentId() } }
+
+ it('requires a private receipt and a still-verifying release root', async () => {
+ const d = await makeDirs()
+ try {
+ assert.equal((await readInstalledOrcaRelease({ managedRoot: d.root })).reason, 'not_installed')
+ const releaseRoot = join(d.root, 'releases', 'r')
+ await writePrivateFile(installReceiptPath(d.root), {
+ schemaVersion: 1,
+ applicationId: 'orca',
+ version: '1.4.230',
+ releaseRoot,
+ releaseContentId: getReleaseContentId(),
+ runtimeId: 'rt'
+ }, { root: d.root })
+
+ const good = await readInstalledOrcaRelease({
+ managedRoot: d.root,
+ verify: async () => ({ version: '1.4.230', releaseRoot, receipt: identity })
+ })
+ assert.equal(good.installed, true)
+ assert.equal(good.version, '1.4.230')
+
+ const tampered = await readInstalledOrcaRelease({
+ managedRoot: d.root,
+ verify: async () => { throw new Error('rehash failed') }
+ })
+ assert.equal(tampered.reason, 'installed_release_failed_verification')
+
+ await writePrivateFile(installReceiptPath(d.root), {
+ schemaVersion: 1, applicationId: 'orca', version: '1.4.230',
+ releaseRoot: '/etc', releaseContentId: getReleaseContentId()
+ }, { root: d.root })
+ assert.equal((await readInstalledOrcaRelease({ managedRoot: d.root })).reason, 'install_receipt_outside_root')
+ } finally {
+ await d.cleanup()
+ }
+ })
+})
diff --git a/scripts/orca/managed-config.mjs b/scripts/orca/managed-config.mjs
new file mode 100644
index 00000000..54cf10e5
--- /dev/null
+++ b/scripts/orca/managed-config.mjs
@@ -0,0 +1,71 @@
+/**
+ * Shape builders for the MSO-owned Orca service config and install receipt.
+ *
+ * Extracted from managed-install.mjs so the install SEQUENCE stays reviewable and
+ * the file stays within the repository's 220-line architecture limit. These are
+ * pure object builders: no filesystem, no systemd, no secrets.
+ */
+
+import { ORCA_VERSION } from './constants.mjs'
+import {
+ MANAGED_APP_ID,
+ UNIT_IDENTITY_MARKER,
+ serviceConfigPath
+} from './managed-paths.mjs'
+
+export function buildPlannedConfig({ root, unitPath, fixedPort, advertised }) {
+ return {
+ schemaVersion: 1,
+ applicationId: MANAGED_APP_ID,
+ version: ORCA_VERSION,
+ unitIdentity: UNIT_IDENTITY_MARKER,
+ boundEndpoint: `ws://127.0.0.1:${fixedPort}`,
+ advertisedEndpoint: advertised,
+ port: fixedPort,
+ managedRoot: root,
+ unitPath
+ }
+}
+
+export function buildServiceConfig({ plannedConfig, prepared, installedAt, hostNode, cliScript }) {
+ if (typeof hostNode !== 'string' || hostNode.length === 0) {
+ throw new Error('managed service config requires the exact launcher hostNode')
+ }
+ if (typeof cliScript !== 'string' || cliScript.length === 0) {
+ throw new Error('managed service config requires the canonical cliScript')
+ }
+ return {
+ ...plannedConfig,
+ // The consumer must be able to reproduce the exact ExecStart. Persist the
+ // launcher host node (NOT release.nodeBinary, the pinned child runtime) and
+ // the canonical CLI the installer actually rendered.
+ hostNode,
+ cliScript,
+ release: {
+ releaseRoot: prepared.releaseRoot,
+ slotDir: prepared.slotDir,
+ webDir: prepared.webDir,
+ nodeBinary: prepared.nodeBinary,
+ receiptPath: prepared.receiptPath,
+ contentId: prepared.receipt.release.contentId
+ },
+ installedAt
+ }
+}
+
+export function buildInstallReceipt({ root, config, unitPath, advertised, ready, readyAt }) {
+ return {
+ schemaVersion: 1,
+ applicationId: MANAGED_APP_ID,
+ version: ORCA_VERSION,
+ runtimeId: ready.runtimeId,
+ releaseRoot: config.release.releaseRoot,
+ releaseContentId: config.release.contentId,
+ boundEndpoint: config.boundEndpoint,
+ advertisedEndpoint: advertised,
+ unitPath,
+ serviceConfig: serviceConfigPath(root),
+ installedAt: config.installedAt,
+ readyAt
+ }
+}
diff --git a/scripts/orca/managed-install.mjs b/scripts/orca/managed-install.mjs
new file mode 100644
index 00000000..1e8f8ead
--- /dev/null
+++ b/scripts/orca/managed-install.mjs
@@ -0,0 +1,188 @@
+/**
+ * Actual install adapter for the MSO-owned Orca web runtime.
+ *
+ * Sequence: validate the configured split origin -> refuse a foreign unit ->
+ * verify the systemd user bus -> verify the fixed loopback port -> acquire and
+ * rehash the pinned release -> write a private service config and a fixed-argv
+ * user unit -> start only `mso-orca.service` -> require live process identity,
+ * readiness on the configured WSS endpoint, and the static web bundle before
+ * writing the install receipt.
+ *
+ * No apt, root, loginctl, firewall, DNS, public-access or credential change is
+ * performed. The operator's existing Orca state and port 6768 are never read,
+ * reused or signalled.
+ */
+
+import { isAbsolute } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { DEFAULT_PORT } from './constants.mjs'
+import { ensureIsolatedDirectories } from './env.mjs'
+import { buildInstallReceipt, buildPlannedConfig, buildServiceConfig } from './managed-config.mjs'
+import {
+ assertPreparedRelease,
+ assertPortFree,
+ assertUserSystemdBus,
+ defaultUserBusEnvironment,
+ toWssEndpoint
+} from './managed-preflight.mjs'
+import {
+ INSTALL_RECEIPT_FILENAME,
+ SERVICE_CONFIG_FILENAME,
+ SERVICE_NAME,
+ assertManagedRootFitsUnixSocket,
+ installReceiptPath,
+ orcaServiceUnitPath,
+ resolveManagedRoot,
+ serviceConfigPath
+} from './managed-paths.mjs'
+import { probeOrcaWebClient, readManagedOrcaStatus } from './managed-status.mjs'
+import {
+ assertNoPartialInstall,
+ capturePriorManagedState,
+ rollbackFirstInstall,
+ writePartialInstall
+} from './managed-rollback.mjs'
+import { defaultSystemctl, sleep, waitForReady, writeUnitAtomic } from './managed-unit-write.mjs'
+import { writePrivateFile } from './private-store.mjs'
+import { preparePinnedRelease } from './release.mjs'
+import { assertConfiguredAdvertisedEndpoint, assertPersistentPort } from './supervision.mjs'
+import { inspectExistingUnit, renderOrcaServiceUnit } from './systemd-unit.mjs'
+
+const DEFAULT_CLI_SCRIPT = fileURLToPath(new URL('./cli.mjs', import.meta.url))
+const CONTROL = /[\0\r\n]/
+
+export async function installManagedOrca({
+ managedRoot,
+ env = process.env,
+ home = env.HOME,
+ port = DEFAULT_PORT,
+ advertisedEndpoint,
+ allowDownload = true,
+ verifiedDebCache,
+ dryRun = false,
+ hostNode = process.execPath,
+ cliScript = DEFAULT_CLI_SCRIPT,
+ prepare = preparePinnedRelease,
+ userBus = defaultUserBusEnvironment,
+ portProbe = assertPortFree,
+ systemctl = defaultSystemctl,
+ writePrivate = writePrivateFile,
+ readStatus = readManagedOrcaStatus,
+ probeWeb = probeOrcaWebClient,
+ wait = sleep,
+ timeoutMs = 90_000,
+ pollMs = 2_000,
+ now = () => new Date().toISOString(),
+ signal
+} = {}) {
+ const root = managedRoot
+ ? resolveManagedRoot({ env: { ...env, ORCA_HOME: managedRoot }, home })
+ : resolveManagedRoot({ env, home })
+ const fixedPort = assertPersistentPort(port)
+ const advertised = assertConfiguredAdvertisedEndpoint(advertisedEndpoint)
+ const unitPath = orcaServiceUnitPath({ home })
+ const unit = renderOrcaServiceUnit({
+ hostNode,
+ cliScript,
+ managedRoot: root,
+ port: fixedPort,
+ advertisedEndpoint: advertised
+ })
+ const existing = await inspectExistingUnit({ unitPath, expectedUnit: unit })
+ const plannedConfig = buildPlannedConfig({ root, unitPath, fixedPort, advertised })
+
+ if (dryRun) {
+ return { dryRun: true, managedRoot: root, unitPath, unit, config: plannedConfig, existingUnit: existing.state }
+ }
+
+ if (CONTROL.test(env?.HOME ?? '') || (env?.HOME && !isAbsolute(env.HOME))) {
+ throw new Error('HOME must be an absolute path without control characters')
+ }
+
+ // A previous attempt that could not roll back left an explicit marker. Never
+ // adopt a half-installed service: refuse and name what to inspect first.
+ await assertNoPartialInstall(root)
+
+ assertManagedRootFitsUnixSocket(root)
+ const bus = await assertUserSystemdBus({ env, probe: userBus })
+ await portProbe({ port: fixedPort, host: '127.0.0.1' })
+ await ensureIsolatedDirectories(root)
+
+ const prepared = assertPreparedRelease(
+ await prepare({
+ installRoot: root,
+ ...(verifiedDebCache ? { verifiedDebCache } : {}),
+ allowDownload,
+ signal
+ }),
+ root
+ )
+ const config = buildServiceConfig({ plannedConfig, prepared, installedAt: now(), hostNode, cliScript })
+
+ // Capture the prior owned state before we touch anything so a failed first
+ // install can be rolled back to it (or to nothing) instead of leaving a
+ // half-installed, restarting service behind.
+ const prior = await capturePriorManagedState({ root, unitState: existing.state, unitText: existing.text })
+ const created = { config: false, unit: false, receipt: false }
+
+ try {
+ // Private config first: it contains no pairing material and is the only
+ // non-unit file the runtime needs to identify its release.
+ await writePrivate(serviceConfigPath(root), config, { root })
+ created.config = true
+ await writeUnitAtomic(unitPath, unit)
+ created.unit = true
+
+ await systemctl({ args: ['daemon-reload'], env, bus })
+ await systemctl({ args: ['enable', '--now', SERVICE_NAME], env, bus })
+
+ const ready = await waitForReady({
+ root,
+ port: fixedPort,
+ advertisedEndpoint: advertised,
+ timeoutMs,
+ pollMs,
+ readStatus,
+ probeWeb,
+ wait
+ })
+ const receipt = buildInstallReceipt({
+ root,
+ config,
+ unitPath,
+ advertised,
+ ready,
+ readyAt: ready.readyAt ?? now()
+ })
+ await writePrivate(installReceiptPath(root), receipt, { root })
+ created.receipt = true
+
+ return {
+ dryRun: false,
+ managedRoot: root,
+ unitPath,
+ unit,
+ config,
+ receipt,
+ runtimeId: ready.runtimeId,
+ boundEndpoint: ready.boundEndpoint,
+ advertisedEndpoint: ready.advertisedEndpoint
+ }
+ } catch (err) {
+ // Bounded owned rollback. If it cannot finish cleanly, record an explicit
+ // partial-install marker so a rerun refuses instead of adopting a half state.
+ const outcome = await rollbackFirstInstall({ root, unitPath, prior, created, unitText: unit, systemctl, env, bus })
+ if (!outcome.complete) {
+ await writePartialInstall(root, {
+ reason: err?.message ?? String(err),
+ failures: outcome.failures,
+ now
+ }).catch(() => {})
+ }
+ throw err
+ }
+}
+
+// Re-exported so existing callers/tests keep one import point.
+export { assertPortFree, assertUserSystemdBus, toWssEndpoint }
+export { INSTALL_RECEIPT_FILENAME, SERVICE_CONFIG_FILENAME, SERVICE_NAME }
diff --git a/scripts/orca/managed-install.test.mjs b/scripts/orca/managed-install.test.mjs
new file mode 100644
index 00000000..1d0297db
--- /dev/null
+++ b/scripts/orca/managed-install.test.mjs
@@ -0,0 +1,226 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { getReleaseContentId, getReleaseIdentity } from './release-identity.mjs'
+import {
+ assertPortFree,
+ installManagedOrca,
+ toWssEndpoint
+} from './managed-install.mjs'
+import { orcaServiceUnitPath, UNIT_IDENTITY_MARKER } from './managed-paths.mjs'
+
+const RELEASE_ID = getReleaseContentId()
+const NODE_REL = getReleaseIdentity().node.executablePath
+async function makeDirs() {
+ // Short root: the runtime's Unix socket path is capped at 108 bytes on Linux.
+ const base = await mkdtemp(join(tmpdir(), 'oi-'))
+ const root = join(base, 'root')
+ const home = join(base, 'home')
+ await mkdir(home, { recursive: true, mode: 0o700 })
+ return { base, root, home, cleanup: () => rm(base, { recursive: true, force: true }) }
+}
+
+function fakeRelease(root) {
+ const releaseRoot = join(root, 'releases', `1.4.230+${RELEASE_ID}`)
+ return {
+ releaseRoot,
+ slotDir: join(releaseRoot, 'slot'),
+ nodeBinary: join(releaseRoot, NODE_REL),
+ webDir: join(releaseRoot, 'web'),
+ receiptPath: join(releaseRoot, 'receipt.json'),
+ version: '1.4.230',
+ receipt: { release: { contentId: RELEASE_ID } }
+ }
+}
+
+const status = {
+ available: true,
+ runtimeId: 'runtime-fixture',
+ boundEndpoint: 'ws://127.0.0.1:6769',
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ readyAt: '2026-10-19T10:00:00.000Z'
+}
+const web = { available: true, url: 'http://127.0.0.1:6769/web-index.html', status: 200 }
+
+describe('Orca split-origin endpoint derivation', () => {
+ it('maps the configured app origin to WSS and refuses same-origin/loopback fallbacks', () => {
+ assert.equal(toWssEndpoint('https://orca.mso.example.com'), 'wss://orca.mso.example.com')
+ assert.throws(() => toWssEndpoint(''), /MSO_INSTALL_APP_ORIGIN/)
+ assert.throws(() => toWssEndpoint('https://127.0.0.1:6769'), /loopback/i)
+ assert.throws(() => toWssEndpoint('https://orca.example.com/?token=x'), /credentials|query/i)
+ assert.throws(() => toWssEndpoint('wss://orca.example.com'), /http/i)
+ })
+})
+
+describe('managed Orca install adapter', () => {
+ it('renders a complete dry-run without downloading, writing, or starting anything', async () => {
+ const d = await makeDirs()
+ try {
+ let prepared = 0
+ const result = await installManagedOrca({
+ managedRoot: d.root,
+ home: d.home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ dryRun: true,
+ prepare: async () => { prepared += 1 }
+ })
+ assert.equal(result.dryRun, true)
+ assert.equal(prepared, 0)
+ assert.match(result.unit, new RegExp(`^${UNIT_IDENTITY_MARKER}$`, 'm'))
+ assert.match(result.unit, /"--port" "6769"/)
+ assert.equal(result.unitPath, orcaServiceUnitPath({ home: d.home }))
+ await assert.rejects(() => lstat(d.root), { code: 'ENOENT' })
+ await assert.rejects(() => lstat(result.unitPath), { code: 'ENOENT' })
+ assert.equal(JSON.stringify(result).includes('pairing'), false)
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('writes private config, a fixed-argv unit, and only then a receipt after identity+web readiness', async () => {
+ const d = await makeDirs()
+ try {
+ const calls = []
+ const hostNode = join(d.base, 'host-node')
+ const result = await installManagedOrca({
+ managedRoot: d.root,
+ home: d.home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ hostNode,
+ prepare: async (input) => {
+ assert.equal(input.installRoot, d.root)
+ assert.equal(input.allowDownload, true)
+ return fakeRelease(d.root)
+ },
+ userBus: async () => ({ XDG_RUNTIME_DIR: '/run/user/1000' }),
+ portProbe: async ({ port }) => calls.push(['port', port]),
+ systemctl: async ({ args }) => calls.push(['systemctl', ...args]),
+ readStatus: async () => status,
+ probeWeb: async () => web,
+ wait: async () => {}
+ })
+ assert.equal(result.dryRun, false)
+ assert.deepEqual(calls, [
+ ['port', 6769],
+ ['systemctl', 'daemon-reload'],
+ ['systemctl', 'enable', '--now', 'mso-orca.service']
+ ])
+
+ const configPath = join(d.root, 'managed-service.json')
+ const receiptPath = join(d.root, 'managed-install.json')
+ for (const file of [configPath, receiptPath]) {
+ assert.equal((await lstat(file)).mode & 0o777, 0o600)
+ assert.equal((await lstat(file)).uid, process.getuid())
+ }
+ assert.equal((await lstat(result.unitPath)).mode & 0o777, 0o644)
+ const config = JSON.parse(await readFile(configPath, 'utf8'))
+ const receipt = JSON.parse(await readFile(receiptPath, 'utf8'))
+ assert.equal(config.release.contentId, getReleaseContentId())
+ assert.equal(config.hostNode, hostNode)
+ assert.equal(config.cliScript, fileURLToPath(new URL('./cli.mjs', import.meta.url)))
+ assert.notEqual(config.hostNode, config.release.nodeBinary)
+ assert.equal(config.advertisedEndpoint, 'wss://orca.mso.example.com')
+ assert.equal(config.boundEndpoint, 'ws://127.0.0.1:6769')
+ assert.equal(receipt.runtimeId, 'runtime-fixture')
+ assert.equal(receipt.readyAt, status.readyAt)
+ const all = JSON.stringify({ config, receipt })
+ for (const forbidden of ['pairing', 'token', 'ticket', 'secret']) {
+ assert.equal(all.toLowerCase().includes(forbidden), false)
+ }
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('refuses a foreign unit before preparing or writing anything', async () => {
+ const d = await makeDirs()
+ try {
+ const unitPath = orcaServiceUnitPath({ home: d.home })
+ await mkdir(join(unitPath, '..'), { recursive: true })
+ await writeFile(unitPath, '[Service]\nExecStart=/usr/bin/orca --port 6768\n')
+ let prepared = 0
+ await assert.rejects(
+ () => installManagedOrca({
+ managedRoot: d.root,
+ home: d.home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ prepare: async () => { prepared += 1 }
+ }),
+ /foreign unit/
+ )
+ assert.equal(prepared, 0)
+ assert.equal(await readFile(unitPath, 'utf8'), '[Service]\nExecStart=/usr/bin/orca --port 6768\n')
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('fails clearly before any mutation when the user bus or port is unavailable', async () => {
+ const d = await makeDirs()
+ try {
+ let prepared = 0
+ await assert.rejects(
+ () => installManagedOrca({
+ managedRoot: d.root,
+ home: d.home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ prepare: async () => { prepared += 1 },
+ userBus: async () => null
+ }),
+ /systemd user bus/
+ )
+ assert.equal(prepared, 0)
+
+ await assert.rejects(
+ () => installManagedOrca({
+ managedRoot: d.root,
+ home: d.home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ prepare: async () => { prepared += 1 },
+ userBus: async () => ({ XDG_RUNTIME_DIR: '/run/user/1000' }),
+ portProbe: async () => { throw new Error('port 127.0.0.1:6769 is already in use') }
+ }),
+ /already in use/
+ )
+ assert.equal(prepared, 0)
+ await assert.rejects(() => lstat(join(d.root, 'managed-service.json')), { code: 'ENOENT' })
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('rejects a prepared release whose files escape the immutable release root', async () => {
+ const d = await makeDirs()
+ try {
+ await assert.rejects(
+ () => installManagedOrca({
+ managedRoot: d.root,
+ home: d.home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ prepare: async () => ({ ...fakeRelease(d.root), nodeBinary: '/usr/bin/node' }),
+ userBus: async () => ({ XDG_RUNTIME_DIR: '/run/user/1000' }),
+ portProbe: async () => {}
+ }),
+ /outside the immutable release root/
+ )
+ await assert.rejects(() => lstat(join(d.root, 'managed-service.json')), { code: 'ENOENT' })
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('detects a genuinely occupied fixed port without ever touching 6768', async () => {
+ const { createServer } = await import('node:net')
+ const server = createServer()
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const { port } = server.address()
+ try {
+ await assert.rejects(() => assertPortFree({ port }), /already in use/)
+ } finally {
+ await new Promise((resolve) => server.close(resolve))
+ }
+ })
+})
diff --git a/scripts/orca/managed-paths.mjs b/scripts/orca/managed-paths.mjs
new file mode 100644
index 00000000..90337942
--- /dev/null
+++ b/scripts/orca/managed-paths.mjs
@@ -0,0 +1,95 @@
+/**
+ * MSO-owned Orca state locations.
+ *
+ * The managed root is deliberately separate from the operator's own Orca state
+ * (`~/.orca`, `~/.orca-remote`). `ORCA_HOME` is honoured only when it is an
+ * absolute path with no traversal segment; otherwise the portable MSO default
+ * is used. Nothing here reads or resolves the user's existing Orca install.
+ */
+
+import { homedir } from 'node:os'
+import { isAbsolute, join, normalize, sep } from 'node:path'
+
+export const MANAGED_APP_ID = 'orca'
+export const SERVICE_NAME = 'mso-orca.service'
+/** Exact first line that marks a unit as generated by this adapter. */
+export const UNIT_IDENTITY_MARKER = '# mso-managed-app: orca'
+export const MANAGED_ROOT_RELATIVE_TO_HOME = ['.local', 'share', 'mso', 'orca']
+export const SERVICE_CONFIG_FILENAME = 'managed-service.json'
+export const INSTALL_RECEIPT_FILENAME = 'managed-install.json'
+
+const CONTROL = /[\0\r\n]/
+
+export function defaultManagedRoot({ home = homedir() } = {}) {
+ return join(home, ...MANAGED_ROOT_RELATIVE_TO_HOME)
+}
+
+function hasTraversal(value) {
+ return value.split(/[\\/]/).some((part) => part === '..')
+}
+
+/**
+ * Absolute managed root. A relative, blank, non-canonical or hostile `ORCA_HOME`
+ * is refused rather than silently reinterpreted: a typo must not point the
+ * installer at `/`, the home directory, or the operator's personal Orca state.
+ * A set-but-empty override is a misconfiguration, not "unset", so it never
+ * falls back to the portable default.
+ */
+export function resolveManagedRoot({ env = process.env, home = homedir() } = {}) {
+ const raw = env?.ORCA_HOME
+ if (raw === undefined) return defaultManagedRoot({ home })
+ if (typeof raw !== 'string' || raw.trim() === '') {
+ throw new Error('ORCA_HOME must be a non-empty absolute path')
+ }
+ if (CONTROL.test(raw)) throw new Error('ORCA_HOME must not contain control characters')
+ if (!isAbsolute(raw)) throw new Error(`ORCA_HOME must be an absolute path, got: ${raw}`)
+ const normalized = normalize(raw)
+ // A trailing slash, a `//`, or a `.`/`..` segment changes the canonical
+ // spelling; refuse it instead of quietly rewriting the operator's config.
+ if (normalized !== raw || (raw.length > 1 && raw.endsWith(sep))) {
+ throw new Error(`ORCA_HOME must be a canonical absolute path, got: ${raw}`)
+ }
+ if (hasTraversal(normalized)) throw new Error(`ORCA_HOME must not contain '..': ${raw}`)
+ if (normalized === sep) throw new Error('ORCA_HOME must not be the filesystem root')
+ const resolvedHome = normalize(home)
+ if (normalized === resolvedHome) throw new Error('ORCA_HOME must not be the home directory itself')
+ for (const denied of ['.orca', '.orca-remote']) {
+ const prefix = join(resolvedHome, denied)
+ if (normalized === prefix || normalized.startsWith(`${prefix}${sep}`)) {
+ throw new Error(`ORCA_HOME must not reuse the operator's ${denied} state`)
+ }
+ }
+ return normalized
+}
+
+export function serviceConfigPath(root) {
+ return join(root, SERVICE_CONFIG_FILENAME)
+}
+
+export function installReceiptPath(root) {
+ return join(root, INSTALL_RECEIPT_FILENAME)
+}
+
+/**
+ * Linux `sun_path` is 108 bytes including the trailing NUL. The upstream server
+ * binds a Unix socket at `<root>/runtime/user-data/o-<pid>-<hex>.sock`, so a
+ * managed root that is too deep makes `listen()` fail with a cryptic EINVAL
+ * before readiness is ever possible. Refuse it with a clear reason instead.
+ */
+export const UNIX_SOCKET_PATH_MAX_BYTES = 107
+const UNIX_SOCKET_LEAF_RESERVE = 'o-1234567-abcd.sock'.length
+
+export function assertManagedRootFitsUnixSocket(root) {
+ const socketPath = `${root}/runtime/user-data/${'x'.repeat(UNIX_SOCKET_LEAF_RESERVE)}`
+ if (Buffer.byteLength(socketPath) > UNIX_SOCKET_PATH_MAX_BYTES) {
+ throw new Error(
+ `managed root is too deep for the Orca runtime's Unix socket ` +
+ `(${Buffer.byteLength(socketPath)} > ${UNIX_SOCKET_PATH_MAX_BYTES} bytes); choose a shorter ORCA_HOME`
+ )
+ }
+ return root
+}
+
+export function orcaServiceUnitPath({ home = homedir() } = {}) {
+ return join(home, '.config', 'systemd', 'user', SERVICE_NAME)
+}
diff --git a/scripts/orca/managed-paths.test.mjs b/scripts/orca/managed-paths.test.mjs
new file mode 100644
index 00000000..26d3cbfe
--- /dev/null
+++ b/scripts/orca/managed-paths.test.mjs
@@ -0,0 +1,57 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { join } from 'node:path'
+import {
+ MANAGED_ROOT_RELATIVE_TO_HOME,
+ UNIT_IDENTITY_MARKER,
+ assertManagedRootFitsUnixSocket,
+ defaultManagedRoot,
+ installReceiptPath,
+ orcaServiceUnitPath,
+ resolveManagedRoot,
+ serviceConfigPath
+} from './managed-paths.mjs'
+
+const HOME = '/home/operator'
+
+describe('managed Orca root resolution', () => {
+ it('defaults to the portable MSO-owned state directory, never ~/.orca', () => {
+ assert.equal(defaultManagedRoot({ home: HOME }), join(HOME, ...MANAGED_ROOT_RELATIVE_TO_HOME))
+ assert.equal(resolveManagedRoot({ env: {}, home: HOME }), join(HOME, '.local', 'share', 'mso', 'orca'))
+ })
+
+ it('accepts only a canonical absolute ORCA_HOME and rejects dirty spellings', () => {
+ assert.equal(resolveManagedRoot({ env: { ORCA_HOME: '/srv/mso/orca' }, home: HOME }), '/srv/mso/orca')
+ for (const dirty of ['/srv/mso/orca/', '/srv//mso/orca', '/srv/mso/./orca', '', ' ']) {
+ assert.throws(() => resolveManagedRoot({ env: { ORCA_HOME: dirty }, home: HOME }), /ORCA_HOME/)
+ }
+ assert.equal(resolveManagedRoot({ env: {}, home: HOME }), join(HOME, '.local', 'share', 'mso', 'orca'))
+ assert.equal(resolveManagedRoot({ env: { ORCA_HOME: undefined }, home: HOME }), defaultManagedRoot({ home: HOME }))
+ })
+
+ it('refuses relative, traversing, root, home, and personal Orca roots', () => {
+ for (const bad of ['relative/orca', '/srv/../etc', '/', HOME, `${HOME}/.orca`, `${HOME}/.orca-remote/x`]) {
+ assert.throws(() => resolveManagedRoot({ env: { ORCA_HOME: bad }, home: HOME }), /ORCA_HOME/)
+ }
+ assert.throws(() => resolveManagedRoot({ env: { ORCA_HOME: '/srv/orca\n' }, home: HOME }), /control/)
+ })
+
+ it('keeps service config and receipts inside the managed root', () => {
+ const root = '/srv/mso/orca'
+ assert.equal(serviceConfigPath(root), '/srv/mso/orca/managed-service.json')
+ assert.equal(installReceiptPath(root), '/srv/mso/orca/managed-install.json')
+ assert.equal(
+ orcaServiceUnitPath({ home: HOME }),
+ join(HOME, '.config', 'systemd', 'user', 'mso-orca.service')
+ )
+ })
+
+ it('pins the unit marker used by the collision guard', () => {
+ assert.equal(UNIT_IDENTITY_MARKER, '# mso-managed-app: orca')
+ })
+
+ it('refuses a managed root too deep for the runtime Unix socket', () => {
+ assert.equal(assertManagedRootFitsUnixSocket('/srv/mso/orca'), '/srv/mso/orca')
+ assert.throws(() => assertManagedRootFitsUnixSocket(`/${'a'.repeat(80)}`), /too deep for the Orca runtime/)
+ })
+})
diff --git a/scripts/orca/managed-preflight.mjs b/scripts/orca/managed-preflight.mjs
new file mode 100644
index 00000000..6d56839b
--- /dev/null
+++ b/scripts/orca/managed-preflight.mjs
@@ -0,0 +1,119 @@
+/**
+ * Preflight guards for the managed Orca install.
+ *
+ * Each guard fails clearly and mutates nothing: the configured split-origin
+ * endpoint, the systemd user bus, the fixed loopback port, and the shape of a
+ * prepared release are all checked before any download, write, or service call.
+ * The operator's existing Orca state and port 6768 are never read or signalled.
+ */
+
+import { existsSync } from 'node:fs'
+import { createServer } from 'node:net'
+import { isAbsolute, join, normalize, sep } from 'node:path'
+import { ORCA_VERSION } from './constants.mjs'
+import { SERVICE_NAME } from './managed-paths.mjs'
+import { getReleaseContentId, getReleaseIdentity } from './release-identity.mjs'
+import { assertConfiguredAdvertisedEndpoint, assertPersistentPort } from './supervision.mjs'
+
+/** `<configured app origin>` -> the exact WSS endpoint Orca advertises. */
+export function toWssEndpoint(appOrigin) {
+ if (typeof appOrigin !== 'string' || !appOrigin.trim()) {
+ throw new Error('Orca install requires MSO_INSTALL_APP_ORIGIN (the configured split app origin)')
+ }
+ let url
+ try {
+ url = new URL(appOrigin.trim())
+ } catch {
+ throw new Error(`configured Orca app origin is not a valid URL: ${appOrigin}`)
+ }
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
+ throw new Error('configured Orca app origin must be http(s)')
+ }
+ if (url.username || url.password || url.search || url.hash) {
+ throw new Error('configured Orca app origin must not contain credentials, query, or fragment')
+ }
+ const wss = new URL(url.href)
+ wss.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
+ return assertConfiguredAdvertisedEndpoint(wss.href)
+}
+
+export function defaultUserBusEnvironment({ env = process.env } = {}) {
+ const current = env.XDG_RUNTIME_DIR
+ if (current && existsSync(`${current}/bus`)) return { XDG_RUNTIME_DIR: current }
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ if (uid !== null && existsSync(`/run/user/${uid}/bus`)) return { XDG_RUNTIME_DIR: `/run/user/${uid}` }
+ return null
+}
+
+/** A clear preflight failure instead of a unit that can never start. */
+export async function assertUserSystemdBus({ env = process.env, probe = defaultUserBusEnvironment } = {}) {
+ const bus = await probe({ env })
+ if (!bus) {
+ throw new Error(
+ `Cannot reach the systemd user bus for this account, so ${SERVICE_NAME} could not be installed or started. ` +
+ 'On a normal systemd host enable user linger (`loginctl enable-linger $USER`) and make XDG_RUNTIME_DIR available to MSO. ' +
+ 'Nothing has been changed.'
+ )
+ }
+ return bus
+}
+
+/** Fixed-port preflight. Never points at 6768: that is the operator's own instance. */
+export async function assertPortFree({ port, host = '127.0.0.1' }) {
+ const fixedPort = assertPersistentPort(port)
+ await new Promise((resolve, reject) => {
+ const probe = createServer()
+ probe.unref()
+ probe.once('error', (err) => {
+ reject(
+ new Error(
+ err?.code === 'EADDRINUSE'
+ ? `port ${host}:${fixedPort} is already in use; refusing to start ${SERVICE_NAME} over another process`
+ : `could not verify port ${host}:${fixedPort} is free: ${err?.code ?? 'unknown error'}`
+ )
+ )
+ })
+ probe.listen(fixedPort, host, () => probe.close(() => resolve()))
+ })
+}
+
+export function assertPreparedRelease(release, managedRoot) {
+ if (!release || typeof release !== 'object') throw new Error('preparePinnedRelease returned no release')
+ const root = normalize(managedRoot)
+ const identity = getReleaseIdentity()
+ // The pinned release lives at exactly `<root>/releases/<version>+<contentId>`
+ // and every other path is a fixed suffix of that slot. Comparing against the
+ // canonical expectation (rather than a lexical `startsWith`) makes a
+ // `/root/../foreign` spelling fail closed as loudly as an outright escape.
+ const expectedReleaseRoot = join(root, 'releases', `${identity.version}+${identity.contentId}`)
+ const expected = {
+ releaseRoot: expectedReleaseRoot,
+ slotDir: join(expectedReleaseRoot, 'slot'),
+ webDir: join(expectedReleaseRoot, 'web'),
+ receiptPath: join(expectedReleaseRoot, 'receipt.json'),
+ nodeBinary: join(expectedReleaseRoot, identity.node.executablePath)
+ }
+ for (const [key, value] of Object.entries(expected)) {
+ if (typeof release[key] !== 'string' || !isAbsolute(release[key])) {
+ throw new Error(`prepared release ${key} must be an absolute path`)
+ }
+ if (release[key] !== normalize(release[key]) || release[key].split(sep).includes('..')) {
+ throw new Error(`prepared release ${key} is not a canonical path: ${release[key]}`)
+ }
+ }
+ if (release.releaseRoot !== expected.releaseRoot) {
+ throw new Error(`prepared release releaseRoot is not the immutable release root: ${release.releaseRoot}`)
+ }
+ for (const key of ['slotDir', 'nodeBinary', 'webDir', 'receiptPath']) {
+ if (release[key] !== expected[key]) {
+ throw new Error(`prepared release ${key} is outside the immutable release root: ${release[key]}`)
+ }
+ }
+ if (release.version !== ORCA_VERSION) {
+ throw new Error(`prepared release version mismatch: expected ${ORCA_VERSION}, got ${release.version}`)
+ }
+ if (release.receipt?.release?.contentId !== getReleaseContentId()) {
+ throw new Error('prepared release receipt content id does not match the pinned release')
+ }
+ return release
+}
diff --git a/scripts/orca/managed-preflight.test.mjs b/scripts/orca/managed-preflight.test.mjs
new file mode 100644
index 00000000..82d058bb
--- /dev/null
+++ b/scripts/orca/managed-preflight.test.mjs
@@ -0,0 +1,54 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { join } from 'node:path'
+import { assertPreparedRelease } from './managed-preflight.mjs'
+import { getReleaseContentId, getReleaseIdentity } from './release-identity.mjs'
+
+const ROOT = '/srv/mso/orca'
+const ID = getReleaseContentId()
+const NODE_REL = getReleaseIdentity().node.executablePath
+const RELEASE_ROOT = join(ROOT, 'releases', `1.4.230+${ID}`)
+
+function release(overrides = {}) {
+ return {
+ releaseRoot: RELEASE_ROOT,
+ slotDir: join(RELEASE_ROOT, 'slot'),
+ webDir: join(RELEASE_ROOT, 'web'),
+ receiptPath: join(RELEASE_ROOT, 'receipt.json'),
+ nodeBinary: join(RELEASE_ROOT, NODE_REL),
+ version: '1.4.230',
+ receipt: { release: { contentId: ID } },
+ ...overrides
+ }
+}
+
+describe('prepared release containment', () => {
+ it('accepts only the exact pinned release layout', () => {
+ assert.equal(assertPreparedRelease(release(), ROOT).releaseRoot, RELEASE_ROOT)
+ })
+
+ it('rejects a release root that is not <root>/releases/<pinned id>', () => {
+ for (const bad of [join(ROOT, 'releases', 'other'), join(ROOT, 'releases'), ROOT, '/srv/etc']) {
+ assert.throws(() => assertPreparedRelease(release({ releaseRoot: bad }), ROOT), /immutable release root/)
+ }
+ })
+
+ it('rejects any slot/node/web/receipt path outside the release root', () => {
+ for (const key of ['slotDir', 'webDir', 'receiptPath', 'nodeBinary']) {
+ assert.throws(() => assertPreparedRelease(release({ [key]: '/usr/bin/node' }), ROOT), /outside the immutable release root/)
+ }
+ })
+
+ it('rejects a non-canonical spelling that would normalize elsewhere', () => {
+ const escaped = `${RELEASE_ROOT}/../../etc/passwd`
+ assert.throws(() => assertPreparedRelease(release({ nodeBinary: escaped }), ROOT), /canonical path/)
+ })
+
+ it('rejects a version or content-id mismatch', () => {
+ assert.throws(() => assertPreparedRelease(release({ version: '1.0.0' }), ROOT), /version mismatch/)
+ assert.throws(
+ () => assertPreparedRelease(release({ receipt: { release: { contentId: 'nope' } } }), ROOT),
+ /content id/
+ )
+ })
+})
diff --git a/scripts/orca/managed-receipt.mjs b/scripts/orca/managed-receipt.mjs
new file mode 100644
index 00000000..640c892e
--- /dev/null
+++ b/scripts/orca/managed-receipt.mjs
@@ -0,0 +1,72 @@
+/**
+ * Verified installed-release reader for the Orca lifecycle adapter.
+ *
+ * `--version` may report the pinned version only after an actual install receipt
+ * exists and the immutable release root it names still rehashes clean. The
+ * presence of this repository's wrapper script proves nothing.
+ */
+
+import { lstat } from 'node:fs/promises'
+import { isAbsolute, relative } from 'node:path'
+import { ORCA_VERSION } from './constants.mjs'
+import { installReceiptPath, resolveManagedRoot } from './managed-paths.mjs'
+import { readPrivateJson } from './private-store.mjs'
+import { getReleaseIdentity } from './release-identity.mjs'
+import { verifyInstalledRelease } from './release-receipt.mjs'
+
+const unavailable = (reason) => ({ installed: false, reason })
+
+function isInside(root, candidate) {
+ if (typeof candidate !== 'string' || !isAbsolute(candidate)) return false
+ const rel = relative(root, candidate)
+ return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel)
+}
+
+export async function readInstalledOrcaRelease({
+ managedRoot = resolveManagedRoot(),
+ verify = verifyInstalledRelease,
+ identity = getReleaseIdentity()
+} = {}) {
+ const root = managedRoot
+ const receiptPath = installReceiptPath(root)
+ try {
+ // `readPrivateJson` reports an absent file as a plain error without a code,
+ // so classify presence first: no receipt means "not installed", while a
+ // present-but-rejected one is merely unreadable. Never parses error text.
+ await lstat(receiptPath)
+ } catch (err) {
+ return unavailable(err?.code === 'ENOENT' ? 'not_installed' : 'install_receipt_unreadable')
+ }
+ let receipt
+ try {
+ receipt = await readPrivateJson(receiptPath, { root })
+ } catch {
+ return unavailable('install_receipt_unreadable')
+ }
+ if (
+ !receipt ||
+ receipt.schemaVersion !== 1 ||
+ receipt.applicationId !== 'orca' ||
+ receipt.version !== ORCA_VERSION
+ ) {
+ return unavailable('invalid_install_receipt')
+ }
+ if (!isInside(root, receipt.releaseRoot)) return unavailable('install_receipt_outside_root')
+
+ let verified
+ try {
+ verified = await verify({ releaseRoot: receipt.releaseRoot, identity })
+ } catch {
+ return unavailable('installed_release_failed_verification')
+ }
+ if (verified?.version !== receipt.version || verified?.receipt?.release?.contentId !== receipt.releaseContentId) {
+ return unavailable('installed_release_identity_mismatch')
+ }
+ return {
+ installed: true,
+ version: verified.version,
+ releaseRoot: verified.releaseRoot,
+ contentId: verified.receipt.release.contentId,
+ advertisedEndpoint: receipt.advertisedEndpoint ?? null
+ }
+}
diff --git a/scripts/orca/managed-rollback.mjs b/scripts/orca/managed-rollback.mjs
new file mode 100644
index 00000000..1a91d48e
--- /dev/null
+++ b/scripts/orca/managed-rollback.mjs
@@ -0,0 +1,188 @@
+/**
+ * Bounded rollback for the FIRST Orca install.
+ *
+ * A first install that fails AFTER the unit was written and started must not
+ * leave a half-installed, restarting `mso-orca.service` that a rerun then
+ * silently adopts. This module stops ONLY the exact unit MSO created, restores
+ * the prior owned service config / unit / install receipt (or removes what this
+ * attempt created), and — when any rollback step itself fails — records an
+ * explicit `partial-install.json` marker so the next attempt refuses to rerun
+ * instead of guessing.
+ *
+ * It never signals a foreign unit and never reads or writes the operator's own
+ * Orca state, port 6768, or any scope other than this user's `mso-orca.service`.
+ */
+
+import { lstat, rm } from 'node:fs/promises'
+import { join } from 'node:path'
+import {
+ MANAGED_APP_ID,
+ SERVICE_NAME,
+ installReceiptPath,
+ serviceConfigPath
+} from './managed-paths.mjs'
+import { readPrivateJson, writePrivateFile } from './private-store.mjs'
+import { inspectExistingUnit } from './systemd-unit.mjs'
+import { writeUnitAtomic } from './managed-unit-write.mjs'
+
+const PARTIAL_MARKER = 'partial-install.json'
+
+export function partialInstallPath(root) {
+ return join(root, PARTIAL_MARKER)
+}
+
+/** Present + readable, present + unreadable, or absent. Never creates the root. */
+async function capturePrivate(path, root) {
+ try {
+ if (!(await lstat(path)).isFile()) return { exists: true, readable: false, data: null }
+ } catch (err) {
+ if (err.code === 'ENOENT') return { exists: false, readable: true, data: null }
+ return { exists: true, readable: false, data: null }
+ }
+ try {
+ return { exists: true, readable: true, data: await readPrivateJson(path, { root }) }
+ } catch {
+ return { exists: true, readable: false, data: null }
+ }
+}
+
+export async function capturePriorManagedState({ root, unitState, unitText }) {
+ return {
+ unitState,
+ unitText: unitText ?? null,
+ config: await capturePrivate(serviceConfigPath(root), root),
+ receipt: await capturePrivate(installReceiptPath(root), root)
+ }
+}
+
+/** Restore a prior private file, or remove the one this attempt created. */
+async function restorePrivate(path, entry, root) {
+ if (!entry.exists) {
+ await rm(path, { force: true })
+ return
+ }
+ if (!entry.readable || entry.data === null) throw new Error(`prior ${path} is unreadable, cannot restore`)
+ await writePrivateFile(path, entry.data, { root })
+}
+
+/**
+ * Best-effort, bounded. Returns `{ complete, failures }`: `complete === false`
+ * means a rollback step failed (or the owned unit was not safely stopped) and the
+ * caller must record a partial-install marker rather than pretend it was clean.
+ *
+ * `created` says which files THIS attempt actually wrote. `unitText` is the exact
+ * unit text this attempt wrote, so a revalidation can confirm the on-disk unit is
+ * still ours before we stop or remove it.
+ */
+export async function rollbackFirstInstall({ root, unitPath, prior, created, unitText, systemctl, env, bus }) {
+ const failures = []
+ const attempt = async (label, fn) => {
+ try {
+ await fn()
+ } catch (err) {
+ failures.push(`${label}: ${err?.message ?? String(err)}`.slice(0, 300))
+ }
+ }
+ // A systemctl call is a FAILURE when it RETURNS a nonzero code, not only when
+ // it throws: the production `defaultSystemctl` reports `{code}` instead of
+ // throwing with `allowFailure: true`. Ignoring the code silently "succeeded" a
+ // refused stop.
+ const control = async (label, args) => {
+ try {
+ const result = await systemctl({ args, env, bus, allowFailure: true })
+ if (result?.code) {
+ failures.push(`${label} failed (exit ${result.code}): ${String(result.stderr ?? '').slice(0, 200)}`)
+ return false
+ }
+ return true
+ } catch (err) {
+ failures.push(`${label}: ${err?.message ?? String(err)}`.slice(0, 300))
+ return false
+ }
+ }
+ const restore = async () => {
+ if (created.config) {
+ await attempt('restore managed service config', () => restorePrivate(serviceConfigPath(root), prior.config, root))
+ }
+ if (created.receipt) {
+ await attempt('restore install receipt', () => restorePrivate(installReceiptPath(root), prior.receipt, root))
+ }
+ }
+
+ if (!created.unit) {
+ // The unit was never written; only the config and/or receipt could exist.
+ await restore()
+ return { complete: failures.length === 0, failures }
+ }
+
+ // Revalidate that the on-disk unit is still the exact one this attempt wrote.
+ let ownUnit = false
+ try {
+ const current = await inspectExistingUnit({ unitPath })
+ ownUnit = current.state === 'managed' && (unitText === undefined || current.text === unitText)
+ } catch {
+ ownUnit = false
+ }
+ if (!ownUnit) {
+ // A foreign unit replaced ours: keep it, restore/remove only what we wrote.
+ await restore()
+ failures.push('the on-disk unit is no longer the MSO-owned unit this attempt wrote; left untouched')
+ return { complete: false, failures }
+ }
+
+ if (prior.unitState === 'absent') {
+ if (!(await control('stop created unit', ['disable', '--now', SERVICE_NAME]))) {
+ // The owned unit may still be running. Keep the unit AND its config as
+ // evidence and let the partial marker force an explicit clean-up: removing
+ // a unit while its server may still be running is worse than a marked
+ // leftover.
+ return { complete: false, failures }
+ }
+ await restore()
+ await attempt('remove created unit', () => rm(unitPath, { force: true }))
+ await control('reload after remove', ['daemon-reload'])
+ return { complete: failures.length === 0, failures }
+ }
+
+ // prior.unitState === 'managed': we replaced an already-owned unit.
+ await restore()
+ await attempt('restore unit', () => writeUnitAtomic(unitPath, prior.unitText))
+ await control('reload restored unit', ['daemon-reload'])
+ return { complete: failures.length === 0, failures }
+}
+
+export async function writePartialInstall(root, { reason, failures, now }) {
+ await writePrivateFile(
+ partialInstallPath(root),
+ {
+ schemaVersion: 1,
+ applicationId: MANAGED_APP_ID,
+ reason: String(reason ?? 'install failed').slice(0, 300),
+ failures,
+ failedAt: now()
+ },
+ { root }
+ )
+}
+
+/** An unreadable marker still counts as present: refuse rather than guess. */
+export async function readPartialInstall(root) {
+ const path = partialInstallPath(root)
+ const info = await lstat(path).catch((err) => {
+ if (err.code === 'ENOENT') return null
+ throw err
+ })
+ if (!info) return null
+ const data = await readPrivateJson(path, { root }).catch(() => null)
+ return data ?? { reason: 'partial-install marker is unreadable' }
+}
+
+/** Throw a clear, named refusal when a prior attempt left a partial state. */
+export async function assertNoPartialInstall(root) {
+ const partial = await readPartialInstall(root)
+ if (!partial) return
+ throw new Error(
+ `a previous Orca install left a partial state (${partial.reason}); inspect and remove ` +
+ `${partialInstallPath(root)} before rerunning`
+ )
+}
diff --git a/scripts/orca/managed-rollback.test.mjs b/scripts/orca/managed-rollback.test.mjs
new file mode 100644
index 00000000..f9994c95
--- /dev/null
+++ b/scripts/orca/managed-rollback.test.mjs
@@ -0,0 +1,204 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { getReleaseContentId, getReleaseIdentity } from './release-identity.mjs'
+import { installManagedOrca } from './managed-install.mjs'
+import { orcaServiceUnitPath } from './managed-paths.mjs'
+
+const RELEASE_ID = getReleaseContentId()
+const NODE_REL = getReleaseIdentity().node.executablePath
+const FOREIGN = '[Service]\nExecStart=/usr/bin/orca --port 6768\n'
+
+async function makeDirs() {
+ const base = await mkdtemp(join(tmpdir(), 'oi-'))
+ const root = join(base, 'root')
+ const home = join(base, 'home')
+ await mkdir(home, { recursive: true, mode: 0o700 })
+ return { base, root, home, cleanup: () => rm(base, { recursive: true, force: true }) }
+}
+
+function fakeRelease(root) {
+ const releaseRoot = join(root, 'releases', `1.4.230+${RELEASE_ID}`)
+ return {
+ releaseRoot,
+ slotDir: join(releaseRoot, 'slot'),
+ nodeBinary: join(releaseRoot, NODE_REL),
+ webDir: join(releaseRoot, 'web'),
+ receiptPath: join(releaseRoot, 'receipt.json'),
+ version: '1.4.230',
+ receipt: { release: { contentId: RELEASE_ID } }
+ }
+}
+
+const exists = async (path) => {
+ try {
+ await lstat(path)
+ return true
+ } catch {
+ return false
+ }
+}
+
+describe('bounded first-install rollback', () => {
+ it('stops the exact created unit and removes every file it wrote when readiness never arrives', async () => {
+ const d = await makeDirs()
+ try {
+ const calls = []
+ const unitPath = orcaServiceUnitPath({ home: d.home })
+ await assert.rejects(
+ () =>
+ installManagedOrca({
+ managedRoot: d.root,
+ home: d.home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ prepare: async () => fakeRelease(d.root),
+ userBus: async () => ({ XDG_RUNTIME_DIR: '/run/user/1000' }),
+ portProbe: async () => {},
+ systemctl: async (opts) => {
+ calls.push(opts)
+ return { code: 0, stdout: '', stderr: '' }
+ },
+ readStatus: async () => ({ available: false, reason: 'server_process_dead' }),
+ probeWeb: async () => ({ available: false, reason: 'web_unreachable' }),
+ wait: async () => {},
+ timeoutMs: 1,
+ pollMs: 1
+ }),
+ /did not become ready/
+ )
+
+ // Only ever the created USER unit, best-effort.
+ assert.ok(calls.some((c) => c.args.join(' ') === 'enable --now mso-orca.service'))
+ const stop = calls.find((c) => c.args.join(' ') === 'disable --now mso-orca.service')
+ assert.equal(stop?.allowFailure, true)
+
+ assert.equal(await exists(unitPath), false)
+ assert.equal(await exists(join(d.root, 'managed-service.json')), false)
+ assert.equal(await exists(join(d.root, 'managed-install.json')), false)
+ // A clean rollback leaves NO partial marker.
+ assert.equal(await exists(join(d.root, 'partial-install.json')), false)
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('does not fabricate success or start anything when the first config write fails', async () => {
+ const d = await makeDirs()
+ try {
+ const calls = []
+ await assert.rejects(
+ () =>
+ installManagedOrca({
+ managedRoot: d.root,
+ home: d.home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ prepare: async () => fakeRelease(d.root),
+ userBus: async () => ({ XDG_RUNTIME_DIR: '/run/user/1000' }),
+ portProbe: async () => {},
+ writePrivate: async () => {
+ throw new Error('disk full')
+ },
+ systemctl: async (opts) => {
+ calls.push(opts.args.join(' '))
+ return { code: 0, stdout: '', stderr: '' }
+ }
+ }),
+ /disk full/
+ )
+ assert.deepEqual(calls, [])
+ assert.equal(await exists(orcaServiceUnitPath({ home: d.home })), false)
+ assert.equal(await exists(join(d.root, 'partial-install.json')), false)
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('keeps the owned unit and config and records a partial marker when the stop returns a nonzero code', async () => {
+ const d = await makeDirs()
+ try {
+ const unitPath = orcaServiceUnitPath({ home: d.home })
+ await assert.rejects(
+ () =>
+ installManagedOrca({
+ managedRoot: d.root,
+ home: d.home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ prepare: async () => fakeRelease(d.root),
+ userBus: async () => ({ XDG_RUNTIME_DIR: '/run/user/1000' }),
+ portProbe: async () => {},
+ // Production `defaultSystemctl` reports the exit code instead of
+ // throwing; a refused stop must be a FAILURE, not a silent success.
+ systemctl: async ({ args }) => (args[0] === 'disable' ? { code: 1, stdout: '', stderr: 'stop refused' } : { code: 0, stdout: '', stderr: '' }),
+ readStatus: async () => ({ available: false, reason: 'server_process_dead' }),
+ probeWeb: async () => ({ available: false, reason: 'web_unreachable' }),
+ wait: async () => {},
+ timeoutMs: 1,
+ pollMs: 1
+ }),
+ /did not become ready/
+ )
+ // A confirmed-stop failure must NOT remove the unit or its config.
+ assert.equal(await exists(unitPath), true)
+ assert.equal(await exists(join(d.root, 'managed-service.json')), true)
+ const marker = join(d.root, 'partial-install.json')
+ assert.equal(await exists(marker), true)
+ const parsed = JSON.parse(await readFile(marker, 'utf8'))
+ assert.match(parsed.failures.join('\n'), /stop created unit failed \(exit 1\)/)
+
+ // A rerun refuses instead of adopting the half state.
+ await assert.rejects(
+ () =>
+ installManagedOrca({
+ managedRoot: d.root,
+ home: d.home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ prepare: async () => fakeRelease(d.root)
+ }),
+ /partial state/
+ )
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('preserves a foreign unit that replaced ours before rollback', async () => {
+ const d = await makeDirs()
+ try {
+ const unitPath = orcaServiceUnitPath({ home: d.home })
+ const calls = []
+ await assert.rejects(
+ () =>
+ installManagedOrca({
+ managedRoot: d.root,
+ home: d.home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ prepare: async () => fakeRelease(d.root),
+ userBus: async () => ({ XDG_RUNTIME_DIR: '/run/user/1000' }),
+ portProbe: async () => {},
+ systemctl: async (opts) => {
+ calls.push(opts.args.join(' '))
+ return { code: 0, stdout: '', stderr: '' }
+ },
+ readStatus: async () => {
+ // A foreign unit appears where ours was, then readiness never arrives.
+ await writeFile(unitPath, FOREIGN)
+ return { available: false, reason: 'server_process_dead' }
+ },
+ probeWeb: async () => ({ available: false, reason: 'web_unreachable' }),
+ wait: async () => {},
+ timeoutMs: 1,
+ pollMs: 1
+ }),
+ /did not become ready/
+ )
+ // The foreign unit is preserved and never disabled/removed.
+ assert.equal(await readFile(unitPath, 'utf8'), FOREIGN)
+ assert.equal(calls.some((c) => c.startsWith('disable')), false)
+ assert.equal(await exists(join(d.root, 'partial-install.json')), true)
+ } finally {
+ await d.cleanup()
+ }
+ })
+})
diff --git a/scripts/orca/managed-status.mjs b/scripts/orca/managed-status.mjs
new file mode 100644
index 00000000..4acec940
--- /dev/null
+++ b/scripts/orca/managed-status.mjs
@@ -0,0 +1,177 @@
+/**
+ * Safe, non-secret view of an installed MSO-owned Orca runtime.
+ *
+ * This is the install-time readiness gate and the `status`/`--version` source.
+ * It reads only private receipts, validates them against the live kernel
+ * process identity, and never returns a pairing URL or token. A static HTTP 200
+ * is deliberately not accepted as health.
+ */
+
+import { lstat, realpath } from 'node:fs/promises'
+import { isAbsolute, relative } from 'node:path'
+import { join } from 'node:path'
+import { ORCA_VERSION, DEFAULT_PORT } from './constants.mjs'
+import { readProcessIdentity } from './proc-identity.mjs'
+import { readPrivateJson } from './private-store.mjs'
+import { resolveManagedRoot } from './managed-paths.mjs'
+import { sanitizeEndpoint } from './launcher.mjs'
+
+const WEB_TITLE = '<title>Orca Web</title>'
+const RUNTIME_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/
+
+const unavailable = (reason) => ({ available: false, reason })
+
+function isInside(root, candidate) {
+ if (typeof candidate !== 'string' || !isAbsolute(candidate)) return false
+ const rel = relative(root, candidate)
+ return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel)
+}
+
+function expectedBoundEndpoint({ bind = '127.0.0.1', port = DEFAULT_PORT } = {}) {
+ return `ws://${bind}:${port}`
+}
+
+function parseHttpPort(boundEndpoint) {
+ try {
+ const url = new URL(boundEndpoint)
+ return url.protocol === 'ws:' && (url.hostname === '127.0.0.1' || url.hostname === 'localhost')
+ ? Number(url.port)
+ : null
+ } catch {
+ return null
+ }
+}
+
+/**
+ * @returns `{available:true, ...safe fields}` or `{available:false, reason}`.
+ * No pairing material is ever part of a successful result.
+ */
+export async function readManagedOrcaStatus({
+ managedRoot = resolveManagedRoot(),
+ expectedPort = DEFAULT_PORT,
+ expectedAdvertisedEndpoint,
+ readIdentity = readProcessIdentity,
+ uid = typeof process.getuid === 'function' ? process.getuid() : null
+} = {}) {
+ const root = managedRoot
+ const statusPath = join(root, 'private-status.json')
+ const identityPath = join(root, 'runtime-identity.json')
+ for (const path of [statusPath, identityPath]) {
+ try {
+ // `readPrivateJson` reports a missing file without an error code, so
+ // classify presence explicitly: absent receipts are "missing", while a
+ // present-but-rejected pair is "unreadable". No error-string parsing.
+ await lstat(path)
+ } catch (err) {
+ return unavailable(err?.code === 'ENOENT' ? 'receipts_missing' : 'receipts_unreadable')
+ }
+ }
+ let status
+ let identity
+ try {
+ status = await readPrivateJson(statusPath, { root })
+ identity = await readPrivateJson(identityPath, { root })
+ } catch {
+ return unavailable('receipts_unreadable')
+ }
+
+ if (!status || status.type !== 'orca_server_ready' || status.schemaVersion !== 1) {
+ return unavailable('invalid_readiness_schema')
+ }
+ if (status.health?.buildVersion !== ORCA_VERSION) return unavailable('incompatible_version')
+ if (typeof status.runtimeId !== 'string' || !RUNTIME_ID_RE.test(status.runtimeId)) {
+ return unavailable('invalid_runtime_id')
+ }
+ if (status.boundEndpoint !== expectedBoundEndpoint({ port: expectedPort })) {
+ return unavailable('unexpected_bound_endpoint')
+ }
+ if (typeof status.advertisedEndpoint !== 'string' || sanitizeEndpoint(status.advertisedEndpoint) !== status.advertisedEndpoint) {
+ return unavailable('invalid_advertised_endpoint')
+ }
+ if (expectedAdvertisedEndpoint && status.advertisedEndpoint !== sanitizeEndpoint(expectedAdvertisedEndpoint)) {
+ return unavailable('advertised_endpoint_mismatch')
+ }
+ if (status.pairing?.available !== true || status.pairing?.scope !== 'runtime' || typeof status.pairing?.url !== 'string') {
+ return unavailable('pairing_unavailable')
+ }
+
+ const daemon = status.health?.terminalDaemon
+ if (
+ daemon?.state !== 'live' ||
+ daemon?.ownsFreshSessions !== true ||
+ daemon?.selfTest?.ok !== true ||
+ !Number.isInteger(daemon?.pid) ||
+ daemon.pid <= 1 ||
+ typeof daemon?.entryPath !== 'string' ||
+ !isAbsolute(daemon.entryPath)
+ ) {
+ return unavailable('terminal_daemon_unhealthy')
+ }
+
+ if (
+ !identity ||
+ identity.schemaVersion !== 1 ||
+ identity.version !== ORCA_VERSION ||
+ identity.runtimeId !== status.runtimeId ||
+ !Number.isInteger(identity.serverPid) ||
+ identity.serverPid <= 1
+ ) {
+ return unavailable('invalid_runtime_identity')
+ }
+ for (const [label, value] of [
+ ['nodeBinary', identity.nodeBinary],
+ ['serverEntry', identity.serverEntry],
+ ['userData', identity.userData]
+ ]) {
+ if (!isInside(root, value)) return unavailable(`runtime_identity_${label}_outside_root`)
+ }
+ if (identity.boundEndpoint !== status.boundEndpoint) return unavailable('runtime_identity_bound_mismatch')
+ if (identity.advertisedEndpoint !== status.advertisedEndpoint) {
+ return unavailable('runtime_identity_advertised_mismatch')
+ }
+
+ const server = await readIdentity(identity.serverPid)
+ if (!server) return unavailable('server_process_dead')
+ if (String(server.startTicks) !== String(identity.serverStartTicks)) return unavailable('server_process_reused')
+ if (uid !== null && server.uid !== uid) return unavailable('server_process_foreign')
+ const expectedExe = await realpath(identity.nodeBinary).catch(() => identity.nodeBinary)
+ if (server.exe !== expectedExe) return unavailable('server_executable_mismatch')
+ if (!server.argv.includes(identity.serverEntry)) return unavailable('server_entry_mismatch')
+ if (status.health?.pid !== identity.serverPid) return unavailable('health_pid_mismatch')
+
+ const daemonIdentity = await readIdentity(daemon.pid)
+ if (!daemonIdentity) return unavailable('terminal_daemon_dead')
+ if (uid !== null && daemonIdentity.uid !== uid) return unavailable('terminal_daemon_foreign')
+ if (!daemonIdentity.argv.includes(daemon.entryPath)) return unavailable('terminal_daemon_entry_mismatch')
+
+ const boundPort = parseHttpPort(status.boundEndpoint)
+ if (!Number.isInteger(boundPort) || boundPort !== expectedPort) return unavailable('unexpected_bound_port')
+
+ return {
+ available: true,
+ version: status.health.buildVersion,
+ runtimeId: status.runtimeId,
+ boundEndpoint: status.boundEndpoint,
+ advertisedEndpoint: status.advertisedEndpoint,
+ serverPid: identity.serverPid,
+ daemonPid: daemon.pid,
+ readyAt: typeof identity.readyAt === 'string' ? identity.readyAt : null
+ }
+}
+
+/** Static web proof is separate from identity health; both are required to call an install successful. */
+export async function probeOrcaWebClient({ port = DEFAULT_PORT, timeoutMs = 5000, fetchImpl = fetch } = {}) {
+ const url = `http://127.0.0.1:${port}/web-index.html`
+ try {
+ const response = await fetchImpl(url, {
+ cache: 'no-store',
+ redirect: 'error',
+ signal: AbortSignal.timeout(timeoutMs)
+ })
+ const body = await response.text()
+ if (!response.ok || !body.includes(WEB_TITLE)) return { available: false, reason: 'web_client_unhealthy' }
+ return { available: true, url, status: response.status }
+ } catch {
+ return { available: false, reason: 'web_client_unreachable' }
+ }
+}
diff --git a/scripts/orca/managed-status.test.mjs b/scripts/orca/managed-status.test.mjs
new file mode 100644
index 00000000..8d5ceb88
--- /dev/null
+++ b/scripts/orca/managed-status.test.mjs
@@ -0,0 +1,156 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { spawn } from 'node:child_process'
+import { mkdtemp, rm, symlink } from 'node:fs/promises'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { probeOrcaWebClient, readManagedOrcaStatus } from './managed-status.mjs'
+import { writePrivateFile } from './private-store.mjs'
+
+const HOLD = fileURLToPath(new URL('./fixtures/hold-child.mjs', import.meta.url))
+const PORT = 6769
+const ADVERTISED = 'wss://orca.mso.example.com'
+
+function spawnHolding(args = []) {
+ const child = spawn(process.execPath, [HOLD, ...args], { stdio: ['ignore', 'pipe', 'ignore'] })
+ return new Promise((resolve) => {
+ child.stdout.once('data', () => resolve(child))
+ })
+}
+
+const waitGone = (pid) => new Promise((resolve) => {
+ const started = Date.now()
+ const poll = () => {
+ try { process.kill(pid, 0) } catch { return resolve(true) }
+ if (Date.now() - started > 3000) return resolve(false)
+ setTimeout(poll, 25)
+ }
+ poll()
+})
+
+async function fixture() {
+ const root = await mkdtemp('/home/antinrml/.hermes/cache/scratch/opencode/orca-status-')
+ const nodeLink = join(root, 'node')
+ await symlink(process.execPath, nodeLink)
+ const serverEntry = join(root, 'releases', 'r1', 'slot', 'orcad-server.js')
+ const daemonEntry = join(root, 'releases', 'r1', 'slot', 'daemon-entry.js')
+ const server = await spawnHolding([serverEntry])
+ const daemon = await spawnHolding([daemonEntry])
+ const status = {
+ type: 'orca_server_ready',
+ schemaVersion: 1,
+ runtimeId: 'runtime-abc',
+ boundEndpoint: `ws://127.0.0.1:${PORT}`,
+ advertisedEndpoint: ADVERTISED,
+ pairing: { available: true, scope: 'runtime', url: 'orca://pair?code=PRIVATE_TOKEN' },
+ health: {
+ buildVersion: '1.4.230',
+ pid: server.pid,
+ terminalDaemon: {
+ state: 'live',
+ ownsFreshSessions: true,
+ pid: daemon.pid,
+ entryPath: daemonEntry,
+ selfTest: { ok: true, verdict: 'healthy' }
+ }
+ }
+ }
+ const identity = {
+ schemaVersion: 1,
+ runtimeId: 'runtime-abc',
+ version: '1.4.230',
+ serverPid: server.pid,
+ serverStartTicks: '0',
+ nodeBinary: nodeLink,
+ serverEntry,
+ userData: join(root, 'runtime', 'user-data'),
+ boundEndpoint: status.boundEndpoint,
+ advertisedEndpoint: ADVERTISED,
+ readyAt: '2026-10-19T00:00:00.000Z'
+ }
+ const { readProcessIdentity } = await import('./proc-identity.mjs')
+ identity.serverStartTicks = (await readProcessIdentity(server.pid)).startTicks
+ await writePrivateFile(join(root, 'private-status.json'), status, { root })
+ await writePrivateFile(join(root, 'runtime-identity.json'), identity, { root })
+ return {
+ root,
+ status,
+ identity,
+ server,
+ daemon,
+ cleanup: async () => {
+ for (const child of [server, daemon]) {
+ try { child.kill('SIGKILL') } catch {}
+ await waitGone(child.pid)
+ }
+ await rm(root, { recursive: true, force: true })
+ }
+ }
+}
+
+describe('verified managed Orca status', () => {
+ it('accepts only matching private receipts and live kernel identities, without leaking pairing', async () => {
+ const fx = await fixture()
+ try {
+ const result = await readManagedOrcaStatus({
+ managedRoot: fx.root,
+ expectedPort: PORT,
+ expectedAdvertisedEndpoint: ADVERTISED
+ })
+ assert.equal(result.available, true)
+ assert.equal(result.version, '1.4.230')
+ assert.equal(result.runtimeId, 'runtime-abc')
+ assert.equal(result.serverPid, fx.server.pid)
+ assert.equal(result.daemonPid, fx.daemon.pid)
+ assert.equal(JSON.stringify(result).includes('PRIVATE_TOKEN'), false)
+ assert.equal(JSON.stringify(result).includes('orca://'), false)
+ } finally {
+ await fx.cleanup()
+ }
+ })
+
+ it('reports unavailable for missing evidence, a dead/reused PID, or an origin mismatch', async () => {
+ const fx = await fixture()
+ try {
+ assert.equal((await readManagedOrcaStatus({ managedRoot: join(fx.root, 'absent') })).reason, 'receipts_missing')
+ assert.equal((await readManagedOrcaStatus({
+ managedRoot: fx.root, expectedPort: PORT, expectedAdvertisedEndpoint: 'wss://other.example.com'
+ })).reason, 'advertised_endpoint_mismatch')
+
+ const changed = { ...fx.identity, serverStartTicks: '1' }
+ await writePrivateFile(join(fx.root, 'runtime-identity.json'), changed, { root: fx.root })
+ assert.equal((await readManagedOrcaStatus({ managedRoot: fx.root, expectedPort: PORT })).reason, 'server_process_reused')
+
+ fx.server.kill('SIGKILL')
+ await waitGone(fx.server.pid)
+ await writePrivateFile(join(fx.root, 'runtime-identity.json'), fx.identity, { root: fx.root })
+ assert.equal((await readManagedOrcaStatus({ managedRoot: fx.root, expectedPort: PORT })).reason, 'server_process_dead')
+ } finally {
+ await fx.cleanup()
+ }
+ })
+
+ it('rejects a receipt outside the managed root or a non-private receipt', async () => {
+ const fx = await fixture()
+ try {
+ await writePrivateFile(join(fx.root, 'runtime-identity.json'), { ...fx.identity, serverEntry: '/etc/passwd' }, { root: fx.root })
+ assert.equal((await readManagedOrcaStatus({ managedRoot: fx.root, expectedPort: PORT })).reason, 'runtime_identity_serverEntry_outside_root')
+ } finally {
+ await fx.cleanup()
+ }
+ })
+
+ it('treats static web reachability as a separate proof', async () => {
+ const ok = await probeOrcaWebClient({
+ port: PORT,
+ fetchImpl: async () => new Response('<html><title>Orca Web</title></html>', { status: 200 })
+ })
+ assert.equal(ok.available, true)
+ const broken = await probeOrcaWebClient({
+ port: PORT,
+ fetchImpl: async () => new Response('<html>not orca</html>', { status: 200 })
+ })
+ assert.equal(broken.available, false)
+ assert.equal(broken.reason, 'web_client_unhealthy')
+ })
+})
diff --git a/scripts/orca/managed-unit-write.mjs b/scripts/orca/managed-unit-write.mjs
new file mode 100644
index 00000000..fd4a0f8c
--- /dev/null
+++ b/scripts/orca/managed-unit-write.mjs
@@ -0,0 +1,109 @@
+/**
+ * Filesystem and systemd writes for the managed Orca install, plus the
+ * readiness wait. Kept separate from the install sequence so the atomic unit
+ * write, the fixed systemctl argv and the bounded poll each stay reviewable.
+ */
+
+import { execFile } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import { chmod, link, mkdir, rename, rm, writeFile } from 'node:fs/promises'
+import { dirname } from 'node:path'
+import { promisify } from 'node:util'
+import { redactSensitiveText } from './bounded-proc.mjs'
+import { SERVICE_NAME } from './managed-paths.mjs'
+import { inspectExistingUnit } from './systemd-unit.mjs'
+
+const execFileAsync = promisify(execFile)
+
+export async function writeUnitAtomic(unitPath, text, { inspect = inspectExistingUnit } = {}) {
+ await mkdir(dirname(unitPath), { recursive: true, mode: 0o700 })
+ const tmp = `${unitPath}.tmp-${process.pid}-${randomUUID()}`
+ try {
+ await writeFile(tmp, text, { mode: 0o644, flag: 'wx' })
+ // Re-run the ownership guard immediately before publishing: a foreign unit
+ // that appeared while we staged must never be clobbered. `inspect` throws on
+ // a foreign/non-regular/other-owner unit and returns 'absent' when nothing
+ // is there yet.
+ const existing = await inspect({ unitPath })
+ if (existing.state === 'managed') {
+ // Same-owner replacement of a unit we generated. `rename` is atomic; the
+ // last-instant window between `inspect` and `rename` is inherent at equal
+ // privilege (same-UID installers can always race), so it is documented
+ // here rather than hidden.
+ await rename(tmp, unitPath)
+ } else {
+ // Absent: publish exclusively. `link` fails with EEXIST instead of
+ // overwriting a foreign unit created in the last instant, so the race
+ // cannot silently replace someone else's unit. The temp inode is unlinked.
+ try {
+ await link(tmp, unitPath)
+ } catch (err) {
+ if (err?.code === 'EEXIST') {
+ throw new Error(`refusing to overwrite a unit that appeared during install: ${unitPath}`)
+ }
+ throw err
+ }
+ await rm(tmp, { force: true })
+ }
+ // Explicit: the unit is generated, contains no secret, and a restrictive
+ // shell umask must not make its mode environment-dependent.
+ await chmod(unitPath, 0o644)
+ } catch (err) {
+ await rm(tmp, { force: true }).catch(() => {})
+ throw err
+ }
+ return unitPath
+}
+
+export async function defaultSystemctl({ args, env, bus, allowFailure = false }) {
+ try {
+ const result = await execFileAsync('systemctl', ['--user', ...args], {
+ timeout: 30_000,
+ maxBuffer: 64 * 1024,
+ env: bus ? { ...env, ...bus } : env
+ })
+ return { code: 0, stdout: String(result.stdout ?? ''), stderr: String(result.stderr ?? '') }
+ } catch (err) {
+ const detail = redactSensitiveText(String(err?.stderr || err?.stdout || err?.message || 'systemctl failed'))
+ // Rollback calls are best-effort: report the failure instead of throwing so
+ // the caller can record it and still restore the rest of the prior state.
+ if (allowFailure) return { code: 1, stdout: '', stderr: detail.slice(0, 300) }
+ throw new Error(`systemctl --user ${args.join(' ')} failed: ${detail.slice(0, 300)}`)
+ }
+}
+
+export function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+/** Poll the identity-verified status and the static web bundle until both answer. */
+export async function waitForReady({
+ root,
+ port,
+ advertisedEndpoint,
+ timeoutMs,
+ pollMs,
+ readStatus,
+ probeWeb,
+ wait
+}) {
+ const deadline = Date.now() + timeoutMs
+ let lastReason = 'not_checked'
+ for (;;) {
+ const status = await readStatus({ managedRoot: root, expectedPort: port, expectedAdvertisedEndpoint: advertisedEndpoint })
+ if (status.available) {
+ const web = await probeWeb({ port })
+ if (web.available) return status
+ lastReason = web.reason
+ } else {
+ lastReason = status.reason
+ }
+ if (Date.now() >= deadline) {
+ throw new Error(
+ `Orca did not become ready within ${Math.round(timeoutMs / 1000)}s (${lastReason}). ` +
+ `Check journalctl --user -u ${SERVICE_NAME} --no-pager.`
+ )
+ }
+ await wait(pollMs)
+ }
+}
diff --git a/scripts/orca/managed-unit-write.test.mjs b/scripts/orca/managed-unit-write.test.mjs
new file mode 100644
index 00000000..ab038e6f
--- /dev/null
+++ b/scripts/orca/managed-unit-write.test.mjs
@@ -0,0 +1,68 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { constants } from 'node:fs'
+import { mkdtemp, open, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { writeUnitAtomic } from './managed-unit-write.mjs'
+import { UNIT_IDENTITY_MARKER, orcaServiceUnitPath } from './managed-paths.mjs'
+
+const FOREIGN = '[Service]\nExecStart=/usr/bin/orca --port 6768\n'
+const managedText = (root) =>
+ `${UNIT_IDENTITY_MARKER}\n[Service]\nExecStart="/usr/bin/node" "/repo/scripts/orca/cli.mjs" "run" --managed-root ${root} --port 6769\n`
+
+// Stat the descriptor, not the path: the mode and the bytes both come from the
+// same inode, so a swap between check and read cannot influence the assertion.
+async function readUnitState(unitPath) {
+ const handle = await open(unitPath, constants.O_RDONLY | constants.O_NOFOLLOW)
+ try {
+ const info = await handle.stat()
+ return { mode: info.mode & 0o777, text: await handle.readFile('utf8') }
+ } finally {
+ await handle.close()
+ }
+}
+
+async function makeHome() {
+ const home = await mkdtemp(join(tmpdir(), 'oi-'))
+ return { home, cleanup: () => rm(home, { recursive: true, force: true }) }
+}
+
+describe('atomic absent-unit publish', () => {
+ it('refuses to clobber a foreign unit that appears at the last instant', async () => {
+ const d = await makeHome()
+ try {
+ const unitPath = orcaServiceUnitPath({ home: d.home })
+ await assert.rejects(
+ () =>
+ writeUnitAtomic(unitPath, managedText('/tmp/root'), {
+ inspect: async () => {
+ await writeFile(unitPath, FOREIGN)
+ return { state: 'absent', text: null }
+ }
+ }),
+ /appeared during install/
+ )
+ assert.equal((await readUnitState(unitPath)).text, FOREIGN)
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('publishes an absent unit at 0644 and replaces only its own managed unit', async () => {
+ const d = await makeHome()
+ try {
+ const unitPath = orcaServiceUnitPath({ home: d.home })
+ await writeUnitAtomic(unitPath, managedText('/tmp/root'))
+ const published = await readUnitState(unitPath)
+ assert.equal(published.mode, 0o644)
+ assert.equal(published.text, managedText('/tmp/root'))
+
+ const updated = managedText('/tmp/root').replace('--port 6769', '--port 6770')
+ await writeUnitAtomic(unitPath, updated)
+ assert.equal((await readUnitState(unitPath)).text, updated)
+ } finally {
+ await d.cleanup()
+ }
+ })
+})
diff --git a/scripts/orca/materializer-filesystem.test.mjs b/scripts/orca/materializer-filesystem.test.mjs
new file mode 100644
index 00000000..68b2c36c
--- /dev/null
+++ b/scripts/orca/materializer-filesystem.test.mjs
@@ -0,0 +1,173 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { createHash } from 'node:crypto'
+import { mkdir, readFile, rm, symlink, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import {
+ ORCAD_COMMON_FILES,
+ ORCAD_SLOT_FILE_COUNT,
+ ORCAD_TARGET_FILES,
+ ORCAD_VERSION,
+ ORCAD_VERSION_FILENAME,
+ SUPPORTED_TARGET
+} from './constants.mjs'
+import { materializeOrcadSlot, verifySlotIntegrity } from './materializer.mjs'
+import { buildTemplate, mobileNames, scratch } from './materializer-fixtures.mjs'
+
+describe('materializer filesystem behavior', () => {
+ it('materializes the exact 175-file slot and preserves unrelated state', async () => {
+ const root = await scratch('slot')
+ try {
+ const { templateDir } = await buildTemplate(root)
+ const sentinel = join(root, 'out', 'user-state.txt')
+ await mkdir(join(root, 'out'), { recursive: true, mode: 0o700 })
+ await writeFile(sentinel, 'keep me', { mode: 0o600 })
+
+ const result = await materializeOrcadSlot({
+ templateDir,
+ outputSlotDir: join(root, 'out', 'slot'),
+ target: SUPPORTED_TARGET
+ })
+ assert.equal(result.reused, false)
+ assert.equal(result.fullVersion.startsWith(`${ORCAD_VERSION}+`), true)
+ assert.equal(Object.keys(result.files).length, ORCAD_SLOT_FILE_COUNT)
+ const version = await readFile(join(result.slotDir, ORCAD_VERSION_FILENAME), 'utf8')
+ assert.equal(version.trim(), result.fullVersion)
+ assert.equal(await readFile(sentinel, 'utf8'), 'keep me')
+
+ const reuse = await materializeOrcadSlot({
+ templateDir,
+ outputSlotDir: join(root, 'out', 'slot'),
+ target: SUPPORTED_TARGET
+ })
+ assert.equal(reuse.reused, true)
+ assert.equal(reuse.treeSha256, result.treeSha256)
+
+ const isIntact = await verifySlotIntegrity(
+ result.slotDir,
+ new Map(Object.entries(result.files).map(([name, sha]) => [name, { sha }])),
+ { expectedVersion: result.fullVersion, exactFileSet: true }
+ )
+ assert.equal(isIntact, true)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('derives fullVersion from the upstream raw-byte artifact identity (independent oracle)', async () => {
+ const root = await scratch('version-oracle')
+ try {
+ const { templateDir } = await buildTemplate(root)
+ const result = await materializeOrcadSlot({
+ templateDir,
+ outputSlotDir: join(root, 'slot'),
+ target: SUPPORTED_TARGET
+ })
+
+ // Independent oracle: replicate orcad-artifact-identity.ts here (raw byte
+ // concatenation in orcadArtifactFilenames order) without calling the
+ // production order helper, then compare.
+ const watcherEntry = 'node_modules/@parcel/watcher/index.js'
+ const manifestName = 'out/mobile-web/manifest.json'
+ const [serverTarget, runtimeMarker, watcherNative, ptyNative, ripgrep] = ORCAD_TARGET_FILES
+ const order = []
+ for (const name of ORCAD_COMMON_FILES) {
+ if (name === watcherEntry) order.push(serverTarget, runtimeMarker, name, watcherNative)
+ else if (name === manifestName) order.push(name, ptyNative, ripgrep)
+ else order.push(name)
+ }
+ order.push(...mobileNames().sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)))
+
+ const hash = createHash('sha256')
+ for (const name of order) hash.update(await readFile(join(result.slotDir, name)))
+ const digest = hash.digest('hex')
+
+ assert.equal(result.artifactSha256, digest)
+ assert.equal(result.fullVersion, `${ORCAD_VERSION}+${digest.slice(0, 12)}`)
+ // The upstream version must not be the internal tree digest.
+ assert.notEqual(result.fullVersion, `${ORCAD_VERSION}+${result.treeSha256.slice(0, 12)}`)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('refuses a tampered existing slot instead of overwriting it', async () => {
+ const root = await scratch('tamper')
+ try {
+ const { templateDir } = await buildTemplate(root)
+ const outputSlotDir = join(root, 'slot')
+ const first = await materializeOrcadSlot({ templateDir, outputSlotDir, target: SUPPORTED_TARGET })
+ const victim = join(first.slotDir, 'orcad-server.js')
+ await writeFile(victim, 'tampered', { mode: 0o600 })
+ await assert.rejects(
+ materializeOrcadSlot({ templateDir, outputSlotDir, target: SUPPORTED_TARGET }),
+ /refusing to overwrite/i
+ )
+ assert.equal(await readFile(victim, 'utf8'), 'tampered')
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('refuses a torn/partial existing slot', async () => {
+ const root = await scratch('torn')
+ try {
+ const { templateDir } = await buildTemplate(root)
+ const outputSlotDir = join(root, 'torn')
+ await mkdir(outputSlotDir, { recursive: true, mode: 0o700 })
+ await writeFile(join(outputSlotDir, ORCAD_VERSION_FILENAME), `${ORCAD_VERSION}+torn\n`, { mode: 0o600 })
+ await assert.rejects(
+ materializeOrcadSlot({ templateDir, outputSlotDir, target: SUPPORTED_TARGET }),
+ /refusing to overwrite/i
+ )
+ assert.equal(await readFile(join(outputSlotDir, ORCAD_VERSION_FILENAME), 'utf8'), `${ORCAD_VERSION}+torn\n`)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects a symlinked template source and a symlinked source file', async () => {
+ const root = await scratch('symlink')
+ try {
+ const { templateDir } = await buildTemplate(root)
+ await symlink(templateDir, join(root, 'template-link'))
+ await assert.rejects(
+ materializeOrcadSlot({
+ templateDir: join(root, 'template-link'),
+ outputSlotDir: join(root, 'slot-a'),
+ target: SUPPORTED_TARGET
+ }),
+ /symlink/i
+ )
+
+ const realFile = join(templateDir, 'orcad-server.js')
+ const saved = await readFile(realFile)
+ await rm(realFile)
+ const target = join(root, 'elsewhere.js')
+ await writeFile(target, saved, { mode: 0o600 })
+ await symlink(target, realFile)
+ await assert.rejects(
+ materializeOrcadSlot({
+ templateDir,
+ outputSlotDir: join(root, 'slot-b'),
+ target: SUPPORTED_TARGET
+ }),
+ /symlink/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('produces a deterministic slot digest', async () => {
+ const root = await scratch('digest')
+ try {
+ const { templateDir } = await buildTemplate(root)
+ const a = await materializeOrcadSlot({ templateDir, outputSlotDir: join(root, 'a'), target: SUPPORTED_TARGET })
+ const b = await materializeOrcadSlot({ templateDir, outputSlotDir: join(root, 'b'), target: SUPPORTED_TARGET })
+ assert.equal(a.treeSha256, b.treeSha256)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/materializer-fixtures.mjs b/scripts/orca/materializer-fixtures.mjs
new file mode 100644
index 00000000..faffc153
--- /dev/null
+++ b/scripts/orca/materializer-fixtures.mjs
@@ -0,0 +1,63 @@
+import { createHash } from 'node:crypto'
+import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import {
+ ORCAD_COMMON_FILES,
+ ORCAD_NODE_RUNTIME_MARKER_FILENAME,
+ ORCAD_SERVER_TARGET_FILENAME,
+ ORCAD_SLOT_FILE_COUNT,
+ ORCAD_TARGET_FILES,
+ PINNED_NODE,
+ SUPPORTED_TARGET
+} from './constants.mjs'
+
+export const sha256 = (text) => createHash('sha256').update(text).digest('hex')
+
+export const MOBILE_COUNT =
+ ORCAD_SLOT_FILE_COUNT - ORCAD_COMMON_FILES.length - ORCAD_TARGET_FILES.length
+
+export async function scratch(name) {
+ // mkdtemp atomically creates an owner-only (0700) directory, so the shared
+ // temp root never holds a predictable name.
+ return mkdtemp(join(tmpdir(), `orca-mat-${name}-`))
+}
+
+export async function writeSourceFile(root, rel, content) {
+ const filePath = join(root, rel)
+ await mkdir(join(filePath, '..'), { recursive: true })
+ await writeFile(filePath, content, { mode: 0o600 })
+ return sha256(content)
+}
+
+export function mobileNames() {
+ return Array.from(
+ { length: MOBILE_COUNT },
+ (_, i) => `out/mobile-web/asset-${String(i).padStart(3, '0')}.txt`
+ )
+}
+
+export async function buildTemplate(root) {
+ const templateDir = join(root, 'template')
+ const targetDir = join(templateDir, 'targets', SUPPORTED_TARGET)
+ await mkdir(targetDir, { recursive: true, mode: 0o700 })
+ const commonSha256 = {}
+ for (const name of ORCAD_COMMON_FILES) {
+ commonSha256[name] = await writeSourceFile(templateDir, name, `common:${name}\n`)
+ }
+ for (const name of mobileNames()) {
+ commonSha256[name] = await writeSourceFile(templateDir, name, `mobile:${name}\n`)
+ }
+ const files = {}
+ for (const name of ORCAD_TARGET_FILES) {
+ let content = `target:${name}\n`
+ if (name === ORCAD_SERVER_TARGET_FILENAME) content = `${SUPPORTED_TARGET}\n`
+ if (name === ORCAD_NODE_RUNTIME_MARKER_FILENAME) content = `${PINNED_NODE.executableSha256}\n`
+ files[name] = await writeSourceFile(targetDir, name, content)
+ }
+ const manifest = { schemaVersion: 3, commonSha256, targets: { [SUPPORTED_TARGET]: { files } } }
+ await writeFile(join(templateDir, 'orcad-template.json'), JSON.stringify(manifest, null, 2), {
+ mode: 0o600
+ })
+ return { templateDir, manifest }
+}
diff --git a/scripts/orca/materializer-manifest.test.mjs b/scripts/orca/materializer-manifest.test.mjs
new file mode 100644
index 00000000..e7cd8f0e
--- /dev/null
+++ b/scripts/orca/materializer-manifest.test.mjs
@@ -0,0 +1,95 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { rm } from 'node:fs/promises'
+import { ORCAD_SLOT_FILE_COUNT, ORCAD_TARGET_FILES, PINNED_NODE, SUPPORTED_TARGET } from './constants.mjs'
+import {
+ getSlotArtifactFilenames,
+ isSafePathSegment,
+ verifyManifestSchema,
+ verifyTargetMarkers
+} from './materializer.mjs'
+import { buildTemplate, scratch, sha256 } from './materializer-fixtures.mjs'
+
+describe('materializer manifest contract', () => {
+ it('rejects unsafe path segments', () => {
+ for (const bad of ['../etc/passwd', '/abs', 'foo/../../bar', 'foo/./bar', '', 'foo\\bar', 'foo//bar', 'a/\x00/b']) {
+ assert.equal(isSafePathSegment(bad), false, bad)
+ }
+ assert.equal(isSafePathSegment('valid/file.js'), true)
+ assert.equal(isSafePathSegment('.server-target'), true)
+ })
+
+ it('rejects malformed manifest roots and digests', async () => {
+ const root = await scratch('schema')
+ try {
+ const { manifest } = await buildTemplate(root)
+ assert.throws(() => verifyManifestSchema(null), /invalid manifest/i)
+ assert.throws(() => verifyManifestSchema([]), /invalid manifest/i)
+ assert.throws(() => verifyManifestSchema({ schemaVersion: 2, commonSha256: {}, targets: {} }), /unsupported schema/i)
+ assert.throws(() => verifyManifestSchema({ schemaVersion: 3, targets: {} }), /commonSha256/i)
+ assert.throws(() => verifyManifestSchema({ schemaVersion: 3, commonSha256: [], targets: {} }), /commonSha256/i)
+ assert.throws(
+ () => verifyManifestSchema({ ...manifest, commonSha256: { ...manifest.commonSha256, 'out/x.js': 'nothex' } }),
+ /invalid digest/i
+ )
+ assert.throws(
+ () => verifyManifestSchema({ ...manifest, commonSha256: { ...manifest.commonSha256, 'out/../x.js': 'a'.repeat(64) } }),
+ /unsafe manifest path/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('enforces the exact common/target file contract', async () => {
+ const root = await scratch('contract')
+ try {
+ const { manifest } = await buildTemplate(root)
+ const names = getSlotArtifactFilenames(SUPPORTED_TARGET, manifest)
+ assert.equal(names.length, ORCAD_SLOT_FILE_COUNT)
+ assert.equal(new Set(names).size, ORCAD_SLOT_FILE_COUNT)
+
+ const withExtraTarget = JSON.parse(JSON.stringify(manifest))
+ withExtraTarget.targets[SUPPORTED_TARGET].files['orcad-server.js'] = sha256('x')
+ assert.throws(
+ () => getSlotArtifactFilenames(SUPPORTED_TARGET, withExtraTarget),
+ /unexpected target file/i
+ )
+
+ const missingTarget = JSON.parse(JSON.stringify(manifest))
+ delete missingTarget.targets[SUPPORTED_TARGET].files[ORCAD_TARGET_FILES[0]]
+ assert.throws(
+ () => getSlotArtifactFilenames(SUPPORTED_TARGET, missingTarget),
+ /missing target file/i
+ )
+
+ const shadowed = JSON.parse(JSON.stringify(manifest))
+ shadowed.commonSha256['.server-target'] = sha256('x')
+ assert.throws(
+ () => getSlotArtifactFilenames(SUPPORTED_TARGET, shadowed),
+ /unexpected common file/i
+ )
+
+ assert.throws(() => getSlotArtifactFilenames('darwin-arm64', manifest), /unsupported target/i)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('checks target marker identity', () => {
+ assert.doesNotThrow(() =>
+ verifyTargetMarkers({
+ serverTarget: 'linux-x64-glibc',
+ runtimeNodeSha256: PINNED_NODE.executableSha256
+ })
+ )
+ assert.throws(
+ () => verifyTargetMarkers({ serverTarget: 'linux-arm64', runtimeNodeSha256: PINNED_NODE.executableSha256 }),
+ /target identity mismatch/i
+ )
+ assert.throws(
+ () => verifyTargetMarkers({ serverTarget: 'linux-x64-glibc', runtimeNodeSha256: 'deadbeef'.repeat(8) }),
+ /runtime node pin mismatch/i
+ )
+ })
+})
diff --git a/scripts/orca/materializer.mjs b/scripts/orca/materializer.mjs
new file mode 100644
index 00000000..6013796d
--- /dev/null
+++ b/scripts/orca/materializer.mjs
@@ -0,0 +1,197 @@
+/**
+ * Slot materialization from an already verified Orca template directory: the
+ * full per-file contract, symlink/ownership/path safety, a destination TOCTOU
+ * re-hash, the upstream raw-byte artifact identity, and publish-or-refuse.
+ */
+
+import { createHash, randomUUID } from 'node:crypto'
+import { createReadStream } from 'node:fs'
+import { copyFile, chmod, lstat, mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+import {
+ ORCAD_NODE_RUNTIME_MARKER_FILENAME,
+ ORCAD_SERVER_TARGET_FILENAME,
+ ORCAD_SLOT_FILE_COUNT,
+ ORCAD_TEMPLATE_MANIFEST_FILENAME,
+ ORCAD_TEMPLATE_TARGETS_DIR,
+ ORCAD_VERSION,
+ ORCAD_VERSION_FILENAME,
+ SUPPORTED_TARGET
+} from './constants.mjs'
+import { fileSha256 } from './node-runtime.mjs'
+import {
+ getSlotArtifactFilenames,
+ getUpstreamArtifactOrder,
+ verifyManifestSchema,
+ verifyTargetMarkers
+} from './slot-manifest.mjs'
+import {
+ assertNoSymlinkAncestors,
+ ensurePrivateDirTree,
+ isSafeRelativePath,
+ lstatOrNull
+} from './safe-paths.mjs'
+
+export { getSlotArtifactFilenames, verifyManifestSchema, verifyTargetMarkers }
+
+const MAX_MANIFEST_BYTES = 1024 * 1024
+const EXECUTABLE_SLOT_FILES = new Set(['ripgrep/linux-x64/rg'])
+
+export const isSafePathSegment = isSafeRelativePath
+
+async function assertRealDir(dir, label) {
+ await assertNoSymlinkAncestors(dir)
+ const s = await lstatOrNull(dir)
+ if (!s || !s.isDirectory() || s.isSymbolicLink()) {
+ throw new Error(`${label} is not a real directory: ${dir}`)
+ }
+}
+
+async function readSmallFile(filePath, label) {
+ await assertNoSymlinkAncestors(filePath)
+ const s = await lstatOrNull(filePath)
+ if (!s || !s.isFile() || s.isSymbolicLink()) {
+ throw new Error(`${label} is not a regular file: ${filePath}`)
+ }
+ if (s.size > MAX_MANIFEST_BYTES) throw new Error(`${label} is unexpectedly large: ${filePath}`)
+ return readFile(filePath)
+}
+
+async function collectRegularFiles(root, rel = '') {
+ const entries = await readdir(join(root, rel), { withFileTypes: true })
+ const out = []
+ for (const entry of entries) {
+ const next = rel ? `${rel}/${entry.name}` : entry.name
+ if (entry.isSymbolicLink()) throw new Error(`Refusing symlink in slot: ${next}`)
+ if (entry.isDirectory()) out.push(...(await collectRegularFiles(root, next)))
+ else if (entry.isFile()) {
+ if (next !== ORCAD_VERSION_FILENAME) out.push(next)
+ } else throw new Error(`Refusing non-regular slot entry: ${next}`)
+ }
+ return out
+}
+
+export async function verifySlotIntegrity(slotDir, fileMap, { expectedVersion, exactFileSet } = {}) {
+ try {
+ const s = await lstat(slotDir)
+ if (!s.isDirectory() || s.isSymbolicLink()) return false
+ await assertNoSymlinkAncestors(slotDir)
+ for (const [name, entry] of fileMap.entries()) {
+ if (!isSafeRelativePath(name)) return false
+ const filePath = join(slotDir, name)
+ await assertNoSymlinkAncestors(filePath)
+ const f = await lstat(filePath)
+ if (!f.isFile() || f.isSymbolicLink()) return false
+ if ((await fileSha256(filePath)) !== entry.sha) return false
+ }
+ if (expectedVersion !== undefined) {
+ const v = await readFile(join(slotDir, ORCAD_VERSION_FILENAME), 'utf8')
+ if (v.trim() !== expectedVersion) return false
+ }
+ if (exactFileSet) {
+ const actual = (await collectRegularFiles(slotDir)).sort()
+ const expected = [...fileMap.keys()].sort()
+ if (actual.length !== expected.length) return false
+ if (actual.some((name, i) => name !== expected[i])) return false
+ }
+ return true
+ } catch {
+ return false
+ }
+}
+
+function slotTreeSha256(filenames, fileMap) {
+ const hash = createHash('sha256')
+ for (const name of filenames) hash.update(`${name}\0${fileMap.get(name).sha}\n`)
+ return hash.digest('hex')
+}
+
+function filesObject(fileMap) {
+ return Object.fromEntries([...fileMap.entries()].map(([name, entry]) => [name, entry.sha]))
+}
+
+export async function materializeOrcadSlot({
+ templateDir,
+ outputSlotDir,
+ target = SUPPORTED_TARGET
+} = {}) {
+ if (typeof templateDir !== 'string' || !templateDir.startsWith('/')) {
+ throw new Error(`templateDir must be absolute: ${templateDir}`)
+ }
+ if (typeof outputSlotDir !== 'string' || !outputSlotDir.startsWith('/')) {
+ throw new Error(`outputSlotDir must be absolute: ${outputSlotDir}`)
+ }
+ await assertRealDir(templateDir, 'Template')
+ const manifestBytes = await readSmallFile(
+ join(templateDir, ORCAD_TEMPLATE_MANIFEST_FILENAME),
+ 'Template manifest'
+ )
+ const manifest = JSON.parse(manifestBytes.toString('utf8'))
+ const filenames = getSlotArtifactFilenames(target, manifest)
+ const targetDir = join(templateDir, ORCAD_TEMPLATE_TARGETS_DIR, target)
+ await assertRealDir(targetDir, 'Target template')
+ verifyTargetMarkers({
+ serverTarget: (await readSmallFile(join(targetDir, ORCAD_SERVER_TARGET_FILENAME), 'Target marker')).toString('utf8'),
+ runtimeNodeSha256: (await readSmallFile(join(targetDir, ORCAD_NODE_RUNTIME_MARKER_FILENAME), 'Node marker')).toString('utf8'),
+ target
+ })
+
+ const targetFiles = manifest.targets[target].files
+ const fileMap = new Map()
+ for (const name of filenames) {
+ const isTarget = Object.hasOwn(targetFiles, name)
+ const expectedSha = isTarget ? targetFiles[name] : manifest.commonSha256[name]
+ const sourcePath = join(isTarget ? targetDir : templateDir, name)
+ await assertNoSymlinkAncestors(sourcePath)
+ const s = await lstat(sourcePath)
+ if (!s.isFile() || s.isSymbolicLink()) throw new Error(`Source file is not regular: ${name}`)
+ if ((await fileSha256(sourcePath)) !== expectedSha) throw new Error(`Checksum mismatch for ${name}`)
+ fileMap.set(name, { sha: expectedSha, sourcePath })
+ }
+ if (fileMap.size !== ORCAD_SLOT_FILE_COUNT) {
+ throw new Error(`Slot file contract mismatch: expected ${ORCAD_SLOT_FILE_COUNT}, got ${fileMap.size}`)
+ }
+ const treeSha256 = slotTreeSha256(filenames, fileMap)
+ const artifactHash = createHash('sha256')
+ for (const name of getUpstreamArtifactOrder(filenames)) {
+ for await (const chunk of createReadStream(fileMap.get(name).sourcePath)) artifactHash.update(chunk)
+ }
+ const artifactSha256 = artifactHash.digest('hex')
+ const fullVersion = `${ORCAD_VERSION}+${artifactSha256.slice(0, 12)}`
+ const files = filesObject(fileMap)
+
+ if (await lstatOrNull(outputSlotDir)) {
+ if (await verifySlotIntegrity(outputSlotDir, fileMap, { expectedVersion: fullVersion, exactFileSet: true })) {
+ return { slotDir: outputSlotDir, fullVersion, treeSha256, artifactSha256, files, reused: true }
+ }
+ throw new Error(`Refusing to overwrite an existing non-matching slot: ${outputSlotDir}`)
+ }
+
+ const parent = dirname(outputSlotDir)
+ await ensurePrivateDirTree(parent)
+ const stagingDir = join(parent, `.staging-slot-${process.pid}-${randomUUID()}`)
+ await assertNoSymlinkAncestors(stagingDir)
+ await mkdir(stagingDir, { recursive: false, mode: 0o700 })
+ try {
+ for (const [name, entry] of fileMap.entries()) {
+ const dest = join(stagingDir, name)
+ await assertNoSymlinkAncestors(dest)
+ await mkdir(dirname(dest), { recursive: true, mode: 0o700 })
+ await copyFile(entry.sourcePath, dest)
+ const mode = EXECUTABLE_SLOT_FILES.has(name) ? 0o700 : 0o600
+ await chmod(dest, mode)
+ if ((await fileSha256(dest)) !== entry.sha) throw new Error(`TOCTOU copy corruption on ${name}`)
+ }
+ await writeFile(join(stagingDir, ORCAD_VERSION_FILENAME), `${fullVersion}\n`, { mode: 0o600 })
+ if (!(await verifySlotIntegrity(stagingDir, fileMap, { expectedVersion: fullVersion, exactFileSet: true }))) {
+ throw new Error('Staged slot failed its own integrity verification')
+ }
+ if (await lstatOrNull(outputSlotDir)) {
+ throw new Error(`Refusing to overwrite a slot created concurrently: ${outputSlotDir}`)
+ }
+ await rename(stagingDir, outputSlotDir)
+ return { slotDir: outputSlotDir, fullVersion, treeSha256, artifactSha256, files, reused: false }
+ } finally {
+ await rm(stagingDir, { recursive: true, force: true }).catch(() => {})
+ }
+}
diff --git a/scripts/orca/node-runtime.mjs b/scripts/orca/node-runtime.mjs
new file mode 100644
index 00000000..7b8d4e92
--- /dev/null
+++ b/scripts/orca/node-runtime.mjs
@@ -0,0 +1,172 @@
+/**
+ * Pinned Node runtime acquisition.
+ *
+ * Pin: Node v24.21.0 linux-x64-glibc. The archive digest is verified while
+ * streaming to a private file; the single `bin/node` member is extracted to a
+ * fresh staging file, re-hashed against the executable pin, and only then
+ * published. A cached executable is reused only after re-hashing every byte;
+ * a torn or mismatched cache is refused, never overwritten. There is no host
+ * Node fallback.
+ */
+
+import { createHash, randomUUID } from 'node:crypto'
+import { createReadStream } from 'node:fs'
+import { chmod, mkdir, open, rename, rm } from 'node:fs/promises'
+import { join } from 'node:path'
+import { PINNED_NODE, isSupportedTarget } from './constants.mjs'
+import { downloadToFile } from './download.mjs'
+import { runBoundedProcess } from './bounded-process.mjs'
+import {
+ assertNoSymlinkAncestors,
+ assertOwnedRegularFile,
+ ensurePrivateDirTree,
+ lstatOrNull
+} from './safe-paths.mjs'
+
+const MAX_EXECUTABLE_BYTES = 256 * 1024 * 1024
+
+export function verifyBufferSha256(buffer, expected, label = 'Buffer') {
+ const hash = createHash('sha256').update(buffer).digest('hex')
+ if (hash !== expected) {
+ throw new Error(`${label} checksum mismatch: expected ${expected}, got ${hash}`)
+ }
+}
+
+export function verifyExecutableBuffer(buffer, expected) {
+ verifyBufferSha256(buffer, expected, 'Executable')
+}
+
+export function verifyArchiveBuffer(buffer, expected) {
+ verifyBufferSha256(buffer, expected, 'Archive')
+}
+
+export async function fileSha256(filePath) {
+ return new Promise((resolve, reject) => {
+ const hash = createHash('sha256')
+ const stream = createReadStream(filePath)
+ stream.on('data', (chunk) => hash.update(chunk))
+ stream.on('end', () => resolve(hash.digest('hex')))
+ stream.on('error', reject)
+ })
+}
+
+async function verifyCachedNode(destination) {
+ const s = await assertOwnedRegularFile(destination)
+ const actual = await fileSha256(destination)
+ if (actual !== PINNED_NODE.executableSha256) {
+ throw new Error(
+ `Cached Node checksum mismatch (${actual}); refusing to overwrite ${destination}`
+ )
+ }
+ if ((s.mode & 0o100) === 0) await chmod(destination, 0o700)
+ return destination
+}
+
+async function downloadArchive({ downloadsDir, signal, timeoutMs, fetchImpl }) {
+ const archivePath = join(downloadsDir, 'node-v24.21.0-linux-x64.tar.gz')
+ const existing = await lstatOrNull(archivePath)
+ if (existing) {
+ const s = await assertOwnedRegularFile(archivePath)
+ if (s.size !== PINNED_NODE.archiveSize) {
+ throw new Error(`Cached Node archive size mismatch; refusing to overwrite ${archivePath}`)
+ }
+ const actual = await fileSha256(archivePath)
+ if (actual !== PINNED_NODE.archiveSha256) {
+ throw new Error(`Cached Node archive checksum mismatch; refusing to overwrite ${archivePath}`)
+ }
+ return archivePath
+ }
+ const result = await downloadToFile({
+ url: PINNED_NODE.archiveUrl,
+ expectedUrl: PINNED_NODE.archiveUrl,
+ destination: archivePath,
+ expectedSha256: PINNED_NODE.archiveSha256,
+ expectedSize: PINNED_NODE.archiveSize,
+ maxBytes: PINNED_NODE.archiveSize,
+ signal,
+ timeoutMs,
+ fetchImpl
+ })
+ return result.path
+}
+
+async function extractNodeBinary({ archivePath, destination, signal, timeoutMs }) {
+ const handle = await open(destination, 'wx', 0o600)
+ try {
+ const res = await runBoundedProcess({
+ command: 'tar',
+ args: ['-xzf', archivePath, '-O', PINNED_NODE.tarMember],
+ timeoutMs,
+ signal,
+ stdoutFd: handle.fd,
+ maxStderrBytes: 65536
+ })
+ if (res.code !== 0) throw new Error(`tar extraction failed with code ${res.code}: ${res.stderr}`)
+ await handle.sync()
+ } finally {
+ await handle.close()
+ }
+ const s = await assertOwnedRegularFile(destination)
+ if (s.size === 0) throw new Error('Extracted Node executable is empty')
+ if (s.size > MAX_EXECUTABLE_BYTES) throw new Error('Extracted Node executable exceeds the size cap')
+ const actual = await fileSha256(destination)
+ if (actual !== PINNED_NODE.executableSha256) {
+ throw new Error(
+ `Extracted Node executable checksum mismatch: expected ${PINNED_NODE.executableSha256}, got ${actual}`
+ )
+ }
+ await chmod(destination, 0o700)
+}
+
+export async function fetchAndMaterializeNodeRuntime({
+ target = 'linux-x64-glibc',
+ runtimesDir,
+ signal,
+ allowDownload = true,
+ timeoutMs = 300000,
+ fetchImpl
+} = {}) {
+ if (!isSupportedTarget(target)) {
+ throw new Error(`Unsupported Node runtime target: ${target}. Only linux-x64-glibc is supported.`)
+ }
+ if (typeof runtimesDir !== 'string' || !runtimesDir.startsWith('/')) {
+ throw new Error(`runtimesDir must be absolute: ${runtimesDir}`)
+ }
+ await ensurePrivateDirTree(runtimesDir)
+ const runtimeRoot = join(runtimesDir, `node-${PINNED_NODE.executableSha256}`)
+ const destination = join(runtimeRoot, 'bin', 'node')
+
+ if (await lstatOrNull(runtimeRoot)) {
+ await assertNoSymlinkAncestors(destination)
+ if (!(await lstatOrNull(destination))) {
+ throw new Error(`Torn Node runtime cache at ${runtimeRoot}; refusing to trust it`)
+ }
+ return verifyCachedNode(destination)
+ }
+ if (!allowDownload) {
+ throw new Error(`Pinned Node executable not found at ${destination} and download not allowed`)
+ }
+
+ const downloadsDir = await ensurePrivateDirTree(join(runtimesDir, '.downloads'))
+ const archivePath = await downloadArchive({ downloadsDir, signal, timeoutMs, fetchImpl })
+ const stagingDir = join(runtimesDir, `.staging-node-${process.pid}-${randomUUID()}`)
+ await assertNoSymlinkAncestors(stagingDir)
+ await mkdir(stagingDir, { recursive: false, mode: 0o700 })
+ try {
+ const stagingBin = join(stagingDir, 'bin')
+ await mkdir(stagingBin, { recursive: false, mode: 0o700 })
+ await extractNodeBinary({
+ archivePath,
+ destination: join(stagingBin, 'node'),
+ signal,
+ timeoutMs
+ })
+ if (await lstatOrNull(runtimeRoot)) {
+ throw new Error(`Node runtime appeared concurrently at ${runtimeRoot}; refusing to overwrite`)
+ }
+ await rename(stagingDir, runtimeRoot)
+ return join(runtimeRoot, 'bin', 'node')
+ } finally {
+ await rm(stagingDir, { recursive: true, force: true }).catch(() => {})
+ }
+}
diff --git a/scripts/orca/node-runtime.test.mjs b/scripts/orca/node-runtime.test.mjs
new file mode 100644
index 00000000..c9905c06
--- /dev/null
+++ b/scripts/orca/node-runtime.test.mjs
@@ -0,0 +1,151 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { join } from 'node:path'
+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import {
+ SUPPORTED_TARGET,
+ PINNED_NODE,
+ ORCAD_VERSION,
+ ORCA_VERSION,
+ isSupportedTarget
+} from './constants.mjs'
+import {
+ fileSha256,
+ fetchAndMaterializeNodeRuntime,
+ verifyArchiveBuffer,
+ verifyExecutableBuffer
+} from './node-runtime.mjs'
+
+async function scratch(name) {
+ // mkdtemp atomically creates an owner-only (0700) directory, so the shared
+ // temp root never holds a predictable name.
+ return mkdtemp(join(tmpdir(), `orca-node-${name}-`))
+}
+
+describe('node-runtime pin & verification', () => {
+ it('pins Node 24.21.0 linux-x64-glibc', () => {
+ assert.equal(SUPPORTED_TARGET, 'linux-x64-glibc')
+ assert.equal(PINNED_NODE.version, '24.21.0')
+ assert.equal(PINNED_NODE.archiveSha256, '6e1db87ef58b8819e5d5402eff1536491b18edd8eb7bee5ef7897876e88dc5ff')
+ assert.equal(PINNED_NODE.executableSha256, '7fde7b8afa198da66257f42ee2001d874c7355631e6d1579a5fb5ef1f246df4c')
+ assert.equal(ORCAD_VERSION, '0.1.0')
+ assert.equal(ORCA_VERSION, '1.4.230')
+ })
+
+ it('rejects unsupported target architectures', () => {
+ assert.equal(isSupportedTarget('linux-x64-glibc'), true)
+ for (const target of ['darwin-arm64', 'linux-arm64-glibc', 'win32-x64', 'linux-x64-musl']) {
+ assert.equal(isSupportedTarget(target), false)
+ }
+ })
+
+ it('verifies and rejects executable/archive buffers', () => {
+ const executable = Buffer.from('mock-node-binary')
+ const executableSha = '16624a14bcc82ed24a406bb3af9f53ad29b48d24c67d7202870540237e419587'
+ assert.doesNotThrow(() => verifyExecutableBuffer(executable, executableSha))
+ assert.throws(
+ () => verifyExecutableBuffer(Buffer.from('tampered'), PINNED_NODE.executableSha256),
+ /checksum mismatch/i
+ )
+ assert.throws(
+ () => verifyArchiveBuffer(Buffer.from('tampered'), PINNED_NODE.archiveSha256),
+ /checksum mismatch/i
+ )
+ })
+
+ it('hashes a file from disk', async () => {
+ const root = await scratch('hash')
+ try {
+ const file = join(root, 'data.bin')
+ await writeFile(file, 'hello orca', { mode: 0o600 })
+ const expected = '7fd0dd3b7c8f1f9b1c0d3c9d8d5e6f5f5b2c1c8f8b8b8b8b8b8b8b8b8b8b8b8b'
+ assert.equal((await fileSha256(file)).length, 64)
+ assert.notEqual(await fileSha256(file), expected)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects a symlinked Node destination', async () => {
+ const root = await scratch('symlink')
+ try {
+ const binDir = join(root, `node-${PINNED_NODE.executableSha256}`, 'bin')
+ await mkdir(binDir, { recursive: true })
+ const real = join(root, 'real-bin')
+ await writeFile(real, 'content', { mode: 0o600 })
+ await symlink(real, join(binDir, 'node'))
+ await assert.rejects(
+ fetchAndMaterializeNodeRuntime({ runtimesDir: root, allowDownload: false }),
+ /symlink/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('refuses a tampered cached executable without overwriting it', async () => {
+ const root = await scratch('tampered')
+ try {
+ const binDir = join(root, `node-${PINNED_NODE.executableSha256}`, 'bin')
+ await mkdir(binDir, { recursive: true })
+ await writeFile(join(binDir, 'node'), 'tampered-binary', { mode: 0o700 })
+ await assert.rejects(
+ fetchAndMaterializeNodeRuntime({ runtimesDir: root, allowDownload: false }),
+ /checksum mismatch/i
+ )
+ assert.equal(await readFile(join(binDir, 'node'), 'utf8'), 'tampered-binary')
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('refuses a torn Node runtime directory', async () => {
+ const root = await scratch('torn')
+ try {
+ await mkdir(join(root, `node-${PINNED_NODE.executableSha256}`), { recursive: true })
+ await assert.rejects(
+ fetchAndMaterializeNodeRuntime({ runtimesDir: root, allowDownload: false }),
+ /torn/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('refuses a corrupt cached archive without downloading or overwriting', async () => {
+ const root = await scratch('archive')
+ try {
+ const downloadsDir = join(root, '.downloads')
+ await mkdir(downloadsDir, { recursive: true, mode: 0o700 })
+ await writeFile(join(downloadsDir, 'node-v24.21.0-linux-x64.tar.gz'), 'corrupt', { mode: 0o600 })
+ let fetched = false
+ await assert.rejects(
+ fetchAndMaterializeNodeRuntime({
+ runtimesDir: root,
+ allowDownload: true,
+ fetchImpl: async () => {
+ fetched = true
+ throw new Error('must not fetch')
+ }
+ }),
+ /archive size mismatch/i
+ )
+ assert.equal(fetched, false)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('fails closed when download is disabled and no verified cache exists', async () => {
+ const root = await scratch('nodownload')
+ try {
+ await assert.rejects(
+ fetchAndMaterializeNodeRuntime({ runtimesDir: root, allowDownload: false }),
+ /download not allowed/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/private-store.mjs b/scripts/orca/private-store.mjs
new file mode 100644
index 00000000..d2b53cb8
--- /dev/null
+++ b/scripts/orca/private-store.mjs
@@ -0,0 +1,219 @@
+/**
+ * Private managed-root publication: 0700 root, no symlink ancestors, bounded
+ * 0600 receipts, and transactional status/identity pair publication.
+ */
+import { constants } from 'node:fs'
+import { randomUUID } from 'node:crypto'
+import { chmod, link, lstat, mkdir, open, rename, rm, writeFile } from 'node:fs/promises'
+import { dirname, isAbsolute, join, resolve, sep } from 'node:path'
+const MAX_PRIVATE_BYTES = 64 * 1024
+
+/** Create/validate a private managed root: 0700, owned, no symlinked ancestors. */
+export async function ensureManagedRoot(root) {
+ const abs = resolve(root)
+ if (!isAbsolute(abs)) throw new Error(`managed root must be absolute: ${root}`)
+ const parts = abs.split(sep).filter(Boolean)
+ let current = sep
+ for (const part of parts) {
+ current = join(current, part)
+ let info
+ try {
+ info = await lstat(current)
+ } catch (err) {
+ if (err.code !== 'ENOENT') throw err
+ await mkdir(current, { mode: 0o700 })
+ info = await lstat(current)
+ }
+ if (info.isSymbolicLink()) throw new Error(`managed root has symlink ancestor: ${current}`)
+ if (!info.isDirectory()) throw new Error(`managed root ancestor is not a directory: ${current}`)
+ // Only the managed root itself must be user-owned; system ancestors need not be.
+ if (current === abs && info.uid !== process.getuid()) {
+ throw new Error(`managed root is not owned by this user: ${current}`)
+ }
+ }
+ if (((await lstat(abs)).mode & 0o077) !== 0) await chmod(abs, 0o700)
+ if (((await lstat(abs)).mode & 0o077) !== 0) throw new Error(`managed root permissions are not 0700: ${abs}`)
+ return abs
+}
+
+function contained(absRoot, absFile) {
+ if (absFile === absRoot || !absFile.startsWith(`${absRoot}${sep}`)) {
+ throw new Error(`path escapes managed root (outside): ${absFile}`)
+ }
+}
+
+async function assertPrivateAncestors(absRoot, absFile) {
+ const dir = dirname(absFile)
+ if (dir === absRoot) return
+ contained(absRoot, dir)
+ let current = absRoot
+ for (const part of dir.slice(absRoot.length + 1).split(sep)) {
+ current = join(current, part)
+ const info = await lstat(current)
+ if (info.isSymbolicLink()) throw new Error(`refusing symlink ancestor: ${current}`)
+ if (!info.isDirectory()) throw new Error(`private ancestor is not a directory: ${current}`)
+ if (info.uid !== process.getuid()) throw new Error(`private ancestor is not owned by this user: ${current}`)
+ }
+}
+
+async function readPrivateRaw(filePath, { root, maxBytes = MAX_PRIVATE_BYTES } = {}) {
+ const absRoot = await ensureManagedRoot(root)
+ const absFile = resolve(filePath)
+ contained(absRoot, absFile)
+ await assertPrivateAncestors(absRoot, absFile)
+ // One descriptor both inspects and reads: the bytes returned are the bytes the
+ // stat described, so nothing can be swapped in between. O_NOFOLLOW makes a
+ // symlinked receipt fail at open time instead of being followed.
+ let handle
+ try {
+ handle = await open(absFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ } catch (err) {
+ if (err.code === 'ENOENT') return null
+ if (err.code === 'ELOOP') throw new Error(`private file is not a regular file: ${absFile}`)
+ throw err
+ }
+ try {
+ const info = await handle.stat()
+ const problem = !info.isFile() ? 'is not a regular file'
+ : (info.mode & 0o077) !== 0 ? 'permissions are not 0600'
+ : info.uid !== process.getuid() ? 'is not owned by this user'
+ : info.size > maxBytes ? `exceeds ${maxBytes} bytes` : null
+ if (problem) throw new Error(`private file ${problem}: ${absFile}`)
+ return { absFile, raw: await handle.readFile('utf8') }
+ } finally {
+ await handle.close().catch(() => {})
+ }
+}
+
+export async function readPrivateJson(filePath, options = {}) {
+ const file = await readPrivateRaw(filePath, options)
+ if (!file) throw new Error(`private file is missing: ${resolve(filePath)}`)
+ return JSON.parse(file.raw)
+}
+
+/** Atomic 0600 write inside a verified managed root; no temp file survives failure. */
+export async function writePrivateFile(filePath, data, { root } = {}) {
+ const absRoot = await ensureManagedRoot(root)
+ const absFile = resolve(filePath)
+ contained(absRoot, absFile)
+ await ensureManagedRoot(dirname(absFile))
+ const existing = await lstat(absFile).catch((err) => { if (err.code !== 'ENOENT') throw err; return null })
+ if (existing && (existing.isSymbolicLink() || !existing.isFile())) {
+ throw new Error(`refusing non-regular or symlink private file: ${absFile}`)
+ }
+ const raw = typeof data === 'string' ? data : JSON.stringify(data, null, 2)
+ const tmp = `${absFile}.tmp-${process.pid}-${randomUUID()}`
+ try {
+ await writeFile(tmp, raw, { mode: 0o600, flag: 'wx' })
+ await rename(tmp, absFile)
+ } catch (err) {
+ await rm(tmp, { force: true }).catch(() => {})
+ throw err
+ }
+ return absFile
+}
+
+/**
+ * Publish a receipt pair as one transaction. Both files are staged before any
+ * rename; a later failure restores only entries whose bytes still equal ours.
+ */
+export async function publishPrivatePair({ root, entries, renameImpl = rename } = {}) {
+ const absRoot = await ensureManagedRoot(root)
+ if (!Array.isArray(entries) || entries.length === 0) throw new Error('receipt entries are required')
+ const prepared = []
+ const seen = new Set()
+ try {
+ for (const entry of entries) {
+ const absFile = resolve(entry.path)
+ contained(absRoot, absFile)
+ if (seen.has(absFile)) throw new Error(`duplicate receipt path: ${absFile}`)
+ seen.add(absFile)
+ await ensureManagedRoot(dirname(absFile))
+ const previous = await readPrivateRaw(absFile, { root: absRoot })
+ const raw = typeof entry.data === 'string' ? entry.data : JSON.stringify(entry.data, null, 2)
+ const tmp = `${absFile}.tmp-${process.pid}-${randomUUID()}`
+ await writeFile(tmp, raw, { mode: 0o600, flag: 'wx' })
+ prepared.push({ absFile, raw, previous: previous?.raw ?? null, tmp, renamed: false })
+ }
+ for (const item of prepared) {
+ await renameImpl(item.tmp, item.absFile)
+ item.renamed = true
+ }
+ return { files: prepared.map((item) => item.absFile) }
+ } catch (err) {
+ for (const item of [...prepared].reverse()) {
+ if (item.tmp) await rm(item.tmp, { force: true }).catch(() => {})
+ if (!item.renamed) continue
+ const current = await readPrivateRaw(item.absFile, { root: absRoot }).catch(() => null)
+ if (!current || current.raw !== item.raw) continue
+ try {
+ if (item.previous === null) {
+ await rm(item.absFile, { force: true })
+ } else {
+ await writePrivateFile(item.absFile, item.previous, { root: absRoot })
+ }
+ } catch {}
+ }
+ throw err
+ } finally {
+ await Promise.all(prepared.map((item) => rm(item.tmp, { force: true }).catch(() => {})))
+ }
+}
+
+async function restoreQuarantine(quarantine, absFile) {
+ try {
+ await link(quarantine, absFile)
+ await rm(quarantine, { force: true })
+ return
+ } catch (err) {
+ if (err.code === 'EEXIST') {
+ // Another runtime recreated the path while we inspected it: keep theirs.
+ await rm(quarantine, { force: true })
+ return
+ }
+ }
+ const existing = await lstat(absFile).catch(() => null)
+ if (existing) throw new Error(`cannot restore quarantined receipt without clobbering: ${absFile}`)
+ await rename(quarantine, absFile)
+}
+
+/**
+ * Remove only receipts that still parse and match this runtime's predicate.
+ * Each candidate is renamed aside, inspected, then deleted or restored.
+ */
+export async function clearPrivatePairIfMatch({ root, matches = [] } = {}) {
+ const absRoot = await ensureManagedRoot(root)
+ const cleared = []
+ const preserved = []
+ for (const match of matches) {
+ const absFile = resolve(match.path)
+ contained(absRoot, absFile)
+ const quarantine = `${absFile}.quarantine-${process.pid}-${randomUUID()}`
+ try {
+ await rename(absFile, quarantine)
+ } catch (err) {
+ if (err.code === 'ENOENT') continue
+ throw err
+ }
+ let matchesOwn = false
+ try {
+ const current = await readPrivateRaw(quarantine, { root: absRoot })
+ if (current) {
+ let parsed
+ try { parsed = JSON.parse(current.raw) } catch { parsed = undefined }
+ matchesOwn = Boolean(parsed && match.predicate(parsed))
+ }
+ } catch (err) {
+ await restoreQuarantine(quarantine, absFile).catch(() => {})
+ throw err
+ }
+ if (matchesOwn) {
+ await rm(quarantine, { force: true })
+ cleared.push(absFile)
+ } else {
+ await restoreQuarantine(quarantine, absFile)
+ preserved.push(absFile)
+ }
+ }
+ return { cleared, preserved }
+}
diff --git a/scripts/orca/private-store.test.mjs b/scripts/orca/private-store.test.mjs
new file mode 100644
index 00000000..5b96b760
--- /dev/null
+++ b/scripts/orca/private-store.test.mjs
@@ -0,0 +1,125 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import {
+ clearPrivatePairIfMatch,
+ ensureManagedRoot,
+ publishPrivatePair,
+ readPrivateJson,
+ writePrivateFile
+} from './private-store.mjs'
+
+async function makeRoot() {
+ const root = await mkdtemp(join(tmpdir(), 'orca-private-'))
+ await ensureManagedRoot(root)
+ return root
+}
+
+describe('private managed receipts', () => {
+ it('rejects symlink, loose-permission, and oversized receipt files', async () => {
+ const root = await makeRoot()
+ const outside = await mkdtemp(join(tmpdir(), 'orca-private-outside-'))
+ try {
+ const real = join(root, 'real.json')
+ await writePrivateFile(real, { ok: true }, { root })
+ const link = join(root, 'link.json')
+ await symlink(real, link)
+ await assert.rejects(() => readPrivateJson(link, { root }), /not a regular file/i)
+
+ await mkdir(join(root, 'nested'), { mode: 0o700 })
+ await symlink(join(root, 'nested'), join(root, 'alias'))
+ await assert.rejects(
+ () => readPrivateJson(join(root, 'alias', 'x.json'), { root }),
+ /symlink ancestor/i
+ )
+
+ await chmod(real, 0o644)
+ await assert.rejects(() => readPrivateJson(real, { root }), /permissions are not 0600/i)
+ await chmod(real, 0o600)
+
+ const big = join(root, 'big.json')
+ await writePrivateFile(big, 'x'.repeat(64 * 1024 + 1), { root })
+ await assert.rejects(() => readPrivateJson(big, { root }), /exceeds/i)
+
+ await assert.rejects(
+ () => readPrivateJson(join(outside, 'x.json'), { root }),
+ /escapes managed root/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ await rm(outside, { recursive: true, force: true })
+ }
+ })
+
+ it('publishes a receipt pair as one transaction and restores the previous pair on failure', async () => {
+ const root = await makeRoot()
+ const status = join(root, 'private-status.json')
+ const identity = join(root, 'runtime-identity.json')
+ try {
+ const oldStatus = JSON.stringify({ runtimeId: 'old', health: { pid: 1 } })
+ const oldIdentity = JSON.stringify({ runtimeId: 'old', serverStartTicks: '1' })
+ await writePrivateFile(status, oldStatus, { root })
+ await writePrivateFile(identity, oldIdentity, { root })
+
+ let renames = 0
+ const failingRename = async (from, to) => {
+ renames += 1
+ if (renames === 2) throw new Error('injected second rename failure')
+ await rename(from, to)
+ }
+ await assert.rejects(
+ () =>
+ publishPrivatePair({
+ root,
+ entries: [
+ { path: status, data: { runtimeId: 'new', health: { pid: 2 } } },
+ { path: identity, data: { runtimeId: 'new', serverStartTicks: '2' } }
+ ],
+ renameImpl: failingRename
+ }),
+ /injected second rename failure/i
+ )
+ assert.equal(await readFile(status, 'utf8'), oldStatus)
+ assert.equal(await readFile(identity, 'utf8'), oldIdentity)
+ const leftovers = (await readdir(root)).filter((name) => name.includes('.tmp-'))
+ assert.deepEqual(leftovers, [])
+
+ await publishPrivatePair({
+ root,
+ entries: [
+ { path: status, data: { runtimeId: 'new', health: { pid: 2 } } },
+ { path: identity, data: { runtimeId: 'new', serverStartTicks: '2' } }
+ ]
+ })
+ assert.equal((await readPrivateJson(status, { root })).runtimeId, 'new')
+ assert.equal((await readPrivateJson(identity, { root })).serverStartTicks, '2')
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('clears only receipts that still match the caller runtime', async () => {
+ const root = await makeRoot()
+ const own = join(root, 'own.json')
+ const other = join(root, 'other.json')
+ try {
+ await writePrivateFile(own, { runtimeId: 'mine', serverStartTicks: '10' }, { root })
+ await writePrivateFile(other, { runtimeId: 'theirs', serverStartTicks: '20' }, { root })
+ const result = await clearPrivatePairIfMatch({
+ root,
+ matches: [
+ { path: own, predicate: (value) => value.runtimeId === 'mine' },
+ { path: other, predicate: (value) => value.runtimeId === 'mine' }
+ ]
+ })
+ assert.deepEqual(result.cleared, [own])
+ assert.deepEqual(result.preserved, [other])
+ await assert.rejects(lstat(own))
+ assert.equal((await readPrivateJson(other, { root })).runtimeId, 'theirs')
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/proc-identity.mjs b/scripts/orca/proc-identity.mjs
new file mode 100644
index 00000000..6ecfc27f
--- /dev/null
+++ b/scripts/orca/proc-identity.mjs
@@ -0,0 +1,195 @@
+/**
+ * Linux process identity: kernel start ticks, uid, executable, argv.
+ * Shared by launcher/lifecycle so no caller ever signals a PID it has not verified.
+ * Identity is read from procfs only; /proc/<pid>/environ is never touched.
+ */
+
+import { readFile, readlink, realpath } from 'node:fs/promises'
+
+const PROC = '/proc'
+
+/** Parse /proc/<pid>/stat where comm may contain spaces and parentheses. */
+export function parseProcStat(raw) {
+ if (typeof raw !== 'string') return null
+ const open = raw.indexOf('(')
+ const close = raw.lastIndexOf(')')
+ if (open < 0 || close < open) return null
+ const pid = Number(raw.slice(0, open).trim())
+ if (!Number.isInteger(pid) || pid <= 0) return null
+ const comm = raw.slice(open + 1, close)
+ const fields = raw.slice(close + 2).trim().split(/\s+/)
+ // fields[0] is stat field 3 (state); starttime is field 22 -> index 19.
+ const state = fields[0]
+ const startTicks = fields[19]
+ if (!state || !/^\d+$/.test(startTicks ?? '')) return null
+ return { pid, comm, state, startTicks }
+}
+
+async function readUid(pid) {
+ try {
+ const status = await readFile(`${PROC}/${pid}/status`, 'utf8')
+ const m = /^Uid:\s+(\d+)\s+(\d+)/m.exec(status)
+ return m ? { uid: Number(m[1]), euid: Number(m[2]) } : null
+ } catch {
+ return null
+ }
+}
+
+async function readArgv(pid) {
+ try {
+ const raw = await readFile(`${PROC}/${pid}/cmdline`, 'utf8')
+ return raw.split('\0').filter((s) => s.length > 0)
+ } catch {
+ return null
+ }
+}
+
+async function readExe(pid) {
+ try {
+ return await realpath(`${PROC}/${pid}/exe`)
+ } catch {
+ try {
+ return await readlink(`${PROC}/${pid}/exe`)
+ } catch {
+ return null
+ }
+ }
+}
+
+/** Full identity snapshot, or null when the process is gone or its PID was reused mid-read. */
+export async function readProcessIdentity(pid) {
+ if (!Number.isInteger(pid) || pid <= 1) return null
+ let raw
+ try {
+ raw = await readFile(`${PROC}/${pid}/stat`, 'utf8')
+ } catch {
+ return null
+ }
+ const parsed = parseProcStat(raw)
+ if (!parsed) return null
+ const owner = await readUid(pid)
+ if (!owner) return null
+ const [argv, exe] = await Promise.all([readArgv(pid), readExe(pid)])
+ // Re-read the kernel start time after the multi-file snapshot: a reused PID
+ // must not combine fields from two different processes.
+ let confirm
+ try {
+ confirm = parseProcStat(await readFile(`${PROC}/${pid}/stat`, 'utf8'))
+ } catch {
+ return null
+ }
+ if (!confirm || confirm.startTicks !== parsed.startTicks) return null
+ return {
+ pid,
+ comm: parsed.comm,
+ state: parsed.state,
+ startTicks: parsed.startTicks,
+ uid: owner.uid,
+ euid: owner.euid,
+ exe,
+ argv: argv ?? []
+ }
+}
+
+async function resolvePath(p) {
+ try {
+ return await realpath(p)
+ } catch {
+ return p
+ }
+}
+
+async function hasScript(argv, scriptPath) {
+ const wanted = await resolvePath(scriptPath)
+ for (const arg of argv) {
+ if (arg === scriptPath) return true
+ if (arg.endsWith(`/${scriptPath}`)) return true
+ if (arg.startsWith('/') && (await resolvePath(arg)) === wanted) return true
+ }
+ return false
+}
+
+function hasSocket(argv, socketPath) {
+ const idx = argv.indexOf('--socket')
+ if (idx >= 0 && argv[idx + 1] === socketPath) return true
+ return argv.includes(socketPath)
+}
+
+/**
+ * Compare a live snapshot with an expected identity. Only fields present in
+ * `expected` are enforced; pid + startTicks + uid + exe are always enforced.
+ */
+export async function verifyProcessIdentity(actual, expected) {
+ if (!actual || !expected) return false
+ if (actual.pid !== expected.pid) return false
+ if (String(actual.startTicks) !== String(expected.startTicks)) return false
+ if (expected.uid !== undefined && actual.uid !== expected.uid) return false
+ if (expected.exe !== undefined && actual.exe !== expected.exe) return false
+ if (expected.scriptPath !== undefined && !(await hasScript(actual.argv, expected.scriptPath))) return false
+ if (expected.socketPath !== undefined && !hasSocket(actual.argv, expected.socketPath)) return false
+ return true
+}
+
+/** Poll until a child identity is observable and matches, else null. */
+export async function waitForProcessIdentity(pid, expected = {}, { attempts = 40, delayMs = 50 } = {}) {
+ for (let i = 0; i < attempts; i += 1) {
+ const actual = await readProcessIdentity(pid)
+ if (actual) {
+ const baseline = {
+ ...expected,
+ pid,
+ startTicks: expected.startTicks ?? actual.startTicks
+ }
+ if (await verifyProcessIdentity(actual, baseline)) return actual
+ }
+ if (i + 1 < attempts) await new Promise((r) => setTimeout(r, delayMs))
+ }
+ return null
+}
+
+/** True once the exact identity is gone (dead, zombie, or the PID was reused). */
+export async function waitForProcessExit(identity, { timeoutMs = 5000, pollMs = 50 } = {}) {
+ const start = Date.now()
+ for (;;) {
+ const actual = await readProcessIdentity(identity.pid)
+ if (!actual || actual.state === 'Z' || actual.startTicks !== identity.startTicks) return true
+ if (Date.now() - start >= timeoutMs) return false
+ await new Promise((r) => setTimeout(r, pollMs))
+ }
+}
+
+/**
+ * Signal only after re-verifying kernel identity. Never signals a stale,
+ * reused, or foreign PID; returns explicit failure instead of pretending.
+ * Linux has no pidfd here, so a verify-then-kill window remains; start ticks
+ * make reuse detectable before/after signalling but cannot eliminate the race.
+ */
+export async function terminateVerifiedProcess(
+ identity,
+ { timeoutMs = 5000, killTimeoutMs = 3000, pollMs = 50 } = {}
+) {
+ const before = await readProcessIdentity(identity.pid)
+ if (!(await verifyProcessIdentity(before, identity))) {
+ return { signaled: false, forced: false, exited: false, stale: true }
+ }
+ try {
+ process.kill(identity.pid, 'SIGTERM')
+ } catch (err) {
+ if (err.code !== 'ESRCH') return { signaled: false, forced: false, exited: false, stale: false }
+ return { signaled: false, forced: false, exited: true, stale: true }
+ }
+ if (await waitForProcessExit(identity, { timeoutMs, pollMs })) {
+ return { signaled: true, forced: false, exited: true, stale: false }
+ }
+ const beforeKill = await readProcessIdentity(identity.pid)
+ if (!(await verifyProcessIdentity(beforeKill, identity))) {
+ return { signaled: true, forced: false, exited: false, stale: true }
+ }
+ try {
+ process.kill(identity.pid, 'SIGKILL')
+ } catch (err) {
+ if (err.code !== 'ESRCH') throw err
+ }
+ const exited = await waitForProcessExit(identity, { timeoutMs: killTimeoutMs, pollMs })
+ return { signaled: true, forced: true, exited, stale: false }
+}
diff --git a/scripts/orca/proc-identity.test.mjs b/scripts/orca/proc-identity.test.mjs
new file mode 100644
index 00000000..aa69e61b
--- /dev/null
+++ b/scripts/orca/proc-identity.test.mjs
@@ -0,0 +1,138 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { spawn } from 'node:child_process'
+import { mkdtemp, rm } from 'node:fs/promises'
+import { realpath } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import {
+ parseProcStat,
+ readProcessIdentity,
+ verifyProcessIdentity,
+ waitForProcessIdentity,
+ waitForProcessExit,
+ terminateVerifiedProcess
+} from './proc-identity.mjs'
+
+const FIXTURES = fileURLToPath(new URL('./fixtures/', import.meta.url))
+const HOLDER = join(FIXTURES, 'hold-child.mjs')
+const STUBBORN = join(FIXTURES, 'stubborn-child.mjs')
+
+async function spawnHolder(script = HOLDER, args = []) {
+ const child = spawn(process.execPath, [script, ...args], { stdio: ['ignore', 'pipe', 'pipe'] })
+ child.stderr.resume()
+ // Wait for the fixture's "ready" line: guarantees its signal handlers exist.
+ await new Promise((resolve, reject) => {
+ let buf = ''
+ child.stdout.on('data', (chunk) => {
+ buf += chunk.toString('utf8')
+ if (buf.includes('ready')) resolve()
+ })
+ child.once('exit', () => reject(new Error('fixture exited before ready')))
+ })
+ child.stdout.resume()
+ return child
+}
+
+async function stopFixture(child) {
+ if (child.exitCode !== null || child.signalCode !== null) return
+ child.kill('SIGKILL')
+ await new Promise((resolve) => child.once('exit', resolve))
+}
+
+function statLine({ pid = 4242, comm = 'node', startTicks = '987654' } = {}) {
+ const rest = ['S', '1', String(pid), String(pid), '0', '-1', '4194304']
+ while (rest.length < 19) rest.push('0')
+ rest.push(startTicks)
+ while (rest.length < 50) rest.push('0')
+ return `${pid} (${comm}) ${rest.join(' ')}`
+}
+
+describe('proc identity parses kernel identity and verifies owned children', () => {
+ it('parses start ticks when comm contains spaces and parentheses', () => {
+ const parsed = parseProcStat(statLine({ pid: 77, comm: 'my (weird) node', startTicks: '12345' }))
+ assert.equal(parsed.pid, 77)
+ assert.equal(parsed.comm, 'my (weird) node')
+ assert.equal(parsed.state, 'S')
+ assert.equal(parsed.startTicks, '12345')
+ })
+
+ it('reads the current process identity from procfs', async () => {
+ const identity = await readProcessIdentity(process.pid)
+ assert.ok(identity)
+ assert.equal(identity.pid, process.pid)
+ assert.equal(identity.uid, process.getuid())
+ assert.equal(identity.exe, await realpath(process.execPath))
+ assert.match(identity.startTicks, /^\d+$/)
+ assert.ok(identity.argv.some((a) => a.includes('proc-identity.test.mjs')))
+ })
+
+ it('returns null for a process that does not exist', async () => {
+ assert.equal(await readProcessIdentity(2 ** 22 + 12345), null)
+ })
+
+ it('accepts the real owned child and rejects forged uid/exe/start ticks/script/socket', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'orca-proc-'))
+ const socketPath = join(dir, 'daemon', 'daemon-v1.sock')
+ const child = await spawnHolder(HOLDER, ['--socket', socketPath, '--entry-path', HOLDER])
+ try {
+ const expected = await waitForProcessIdentity(child.pid, {
+ exe: await realpath(process.execPath),
+ scriptPath: HOLDER,
+ socketPath,
+ uid: process.getuid()
+ })
+ assert.ok(expected)
+ assert.equal(await verifyProcessIdentity(expected, expected), true)
+
+ assert.equal(await verifyProcessIdentity({ ...expected, uid: expected.uid + 1 }, expected), false)
+ assert.equal(await verifyProcessIdentity({ ...expected, exe: '/bin/false' }, expected), false)
+ assert.equal(await verifyProcessIdentity({ ...expected, startTicks: '1' }, expected), false)
+ assert.equal(await verifyProcessIdentity({ ...expected, pid: expected.pid + 1 }, expected), false)
+
+ assert.equal(
+ await waitForProcessIdentity(child.pid, { scriptPath: join(dir, 'other-entry.js') }, { attempts: 2, delayMs: 5 }),
+ null
+ )
+ assert.equal(
+ await waitForProcessIdentity(child.pid, { socketPath: join(dir, 'other', 'x.sock') }, { attempts: 2, delayMs: 5 }),
+ null
+ )
+ } finally {
+ await stopFixture(child)
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('waits for a real exit and reports reused/stale identities without signaling them', async () => {
+ const child = await spawnHolder()
+ const identity = await waitForProcessIdentity(child.pid, { exe: await realpath(process.execPath), scriptPath: HOLDER })
+ assert.ok(identity)
+
+ const stale = { ...identity, startTicks: '1' }
+ const result = await terminateVerifiedProcess(stale, { timeoutMs: 200 })
+ assert.equal(result.signaled, false)
+ assert.equal(result.exited, false)
+ assert.equal(child.exitCode, null)
+
+ const terminated = await terminateVerifiedProcess(identity, { timeoutMs: 3000 })
+ assert.equal(terminated.signaled, true)
+ assert.equal(terminated.exited, true)
+ assert.equal(await waitForProcessExit(identity, { timeoutMs: 1000 }), true)
+ })
+
+ it('escalates to SIGKILL for a verified child that ignores SIGTERM', async () => {
+ const child = await spawnHolder(STUBBORN)
+ try {
+ const identity = await waitForProcessIdentity(child.pid, { exe: await realpath(process.execPath), scriptPath: STUBBORN })
+ assert.ok(identity)
+ const result = await terminateVerifiedProcess(identity, { timeoutMs: 300, killTimeoutMs: 3000 })
+ assert.equal(result.signaled, true)
+ assert.equal(result.forced, true)
+ assert.equal(result.exited, true)
+ } finally {
+ await stopFixture(child)
+ }
+ })
+})
diff --git a/scripts/orca/readiness-wait.mjs b/scripts/orca/readiness-wait.mjs
new file mode 100644
index 00000000..6da52661
--- /dev/null
+++ b/scripts/orca/readiness-wait.mjs
@@ -0,0 +1,69 @@
+/**
+ * Bounded readiness capture: one JSON line, capped stdout, capped/redacted
+ * stderr, explicit timeout, and premature-exit failure.
+ */
+
+import { createBoundedLineReader } from './bounded-stream.mjs'
+import { redactSensitiveText } from './bounded-proc.mjs'
+
+export function waitForReadiness({ child, timeoutMs, stderrSink, signal }) {
+ return new Promise((resolve, reject) => {
+ let settled = false
+ let reader = null
+ let abortListener = null
+ const stderrTail = () => redactSensitiveText(stderrSink.text()).slice(-2048)
+ const timer = setTimeout(() => {
+ finish(
+ new Error(
+ `timed out after ${timeoutMs}ms waiting for orca_server_ready${stderrTail() ? `: ${stderrTail()}` : ''}`
+ )
+ )
+ }, timeoutMs)
+ const cleanup = () => {
+ clearTimeout(timer)
+ child.removeListener('error', onError)
+ child.removeListener('exit', onExit)
+ if (signal && abortListener) signal.removeEventListener('abort', abortListener)
+ }
+ const finish = (err, value) => {
+ if (settled) return
+ settled = true
+ cleanup()
+ if (err) {
+ reader?.detach()
+ reject(err)
+ } else resolve(value)
+ }
+ const onError = (err) => finish(new Error(`failed to spawn orcad-server: ${err.message}`))
+ const onExit = (code, exitSignal) =>
+ finish(
+ new Error(`orcad-server exited prematurely (code ${code}, signal ${exitSignal}): ${stderrTail()}`)
+ )
+
+ if (signal) {
+ abortListener = () => {
+ const reason = signal.reason instanceof Error ? signal.reason.message : 'startup cancelled'
+ finish(new Error(reason))
+ }
+ if (signal.aborted) {
+ abortListener()
+ return
+ }
+ signal.addEventListener('abort', abortListener, { once: true })
+ }
+
+ reader = createBoundedLineReader(child.stdout, {
+ onLine: (line) => {
+ if (!line.includes('"orca_server_ready"')) return
+ try {
+ finish(null, { payload: JSON.parse(line), reader })
+ } catch (err) {
+ finish(new Error(`invalid readiness JSON: ${redactSensitiveText(err.message)}`))
+ }
+ },
+ onOverflow: (err) => finish(err)
+ })
+ child.once('error', onError)
+ child.once('exit', onExit)
+ })
+}
diff --git a/scripts/orca/release-fixtures.mjs b/scripts/orca/release-fixtures.mjs
new file mode 100644
index 00000000..5cb27a8f
--- /dev/null
+++ b/scripts/orca/release-fixtures.mjs
@@ -0,0 +1,29 @@
+import { createHash } from 'node:crypto'
+import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+export const sha256 = (text) => createHash('sha256').update(text).digest('hex')
+
+export async function scratch(name) {
+ // mkdtemp atomically creates an owner-only (0700) directory, so the shared
+ // temp root never holds a predictable name.
+ return mkdtemp(join(tmpdir(), `orca-rel-${name}-`))
+}
+
+export async function writeFileAt(root, rel, content) {
+ const filePath = join(root, rel)
+ await mkdir(join(filePath, '..'), { recursive: true })
+ await writeFile(filePath, content, { mode: 0o600 })
+ return filePath
+}
+
+export function fakeAsar(entryName, data) {
+ const headerJson = Buffer.from(JSON.stringify({ files: { [entryName]: { size: data.length, offset: '0' } } }))
+ const headerSize = headerJson.length + 8
+ const preamble = Buffer.alloc(16)
+ preamble.writeUInt32LE(4, 0)
+ preamble.writeUInt32LE(headerSize, 4)
+ preamble.writeUInt32LE(headerJson.length, 12)
+ return Buffer.concat([preamble, headerJson, data])
+}
diff --git a/scripts/orca/release-identity.mjs b/scripts/orca/release-identity.mjs
new file mode 100644
index 00000000..dc3b00cc
--- /dev/null
+++ b/scripts/orca/release-identity.mjs
@@ -0,0 +1,98 @@
+/**
+ * Pure release identity derived only from pinned release facts.
+ *
+ * The content id can be computed before downloading/extracting anything, which
+ * lets `preparePinnedRelease` locate and fully re-verify an existing release
+ * without touching the network or the filesystem source cache.
+ */
+
+import { createHash } from 'node:crypto'
+import {
+ ORCA_DEB_ARCHITECTURE,
+ ORCA_DEB_PACKAGE,
+ ORCA_DEB_SHA256,
+ ORCA_DEB_SIZE,
+ ORCA_DEB_URL,
+ ORCA_LICENSE_SHA256,
+ ORCA_LICENSE_SIZE,
+ ORCA_SOURCE_COMMIT,
+ ORCA_THIRD_PARTY_NOTICES_SHA256,
+ ORCA_THIRD_PARTY_NOTICES_SIZE,
+ ORCA_VERSION,
+ ORCAD_VERSION,
+ PINNED_NODE,
+ SUPPORTED_TARGET
+} from './constants.mjs'
+
+export const RELEASE_CONTENT_ID_LENGTH = 16
+export const RELEASE_RUNTIME_DIRNAME = 'runtimes'
+export const RELEASE_RUNTIME_DIR_PREFIX = 'node-'
+
+/** Upstream slot-relative runtime: `<slot>/../runtimes/node-<exeSha>/bin/node`. */
+export function nodeRuntimeRelativePath(executableSha256) {
+ return `${RELEASE_RUNTIME_DIRNAME}/${RELEASE_RUNTIME_DIR_PREFIX}${executableSha256}/bin/node`
+}
+
+export function getReleaseContentId() {
+ return createHash('sha256')
+ .update(
+ [
+ 'mso-orca-release-v3',
+ 'runtimes/node-<executableSha256>/bin/node',
+ 'slot-version:sha256-raw-bytes-orcadArtifactFilenames-order',
+ ORCA_VERSION,
+ ORCAD_VERSION,
+ ORCA_SOURCE_COMMIT,
+ ORCA_DEB_URL,
+ ORCA_DEB_SHA256,
+ String(ORCA_DEB_SIZE),
+ PINNED_NODE.version,
+ PINNED_NODE.archiveUrl,
+ PINNED_NODE.archiveSha256,
+ PINNED_NODE.executableSha256,
+ ORCA_LICENSE_SHA256,
+ ORCA_THIRD_PARTY_NOTICES_SHA256
+ ].join('\n')
+ )
+ .digest('hex')
+ .slice(0, RELEASE_CONTENT_ID_LENGTH)
+}
+
+export function getReleaseIdentity() {
+ return Object.freeze({
+ schemaVersion: 3,
+ version: ORCA_VERSION,
+ orcadVersion: ORCAD_VERSION,
+ target: SUPPORTED_TARGET,
+ sourceCommit: ORCA_SOURCE_COMMIT,
+ contentId: getReleaseContentId(),
+ runtimeLayout: {
+ dirname: RELEASE_RUNTIME_DIRNAME,
+ dirPrefix: RELEASE_RUNTIME_DIR_PREFIX,
+ slotRelativePath: `../${RELEASE_RUNTIME_DIRNAME}`
+ },
+ deb: {
+ url: ORCA_DEB_URL,
+ sha256: ORCA_DEB_SHA256,
+ size: ORCA_DEB_SIZE,
+ package: ORCA_DEB_PACKAGE,
+ architecture: ORCA_DEB_ARCHITECTURE
+ },
+ node: {
+ version: PINNED_NODE.version,
+ archiveUrl: PINNED_NODE.archiveUrl,
+ archiveSha256: PINNED_NODE.archiveSha256,
+ archiveSize: PINNED_NODE.archiveSize,
+ executableSha256: PINNED_NODE.executableSha256,
+ executablePath: nodeRuntimeRelativePath(PINNED_NODE.executableSha256)
+ },
+ licenses: [
+ { path: 'licenses/LICENSE', sha256: ORCA_LICENSE_SHA256, size: ORCA_LICENSE_SIZE },
+ {
+ path: 'licenses/THIRD_PARTY_NOTICES.md',
+ sha256: ORCA_THIRD_PARTY_NOTICES_SHA256,
+ size: ORCA_THIRD_PARTY_NOTICES_SIZE
+ }
+ ]
+ })
+}
diff --git a/scripts/orca/release-identity.test.mjs b/scripts/orca/release-identity.test.mjs
new file mode 100644
index 00000000..101ce592
--- /dev/null
+++ b/scripts/orca/release-identity.test.mjs
@@ -0,0 +1,78 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdir, rm } from 'node:fs/promises'
+import { join } from 'node:path'
+import { ORCA_VERSION, SUPPORTED_TARGET } from './constants.mjs'
+import { getReleaseContentId, getReleaseIdentity, nodeRuntimeRelativePath } from './release-identity.mjs'
+import { buildReceipt, verifyInstalledRelease } from './release-receipt.mjs'
+import { scratch, sha256 } from './release-fixtures.mjs'
+
+describe('release identity & receipt', () => {
+ it('derives a stable 16-hex content id from pins only', () => {
+ const id = getReleaseContentId()
+ assert.match(id, /^[a-f0-9]{16}$/)
+ assert.equal(id, getReleaseContentId())
+ const identity = getReleaseIdentity()
+ assert.equal(identity.contentId, id)
+ assert.equal(identity.version, ORCA_VERSION)
+ assert.equal(identity.target, SUPPORTED_TARGET)
+ assert.equal(identity.sourceCommit.length, 40)
+ assert.equal(identity.licenses.length, 2)
+ assert.equal(
+ identity.node.executablePath,
+ `runtimes/node-${identity.node.executableSha256}/bin/node`
+ )
+ assert.equal(identity.runtimeLayout.slotRelativePath, '../runtimes')
+ assert.equal(Object.isFrozen(identity), true)
+ })
+
+ it('names the sibling runtime path the upstream .runtime-node contract expects', () => {
+ const sha = 'a'.repeat(64)
+ assert.equal(nodeRuntimeRelativePath(sha), `runtimes/node-${sha}/bin/node`)
+ // Intentional layout/identity bumps: earlier packaged-release content ids must not be reused.
+ assert.notEqual(getReleaseContentId(), 'db813ed170845dbe')
+ assert.notEqual(getReleaseContentId(), '1cc972057c04eea1')
+ })
+
+ it('builds a receipt consistent with the identity', () => {
+ const identity = getReleaseIdentity()
+ const files = { 'a.js': 'a'.repeat(64) }
+ const slot = {
+ treeSha256: sha256(`a.js\0${'a'.repeat(64)}\n`),
+ artifactSha256: 'd'.repeat(64),
+ fullVersion: `${ORCA_VERSION}+${'d'.repeat(12)}`,
+ files
+ }
+ const web = { treeSha256: 'b'.repeat(64), fileCount: 1, totalBytes: 3, files: { 'index.html': 'c'.repeat(64) } }
+ const receipt = buildReceipt({ identity, slot, web })
+ assert.equal(receipt.schemaVersion, 3)
+ assert.equal(receipt.release.contentId, identity.contentId)
+ assert.equal(receipt.node.executablePath, identity.node.executablePath)
+ assert.equal(receipt.slot.artifactSha256, slot.artifactSha256)
+ assert.equal(receipt.slot.fileCount, 1)
+ assert.equal(receipt.web.fileCount, 1)
+ assert.equal(typeof receipt.createdAt, 'string')
+ })
+
+ it('refuses a release root that is missing its receipt or has extra entries', async () => {
+ const root = await scratch('receipt')
+ try {
+ const releaseRoot = join(root, 'release')
+ await mkdir(releaseRoot, { recursive: true, mode: 0o700 })
+ await assert.rejects(
+ verifyInstalledRelease({ releaseRoot, identity: getReleaseIdentity() }),
+ /layout is not exact/i
+ )
+ for (const name of ['licenses', 'runtimes', 'slot', 'web']) {
+ await mkdir(join(releaseRoot, name), { recursive: true, mode: 0o700 })
+ }
+ await mkdir(join(releaseRoot, 'receipt.json'), { recursive: true, mode: 0o700 })
+ await assert.rejects(
+ verifyInstalledRelease({ releaseRoot, identity: getReleaseIdentity() }),
+ /regular file/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/release-receipt.mjs b/scripts/orca/release-receipt.mjs
new file mode 100644
index 00000000..9037f7b1
--- /dev/null
+++ b/scripts/orca/release-receipt.mjs
@@ -0,0 +1,153 @@
+/**
+ * Release identity and integrity receipt.
+ *
+ * The content id is derived only from pinned release facts, so a release can
+ * be located and verified before any download/extraction. Reuse always
+ * re-hashes the installed slot, web bundle, Node executable, and license files;
+ * a mismatch is refused, never silently repaired.
+ */
+
+import { createHash } from 'node:crypto'
+import { lstat, readdir } from 'node:fs/promises'
+import { join } from 'node:path'
+import { fileSha256 } from './node-runtime.mjs'
+import { verifySlotIntegrity } from './materializer.mjs'
+import { readPrivateJson, verifyWebTree } from './release-tree.mjs'
+import { assertNoSymlinkAncestors, assertOwnedRegularFile, isSafeRelativePath } from './safe-paths.mjs'
+
+export const RELEASE_LAYOUT = Object.freeze(['licenses', 'receipt.json', 'runtimes', 'slot', 'web'])
+
+export function buildReceipt({ identity, slot, web }) {
+ return {
+ schemaVersion: 3,
+ release: {
+ contentId: identity.contentId,
+ version: identity.version,
+ orcadVersion: identity.orcadVersion,
+ target: identity.target,
+ sourceCommit: identity.sourceCommit,
+ runtimeLayout: identity.runtimeLayout
+ },
+ deb: identity.deb,
+ node: identity.node,
+ slot: {
+ treeSha256: slot.treeSha256,
+ artifactSha256: slot.artifactSha256,
+ fullVersion: slot.fullVersion,
+ fileCount: Object.keys(slot.files).length,
+ files: slot.files
+ },
+ web: {
+ treeSha256: web.treeSha256,
+ fileCount: web.fileCount,
+ totalBytes: web.totalBytes,
+ files: web.files
+ },
+ licenses: identity.licenses.map((entry) => ({ ...entry })),
+ createdAt: new Date().toISOString()
+ }
+}
+
+function slotTreeSha256(files) {
+ const hash = createHash('sha256')
+ for (const [name, digest] of Object.entries(files)) hash.update(`${name}\0${digest}\n`)
+ return hash.digest('hex')
+}
+
+function assertReceipt(receipt, identity) {
+ if (!receipt || receipt.schemaVersion !== 3) throw new Error('Receipt schema is not version 3')
+ const release = receipt.release
+ if (!release || release.contentId !== identity.contentId) {
+ throw new Error('Receipt content id does not match the pinned release')
+ }
+ if (release.version !== identity.version || release.sourceCommit !== identity.sourceCommit) {
+ throw new Error('Receipt release identity does not match the pins')
+ }
+ if (receipt.node?.executablePath !== identity.node.executablePath) {
+ throw new Error('Receipt Node runtime path does not match the pinned sibling layout')
+ }
+ if (receipt.slot?.fileCount !== Object.keys(receipt.slot?.files ?? {}).length) {
+ throw new Error('Receipt slot file count is inconsistent')
+ }
+ if (slotTreeSha256(receipt.slot.files) !== receipt.slot.treeSha256) {
+ throw new Error('Receipt slot tree digest is inconsistent')
+ }
+ // Upstream `.version` is the first 12 hex chars of the raw-byte artifact hash.
+ if (
+ typeof receipt.slot.artifactSha256 !== 'string' ||
+ receipt.slot.fullVersion !== `${identity.orcadVersion}+${receipt.slot.artifactSha256.slice(0, 12)}`
+ ) {
+ throw new Error('Receipt slot version is not the upstream raw-byte artifact identity')
+ }
+}
+
+export async function verifyInstalledRelease({ releaseRoot, identity }) {
+ await assertNoSymlinkAncestors(releaseRoot)
+ const rootStat = await lstat(releaseRoot)
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
+ throw new Error(`Release root is not a real directory: ${releaseRoot}`)
+ }
+ const entries = (await readdir(releaseRoot)).sort()
+ if (entries.length !== RELEASE_LAYOUT.length || entries.some((n, i) => n !== RELEASE_LAYOUT[i])) {
+ throw new Error(`Release layout is not exact: ${entries.join(', ')}`)
+ }
+
+ const receiptPath = join(releaseRoot, 'receipt.json')
+ const receipt = await readPrivateJson(receiptPath)
+ assertReceipt(receipt, identity)
+
+ const slotDir = join(releaseRoot, 'slot')
+ const slotMap = new Map(
+ Object.entries(receipt.slot.files).map(([name, digest]) => {
+ if (!isSafeRelativePath(name)) throw new Error(`Unsafe slot receipt path: ${name}`)
+ return [name, { sha: digest }]
+ })
+ )
+ if (!(await verifySlotIntegrity(slotDir, slotMap, {
+ expectedVersion: receipt.slot.fullVersion,
+ exactFileSet: true
+ }))) {
+ throw new Error('Installed slot failed rehash verification')
+ }
+
+ const webDir = join(releaseRoot, 'web')
+ if (!(await verifyWebTree({ dir: webDir, expected: receipt.web }))) {
+ throw new Error('Installed web bundle failed rehash verification')
+ }
+
+ if (!isSafeRelativePath(identity.node.executablePath)) {
+ throw new Error(`Unsafe Node runtime path: ${identity.node.executablePath}`)
+ }
+ const runtimesDir = join(releaseRoot, 'runtimes')
+ const runtimeEntries = (await readdir(runtimesDir)).sort()
+ const expectedRuntimeDir = `node-${identity.node.executableSha256}`
+ if (runtimeEntries.length !== 1 || runtimeEntries[0] !== expectedRuntimeDir) {
+ throw new Error(`Release runtimes layout is not exact: ${runtimeEntries.join(', ')}`)
+ }
+ const nodeBinary = join(releaseRoot, identity.node.executablePath)
+ const nodeStat = await assertOwnedRegularFile(nodeBinary)
+ if ((nodeStat.mode & 0o100) === 0) throw new Error('Installed Node executable is not executable')
+ if ((await fileSha256(nodeBinary)) !== identity.node.executableSha256) {
+ throw new Error('Installed Node executable failed rehash verification')
+ }
+
+ for (const entry of receipt.licenses) {
+ if (!isSafeRelativePath(entry.path)) throw new Error(`Unsafe license path: ${entry.path}`)
+ const licensePath = join(releaseRoot, entry.path)
+ const s = await assertOwnedRegularFile(licensePath)
+ if (s.size !== entry.size) throw new Error(`License size mismatch: ${entry.path}`)
+ if ((await fileSha256(licensePath)) !== entry.sha256) {
+ throw new Error(`License checksum mismatch: ${entry.path}`)
+ }
+ }
+
+ return {
+ releaseRoot,
+ slotDir,
+ nodeBinary,
+ webDir,
+ version: identity.version,
+ receipt,
+ receiptPath
+ }
+}
diff --git a/scripts/orca/release-runtime.test.mjs b/scripts/orca/release-runtime.test.mjs
new file mode 100644
index 00000000..c9ffeeac
--- /dev/null
+++ b/scripts/orca/release-runtime.test.mjs
@@ -0,0 +1,166 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdir, readFile, readdir, rm, symlink, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { ORCA_VERSION } from './constants.mjs'
+import { getReleaseContentId } from './release-identity.mjs'
+import { preparePinnedRelease } from './release.mjs'
+import { copyVerifiedFile, copyWebTree, readPrivateJson, verifyWebTree, writePrivateJson } from './release-tree.mjs'
+import { readAsarEntry } from './asar-license.mjs'
+import { fakeAsar, scratch, sha256, writeFileAt } from './release-fixtures.mjs'
+
+describe('release tree helpers', () => {
+ it('copies and verifies the web bundle, then detects tampering', async () => {
+ const root = await scratch('web')
+ try {
+ const source = join(root, 'source')
+ await writeFileAt(source, 'index.html', 'root')
+ await writeFileAt(source, 'assets/app.js', 'app')
+ const web = await copyWebTree({ sourceDir: source, destDir: join(root, 'web') })
+ assert.equal(web.fileCount, 2)
+ assert.equal(web.totalBytes, 'root'.length + 'app'.length)
+ assert.equal(await verifyWebTree({ dir: web.dir, expected: web }), true)
+
+ await writeFile(join(web.dir, 'index.html'), 'tampered', { mode: 0o600 })
+ assert.equal(await verifyWebTree({ dir: web.dir, expected: web }), false)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects symlinks in a web source tree', async () => {
+ const root = await scratch('websymlink')
+ try {
+ const source = join(root, 'source')
+ await mkdir(source, { recursive: true, mode: 0o700 })
+ await writeFile(join(source, 'real.js'), 'x', { mode: 0o600 })
+ await symlink(join(source, 'real.js'), join(source, 'link.js'))
+ await assert.rejects(
+ copyWebTree({ sourceDir: source, destDir: join(root, 'web') }),
+ /symlink/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('copies only a verified file and refuses overwrite/mismatch', async () => {
+ const root = await scratch('copy')
+ try {
+ const source = join(root, 'source.bin')
+ await writeFile(source, 'payload', { mode: 0o600 })
+ const digest = sha256('payload')
+ const dest = join(root, 'dest.bin')
+ const copied = await copyVerifiedFile({ sourcePath: source, destination: dest, expectedSha256: digest })
+ assert.equal(copied.sha256, digest)
+ assert.equal(await readFile(dest, 'utf8'), 'payload')
+ await assert.rejects(
+ copyVerifiedFile({ sourcePath: source, destination: dest, expectedSha256: digest }),
+ /overwrite/i
+ )
+ await assert.rejects(
+ copyVerifiedFile({
+ sourcePath: source,
+ destination: join(root, 'other.bin'),
+ expectedSha256: '0'.repeat(64)
+ }),
+ /checksum mismatch/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('writes private JSON with 0600 and reads it back', async () => {
+ const root = await scratch('json')
+ try {
+ const filePath = join(root, 'receipt.json')
+ await writePrivateJson(filePath, { ok: true })
+ const { stat } = await import('node:fs/promises')
+ assert.equal((await stat(filePath)).mode & 0o777, 0o600)
+ assert.deepEqual(await readPrivateJson(filePath), { ok: true })
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
+
+describe('asar entry extraction', () => {
+ it('extracts a bounded, checksum-verified entry', async () => {
+ const root = await scratch('asar')
+ try {
+ const asarPath = join(root, 'app.asar')
+ const data = Buffer.from('MIT license text')
+ await writeFile(asarPath, fakeAsar('LICENSE', data), { mode: 0o600 })
+ const entry = await readAsarEntry({
+ asarPath,
+ entryName: 'LICENSE',
+ expectedSha256: sha256('MIT license text')
+ })
+ assert.equal(entry.data.toString('utf8'), 'MIT license text')
+ await assert.rejects(readAsarEntry({ asarPath, entryName: 'LICENSE', expectedSha256: '0'.repeat(64) }), /checksum mismatch/i)
+ await assert.rejects(readAsarEntry({ asarPath, entryName: 'missing' }), /not found/i)
+ await assert.rejects(readAsarEntry({ asarPath, entryName: '../escape' }), /unsafe/i)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
+
+describe('preparePinnedRelease guards', () => {
+ it('requires an absolute install root', async () => {
+ await assert.rejects(preparePinnedRelease({ installRoot: 'relative/root' }), /absolute/i)
+ })
+
+ it('refuses to replace an existing non-matching release', async () => {
+ const root = await scratch('existing')
+ try {
+ const installRoot = join(root, 'install')
+ const releaseRoot = join(installRoot, 'releases', `${ORCA_VERSION}+${getReleaseContentId()}`)
+ await mkdir(releaseRoot, { recursive: true, mode: 0o700 })
+ await writeFile(join(releaseRoot, 'receipt.json'), 'junk', { mode: 0o600 })
+ await assert.rejects(
+ preparePinnedRelease({ installRoot, allowDownload: false }),
+ /refusing to replace existing release/i
+ )
+ assert.equal(await readFile(join(releaseRoot, 'receipt.json'), 'utf8'), 'junk')
+ const releases = await readdir(join(installRoot, 'releases'))
+ assert.deepEqual(releases, [`${ORCA_VERSION}+${getReleaseContentId()}`])
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects a symlinked deb cache and a corrupt deb cache', async () => {
+ const root = await scratch('deb')
+ try {
+ const installRoot = join(root, 'install')
+ const real = join(root, 'real.deb')
+ await writeFile(real, 'not-the-deb', { mode: 0o600 })
+ const link = join(root, 'link.deb')
+ await symlink(real, link)
+ await assert.rejects(
+ preparePinnedRelease({ installRoot, verifiedDebCache: link, allowDownload: false }),
+ /symlink/i
+ )
+ await assert.rejects(
+ preparePinnedRelease({ installRoot, verifiedDebCache: real, allowDownload: false }),
+ /mismatch/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('fails closed when no cache exists and download is disabled', async () => {
+ const root = await scratch('closed')
+ try {
+ await assert.rejects(
+ preparePinnedRelease({ installRoot: join(root, 'install'), allowDownload: false }),
+ /download is disabled/i
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/release-tree.mjs b/scripts/orca/release-tree.mjs
new file mode 100644
index 00000000..d507cb87
--- /dev/null
+++ b/scripts/orca/release-tree.mjs
@@ -0,0 +1,146 @@
+/**
+ * Release tree helpers: copy/verify the standalone web bundle, copy verified
+ * files, and read/write the private integrity receipt.
+ */
+
+import { createHash } from 'node:crypto'
+import { copyFile, chmod, mkdir, readFile, readdir, writeFile } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+import { fileSha256 } from './node-runtime.mjs'
+import {
+ assertNoSymlinkAncestors,
+ assertOwnedRegularFile,
+ ensurePrivateDirTree,
+ isSafeRelativePath,
+ lstatOrNull
+} from './safe-paths.mjs'
+
+const MAX_RECEIPT_BYTES = 8 * 1024 * 1024
+
+async function assertRealDir(dir, label) {
+ await assertNoSymlinkAncestors(dir)
+ const s = await lstatOrNull(dir)
+ if (!s || !s.isDirectory() || s.isSymbolicLink()) {
+ throw new Error(`${label} is not a real directory: ${dir}`)
+ }
+}
+
+async function walkFiles(root, rel = '') {
+ const entries = await readdir(join(root, rel), { withFileTypes: true })
+ const out = []
+ for (const entry of entries) {
+ const next = rel ? `${rel}/${entry.name}` : entry.name
+ if (!isSafeRelativePath(next)) throw new Error(`Unsafe web path: ${next}`)
+ if (entry.isSymbolicLink()) throw new Error(`Refusing symlink in web bundle: ${next}`)
+ if (entry.isDirectory()) out.push(...(await walkFiles(root, next)))
+ else if (entry.isFile()) out.push(next)
+ else throw new Error(`Refusing non-regular web entry: ${next}`)
+ }
+ return out
+}
+
+export async function copyWebTree({ sourceDir, destDir } = {}) {
+ if (typeof sourceDir !== 'string' || !sourceDir.startsWith('/')) {
+ throw new Error(`sourceDir must be absolute: ${sourceDir}`)
+ }
+ if (typeof destDir !== 'string' || !destDir.startsWith('/')) {
+ throw new Error(`destDir must be absolute: ${destDir}`)
+ }
+ await assertRealDir(sourceDir, 'Web source')
+ if (await lstatOrNull(destDir)) throw new Error(`Refusing to overwrite web destination: ${destDir}`)
+ await ensurePrivateDirTree(dirname(destDir))
+ await mkdir(destDir, { recursive: false, mode: 0o700 })
+
+ const files = await walkFiles(sourceDir)
+ const hash = createHash('sha256')
+ const digestMap = {}
+ let totalBytes = 0
+ for (const rel of files.sort()) {
+ const sourcePath = join(sourceDir, rel)
+ await assertNoSymlinkAncestors(sourcePath)
+ const sourceStat = await assertOwnedRegularFile(sourcePath)
+ const sourceSha = await fileSha256(sourcePath)
+ const destPath = join(destDir, rel)
+ await assertNoSymlinkAncestors(destPath)
+ await mkdir(dirname(destPath), { recursive: true, mode: 0o700 })
+ await copyFile(sourcePath, destPath)
+ await chmod(destPath, 0o600)
+ if ((await fileSha256(destPath)) !== sourceSha) {
+ throw new Error(`TOCTOU web copy corruption on ${rel}`)
+ }
+ if ((await lstatOrNull(sourcePath))?.size !== sourceStat.size) {
+ throw new Error(`Web source changed during copy: ${rel}`)
+ }
+ digestMap[rel] = sourceSha
+ totalBytes += sourceStat.size
+ hash.update(`${rel}\0${sourceSha}\n`)
+ }
+ return {
+ dir: destDir,
+ treeSha256: hash.digest('hex'),
+ fileCount: files.length,
+ totalBytes,
+ files: digestMap
+ }
+}
+
+export async function verifyWebTree({ dir, expected } = {}) {
+ try {
+ await assertRealDir(dir, 'Web release')
+ if (!expected || typeof expected.files !== 'object' || expected.files === null) return false
+ const actual = (await walkFiles(dir)).sort()
+ const wanted = Object.keys(expected.files).sort()
+ if (actual.length !== wanted.length) return false
+ if (actual.some((name, i) => name !== wanted[i])) return false
+ const hash = createHash('sha256')
+ let total = 0
+ for (const rel of wanted) {
+ const filePath = join(dir, rel)
+ await assertNoSymlinkAncestors(filePath)
+ const s = await lstatOrNull(filePath)
+ if (!s || !s.isFile() || s.isSymbolicLink()) return false
+ const actualSha = await fileSha256(filePath)
+ if (actualSha !== expected.files[rel]) return false
+ total += s.size
+ hash.update(`${rel}\0${actualSha}\n`)
+ }
+ return hash.digest('hex') === expected.treeSha256 && total === expected.totalBytes
+ } catch {
+ return false
+ }
+}
+
+export async function copyVerifiedFile({ sourcePath, destination, expectedSha256, mode = 0o600 } = {}) {
+ await assertNoSymlinkAncestors(sourcePath)
+ const s = await assertOwnedRegularFile(sourcePath)
+ if ((await fileSha256(sourcePath)) !== expectedSha256) {
+ throw new Error(`Source checksum mismatch: ${sourcePath}`)
+ }
+ if (await lstatOrNull(destination)) throw new Error(`Refusing to overwrite: ${destination}`)
+ await assertNoSymlinkAncestors(destination)
+ await mkdir(dirname(destination), { recursive: true, mode: 0o700 })
+ await copyFile(sourcePath, destination)
+ await chmod(destination, mode)
+ if ((await fileSha256(destination)) !== expectedSha256) {
+ throw new Error(`TOCTOU copy corruption: ${destination}`)
+ }
+ if ((await lstatOrNull(sourcePath))?.size !== s.size) {
+ throw new Error(`Source changed during copy: ${sourcePath}`)
+ }
+ return { path: destination, sha256: expectedSha256, size: s.size }
+}
+
+export async function writePrivateJson(filePath, value) {
+ if (await lstatOrNull(filePath)) throw new Error(`Refusing to overwrite: ${filePath}`)
+ await assertNoSymlinkAncestors(filePath)
+ await writeFile(filePath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' })
+ return filePath
+}
+
+export async function readPrivateJson(filePath) {
+ await assertNoSymlinkAncestors(filePath)
+ const s = await assertOwnedRegularFile(filePath)
+ if ((s.mode & 0o077) !== 0) throw new Error(`Receipt must be private (0600): ${filePath}`)
+ if (s.size > MAX_RECEIPT_BYTES) throw new Error(`Receipt is unexpectedly large: ${filePath}`)
+ return JSON.parse(await readFile(filePath, 'utf8'))
+}
diff --git a/scripts/orca/release.mjs b/scripts/orca/release.mjs
new file mode 100644
index 00000000..87e3b08f
--- /dev/null
+++ b/scripts/orca/release.mjs
@@ -0,0 +1,198 @@
+/**
+ * `preparePinnedRelease` — immutable Orca release acquisition.
+ *
+ * Chain: fixed .deb URL/digest -> package identity -> fresh data-only
+ * extraction -> exact 175-file slot + standalone web bundle + pinned Node +
+ * MIT license/notices -> private receipt -> atomic publish. Existing releases
+ * are reused only after a complete rehash; a mismatch is refused, never
+ * overwritten or deleted.
+ */
+
+import { randomUUID } from 'node:crypto'
+import { mkdir, rename, rm } from 'node:fs/promises'
+import { join } from 'node:path'
+import {
+ ORCA_DEB_FILENAME,
+ ORCA_LICENSE_SHA256,
+ ORCA_THIRD_PARTY_NOTICES_RELATIVE_PATH,
+ ORCA_THIRD_PARTY_NOTICES_SHA256,
+ ORCA_THIRD_PARTY_NOTICES_SIZE,
+ ORCA_THIRD_PARTY_NOTICES_URL,
+ SUPPORTED_TARGET,
+ assertSupportedHostPlatform
+} from './constants.mjs'
+import { acquireAndExtractDeb, downloadDebArchive, verifyDebHash } from './artifact-source.mjs'
+import { extractAsarEntry } from './asar-license.mjs'
+import { downloadToFile } from './download.mjs'
+import { fetchAndMaterializeNodeRuntime, fileSha256 } from './node-runtime.mjs'
+import { materializeOrcadSlot } from './materializer.mjs'
+import { buildReceipt, verifyInstalledRelease } from './release-receipt.mjs'
+import { getReleaseIdentity } from './release-identity.mjs'
+import { copyVerifiedFile, copyWebTree, writePrivateJson } from './release-tree.mjs'
+import {
+ assertNoSymlinkAncestors,
+ assertOwnedRegularFile,
+ ensurePrivateDir,
+ ensurePrivateDirTree,
+ lstatOrNull
+} from './safe-paths.mjs'
+
+async function verifyPinnedFile(filePath, { sha256, size, label }) {
+ const s = await assertOwnedRegularFile(filePath)
+ if (size !== undefined && s.size !== size) {
+ throw new Error(`${label} size mismatch: expected ${size}, got ${s.size}`)
+ }
+ if ((await fileSha256(filePath)) !== sha256) throw new Error(`${label} checksum mismatch`)
+ return filePath
+}
+
+async function resolveDeb({ cacheDir, verifiedDebCache, signal, timeoutMs, fetchImpl, allowDownload }) {
+ if (verifiedDebCache) {
+ await verifyDebHash(verifiedDebCache)
+ return verifiedDebCache
+ }
+ if (!allowDownload) throw new Error('No verified deb cache supplied and download is disabled')
+ const debPath = join(cacheDir, ORCA_DEB_FILENAME)
+ if (await lstatOrNull(debPath)) {
+ await verifyDebHash(debPath)
+ return debPath
+ }
+ await downloadDebArchive({ destination: debPath, signal, timeoutMs, fetchImpl })
+ return debPath
+}
+
+async function resolveNotices({ cacheDir, verifiedSourceRoot, signal, timeoutMs, fetchImpl }) {
+ if (verifiedSourceRoot) {
+ if (!verifiedSourceRoot.startsWith('/')) throw new Error('verifiedSourceRoot must be absolute')
+ const sourcePath = join(verifiedSourceRoot, ORCA_THIRD_PARTY_NOTICES_RELATIVE_PATH)
+ return verifyPinnedFile(sourcePath, {
+ sha256: ORCA_THIRD_PARTY_NOTICES_SHA256,
+ size: ORCA_THIRD_PARTY_NOTICES_SIZE,
+ label: 'Third-party notices'
+ })
+ }
+ const noticesPath = join(cacheDir, 'THIRD_PARTY_NOTICES.md')
+ if (await lstatOrNull(noticesPath)) {
+ return verifyPinnedFile(noticesPath, {
+ sha256: ORCA_THIRD_PARTY_NOTICES_SHA256,
+ size: ORCA_THIRD_PARTY_NOTICES_SIZE,
+ label: 'Third-party notices'
+ })
+ }
+ const result = await downloadToFile({
+ url: ORCA_THIRD_PARTY_NOTICES_URL,
+ expectedUrl: ORCA_THIRD_PARTY_NOTICES_URL,
+ destination: noticesPath,
+ expectedSha256: ORCA_THIRD_PARTY_NOTICES_SHA256,
+ expectedSize: ORCA_THIRD_PARTY_NOTICES_SIZE,
+ maxBytes: ORCA_THIRD_PARTY_NOTICES_SIZE,
+ signal,
+ timeoutMs,
+ fetchImpl,
+ allowedRedirectHosts: ['raw.githubusercontent.com']
+ })
+ return result.path
+}
+
+export async function preparePinnedRelease({
+ installRoot,
+ verifiedDebCache,
+ verifiedSourceRoot,
+ signal,
+ timeoutMs = 300000,
+ fetchImpl,
+ allowDownload = true
+} = {}) {
+ assertSupportedHostPlatform()
+ if (typeof installRoot !== 'string' || !installRoot.startsWith('/')) {
+ throw new Error(`installRoot must be absolute: ${installRoot}`)
+ }
+ await ensurePrivateDirTree(installRoot)
+ const identity = getReleaseIdentity()
+ const releasesDir = await ensurePrivateDir(installRoot, 'releases')
+ const releaseRoot = join(releasesDir, `${identity.version}+${identity.contentId}`)
+
+ if (await lstatOrNull(releaseRoot)) {
+ try {
+ return await verifyInstalledRelease({ releaseRoot, identity })
+ } catch (err) {
+ throw new Error(`Refusing to replace existing release ${releaseRoot}: ${err.message}`)
+ }
+ }
+
+ const cacheDir = await ensurePrivateDir(installRoot, 'cache')
+ const debPath = await resolveDeb({
+ cacheDir,
+ verifiedDebCache,
+ signal,
+ timeoutMs,
+ fetchImpl,
+ allowDownload
+ })
+ const runtimesDir = await ensurePrivateDir(cacheDir, 'runtimes')
+ const nodeBinary = await fetchAndMaterializeNodeRuntime({
+ target: SUPPORTED_TARGET,
+ runtimesDir,
+ signal,
+ allowDownload,
+ timeoutMs,
+ fetchImpl
+ })
+ const noticesPath = await resolveNotices({
+ cacheDir,
+ verifiedSourceRoot,
+ signal,
+ timeoutMs,
+ fetchImpl
+ })
+
+ const workDir = await ensurePrivateDir(cacheDir, 'work')
+ const extractDir = join(workDir, `deb-${identity.contentId}-${randomUUID()}`)
+ const source = await acquireAndExtractDeb({ debPath, extractDir, signal, timeoutMs })
+ const stagingRoot = join(releasesDir, `.staging-${identity.contentId}-${randomUUID()}`)
+ await assertNoSymlinkAncestors(stagingRoot)
+ await mkdir(stagingRoot, { recursive: false, mode: 0o700 })
+ try {
+ const slot = await materializeOrcadSlot({
+ templateDir: source.templateDir,
+ outputSlotDir: join(stagingRoot, 'slot'),
+ target: identity.target
+ })
+ const web = await copyWebTree({
+ sourceDir: source.webDir,
+ destDir: join(stagingRoot, 'web')
+ })
+ await copyVerifiedFile({
+ sourcePath: nodeBinary,
+ destination: join(stagingRoot, identity.node.executablePath),
+ expectedSha256: identity.node.executableSha256,
+ mode: 0o700
+ })
+ await mkdir(join(stagingRoot, 'licenses'), { recursive: false, mode: 0o700 })
+ await extractAsarEntry({
+ asarPath: source.appAsarPath,
+ entryName: 'LICENSE',
+ destination: join(stagingRoot, 'licenses', 'LICENSE'),
+ expectedSha256: ORCA_LICENSE_SHA256
+ })
+ await copyVerifiedFile({
+ sourcePath: noticesPath,
+ destination: join(stagingRoot, 'licenses', 'THIRD_PARTY_NOTICES.md'),
+ expectedSha256: ORCA_THIRD_PARTY_NOTICES_SHA256
+ })
+ const receipt = buildReceipt({ identity, slot, web })
+ await writePrivateJson(join(stagingRoot, 'receipt.json'), receipt)
+
+ await verifyInstalledRelease({ releaseRoot: stagingRoot, identity })
+ if (await lstatOrNull(releaseRoot)) {
+ throw new Error(`Release appeared concurrently at ${releaseRoot}; refusing to overwrite`)
+ }
+ await rename(stagingRoot, releaseRoot)
+ await rm(extractDir, { recursive: true, force: true }).catch(() => {})
+ return await verifyInstalledRelease({ releaseRoot, identity })
+ } finally {
+ await rm(stagingRoot, { recursive: true, force: true }).catch(() => {})
+ }
+}
+
+export { getReleaseContentId, getReleaseIdentity } from './release-identity.mjs'
diff --git a/scripts/orca/safe-paths.mjs b/scripts/orca/safe-paths.mjs
new file mode 100644
index 00000000..e2ee13eb
--- /dev/null
+++ b/scripts/orca/safe-paths.mjs
@@ -0,0 +1,135 @@
+/**
+ * Filesystem guards shared by acquisition/materialization.
+ * Every path that will be read, written, renamed, or trusted goes through here.
+ */
+
+import { lstat, mkdir, realpath } from 'node:fs/promises'
+import { dirname, isAbsolute, join, normalize, relative, sep } from 'node:path'
+
+const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/
+
+export async function lstatOrNull(p) {
+ try {
+ return await lstat(p)
+ } catch (err) {
+ if (err.code === 'ENOENT') return null
+ throw err
+ }
+}
+
+export function isSafeRelativePath(relPath) {
+ if (typeof relPath !== 'string' || relPath.length === 0) return false
+ if (isAbsolute(relPath) || relPath.includes('\\') || CONTROL_CHAR_RE.test(relPath)) return false
+ const parts = relPath.split('/')
+ if (parts.some((p) => p === '' || p === '.' || p === '..')) return false
+ const normalized = normalize(relPath)
+ return normalized === relPath && !normalized.startsWith('..') && normalized !== '.'
+}
+
+/**
+ * Reject symlinked path components, including a symlink ancestor that hides a
+ * missing suffix (`link/missing/file`). Missing components are allowed as long
+ * as every existing ancestor is a real directory.
+ */
+export async function assertNoSymlinkAncestors(targetPath) {
+ if (typeof targetPath !== 'string' || !isAbsolute(targetPath)) {
+ throw new Error(`Path must be absolute: ${targetPath}`)
+ }
+ const chain = []
+ let current = normalize(targetPath)
+ for (;;) {
+ chain.push(current)
+ const parent = dirname(current)
+ if (parent === current) break
+ current = parent
+ }
+ for (const candidate of chain.reverse()) {
+ const s = await lstatOrNull(candidate)
+ if (!s) continue
+ if (s.isSymbolicLink()) {
+ throw new Error(`Refusing path with symlink component: ${candidate}`)
+ }
+ if (candidate !== chain[chain.length - 1] && !s.isDirectory()) {
+ throw new Error(`Refusing path with non-directory ancestor: ${candidate}`)
+ }
+ }
+}
+
+export async function resolveUnderRoot(root, relPath) {
+ if (!isSafeRelativePath(relPath)) throw new Error(`Unsafe relative path: ${relPath}`)
+ const resolvedRoot = await realpath(root)
+ const resolved = join(resolvedRoot, relPath)
+ assertContainedSync(resolvedRoot, resolved)
+ return resolved
+}
+
+export function assertContainedSync(root, candidate) {
+ const rel = relative(root, candidate)
+ if (rel === '' || rel.startsWith('..') || rel.includes(`..${sep}`) || isAbsolute(rel)) {
+ throw new Error(`Path ${candidate} is outside owned root ${root}`)
+ }
+ return candidate
+}
+
+export async function assertContained(root, candidate) {
+ const resolvedRoot = await realpath(root)
+ const parent = dirname(candidate)
+ const resolvedParent = await realpath(parent).catch(async (err) => {
+ if (err.code === 'ENOENT') return null
+ throw err
+ })
+ if (resolvedParent === null) {
+ assertContainedSync(resolvedRoot, normalize(candidate))
+ return candidate
+ }
+ assertContainedSync(resolvedRoot, join(resolvedParent, candidate.slice(parent.length + 1)))
+ return candidate
+}
+
+export async function ensurePrivateDir(parent, name) {
+ if (!isSafeRelativePath(name)) throw new Error(`Unsafe directory name: ${name}`)
+ await assertNoSymlinkAncestors(parent)
+ await mkdir(parent, { recursive: true, mode: 0o700 })
+ await assertOwnedPrivateDir(parent)
+ const dir = join(parent, name)
+ const existing = await lstatOrNull(dir)
+ if (!existing) {
+ await mkdir(dir, { recursive: true, mode: 0o700 })
+ }
+ await assertOwnedPrivateDir(dir)
+ return dir
+}
+
+/** Create `dir` (and parents) privately, refusing symlink ancestors first. */
+export async function ensurePrivateDirTree(dir) {
+ await assertNoSymlinkAncestors(dir)
+ await mkdir(dir, { recursive: true, mode: 0o700 })
+ await assertOwnedPrivateDir(dir)
+ return dir
+}
+
+export async function assertOwnedPrivateDir(dir) {
+ await assertNoSymlinkAncestors(dir)
+ const s = await lstat(dir)
+ if (!s.isDirectory() || s.isSymbolicLink()) {
+ throw new Error(`Expected a real directory: ${dir}`)
+ }
+ if (typeof process.getuid === 'function' && s.uid !== process.getuid()) {
+ throw new Error(`Directory is not owned by the current user: ${dir}`)
+ }
+ if ((s.mode & 0o077) !== 0) {
+ throw new Error(`Directory must be private (0700): ${dir}`)
+ }
+ return s
+}
+
+export async function assertOwnedRegularFile(filePath) {
+ await assertNoSymlinkAncestors(filePath)
+ const s = await lstat(filePath)
+ if (s.isSymbolicLink()) throw new Error(`Refusing symlink: ${filePath}`)
+ if (!s.isFile()) throw new Error(`Expected a regular file: ${filePath}`)
+ if (typeof process.getuid === 'function' && s.uid !== process.getuid()) {
+ throw new Error(`File is not owned by the current user: ${filePath}`)
+ }
+ return s
+}
diff --git a/scripts/orca/safe-paths.test.mjs b/scripts/orca/safe-paths.test.mjs
new file mode 100644
index 00000000..16a2bd38
--- /dev/null
+++ b/scripts/orca/safe-paths.test.mjs
@@ -0,0 +1,122 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { join } from 'node:path'
+import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import {
+ assertContained,
+ assertNoSymlinkAncestors,
+ assertOwnedPrivateDir,
+ assertOwnedRegularFile,
+ ensurePrivateDir,
+ isSafeRelativePath,
+ lstatOrNull,
+ resolveUnderRoot
+} from './safe-paths.mjs'
+
+async function scratch(name) {
+ return mkdtemp(join(tmpdir(), `orca-safe-${name}-`))
+}
+
+describe('safe-paths filesystem guards', () => {
+ it('rejects a symlinked file and every symlink ancestor', async () => {
+ const root = await scratch('symlink')
+ try {
+ const realDir = join(root, 'real')
+ await mkdir(realDir, { mode: 0o700 })
+ await writeFile(join(realDir, 'file.txt'), 'x', { mode: 0o600 })
+ await symlink(realDir, join(root, 'link-dir'))
+ await symlink(join(realDir, 'file.txt'), join(root, 'link-file'))
+
+ await assert.rejects(assertNoSymlinkAncestors(join(root, 'link-file')), /symlink/i)
+ await assert.rejects(
+ assertNoSymlinkAncestors(join(root, 'link-dir', 'file.txt')),
+ /symlink/i
+ )
+ // Missing suffix beneath a symlink ancestor is still refused.
+ await assert.rejects(
+ assertNoSymlinkAncestors(join(root, 'link-dir', 'missing', 'deep.txt')),
+ /symlink/i
+ )
+ await assert.doesNotReject(assertNoSymlinkAncestors(join(realDir, 'file.txt')))
+ await assert.doesNotReject(
+ assertNoSymlinkAncestors(join(root, 'missing', 'deep.txt'))
+ )
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects a regular file used as an ancestor', async () => {
+ const root = await scratch('file-ancestor')
+ try {
+ const file = join(root, 'plain')
+ await writeFile(file, 'x', { mode: 0o600 })
+ await assert.rejects(assertNoSymlinkAncestors(join(file, 'child')), /directory/i)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('requires absolute paths and private owned directories', async () => {
+ const root = await scratch('private')
+ try {
+ await assert.rejects(assertNoSymlinkAncestors('relative/path'), /absolute/i)
+
+ const openDir = join(root, 'open')
+ await mkdir(openDir, { mode: 0o755 })
+ await chmod(openDir, 0o755)
+ await assert.rejects(assertOwnedPrivateDir(openDir), /private/i)
+
+ const created = await ensurePrivateDir(root, 'nested/private')
+ assert.equal((await lstatOrNull(created))?.isDirectory(), true)
+ await assert.doesNotReject(assertOwnedPrivateDir(created))
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('checks regular file type and rejects symlinks', async () => {
+ const root = await scratch('regular')
+ try {
+ const real = join(root, 'real.bin')
+ await writeFile(real, 'payload', { mode: 0o600 })
+ await assert.doesNotReject(assertOwnedRegularFile(real))
+
+ const link = join(root, 'link.bin')
+ await symlink(real, link)
+ await assert.rejects(assertOwnedRegularFile(link), /symlink/i)
+ await assert.rejects(assertOwnedRegularFile(root), /regular file/i)
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('keeps resolved paths inside the owned root', async () => {
+ const root = await scratch('contain')
+ try {
+ assert.equal(await resolveUnderRoot(root, 'a/b.txt'), join(root, 'a', 'b.txt'))
+ await assert.rejects(resolveUnderRoot(root, '../escape'), /unsafe/i)
+ await assert.rejects(resolveUnderRoot(root, '/abs'), /unsafe/i)
+ await assert.rejects(resolveUnderRoot(root, 'a/../../escape'), /unsafe/i)
+
+ const outside = await mkdtemp(join(tmpdir(), 'orca-outside-'))
+ try {
+ await assert.rejects(assertContained(root, outside), /outside/i)
+ } finally {
+ await rm(outside, { recursive: true, force: true })
+ }
+ await assert.doesNotReject(assertContained(root, join(root, 'missing', 'file')))
+ } finally {
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('classifies manifest-relative paths conservatively', () => {
+ assert.equal(isSafeRelativePath('valid/file.js'), true)
+ assert.equal(isSafeRelativePath('.server-target'), true)
+ for (const bad of ['', '/abs', '../x', 'a/../../b', 'a/./b', 'a//b', 'a\\b', 'a/\x00/b', 'a/\n/b']) {
+ assert.equal(isSafeRelativePath(bad), false, bad)
+ }
+ })
+})
diff --git a/scripts/orca/slot-manifest.mjs b/scripts/orca/slot-manifest.mjs
new file mode 100644
index 00000000..d79bb59e
--- /dev/null
+++ b/scripts/orca/slot-manifest.mjs
@@ -0,0 +1,151 @@
+/**
+ * Strict validation of the upstream orcad-template manifest.
+ *
+ * The manifest is one release contract: schema 3, plain objects only, safe
+ * relative paths, SHA-256 digests, the exact upstream common list, exactly the
+ * five linux-x64-glibc target files, and no target key that shadows a common
+ * key. The final slot is always 175 files.
+ */
+
+import {
+ ORCAD_COMMON_FILES,
+ ORCAD_SLOT_FILE_COUNT,
+ ORCAD_TARGET_FILES,
+ PINNED_NODE,
+ SUPPORTED_TARGET,
+ isSupportedTarget
+} from './constants.mjs'
+import { isSafeRelativePath } from './safe-paths.mjs'
+
+const SHA256_RE = /^[a-f0-9]{64}$/
+const MOBILE_PREFIX = 'out/mobile-web/'
+const MANIFEST_NAME = 'out/mobile-web/manifest.json'
+const WATCHER_ENTRY_NAME = 'node_modules/@parcel/watcher/index.js'
+
+function compareCodeUnits(left, right) {
+ return left < right ? -1 : left > right ? 1 : 0
+}
+
+function isPlainObject(value) {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
+ const proto = Object.getPrototypeOf(value)
+ return proto === Object.prototype || proto === null
+}
+
+function assertDigest(name, digest, label) {
+ if (typeof digest !== 'string' || !SHA256_RE.test(digest)) {
+ throw new Error(`Missing or invalid digest for ${label}: ${name}`)
+ }
+}
+
+export function verifyManifestSchema(manifest) {
+ if (!isPlainObject(manifest)) throw new Error('Invalid manifest: root must be an object')
+ if (manifest.schemaVersion !== 3) {
+ throw new Error(`Unsupported schema version: ${manifest.schemaVersion}, expected 3`)
+ }
+ if (!isPlainObject(manifest.commonSha256)) {
+ throw new Error('Invalid manifest: commonSha256 must be an object')
+ }
+ if (!isPlainObject(manifest.targets)) {
+ throw new Error('Invalid manifest: targets must be an object')
+ }
+ for (const [name, digest] of Object.entries(manifest.commonSha256)) {
+ if (!isSafeRelativePath(name)) throw new Error(`Unsafe manifest path: ${name}`)
+ assertDigest(name, digest, 'common file')
+ }
+ for (const [targetName, target] of Object.entries(manifest.targets)) {
+ if (!isSafeRelativePath(targetName)) throw new Error(`Unsafe target name: ${targetName}`)
+ if (!isPlainObject(target) || !isPlainObject(target.files)) {
+ throw new Error(`Invalid manifest target: ${targetName}`)
+ }
+ for (const [name, digest] of Object.entries(target.files)) {
+ if (!isSafeRelativePath(name)) throw new Error(`Unsafe target path: ${name}`)
+ assertDigest(name, digest, `target ${targetName} file`)
+ }
+ }
+}
+
+function assertExactSet(actual, expected, label) {
+ const actualSet = new Set(actual)
+ const expectedSet = new Set(expected)
+ for (const name of expectedSet) {
+ if (!actualSet.has(name)) throw new Error(`Manifest is missing ${label}: ${name}`)
+ }
+ for (const name of actualSet) {
+ if (!expectedSet.has(name)) throw new Error(`Manifest has an unexpected ${label}: ${name}`)
+ }
+}
+
+function mobileAssets(manifest) {
+ return Object.keys(manifest.commonSha256)
+ .filter((name) => name.startsWith(MOBILE_PREFIX) && name !== MANIFEST_NAME)
+ .sort(compareCodeUnits)
+}
+
+/**
+ * Upstream artifact identity order (`orcadArtifactFilenames` in
+ * src/shared/orcad-artifacts.ts): the common artifacts with the three
+ * target-only common positions interleaved where upstream lists them, then the
+ * native PTY and ripgrep artifacts, then the sorted mobile page assets.
+ * `filenames` is the slot's file set; the result is a permutation of it.
+ */
+export function getUpstreamArtifactOrder(filenames) {
+ const [serverTarget, runtimeMarker, watcherNative, ptyNative, ripgrep] = ORCAD_TARGET_FILES
+ const mobile = filenames
+ .filter((name) => name.startsWith(MOBILE_PREFIX) && name !== MANIFEST_NAME)
+ .sort(compareCodeUnits)
+ const order = []
+ for (const name of ORCAD_COMMON_FILES) {
+ if (name === WATCHER_ENTRY_NAME) order.push(serverTarget, runtimeMarker, name, watcherNative)
+ else if (name === MANIFEST_NAME) order.push(name, ptyNative, ripgrep)
+ else order.push(name)
+ }
+ order.push(...mobile)
+ const expected = new Set(filenames)
+ const isPermutation =
+ order.length === filenames.length &&
+ new Set(order).size === order.length &&
+ order.every((name) => expected.has(name))
+ if (!isPermutation) throw new Error('Upstream artifact order is not a permutation of the slot files')
+ return order
+}
+
+export function getSlotArtifactFilenames(target, manifest) {
+ if (!isSupportedTarget(target)) throw new Error(`Unsupported target: ${target}`)
+ verifyManifestSchema(manifest)
+ const mobile = mobileAssets(manifest)
+ assertExactSet(Object.keys(manifest.commonSha256), [...ORCAD_COMMON_FILES, ...mobile], 'common file')
+
+ const targetManifest = manifest.targets[target]
+ if (!targetManifest) throw new Error(`Template manifest does not support target: ${target}`)
+ assertExactSet(Object.keys(targetManifest.files), ORCAD_TARGET_FILES, 'target file')
+ for (const name of ORCAD_TARGET_FILES) {
+ if (Object.hasOwn(manifest.commonSha256, name)) {
+ throw new Error(`Target file must not shadow a common file: ${name}`)
+ }
+ }
+
+ const filenames = [...ORCAD_COMMON_FILES, ...ORCAD_TARGET_FILES, ...mobile]
+ if (filenames.length !== ORCAD_SLOT_FILE_COUNT) {
+ throw new Error(
+ `Slot file contract mismatch: expected ${ORCAD_SLOT_FILE_COUNT}, got ${filenames.length}`
+ )
+ }
+ return filenames
+}
+
+export function verifyTargetMarkers({
+ serverTarget,
+ runtimeNodeSha256,
+ target = SUPPORTED_TARGET,
+ expectedNodeSha256 = PINNED_NODE.executableSha256
+}) {
+ if (serverTarget.trim() !== target) {
+ throw new Error(`Target identity mismatch: expected ${target}, got ${serverTarget.trim()}`)
+ }
+ if (runtimeNodeSha256.trim() !== expectedNodeSha256) {
+ throw new Error(
+ `Runtime node pin mismatch: expected ${expectedNodeSha256}, got ${runtimeNodeSha256.trim()}`
+ )
+ }
+}
diff --git a/scripts/orca/smoke.mjs b/scripts/orca/smoke.mjs
new file mode 100644
index 00000000..4c25df1f
--- /dev/null
+++ b/scripts/orca/smoke.mjs
@@ -0,0 +1,103 @@
+/**
+ * Disposable smoke proof: launch on a scratch loopback port, probe the real web
+ * bundle, then create/read/close one real PTY via the Orca CLI. Always cleans the
+ * task-owned server and daemon.
+ */
+
+import { existsSync } from 'node:fs'
+import { join } from 'node:path'
+import { DEFAULT_BIND } from './constants.mjs'
+import { createIsolatedEnv } from './env.mjs'
+import { launchOrcadServer } from './lifecycle.mjs'
+import { initScratchGitRepo, verifyRealTerminalEcho } from './terminal-proof.mjs'
+
+const WEB_TITLE = '<title>Orca Web</title>'
+
+function actualPort(boundEndpoint) {
+ try {
+ const port = Number(new URL(boundEndpoint).port)
+ return Number.isInteger(port) && port > 0 ? port : null
+ } catch {
+ return null
+ }
+}
+
+export async function probeWebClient(boundEndpoint, { timeoutMs = 5000 } = {}) {
+ const port = actualPort(boundEndpoint)
+ if (!port) throw new Error(`bound endpoint has no usable port: ${boundEndpoint}`)
+ const url = new URL(`http://127.0.0.1:${port}/web-index.html`)
+ const res = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) })
+ if (!res.ok) throw new Error(`web client probe failed: HTTP ${res.status}`)
+ const html = await res.text()
+ if (!html.includes(WEB_TITLE)) throw new Error(`web client HTML did not contain ${WEB_TITLE}`)
+ return { url: url.href, status: res.status }
+}
+
+export async function runSmokeProof({
+ release,
+ managedRoot,
+ port = 0,
+ bind = DEFAULT_BIND,
+ advertisedEndpoint,
+ timeoutMs = 30000,
+ log = console
+} = {}) {
+ if (!release?.slotDir || !release?.nodeBinary || !release?.webDir) {
+ throw new Error('runSmokeProof requires a prepared release')
+ }
+ const cliPath = join(release.slotDir, 'out', 'cli', 'index.js')
+ if (!existsSync(cliPath)) throw new Error(`Orca CLI entry is missing: ${cliPath}`)
+
+ const env = createIsolatedEnv({ scratchDir: managedRoot })
+ const instance = await launchOrcadServer({
+ nodeBinary: release.nodeBinary,
+ slotDir: release.slotDir,
+ options: {
+ bind,
+ port,
+ webClientRoot: release.webDir,
+ ...(advertisedEndpoint
+ ? { advertisedEndpoint, pairingAddress: advertisedEndpoint }
+ : { allowLoopbackAdvertised: true })
+ },
+ env,
+ managedRoot,
+ timeoutMs,
+ privateStatusPath: join(managedRoot, 'private-status.json'),
+ runtimeIdentityPath: join(managedRoot, 'runtime-identity.json')
+ })
+
+ try {
+ log.log(`[orca-cli] Ready: ${instance.redacted.boundEndpoint}`)
+ log.log(`[orca-cli] Safe metadata: ${JSON.stringify(instance.redacted)}`)
+
+ const web = await probeWebClient(instance.readyPayload.boundEndpoint)
+ log.log(`[orca-cli] Web client probe passed: ${web.url} (HTTP ${web.status})`)
+
+ const pairingUrl = instance.readyPayload.pairing?.url
+ if (typeof pairingUrl !== 'string' || pairingUrl.length === 0) {
+ throw new Error('readiness payload has no pairing URL')
+ }
+ const proofRepo = await initScratchGitRepo(join(managedRoot, 'proof-repo'))
+ const echoToken = `ORCA_ECHO_PASSED_${Date.now()}`
+ log.log(`[orca-cli] Running PTY echo proof with token ${echoToken}...`)
+ const echo = await verifyRealTerminalEcho({
+ nodeBinary: release.nodeBinary,
+ cliPath,
+ cliEnv: { ...env, ORCA_PAIRING_CODE: pairingUrl },
+ testRepo: proofRepo,
+ echoToken
+ })
+ log.log('[orca-cli] PTY echo proof passed; closing terminal.')
+
+ return {
+ version: release.version,
+ redacted: instance.redacted,
+ web,
+ echo: { observed: echo.echoObserved, termHandle: echo.termHandle }
+ }
+ } finally {
+ log.log('[orca-cli] Stopping server and task-owned terminal daemon...')
+ await instance.stop({ cleanDaemon: true })
+ }
+}
diff --git a/scripts/orca/supervision.mjs b/scripts/orca/supervision.mjs
new file mode 100644
index 00000000..05f5e258
--- /dev/null
+++ b/scripts/orca/supervision.mjs
@@ -0,0 +1,167 @@
+/**
+ * Persistent supervised Orca run. Signal handlers exist before spawn, startup
+ * abort cancels the launch through AbortSignal, and an unexpected child exit
+ * fails the wrapper instead of leaving it alive. Never prints pairing material.
+ */
+
+import { join } from 'node:path'
+import { DEFAULT_BIND, DEFAULT_PORT } from './constants.mjs'
+import { createIsolatedEnv } from './env.mjs'
+import { launchOrcadServer } from './lifecycle.mjs'
+import { sanitizeEndpoint } from './launcher.mjs'
+import { redactSensitiveText } from './bounded-proc.mjs'
+
+const LOOPBACK_HOSTS = new Set(['localhost', '::1', '[::1]', '0.0.0.0', '[::]', '::'])
+
+export function assertConfiguredAdvertisedEndpoint(value) {
+ if (typeof value !== 'string' || value.length === 0) {
+ throw new Error('run requires --advertised-endpoint (configured wss URL)')
+ }
+ let url
+ try {
+ url = new URL(value)
+ } catch {
+ throw new Error(`advertised endpoint is not a valid URL: ${value}`)
+ }
+ if (url.protocol !== 'wss:') throw new Error('advertised endpoint must use wss://')
+ if (url.username || url.password || url.search || url.hash) {
+ throw new Error('advertised endpoint must not contain credentials, query, or fragment')
+ }
+ if (LOOPBACK_HOSTS.has(url.hostname) || /^127\./.test(url.hostname)) {
+ throw new Error('advertised endpoint must not be loopback for a persistent run')
+ }
+ const normalized = sanitizeEndpoint(value)
+ if (!normalized) throw new Error('advertised endpoint is malformed')
+ return normalized
+}
+
+export function assertPersistentPort(port) {
+ const value = Number(port)
+ if (!Number.isInteger(value) || value < 1 || value > 65535) {
+ throw new Error(`run requires a fixed port 1-65535, got: ${port}`)
+ }
+ return value
+}
+
+export async function runSupervisedRuntime({
+ release,
+ managedRoot,
+ port = DEFAULT_PORT,
+ bind = DEFAULT_BIND,
+ advertisedEndpoint,
+ timeoutMs = 30000,
+ log = console,
+ launch = launchOrcadServer
+} = {}) {
+ if (!release?.slotDir || !release?.nodeBinary || !release?.webDir) {
+ throw new Error('runSupervisedRuntime requires a prepared release')
+ }
+ const fixedPort = assertPersistentPort(port)
+ const advertised = assertConfiguredAdvertisedEndpoint(advertisedEndpoint)
+ const env = createIsolatedEnv({ scratchDir: managedRoot })
+
+ let phase = 'starting'
+ let startupSignal = null
+ let resolveSignal
+ const signaled = new Promise((resolve) => {
+ resolveSignal = resolve
+ })
+ const abortController = new AbortController()
+ const handlers = new Map(
+ ['SIGINT', 'SIGTERM'].map((signal) => {
+ const handler = () => {
+ if (phase === 'starting') {
+ if (!startupSignal) {
+ startupSignal = signal
+ abortController.abort(new Error(`startup cancelled by ${signal}`))
+ }
+ return
+ }
+ resolveSignal(signal)
+ }
+ process.once(signal, handler)
+ return [signal, handler]
+ })
+ )
+
+ let instance = null
+ let stopCompleted = false
+ try {
+ try {
+ instance = await launch({
+ nodeBinary: release.nodeBinary,
+ slotDir: release.slotDir,
+ options: {
+ bind,
+ port: fixedPort,
+ webClientRoot: release.webDir,
+ advertisedEndpoint: advertised,
+ pairingAddress: advertised
+ },
+ env,
+ managedRoot,
+ timeoutMs,
+ signal: abortController.signal,
+ privateStatusPath: join(managedRoot, 'private-status.json'),
+ runtimeIdentityPath: join(managedRoot, 'runtime-identity.json')
+ })
+ } catch (err) {
+ if (startupSignal) {
+ throw new Error(`supervised startup cancelled by ${startupSignal}: ${redactSensitiveText(err.message)}`)
+ }
+ throw err
+ }
+ if (startupSignal) {
+ // Readiness can win the race against the abort listener; never leave a
+ // successfully launched runtime running after a startup signal.
+ await instance.stop({ cleanDaemon: true })
+ stopCompleted = true
+ throw new Error(`supervised startup cancelled by ${startupSignal}`)
+ }
+ phase = 'running'
+ log.log(
+ `[orca-cli] Runtime ready: ${instance.redacted.boundEndpoint} (advertised ${instance.redacted.advertisedEndpoint})`
+ )
+ log.log(`[orca-cli] Safe metadata: ${JSON.stringify(instance.redacted)}`)
+
+ const outcome = await Promise.race([
+ signaled.then((signal) => ({ kind: 'signal', signal })),
+ instance.childExit.then((exit) => ({ kind: 'exit', exit }))
+ ])
+ const childExited = instance.child.exitCode !== null || instance.child.signalCode !== null
+ if (outcome.kind === 'exit' || (outcome.kind === 'signal' && childExited)) {
+ const exit = outcome.kind === 'exit' ? outcome.exit : { code: instance.child.exitCode, signal: instance.child.signalCode }
+ let cleanup = null
+ let cleanupError = null
+ try {
+ cleanup = await instance.stop({ cleanDaemon: false })
+ stopCompleted = true
+ } catch (err) {
+ cleanupError = err
+ }
+ const detail = `orcad-server exited unexpectedly (code ${exit.code}, signal ${exit.signal})`
+ if (cleanupError) {
+ throw new Error(`${detail}; cleanup failed: ${redactSensitiveText(cleanupError.message)}`)
+ }
+ throw new Error(
+ `${detail}; receipts cleared=${Boolean(cleanup?.receiptsCleared)}; daemon preserved=${cleanup?.daemonPreserved}`
+ )
+ }
+
+ const signal = outcome.signal
+ log.log(`[orca-cli] Received ${signal}; stopping server...`)
+ const stopResult = await instance.stop({ cleanDaemon: false })
+ stopCompleted = true
+ if (stopResult.daemonPreserved === true) {
+ log.log('[orca-cli] Server stopped; verified terminal daemon is still running.')
+ } else if (stopResult.daemonPreserved === false) {
+ log.log('[orca-cli] Server stopped; terminal daemon is not running.')
+ } else {
+ log.log('[orca-cli] Server stopped; terminal daemon state is unknown (not promising persistence).')
+ }
+ return { signal, stop: stopResult, redacted: instance.redacted }
+ } finally {
+ for (const [signal, handler] of handlers) process.removeListener(signal, handler)
+ if (instance && !stopCompleted) await instance.stop({ cleanDaemon: false }).catch(() => {})
+ }
+}
diff --git a/scripts/orca/supervision.test.mjs b/scripts/orca/supervision.test.mjs
new file mode 100644
index 00000000..c57e74ba
--- /dev/null
+++ b/scripts/orca/supervision.test.mjs
@@ -0,0 +1,186 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdir, readFile, lstat, mkdtemp, rm, writeFile } from 'node:fs/promises'
+import { createServer } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { runSupervisedRuntime } from './supervision.mjs'
+import { launchOrcadServer } from './lifecycle.mjs'
+import { discoverOwnedDaemon } from './daemon-identity.mjs'
+import { ensureIsolatedDirectories } from './env.mjs'
+import { terminateVerifiedProcess } from './proc-identity.mjs'
+
+const FIXTURES = fileURLToPath(new URL('./fixtures/', import.meta.url))
+const FAKE_SERVER = join(FIXTURES, 'fake-orcad-server.mjs')
+const DAEMON_ENTRY = join(FIXTURES, 'daemon-entry.js')
+const NODE = process.execPath
+
+function sleep(ms) {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}
+
+async function makeRoot() {
+ const root = await mkdtemp(join(tmpdir(), 'orca-supervision-'))
+ await ensureIsolatedDirectories(root)
+ const webDir = join(root, 'web')
+ await mkdir(webDir, { mode: 0o700 })
+ await writeFile(join(webDir, 'web-index.html'), '<!doctype html><title>fixture</title>')
+ return root
+}
+
+async function freePort() {
+ return new Promise((resolve, reject) => {
+ const server = createServer()
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', () => {
+ const { port } = server.address()
+ server.close(() => resolve(port))
+ })
+ })
+}
+
+async function waitForPids(root, timeoutMs = 4000) {
+ const file = join(root, 'runtime', 'user-data', 'fake-pids.json')
+ const deadline = Date.now() + timeoutMs
+ for (;;) {
+ try {
+ return JSON.parse(await readFile(file, 'utf8'))
+ } catch {
+ if (Date.now() >= deadline) throw new Error('fake pids were not written')
+ await sleep(25)
+ }
+ }
+}
+
+async function waitGone(pid, timeoutMs = 4000) {
+ const deadline = Date.now() + timeoutMs
+ for (;;) {
+ try {
+ process.kill(pid, 0)
+ if (Date.now() >= deadline) return false
+ await sleep(25)
+ } catch {
+ return true
+ }
+ }
+}
+
+function launchFor(mode, env = {}) {
+ return (options) =>
+ launchOrcadServer({
+ ...options,
+ serverEntry: FAKE_SERVER,
+ daemonEntryPath: DAEMON_ENTRY,
+ env: { ...options.env, FAKE_MODE: mode, ...env }
+ })
+}
+
+function baseOptions(root, port, mode, env) {
+ const logs = []
+ return {
+ release: { slotDir: FIXTURES, nodeBinary: NODE, webDir: join(root, 'web') },
+ managedRoot: root,
+ port,
+ advertisedEndpoint: 'wss://orca-supervision-proof.invalid',
+ timeoutMs: 6000,
+ log: { log: (line) => logs.push(line) },
+ launch: launchFor(mode, env),
+ logs
+ }
+}
+
+async function cleanupDaemon(root) {
+ const userData = join(root, 'runtime', 'user-data')
+ const identity = await discoverOwnedDaemon({
+ userData,
+ nodeBinary: NODE,
+ daemonEntryPath: DAEMON_ENTRY,
+ waitMs: 1000
+ })
+ if (identity) await terminateVerifiedProcess(identity, { timeoutMs: 3000 })
+}
+
+describe('supervised wrapper signal and child-exit supervision', () => {
+ it('cancels a delayed startup through AbortSignal and reaps the owned child/daemon', async () => {
+ const root = await makeRoot()
+ const port = await freePort()
+ try {
+ const promise = runSupervisedRuntime(baseOptions(root, port, 'delayed-ready', { FAKE_READY_DELAY_MS: '1500' }))
+ const pids = await waitForPids(root)
+ process.emit('SIGTERM', 'SIGTERM')
+ await assert.rejects(promise, /cancelled by SIGTERM/i)
+ assert.equal(await waitGone(pids.serverPid), true)
+ assert.equal(await waitGone(pids.daemonPid), true)
+ await assert.rejects(lstat(join(root, 'private-status.json')))
+ await assert.rejects(lstat(join(root, 'runtime-identity.json')))
+ } finally {
+ await cleanupDaemon(root).catch(() => {})
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('fails the wrapper on an unexpected child exit, clears receipts, and preserves restart state', async () => {
+ const root = await makeRoot()
+ const port = await freePort()
+ try {
+ await assert.rejects(
+ () => runSupervisedRuntime(baseOptions(root, port, 'crash-after-ready', { FAKE_CRASH_DELAY_MS: '200' })),
+ /exited unexpectedly \(code 42/i
+ )
+ const pids = await waitForPids(root)
+ assert.equal(await waitGone(pids.serverPid), true)
+ await assert.rejects(lstat(join(root, 'private-status.json')))
+ await assert.rejects(lstat(join(root, 'runtime-identity.json')))
+ } finally {
+ await cleanupDaemon(root).catch(() => {})
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('does not leave a runtime alive when a startup signal lands after readiness', async () => {
+ const root = await makeRoot()
+ const port = await freePort()
+ try {
+ const options = baseOptions(root, port, 'normal')
+ const realLaunch = options.launch
+ options.launch = async (launchOptions) => {
+ const instance = await realLaunch(launchOptions)
+ process.emit('SIGTERM', 'SIGTERM')
+ return instance
+ }
+ await assert.rejects(() => runSupervisedRuntime(options), /cancelled by SIGTERM/i)
+ const pids = JSON.parse(await readFile(join(root, 'runtime', 'user-data', 'fake-pids.json'), 'utf8'))
+ assert.equal(await waitGone(pids.serverPid), true)
+ assert.equal(await waitGone(pids.daemonPid), true)
+ await assert.rejects(lstat(join(root, 'private-status.json')))
+ } finally {
+ await cleanupDaemon(root).catch(() => {})
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+
+ it('handles SIGTERM after readiness and reports verified daemon preservation', async () => {
+ const root = await makeRoot()
+ const port = await freePort()
+ try {
+ const options = baseOptions(root, port, 'normal')
+ const promise = runSupervisedRuntime(options)
+ const deadline = Date.now() + 5000
+ while (!options.logs.some((line) => line.includes('Runtime ready'))) {
+ if (Date.now() >= deadline) throw new Error('runtime did not report readiness')
+ await sleep(25)
+ }
+ const pids = await waitForPids(root)
+ process.emit('SIGTERM', 'SIGTERM')
+ const result = await promise
+ assert.equal(result.signal, 'SIGTERM')
+ assert.equal(result.stop.daemonPreserved, true)
+ assert.equal(await waitGone(pids.serverPid), true)
+ assert.equal(await waitGone(pids.daemonPid, 1000), false)
+ } finally {
+ await cleanupDaemon(root).catch(() => {})
+ await rm(root, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/systemd-unit.mjs b/scripts/orca/systemd-unit.mjs
new file mode 100644
index 00000000..bc214e16
--- /dev/null
+++ b/scripts/orca/systemd-unit.mjs
@@ -0,0 +1,169 @@
+/**
+ * Deterministic systemd user-unit rendering for the MSO-owned Orca runtime.
+ *
+ * The unit is generated only from validated, code-owned values. It never
+ * contains a pairing token, a request value, or free-form environment, and it
+ * always names this repository's CLI entry point rather than a mutable path.
+ *
+ * `KillMode=process` owns only the main dispatcher process. The Orca CLI's
+ * terminal daemon is a separate, verified MSO-owned process whose lifetime this
+ * unit does not guarantee; stopping or restarting the unit must not be
+ * presented as preserving terminal sessions. Orphaned daemons are not claimed
+ * to be safe, and this file promises no persistence.
+ */
+
+import { lstat, readFile } from 'node:fs/promises'
+import { dirname, isAbsolute } from 'node:path'
+import { DEFAULT_PORT } from './constants.mjs'
+import { SERVICE_NAME, UNIT_IDENTITY_MARKER } from './managed-paths.mjs'
+import { assertConfiguredAdvertisedEndpoint, assertPersistentPort } from './supervision.mjs'
+import { renderUnitText, systemdQuote } from './unit-render.mjs'
+import { readOwnedUnitFile } from './unit-read.mjs'
+
+export { systemdQuote }
+
+const CONTROL = /[\0\r\n]/
+
+function assertCleanString(value, label) {
+ if (typeof value !== 'string' || value.length === 0) throw new Error(`${label} must be a non-empty string`)
+ if (CONTROL.test(value)) throw new Error(`${label} must not contain control characters`)
+ return value
+}
+
+function assertAbsoluteClean(value, label) {
+ assertCleanString(value, label)
+ if (!isAbsolute(value)) throw new Error(`${label} must be an absolute path, got: ${value}`)
+ return value
+}
+
+/**
+ * Render the one fixed user unit. All values are validated here; the exact
+ * bytes come from the pure shared renderer used by the ownership proof too.
+ */
+export function renderOrcaServiceUnit({
+ hostNode,
+ cliScript,
+ managedRoot,
+ port = DEFAULT_PORT,
+ advertisedEndpoint,
+ identityMarker = UNIT_IDENTITY_MARKER,
+ serviceName = SERVICE_NAME
+} = {}) {
+ const node = assertAbsoluteClean(hostNode, 'host node binary')
+ const cli = assertAbsoluteClean(cliScript, 'Orca CLI script')
+ const root = assertAbsoluteClean(managedRoot, 'managed root')
+ const fixedPort = assertPersistentPort(port)
+ const advertised = assertConfiguredAdvertisedEndpoint(advertisedEndpoint)
+ const marker = assertCleanString(identityMarker, 'unit identity marker')
+
+ return renderUnitText({
+ marker,
+ serviceName,
+ hostNode: node,
+ cliScript: cli,
+ managedRoot: root,
+ port: fixedPort,
+ advertisedEndpoint: advertised
+ })
+}
+
+/**
+ * A unit may be replaced only when this adapter's exact identity is present and,
+ * when expectedUnit or expectedConfig is provided, matches byte-for-byte.
+ * Extraneous directives, foreign ExecStart, ExecStartPre/Post hooks, and
+ * wrapper scripts are rejected.
+ */
+export function isManagedOrcaUnit(text, expectedUnit = null) {
+ if (typeof text !== 'string') return false
+ if (typeof expectedUnit === 'string') {
+ return text === expectedUnit
+ }
+ if (expectedUnit && typeof expectedUnit === 'object') {
+ return text === renderOrcaServiceUnit(expectedUnit)
+ }
+ if (!text.startsWith(`${UNIT_IDENTITY_MARKER}\n`)) return false
+ if (/^ExecStart(?:Pre|Post)=/m.test(text)) return false
+ if (/^EnvironmentFile=/m.test(text)) return false
+
+ const execLine = text.match(/^ExecStart=(.+)$/m)
+ if (!execLine) return false
+ const exec = execLine[1]
+
+ if (!exec.includes('--managed-root')) return false
+
+ const validExec = /^("?(?:[^"\\]|\\.)*node"?) ("?(?:[^"\\]|\\.)*\/scripts\/orca\/cli\.mjs"?) "run"/m.test(exec)
+ if (!validExec) return false
+
+ return true
+}
+
+/**
+ * Refuse a symlinked unit or a symlinked ancestor before reading or writing: a
+ * symlink could redirect the write into the operator's own Orca state.
+ *
+ * EVERY ancestor from the unit up to the filesystem root is inspected, including
+ * components above the nearest existing directory. Stopping at the first path
+ * that exists (as an earlier version did) accepted an existing regular unit, or a
+ * missing leaf, reached through a symlinked parent. `lstat` never follows a link
+ * and never opens or reads the target, so a FIFO ancestor cannot block.
+ */
+async function assertNoSymlinkUnitPath(unitPath) {
+ let current = unitPath
+ for (;;) {
+ const info = await lstat(current).catch((err) => {
+ if (err.code === 'ENOENT') return null
+ throw err
+ })
+ if (info?.isSymbolicLink()) throw new Error(`refusing a symlinked unit path: ${current}`)
+ const parent = dirname(current)
+ if (parent === current) return
+ current = parent
+ }
+}
+
+/**
+ * Fail closed on a pre-existing unit we did not generate. Returns 'absent' or
+ * 'managed'; a foreign unit is an error before any download or service action.
+ * Rejects symlinked paths and non-regular/foreign files instead of trusting the
+ * marker alone.
+ */
+export async function inspectExistingUnit({
+ unitPath,
+ expectedUnit,
+ expectedConfig,
+ read,
+ uid = typeof process.getuid === 'function' ? process.getuid() : null
+} = {}) {
+ assertAbsoluteClean(unitPath, 'unit path')
+ await assertNoSymlinkUnitPath(unitPath)
+
+ let targetExpected = expectedUnit
+ if (!targetExpected && expectedConfig) {
+ targetExpected = renderOrcaServiceUnit(expectedConfig)
+ }
+
+ try {
+ let text
+ if (typeof read === 'function') {
+ const info = await lstat(unitPath)
+ if (!info.isFile() || info.isSymbolicLink()) {
+ throw new Error(`refusing a non-regular unit: ${unitPath}`)
+ }
+ if (uid !== null && info.uid !== uid) {
+ throw new Error(`refusing a unit not owned by this user: ${unitPath}`)
+ }
+ text = await read(unitPath)
+ } else {
+ text = await readOwnedUnitFile(unitPath, uid)
+ if (text === null) return { state: 'absent', text: null }
+ }
+
+ if (!isManagedOrcaUnit(text, targetExpected)) {
+ throw new Error(`refusing to overwrite an existing foreign unit: ${unitPath}`)
+ }
+ return { state: 'managed', text }
+ } catch (err) {
+ if (err?.code === 'ENOENT') return { state: 'absent', text: null }
+ throw err
+ }
+}
diff --git a/scripts/orca/systemd-unit.test.mjs b/scripts/orca/systemd-unit.test.mjs
new file mode 100644
index 00000000..51aefc7d
--- /dev/null
+++ b/scripts/orca/systemd-unit.test.mjs
@@ -0,0 +1,94 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtemp, symlink, writeFile, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import {
+ inspectExistingUnit,
+ isManagedOrcaUnit,
+ renderOrcaServiceUnit,
+ systemdQuote
+} from './systemd-unit.mjs'
+
+const BASE = {
+ hostNode: '/usr/bin/node',
+ cliScript: '/opt/mso/scripts/orca/cli.mjs',
+ managedRoot: '/home/operator/.local/share/mso/orca',
+ port: 6769,
+ advertisedEndpoint: 'wss://orca.mso.example.com'
+}
+
+describe('Orca user unit rendering', () => {
+ it('renders one fixed run argv on the canonical CLI path', () => {
+ const unit = renderOrcaServiceUnit(BASE)
+ assert.match(unit, /^\# mso-managed-app: orca$/m)
+ assert.match(unit, /ExecStart="\/usr\/bin\/node" "\/opt\/mso\/scripts\/orca\/cli\.mjs" "run"/)
+ assert.match(unit, /"--managed-root" "\/home\/operator\/\.local\/share\/mso\/orca"/)
+ assert.match(unit, /"--port" "6769"/)
+ assert.match(unit, /"--advertised-endpoint" "wss:\/\/orca\.mso\.example\.com"/)
+ assert.match(unit, /^KillMode=process$/m)
+ assert.match(unit, /^Restart=on-failure$/m)
+ assert.match(unit, /^StartLimitBurst=3$/m)
+ assert.match(unit, /^TimeoutStartSec=90$/m)
+ assert.equal(isManagedOrcaUnit(unit), true)
+ assert.doesNotMatch(unit, /pairing|token|ticket|secret/i)
+ })
+
+ it('escapes spaces, quotes, backslashes, percent specifiers and dollars', () => {
+ const unit = renderOrcaServiceUnit({
+ ...BASE,
+ hostNode: '/opt/Node 24/bin/node',
+ managedRoot: '/srv/mso/orca %h "quoted" \\ $HOME'
+ })
+ assert.match(unit, /"\/opt\/Node 24\/bin\/node"/)
+ assert.match(unit, /orca %%h \\"quoted\\" \\\\ \$\$HOME/)
+ // The specifier/env syntaxes the unit must never expand are escaped.
+ assert.ok(unit.includes('%%h'))
+ assert.ok(unit.includes('$$HOME'))
+ })
+
+ it('quotes a single argument as one systemd token', () => {
+ assert.equal(systemdQuote('plain'), '"plain"')
+ assert.equal(systemdQuote('a b'), '"a b"')
+ assert.equal(systemdQuote('a"b'), '"a\\"b"')
+ assert.equal(systemdQuote('100%'), '"100%%"')
+ assert.throws(() => systemdQuote('a\nb'), /control/)
+ })
+
+ it('refuses non-absolute, dynamic, loopback and malformed configuration', () => {
+ assert.throws(() => renderOrcaServiceUnit({ ...BASE, hostNode: 'node' }), /absolute/)
+ assert.throws(() => renderOrcaServiceUnit({ ...BASE, managedRoot: 'relative' }), /absolute/)
+ assert.throws(() => renderOrcaServiceUnit({ ...BASE, port: 0 }), /fixed port/)
+ assert.throws(() => renderOrcaServiceUnit({ ...BASE, port: 70000 }), /fixed port/)
+ assert.throws(() => renderOrcaServiceUnit({ ...BASE, advertisedEndpoint: 'ws://orca.example' }), /wss/i)
+ assert.throws(() => renderOrcaServiceUnit({ ...BASE, advertisedEndpoint: 'wss://127.0.0.1:6769' }), /loopback/i)
+ assert.throws(() => renderOrcaServiceUnit({ ...BASE, cliScript: '/x/y\nExecStart=/bin/evil' }), /control/)
+ })
+
+ it('detects a foreign unit and refuses to overwrite it', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'ou-'))
+ try {
+ const foreign = join(dir, 'mso-orca.service')
+ await writeFile(foreign, '[Service]\nExecStart=/usr/bin/orca --port 6768\n')
+ await assert.rejects(() => inspectExistingUnit({ unitPath: foreign }), /foreign unit/)
+ await writeFile(foreign, renderOrcaServiceUnit(BASE))
+ assert.equal((await inspectExistingUnit({ unitPath: foreign })).state, 'managed')
+ assert.equal((await inspectExistingUnit({ unitPath: join(dir, 'absent.service') })).state, 'absent')
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('refuses a symlinked unit path before reading it', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'ou-'))
+ try {
+ const real = join(dir, 'real.service')
+ await writeFile(real, renderOrcaServiceUnit(BASE))
+ const link = join(dir, 'mso-orca.service')
+ await symlink(real, link)
+ await assert.rejects(() => inspectExistingUnit({ unitPath: link }), /symlink/)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/terminal-proof.mjs b/scripts/orca/terminal-proof.mjs
new file mode 100644
index 00000000..1e236ee1
--- /dev/null
+++ b/scripts/orca/terminal-proof.mjs
@@ -0,0 +1,135 @@
+/**
+ * Real PTY echo proof through the Orca CLI RPC.
+ * Every call is bounded, exit-checked, JSON-checked, and the exact created
+ * terminal is closed on every path. A token only passes when it appears as its
+ * own output line, not as the echoed input command.
+ */
+
+import { lstat, mkdir, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { redactSensitiveText, runBounded } from './bounded-proc.mjs'
+
+const ECHO_TOKEN_RE = /^[A-Za-z0-9._:-]{1,128}$/
+const HANDLE_RE = /^[A-Za-z0-9._:-]{1,128}$/
+
+function safeError(parsed) {
+ const raw = parsed?.error?.message ?? parsed?.error ?? parsed?.message ?? 'unknown error'
+ const text = typeof raw === 'string' ? raw : JSON.stringify(raw)
+ return redactSensitiveText(text).slice(0, 500)
+}
+
+export async function initScratchGitRepo(repoDir, { timeoutMs = 30000 } = {}) {
+ try {
+ const info = await lstat(join(repoDir, '.git'))
+ if (info.isDirectory()) return repoDir
+ } catch {}
+ await mkdir(repoDir, { recursive: true, mode: 0o700 })
+ await writeFile(join(repoDir, 'README.md'), '# Scratch Repo\n', { mode: 0o600 })
+ const git = async (args) => {
+ const res = await runBounded({
+ cmd: 'git',
+ args,
+ timeoutMs,
+ maxStdoutBytes: 256 * 1024,
+ maxStderrBytes: 64 * 1024
+ })
+ if (res.code !== 0) {
+ throw new Error(`git ${args[0]} failed (exit ${res.code}): ${redactSensitiveText(res.stderr).slice(-500)}`)
+ }
+ }
+ await git(['init', '-b', 'main', repoDir])
+ await git(['-C', repoDir, 'config', 'user.name', 'Orca Tester'])
+ await git(['-C', repoDir, 'config', 'user.email', '[email protected]'])
+ await git(['-C', repoDir, 'add', '.'])
+ await git(['-C', repoDir, 'commit', '-m', 'Initial commit'])
+ return repoDir
+}
+
+export async function verifyRealTerminalEcho({
+ nodeBinary,
+ cliPath,
+ cliEnv,
+ testRepo,
+ echoToken,
+ callTimeoutMs = 20000,
+ echoDeadlineMs = 15000,
+ pollMs = 250
+} = {}) {
+ if (typeof nodeBinary !== 'string' || typeof cliPath !== 'string') {
+ throw new Error('nodeBinary and cliPath are required')
+ }
+ if (typeof testRepo !== 'string' || testRepo.length === 0) throw new Error('testRepo is required')
+ if (typeof echoToken !== 'string' || !ECHO_TOKEN_RE.test(echoToken)) {
+ throw new Error('echoToken must be a short alphanumeric marker')
+ }
+
+ const call = async (args, label) => {
+ const res = await runBounded({
+ cmd: nodeBinary,
+ args: [cliPath, ...args],
+ env: cliEnv,
+ timeoutMs: callTimeoutMs,
+ maxStdoutBytes: 1024 * 1024,
+ maxStderrBytes: 64 * 1024
+ })
+ if (res.code !== 0) {
+ throw new Error(
+ `${label} exited ${res.code}: ${redactSensitiveText(res.stderr).slice(-500)}`
+ )
+ }
+ let parsed
+ try {
+ parsed = JSON.parse(res.stdout.trim())
+ } catch {
+ throw new Error(`${label} returned invalid JSON`)
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ throw new Error(`${label} returned non-object JSON`)
+ }
+ if (parsed.ok !== true) throw new Error(`${label} was not ok: ${safeError(parsed)}`)
+ return parsed
+ }
+
+ let termHandle = null
+ let primary = null
+ try {
+ await call(['repo', 'add', '--path', testRepo, '--json'], 'repo add')
+
+ const created = await call(
+ ['terminal', 'create', '--worktree', `path:${testRepo}`, '--command', `echo ${echoToken}`, '--json'],
+ 'terminal create'
+ )
+ termHandle = created.result?.terminal?.handle
+ if (typeof termHandle !== 'string' || !HANDLE_RE.test(termHandle)) {
+ throw new Error('terminal create returned no valid terminal handle')
+ }
+
+ const deadline = Date.now() + echoDeadlineMs
+ let observed = false
+ while (Date.now() < deadline) {
+ const read = await call(['terminal', 'read', '--terminal', termHandle, '--json'], 'terminal read')
+ const tail = read.result?.terminal?.tail
+ if (!Array.isArray(tail)) throw new Error('terminal read returned no tail array')
+ if (tail.some((line) => typeof line === 'string' && line.trim() === echoToken)) {
+ observed = true
+ break
+ }
+ await new Promise((r) => setTimeout(r, pollMs))
+ }
+ if (!observed) throw new Error(`echo token was not observed as an output line: ${echoToken}`)
+ } catch (err) {
+ primary = err
+ } finally {
+ if (termHandle) {
+ try {
+ await call(['terminal', 'close', '--terminal', termHandle, '--json'], 'terminal close')
+ } catch (err) {
+ if (primary) primary.message = `${primary.message}; additionally failed to close ${termHandle}: ${err.message}`
+ else primary = err
+ }
+ }
+ }
+
+ if (primary) throw primary
+ return { ok: true, termHandle, echoObserved: true }
+}
diff --git a/scripts/orca/terminal-proof.test.mjs b/scripts/orca/terminal-proof.test.mjs
new file mode 100644
index 00000000..7f5d52f1
--- /dev/null
+++ b/scripts/orca/terminal-proof.test.mjs
@@ -0,0 +1,209 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdtemp, readFile, rm } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { verifyRealTerminalEcho } from './terminal-proof.mjs'
+
+const FIXTURES = fileURLToPath(new URL('./fixtures/', import.meta.url))
+const FAKE_CLI = join(FIXTURES, 'fake-orca-cli.mjs')
+const NODE = process.execPath
+const TOKEN = 'ORCA_ECHO_TEST_123'
+
+function alive(pid) {
+ try {
+ process.kill(pid, 0)
+ return true
+ } catch {
+ return false
+ }
+}
+
+async function waitGone(pid, timeoutMs = 3000) {
+ const start = Date.now()
+ while (Date.now() - start < timeoutMs) {
+ if (!alive(pid)) return true
+ await new Promise((r) => setTimeout(r, 25))
+ }
+ return !alive(pid)
+}
+
+async function setup(mode) {
+ const dir = await mkdtemp(join(tmpdir(), 'orca-terminal-'))
+ const logPath = join(dir, 'cli.log')
+ const env = {
+ PATH: '/usr/local/bin:/usr/bin:/bin',
+ FAKE_CLI_MODE: mode,
+ FAKE_CLI_TOKEN: TOKEN,
+ FAKE_CLI_LOG: logPath
+ }
+ return { dir, logPath, env }
+}
+
+const readLog = (p) => readFile(p, 'utf8').catch(() => '')
+
+describe('strict terminal echo proof', () => {
+ it('requires one owned terminal, observes its output line, and closes it', async () => {
+ const { dir, logPath, env } = await setup('normal')
+ try {
+ const result = await verifyRealTerminalEcho({
+ nodeBinary: NODE,
+ cliPath: FAKE_CLI,
+ cliEnv: env,
+ testRepo: dir,
+ echoToken: TOKEN,
+ echoDeadlineMs: 2000,
+ pollMs: 20
+ })
+ assert.equal(result.ok, true)
+ assert.equal(result.termHandle, 'term-abc')
+ const log = await readLog(logPath)
+ assert.match(log, /terminal create --worktree path:/)
+ assert.match(log, /terminal read --terminal term-abc/)
+ assert.match(log, /terminal close --terminal term-abc/)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects when only the echoed input command is visible, not its output', async () => {
+ const { dir, logPath, env } = await setup('no-echo')
+ try {
+ await assert.rejects(
+ () =>
+ verifyRealTerminalEcho({
+ nodeBinary: NODE,
+ cliPath: FAKE_CLI,
+ cliEnv: env,
+ testRepo: dir,
+ echoToken: TOKEN,
+ echoDeadlineMs: 400,
+ pollMs: 20
+ }),
+ /not observed as an output line/i
+ )
+ assert.match(await readLog(logPath), /terminal close --terminal term-abc/)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('fails before closing when terminal creation is not ok', async () => {
+ const { dir, logPath, env } = await setup('create-fail')
+ try {
+ await assert.rejects(
+ () =>
+ verifyRealTerminalEcho({
+ nodeBinary: NODE,
+ cliPath: FAKE_CLI,
+ cliEnv: env,
+ testRepo: dir,
+ echoToken: TOKEN,
+ echoDeadlineMs: 400,
+ pollMs: 20
+ }),
+ /terminal create was not ok: create denied/
+ )
+ assert.doesNotMatch(await readLog(logPath), /terminal close/)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('surfaces a close failure after a successful echo', async () => {
+ const { dir, env } = await setup('close-fail')
+ try {
+ await assert.rejects(
+ () =>
+ verifyRealTerminalEcho({
+ nodeBinary: NODE,
+ cliPath: FAKE_CLI,
+ cliEnv: env,
+ testRepo: dir,
+ echoToken: TOKEN,
+ echoDeadlineMs: 2000,
+ pollMs: 20
+ }),
+ /terminal close was not ok: close denied/
+ )
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects a nonzero CLI exit instead of parsing stdout', async () => {
+ const { dir, env } = await setup('exit-nonzero')
+ try {
+ await assert.rejects(
+ () =>
+ verifyRealTerminalEcho({
+ nodeBinary: NODE,
+ cliPath: FAKE_CLI,
+ cliEnv: env,
+ testRepo: dir,
+ echoToken: TOKEN
+ }),
+ /repo add exited 4/
+ )
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects invalid JSON and non-ok payloads', async () => {
+ const { dir: badDir, env: badEnv } = await setup('invalid-json')
+ const { dir: failDir, env: failEnv } = await setup('repo-fail')
+ try {
+ await assert.rejects(
+ () =>
+ verifyRealTerminalEcho({
+ nodeBinary: NODE,
+ cliPath: FAKE_CLI,
+ cliEnv: badEnv,
+ testRepo: badDir,
+ echoToken: TOKEN
+ }),
+ /invalid JSON/
+ )
+ await assert.rejects(
+ () =>
+ verifyRealTerminalEcho({
+ nodeBinary: NODE,
+ cliPath: FAKE_CLI,
+ cliEnv: failEnv,
+ testRepo: failDir,
+ echoToken: TOKEN
+ }),
+ /repo add was not ok: repo denied/
+ )
+ } finally {
+ await rm(badDir, { recursive: true, force: true })
+ await rm(failDir, { recursive: true, force: true })
+ }
+ })
+
+ it('times out and reaps the owned CLI child', async () => {
+ const { dir, logPath, env } = await setup('hang')
+ try {
+ await assert.rejects(
+ () =>
+ verifyRealTerminalEcho({
+ nodeBinary: NODE,
+ cliPath: FAKE_CLI,
+ cliEnv: env,
+ testRepo: dir,
+ echoToken: TOKEN,
+ callTimeoutMs: 300
+ }),
+ /timed out/i
+ )
+ const pidLine = (await readLog(logPath)).split('\n')[0] || ''
+ const pid = Number(/^pid:(\d+)/.exec(pidLine)?.[1])
+ assert.ok(Number.isInteger(pid) && pid > 1, 'fixture pid was not recorded')
+ assert.equal(await waitGone(pid), true, 'timed-out CLI child survived')
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/orca/unit-path.test.mjs b/scripts/orca/unit-path.test.mjs
new file mode 100644
index 00000000..4ad2cfaa
--- /dev/null
+++ b/scripts/orca/unit-path.test.mjs
@@ -0,0 +1,88 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { inspectExistingUnit, renderOrcaServiceUnit } from './systemd-unit.mjs'
+
+/**
+ * Ancestor guard coverage for `inspectExistingUnit`.
+ *
+ * `assertNoSymlinkUnitPath` used to return at the FIRST existing path component,
+ * so an existing unit — or a missing leaf — reached through a symlinked parent was
+ * accepted. These fixtures reproduce that and pin the corrected behaviour: every
+ * ancestor from the unit up to the filesystem root is checked.
+ */
+
+const OWNED = renderOrcaServiceUnit({
+ hostNode: '/usr/bin/node',
+ cliScript: '/opt/mso/scripts/orca/cli.mjs',
+ managedRoot: '/home/operator/.local/share/mso/orca',
+ port: 6769,
+ advertisedEndpoint: 'wss://orca.mso.example.com'
+})
+const FOREIGN = '[Service]\nExecStart=/usr/bin/orca --port 6768\n'
+
+// Canonicalise the base so the temp tree has no incidental symlinked ancestor.
+async function makeBase() {
+ const base = await realpath(await mkdtemp(join(tmpdir(), 'up-')))
+ return { base, cleanup: () => rm(base, { recursive: true, force: true }) }
+}
+
+async function writeUnit(dir, text) {
+ await mkdir(dir, { recursive: true })
+ const unitPath = join(dir, 'mso-orca.service')
+ await writeFile(unitPath, text, { mode: 0o644 })
+ return unitPath
+}
+
+describe('Orca unit ancestor guard', () => {
+ it('refuses an existing owned unit reached through a symlinked parent', async () => {
+ const d = await makeBase()
+ try {
+ await writeUnit(join(d.base, 'real', 'systemd', 'user'), OWNED)
+ await symlink(join(d.base, 'real'), join(d.base, 'link'))
+ const unitPath = join(d.base, 'link', 'systemd', 'user', 'mso-orca.service')
+ await assert.rejects(() => inspectExistingUnit({ unitPath }), /symlink/i)
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('refuses a missing unit leaf under a symlinked parent', async () => {
+ const d = await makeBase()
+ try {
+ await mkdir(join(d.base, 'real', 'systemd', 'user'), { recursive: true })
+ await symlink(join(d.base, 'real'), join(d.base, 'link'))
+ const unitPath = join(d.base, 'link', 'systemd', 'user', 'mso-orca.service')
+ await assert.rejects(() => inspectExistingUnit({ unitPath }), /symlink/i)
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('accepts a legitimate owned unit and reports an absent one', async () => {
+ const d = await makeBase()
+ try {
+ const dir = join(d.base, 'home', '.config', 'systemd', 'user')
+ const unitPath = await writeUnit(dir, OWNED)
+ const found = await inspectExistingUnit({ unitPath })
+ assert.equal(found.state, 'managed')
+ assert.equal(found.text, OWNED)
+ assert.equal((await inspectExistingUnit({ unitPath: join(dir, 'absent.service') })).state, 'absent')
+ } finally {
+ await d.cleanup()
+ }
+ })
+
+ it('refuses a foreign unit and leaves it untouched', async () => {
+ const d = await makeBase()
+ try {
+ const unitPath = await writeUnit(join(d.base, 'home', '.config', 'systemd', 'user'), FOREIGN)
+ await assert.rejects(() => inspectExistingUnit({ unitPath }), /foreign unit/i)
+ assert.equal(await readFile(unitPath, 'utf8'), FOREIGN)
+ } finally {
+ await d.cleanup()
+ }
+ })
+})
diff --git a/scripts/orca/unit-read.mjs b/scripts/orca/unit-read.mjs
new file mode 100644
index 00000000..2df2907f
--- /dev/null
+++ b/scripts/orca/unit-read.mjs
@@ -0,0 +1,124 @@
+/**
+ * Bounded, symlink-proof, owner-checked filesystem reading for Orca unit files.
+ * Uses pinned-directory descriptors and cap+1 bounded reads.
+ */
+
+import { constants } from 'node:fs'
+import { open, realpath } from 'node:fs/promises'
+import { basename, dirname, resolve } from 'node:path'
+
+export const UNIT_MAX_BYTES = 32 * 1024
+
+export function ownerUidMatches(uid) {
+ return typeof process.getuid !== 'function' || uid === process.getuid()
+}
+
+/** Read at most `maxBytes`; a file that reaches cap+1 is refused. */
+export async function readBounded(handle, maxBytes) {
+ const chunks = []
+ let total = 0
+ for (;;) {
+ const remaining = maxBytes + 1 - total
+ if (remaining <= 0) return null
+ const chunk = Buffer.alloc(Math.min(remaining, 16 * 1024))
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, null)
+ if (bytesRead === 0) break
+ total += bytesRead
+ if (total > maxBytes) return null
+ chunks.push(chunk.subarray(0, bytesRead))
+ }
+ return Buffer.concat(chunks, total)
+}
+
+/**
+ * Pinned directory descriptor, symlink-proof, bounded read for a unit file.
+ */
+export async function readOwnedUnitFile(
+ unitPath,
+ uid = typeof process.getuid === 'function' ? process.getuid() : null,
+ maxBytes = UNIT_MAX_BYTES
+) {
+ const dir = dirname(unitPath)
+ const filename = basename(unitPath)
+
+ let canonicalDir
+ try {
+ canonicalDir = await realpath(dir)
+ } catch (err) {
+ if (err?.code === 'ENOENT') return null
+ throw err
+ }
+ if (canonicalDir !== resolve(dir)) {
+ throw new Error(`refusing a symlinked unit directory: ${dir}`)
+ }
+
+ let directory
+ try {
+ directory = await open(canonicalDir, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
+ } catch (err) {
+ if (err?.code === 'ENOENT') return null
+ throw err
+ }
+
+ try {
+ const dirStat = await directory.stat()
+ if (!dirStat.isDirectory()) {
+ throw new Error(`refusing non-directory unit directory: ${dir}`)
+ }
+ if (uid !== null && !ownerUidMatches(dirStat.uid)) {
+ throw new Error(`refusing a unit directory not owned by this user: ${dir}`)
+ }
+ if ((dirStat.mode & 0o022) !== 0) {
+ throw new Error(`refusing a group- or world-writable unit directory: ${dir}`)
+ }
+
+ let handle
+ try {
+ handle = await open(
+ `/proc/self/fd/${directory.fd}/${filename}`,
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK
+ )
+ } catch (err) {
+ if (err?.code === 'ENOENT') return null
+ throw err
+ }
+
+ try {
+ const before = await handle.stat()
+ if (!before.isFile() || before.isSymbolicLink()) {
+ throw new Error(`refusing a non-regular unit: ${unitPath}`)
+ }
+ if (uid !== null && !ownerUidMatches(before.uid)) {
+ throw new Error(`refusing a unit not owned by this user: ${unitPath}`)
+ }
+ if ((before.mode & 0o022) !== 0) {
+ throw new Error(`refusing a group- or world-writable unit: ${unitPath}`)
+ }
+ if (before.size > maxBytes) {
+ throw new Error(`refusing unit exceeding maximum size of ${maxBytes} bytes: ${unitPath}`)
+ }
+
+ const buffer = await readBounded(handle, maxBytes)
+ if (buffer === null) {
+ throw new Error(`refusing unit exceeding maximum size of ${maxBytes} bytes: ${unitPath}`)
+ }
+
+ const after = await handle.stat()
+ if (
+ after.size !== buffer.length ||
+ after.ino !== before.ino ||
+ after.dev !== before.dev ||
+ after.mtimeMs !== before.mtimeMs ||
+ after.mode !== before.mode
+ ) {
+ throw new Error(`refusing unit modified or replaced during read: ${unitPath}`)
+ }
+
+ return buffer.toString('utf8')
+ } finally {
+ await handle.close()
+ }
+ } finally {
+ await directory.close()
+ }
+}
diff --git a/scripts/orca/unit-render.mjs b/scripts/orca/unit-render.mjs
new file mode 100644
index 00000000..d48d3a14
--- /dev/null
+++ b/scripts/orca/unit-render.mjs
@@ -0,0 +1,79 @@
+/**
+ * Pure systemd unit rendering shared by the installer (`systemd-unit.mjs`) and
+ * the runtime ownership proof (`lib/managed-apps`). Keeping the exact bytes in
+ * one place means the producer and consumer cannot drift into a fake fixture.
+ *
+ * Validation belongs to the caller: `systemd-unit.mjs` rejects non-absolute,
+ * dynamic, loopback, or malformed configuration before calling this.
+ */
+
+const CONTROL = /[\0\r\n]/
+
+/** @param {string} value */
+export function systemdQuote(value) {
+ if (typeof value !== 'string' || value.length === 0 || CONTROL.test(value)) {
+ throw new Error('unit value must be a non-empty string without control characters')
+ }
+ const escaped = value
+ .replace(/%/g, '%%')
+ .replace(/\$/g, () => '$$')
+ .replace(/\\/g, '\\\\')
+ .replace(/"/g, '\\"')
+ return `"${escaped}"`
+}
+
+/**
+ * @typedef {object} UnitRenderInput
+ * @property {string} marker
+ * @property {string} serviceName
+ * @property {string} hostNode
+ * @property {string} cliScript
+ * @property {string} managedRoot
+ * @property {number} port
+ * @property {string} advertisedEndpoint
+ */
+
+/**
+ * @param {UnitRenderInput} input
+ */
+export function renderUnitText({ marker, serviceName, hostNode, cliScript, managedRoot, port, advertisedEndpoint }) {
+ const argv = [
+ hostNode,
+ cliScript,
+ 'run',
+ '--managed-root',
+ managedRoot,
+ '--port',
+ String(port),
+ '--advertised-endpoint',
+ advertisedEndpoint
+ ]
+
+ return `${marker}
+# Generated by MSO's managed-app-orca adapter. Do not edit by hand; reinstall
+# through MSO instead. This unit runs only the pinned, verified Orca release
+# under the MSO-owned managed root. It contains no credential.
+[Unit]
+Description=Orca web workspace (MSO managed ${serviceName})
+After=network-online.target
+Wants=network-online.target
+StartLimitIntervalSec=300
+StartLimitBurst=3
+
+[Service]
+Type=simple
+WorkingDirectory=${systemdQuote(managedRoot)}
+ExecStart=${argv.map(systemdQuote).join(' ')}
+Environment="NODE_ENV=production"
+Restart=on-failure
+RestartSec=5
+TimeoutStartSec=90
+TimeoutStopSec=20
+KillMode=process
+StandardOutput=journal
+StandardError=journal
+
+[Install]
+WantedBy=default.target
+`
+}
diff --git a/scripts/orca/unit-replacement.test.mjs b/scripts/orca/unit-replacement.test.mjs
new file mode 100644
index 00000000..6f6e232d
--- /dev/null
+++ b/scripts/orca/unit-replacement.test.mjs
@@ -0,0 +1,134 @@
+import { describe, it } from 'node:test'
+import assert from 'node:assert/strict'
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { inspectExistingUnit, isManagedOrcaUnit, renderOrcaServiceUnit } from './systemd-unit.mjs'
+import { installManagedOrca } from './managed-install.mjs'
+import { orcaServiceUnitPath } from './managed-paths.mjs'
+
+const TRUSTED_CONFIG = {
+ hostNode: '/usr/bin/node',
+ cliScript: '/opt/mso/scripts/orca/cli.mjs',
+ managedRoot: '/home/operator/.local/share/mso/orca',
+ port: 6769,
+ advertisedEndpoint: 'wss://orca.mso.example.com'
+}
+
+const TRUSTED_UNIT = renderOrcaServiceUnit(TRUSTED_CONFIG)
+
+const FOREIGN_UNIT = `# mso-managed-app: orca
+# --managed-root /tmp/evil
+[Unit]
+Description=Injected foreign Orca
+[Service]
+ExecStart=/bin/foreign /opt/mso/scripts/orca/cli.mjs run
+ExecStartPre=/bin/evil-hook
+`
+
+describe('Orca installer replacement authorization regression', () => {
+ it('rejects unit with marker, foreign ExecStart, ExecStartPre, and --managed-root comment while preserving byte identity', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'ou-replace-'))
+ try {
+ const unitPath = join(dir, 'mso-orca.service')
+ await writeFile(unitPath, FOREIGN_UNIT, { mode: 0o644 })
+
+ // Predicate check must reject foreign ExecStart and ExecStartPre
+ assert.equal(isManagedOrcaUnit(FOREIGN_UNIT, TRUSTED_UNIT), false)
+
+ // Direct inspection with caller's expected unit must reject foreign unit
+ await assert.rejects(
+ () => inspectExistingUnit({
+ unitPath,
+ expectedUnit: TRUSTED_UNIT
+ }),
+ /foreign unit/i
+ )
+
+ // File byte identity must be preserved exactly
+ const textAfter = await readFile(unitPath, 'utf8')
+ assert.equal(textAfter, FOREIGN_UNIT)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('accepts legitimate owned unit matching trusted expected configuration', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'ou-replace-'))
+ try {
+ const unitPath = join(dir, 'mso-orca.service')
+ await writeFile(unitPath, TRUSTED_UNIT, { mode: 0o644 })
+
+ const inspected = await inspectExistingUnit({
+ unitPath,
+ expectedUnit: TRUSTED_UNIT
+ })
+ assert.equal(inspected.state, 'managed')
+ assert.equal(inspected.text, TRUSTED_UNIT)
+
+ // Also accepts with expectedConfig
+ const inspectedConfig = await inspectExistingUnit({
+ unitPath,
+ expectedConfig: TRUSTED_CONFIG
+ })
+ assert.equal(inspectedConfig.state, 'managed')
+ assert.equal(inspectedConfig.text, TRUSTED_UNIT)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('rejects legitimate owned unit if desired expected configuration does not match', async () => {
+ const dir = await mkdtemp(join(tmpdir(), 'ou-replace-'))
+ try {
+ const unitPath = join(dir, 'mso-orca.service')
+ await writeFile(unitPath, TRUSTED_UNIT, { mode: 0o644 })
+
+ const otherConfig = { ...TRUSTED_CONFIG, port: 6770 }
+ const otherUnit = renderOrcaServiceUnit(otherConfig)
+
+ await assert.rejects(
+ () => inspectExistingUnit({
+ unitPath,
+ expectedUnit: otherUnit
+ }),
+ /foreign unit/i
+ )
+
+ // Verify file byte identity preserved
+ assert.equal(await readFile(unitPath, 'utf8'), TRUSTED_UNIT)
+ } finally {
+ await rm(dir, { recursive: true, force: true })
+ }
+ })
+
+ it('installer rejects existing unit with foreign ExecStart or hooks before prepare/download or systemctl', async () => {
+ const base = await mkdtemp(join(tmpdir(), 'ou-inst-'))
+ try {
+ const home = join(base, 'home')
+ const root = join(base, 'root')
+ const unitPath = orcaServiceUnitPath({ home })
+ await mkdir(join(unitPath, '..'), { recursive: true })
+ await writeFile(unitPath, FOREIGN_UNIT, { mode: 0o644 })
+
+ let prepared = 0
+ let systemctlCalled = 0
+ await assert.rejects(
+ () => installManagedOrca({
+ managedRoot: root,
+ home,
+ advertisedEndpoint: 'wss://orca.mso.example.com',
+ prepare: async () => { prepared += 1 },
+ systemctl: async () => { systemctlCalled += 1 }
+ }),
+ /foreign unit/i
+ )
+
+ assert.equal(prepared, 0)
+ assert.equal(systemctlCalled, 0)
+ assert.equal(await readFile(unitPath, 'utf8'), FOREIGN_UNIT)
+ } finally {
+ await rm(base, { recursive: true, force: true })
+ }
+ })
+})
diff --git a/scripts/server.mjs b/scripts/server.mjs
index 55d07a30..8b01f25d 100644
--- a/scripts/server.mjs
+++ b/scripts/server.mjs
@@ -10,8 +10,16 @@ const hostname = argument("--hostname", process.env.HOSTNAME ?? "0.0.0.0");
const port = Number(argument("--port", process.env.PORT ?? "3000"));
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("invalid runtime port");
process.env.MSO_SOCKET_POLICY_SECRET = randomBytes(32).toString("hex");
+// Next builds the internal request origin (`initUrl`) from this hostname, and that origin
+// decides whether a middleware rewrite is internal or external. Next's NextURL canonicalizes
+// a bare loopback IP to `localhost` (next-url.js REGEX_LOCALHOST_HOSTNAME), so handing Next
+// the raw address makes `initUrl` (127.0.0.1) disagree with the middleware's `nextUrl`
+// (localhost) and every managed-app internal rewrite is misclassified as EXTERNAL and
+// self-proxied over TLS (EPROTO/500). Pass the canonical loopback name Next itself uses
+// while we keep binding the public socket to the real address below.
+const nextHostname = /^(?:127(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)){3}|\[::1\]|::1|localhost)$/.test(hostname) ? "localhost" : hostname;
const internal = createServer();
-const app = next({ dev: false, hostname, port, httpServer: internal });
+const app = next({ dev: false, hostname: nextHostname, port, httpServer: internal });
await app.prepare();
internal.on("request", app.getRequestHandler());
await new Promise((resolve) => internal.listen(0, "127.0.0.1", resolve));