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.

refactor(security): isolate Convex snapshot staging

Rahman03cd704910e5
diff --git a/lib/infra/convex-cloud-cli-runner.ts b/lib/infra/convex-cloud-cli-runner.ts
index c71d3f26..31918e4b 100644
--- a/lib/infra/convex-cloud-cli-runner.ts
+++ b/lib/infra/convex-cloud-cli-runner.ts
@@ -1,11 +1,10 @@
-import { createHash } from "node:crypto";
import { spawn } from "node:child_process";
-import { constants as fsConstants, promises as fs } from "node:fs";
-import os from "node:os";
+import { promises as fs } from "node:fs";
import path from "node:path";
import { childEnv } from "@/lib/host/child-env";
import { resolveReadable } from "@/lib/host/paths";
import { IntegrationError } from "./identity";
+import { stageConvexSnapshot } from "./convex-snapshot-stage";
export type ConvexCliResult = {
code: number;
@@ -21,7 +20,6 @@ export type RunConvexCli = (
) => Promise<ConvexCliResult>;
const MAX_CLI_OUTPUT = 64 * 1024;
-const MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024 * 1024;
function appendBounded(current: string, chunk: Buffer | string): string {
const text = current + chunk.toString();
@@ -114,95 +112,7 @@ export async function convexSnapshotContext(snapshotPath: unknown) {
});
if (!snapshot.toLowerCase().endsWith(".zip"))
throw new IntegrationError("convex_snapshot_zip_required");
-
- const handle = await fs
- .open(snapshot, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)
- .catch(() => {
- throw new IntegrationError("invalid_snapshot_path");
- });
- let stageDir = "";
- try {
- const stat = await handle.stat();
- if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_SNAPSHOT_BYTES)
- throw new IntegrationError("invalid_snapshot_path");
- if (typeof process.getuid === "function" && stat.uid !== process.getuid())
- throw new IntegrationError("invalid_snapshot_path");
-
- const head = Buffer.alloc(4);
- const first = await handle.read(head, 0, 4, 0);
- if (
- first.bytesRead < 4 ||
- head[0] !== 0x50 ||
- head[1] !== 0x4b ||
- ![0x03, 0x05, 0x07].includes(head[2])
- )
- throw new IntegrationError("convex_snapshot_zip_required");
-
- // Import from a private copy produced from the same already-open descriptor that
- // we validate and hash. This closes the path TOCTOU window: replacing the user
- // path after validation cannot change the bytes later consumed by the Convex CLI.
- stageDir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-convex-snapshot-"));
- await fs.chmod(stageDir, 0o700);
- const stagedSnapshot = path.join(stageDir, "snapshot.zip");
- const staged = await fs.open(
- stagedSnapshot,
- fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY,
- 0o600,
- );
- const hash = createHash("sha256");
- const chunk = Buffer.allocUnsafe(1024 * 1024);
- let offset = 0;
- try {
- while (offset < stat.size) {
- const requested = Math.min(chunk.length, stat.size - offset);
- const { bytesRead } = await handle.read(chunk, 0, requested, offset);
- if (bytesRead <= 0) throw new IntegrationError("invalid_snapshot_path");
- const view = chunk.subarray(0, bytesRead);
- hash.update(view);
- let written = 0;
- while (written < bytesRead) {
- const result = await staged.write(
- view,
- written,
- bytesRead - written,
- offset + written,
- );
- if (result.bytesWritten <= 0)
- throw new IntegrationError("invalid_snapshot_path");
- written += result.bytesWritten;
- }
- offset += bytesRead;
- }
- await staged.sync();
- } finally {
- await staged.close().catch(() => undefined);
- }
-
- const after = await handle.stat();
- if (
- after.dev !== stat.dev ||
- after.ino !== stat.ino ||
- after.size !== stat.size ||
- after.mtimeMs !== stat.mtimeMs ||
- after.ctimeMs !== stat.ctimeMs
- )
- throw new IntegrationError("invalid_snapshot_path");
-
- return {
- snapshot,
- stagedSnapshot,
- size: stat.size,
- sha256: hash.digest("hex"),
- cleanup: async () => {
- await fs.rm(stageDir, { recursive: true, force: true });
- },
- };
- } catch (error) {
- if (stageDir) await fs.rm(stageDir, { recursive: true, force: true });
- throw error;
- } finally {
- await handle.close().catch(() => undefined);
- }
+ return { snapshot, ...(await stageConvexSnapshot(snapshot)) };
}
export function convexCliEnv(deployKey: string): Record<string, string> {
diff --git a/lib/infra/convex-cloud-runner.test.ts b/lib/infra/convex-cloud-runner.test.ts
index 5e4c47a8..8f705c69 100644
--- a/lib/infra/convex-cloud-runner.test.ts
+++ b/lib/infra/convex-cloud-runner.test.ts
@@ -2,8 +2,7 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
-const PAT = "pat_synthetic_12345678901234567890";
-const DEPLOY_KEY = "prod:happy-otter-123|synthetic_deploy_key_1234567890abcdef";
+const PAT = "pat_synthetic_12345678901234567890", DEPLOY_KEY = "prod:happy-otter-123|synthetic_deploy_key_1234567890abcdef";
let root: string;
let project: string;
let snapshot: string;
@@ -165,8 +164,7 @@ it("imports only with explicit mode and a data-scoped ephemeral key", async () =
imported: true, mode: "replace-all", snapshot: { bytes: 22, path: snapshot },
});
expect(result.snapshot.sha256).toMatch(/^[a-f0-9]{64}$/); expect(deleted).toBe(true);
- await expect(fs.stat(stagedSnapshot)).rejects.toMatchObject({ code: "ENOENT" });
- expect(JSON.stringify(result)).not.toContain(DEPLOY_KEY);
+ await expect(fs.stat(stagedSnapshot)).rejects.toMatchObject({ code: "ENOENT" }); expect(JSON.stringify(result)).not.toContain(DEPLOY_KEY);
});
it("revokes the ephemeral key when the CLI operation fails", async () => {
const withSelection = await seeded();
diff --git a/lib/infra/convex-snapshot-stage.ts b/lib/infra/convex-snapshot-stage.ts
new file mode 100644
index 00000000..737faaa6
--- /dev/null
+++ b/lib/infra/convex-snapshot-stage.ts
@@ -0,0 +1,97 @@
+import { createHash } from "node:crypto";
+import { constants as fsConstants, promises as fs } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { IntegrationError } from "./identity";
+
+const MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024 * 1024;
+const COPY_CHUNK_BYTES = 1024 * 1024;
+
+export async function stageConvexSnapshot(snapshot: string) {
+ const handle = await fs
+ .open(snapshot, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW)
+ .catch(() => {
+ throw new IntegrationError("invalid_snapshot_path");
+ });
+ let stageDir = "";
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_SNAPSHOT_BYTES)
+ throw new IntegrationError("invalid_snapshot_path");
+ if (typeof process.getuid === "function" && stat.uid !== process.getuid())
+ throw new IntegrationError("invalid_snapshot_path");
+
+ const head = Buffer.alloc(4);
+ const first = await handle.read(head, 0, 4, 0);
+ if (
+ first.bytesRead < 4 ||
+ head[0] !== 0x50 ||
+ head[1] !== 0x4b ||
+ ![0x03, 0x05, 0x07].includes(head[2])
+ )
+ throw new IntegrationError("convex_snapshot_zip_required");
+
+ // The CLI imports a private copy made from the same descriptor checked above.
+ // Replacing the caller-controlled pathname cannot swap the validated bytes.
+ stageDir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-convex-snapshot-"));
+ await fs.chmod(stageDir, 0o700);
+ const stagedSnapshot = path.join(stageDir, "snapshot.zip");
+ const staged = await fs.open(
+ stagedSnapshot,
+ fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY,
+ 0o600,
+ );
+ const hash = createHash("sha256");
+ const chunk = Buffer.allocUnsafe(COPY_CHUNK_BYTES);
+ let offset = 0;
+ try {
+ while (offset < stat.size) {
+ const requested = Math.min(chunk.length, stat.size - offset);
+ const { bytesRead } = await handle.read(chunk, 0, requested, offset);
+ if (bytesRead <= 0) throw new IntegrationError("invalid_snapshot_path");
+ const view = chunk.subarray(0, bytesRead);
+ hash.update(view);
+ let written = 0;
+ while (written < bytesRead) {
+ const { bytesWritten } = await staged.write(
+ view,
+ written,
+ bytesRead - written,
+ offset + written,
+ );
+ if (bytesWritten <= 0)
+ throw new IntegrationError("invalid_snapshot_path");
+ written += bytesWritten;
+ }
+ offset += bytesRead;
+ }
+ await staged.sync();
+ } finally {
+ await staged.close().catch(() => undefined);
+ }
+
+ const after = await handle.stat();
+ if (
+ after.dev !== stat.dev ||
+ after.ino !== stat.ino ||
+ after.size !== stat.size ||
+ after.mtimeMs !== stat.mtimeMs ||
+ after.ctimeMs !== stat.ctimeMs
+ )
+ throw new IntegrationError("invalid_snapshot_path");
+
+ return {
+ stagedSnapshot,
+ size: stat.size,
+ sha256: hash.digest("hex"),
+ cleanup: async () => {
+ await fs.rm(stageDir, { recursive: true, force: true });
+ },
+ };
+ } catch (error) {
+ if (stageDir) await fs.rm(stageDir, { recursive: true, force: true });
+ throw error;
+ } finally {
+ await handle.close().catch(() => undefined);
+ }
+}