Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat: add secure temporary screenshot links

Rahman2c0f4b26e833
diff --git a/app/api/v1/temp-share/[id]/route.ts b/app/api/v1/temp-share/[id]/route.ts
new file mode 100644
index 00000000..4c85941a
--- /dev/null
+++ b/app/api/v1/temp-share/[id]/route.ts
@@ -0,0 +1,65 @@
+import { NextResponse } from "next/server";
+import { verifyAuth } from "@/lib/agent/server";
+import { consumeTempShare, inspectTempShare } from "@/lib/host";
+
+export const runtime = "nodejs";
+export const dynamic = "force-dynamic";
+
+function asciiFilename(name: string): string {
+ const safe = name.replace(/[^A-Za-z0-9._ -]/g, "_").replace(/"/g, "_").slice(0, 120);
+ return safe || "download.bin";
+}
+
+function headers(info: { name: string; mimeType: string; bytes: number; expiresAt: number; downloadsLeft: number }, download: boolean): Headers {
+ const disposition = download ? "attachment" : "inline";
+ const h = new Headers({
+ "content-type": info.mimeType,
+ "content-length": String(info.bytes),
+ "content-disposition": `${disposition}; filename="${asciiFilename(info.name)}"; filename*=UTF-8''${encodeURIComponent(info.name)}`,
+ "cache-control": "private, no-store, no-cache, max-age=0, must-revalidate",
+ pragma: "no-cache",
+ expires: "0",
+ "referrer-policy": "no-referrer",
+ "x-content-type-options": "nosniff",
+ "content-security-policy": "default-src 'none'; sandbox",
+ "cross-origin-resource-policy": "same-origin",
+ "x-temp-link-expires": new Date(info.expiresAt).toISOString(),
+ "x-temp-downloads-left": String(Math.max(info.downloadsLeft, 0)),
+ });
+ return h;
+}
+
+async function authorized(req: Request): Promise<NextResponse | null> {
+ if (await verifyAuth(req)) return null;
+ return NextResponse.json(
+ { error: "unauthorized", detail: "Open MSO and sign in on this approved device, then open the link again." },
+ { status: 401, headers: { "cache-control": "no-store" } },
+ );
+}
+
+export async function HEAD(req: Request, context: { params: Promise<{ id: string }> }) {
+ const denied = await authorized(req);
+ if (denied) return denied;
+ const { id } = await context.params;
+ try {
+ const info = await inspectTempShare(id);
+ return new Response(null, { status: 200, headers: headers(info, new URL(req.url).searchParams.get("download") === "1") });
+ } catch {
+ return new Response("Not Found", { status: 404, headers: { "cache-control": "no-store" } });
+ }
+}
+
+export async function GET(req: Request, context: { params: Promise<{ id: string }> }) {
+ const denied = await authorized(req);
+ if (denied) return denied;
+ const { id } = await context.params;
+ try {
+ const share = await consumeTempShare(id);
+ return new Response(new Uint8Array(share.data), {
+ status: 200,
+ headers: headers(share, new URL(req.url).searchParams.get("download") === "1"),
+ });
+ } catch {
+ return new Response("Not Found", { status: 404, headers: { "cache-control": "no-store" } });
+ }
+}
diff --git a/bin/mso b/bin/mso
index 221aed1a..7dac5396 100755
--- a/bin/mso
+++ b/bin/mso
@@ -20,6 +20,7 @@
# ls [path] List a directory (default ~)
# cat <path> Read a text file
# raw <path> Stream a file's raw bytes to stdout (images, video, any blob)
+# share <id> Download an authenticated temporary-link artifact to stdout
# write <path> <text> Write a file
# mkdir <path> Create a directory
# rm <path> Delete, recursively
@@ -273,6 +274,7 @@ case "$cmd" in
ls) jget "/api/v1/fs/list?path=$(enc "${1:-~}")" ;;
cat) jget "/api/v1/fs/read?path=$(enc "${1:?path}")" | jq -r . ;;
raw) reqraw "$B/api/v1/fs/raw?path=$(enc "${1:?path}")"; exit 0 ;;
+ share) reqraw "$B/api/v1/temp-share/$(enc "${1:?temporary link id}")?download=1"; exit 0 ;;
usage) jget "/api/v1/fs/usage?path=$(enc "${1:-~}")" ;;
search) jget "/api/v1/fs/search?q=$(enc "${1:?query}")${2:+&root=$(enc "$2")}" ;;
write) jpost "/api/v1/fs/write" "$(jq -n --arg p "${1:?path}" --arg c "${2-}" '{path:$p,content:$c}')" ;;
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 38758893..c5378cff 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- add secure temporary screenshot links
- add MCP screenshots and live activity
**Fixed**
diff --git a/docs/CLI.md b/docs/CLI.md
index 0ce9a37b..da6ba6fe 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -54,6 +54,7 @@ Commands:
ls [path] List a directory (default ~)
cat <path> Read a text file
raw <path> Stream a file's raw bytes to stdout (images, video, any blob)
+ share <id> Download an authenticated temporary-link artifact to stdout
write <path> <text> Write a file
mkdir <path> Create a directory
rm <path> Delete, recursively
diff --git a/lib/host/index.ts b/lib/host/index.ts
index 551291a3..c2a98fc9 100644
--- a/lib/host/index.ts
+++ b/lib/host/index.ts
@@ -13,6 +13,8 @@ export { stats, processes } from "./sys";
export { captureMsoScreen } from "./screenshot";
export type { ScreenshotShell, ScreenshotResult } from "./screenshot";
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 { HostError } from "./host-error";
diff --git a/lib/host/temp-share.test.ts b/lib/host/temp-share.test.ts
new file mode 100644
index 00000000..0bf0445d
--- /dev/null
+++ b/lib/host/temp-share.test.ts
@@ -0,0 +1,52 @@
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { consumeTempShare, createTempShare, inspectTempShare, tempShareUrl } from "./temp-share";
+
+const ROOT = path.join(os.tmpdir(), `mso-temp-shares-${process.pid}`);
+
+beforeEach(async () => {
+ await fs.rm(ROOT, { recursive: true, force: true });
+ vi.unstubAllEnvs();
+});
+
+afterEach(async () => {
+ await fs.rm(ROOT, { recursive: true, force: true });
+ vi.unstubAllEnvs();
+});
+
+describe("authenticated temporary downloads", () => {
+ it("keeps bytes outside public/, sanitizes the name and spends download allowances", async () => {
+ const created = await createTempShare({
+ data: Buffer.from("hello"),
+ filename: '../bad/"shot".png',
+ mimeType: "image/png",
+ maxDownloads: 2,
+ });
+
+ expect(created.id).toMatch(/^[A-Za-z0-9_-]{32}$/);
+ expect(created.name).toBe("_shot_.png");
+ expect(created.bytes).toBe(5);
+ expect(created.downloadsLeft).toBe(2);
+
+ const first = await consumeTempShare(created.id);
+ expect(first.data.toString()).toBe("hello");
+ expect(first.downloadsLeft).toBe(1);
+ expect((await inspectTempShare(created.id)).downloadsLeft).toBe(1);
+
+ const second = await consumeTempShare(created.id);
+ expect(second.data.toString()).toBe("hello");
+ await expect(inspectTempShare(created.id)).rejects.toThrow("unknown or expired");
+ });
+
+ it("builds HTTPS production links and refuses an insecure public origin", async () => {
+ const created = await createTempShare({ data: Buffer.from("x"), filename: "x.png", mimeType: "image/png" });
+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.test/some/path");
+ expect(tempShareUrl(created.id)).toBe(`https://mso.example.test/api/v1/temp-share/${created.id}`);
+ expect(tempShareUrl(created.id, true)).toBe(`https://mso.example.test/api/v1/temp-share/${created.id}?download=1`);
+
+ vi.stubEnv("OS_PUBLIC_ORIGIN", "http://mso.example.test");
+ expect(() => tempShareUrl(created.id)).toThrow("must use HTTPS");
+ });
+});
diff --git a/lib/host/temp-share.ts b/lib/host/temp-share.ts
new file mode 100644
index 00000000..fbe293e1
--- /dev/null
+++ b/lib/host/temp-share.ts
@@ -0,0 +1,232 @@
+import crypto from "crypto";
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+
+// Authenticated, expiring download links for small generated artifacts such as
+// MCP screenshots. The URL contains only an opaque random id; the real bytes live
+// under ~/.mso (0700/0600), never in public/, and every GET still has to pass the
+// normal approved-device session gate in the route.
+
+const VERSION = 1 as const;
+const DEFAULT_TTL_MS = 15 * 60_000;
+const MIN_TTL_MS = 60_000;
+const MAX_TTL_MS = 60 * 60_000;
+const DEFAULT_DOWNLOADS = 5;
+const MAX_DOWNLOADS = 10;
+const MAX_BYTES = 10 * 1024 * 1024;
+const ID_RE = /^[A-Za-z0-9_-]{32}$/;
+
+type TempShareEntry = {
+ id: string;
+ file: string;
+ name: string;
+ mimeType: string;
+ createdAt: number;
+ expiresAt: number;
+ downloadsLeft: number;
+};
+
+type TempShareStore = {
+ version: typeof VERSION;
+ entries: Record<string, TempShareEntry>;
+};
+
+export type TempShareInfo = Omit<TempShareEntry, "file"> & { bytes: number };
+export type ConsumedTempShare = TempShareInfo & { data: Buffer };
+
+function rootDir(): string {
+ // Never let a unit test touch the owner's real ~/.mso state. The process id
+ // keeps parallel vitest workers isolated without adding a production knob.
+ if (process.env.VITEST) return path.join(os.tmpdir(), `mso-temp-shares-${process.pid}`);
+ return path.join(os.homedir(), ".mso", "temp-shares");
+}
+
+function storePath(): string {
+ return path.join(rootDir(), "index.json");
+}
+
+function clamp(n: number | undefined, min: number, max: number, fallback: number): number {
+ if (!Number.isFinite(n)) return fallback;
+ return Math.min(Math.max(Math.round(n as number), min), max);
+}
+
+function cleanFilename(input: string): string {
+ const base = path.basename(input || "download.bin");
+ const cleaned = base
+ .replace(/[\u0000-\u001f\u007f"\\/]/g, "_")
+ .replace(/\s+/g, " ")
+ .trim()
+ .slice(0, 120);
+ return cleaned || "download.bin";
+}
+
+function cleanMimeType(input: string): string {
+ return /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(input)
+ ? input.toLowerCase()
+ : "application/octet-stream";
+}
+
+function assertId(id: string): void {
+ if (!ID_RE.test(id)) throw new Error("unknown or expired temporary link");
+}
+
+async function readStore(): Promise<TempShareStore> {
+ let raw: string;
+ try {
+ raw = await fs.readFile(storePath(), "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { version: VERSION, entries: {} };
+ throw error;
+ }
+ const parsed = JSON.parse(raw) as Partial<TempShareStore>;
+ if (parsed.version !== VERSION || !parsed.entries || typeof parsed.entries !== "object") {
+ throw new Error("temporary-link store is invalid");
+ }
+ return { version: VERSION, entries: parsed.entries };
+}
+
+async function writeStore(store: TempShareStore): Promise<void> {
+ const dir = rootDir();
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
+ const tmp = `${storePath()}.tmp`;
+ await fs.writeFile(tmp, JSON.stringify(store, null, 2), { encoding: "utf8", mode: 0o600 });
+ await fs.rename(tmp, storePath());
+}
+
+async function cleanupUnlocked(store: TempShareStore, now = Date.now()): Promise<boolean> {
+ let changed = false;
+ for (const [id, entry] of Object.entries(store.entries)) {
+ if (entry.expiresAt > now && entry.downloadsLeft > 0) continue;
+ delete store.entries[id];
+ changed = true;
+ await fs.rm(path.join(rootDir(), entry.file), { force: true }).catch(() => undefined);
+ }
+ return changed;
+}
+
+// Serialize every read-modify-write so simultaneous browser downloads cannot both
+// spend the same final allowance or resurrect an entry another request removed.
+let mutationChain: Promise<unknown> = Promise.resolve();
+function mutate<T>(fn: () => Promise<T>): Promise<T> {
+ const run = mutationChain.then(fn, fn);
+ mutationChain = run.then(() => undefined, () => undefined);
+ return run;
+}
+
+export async function createTempShare(input: {
+ data: Uint8Array | Buffer;
+ filename: string;
+ mimeType: string;
+ ttlMs?: number;
+ maxDownloads?: number;
+}): Promise<TempShareInfo> {
+ const data = Buffer.from(input.data);
+ if (data.byteLength === 0 || data.byteLength > MAX_BYTES) {
+ throw new Error(`temporary download must be between 1 byte and ${MAX_BYTES} bytes`);
+ }
+ const ttlMs = clamp(input.ttlMs, MIN_TTL_MS, MAX_TTL_MS, DEFAULT_TTL_MS);
+ const downloadsLeft = clamp(input.maxDownloads, 1, MAX_DOWNLOADS, DEFAULT_DOWNLOADS);
+ const name = cleanFilename(input.filename);
+ const mimeType = cleanMimeType(input.mimeType);
+
+ return mutate(async () => {
+ const dir = rootDir();
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
+ const store = await readStore();
+ await cleanupUnlocked(store);
+
+ const id = crypto.randomBytes(24).toString("base64url");
+ const file = `${id}.bin`;
+ const createdAt = Date.now();
+ const expiresAt = createdAt + ttlMs;
+ const entry: TempShareEntry = { id, file, name, mimeType, createdAt, expiresAt, downloadsLeft };
+
+ await fs.writeFile(path.join(dir, file), data, { mode: 0o600 });
+ store.entries[id] = entry;
+ await writeStore(store);
+
+ const timer = setTimeout(() => void revokeTempShare(id), ttlMs + 1_000);
+ timer.unref?.();
+ return { ...entry, bytes: data.byteLength };
+ });
+}
+
+export async function inspectTempShare(id: string): Promise<TempShareInfo> {
+ assertId(id);
+ return mutate(async () => {
+ const store = await readStore();
+ const changed = await cleanupUnlocked(store);
+ const entry = store.entries[id];
+ if (!entry) {
+ if (changed) await writeStore(store);
+ throw new Error("unknown or expired temporary link");
+ }
+ let stat;
+ try {
+ stat = await fs.stat(path.join(rootDir(), entry.file));
+ } catch {
+ delete store.entries[id];
+ await writeStore(store);
+ throw new Error("unknown or expired temporary link");
+ }
+ if (changed) await writeStore(store);
+ return { ...entry, bytes: stat.size };
+ });
+}
+
+export async function consumeTempShare(id: string): Promise<ConsumedTempShare> {
+ assertId(id);
+ return mutate(async () => {
+ const store = await readStore();
+ await cleanupUnlocked(store);
+ const entry = store.entries[id];
+ if (!entry) {
+ await writeStore(store);
+ throw new Error("unknown or expired temporary link");
+ }
+ const filePath = path.join(rootDir(), entry.file);
+ let data: Buffer;
+ try {
+ data = await fs.readFile(filePath);
+ } catch {
+ delete store.entries[id];
+ await writeStore(store);
+ throw new Error("unknown or expired temporary link");
+ }
+
+ entry.downloadsLeft -= 1;
+ if (entry.downloadsLeft <= 0) {
+ delete store.entries[id];
+ await fs.rm(filePath, { force: true }).catch(() => undefined);
+ }
+ await writeStore(store);
+ return { ...entry, bytes: data.byteLength, data };
+ });
+}
+
+export async function revokeTempShare(id: string): Promise<boolean> {
+ if (!ID_RE.test(id)) return false;
+ return mutate(async () => {
+ const store = await readStore();
+ const entry = store.entries[id];
+ if (!entry) return false;
+ delete store.entries[id];
+ await fs.rm(path.join(rootDir(), entry.file), { force: true }).catch(() => undefined);
+ await writeStore(store);
+ return true;
+ });
+}
+
+export function tempShareUrl(id: string, download = false): string {
+ assertId(id);
+ const relative = `/api/v1/temp-share/${id}${download ? "?download=1" : ""}`;
+ const explicit = process.env.OS_PUBLIC_ORIGIN?.trim();
+ if (!explicit) return relative;
+ const url = new URL(explicit);
+ const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1";
+ if (url.protocol !== "https:" && !loopback) {
+ throw new Error("OS_PUBLIC_ORIGIN must use HTTPS for temporary download links");
+ }
+ return `${url.origin}${relative}`;
+}
diff --git a/lib/mcp/tools-read.ts b/lib/mcp/tools-read.ts
index 2870df17..f6083fdb 100644
--- a/lib/mcp/tools-read.ts
+++ b/lib/mcp/tools-read.ts
@@ -1,4 +1,4 @@
-import { listDir, readFile, searchFs, usage, stats, processes, captureMsoScreen } from "@/lib/host";
+import { listDir, readFile, searchFs, usage, stats, processes, captureMsoScreen, createTempShare, tempShareUrl } from "@/lib/host";
import { camoufoxStatus } from "@/lib/camoufox/service";
import { listManagedApps, getManagedAppLogs } from "@/lib/managed-apps/manager";
import { isManagedAppId } from "@/lib/managed-apps/catalog";
@@ -104,7 +104,8 @@ export const READ_TOOLS: McpTool[] = [
description:
"Capture the authenticated MSO desktop and return it as an image. This is intentionally limited to " +
"MSO itself (no arbitrary URL capture), so it can be used to show visual progress without turning a read token " +
- "into a browser exfiltration primitive. Choose macos, windows or dashboard; default macos.",
+ "into a browser exfiltration primitive. It also returns a 15-minute, session-gated temporary preview/download link. " +
+ "Choose macos, windows or dashboard; default macos.",
scope: "read",
annotations: READ_ONLY,
limit: { key: "screen.capture", max: 10, windowMs: 60_000 },
@@ -122,9 +123,26 @@ export const READ_TOOLS: McpTool[] = [
width: typeof a.width === "number" ? a.width : undefined,
height: typeof a.height === "number" ? a.height : undefined,
});
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
+ const share = await createTempShare({
+ data: Buffer.from(shot.data, "base64"),
+ filename: `mso-${shot.shell}-${stamp}.png`,
+ mimeType: shot.mimeType,
+ ttlMs: 15 * 60_000,
+ maxDownloads: 5,
+ });
+ const previewUrl = tempShareUrl(share.id);
+ const downloadUrl = tempShareUrl(share.id, true);
return mcpDirect([
{ type: "image", data: shot.data, mimeType: shot.mimeType },
- { type: "text", text: `MSO ${shot.shell} screenshot — ${shot.width}×${shot.height}` },
+ {
+ type: "text",
+ text:
+ `MSO ${shot.shell} screenshot — ${shot.width}×${shot.height}\n` +
+ `Temporary preview: ${previewUrl}\n` +
+ `Direct download: ${downloadUrl}\n` +
+ `Expires ${new Date(share.expiresAt).toISOString()} · ${share.downloadsLeft} authenticated downloads`,
+ },
]);
},
},