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: harden security state and credential guards

Rahmanc820d4d20f0b
diff --git a/app/mcp/route.ts b/app/mcp/route.ts
index 4ba4772b..1009d6f2 100644
--- a/app/mcp/route.ts
+++ b/app/mcp/route.ts
@@ -2,7 +2,7 @@ import { dispatch, isNotification, rpcError, UNAUTHORIZED, RATE_LIMITED } from "
import { validateToken, touchToken } from "@/lib/mcp/store";
import { mcpEnabled } from "@/lib/mcp/scope";
import { publicOrigin, clientIp } from "@/lib/mcp/origin";
-import { rateLimited } from "@/lib/host";
+import { rateLimited, rateLimitedUntrusted } from "@/lib/host";
import { TOOLS } from "@/lib/mcp/tools";
import { toolsetInfo } from "@/lib/mcp/toolset";
@@ -26,7 +26,7 @@ export async function POST(req: Request) {
if (!mcpEnabled()) return new Response("Not Found", { status: 404 });
// Pre-auth flood guard: an invalid token still costs a sha256 + a file read.
- if (rateLimited(`mcp:ip:${clientIp(req)}`, PREAUTH_PER_MIN, 60_000)) {
+ if (rateLimitedUntrusted(`mcp:ip:${clientIp(req)}`, PREAUTH_PER_MIN, 60_000)) {
return Response.json(rpcError(null, RATE_LIMITED, "rate limited"), { status: 429, headers: { "Retry-After": "60" } });
}
diff --git a/app/oauth/register/route.ts b/app/oauth/register/route.ts
index 036f99a5..5dfbd5c2 100644
--- a/app/oauth/register/route.ts
+++ b/app/oauth/register/route.ts
@@ -2,7 +2,7 @@ import { registerClient } from "@/lib/mcp/store";
import { isAllowedRedirect } from "@/lib/mcp/pkce";
import { mcpEnabled } from "@/lib/mcp/scope";
import { clientIp } from "@/lib/mcp/origin";
-import { rateLimited } from "@/lib/host";
+import { rateLimitedUntrusted } from "@/lib/host";
// RFC 7591 Dynamic Client Registration. Open by design and safe to be: a
// registered client is INERT until the owner approves it on the consent page and
@@ -15,7 +15,7 @@ const bad = (error: string, description: string, status = 400) =>
export async function POST(req: Request) {
if (!mcpEnabled()) return new Response("Not Found", { status: 404 });
- if (rateLimited(`mcp:dcr:${clientIp(req)}`, 10, 3_600_000)) {
+ if (rateLimitedUntrusted(`mcp:dcr:${clientIp(req)}`, 10, 3_600_000)) {
return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "3600" } });
}
diff --git a/app/oauth/token/route.ts b/app/oauth/token/route.ts
index 2b95f7d4..e309295b 100644
--- a/app/oauth/token/route.ts
+++ b/app/oauth/token/route.ts
@@ -2,7 +2,7 @@ import { consumeCode, storeToken, TOKEN_TTL_MS } from "@/lib/mcp/store";
import { verifyPkce, randomToken } from "@/lib/mcp/pkce";
import { mcpEnabled } from "@/lib/mcp/scope";
import { clientIp } from "@/lib/mcp/origin";
-import { rateLimited } from "@/lib/host";
+import { rateLimitedUntrusted } from "@/lib/host";
// OAuth token endpoint. authorization_code only, PKCE mandatory.
export const runtime = "nodejs";
@@ -13,7 +13,7 @@ const json = (body: unknown, status: number) =>
export async function POST(req: Request) {
if (!mcpEnabled()) return new Response("Not Found", { status: 404 });
- if (rateLimited(`mcp:token:${clientIp(req)}`, 30, 60_000)) {
+ if (rateLimitedUntrusted(`mcp:token:${clientIp(req)}`, 30, 60_000)) {
return Response.json({ error: "rate_limited" }, { status: 429, headers: { "Retry-After": "60" } });
}
diff --git a/bin/mso.test.ts b/bin/mso.test.ts
index 2932fb79..cf899abe 100644
--- a/bin/mso.test.ts
+++ b/bin/mso.test.ts
@@ -155,6 +155,23 @@ describe("bin/mso", () => {
expect(JSON.parse(fs.readFileSync(store, "utf8")).approved).toEqual({});
});
+ it("fails closed instead of replacing a corrupt device allowlist", () => {
+ const fs = require("node:fs") as typeof import("node:fs");
+ const os = require("node:os") as typeof import("node:os");
+ const store = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "mso-dev-")), "devices.json");
+ const corrupt = "{ this is not valid json";
+ fs.writeFileSync(store, corrupt);
+ const id = "e".repeat(32);
+
+ expect(() =>
+ execFileSync(CLI, ["device", "approve", id, "test"], {
+ encoding: "utf8",
+ env: { ...process.env, MSO_ENV: "/dev/null", OS_DEVICE_STORE: store },
+ }),
+ ).toThrow();
+ expect(fs.readFileSync(store, "utf8")).toBe(corrupt);
+ });
+
it("prints a paste-ready command under every device, quoted safely", () => {
const fs = require("node:fs") as typeof import("node:fs");
const os = require("node:os") as typeof import("node:os");
diff --git a/docs/AUDIT-2026-08-24.md b/docs/AUDIT-2026-08-24.md
new file mode 100644
index 00000000..2a2c0c2f
--- /dev/null
+++ b/docs/AUDIT-2026-08-24.md
@@ -0,0 +1,167 @@
+# MSO Security Audit — 2026-08-24
+
+> **Point-in-time evidence, not a standing implementation contract.** This audit targets
+> `main` at `0402234d7a9da7e1fd0db601ff29e855401c09c5` and records the remediation prepared
+> from that snapshot. Current behavior is authoritative in code, `SECURITY.md`, and the
+> live descriptors.
+
+## Executive result
+
+**Release gate after remediation: PASS.** The audit found **0 Critical / 0 High**, three
+confirmed vulnerability classes (**2 Medium, 1 Low**) and several hardening observations.
+All three confirmed classes were reproduced against the audited snapshot, fixed, and pinned
+by regression tests before release.
+
+The highest-value negative result is also explicit: no auth bypass, unauthenticated host
+access, OAuth/MCP scope bypass, filesystem-root escape, managed-app origin break, or SSRF
+was confirmed in this pass.
+
+## Method
+
+The review used two independent lanes and required reproducible evidence before a candidate
+could block release:
+
+1. **Claude Fable 5 + Ultracode**, read-only against the unchanged snapshot. The workflow
+ actually fan-out to **8 workstreams / 27 sub-agents**: seven domain finders plus twenty
+ adversarial verifiers whose job was to disprove candidate findings. Fable reported 20
+ candidates: 2 confirmed, 15 downgraded, 3 rejected.
+2. **Manual + dynamic verification** against the same checkout: security-relevant Vitest
+ selection, dependency audit, route/auth inventory, source review of trust boundaries,
+ unauthenticated loopback HTTP probes against the running service, and purpose-built race
+ / state-churn reproducers.
+
+The review covered authentication/session/device approval, OAuth 2.1 + PKCE, MCP bearer
+scope and token lifecycle, filesystem/zip/upload boundaries, command/PTY execution,
+managed-app proxy/origin/CSP, Camoufox exposure, server input/CSRF/XSS/SSRF boundaries,
+installer/supply-chain posture, secrets/logging/audit state, skills/project discovery, and
+security-state concurrency.
+
+No real credentials were used in test fixtures and no secret values are recorded here.
+
+## Confirmed findings
+
+### SEC-2026-08-24-01 — MEDIUM — nested private-key denylist / recursive ZIP escape
+
+**Affected:** `lib/host/paths.ts`, `lib/host/fs-zip.ts`.
+
+The loose SSH key names `id_rsa`, `id_ed25519`, `id_ecdsa`, and `id_dsa` were represented as
+fixed `$HOME/<name>` entries. A same-named key deeper in an otherwise readable root, e.g.
+`~/projects/app/id_rsa`, therefore passed the per-path credential gate. Recursive ZIP also
+validated only the selected top-level entry before invoking `zip -r`; its forced excludes
+covered fixed sensitive locations but not basename-anywhere `id_*` or `*.pem` descendants.
+A read-scope MCP bearer uses the same host reader, so this weakened the intended
+credential-defense boundary even without write/exec scope.
+
+**Pre-fix proof with dummy fixtures:** nested `id_rsa` resolved as readable and appeared in
+the ZIP central directory. No private key material was used.
+
+**Remediation:** classify private-key basenames anywhere in a legal root, retain the
+existing `OS_FS_ALLOW_SENSITIVE=1` behavior for `id_*`, retain the existing hard block for
+`*.pem`, and force matching exclusions into recursive ZIP.
+
+**Post-fix proof:** nested `id_rsa` and `deploy.pem` are both blocked by `resolveReadable`;
+both are absent from a recursive archive while `readme.txt` remains present.
+
+### SEC-2026-08-24-02 — MEDIUM — security-state lost-update races weaken kill switches
+
+**Affected:** `lib/mcp/store.ts`, `lib/auth/device-store.ts`, `scripts/approve-device.js`.
+
+The MCP and device allowlist stores used atomic `tmp -> rename` writes, but each mutation
+was a multi-step **read → modify → write** transaction with no transaction serialization.
+Atomic rename prevents a torn individual write; it does not stop two callers from reading
+the same stale state and later overwriting each other's security decision. The shared temp
+filename also caused write collisions. The local device CLI is a separate process, so an
+in-process promise queue alone would not be sufficient.
+
+Dynamic stress on the audited snapshot confirmed all relevant failure modes:
+
+| Reproducer | Pre-fix result |
+|---|---:|
+| 200 OAuth-code double-consume races | 4 runs returned the same single-use code to both consumers; 196 write races |
+| 200 pairs of concurrent MCP token mints | token state lost in 200/200 iterations; 199 write races |
+| 300 MCP revoke-vs-touch races | 125 cases where revoke returned success but the token still validated |
+| 300 device revoke-vs-login-touch races | 42 cases ended with the device approved |
+
+That evidence is why the release classification here is **Medium** even though the Fable
+synthesis downgraded the races to Low/hardening based on timing and credential
+preconditions. A revocation control that reports success but can be overwritten by a live
+request is a kill-switch integrity defect.
+
+**Remediation:** serialize each in-process security-store transaction, use per-process temp
+files, add a fail-closed cross-process lock for security state, make the operator device CLI
+participate in the same lock protocol, and make corrupt CLI store reads fail closed rather
+than treating corruption as an empty allowlist.
+
+**Post-fix stress:** 100 OAuth-code race sets had exactly one consumer; 100 token-mint race
+sets lost no rows; 100 token revoke/touch sets had zero resurrection; 200 cross-process CLI
+revoke vs server-touch iterations had zero re-approval; no operation errors were observed.
+Focused concurrency tests are now permanent.
+
+### SEC-2026-08-24-03 — LOW — shared rate-limit table overflow reset live privileged buckets
+
+**Affected:** `lib/host/rate-limit.ts`.
+
+The shared fixed-window limiter pruned expired buckets when its Map exceeded 4,096 keys,
+then called `buckets.clear()` if the table remained large. Pre-auth MCP IP keys and
+privileged/authenticated MCP + host-action keys share this Map. Sufficient attacker-chosen
+key churn could therefore erase an already-blocked token/action bucket. This is not an
+authorization bypass by itself, but it weakens a defense used around exec-capable surfaces.
+
+**Pre-fix proof:** a `max=1` victim was blocked; after 4,100 unique churn keys the same victim
+was allowed again.
+
+**Remediation:** split public/pre-auth IP buckets from authenticated/privileged buckets.
+Each pool is independently bounded and uses cold-key eviction after pruning expired rows.
+Unauthenticated key churn therefore cannot reset/evict a token or owner-action decision,
+and table pressure does not become a global 429 for new privileged actors.
+
+**Post-fix proof:** after >4,200 public churn keys, the privileged victim remains blocked
+while fresh public keys still enter their own bounded pool. Regression tests pin both the
+isolation and bounded-eviction behavior.
+
+## Controls independently verified
+
+- Session cookies are HttpOnly, Secure and SameSite=Strict; HMAC verification is length-safe
+ and device approval is rechecked.
+- Correct password on an unapproved device creates pending state but no session.
+- Mutating `/api` traffic is protected by the same-origin/Fetch-Metadata gate; unauthenticated
+ filesystem/device/MCP-token routes returned 401 and forged-origin exec calls returned 403
+ in loopback probes.
+- OAuth uses authorization-code + PKCE S256, binds code/client/redirect/challenge and MCP
+ tool scope is filtered in discovery **and** rechecked at call time.
+- Filesystem reads/writes realpath before bounds checks; upload/ZIP guards reject traversal
+ and ZIP stores symlinks as links instead of following targets.
+- Managed-app upstreams are loopback-only; the split-origin proxy strips ambient
+ authorization, constrains redirects/headers and intersects upstream CSP.
+- No runtime `eval()` / `new Function()` sink or `shell: true` child-process path was found.
+- The dependency audit was clean at high/critical and returned no advisory records in the
+ subsequent JSON check.
+- API inventory found 57 route modules: 53 with direct session verification; the remaining
+ login, logout, health and service-worker routes are intentionally public surfaces.
+
+## Rejected / non-blocking candidates
+
+The adversarial Fable lane rejected or downgraded candidates involving `/api/skills`
+untrusted content, managed-app CSP external exfiltration, custom-provider DNS rebinding,
+MCP max-scope reclamping, X-Forwarded-* trust, backup retention, memory persistence, audit
+registry availability, and untrusted-skill descriptions. Where real assumptions exist,
+they match documented owner-operated/deployment boundaries rather than a newly demonstrated
+release-blocking exploit.
+
+Two operational risks remain intentional and should stay visible rather than be mislabeled
+as bugs: exec/PTY is full owner-level host power after its authorization boundary, and some
+operator-initiated installers ultimately trust remote package/vendor infrastructure. Those
+are supply-chain / operator-trust decisions, not an unauthenticated MSO RCE found by this
+audit.
+
+## Tests added by this audit
+
+- OAuth single-use code under concurrent consumption.
+- Concurrent MCP token persistence and revoke-vs-touch kill-switch integrity.
+- Device revoke-vs-touch integrity plus CLI corrupt-store fail-closed behavior.
+- Cross-process device-store locking exercised dynamically against CLI + server module.
+- Nested `id_*` / `*.pem` credential classification and recursive ZIP exclusion.
+- Shared limiter overflow/churn cannot reset an established blocked bucket.
+
+The final release gate is `bun run verify` plus post-ship service/HTTP checks. This document
+must not be used as evidence that a future commit is secure without rerunning those gates.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 67b027d2..02468a28 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -4,6 +4,12 @@
Newest first. `docs/PROGRESS.md` is the source of truth for *why* a change was made;
this is the *what*, and it is what Settings → About shows as “What's new”.
+## 2026-08-24
+
+**Fixed**
+
+- harden security state and credential guards
+
## 2026-08-23
**Added**
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 0a8e3bc9..a53f4104 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -9,6 +9,30 @@ Running log of what shipped each phase. Newest at top.
> [`docs/README.md`](./README.md) and [`docs/ARCHITECTURE.md`](./ARCHITECTURE.md); keep old
> entries intact as historical evidence even when their commands/counts have been superseded.
+## 2026-08-24 — Fable/Ultracode security audit + security-state hardening (DONE)
+
+A point-in-time security audit combined Claude Fable 5 in Ultracode mode with an independent
+dynamic/manual lane. Fable actually fan-out to 8 workstreams / 27 sub-agents (7 domain finders
+plus 20 adversarial verifiers), while the second lane ran the security-relevant tests, route/auth
+inventory, dependency audit, trust-boundary review, unauthenticated live probes and targeted race
+reproducers. Full evidence and rejected candidates are in `AUDIT-2026-08-24.md`.
+
+Three vulnerability classes survived verification. A nested deploy key named `id_rsa` was not
+covered by the fixed `$HOME` credential denylist, and recursive ZIP could carry nested `id_*` /
+`*.pem`; both are now basename-aware / force-excluded. More importantly, MCP OAuth/token and
+device-approval JSON stores used atomic rename without serializing the enclosing read-modify-write
+transaction. Stress proved single-use OAuth codes could be consumed twice, concurrent mints could
+lose state, and successful token/device revocations could be overwritten by a simultaneous usage
+touch. Security-store mutations now serialize in process and use one fail-closed cross-process
+lock protocol shared with the operator device CLI; corrupt CLI store reads also fail closed. The
+shared limiter no longer lets attacker-controlled pre-auth IP churn share eviction state with
+authenticated token/owner-action buckets; public and privileged pools are separately bounded.
+
+Permanent regressions pin concurrency, kill-switch integrity, nested private-key classification,
+ZIP filtering, corrupt-store handling and limiter churn. Pre/post stress evidence is kept in the
+audit rather than this running log. Release verification and live post-ship probes are required
+before this entry is considered shipped.
+
## 2026-08-24 — one-line install now ends in terminal onboarding + reviewed skill market (DONE)
The one-line installer previously did the build/service work but stopped at a block of
diff --git a/docs/README.md b/docs/README.md
index d0c4ceab..a2166f02 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -53,6 +53,7 @@ source comments. They are **not current implementation contracts**.
| Document | Status |
|---|---|
+| [`AUDIT-2026-08-24.md`](./AUDIT-2026-08-24.md) | Fable/Ultracode + dynamic security audit at its named commit; includes reproduced findings and release remediation |
| [`AUDIT-2026-06-11.md`](./AUDIT-2026-06-11.md) | Archived audit at its named date; later fixes changed many findings |
| [`SHELL-FIDELITY-PLAN.md`](./SHELL-FIDELITY-PLAN.md) | Historical design backlog/baseline; current shell design lives in code + architecture |
| [`DRAWER-MENU-BYOK-PLAN.md`](./DRAWER-MENU-BYOK-PLAN.md) | Historical implementation plan; phases A–C and OpenAI Codex D1 shipped; remaining ideas are not promises |
diff --git a/lib/auth/device-store.test.ts b/lib/auth/device-store.test.ts
index aface498..d264ee8e 100644
--- a/lib/auth/device-store.test.ts
+++ b/lib/auth/device-store.test.ts
@@ -66,6 +66,16 @@ describe("device-store — an unreadable file must never look like an empty one"
await expect(isApproved(OTHER)).resolves.toBe(false);
});
+ it("keeps a device revoked when login touches race the kill switch", async () => {
+ const { approveDevice, revokeDevice, touchApproved, isApproved } = await load();
+ await approveDevice(DEV, "my laptop");
+ await Promise.all([
+ ...Array.from({ length: 16 }, () => touchApproved(DEV)),
+ revokeDevice(DEV),
+ ]);
+ await expect(isApproved(DEV)).resolves.toBe(false);
+ });
+
it("writes the store 0600 inside a 0700 dir", async () => {
const { approveDevice } = await load();
await approveDevice(DEV, "my laptop");
diff --git a/lib/auth/device-store.ts b/lib/auth/device-store.ts
index 1f5c1293..e1dcc951 100644
--- a/lib/auth/device-store.ts
+++ b/lib/auth/device-store.ts
@@ -1,6 +1,7 @@
import { promises as fs } from "fs";
import os from "os";
import path from "path";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
// Server-side device allowlist, ported from the VPS Control Room. The login
// password is a weak/memorable factor; the strong factor is a 128-bit device
@@ -65,24 +66,37 @@ async function read(): Promise<DeviceStore> {
async function write(store: DeviceStore): Promise<void> {
await fs.mkdir(path.dirname(STORE_PATH), { recursive: true, mode: 0o700 });
- const tmp = `${STORE_PATH}.tmp`;
+ const tmp = `${STORE_PATH}.${process.pid}.tmp`;
await fs.writeFile(tmp, JSON.stringify(store, null, 2), { encoding: "utf8", mode: 0o600 });
await fs.rename(tmp, STORE_PATH);
}
+// Approval/revocation is a security decision, so serialize the entire read-modify-
+// write transaction. A plain atomic rename is not enough: two requests can read the
+// same approved set and a later `touchApproved` can otherwise overwrite a revoke.
+let mutationChain: Promise<unknown> = Promise.resolve();
+function mutate<T>(fn: () => Promise<T>): Promise<T> {
+ const locked = () => withSecurityStoreLock(STORE_PATH, fn);
+ const run = mutationChain.then(locked, locked);
+ mutationChain = run.then(() => undefined, () => undefined);
+ return run;
+}
+
export async function isApproved(deviceId: string): Promise<boolean> {
const store = await read();
return deviceId in store.approved;
}
/** Mark an approved device as just-seen (best effort). */
-export async function touchApproved(deviceId: string): Promise<void> {
- const store = await read();
- const entry = store.approved[deviceId];
- if (!entry) return;
- entry.lastSeen = Date.now();
- delete store.pending[deviceId];
- await write(store);
+export function touchApproved(deviceId: string): Promise<void> {
+ return mutate(async () => {
+ const store = await read();
+ const entry = store.approved[deviceId];
+ if (!entry) return;
+ entry.lastSeen = Date.now();
+ delete store.pending[deviceId];
+ await write(store);
+ });
}
export async function listDevices(): Promise<DeviceStore> {
@@ -90,45 +104,51 @@ export async function listDevices(): Promise<DeviceStore> {
}
/** Approve a device (moves it out of pending). Used by the in-app panel + CLI. */
-export async function approveDevice(deviceId: string, label?: string): Promise<void> {
- const store = await read();
- const pending = store.pending[deviceId];
- store.approved[deviceId] = {
- label: (label && label.slice(0, 80)) || pending?.label || "approved device",
- approvedAt: Date.now(),
- };
- delete store.pending[deviceId];
- await write(store);
+export function approveDevice(deviceId: string, label?: string): Promise<void> {
+ return mutate(async () => {
+ const store = await read();
+ const pending = store.pending[deviceId];
+ store.approved[deviceId] = {
+ label: (label && label.slice(0, 80)) || pending?.label || "approved device",
+ approvedAt: Date.now(),
+ };
+ delete store.pending[deviceId];
+ await write(store);
+ });
}
/** Un-trust a device (and clear any pending record for the same id). */
-export async function revokeDevice(deviceId: string): Promise<void> {
- const store = await read();
- if (!(deviceId in store.approved) && !(deviceId in store.pending)) return;
- delete store.approved[deviceId];
- delete store.pending[deviceId];
- await write(store);
+export function revokeDevice(deviceId: string): Promise<void> {
+ return mutate(async () => {
+ const store = await read();
+ if (!(deviceId in store.approved) && !(deviceId in store.pending)) return;
+ delete store.approved[deviceId];
+ delete store.pending[deviceId];
+ await write(store);
+ });
}
/** Record (or bump) a device that presented the right password but isn't approved. */
-export async function recordPending(deviceId: string, label: string, ip: string): Promise<void> {
- const store = await read();
- const now = Date.now();
- const existing = store.pending[deviceId];
- if (existing) {
- existing.lastSeen = now;
- existing.attempts += 1;
- existing.label = label || existing.label;
- existing.ip = ip;
- } else {
- store.pending[deviceId] = { label, firstSeen: now, lastSeen: now, ip, attempts: 1 };
- }
- const ids = Object.keys(store.pending);
- if (ids.length > MAX_PENDING) {
- ids
- .sort((a, b) => store.pending[a].lastSeen - store.pending[b].lastSeen)
- .slice(0, ids.length - MAX_PENDING)
- .forEach((id) => delete store.pending[id]);
- }
- await write(store);
+export function recordPending(deviceId: string, label: string, ip: string): Promise<void> {
+ return mutate(async () => {
+ const store = await read();
+ const now = Date.now();
+ const existing = store.pending[deviceId];
+ if (existing) {
+ existing.lastSeen = now;
+ existing.attempts += 1;
+ existing.label = label || existing.label;
+ existing.ip = ip;
+ } else {
+ store.pending[deviceId] = { label, firstSeen: now, lastSeen: now, ip, attempts: 1 };
+ }
+ const ids = Object.keys(store.pending);
+ if (ids.length > MAX_PENDING) {
+ ids
+ .sort((a, b) => store.pending[a].lastSeen - store.pending[b].lastSeen)
+ .slice(0, ids.length - MAX_PENDING)
+ .forEach((id) => delete store.pending[id]);
+ }
+ await write(store);
+ });
}
diff --git a/lib/host/fs-zip.test.ts b/lib/host/fs-zip.test.ts
index 2cc697e4..4b3aa6d5 100644
--- a/lib/host/fs-zip.test.ts
+++ b/lib/host/fs-zip.test.ts
@@ -79,6 +79,20 @@ describe("zipStream against the real zip binary", () => {
expect(names).toContain("proj/src.txt");
});
+ it("force-strips nested loose private keys from recursive archives", async () => {
+ const dir = path.join(base, "secrets-fixture");
+ mkdirSync(path.join(dir, "nested"), { recursive: true });
+ writeFileSync(path.join(dir, "nested", "id_rsa"), "dummy-private-key\n");
+ writeFileSync(path.join(dir, "nested", "deploy.pem"), "dummy-pem\n");
+ writeFileSync(path.join(dir, "nested", "id_rsa.pub"), "public-key\n");
+ writeFileSync(path.join(dir, "nested", "readme.txt"), "keep\n");
+ const names = entries(await read(await zipStream(base, ["secrets-fixture"])));
+ expect(names).not.toContain("secrets-fixture/nested/id_rsa");
+ expect(names).not.toContain("secrets-fixture/nested/deploy.pem");
+ expect(names).toContain("secrets-fixture/nested/id_rsa.pub");
+ expect(names).toContain("secrets-fixture/nested/readme.txt");
+ });
+
it("returns the archive when one file is unreadable (zip exit 18)", async () => {
const dir = path.join(base, "partial");
mkdirSync(dir, { recursive: true });
diff --git a/lib/host/fs-zip.ts b/lib/host/fs-zip.ts
index afbdabe4..cb0587be 100644
--- a/lib/host/fs-zip.ts
+++ b/lib/host/fs-zip.ts
@@ -21,7 +21,7 @@ import os from "os";
import path from "path";
import type { Readable } from "stream";
import { HostError } from "./host-error";
-import { appDir, resolveReadable, sensitiveExcludes } from "./paths";
+import { appDir, looseCredentialExcludes, resolveReadable, sensitiveExcludes } from "./paths";
// A selectable item is a single basename in the listed dir — never a path. Reject
// separators/traversal/NUL so a name can't escape `base` (defense-in-depth; the
@@ -70,6 +70,7 @@ export async function zipStream(
}
patterns.push(...appSecretExcludes(real)); // forced credential guard, see above
patterns.push(...sensitiveExcludes(real)); // same, for ~/ credential dirs nested under `base`
+ patterns.push(...looseCredentialExcludes()); // basename-anywhere private keys / *.pem
if (patterns.length) args.push("-x", ...patterns);
// All stdio ignored — zip writes to the temp FILE, not a pipe, so there's no
diff --git a/lib/host/index.ts b/lib/host/index.ts
index a19d2b8f..c7140442 100644
--- a/lib/host/index.ts
+++ b/lib/host/index.ts
@@ -25,6 +25,6 @@ export { audit, readAuditTail } from "./audit";
export { createTempShare, inspectTempShare, consumeTempShare, revokeTempShare, tempShareUrl } from "./temp-share";
export type { TempShareInfo, ConsumedTempShare } from "./temp-share";
export type { AuditAction, AuditEntry, AuditRecord } from "./audit";
-export { rateLimited } from "./rate-limit";
+export { rateLimited, rateLimitedUntrusted } from "./rate-limit";
export { HostError } from "./host-error";
export { apiError, readJson, requireString, optionalString, requireInt, invalidRequest } from "./api-error";
diff --git a/lib/host/paths-credentials.test.ts b/lib/host/paths-credentials.test.ts
index 52f2ff04..1be117c8 100644
--- a/lib/host/paths-credentials.test.ts
+++ b/lib/host/paths-credentials.test.ts
@@ -6,7 +6,9 @@ import {
appSecretCopyFilter,
assertNoAppSecretDescendants,
assertNoSensitiveDescendants,
+ isCredentialPath,
isSensitivePath,
+ looseCredentialExcludes,
sensitiveExcludes,
} from "./paths";
@@ -58,6 +60,15 @@ describe("recursive credential guard", () => {
expect(isSensitivePath(path.join(fakeHome, ".gitconfig"))).toBe(false);
});
+ it("blocks loose private-key basenames anywhere under a legal root", () => {
+ vi.stubEnv("HOME", fakeHome);
+ for (const name of ["id_rsa", "id_ed25519", "id_ecdsa", "id_dsa", "deploy.pem", "DEPLOY.PEM"]) {
+ expect(isCredentialPath(path.join(fakeHome, "safe", "nested", name)), name).toBe(true);
+ }
+ expect(isCredentialPath(path.join(fakeHome, "safe", "nested", "id_rsa.pub"))).toBe(false);
+ expect(looseCredentialExcludes()).toEqual(expect.arrayContaining(["*.pem", "id_rsa", "*/id_rsa"]));
+ });
+
it("excludes a credential dir nested under the zip base", () => {
vi.stubEnv("HOME", fakeHome);
expect(isSensitivePath(parent)).toBe(false); // the exact gap this guard closes
@@ -76,6 +87,9 @@ describe("recursive credential guard", () => {
vi.stubEnv("HOME", fakeHome);
vi.stubEnv("OS_FS_ALLOW_SENSITIVE", "1");
expect(sensitiveExcludes(fakeHome)).toEqual([]);
+ expect(looseCredentialExcludes()).toEqual(["*.pem"]);
+ expect(isCredentialPath(path.join(fakeHome, "safe", "id_rsa"))).toBe(false);
+ expect(isCredentialPath(path.join(fakeHome, "safe", "deploy.pem"))).toBe(true);
expect(() => assertNoSensitiveDescendants(parent)).not.toThrow();
});
});
diff --git a/lib/host/paths.ts b/lib/host/paths.ts
index 1b6d9560..e727ef3f 100644
--- a/lib/host/paths.ts
+++ b/lib/host/paths.ts
@@ -95,10 +95,16 @@ const SENSITIVE_HOME = [
".bashrc", ".bash_profile", ".bash_login", ".bash_aliases", ".profile",
".zshrc", ".zprofile", ".zshenv", ".zlogin", ".kshrc",
".config/fish/config.fish", ".config/fish/conf.d",
- // loose private keys saved outside ~/.ssh (heredoc dumps, exports, etc.)
+ // root-level loose private keys; nested copies are caught by basename below too.
"id_rsa", "id_ed25519", "id_ecdsa", "id_dsa",
];
+// Loose private keys are identified by BASENAME anywhere inside a legal read root.
+// Keeping these in SENSITIVE_HOME only protected ~/id_rsa, while the common deploy-key
+// shape ~/projects/app/id_rsa stayed readable to a session/read-scope MCP bearer.
+const PRIVATE_KEY_BASENAMES = ["id_rsa", "id_ed25519", "id_ecdsa", "id_dsa"] as const;
+const PRIVATE_KEY_NAMES = new Set<string>(PRIVATE_KEY_BASENAMES);
+
export function isSensitivePath(real: string): boolean {
if (process.env.OS_FS_ALLOW_SENSITIVE === "1") return false;
const h = homeDir();
@@ -123,12 +129,25 @@ export function isCredentialPath(real: string): boolean {
if (real === store || isUnderRoot(real, store)) return true;
if (isSensitivePath(real)) return true;
const base = path.basename(real);
- // Private keys land anywhere (heredoc dumps, downloaded service accounts); the
- // extension is the only reliable marker outside the fixed ~/ locations above.
- if (base.endsWith(".pem")) return true;
+ // Private keys land anywhere (heredoc dumps, deploy keys, downloaded service
+ // accounts). Their basename/extension is the reliable marker outside fixed ~/ paths.
+ if (PRIVATE_KEY_NAMES.has(base) && process.env.OS_FS_ALLOW_SENSITIVE !== "1") return true;
+ if (base.toLowerCase().endsWith(".pem")) return true;
return isAppSecret(real);
}
+// `zip -r` validates the selected top-level names, then walks descendants itself.
+// These patterns enforce the same basename-anywhere private-key rule inside that
+// recursive walk. Info-ZIP `*` spans `/`; explicit root forms cover the no-slash case.
+export function looseCredentialExcludes(): string[] {
+ const privateNames = process.env.OS_FS_ALLOW_SENSITIVE === "1"
+ ? []
+ : PRIVATE_KEY_BASENAMES.flatMap((name) => [name, `*/${name}`]);
+ // *.pem has historically been a hard credential boundary, independent of the
+ // SENSITIVE_HOME escape hatch; keep that contract while extending id_* safely.
+ return ["*.pem", ...privateNames];
+}
+
/** The app's own secrets sitting UNDER `realBase` — empty when APP_DIR is not a
* descendant, or holds no secrets. The per-path gate is exact-or-under, so a
* recursive walk starting at a PARENT of APP_DIR never consults it for these. */
diff --git a/lib/host/rate-limit.test.ts b/lib/host/rate-limit.test.ts
index ad24f6cc..adba3973 100644
--- a/lib/host/rate-limit.test.ts
+++ b/lib/host/rate-limit.test.ts
@@ -1,7 +1,7 @@
// Unit tests for the fixed-window in-memory rate limiter (lib/host/rate-limit.ts).
// Uses fake timers to exercise window expiry without sleeping.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { rateLimited } from "./rate-limit";
+import { rateLimited, rateLimitedUntrusted } from "./rate-limit";
describe("rateLimited", () => {
beforeEach(() => {
@@ -60,6 +60,26 @@ describe("rateLimited", () => {
expect(rateLimited(global, 5, 1000)).toBe(false);
});
+ it("isolates attacker-controlled pre-auth churn from privileged buckets", () => {
+ const victim = `privileged-victim-${Math.random()}`;
+ expect(rateLimited(victim, 1, 60_000)).toBe(false);
+ expect(rateLimited(victim, 1, 60_000)).toBe(true);
+
+ // More public keys than the table ceiling. The vulnerable implementation used
+ // one Map and clear()ed it, silently restoring the victim's allowance.
+ for (let i = 0; i < 4200; i++) {
+ expect(rateLimitedUntrusted(`spoofed-ip-${Math.random()}-${i}`, 1, 60_000)).toBe(false);
+ }
+ expect(rateLimited(victim, 1, 60_000)).toBe(true);
+ });
+
+ it("evicts cold pre-auth keys instead of turning table pressure into a global 429", () => {
+ for (let i = 0; i < 4200; i++) {
+ expect(rateLimitedUntrusted(`public-churn-${Math.random()}-${i}`, 1, 60_000)).toBe(false);
+ }
+ expect(rateLimitedUntrusted(`fresh-public-${Math.random()}`, 1, 60_000)).toBe(false);
+ });
+
it("counts the call as a hit only when not blocked", () => {
const key = `count-${Math.random()}`;
rateLimited(key, 2, 1000); // 1
diff --git a/lib/host/rate-limit.ts b/lib/host/rate-limit.ts
index 34b82456..41fd71f3 100644
--- a/lib/host/rate-limit.ts
+++ b/lib/host/rate-limit.ts
@@ -1,24 +1,50 @@
// SERVER-ONLY. Tiny fixed-window in-memory rate limiter. Process-local (resets
// on restart) — enough to blunt a runaway client or a leaked-cookie flood on the
-// privileged endpoints. The login route keeps its own specialised limiter; this
-// one guards /exec/run and friends.
-const buckets = new Map<string, { count: number; resetAt: number }>();
+// privileged endpoints. The login route keeps its own specialised limiter.
+//
+// IMPORTANT: pre-auth/IP keys live in a separate bounded pool. They can be churned
+// by an unauthenticated client (and proxy IP attribution is inherently best-effort),
+// so they must never evict/reset an authenticated MCP token or owner-action bucket.
+type Bucket = { count: number; resetAt: number };
+const privilegedBuckets = new Map<string, Bucket>();
+const untrustedBuckets = new Map<string, Bucket>();
const MAX_KEYS = 4096;
-// Returns true when `key` has exceeded `max` hits inside `windowMs` (caller
-// should then reject with 429). Counts this call as a hit when allowed.
-export function rateLimited(key: string, max: number, windowMs: number): boolean {
+function limit(buckets: Map<string, Bucket>, key: string, max: number, windowMs: number): boolean {
const now = Date.now();
- if (buckets.size > MAX_KEYS) {
- for (const [k, v] of buckets) if (now > v.resetAt) buckets.delete(k);
- if (buckets.size > MAX_KEYS) buckets.clear();
- }
const b = buckets.get(key);
- if (!b || now > b.resetAt) {
- buckets.set(key, { count: 1, resetAt: now + windowMs });
+ if (b && now <= b.resetAt) {
+ // Refresh insertion order so overflow evicts genuinely cold keys, not an active
+ // bucket merely because it happened to be created earlier.
+ buckets.delete(key);
+ buckets.set(key, b);
+ if (b.count >= max) return true;
+ b.count += 1;
return false;
}
- if (b.count >= max) return true;
- b.count += 1;
+ if (b) buckets.delete(key);
+
+ if (buckets.size >= MAX_KEYS) {
+ for (const [k, v] of buckets) if (now > v.resetAt) buckets.delete(k);
+ while (buckets.size >= MAX_KEYS) {
+ const oldest = buckets.keys().next().value as string | undefined;
+ if (!oldest) break;
+ buckets.delete(oldest);
+ }
+ }
+
+ buckets.set(key, { count: 1, resetAt: now + windowMs });
return false;
}
+
+// Authenticated/session/bearer/owner-action limits. Never call this with a raw
+// unauthenticated IP key; use rateLimitedUntrusted for those.
+export function rateLimited(key: string, max: number, windowMs: number): boolean {
+ return limit(privilegedBuckets, key, max, windowMs);
+}
+
+// Public/pre-auth limits. Kept physically separate so spoofed-IP key churn cannot
+// reset or evict a blocked credential/exec bucket in the privileged pool.
+export function rateLimitedUntrusted(key: string, max: number, windowMs: number): boolean {
+ return limit(untrustedBuckets, key, max, windowMs);
+}
diff --git a/lib/mcp/store.test.ts b/lib/mcp/store.test.ts
index a4a5c5bd..04402b1c 100644
--- a/lib/mcp/store.test.ts
+++ b/lib/mcp/store.test.ts
@@ -36,6 +36,12 @@ describe("codes", () => {
expect(await store.consumeCode("old")).toBeNull();
});
+ it("serializes concurrent code exchanges so exactly one caller can consume a code", async () => {
+ await store.storeCode("race-code", rec());
+ const results = await Promise.all(Array.from({ length: 16 }, () => store.consumeCode("race-code")));
+ expect(results.filter(Boolean)).toHaveLength(1);
+ });
+
it("never writes the raw code to disk", async () => {
await store.storeCode("super-secret-code", rec());
const raw = await fs.readFile(process.env.OS_MCP_STORE!, "utf8");
@@ -83,6 +89,28 @@ describe("tokens", () => {
expect((await store.validateToken("ro"))!.scope).toBe("read");
expect((await store.validateToken("rw"))!.scope).toBe("exec");
});
+
+ it("does not lose concurrent token mints", async () => {
+ const tokens = Array.from({ length: 16 }, (_, i) => `parallel-${i}`);
+ await Promise.all(tokens.map((token) => mint(token)));
+ const listed = await store.listTokens();
+ expect(listed).toHaveLength(tokens.length);
+ for (const token of tokens) expect(await store.validateToken(token)).not.toBeNull();
+ });
+
+ it("keeps a token revoked when last-used touches race the kill switch", async () => {
+ await mint("tok-race", "exec");
+ const live = await store.validateToken("tok-race");
+ expect(live).not.toBeNull();
+ const id = (await store.listTokens())[0].id;
+ const operations = [
+ ...Array.from({ length: 16 }, () => store.touchToken(live!.hash)),
+ store.revokeToken(id),
+ ];
+ const results = await Promise.all(operations);
+ expect(results.at(-1)).toBe(true);
+ expect(await store.validateToken("tok-race")).toBeNull();
+ });
});
describe("clients", () => {
diff --git a/lib/mcp/store.ts b/lib/mcp/store.ts
index 4498d1e1..6b63d0d5 100644
--- a/lib/mcp/store.ts
+++ b/lib/mcp/store.ts
@@ -3,6 +3,7 @@ import os from "node:os";
import path from "node:path";
import { sha256hex } from "./pkce";
import type { Scope } from "./scope";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
// OAuth clients, authorization codes and bearer tokens for the MCP server.
// mso has no database, so this is the same shape lib/auth/device-store.ts uses:
@@ -68,11 +69,26 @@ async function read(): Promise<Store> {
async function write(store: Store): Promise<void> {
await fs.mkdir(path.dirname(STORE_PATH), { recursive: true, mode: 0o700 });
- const tmp = `${STORE_PATH}.tmp`;
+ // Per-process temp name prevents an operator-side helper / another server process
+ // from clobbering the exact temp path while this process is committing a write.
+ const tmp = `${STORE_PATH}.${process.pid}.tmp`;
await fs.writeFile(tmp, JSON.stringify(store, null, 2), { encoding: "utf8", mode: 0o600 });
await fs.rename(tmp, STORE_PATH);
}
+// Every credential mutation is a read-modify-write. Atomic rename only makes ONE
+// write indivisible; without serialising the whole transaction, concurrent requests
+// can both read the same old state and then overwrite each other's decisions. That
+// is security-significant here: a token touch must never resurrect a token that a
+// concurrent revoke just killed, and an OAuth code must be consumable exactly once.
+let mutationChain: Promise<unknown> = Promise.resolve();
+function mutate<T>(fn: () => Promise<T>): Promise<T> {
+ const locked = () => withSecurityStoreLock(STORE_PATH, fn);
+ const run = mutationChain.then(locked, locked);
+ mutationChain = run.then(() => undefined, () => undefined);
+ return run;
+}
+
/** Drop expired codes on every write path — they are single-use and short-lived,
* so without this the file grows one dead row per abandoned consent, forever. */
function sweep(store: Store): Store {
@@ -81,34 +97,38 @@ function sweep(store: Store): Store {
return store;
}
-export async function registerClient(name: string, redirectUris: string[]): Promise<string> {
- const store = sweep(await read());
- // Re-registering the same redirect set returns the existing id instead of
+export function registerClient(name: string, redirectUris: string[]): Promise<string> {
+ return mutate(async () => {
+ const store = sweep(await read());
+ // Re-registering the same redirect set returns the existing id instead of
// minting a new one — mcp-remote and Cursor re-register on every launch.
- const key = [...redirectUris].sort().join(" ");
- for (const [id, c] of Object.entries(store.clients)) {
- if ([...c.redirectUris].sort().join(" ") === key) return id;
- }
- const ids = Object.keys(store.clients);
- if (ids.length >= MAX_CLIENTS) {
- ids.sort((a, b) => store.clients[a].createdAt - store.clients[b].createdAt)
- .slice(0, ids.length - MAX_CLIENTS + 1)
- .forEach((id) => delete store.clients[id]);
- }
- const clientId = "mcpc_" + sha256hex(key + Date.now()).slice(0, 24);
- store.clients[clientId] = { name: name.slice(0, 80) || "MCP Client", redirectUris, createdAt: Date.now() };
- await write(store);
- return clientId;
+ const key = [...redirectUris].sort().join(" ");
+ for (const [id, c] of Object.entries(store.clients)) {
+ if ([...c.redirectUris].sort().join(" ") === key) return id;
+ }
+ const ids = Object.keys(store.clients);
+ if (ids.length >= MAX_CLIENTS) {
+ ids.sort((a, b) => store.clients[a].createdAt - store.clients[b].createdAt)
+ .slice(0, ids.length - MAX_CLIENTS + 1)
+ .forEach((id) => delete store.clients[id]);
+ }
+ const clientId = "mcpc_" + sha256hex(key + Date.now()).slice(0, 24);
+ store.clients[clientId] = { name: name.slice(0, 80) || "MCP Client", redirectUris, createdAt: Date.now() };
+ await write(store);
+ return clientId;
+ });
}
export async function getClient(clientId: string): Promise<McpClient | null> {
return (await read()).clients[clientId] ?? null;
}
-export async function storeCode(code: string, rec: McpCode): Promise<void> {
- const store = sweep(await read());
- store.codes[sha256hex(code)] = rec;
- await write(store);
+export function storeCode(code: string, rec: McpCode): Promise<void> {
+ return mutate(async () => {
+ const store = sweep(await read());
+ store.codes[sha256hex(code)] = rec;
+ await write(store);
+ });
}
/**
@@ -116,21 +136,25 @@ export async function storeCode(code: string, rec: McpCode): Promise<void> {
* replayed code finds nothing and gets `invalid_grant` — and the table does not
* grow a dead "consumed" row per successful login.
*/
-export async function consumeCode(code: string): Promise<McpCode | null> {
- const store = sweep(await read());
- const hash = sha256hex(code);
- const rec = store.codes[hash];
- if (!rec || rec.expiresAt < Date.now()) return null;
- delete store.codes[hash];
- await write(store);
- return rec;
-}
-
-export async function storeToken(token: string, rec: Omit<McpToken, "createdAt" | "expiresAt">): Promise<void> {
- const store = sweep(await read());
- const now = Date.now();
- store.tokens[sha256hex(token)] = { ...rec, createdAt: now, expiresAt: now + TOKEN_TTL_MS };
- await write(store);
+export function consumeCode(code: string): Promise<McpCode | null> {
+ return mutate(async () => {
+ const store = sweep(await read());
+ const hash = sha256hex(code);
+ const rec = store.codes[hash];
+ if (!rec || rec.expiresAt < Date.now()) return null;
+ delete store.codes[hash];
+ await write(store);
+ return rec;
+ });
+}
+
+export function storeToken(token: string, rec: Omit<McpToken, "createdAt" | "expiresAt">): Promise<void> {
+ return mutate(async () => {
+ const store = sweep(await read());
+ const now = Date.now();
+ store.tokens[sha256hex(token)] = { ...rec, createdAt: now, expiresAt: now + TOKEN_TTL_MS };
+ await write(store);
+ });
}
/** Returns the live token record, or null for unknown / revoked / expired. Both
@@ -145,12 +169,14 @@ export async function validateToken(token: string): Promise<(McpToken & { hash:
return { ...rec, hash };
}
-export async function touchToken(hash: string): Promise<void> {
- const store = await read();
- const rec = store.tokens[hash];
- if (!rec) return;
- rec.lastUsedAt = Date.now();
- await write(store);
+export function touchToken(hash: string): Promise<void> {
+ return mutate(async () => {
+ const store = await read();
+ const rec = store.tokens[hash];
+ if (!rec) return;
+ rec.lastUsedAt = Date.now();
+ await write(store);
+ });
}
export interface TokenView extends McpToken {
@@ -174,20 +200,24 @@ export async function listTokens(): Promise<TokenView[]> {
.sort((a, b) => b.createdAt - a.createdAt);
}
-export async function revokeToken(id: string): Promise<boolean> {
- const store = await read();
- const hit = Object.keys(store.tokens).find((h) => h.startsWith(id));
- if (!hit || store.tokens[hit].revokedAt) return false;
- store.tokens[hit].revokedAt = Date.now();
- await write(store);
- return true;
+export function revokeToken(id: string): Promise<boolean> {
+ return mutate(async () => {
+ const store = await read();
+ const hit = Object.keys(store.tokens).find((h) => h.startsWith(id));
+ if (!hit || store.tokens[hit].revokedAt) return false;
+ store.tokens[hit].revokedAt = Date.now();
+ await write(store);
+ return true;
+ });
}
/** Panic button — kills every live bearer at once. */
-export async function revokeAllTokens(): Promise<number> {
- const store = await read();
- let n = 0;
- for (const t of Object.values(store.tokens)) if (!t.revokedAt) { t.revokedAt = Date.now(); n++; }
- if (n) await write(store);
- return n;
+export function revokeAllTokens(): Promise<number> {
+ return mutate(async () => {
+ const store = await read();
+ let n = 0;
+ for (const t of Object.values(store.tokens)) if (!t.revokedAt) { t.revokedAt = Date.now(); n++; }
+ if (n) await write(store);
+ return n;
+ });
}
diff --git a/lib/security-store-lock.ts b/lib/security-store-lock.ts
new file mode 100644
index 00000000..adae6bbe
--- /dev/null
+++ b/lib/security-store-lock.ts
@@ -0,0 +1,84 @@
+import { randomUUID } from "node:crypto";
+import { promises as fs } from "node:fs";
+import type { FileHandle } from "node:fs/promises";
+import path from "node:path";
+
+// Cross-process lock for the tiny JSON files that carry security decisions.
+// Atomic rename protects one write, but not a whole read-modify-write transaction.
+// The web process also serializes in-process callers; this lock covers supported
+// operator-side helpers (notably `mso device ...`) that edit the same store.
+const WAIT_MS = 25;
+const BUSY_TIMEOUT_MS = 3_000;
+const STALE_MS = 30_000;
+
+const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+
+interface HeldLock {
+ handle: FileHandle;
+ token: string;
+}
+
+function pidIsGone(pid: number): boolean {
+ try {
+ process.kill(pid, 0);
+ return false;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException).code === "ESRCH";
+ }
+}
+
+async function abandoned(lockPath: string): 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 > STALE_MS;
+}
+
+async function acquire(lockPath: string): Promise<HeldLock> {
+ await fs.mkdir(path.dirname(lockPath), { recursive: true, mode: 0o700 });
+ const token = `${process.pid}:${randomUUID()}`;
+ const deadline = Date.now() + BUSY_TIMEOUT_MS;
+ while (true) {
+ try {
+ const handle = await fs.open(lockPath, "wx", 0o600);
+ try {
+ await handle.writeFile(token, "utf8");
+ } catch (error) {
+ await handle.close().catch(() => undefined);
+ await fs.unlink(lockPath).catch(() => undefined);
+ throw error;
+ }
+ return { handle, token };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
+ if (await abandoned(lockPath)) {
+ await fs.unlink(lockPath).catch(() => undefined);
+ continue;
+ }
+ if (Date.now() >= deadline) throw new Error("security store is busy; retry the operation");
+ await sleep(WAIT_MS);
+ }
+ }
+}
+
+async function release(lockPath: string, held: HeldLock): Promise<void> {
+ await held.handle.close().catch(() => undefined);
+ const owner = await fs.readFile(lockPath, "utf8").catch(() => "");
+ // Never remove a lock that a stale-lock recovery may have handed to another process.
+ if (owner === held.token) await fs.unlink(lockPath).catch(() => undefined);
+}
+
+export async function withSecurityStoreLock<T>(storePath: string, fn: () => Promise<T>): Promise<T> {
+ const lockPath = `${storePath}.lock`;
+ const held = await acquire(lockPath);
+ try {
+ return await fn();
+ } finally {
+ await release(lockPath, held);
+ }
+}
diff --git a/scripts/approve-device.js b/scripts/approve-device.js
index 45a5fd22..2ac574b8 100644
--- a/scripts/approve-device.js
+++ b/scripts/approve-device.js
@@ -12,6 +12,7 @@
const fs = require("fs");
const os = require("os");
const path = require("path");
+const { randomUUID } = require("crypto");
const STORE =
process.env.OS_DEVICE_STORE || path.join(os.homedir(), ".mso", "auth-devices.json");
@@ -21,16 +22,73 @@ function read() {
try {
const p = JSON.parse(fs.readFileSync(STORE, "utf8"));
return { approved: p.approved || {}, pending: p.pending || {} };
- } catch {
- return { approved: {}, pending: {} };
+ } catch (error) {
+ if (error && error.code === "ENOENT") return { approved: {}, pending: {} };
+ throw error;
}
}
function write(store) {
- fs.mkdirSync(path.dirname(STORE), { recursive: true });
- const tmp = `${STORE}.tmp`;
+ fs.mkdirSync(path.dirname(STORE), { recursive: true, mode: 0o700 });
+ const tmp = `${STORE}.${process.pid}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(store, null, 2), { mode: 0o600 });
fs.renameSync(tmp, STORE);
}
+
+// The web process edits the same allowlist. Lock the full read-modify-write so a
+// local revoke cannot be overwritten by a concurrent login `lastSeen` touch. The
+// lock owner is recorded so a crashed helper/server is recoverable without turning
+// a stale file into a permanent authentication outage.
+const LOCK = `${STORE}.lock`;
+const LOCK_WAIT_MS = 25;
+const LOCK_TIMEOUT_MS = 3000;
+const LOCK_STALE_MS = 30000;
+const sleeper = new Int32Array(new SharedArrayBuffer(4));
+function sleep(ms) { Atomics.wait(sleeper, 0, 0, ms); }
+function pidIsGone(pid) {
+ try { process.kill(pid, 0); return false; }
+ catch (error) { return error && error.code === "ESRCH"; }
+}
+function abandonedLock() {
+ try {
+ const st = fs.statSync(LOCK);
+ let owner = "";
+ try { owner = fs.readFileSync(LOCK, "utf8"); } catch {}
+ 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;
+ }
+}
+function acquireLock() {
+ fs.mkdirSync(path.dirname(STORE), { recursive: true, mode: 0o700 });
+ const token = `${process.pid}:${randomUUID()}`;
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
+ while (true) {
+ try {
+ const fd = fs.openSync(LOCK, "wx", 0o600);
+ try { fs.writeFileSync(fd, token, "utf8"); }
+ catch (error) { try { fs.closeSync(fd); } catch {} try { fs.unlinkSync(LOCK); } catch {} throw error; }
+ return { fd, token };
+ } catch (error) {
+ if (!error || error.code !== "EEXIST") throw error;
+ if (abandonedLock()) { try { fs.unlinkSync(LOCK); } catch {} continue; }
+ if (Date.now() >= deadline) throw new Error("security store is busy; retry the operation");
+ sleep(LOCK_WAIT_MS);
+ }
+ }
+}
+function withMutation(fn) {
+ const held = acquireLock();
+ try { return fn(); }
+ finally {
+ try { fs.closeSync(held.fd); } catch {}
+ let owner = "";
+ try { owner = fs.readFileSync(LOCK, "utf8"); } catch {}
+ if (owner === held.token) { try { fs.unlinkSync(LOCK); } catch {} }
+ }
+}
const ts = (t) => (t ? new Date(t).toISOString() : "—");
// Two ways to act on a device: copy the bare id (compose your own command), or
@@ -89,10 +147,15 @@ if (args[0] === "--revoke-all") {
console.error(" mso device approve <deviceId> \"label\"");
process.exit(1);
}
- s.approved = {};
- write(s);
- console.log(`revoked ${ids.length} device(s):`);
- for (const id of ids) console.log(` ${id}`);
+ const revokedIds = withMutation(() => {
+ const current = read();
+ const currentIds = Object.keys(current.approved);
+ current.approved = {};
+ write(current);
+ return currentIds;
+ });
+ console.log(`revoked ${revokedIds.length} device(s):`);
+ for (const id of revokedIds) console.log(` ${id}`);
console.log("\nno device can sign in until you approve one again.");
process.exit(0);
}
@@ -100,16 +163,20 @@ if (args[0] === "--revoke-all") {
if (args[0] === "--revoke") {
const id = args[1];
if (!id) { console.error("usage: --revoke <deviceId>"); process.exit(1); }
- const s = read();
- if (!s.approved[id]) {
+ const result = withMutation(() => {
+ const s = read();
+ if (!s.approved[id]) return null;
+ const label = s.approved[id].label;
+ delete s.approved[id];
+ write(s);
+ return { label, left: Object.keys(s.approved).length };
+ });
+ if (!result) {
console.error(`not approved: ${id}`);
if (id === "all") console.error("to revoke every device: mso device revoke all --yes");
process.exit(1);
}
- const label = s.approved[id].label;
- delete s.approved[id];
- write(s);
- const left = Object.keys(s.approved).length;
+ const { label, left } = result;
// Say what is left, so the obvious follow-up (`device list`) isn't needed — and
// so revoking your last device is impossible to do without noticing.
console.log(`revoked ${id} "${label}"`);
@@ -124,13 +191,16 @@ if (!id || !DEVICE_ID_RE.test(id)) {
console.error("deviceId must be 16-128 hex/uuid chars");
process.exit(1);
}
-const store = read();
-const pending = store.pending[id];
-store.approved[id] = {
- label: label !== "seeded device" ? label : (pending && pending.label) || label,
- approvedAt: Date.now(),
-};
-delete store.pending[id];
-write(store);
-console.log(`approved ${id} "${store.approved[id].label}"`);
+const approvedLabel = withMutation(() => {
+ const store = read();
+ const pending = store.pending[id];
+ store.approved[id] = {
+ label: label !== "seeded device" ? label : (pending && pending.label) || label,
+ approvedAt: Date.now(),
+ };
+ delete store.pending[id];
+ write(store);
+ return store.approved[id].label;
+});
+console.log(`approved ${id} "${approvedLabel}"`);
console.log("-> that device can now sign in with the password.");