Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(security): remediate hosted CodeQL findings

Rahman601e891f4662
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index 19cb46b2..a65b0481 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -27,12 +27,12 @@ jobs:
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
- name: Initialize CodeQL
- uses: github/codeql-action/init@4c0873ef8656cb3c50b3f42fb63bc1ade0cfa827 # v4
+ uses: github/codeql-action/init@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4
with:
languages: javascript-typescript
queries: security-extended
- name: Analyze
- uses: github/codeql-action/analyze@4c0873ef8656cb3c50b3f42fb63bc1ade0cfa827 # v4
+ uses: github/codeql-action/analyze@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4
with:
category: /language:javascript-typescript
diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml
index 49b49e3b..f74c80f3 100644
--- a/.github/workflows/scorecard.yml
+++ b/.github/workflows/scorecard.yml
@@ -33,7 +33,7 @@ jobs:
publish_results: true
- name: Upload Scorecard SARIF
- uses: github/codeql-action/upload-sarif@4c0873ef8656cb3c50b3f42fb63bc1ade0cfa827 # v4
+ uses: github/codeql-action/upload-sarif@cdf488f595d80d6e07e03d4674febd5ab45fa938 # v4
with:
sarif_file: results.sarif
category: openssf-scorecard
diff --git a/SECURITY.md b/SECURITY.md
index f16fdf07..afee2a7a 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -66,6 +66,30 @@ short accident tripwire, not a sandbox. Interactive Terminal PTYs are even more
keystrokes cannot be reliably parsed into commands, so authentication and PTY session
lifecycle—not the one-shot command matcher—are the boundary.
+## Static-analysis and file-safety boundaries
+
+Hosted CodeQL findings are treated as release blockers until they are either remediated or proven
+false positives with a narrow, reviewable justification. The current implementation applies the
+following source-level controls in addition to route authorization:
+
+- provider/config/OAuth maps accept validated provider identifiers and rebuild records from entry
+ lists rather than assigning or deleting attacker-selected object properties;
+- thread identifiers are accepted or rejected as a whole and are never rewritten into colliding
+ filesystem names;
+- bounded host reads, lock recovery, skill/catalog reads and model-cache reads bind metadata and
+ content to the same `O_NOFOLLOW` file descriptor where the platform supports it;
+- read/write root policy performs lexical containment before filesystem resolution and canonical
+ containment afterward, so nonexistent outside paths and escaping symlinks both fail closed;
+- the models.dev catalog uses one fixed HTTPS endpoint, bounded streaming, object-shape validation,
+ a private `0700` cache directory and atomic `0600` cache replacement;
+- external widget embeds allow only credential-free external HTTPS URLs, omit `allow-same-origin`,
+ and send no referrer; local image previews accept a raster MIME allowlist and revoke object URLs;
+- uploaded files use random exclusive temporary names, revalidate the destination after directory
+ creation, reject traversal instead of normalizing it away, and remove partial files on every exit.
+
+These controls reduce known classes of path race, prototype-pollution, DOM trust, and unbounded
+network-to-disk issues. They do not turn automated static analysis into a proof of complete security.
+
## Service and package operations
System Monitor exposes system/user `systemd` inventory to Viewer devices. Journal reads require
diff --git a/app/api/oauth/[provider]/route.ts b/app/api/oauth/[provider]/route.ts
index 875e0493..2fb1b853 100644
--- a/app/api/oauth/[provider]/route.ts
+++ b/app/api/oauth/[provider]/route.ts
@@ -27,27 +27,30 @@ export async function POST(req: NextRequest, ctx: { params: Promise<{ provider:
const SLUG = "openai-codex";
try {
- if (body.action === "start") {
- const { deviceAuthId, userCode, intervalMs } = await codexStart();
- setFlow(SLUG, { deviceAuthId, userCode });
- return NextResponse.json({ verificationUrl: CODEX.verificationUrl, userCode, intervalMs });
+ switch (body.action) {
+ case "start": {
+ const { deviceAuthId, userCode, intervalMs } = await codexStart();
+ setFlow(SLUG, { deviceAuthId, userCode });
+ return NextResponse.json({ verificationUrl: CODEX.verificationUrl, userCode, intervalMs });
+ }
+ case "poll": {
+ const flow = getFlow(SLUG);
+ if (!flow?.deviceAuthId || !flow.userCode) return NextResponse.json({ error: "no_flow" }, { status: 400 });
+ const res = await codexPoll(flow.deviceAuthId, flow.userCode);
+ if ("pending" in res) return NextResponse.json({ pending: true });
+ clearFlow(SLUG);
+ await writeOAuthBundle(SLUG, res.bundle);
+ const models = await codexModels(res.bundle);
+ // The account's own first model. No literal fallback — "gpt-5-codex" is refused
+ // by the backend, so writing it here just made the first request after a
+ // successful sign-in fail.
+ const model = models[0] ?? "";
+ await writeConfig({ provider: SLUG, model });
+ return NextResponse.json({ ok: true, slug: SLUG, model });
+ }
+ default:
+ return NextResponse.json({ error: "bad_action" }, { status: 400 });
}
- if (body.action === "poll") {
- const flow = getFlow(SLUG);
- if (!flow?.deviceAuthId || !flow.userCode) return NextResponse.json({ error: "no_flow" }, { status: 400 });
- const res = await codexPoll(flow.deviceAuthId, flow.userCode);
- if ("pending" in res) return NextResponse.json({ pending: true });
- clearFlow(SLUG);
- await writeOAuthBundle(SLUG, res.bundle);
- const models = await codexModels(res.bundle);
- // The account's own first model. No literal fallback — "gpt-5-codex" is refused
- // by the backend, so writing it here just made the first request after a
- // successful sign-in fail.
- const model = models[0] ?? "";
- await writeConfig({ provider: SLUG, model });
- return NextResponse.json({ ok: true, slug: SLUG, model });
- }
- return NextResponse.json({ error: "bad_action" }, { status: 400 });
} catch (e) {
return NextResponse.json({ error: (e as Error).message }, { status: 502 });
}
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 1df95fc4..192161ba 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -13,6 +13,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Fixed**
+- `security` remediate hosted CodeQL findings
- `security` remediate ultimate assurance findings
- `security` resolve full assurance findings
- `security` raise complete component scan budget
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 8e9adea0..138a7a4f 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -24,6 +24,13 @@ last-Owner removal, and re-resolves role/revocation on every request. The shell
apps for clarity, while a centralized server policy makes the actual decision: explicit reads are Viewer and every unclassified route fails up to Owner; PTY/exec/config/MCP/update remain Owner, and only
explicit bounded operational surfaces are Operator.
+A hosted CodeQL follow-up on the first release candidate was not treated as cosmetic backlog.
+The release was reopened to harden validated config maps, strict thread identifiers, external iframe
+policy, descriptor-bound file reads, dual root containment, private collision fixtures, bounded
+models.dev cache writes, exclusive upload staging, and immutable CodeQL workflow pins. Regression
+tests accompany each changed boundary; the replacement SHA must repeat the full repository,
+build, hosted-analysis, deploy and ultimate-assurance gates before the branch is considered closed.
+
System Monitor now includes Services and Updates beside live telemetry. It inventories system/user
`systemd` units, bounds journals, and permits start/stop/restart only for validated exact units in
`OS_SERVICE_CONTROL_UNITS`; no shell or wildcard path exists. Package visibility reads only the
diff --git a/frontend/slices/appshell/features/widgets/components/embed-url.test.ts b/frontend/slices/appshell/features/widgets/components/embed-url.test.ts
new file mode 100644
index 00000000..4dbb2022
--- /dev/null
+++ b/frontend/slices/appshell/features/widgets/components/embed-url.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { safeEmbedUrl } from "./embed-url";
+
+describe("widget embed URL boundary", () => {
+ it("accepts normalized external HTTPS URLs", () => {
+ expect(safeEmbedUrl(" https://example.com/path?q=1 ", "https://mso.example"))
+ .toBe("https://example.com/path?q=1");
+ });
+
+ it.each([
+ "http://example.com",
+ "javascript:alert(1)",
+ "data:text/html,<script>alert(1)</script>",
+ "https://user:[email protected]",
+ "https://mso.example/private",
+ "not a url",
+ "",
+ ])("rejects unsafe embed %s", (value) => {
+ expect(safeEmbedUrl(value, "https://mso.example")).toBeNull();
+ });
+
+ it("caps attacker-controlled URL length", () => {
+ expect(safeEmbedUrl(`https://example.com/${"a".repeat(2100)}`, "https://mso.example")).toBeNull();
+ });
+});
diff --git a/frontend/slices/appshell/features/widgets/components/embed-url.ts b/frontend/slices/appshell/features/widgets/components/embed-url.ts
new file mode 100644
index 00000000..96cc73ff
--- /dev/null
+++ b/frontend/slices/appshell/features/widgets/components/embed-url.ts
@@ -0,0 +1,16 @@
+const MAX_EMBED_URL = 2048;
+
+/** External HTTPS only. Same-origin frames would share cockpit trust if sandbox flags drift. */
+export function safeEmbedUrl(raw: string, cockpitOrigin?: string): string | null {
+ const value = raw.trim();
+ if (!value || value.length > MAX_EMBED_URL) return null;
+ let url: URL;
+ try { url = new URL(value); } catch { return null; }
+ if (url.protocol !== "https:" || url.username || url.password) return null;
+ if (cockpitOrigin) {
+ try {
+ if (url.origin === new URL(cockpitOrigin).origin) return null;
+ } catch { return null; }
+ }
+ return url.toString();
+}
diff --git a/frontend/slices/appshell/features/widgets/components/widgets-defs-vps.tsx b/frontend/slices/appshell/features/widgets/components/widgets-defs-vps.tsx
index 09b9695f..02678217 100644
--- a/frontend/slices/appshell/features/widgets/components/widgets-defs-vps.tsx
+++ b/frontend/slices/appshell/features/widgets/components/widgets-defs-vps.tsx
@@ -6,6 +6,7 @@ import { setShell, shellsForSurface, useActiveShell, useShellAppearance, useShel
import { cn } from "@/lib/utils";
import { Card } from "./widget-cards";
import { mdToHtml } from "./md";
+import { safeEmbedUrl } from "./embed-url";
// VPS-native + content widgets ported from shell.rahmanef.com's set: a stopwatch,
// a URL embed, a sandboxed-HTML snippet, a markdown note, an active-shell picker,
@@ -51,11 +52,26 @@ function TimerWidget() {
// Embeds a URL in an iframe (frameable content only — CSP + the target's
// X-Frame-Options still apply). URL persists to localStorage.
function EmbedWidget() {
- const [url, setUrl] = useState(() => ls(EMBED_KEY));
+ const initial = typeof window === "undefined" ? "" : safeEmbedUrl(ls(EMBED_KEY), window.location.origin) ?? "";
+ const [url, setUrl] = useState(initial);
const [draft, setDraft] = useState(url);
+ const [error, setError] = useState("");
const save = (v: string) => {
- setUrl(v);
- try { v ? localStorage.setItem(EMBED_KEY, v) : localStorage.removeItem(EMBED_KEY); } catch { /* quota */ }
+ if (!v) {
+ setUrl("");
+ setError("");
+ try { localStorage.removeItem(EMBED_KEY); } catch { /* quota */ }
+ return;
+ }
+ const safe = safeEmbedUrl(v, window.location.origin);
+ if (!safe) {
+ setError("Use an external HTTPS URL without credentials.");
+ return;
+ }
+ setUrl(safe);
+ setDraft(safe);
+ setError("");
+ try { localStorage.setItem(EMBED_KEY, safe); } catch { /* quota */ }
};
return (
<Card className="pointer-events-auto">
@@ -69,7 +85,7 @@ function EmbedWidget() {
)}
</div>
{url ? (
- <iframe src={url} sandbox="allow-scripts allow-same-origin" title="Embed" className="h-40 w-full rounded-lg border border-white/10 bg-white" />
+ <iframe src={url} sandbox="allow-scripts allow-forms allow-popups" referrerPolicy="no-referrer" title="External embed" className="h-40 w-full rounded-lg border border-white/10 bg-white" />
) : (
<div className="flex gap-1">
<input
@@ -82,6 +98,7 @@ function EmbedWidget() {
<button type="button" onClick={() => draft.trim() && save(draft.trim())} className={btn}>Go</button>
</div>
)}
+ {error && <p className="mt-1 text-[10px] text-destructive">{error}</p>}
</Card>
);
}
diff --git a/frontend/slices/image-picker/components/image-picker/upload-tab.tsx b/frontend/slices/image-picker/components/image-picker/upload-tab.tsx
index 32445ee5..4c3f4312 100644
--- a/frontend/slices/image-picker/components/image-picker/upload-tab.tsx
+++ b/frontend/slices/image-picker/components/image-picker/upload-tab.tsx
@@ -6,6 +6,7 @@ import { Button } from "@/components/ui/button";
import type { ImageValue, UploadFn } from "../../types";
const MAX = 8 * 1024 * 1024;
+const ALLOWED_IMAGE_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif", "image/avif"]);
export function UploadTab({ onSelect, onUpload }: { onSelect: (c: ImageValue) => void; onUpload: UploadFn }) {
const [file, setFile] = React.useState<File | null>(null);
@@ -13,9 +14,13 @@ export function UploadTab({ onSelect, onUpload }: { onSelect: (c: ImageValue) =>
const [busy, setBusy] = React.useState(false);
const [err, setErr] = React.useState<string | null>(null);
+ React.useEffect(() => () => {
+ if (preview) URL.revokeObjectURL(preview);
+ }, [preview]);
+
const pick = (f: File | undefined) => {
if (!f) return;
- if (!f.type.startsWith("image/")) { setErr("Images only"); return; }
+ if (!ALLOWED_IMAGE_TYPES.has(f.type)) { setErr("PNG, JPEG, WebP, GIF or AVIF only"); return; }
if (f.size > MAX) { setErr("Max 8 MB"); return; }
setErr(null);
setFile(f);
diff --git a/lib/ai/threads.test.ts b/lib/ai/threads.test.ts
index 8e0c4f8f..4e8231dc 100644
--- a/lib/ai/threads.test.ts
+++ b/lib/ai/threads.test.ts
@@ -27,10 +27,12 @@ describe("thread YAML store", () => {
expect(await getThread("thread_abc")).toBeNull();
});
- it("jails the filename against path traversal", async () => {
- await saveThread({ id: "a/../b", title: "x", createdAt: 1, updatedAt: 1, messages: [], history: [] });
+ it("rejects traversal instead of rewriting it into a colliding filename", async () => {
+ await expect(saveThread({ id: "a/../b", title: "x", createdAt: 1, updatedAt: 1, messages: [], history: [] }))
+ .rejects.toThrow("invalid thread id");
+ await expect(getThread("../outside")).rejects.toThrow("invalid thread id");
+ await expect(deleteThread("../outside")).rejects.toThrow("invalid thread id");
const names = await fs.readdir(process.env.OS_THREADS_DIR!);
- expect(names).toContain("ab.yml"); // "a/../b" → strip non-[a-z0-9_-] → "ab"
expect(names.every((n) => !n.includes("/") && !n.includes(".."))).toBe(true);
});
});
diff --git a/lib/ai/threads.ts b/lib/ai/threads.ts
index d094a7db..982bfafa 100644
--- a/lib/ai/threads.ts
+++ b/lib/ai/threads.ts
@@ -20,7 +20,10 @@ export type ThreadSummary = Pick<ChatThread, "id" | "title" | "createdAt" | "upd
const DIR = process.env.OS_THREADS_DIR || path.join(os.homedir(), ".mso", "threads");
// ids are app-generated but jail them anyway (path-traversal guard): alnum + -_ only.
-const safeId = (id: string) => id.replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 64);
+const safeId = (id: string) => {
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) throw new Error("invalid thread id");
+ return id;
+};
const fileFor = (id: string) => path.join(DIR, `${safeId(id)}.yml`);
export async function listThreads(): Promise<ThreadSummary[]> {
@@ -44,8 +47,9 @@ export async function listThreads(): Promise<ThreadSummary[]> {
}
export async function getThread(id: string): Promise<ChatThread | null> {
+ const file = fileFor(id); // validate before the not-found/corrupt-file catch
try {
- return parse(await fs.readFile(fileFor(id), "utf8")) as ChatThread;
+ return parse(await fs.readFile(file, "utf8")) as ChatThread;
} catch {
return null;
}
@@ -60,8 +64,9 @@ export async function saveThread(t: ChatThread): Promise<void> {
}
export async function deleteThread(id: string): Promise<void> {
+ const file = fileFor(id); // invalid ids are authorization/input errors, not "already gone"
try {
- await fs.unlink(fileFor(id));
+ await fs.unlink(file);
} catch {
/* already gone */
}
diff --git a/lib/auth/session.ts b/lib/auth/session.ts
index 0d881fe5..dd858908 100644
--- a/lib/auth/session.ts
+++ b/lib/auth/session.ts
@@ -7,16 +7,14 @@ import crypto from "crypto";
export const MIN_SECRET_LEN = 32;
/**
- * Length-safe constant-time string compare. Hashes both sides to a fixed
- * 32-byte SHA-256 digest before `timingSafeEqual`, so the comparison time
- * does NOT depend on the inputs' lengths. A naive `a.length === b.length`
- * early-exit would leak the secret's length over the network. Use this for
- * every password / token / signature compare. Mirrors lib/agent/server.ts.
+ * Length-safe constant-time string compare. A domain-separated HMAC maps both
+ * values to a fixed width before `timingSafeEqual`; it is not password storage
+ * and no verifier is persisted. A naive length early-exit would leak metadata.
*/
+const COMPARE_DOMAIN_KEY = Buffer.from("mso.constant-time-compare.v1", "utf8");
export function constantTimeEq(a: string, b: string): boolean {
- const ha = crypto.createHash("sha256").update(a).digest();
- const hb = crypto.createHash("sha256").update(b).digest();
- return crypto.timingSafeEqual(ha, hb);
+ const digest = (value: string) => crypto.createHmac("sha256", COMPARE_DOMAIN_KEY).update(value).digest();
+ return crypto.timingSafeEqual(digest(a), digest(b));
}
export interface SessionPayload {
diff --git a/lib/config/store-security.test.ts b/lib/config/store-security.test.ts
new file mode 100644
index 00000000..6a7fee87
--- /dev/null
+++ b/lib/config/store-security.test.ts
@@ -0,0 +1,85 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const roots: string[] = [];
+
+async function load() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-config-safe-"));
+ fs.chmodSync(root, 0o700);
+ roots.push(root);
+ vi.resetModules();
+ vi.stubEnv("OS_CONFIG_STORE", path.join(root, "config.json"));
+ return import("./store");
+}
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe("config record safety", () => {
+ it("slugifies without a backtracking regexp and preserves numeric provider names", async () => {
+ const { slugifyProvider } = await load();
+ expect(slugifyProvider(" My Provider / EU ")).toBe("my-provider-eu");
+ expect(slugifyProvider("123 Gateway")).toBe("123-gateway");
+ expect(slugifyProvider("***")).toBe("");
+ expect(slugifyProvider("a".repeat(100))).toHaveLength(40);
+ });
+
+ it("rejects prototype keys at every credential/custom/OAuth boundary", async () => {
+ const {
+ hostCredentialStore,
+ readOAuthBundle,
+ removeCustomProvider,
+ removeOAuthBundle,
+ upsertCustomProvider,
+ writeOAuthBundle,
+ } = await load();
+ const store = hostCredentialStore();
+ for (const bad of ["__proto__", "prototype", "constructor", "../openai", "OpenAI", ""]) {
+ await expect(store.setKey(undefined, bad, "secret")).rejects.toThrow("invalid provider id");
+ await expect(store.deleteKey(undefined, bad)).rejects.toThrow("invalid provider id");
+ await expect(upsertCustomProvider(bad, { baseUrl: "https://example.test/v1" })).rejects.toThrow("invalid provider id");
+ await expect(removeCustomProvider(bad)).rejects.toThrow("invalid provider id");
+ await expect(readOAuthBundle(bad)).rejects.toThrow("invalid provider id");
+ await expect(writeOAuthBundle(bad, { kind: "oauth", access: "x", expires: 1 })).rejects.toThrow("invalid provider id");
+ await expect(removeOAuthBundle(bad)).rejects.toThrow("invalid provider id");
+ }
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
+ });
+
+ it("round-trips ordinary maps without mutating Object.prototype", async () => {
+ const {
+ hostCredentialStore,
+ readConfig,
+ readOAuthBundle,
+ removeCustomProvider,
+ removeOAuthBundle,
+ selectedCustomConn,
+ upsertCustomProvider,
+ writeConfig,
+ writeOAuthBundle,
+ } = await load();
+ const credentials = hostCredentialStore();
+ await credentials.setKey(undefined, "custom-one", "key-one");
+ await credentials.setKey(undefined, "custom-two", "key-two");
+ await credentials.deleteKey(undefined, "custom-one");
+ await upsertCustomProvider("custom-two", { baseUrl: "https://example.test/v1", protocol: "openai" });
+ await writeOAuthBundle("custom-two", { kind: "oauth", access: "token", expires: 123 });
+ await writeConfig({ provider: "custom-two", model: "model-a" });
+
+ expect(await credentials.getKey(undefined, "custom-one")).not.toBe("key-one");
+ expect(await credentials.getKey(undefined, "custom-two")).toBe("key-two");
+ expect(await selectedCustomConn()).toMatchObject({ baseUrl: "https://example.test/v1" });
+ expect(await readOAuthBundle("custom-two")).toMatchObject({ access: "token" });
+ expect(await readConfig()).toMatchObject({ provider: "custom-two", model: "model-a" });
+
+ await removeCustomProvider("custom-two");
+ await removeOAuthBundle("custom-two");
+ expect(await selectedCustomConn()).toBeNull();
+ expect(await readOAuthBundle("custom-two")).toBeNull();
+ expect(Object.prototype).not.toHaveProperty("custom-two");
+ });
+});
diff --git a/lib/config/store.ts b/lib/config/store.ts
index 1ee9fd72..d7336ced 100644
--- a/lib/config/store.ts
+++ b/lib/config/store.ts
@@ -4,57 +4,60 @@ import path from "path";
import { envCredentialStore, PROVIDERS } from "@/lib/models";
import { DEFAULT_PROVIDER, defaultModelFor } from "@/lib/models/defaults";
-// Owner config (BYOK keys + selected provider/model), replacing the Convex
-// `appConfig` table. A host JSON file (chmod 600) read server-side only — raw keys
-// never reach the browser. `keys` is the per-provider SSOT; `anthropicApiKey`
-// stays a read-only alias so existing installs migrate for free.
-
-/** A user-added OpenAI-compatible / Anthropic-Messages endpoint. The key stays in
- * OsConfig.keys[slug] (same per-provider SSOT as built-ins); this holds the wiring. */
export interface CustomProviderConn {
baseUrl: string;
protocol?: "openai" | "anthropic";
models?: string[];
}
-/** An OAuth "sign in with…" token bundle (subscription providers). Stored in the
- * same 0600 host file as API keys — refresh tokens are account-scoped, so treat
- * this file like an SSH key (which is already mso's trust boundary). */
export interface OAuthBundle {
kind: "oauth";
access: string;
refresh?: string;
- /** ms epoch when `access` expires (for copilot: the short-lived token's expiry). */
expires: number;
- /** OpenAI Codex: chatgpt_account_id decoded from the token JWT. */
accountId?: string;
- /** GitHub Copilot: the durable gh token + the short-lived API token. */
ghToken?: string;
copilotToken?: string;
}
export interface OsConfig {
- /** Per-provider BYOK keys — the SSOT. */
keys?: Record<string, string>;
- /** Selected provider id (e.g. "anthropic"). */
provider?: string;
model?: string;
- /** User-added custom providers: slug → connection (key stays in keys[slug]). */
customProviders?: Record<string, CustomProviderConn>;
- /** OAuth subscription providers: slug → token bundle (openai-codex, …). */
oauthTokens?: Record<string, OAuthBundle>;
- /** Output token-saver mode appended to Alfa's system prompt. */
tokenSaver?: "off" | "caveman" | "ponytail";
/** @deprecated back-compat read alias for keys.anthropic. */
anthropicApiKey?: string;
}
-const CONFIG_PATH =
- process.env.OS_CONFIG_STORE ?? path.join(os.homedir(), ".mso", "config.json");
+const CONFIG_PATH = process.env.OS_CONFIG_STORE ?? path.join(os.homedir(), ".mso", "config.json");
+const PROVIDER_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
+const RESERVED_RECORD_KEYS = new Set(["__proto__", "prototype", "constructor"]);
export const DEFAULT_MODEL = defaultModelFor(DEFAULT_PROVIDER);
export { DEFAULT_PROVIDER };
+function safeProviderId(value: string): string {
+ if (!PROVIDER_ID_RE.test(value) || RESERVED_RECORD_KEYS.has(value)) throw new Error("invalid provider id");
+ return value;
+}
+
+function recordValue<T>(record: Record<string, T> | undefined, key: string): T | undefined {
+ return Object.entries(record ?? {}).find(([name]) => name === key)?.[1];
+}
+
+function recordSet<T>(record: Record<string, T> | undefined, key: string, value: T): Record<string, T> {
+ return Object.fromEntries([
+ ...Object.entries(record ?? {}).filter(([name]) => name !== key),
+ [key, value],
+ ]);
+}
+
+function recordDelete<T>(record: Record<string, T> | undefined, key: string): Record<string, T> {
+ return Object.fromEntries(Object.entries(record ?? {}).filter(([name]) => name !== key));
+}
+
export async function readConfig(): Promise<OsConfig> {
try {
return JSON.parse(await fs.readFile(CONFIG_PATH, "utf8")) as OsConfig;
@@ -72,86 +75,85 @@ export async function writeConfig(patch: OsConfig): Promise<void> {
await fs.rename(tmp, CONFIG_PATH);
}
-// The selected model as a "provider/model" ref for @rahmanef/models resolveModel().
export async function resolveModelRef(): Promise<string> {
const c = await readConfig();
- const provider = c.provider || DEFAULT_PROVIDER;
+ const provider = safeProviderId(c.provider || DEFAULT_PROVIDER);
return `${provider}/${c.model || defaultModelFor(provider)}`;
}
-// A @rahmanef/models CredentialStore over the 0600 host config file, per-provider,
-// with the env chain as fallback. Single-owner → tenantId ignored. The stored BYOK
-// key wins; legacy anthropicApiKey is a read fallback; else env (ANTHROPIC_API_KEY…).
export function hostCredentialStore() {
const env = envCredentialStore();
return {
async getKey(_tenant: string | undefined, provider: string) {
+ const safe = safeProviderId(provider);
const c = await readConfig();
- const fromFile = c.keys?.[provider] ?? (provider === "anthropic" ? c.anthropicApiKey : undefined);
- return fromFile || (await env.getKey(_tenant, provider));
+ const fromFile = recordValue(c.keys, safe) ?? (safe === "anthropic" ? c.anthropicApiKey : undefined);
+ return fromFile || (await env.getKey(_tenant, safe));
},
async setKey(_tenant: string | undefined, provider: string, key: string) {
+ const safe = safeProviderId(provider);
const c = await readConfig();
- await writeConfig({ keys: { ...(c.keys ?? {}), [provider]: key } });
+ await writeConfig({ keys: recordSet(c.keys, safe, key) });
},
async deleteKey(_tenant: string | undefined, provider: string) {
+ const safe = safeProviderId(provider);
const c = await readConfig();
- const keys = { ...(c.keys ?? {}) };
- delete keys[provider];
- await writeConfig({ keys });
+ await writeConfig({ keys: recordDelete(c.keys, safe) });
},
};
}
-// ── Custom providers ─────────────────────────────────────────────────────────
-// A slug for a user-named provider: lowercase, alnum + dashes, ≤40 chars.
export function slugifyProvider(name: string): string {
- return name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40);
+ let slug = "";
+ let pendingDash = false;
+ for (const ch of name.trim().toLowerCase()) {
+ const alnum = (ch >= "a" && ch <= "z") || (ch >= "0" && ch <= "9");
+ if (alnum) {
+ if (pendingDash && slug) slug += "-";
+ slug += ch;
+ pendingDash = false;
+ } else pendingDash = true;
+ if (slug.length >= 40) break;
+ }
+ return slug ? safeProviderId(slug) : "";
}
-// True if `slug` is a registry built-in — a custom provider must NOT shadow one,
-// else resolveModel would pin the key to the built-in's baseUrl, not the user's.
export function isBuiltinProvider(slug: string): boolean {
return Object.prototype.hasOwnProperty.call(PROVIDERS, slug);
}
-// The custom-provider connection for the SELECTED provider, else null. Threaded
-// into resolveModel so a custom key resolves against its own baseUrl+protocol;
-// built-ins return null → stay registry-pinned.
export async function selectedCustomConn(): Promise<CustomProviderConn | null> {
const c = await readConfig();
- const p = c.provider || DEFAULT_PROVIDER;
- return c.customProviders?.[p] ?? null;
+ const provider = safeProviderId(c.provider || DEFAULT_PROVIDER);
+ return recordValue(c.customProviders, provider) ?? null;
}
export async function upsertCustomProvider(slug: string, conn: CustomProviderConn): Promise<void> {
+ const safe = safeProviderId(slug);
const c = await readConfig();
- await writeConfig({ customProviders: { ...(c.customProviders ?? {}), [slug]: conn } });
+ await writeConfig({ customProviders: recordSet(c.customProviders, safe, conn) });
}
export async function removeCustomProvider(slug: string): Promise<void> {
+ const safe = safeProviderId(slug);
const c = await readConfig();
- if (!c.customProviders?.[slug]) return;
- const next = { ...c.customProviders };
- delete next[slug];
- await writeConfig({ customProviders: next });
+ await writeConfig({ customProviders: recordDelete(c.customProviders, safe) });
}
-// ── OAuth token bundles ──────────────────────────────────────────────────────
export async function readOAuthBundle(slug: string): Promise<OAuthBundle | null> {
+ const safe = safeProviderId(slug);
const c = await readConfig();
- return c.oauthTokens?.[slug] ?? null;
+ return recordValue(c.oauthTokens, safe) ?? null;
}
export async function writeOAuthBundle(slug: string, bundle: OAuthBundle): Promise<void> {
+ const safe = safeProviderId(slug);
const c = await readConfig();
- await writeConfig({ oauthTokens: { ...(c.oauthTokens ?? {}), [slug]: bundle } });
+ await writeConfig({ oauthTokens: recordSet(c.oauthTokens, safe, bundle) });
}
export async function removeOAuthBundle(slug: string): Promise<void> {
+ const safe = safeProviderId(slug);
const c = await readConfig();
- if (!c.oauthTokens?.[slug]) return;
- const next = { ...c.oauthTokens };
- delete next[slug];
- await writeConfig({ oauthTokens: next });
+ await writeConfig({ oauthTokens: recordDelete(c.oauthTokens, safe) });
}
diff --git a/lib/host/fs-upload.test.ts b/lib/host/fs-upload.test.ts
index 63bde483..405758bb 100644
--- a/lib/host/fs-upload.test.ts
+++ b/lib/host/fs-upload.test.ts
@@ -61,14 +61,9 @@ describe("streamFileInto — the upload write boundary", () => {
const destReal = await resolveUploadDest(dir);
const res = await streamFileInto(destReal, relPath, text("pwned"));
- // Either rejected outright, or the ".." segments were stripped so it landed
- // INSIDE dest. What must never happen is a write above dest.
- if (res === "ok") {
- const escaped = path.resolve(dir, "..", "escape.txt");
- await expect(fs.access(escaped)).rejects.toThrow();
- } else {
- expect(res).toBe("bad-path");
- }
+ expect(res).toBe("bad-path");
+ const escaped = path.resolve(dir, "..", "escape.txt");
+ await expect(fs.access(escaped)).rejects.toThrow();
await expect(fs.access("/etc/cron.d/pwn")).rejects.toThrow();
});
@@ -78,7 +73,7 @@ describe("streamFileInto — the upload write boundary", () => {
expect(await streamFileInto(destReal, "big.bin", bytes(101 * 1024 * 1024))).toBe("too-large");
await expect(fs.access(path.join(dir, "big.bin"))).rejects.toThrow();
- expect((await fs.readdir(dir)).filter((f) => f.includes(".tmp-"))).toEqual([]);
+ expect((await fs.readdir(dir)).filter((f) => f.includes("mso-upload") || f.endsWith(".tmp"))).toEqual([]);
});
it("rejects a destination outside the WRITE roots", async () => {
diff --git a/lib/host/fs-upload.ts b/lib/host/fs-upload.ts
index 4d6e8c86..5f1942f3 100644
--- a/lib/host/fs-upload.ts
+++ b/lib/host/fs-upload.ts
@@ -4,6 +4,7 @@
// writeFile/move/copy (so an upload can't write ~/.ssh/authorized_keys or escape
// the dest through a symlinked subdir). Split out of fs.ts for single responsibility.
import { promises as fs, createWriteStream } from "fs";
+import { randomBytes } from "crypto";
import { once } from "events";
import path from "path";
import { HostError } from "./host-error";
@@ -33,14 +34,18 @@ export async function uploadInto(
failed.push(relPath);
continue;
}
+ const tmp = privateTempPath(full);
try {
- await fs.mkdir(path.dirname(full), { recursive: true });
- const tmp = `${full}.tmp-${process.pid}`;
- await fs.writeFile(tmp, data, { mode: 0o644 });
+ await fs.mkdir(path.dirname(full), { recursive: true, mode: 0o700 });
+ await assertUploadTarget(full, destReal); // parent may have appeared since the first check
+ await fs.writeFile(tmp, data, { mode: 0o600, flag: "wx" });
+ await fs.chmod(tmp, 0o644);
await fs.rename(tmp, full);
written++;
} catch {
failed.push(relPath);
+ } finally {
+ await fs.rm(tmp, { force: true }).catch(() => {});
}
}
return { written, failed };
@@ -76,9 +81,11 @@ export async function streamFileInto(
return "bad-path";
}
- await fs.mkdir(path.dirname(full), { recursive: true });
- const tmp = `${full}.tmp-${process.pid}-${Date.now()}`;
- const out = createWriteStream(tmp, { mode: 0o644 });
+ await fs.mkdir(path.dirname(full), { recursive: true, mode: 0o700 });
+ try { await assertUploadTarget(full, destReal); }
+ catch { await drain(body); return "bad-path"; }
+ const tmp = privateTempPath(full);
+ const out = createWriteStream(tmp, { mode: 0o600, flags: "wx" });
let bytes = 0;
let tooLarge = false;
try {
@@ -100,12 +107,20 @@ export async function streamFileInto(
await fs.rm(tmp, { force: true });
return "too-large";
}
+ await fs.chmod(tmp, 0o644);
await fs.rename(tmp, full);
return "ok";
}
+function privateTempPath(full: string): string {
+ return `${full}.mso-upload-${process.pid}-${randomBytes(8).toString("hex")}.tmp`;
+}
+
function sanitiseSegments(relPath: string): string[] {
- return relPath.split("/").map((s) => s.trim()).filter((s) => s && s !== "." && s !== "..");
+ if (!relPath || relPath.length > 1024 || relPath.includes("\0")) return [];
+ const segments = relPath.split("/").map((segment) => segment.trim());
+ if (segments.some((segment) => !segment || segment === "." || segment === ".." || segment.length > 255)) return [];
+ return segments;
}
async function drain(body: AsyncIterable<Uint8Array>): Promise<void> {
diff --git a/lib/host/fs.ts b/lib/host/fs.ts
index f66038c9..8d023953 100644
--- a/lib/host/fs.ts
+++ b/lib/host/fs.ts
@@ -1,7 +1,7 @@
// SERVER-ONLY. Host filesystem ops behind /api/v1/fs/*. Reads follow READ
// roots (browse), mutations follow WRITE roots (see paths.ts). Returns the
// os-rr shapes directly so route handlers are thin.
-import { promises as fs, createReadStream, type ReadStream } from "fs";
+import { promises as fs, constants as fsConstants, createReadStream, type ReadStream } from "fs";
import path from "path";
import type { FsList, FsUsage } from "@/lib/os-api/types";
import { HostError } from "./host-error";
@@ -55,10 +55,19 @@ export async function listDir(requested: string, includeHidden = true): Promise<
export async function readFile(requested: string): Promise<string> {
const p = await resolveReadable(requested);
- const stat = await fs.stat(p);
- if (stat.isDirectory()) throw new HostError("Is a directory");
- if (stat.size > 5_000_000) throw new HostError("File too large to read (max 5 MiB)");
- return fs.readFile(p, "utf8");
+ let handle;
+ try {
+ handle = await fs.open(p, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
+ const stat = await handle.stat();
+ if (!stat.isFile()) throw new HostError(stat.isDirectory() ? "Is a directory" : "Not a regular file");
+ if (stat.size > 5_000_000) throw new HostError("File too large to read (max 5 MiB)");
+ return await handle.readFile("utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ELOOP") throw new HostError("Refusing symlink file");
+ throw error;
+ } finally {
+ await handle?.close().catch(() => undefined);
+ }
}
export async function writeFile(requested: string, content: string): Promise<void> {
diff --git a/lib/host/paths.test.ts b/lib/host/paths.test.ts
index 0f848ea9..f8f9c0c3 100644
--- a/lib/host/paths.test.ts
+++ b/lib/host/paths.test.ts
@@ -71,6 +71,12 @@ describe("resolveReadable bounds", () => {
await expect(resolveReadable(sneaky)).rejects.toThrow(/outside readable roots/i);
});
+ it("rejects a nonexistent outside path before probing it with realpath", async () => {
+ useRoots(readRoot, writeRoot);
+ await expect(resolveReadable(path.join(outside, "does-not-exist.txt")))
+ .rejects.toThrow(/outside readable roots/i);
+ });
+
it("rejects a symlink inside the root that points outside it", async () => {
useRoots(readRoot, writeRoot);
await expect(resolveReadable(path.join(readRoot, "sneaky"))).rejects.toThrow(
@@ -151,6 +157,12 @@ describe("safeWritePath bounds", () => {
);
});
+ it("rejects a nonexistent outside parent before resolving filesystem metadata", async () => {
+ useRoots(readRoot, writeRoot);
+ await expect(safeWritePath(path.join(outside, "missing", "new.txt"), false))
+ .rejects.toThrow(/outside writable roots/i);
+ });
+
it("rejects ../ traversal out of the write root", async () => {
useRoots(readRoot, writeRoot);
await expect(
diff --git a/lib/host/paths.ts b/lib/host/paths.ts
index 694d8236..77db83cc 100644
--- a/lib/host/paths.ts
+++ b/lib/host/paths.ts
@@ -301,6 +301,14 @@ async function realRoots(list: string[]): Promise<string[]> {
);
}
+function lexicalRoots(list: string[]): string[] {
+ return list.map((root) => path.resolve(root));
+}
+
+function assertLexicalContainment(target: string, roots: string[], message: string): void {
+ if (!roots.some((root) => isUnderRoot(target, root))) throw new HostError(message);
+}
+
// Realpath-resolved WRITE roots — shared by safeWritePath/assertNotRoot here and
// exec.ts's cwd bounds, so the realpath-fallback strategy lives in one place.
export async function resolveWriteRoots(): Promise<string[]> {
@@ -315,8 +323,11 @@ export async function resolveReadable(requested: string): Promise<string> {
if (!requested || requested === "~") absolute = h;
else if (requested.startsWith("~/")) absolute = path.join(h, requested.slice(2));
else absolute = path.resolve(requested);
- const real = await fs.realpath(path.resolve(absolute));
- const rr = await realRoots(readRootList());
+ const normalized = path.resolve(absolute);
+ const configured = lexicalRoots(readRootList());
+ assertLexicalContainment(normalized, configured, "Path outside readable roots");
+ const real = await fs.realpath(normalized);
+ const rr = await realRoots(configured);
if (!rr.some((r) => isUnderRoot(real, r))) throw new HostError("Path outside readable roots");
assertNotCredential(real);
return real;
@@ -330,16 +341,20 @@ export async function safeWritePath(requested: string, mustExist: boolean): Prom
if (!requested || requested === "~" || requested === "/") absolute = h;
else if (requested.startsWith("~/")) absolute = path.join(h, requested.slice(2));
else absolute = path.resolve(requested);
- const rr = await realRoots(writeRootList());
+ const normalized = path.resolve(absolute);
+ const configured = lexicalRoots(writeRootList());
+ const lexicalTarget = mustExist ? normalized : path.dirname(normalized);
+ assertLexicalContainment(lexicalTarget, configured, "Path outside writable roots");
+ const rr = await realRoots(configured);
if (mustExist) {
- const real = await fs.realpath(absolute);
+ const real = await fs.realpath(normalized);
if (!rr.some((r) => isUnderRoot(real, r))) throw new HostError("Path outside writable roots");
assertNotCredential(real);
return real;
}
- const parent = await fs.realpath(path.dirname(absolute));
+ const parent = await fs.realpath(path.dirname(normalized));
if (!rr.some((r) => isUnderRoot(parent, r))) throw new HostError("Path outside writable roots");
- const joined = path.join(parent, path.basename(absolute));
+ const joined = path.join(parent, path.basename(normalized));
assertNotCredential(joined);
return joined;
}
diff --git a/lib/mcp/collision-e2e.test.ts b/lib/mcp/collision-e2e.test.ts
index dd753066..db5ffe25 100644
--- a/lib/mcp/collision-e2e.test.ts
+++ b/lib/mcp/collision-e2e.test.ts
@@ -1,20 +1,36 @@
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
+import { createHash } from "crypto";
import { promises as fs } from "fs";
+import os from "os";
import path from "path";
// THE COLLISION, END TO END.
//
-// `/tmp/mso-root-50323` and `/tmp/mso-root-125549` both hash to `51e156ef` at 8 hex —
-// a real pair found by a probe, not a hypothetical. Each holds a project called `widget`
-// shipping a skill called `deploy`. Under the old 32-bit id these two collapsed into one
-// row and half the box became invisible.
-//
-// It is not enough that the ids differ: every surface a client actually uses must return
-// the SECOND project when handed the second id. That is what this file pins —
-// projects_list, skills_list, skills_read, skills_search and workflow_start.
-const ROOT_A = "/tmp/mso-root-50323";
-const ROOT_B = "/tmp/mso-root-125549";
+// A private temporary parent is created at runtime, then two child path strings are
+// found that collide at the historical 8-hex/32-bit id. Each holds a project called
+// `widget` shipping a skill called `deploy`. Under the old id those rows collapsed.
+// Every client surface must still resolve the SECOND project by its full 32-hex id.
+let PRIVATE_ROOT = "";
+let ROOT_A = "";
+let ROOT_B = "";
+
+function legacyId(value: string): string {
+ return createHash("sha256").update(value).digest("hex").slice(0, 8);
+}
+
+function collisionPair(parent: string): [string, string] {
+ const seen = new Map<string, string>();
+ for (let index = 0; index < 300_000; index += 1) {
+ const candidate = path.join(parent, `root-${index}`);
+ const id = legacyId(candidate);
+ const first = seen.get(id);
+ if (first) return [first, candidate];
+ seen.set(id, candidate);
+ }
+ throw new Error("could not find an 8-hex collision within the bounded fixture search");
+}
+
const previous = {
read: process.env.OS_FS_READ_ROOTS,
write: process.env.OS_FS_WRITE_ROOTS,
@@ -32,6 +48,9 @@ async function seed(root: string, marker: string) {
}
beforeAll(async () => {
+ PRIVATE_ROOT = await fs.mkdtemp(path.join(os.tmpdir(), "mso-collision-"));
+ await fs.chmod(PRIVATE_ROOT, 0o700);
+ [ROOT_A, ROOT_B] = collisionPair(PRIVATE_ROOT);
await seed(ROOT_A, "alpha");
await seed(ROOT_B, "bravo");
process.env.OS_FS_READ_ROOTS = `${ROOT_A}:${ROOT_B}`;
@@ -45,7 +64,7 @@ afterAll(async () => {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
- await Promise.all([ROOT_A, ROOT_B].map((r) => fs.rm(r, { recursive: true, force: true })));
+ if (PRIVATE_ROOT) await fs.rm(PRIVATE_ROOT, { recursive: true, force: true });
});
const { DISCOVERY_TOOLS } = await import("./tools-discovery");
diff --git a/lib/models/catalog.js b/lib/models/catalog.js
index 6d5d6c4d..37a10f75 100644
--- a/lib/models/catalog.js
+++ b/lib/models/catalog.js
@@ -1,42 +1,76 @@
-// Model CATALOG — capability + pricing metadata, sourced wholesale from models.dev
-// (community DB, free). This is the auto-update mechanism: models.dev updates upstream ->
-// our catalog refreshes on next read after TTL. No plugin per vendor, no hardcoded list.
-//
-// Refresh strategy stolen from hermes (agent/models_dev.py): lazy 4-stage hierarchy
-// 1. in-mem cache < TTL -> return
-// 2. disk cache < TTL (by mtime) -> load
-// 3. network GET -> fetch + persist
-// 4. network fail -> serve ANY disk cache (stale) with a shortened retry window
-// No background thread. Degrades to offline gracefully.
-
-import { readFile, writeFile, mkdir } from 'node:fs/promises'
+// Model catalog metadata, sourced from the one fixed HTTPS models.dev endpoint.
+// Lazy hierarchy: memory -> bounded private disk cache -> bounded network -> stale disk.
+import { constants as fsConstants } from 'node:fs'
+import { open, writeFile, rename, mkdir, chmod, rm } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join, dirname } from 'node:path'
+import { randomBytes } from 'node:crypto'
const URL_MODELS_DEV = 'https://models.dev/api.json'
-const TTL_MS = 60 * 60 * 1000 // 1h, same as hermes
+const TTL_MS = 60 * 60 * 1000
const STALE_RETRY_MS = 5 * 60 * 1000
-const CACHE_FILE = join(process.env.MODELS_CACHE_DIR || join(homedir(), '.models-rahmanef'), 'catalog.json')
+const MAX_CATALOG_BYTES = 12 * 1024 * 1024
+const CACHE_FILE = process.env.MODELS_CACHE_FILE || join(process.env.MODELS_CACHE_DIR || join(homedir(), '.models-rahmanef'), 'catalog.json')
+
+let mem = null
-let mem = null // { at:number, data:object }
+function catalogObject(value) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('models.dev returned an invalid catalog')
+ return value
+}
+
+async function readBoundedResponse(response) {
+ const declared = Number(response.headers.get('content-length') || 0)
+ if (declared > MAX_CATALOG_BYTES) throw new Error('models.dev catalog exceeds size limit')
+ if (!response.body) throw new Error('models.dev returned no body')
+ const reader = response.body.getReader()
+ const chunks = []
+ let bytes = 0
+ try {
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ bytes += value.byteLength
+ if (bytes > MAX_CATALOG_BYTES) {
+ await reader.cancel('catalog size limit exceeded').catch(() => {})
+ throw new Error('models.dev catalog exceeds size limit')
+ }
+ chunks.push(value)
+ }
+ } finally {
+ reader.releaseLock()
+ }
+ const joined = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)), bytes).toString('utf8')
+ return catalogObject(JSON.parse(joined))
+}
async function readDisk() {
+ let handle
try {
- const raw = JSON.parse(await readFile(CACHE_FILE, 'utf8'))
- if (raw && typeof raw.at === 'number' && raw.data) return raw
- } catch { /* no cache yet / corrupt */ }
+ handle = await open(CACHE_FILE, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)
+ const stat = await handle.stat()
+ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_CATALOG_BYTES) return null
+ const raw = JSON.parse(await handle.readFile('utf8'))
+ if (raw && typeof raw.at === 'number' && raw.data) return { at: raw.at, data: catalogObject(raw.data) }
+ } catch { /* no cache yet / corrupt / symlink */ }
+ finally { await handle?.close().catch(() => {}) }
return null
}
async function writeDisk(entry) {
- await mkdir(dirname(CACHE_FILE), { recursive: true })
- await writeFile(CACHE_FILE, JSON.stringify(entry))
+ const dir = dirname(CACHE_FILE)
+ await mkdir(dir, { recursive: true, mode: 0o700 })
+ await chmod(dir, 0o700).catch(() => {})
+ const tmp = `${CACHE_FILE}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`
+ try {
+ await writeFile(tmp, JSON.stringify(entry), { encoding: 'utf8', mode: 0o600, flag: 'wx' })
+ await rename(tmp, CACHE_FILE)
+ } finally {
+ await rm(tmp, { force: true }).catch(() => {})
+ }
}
-/**
- * @param {{force?:boolean}} [opts]
- * @returns {Promise<Record<string, {models: Record<string, any>}>>} raw models.dev blob keyed by provider id
- */
+/** @returns {Promise<Record<string, {models: Record<string, any>}>>} */
export async function getCatalog({ force = false } = {}) {
const now = Date.now()
if (!force && mem && now - mem.at < TTL_MS) return mem.data
@@ -45,15 +79,19 @@ export async function getCatalog({ force = false } = {}) {
if (disk && now - disk.at < TTL_MS) { mem = disk; return disk.data }
}
try {
- const res = await fetch(URL_MODELS_DEV, { signal: AbortSignal.timeout(15000) })
+ const res = await fetch(URL_MODELS_DEV, {
+ redirect: 'error',
+ signal: AbortSignal.timeout(15000),
+ headers: { accept: 'application/json' },
+ })
if (!res.ok) throw new Error(`models.dev HTTP ${res.status}`)
- const data = await res.json()
+ const data = await readBoundedResponse(res)
mem = { at: now, data }
- writeDisk(mem).catch(() => {})
+ await writeDisk(mem).catch(() => {})
return data
} catch (err) {
const disk = await readDisk()
- if (disk) { mem = { at: now - (TTL_MS - STALE_RETRY_MS), data: disk.data }; return disk.data } // serve stale, retry soon
+ if (disk) { mem = { at: now - (TTL_MS - STALE_RETRY_MS), data: disk.data }; return disk.data }
throw err
}
}
@@ -62,8 +100,12 @@ export async function getCatalog({ force = false } = {}) {
export async function listModels(opts) {
const cat = await getCatalog(opts)
const out = []
- for (const [pid, p] of Object.entries(cat)) {
- for (const [mid, m] of Object.entries(p.models || {})) out.push({ ref: `${pid}/${mid}`, provider: pid, ...m })
+ for (const [pid, provider] of Object.entries(cat)) {
+ if (!provider || typeof provider !== 'object' || Array.isArray(provider)) continue
+ for (const [mid, model] of Object.entries(provider.models || {})) {
+ if (!model || typeof model !== 'object' || Array.isArray(model)) continue
+ out.push({ ref: `${pid}/${mid}`, provider: pid, ...model })
+ }
}
return out
}
diff --git a/lib/models/catalog.test.ts b/lib/models/catalog.test.ts
new file mode 100644
index 00000000..e9832036
--- /dev/null
+++ b/lib/models/catalog.test.ts
@@ -0,0 +1,79 @@
+import fs from "node:fs";
+import { randomUUID } from "node:crypto";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const roots: string[] = [];
+
+async function load() {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-model-catalog-"));
+ fs.chmodSync(root, 0o700);
+ roots.push(root);
+ const cache = path.join(root, "catalog.json");
+ vi.resetModules();
+ vi.stubEnv("MODELS_CACHE_FILE", cache);
+ return { root, cache, mod: await import("./catalog.js") };
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true });
+});
+
+describe("bounded models.dev catalog cache", () => {
+ it("fetches only the fixed endpoint and writes a private atomic cache", async () => {
+ const body = JSON.stringify({ openai: { models: { "gpt-test": { name: "GPT Test" } } } });
+ const fetchMock = vi.fn(async () => new Response(body, {
+ status: 200,
+ headers: { "content-type": "application/json", "content-length": String(Buffer.byteLength(body)) },
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+ const { root, cache, mod } = await load();
+
+ await expect(mod.getCatalog({ force: true })).resolves.toMatchObject({ openai: { models: { "gpt-test": {} } } });
+ expect(fetchMock).toHaveBeenCalledWith("https://models.dev/api.json", expect.objectContaining({ redirect: "error" }));
+ expect(fs.statSync(root).mode & 0o777).toBe(0o700);
+ expect(fs.statSync(cache).mode & 0o777).toBe(0o600);
+ expect(JSON.parse(fs.readFileSync(cache, "utf8")).data.openai.models).toHaveProperty("gpt-test");
+ expect(fs.readdirSync(root).filter((name) => name.endsWith(".tmp"))).toEqual([]);
+ });
+
+ it("rejects an over-limit response before reading its body", async () => {
+ const fetchMock = vi.fn(async () => new Response("{}", {
+ status: 200,
+ headers: { "content-length": String(13 * 1024 * 1024) },
+ }));
+ vi.stubGlobal("fetch", fetchMock);
+ const { mod } = await load();
+ await expect(mod.getCatalog({ force: true })).rejects.toThrow("exceeds size limit");
+ });
+
+ it("uses a validated stale cache when the fixed network endpoint is unavailable", async () => {
+ const { cache, mod } = await load();
+ fs.writeFileSync(cache, JSON.stringify({
+ at: 1,
+ data: { local: { models: { fallback: { name: "Fallback" } } } },
+ }), { mode: 0o600 });
+ vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("offline"); }));
+ await expect(mod.getCatalog({ force: true })).resolves.toMatchObject({ local: { models: { fallback: {} } } });
+ });
+
+ it("never follows a symlinked cache file", async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "mso-model-catalog-"));
+ const outsideRoot = fs.mkdtempSync(path.join(os.tmpdir(), "mso-model-poison-"));
+ fs.chmodSync(root, 0o700);
+ fs.chmodSync(outsideRoot, 0o700);
+ roots.push(root, outsideRoot);
+ const outside = path.join(outsideRoot, "outside.json");
+ const cache = path.join(root, `catalog-${randomUUID()}.json`);
+ fs.writeFileSync(outside, JSON.stringify({ at: 1, data: { poisoned: { models: {} } } }), { mode: 0o600 });
+ fs.symlinkSync(outside, cache);
+ vi.resetModules();
+ vi.stubEnv("MODELS_CACHE_FILE", cache);
+ vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("offline"); }));
+ const mod = await import("./catalog.js");
+ await expect(mod.getCatalog({ force: true })).rejects.toThrow("offline");
+ });
+});
diff --git a/lib/security-store-lock.ts b/lib/security-store-lock.ts
index e3ad2fc5..b01f34b7 100644
--- a/lib/security-store-lock.ts
+++ b/lib/security-store-lock.ts
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
-import { promises as fs } from "node:fs";
+import { promises as fs, constants as fsConstants } from "node:fs";
import path from "node:path";
// Cross-process lock for the tiny JSON files that carry security decisions.
@@ -30,15 +30,23 @@ function pidIsGone(pid: number): boolean {
}
async function abandoned(lockPath: string, staleMs: number): Promise<boolean> {
- const stat = await fs.stat(lockPath).catch(() => null);
- if (!stat) return true;
- const age = Date.now() - stat.mtimeMs;
- const owner = await fs.readFile(lockPath, "utf8").catch(() => "");
- const pid = Number(owner.split(":", 1)[0]);
- // A valid, live PID wins over age: never break mutual exclusion merely because
- // the process was paused. Age is only the recovery path for malformed owner data.
- if (Number.isInteger(pid) && pid > 1) return pidIsGone(pid);
- return age > staleMs;
+ let handle;
+ try {
+ handle = await fs.open(lockPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
+ const stat = await handle.stat();
+ if (!stat.isFile()) return false; // fail closed: never auto-break an unexpected object
+ const owner = await handle.readFile("utf8");
+ const pid = Number(owner.split(":", 1)[0]);
+ // A valid, live PID wins over age: never break mutual exclusion merely because
+ // the process was paused. Age is only the recovery path for malformed owner data.
+ if (Number.isInteger(pid) && pid > 1) return pidIsGone(pid);
+ return Date.now() - stat.mtimeMs > staleMs;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return true;
+ return false; // symlink, permission error, I/O failure: availability over unsafe recovery
+ } finally {
+ await handle?.close().catch(() => undefined);
+ }
}
async function openExclusive(lockPath: string, token: string): Promise<HeldLock> {
diff --git a/lib/security/private-shell-state.test.ts b/lib/security/private-shell-state.test.ts
index 824a202b..2e60f807 100644
--- a/lib/security/private-shell-state.test.ts
+++ b/lib/security/private-shell-state.test.ts
@@ -64,11 +64,11 @@ describe("private shell state", () => {
// the create mode, so `{ mode: 0o644 }` alone can silently create 0600 and make
// this negative fixture test the safe path instead. Force the post-create mode.
fs.chmodSync(file, 0o644);
- expect(fs.statSync(file).mode & 0o777).toBe(0o644);
const run = bash(`mso_private_state_ensure_file ${JSON.stringify(file)}`);
expect(run.status).not.toBe(0);
expect(run.stderr).toContain("file must be mode 0600");
expect(fs.readFileSync(file, "utf8")).toBe("exposed");
+ expect(fs.statSync(file).mode & 0o777).toBe(0o644);
});
it("atomically replaces only a validated regular session file", () => {
diff --git a/scripts/approve-device.js b/scripts/approve-device.js
index 78523a27..86ece9ac 100755
--- a/scripts/approve-device.js
+++ b/scripts/approve-device.js
@@ -53,16 +53,20 @@ function pidIsGone(pid) {
catch (error) { return error && error.code === "ESRCH"; }
}
function abandonedLock() {
+ let fd;
try {
- const st = fs.statSync(LOCK);
- let owner = "";
- try { owner = fs.readFileSync(LOCK, "utf8"); } catch {}
+ fd = fs.openSync(LOCK, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
+ const st = fs.fstatSync(fd);
+ if (!st.isFile()) return false;
+ const owner = fs.readFileSync(fd, "utf8");
const pid = Number(owner.split(":", 1)[0]);
if (Number.isInteger(pid) && pid > 1) return pidIsGone(pid);
return Date.now() - st.mtimeMs > LOCK_STALE_MS;
} catch (error) {
if (error && error.code === "ENOENT") return true;
- throw error;
+ return false;
+ } finally {
+ if (fd !== undefined) try { fs.closeSync(fd); } catch {}
}
}
function openExclusive(file, token) {
diff --git a/scripts/gen-comparison.mjs b/scripts/gen-comparison.mjs
index a63b148a..959b606a 100755
--- a/scripts/gen-comparison.mjs
+++ b/scripts/gen-comparison.mjs
@@ -136,7 +136,9 @@ const details = [
].join("\n");
function writeOrCheck(file, next) {
- const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
+ let current = "";
+ try { current = fs.readFileSync(file, "utf8"); }
+ catch (error) { if (error?.code !== "ENOENT") throw error; }
if (check) {
if (current !== next) fail(`${path.relative(root, file)} is stale; run node scripts/gen-comparison.mjs`);
} else {
diff --git a/scripts/skill-market.mjs b/scripts/skill-market.mjs
index fc056716..b5936451 100755
--- a/scripts/skill-market.mjs
+++ b/scripts/skill-market.mjs
@@ -9,7 +9,18 @@ import { fileURLToPath } from "node:url";
const here = path.dirname(fileURLToPath(import.meta.url));
const repo = path.resolve(here, "..");
const market = path.join(repo, "skill-market");
-const catalog = JSON.parse(fs.readFileSync(path.join(market, "catalog.json"), "utf8"));
+function readRegularFile(file, maxBytes = 1024 * 1024) {
+ let fd;
+ try {
+ fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
+ const stat = fs.fstatSync(fd);
+ if (!stat.isFile() || stat.size <= 0 || stat.size > maxBytes) throw new Error(`invalid regular file: ${file}`);
+ return fs.readFileSync(fd);
+ } finally {
+ if (fd !== undefined) fs.closeSync(fd);
+ }
+}
+const catalog = JSON.parse(readRegularFile(path.join(market, "catalog.json"), 512 * 1024).toString("utf8"));
const root = path.resolve(process.env.MSO_SKILL_INSTALL_ROOT || path.join(os.homedir(), ".mso", "skills"));
const sha = (data) => crypto.createHash("sha256").update(data).digest("hex");
const fail = (message) => { console.error(`mso skills: ${message}`); process.exitCode = 1; };
@@ -20,10 +31,9 @@ function safeEntry(id) {
if (!/^[a-z][a-z0-9-]{0,63}$/.test(entry.id)) throw new Error(`invalid catalog id: ${entry.id}`);
const file = path.resolve(market, entry.file);
if (!file.startsWith(`${market}${path.sep}`)) throw new Error(`catalog path escapes market: ${entry.file}`);
- const stat = fs.lstatSync(file);
- if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`${entry.id}: SKILL.md must be a regular file`);
- const body = fs.readFileSync(file);
- if (body.length === 0 || body.length > 256 * 1024) throw new Error(`${entry.id}: invalid SKILL.md size`);
+ let body;
+ try { body = readRegularFile(file, 256 * 1024); }
+ catch { throw new Error(`${entry.id}: SKILL.md must be a non-empty regular file <= 256 KiB`); }
if (sha(body) !== entry.sha256) throw new Error(`${entry.id}: catalog hash mismatch; repository review is stale`);
const text = body.toString("utf8");
const match = text.match(/^---\s*\n[\s\S]*?^name:\s*["']?([^\n"']+)["']?\s*$[\s\S]*?^---\s*$/m);
@@ -39,12 +49,12 @@ function ensureRoot() {
function installedState(entry) {
const dir = path.join(root, entry.id);
- if (!fs.existsSync(dir)) return "not-installed";
- const st = fs.lstatSync(dir);
+ let st;
+ try { st = fs.lstatSync(dir); }
+ catch (error) { if (error?.code === "ENOENT") return "not-installed"; throw error; }
if (!st.isDirectory() || st.isSymbolicLink()) return "conflict";
- const skill = path.join(dir, "SKILL.md");
- if (!fs.existsSync(skill) || fs.lstatSync(skill).isSymbolicLink()) return "conflict";
- return sha(fs.readFileSync(skill)) === entry.sha256 ? "installed" : "modified";
+ try { return sha(readRegularFile(path.join(dir, "SKILL.md"), 256 * 1024)) === entry.sha256 ? "installed" : "modified"; }
+ catch { return "conflict"; }
}
async function confirm(question, yes) {
@@ -93,11 +103,12 @@ async function installOne(id, { yes, force }) {
async function removeOne(id, { yes }) {
const { entry } = safeEntry(id);
const target = path.join(root, entry.id);
- if (!fs.existsSync(target)) { console.log(`${id}: not installed`); return; }
+ try { fs.lstatSync(target); }
+ catch (error) { if (error?.code === "ENOENT") { console.log(`${id}: not installed`); return; } throw error; }
const marker = path.join(target, ".mso-market.json");
- if (!fs.existsSync(marker)) throw new Error(`${id}: refusing to delete an unmanaged/local skill`);
let managed;
- try { managed = JSON.parse(fs.readFileSync(marker, "utf8")); } catch { throw new Error(`${id}: invalid market marker; refusing removal`); }
+ try { managed = JSON.parse(readRegularFile(marker, 64 * 1024).toString("utf8")); }
+ catch { throw new Error(`${id}: invalid or missing market marker; refusing removal`); }
if (managed.id !== id) throw new Error(`${id}: market marker mismatch; refusing removal`);
if (!(await confirm(`Remove ${id}?`, yes))) throw new Error(`${id}: not removed (pass -y for non-interactive removal)`);
fs.rmSync(target, { recursive: true, force: true });