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(mcp): harden bidirectional file transfer

Rahman69323d0c0368
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index bac9f4d6..575f9ccd 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -12,6 +12,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Fixed**
+- `mcp` harden bidirectional file transfer
- `mcp` bind ChatGPT Azure file trust to OAuth provenance
- `mcp` make project plugins explicit opt-in installs
- `mcp` trust verified ChatGPT Azure file host
diff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.md
index 12163a81..cb435bc7 100644
--- a/docs/CHATGPT-PLUGIN.md
+++ b/docs/CHATGPT-PLUGIN.md
@@ -131,20 +131,15 @@ ChatGPT file parameter VPS file
├─ PNG/WebP/JPEG/JSON/ZIP only ├─ OS_FS_READ_ROOTS + credential denylist
├─ 20 MiB streamed cap ├─ original bytes, max 10 MiB
├─ provenance-bound OpenAI/Azure host ├─ SHA-256
- └─ OS_FS_WRITE_ROOTS └─ private 15-minute temp-share
- │
- ▼
- approved-device authenticated download
+ ├─ full image/JSON/ZIP validation ├─ owner+session mso-file resource
+ ├─ conflict guard / CAS replace └─ private browser temp-share fallback
+ └─ OS_FS_WRITE_ROOTS
```
Upload trusts `*.oaiusercontent.com` directly. When OAuth proves a `chatgpt.com` callback,
`openai/fileParams` may also use ChatGPT's rotating `oaisdmntpr<region>.blob.core.windows.net`
temporary-file family. A self-declared client name never unlocks that family; generic MCP clients
-need exact `OS_MCP_OPENAI_FILE_HOSTS` entries. Export returns a `resource_link` plus structured
-checksum/size metadata.
-The link is not public, consumes the existing MSO approved-device session gate, allows at most five
-downloads, and preserves the source bytes exactly. `session_artifacts` remains a preview/artifact
-workflow and may recompress large images, so it is not the original-file export path.
+need exact `OS_MCP_OPENAI_FILE_HOSTS` entries. Raster uploads must fully decode; JSON and ZIP are structurally validated. Identical retries are unchanged, different existing bytes fail by default, deterministic rename is explicit, and replace requires the current `expected_sha256`. Export returns an owner+conversation-session-bound `mso-file:///…` `resource_link`; `resources/read` returns the exact original blob with expiry/read limits. A separate approved-device browser URL remains available as a human fallback. `session_artifacts` is still a preview workflow and may recompress large images, so it is not the original-file export path.
## OAuth contract
diff --git a/docs/FAQ.md b/docs/FAQ.md
index 9a7db3a3..50ce0b1e 100644
--- a/docs/FAQ.md
+++ b/docs/FAQ.md
@@ -122,10 +122,7 @@ does not grant the other.
### Can ChatGPT send a generated image/file into the VPS?
-Yes. `fs_upload_file` accepts a ChatGPT-provided temporary file reference, validates the
-OpenAI download host/redirects/type/size, and writes it inside `OS_FS_WRITE_ROOTS`. MSO does
-not maintain a second image generator; use ChatGPT's native generation, then transfer the
-result.
+Yes. `fs_upload_file` accepts ChatGPT-provided PNG/WebP/JPEG/JSON/ZIP references, validates the OpenAI download host, redirects, type, size and content, then writes inside `OS_FS_WRITE_ROOTS`. Identical retries are unchanged; different existing bytes fail unless deterministic rename or guarded `expected_sha256` replacement is explicit. `fs_export_file` returns an owner-bound MCP resource whose exact bytes are fetched with `resources/read`, plus a separate approved-device browser download fallback. MSO does not maintain a second image generator; use ChatGPT's native generation, then transfer the result.
### Does MCP expose every project automatically?
diff --git a/docs/MCP.md b/docs/MCP.md
index 899de109..9f74cf52 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -566,17 +566,12 @@ and ZIP signatures are validated before the normal credential/path jail writes i
registered callback is owned by `chatgpt.com`, the `openai/fileParams` bridge may also follow the
rotating `oaisdmntpr<region>.blob.core.windows.net` family used by ChatGPT temporary downloads.
That family exception is never granted from a self-declared client name alone; generic MCP clients
-still need exact Azure hosts in `OS_MCP_OPENAI_FILE_HOSTS`. The final write uses an exclusive random
-temporary file and atomic rename, never executes transferred bytes, and returns path, bytes and
-SHA-256. Existing same-name files may still be replaced, so import remains a write/destructive action.
+still need exact Azure hosts in `OS_MCP_OPENAI_FILE_HOSTS`. Raster files must also fully decode through bounded Sharp validation; magic bytes alone are insufficient. ZIP input requires a valid end-of-central-directory structure. The final write uses exclusive temporary files and atomic filesystem operations and never executes transferred bytes. Same bytes are idempotent; different existing bytes fail by default. `conflict=rename` uses a deterministic content-hash filename, while `conflict=replace` requires the current `expected_sha256`, so stale overwrites fail.
**`fs_export_file`** is the read-side counterpart for one original file up to **10 MiB**. It uses
the same `OS_FS_READ_ROOTS`, realpath and credential denylist as other reads, reads with
`O_NOFOLLOW`, computes SHA-256 over the original bytes, then copies those bytes into the existing
-private temporary-share store. The returned resource/download link requires an approved-device MSO
-session, is `no-store`, expires after 15 minutes and is limited to five downloads. It never creates
-a public URL and never routes through `session_artifacts`, so images and archives are not
-recompressed or text-decoded. See `CHATGPT-PLUGIN.md` for the end-to-end contract.
+private temporary-share store and creates an owner+conversation-session-bound `mso-file:///…` MCP resource. `resources/read` returns that resource as the exact base64 `blob` only to the same authenticated MCP principal and session; it expires after 15 minutes and is read-count bounded. The approved-device browser download remains a separate fallback. Neither path routes through `session_artifacts`, so images and archives are not recompressed or text-decoded. After a public tool/schema change, deploy first, then Scan Tools / Refresh in ChatGPT and test from a new chat. See `CHATGPT-PLUGIN.md` for the end-to-end contract.
`OS_CODEX_BUILTIN_TOOLS` still exists and still takes an allowlisted list, but its
default is now EMPTY and `image_generation` is no longer an accepted value — naming it
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 26e99f7e..a5aea63f 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,4 +1,9 @@
-## 2026-09-14 — Original-byte MCP file export + explicit ChatGPT import matrix
+## 2026-09-15 — Original-byte MCP transfer final hardening
+
+- `fs_upload_file` is content-idempotent and fail-closed on filename conflicts by default; deterministic rename and SHA-guarded replacement are explicit.
+- PNG/JPEG/WebP require bounded full decode; JSON requires fatal UTF-8 + parse; ZIP requires an EOCD structure before write.
+- `fs_export_file` now exposes owner-bound ephemeral `mso-file:///…` resources; `resources/read` returns exact original blobs only to the same MCP principal + conversation session while browser temp-share remains a separate convenience.
+- Public schema changes require ChatGPT Scan Tools / Refresh and a new chat before external-client acceptance testing.
## 2026-09-15 — Project plugins are opt-in, isolated installations
@@ -9,6 +14,8 @@ Batonly joins SI-Coder as a first-class reviewed project plugin. Its project bin
This preserves three separate layers: host MCP access, reusable MSO Integrations credentials, and project-local plugin bindings. Installing or removing a plugin from one project changes neither standalone SI-Coder nor Batonly data nor another project.
+## 2026-09-14 — Original-byte MCP file export + explicit ChatGPT import matrix
+
The upstream MSO file-transfer audit is now implemented instead of remaining a read-only finding.
`fs_export_file` exports one original file through the existing authenticated temporary-share store:
READ-root/credential guards and `O_NOFOLLOW` remain authoritative, bytes are not decoded or
diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.md
index 10500747..6b06e130 100644
--- a/docs/generated/MCP-CATALOG.md
+++ b/docs/generated/MCP-CATALOG.md
@@ -10,7 +10,7 @@
|---|---:|
| MCP server | `1.14.2` |
| Toolset | `2026.09.15.1` |
-| Toolset changed at | `2026-09-15T00:10:00+07:00` |
+| Toolset changed at | `2026-09-15T00:30:00+07:00` |
| Transport tools | **107** |
| Model/operator tools | **105** |
| Read | **50** |
diff --git a/lib/host/fs-api.ts b/lib/host/fs-api.ts
index 6ea62848..d7cf20c6 100644
--- a/lib/host/fs-api.ts
+++ b/lib/host/fs-api.ts
@@ -1,9 +1,10 @@
export { listDir, readFile, writeFile, makeDir, remove, move, copy, searchFs, usage, statReadable, mimeFor, fileStream } from "./fs";
export { uploadInto, resolveUploadDest, streamFileInto } from "./fs-upload";
+export { uploadOneGuarded } from "./fs-upload-guarded";
+export type { UploadConflictPolicy, GuardedUploadResult } from "./fs-upload-guarded";
export { zipStream } from "./fs-zip";
export { parseMultipart, boundaryFromContentType, UploadTooLargeError } from "./multipart";
export type { MultipartPart } from "./multipart";
export { sha256Text, utf8Bytes } from "./hash";
export { writeFileGuarded } from "./guarded-write";
-
export { readFileBytes } from "./fs-read-bytes";
diff --git a/lib/host/fs-upload-guarded.test.ts b/lib/host/fs-upload-guarded.test.ts
new file mode 100644
index 00000000..ed14658b
--- /dev/null
+++ b/lib/host/fs-upload-guarded.test.ts
@@ -0,0 +1,52 @@
+import { createHash } from "crypto";
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+let dir: string;
+beforeEach(async () => {
+ dir = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "mso-guarded-upload-")));
+ vi.stubEnv("OS_FS_WRITE_ROOTS", dir);
+ vi.stubEnv("OS_FS_READ_ROOTS", dir);
+});
+afterEach(async () => { vi.unstubAllEnvs(); await fs.rm(dir, { recursive: true, force: true }); });
+
+describe("uploadOneGuarded", () => {
+ it("creates, then treats identical bytes as idempotent unchanged", async () => {
+ const { uploadOneGuarded } = await import("./fs-upload-guarded");
+ const data = Buffer.from("same");
+ expect(await uploadOneGuarded({ dest: dir, filename: "a.json", data })).toMatchObject({ status: "created" });
+ expect(await uploadOneGuarded({ dest: dir, filename: "a.json", data })).toMatchObject({ status: "unchanged" });
+ });
+ it("refuses different existing bytes by default", async () => {
+ const { uploadOneGuarded } = await import("./fs-upload-guarded");
+ await fs.writeFile(path.join(dir, "a.json"), "old");
+ await expect(uploadOneGuarded({ dest: dir, filename: "a.json", data: Buffer.from("new") })).rejects.toThrow(/already exists/i);
+ });
+ it("renames deterministically and is idempotent on retry", async () => {
+ const { uploadOneGuarded } = await import("./fs-upload-guarded");
+ await fs.writeFile(path.join(dir, "a.json"), "old");
+ const first = await uploadOneGuarded({ dest: dir, filename: "a.json", data: Buffer.from("new"), conflict: "rename" });
+ const second = await uploadOneGuarded({ dest: dir, filename: "a.json", data: Buffer.from("new"), conflict: "rename" });
+ expect(first.status).toBe("renamed");
+ expect(first.filename).toMatch(/^a\.[a-f0-9]{16}\.json$/);
+ expect(second).toMatchObject({ status: "unchanged", filename: first.filename });
+ });
+ it("requires the exact prior hash for replacement", async () => {
+ const { uploadOneGuarded } = await import("./fs-upload-guarded");
+ const file = path.join(dir, "a.json");
+ await fs.writeFile(file, "old");
+ const oldHash = createHash("sha256").update("old").digest("hex");
+ await expect(uploadOneGuarded({ dest: dir, filename: "a.json", data: Buffer.from("new"), conflict: "replace" })).rejects.toThrow(/expected_sha256/i);
+ await expect(uploadOneGuarded({ dest: dir, filename: "a.json", data: Buffer.from("new"), conflict: "replace", expectedSha256: "0".repeat(64) })).rejects.toThrow(/changed/i);
+ const replaced = await uploadOneGuarded({ dest: dir, filename: "a.json", data: Buffer.from("new"), conflict: "replace", expectedSha256: oldHash });
+ expect(replaced.status).toBe("replaced");
+ expect(await fs.readFile(file, "utf8")).toBe("new");
+ expect(await uploadOneGuarded({ dest: dir, filename: "a.json", data: Buffer.from("new"), conflict: "replace", expectedSha256: oldHash })).toMatchObject({ status: "unchanged" });
+ });
+ it("does not create a missing destination in replace mode", async () => {
+ const { uploadOneGuarded } = await import("./fs-upload-guarded");
+ await expect(uploadOneGuarded({ dest: dir, filename: "a.json", data: Buffer.from("new"), conflict: "replace", expectedSha256: "0".repeat(64) })).rejects.toThrow(/existing destination/i);
+ });
+});
diff --git a/lib/host/fs-upload-guarded.ts b/lib/host/fs-upload-guarded.ts
new file mode 100644
index 00000000..7ab52234
--- /dev/null
+++ b/lib/host/fs-upload-guarded.ts
@@ -0,0 +1,120 @@
+import { createHash, randomUUID } from "crypto";
+import { promises as fs, constants as fsConstants } from "fs";
+import path from "path";
+import { HostError } from "./host-error";
+import { assertUploadTarget } from "./paths";
+import { resolveUploadDest } from "./fs-upload";
+
+export type UploadConflictPolicy = "error" | "rename" | "replace";
+export type GuardedUploadResult = {
+ path: string;
+ filename: string;
+ status: "created" | "unchanged" | "renamed" | "replaced";
+ sha256: string;
+ previousSha256?: string;
+};
+
+const SHA_RE = /^[a-f0-9]{64}$/i;
+const hash = (data: Uint8Array) => createHash("sha256").update(data).digest("hex");
+
+function safeName(name: string): string {
+ if (!name || path.basename(name) !== name || name.length > 200 || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) {
+ throw new HostError("filename is invalid");
+ }
+ return name;
+}
+
+async function existingHash(full: string): Promise<string | null> {
+ let handle;
+ try {
+ handle = await fs.open(full, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ if ((error as NodeJS.ErrnoException).code === "ELOOP") throw new HostError("Refusing symlink file");
+ throw error;
+ }
+ try {
+ const stat = await handle.stat();
+ if (!stat.isFile()) throw new HostError("Destination exists but is not a regular file");
+ const digest = createHash("sha256"), chunk = Buffer.allocUnsafe(1024 * 1024);
+ let offset = 0;
+ while (offset < stat.size) {
+ const { bytesRead } = await handle.read(chunk, 0, Math.min(chunk.length, stat.size - offset), offset);
+ if (!bytesRead) break;
+ digest.update(chunk.subarray(0, bytesRead));
+ offset += bytesRead;
+ }
+ return digest.digest("hex");
+ } finally {
+ await handle.close().catch(() => undefined);
+ }
+}
+
+function renamed(name: string, sha256: string): string {
+ const ext = path.extname(name), stem = path.basename(name, ext), suffix = sha256.slice(0, 16);
+ const maxStem = Math.max(1, 200 - ext.length - suffix.length - 2);
+ return `${stem.slice(0, maxStem)}.${suffix}${ext}`;
+}
+
+async function createExclusive(full: string, data: Uint8Array): Promise<boolean> {
+ const tmp = `${full}.mso-upload-${process.pid}-${randomUUID()}.tmp`;
+ try {
+ await fs.writeFile(tmp, data, { mode: 0o600, flag: "wx" });
+ await fs.chmod(tmp, 0o644);
+ await fs.link(tmp, full);
+ return true;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") return false;
+ throw error;
+ } finally {
+ await fs.rm(tmp, { force: true }).catch(() => undefined);
+ }
+}
+
+async function replaceAtomic(full: string, data: Uint8Array): Promise<void> {
+ const tmp = `${full}.mso-upload-${process.pid}-${randomUUID()}.tmp`;
+ try {
+ await fs.writeFile(tmp, data, { mode: 0o600, flag: "wx" });
+ await fs.chmod(tmp, 0o644);
+ await fs.rename(tmp, full);
+ } finally {
+ await fs.rm(tmp, { force: true }).catch(() => undefined);
+ }
+}
+
+export async function uploadOneGuarded(input: {
+ dest: string; filename: string; data: Uint8Array;
+ conflict?: UploadConflictPolicy; expectedSha256?: string;
+}): Promise<GuardedUploadResult> {
+ const destReal = await resolveUploadDest(input.dest), filename = safeName(input.filename);
+ const full = path.join(destReal, filename), sha256 = hash(input.data), policy = input.conflict ?? "error";
+ await assertUploadTarget(full, destReal);
+ await fs.mkdir(path.dirname(full), { recursive: true, mode: 0o700 });
+ await assertUploadTarget(full, destReal);
+
+ let previous = await existingHash(full);
+ if (previous === null) {
+ if (policy === "replace") throw new HostError("replace requires an existing destination and expected_sha256");
+ if (await createExclusive(full, input.data)) return { path: full, filename, status: "created", sha256 };
+ previous = await existingHash(full);
+ }
+ if (previous === sha256) return { path: full, filename, status: "unchanged", sha256, previousSha256: previous };
+ if (policy === "error") throw new HostError("destination already exists with different content; choose rename or guarded replace");
+
+ if (policy === "rename") {
+ const alternate = renamed(filename, sha256), alternateFull = path.join(/*turbopackIgnore: true*/ destReal, alternate);
+ await assertUploadTarget(alternateFull, destReal);
+ const alternateHash = await existingHash(alternateFull);
+ if (alternateHash === sha256) return { path: alternateFull, filename: alternate, status: "unchanged", sha256, previousSha256: alternateHash };
+ if (alternateHash !== null || !(await createExclusive(alternateFull, input.data))) throw new HostError("deterministic renamed destination already exists with different content");
+ return { path: alternateFull, filename: alternate, status: "renamed", sha256, previousSha256: previous ?? undefined };
+ }
+
+ const expected = input.expectedSha256?.toLowerCase();
+ if (!expected || !SHA_RE.test(expected)) throw new HostError("replace requires expected_sha256 from a prior read/export");
+ if (previous !== expected) throw new HostError("destination changed since inspection; refresh its SHA-256 before replacing");
+ const rechecked = await existingHash(full);
+ if (rechecked !== expected) throw new HostError("destination changed during replacement; retry only after a fresh read/export");
+ await replaceAtomic(full, input.data);
+ return { path: full, filename, status: "replaced", sha256, previousSha256: previous ?? undefined };
+}
diff --git a/lib/mcp/dispatch.ts b/lib/mcp/dispatch.ts
index e65100cb..ba7d8a52 100644
--- a/lib/mcp/dispatch.ts
+++ b/lib/mcp/dispatch.ts
@@ -4,6 +4,7 @@ import { TOOLS } from "./tools";
import { listUiResources, readUiResource } from "./ui-resources";
import { MCP_SKILLS_EXTENSION, getMcpSkill, listMcpSkills, readMcpSkillResource } from "./skills-extension";
import { dispatchToolCall } from "./dispatch-tools";
+import { readMcpFileResource } from "./file-transfer-resource";
import { toolDescriptor, visibleToolsForProfile, type McpToolProfile } from "./tool-contract";
import { MCP_PROTOCOL_LATEST, MCP_PROTOCOLS, negotiateMcpProtocol } from "./protocol";
import { rpcFail, rpcOk, type McpAgentContext, type RpcRequest } from "./dispatch-types";
@@ -69,6 +70,10 @@ export async function dispatch(req: RpcRequest, scope: Scope, actor?: string, ag
if (!uri) return rpcFail(id, -32602, "resources/read needs { uri }");
const resource = await readUiResource(uri);
if (resource) return rpcOk(id, { contents: [{ uri: resource.uri, mimeType: resource.mimeType, text: resource.text, _meta: resource._meta }] });
+ try {
+ const fileResource = await readMcpFileResource(uri, agentContext?.principal, agentContext?.sessionId);
+ if (fileResource) return rpcOk(id, { contents: [{ uri: fileResource.uri, mimeType: fileResource.mimeType, blob: fileResource.data.toString("base64") }] });
+ } catch (error) { return rpcFail(id, -32602, error instanceof Error ? error.message : String(error)); }
try {
const skillResource = await readMcpSkillResource(uri);
if (skillResource) return rpcOk(id, { contents: [skillResource] });
diff --git a/lib/mcp/file-transfer-dispatch.test.ts b/lib/mcp/file-transfer-dispatch.test.ts
new file mode 100644
index 00000000..69ab193d
--- /dev/null
+++ b/lib/mcp/file-transfer-dispatch.test.ts
@@ -0,0 +1,25 @@
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+import { createMcpFileResource } from "./file-transfer-resource";
+import { dispatch } from "./dispatch";
+
+const ROOT = path.join(os.tmpdir(), `mso-mcp-file-resources-${process.pid}`);
+beforeEach(async () => { await fs.rm(ROOT, { recursive: true, force: true }); });
+afterEach(async () => { await fs.rm(ROOT, { recursive: true, force: true }); });
+
+describe("resources/read original-byte file bridge", () => {
+ it("returns exact base64 bytes for the owner and denies another principal", async () => {
+ const bytes = Buffer.from([0,1,2,3,4,250,251,252]);
+ const resource = await createMcpFileResource({ data: bytes, filename: "fixture.zip", mimeType: "application/zip", principal: "alice", sessionId: "session-a", maxReads: 3 });
+ const ok = await dispatch({ id: 1, method: "resources/read", params: { uri: resource.uri } }, "read", "actor", { principal: "alice", sessionId: "session-a", toolProfile: "chatgpt" });
+ const result = (ok as any).result;
+ expect(result.contents[0]).toMatchObject({ uri: resource.uri, mimeType: "application/zip", blob: bytes.toString("base64") });
+ const denied = await dispatch({ id: 2, method: "resources/read", params: { uri: resource.uri } }, "read", "actor", { principal: "bob", sessionId: "session-a", toolProfile: "chatgpt" });
+ expect((denied as any).error?.message).toMatch(/unknown or expired/i);
+ const wrongSession = await dispatch({ id: 3, method: "resources/read", params: { uri: resource.uri } }, "read", "actor", { principal: "alice", sessionId: "session-b", toolProfile: "chatgpt" });
+ expect((wrongSession as any).error?.message).toMatch(/unknown or expired/i);
+ });
+});
diff --git a/lib/mcp/file-transfer-resource.test.ts b/lib/mcp/file-transfer-resource.test.ts
new file mode 100644
index 00000000..58f2f4d6
--- /dev/null
+++ b/lib/mcp/file-transfer-resource.test.ts
@@ -0,0 +1,33 @@
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createMcpFileResource, readMcpFileResource } from "./file-transfer-resource";
+
+const ROOT = path.join(os.tmpdir(), `mso-mcp-file-resources-${process.pid}`);
+beforeEach(async () => { await fs.rm(ROOT, { recursive: true, force: true }); vi.useRealTimers(); });
+afterEach(async () => { vi.useRealTimers(); await fs.rm(ROOT, { recursive: true, force: true }); });
+
+describe("principal-bound MCP file resources", () => {
+ it("returns exact bytes only to the creating principal", async () => {
+ const data = Buffer.from([0,1,2,3,255]);
+ const resource = await createMcpFileResource({ data, filename: "x.bin", mimeType: "application/octet-stream", principal: "alice", sessionId: "session-a", maxReads: 3 });
+ expect(resource.uri).toMatch(/^mso-file:\/\/[\/][a-f0-9]{48}$/);
+ await expect(readMcpFileResource(resource.uri, "bob", "session-a")).rejects.toThrow(/unknown or expired/i);
+ const read = await readMcpFileResource(resource.uri, "alice", "session-a");
+ expect(read?.data).toEqual(data);
+ expect(read?.sha256).toBe(resource.sha256);
+ });
+ it("enforces read exhaustion", async () => {
+ const one = await createMcpFileResource({ data: Buffer.from("x"), filename: "x.txt", mimeType: "text/plain", principal: "alice", sessionId: "session-a", maxReads: 1 });
+ expect((await readMcpFileResource(one.uri, "alice", "session-a"))?.data.toString()).toBe("x");
+ await expect(readMcpFileResource(one.uri, "alice", "session-a")).rejects.toThrow(/unknown or expired/i);
+ });
+ it("expires after its TTL", async () => {
+ vi.useFakeTimers();
+ const now = Date.now(); vi.setSystemTime(now);
+ const expiring = await createMcpFileResource({ data: Buffer.from("y"), filename: "y.txt", mimeType: "text/plain", principal: "alice", sessionId: "session-a", ttlMs: 60_000 });
+ vi.setSystemTime(now + 61_000);
+ await expect(readMcpFileResource(expiring.uri, "alice", "session-a")).rejects.toThrow(/unknown or expired/i);
+ });
+});
diff --git a/lib/mcp/file-transfer-resource.ts b/lib/mcp/file-transfer-resource.ts
new file mode 100644
index 00000000..5b5a5ce4
--- /dev/null
+++ b/lib/mcp/file-transfer-resource.ts
@@ -0,0 +1,110 @@
+import { createHash, randomBytes } from "crypto";
+import { promises as fs } from "fs";
+import os from "os";
+import path from "path";
+
+const VERSION = 1 as const;
+const MAX_BYTES = 10 * 1024 * 1024;
+const DEFAULT_TTL_MS = 15 * 60_000;
+const DEFAULT_READS = 5;
+const ID_RE = /^[a-f0-9]{48}$/;
+
+type Entry = {
+ version: typeof VERSION; id: string; file: string; filename: string; mimeType: string;
+ ownerHash: string; sha256: string; bytes: number; createdAt: number; expiresAt: number; readsLeft: number;
+};
+export type McpFileResourceInfo = Omit<Entry, "ownerHash" | "file" | "version"> & { uri: string };
+
+function rootDir(): string {
+ if (process.env.VITEST) return path.join(os.tmpdir(), `mso-mcp-file-resources-${process.pid}`);
+ return path.join(os.homedir(), ".mso", "mcp-file-resources");
+}
+const ownerHash = (principal: string, sessionId: string) => createHash("sha256").update(`${principal}\0${sessionId}`).digest("hex");
+const uriOf = (id: string) => `mso-file:///${id}`;
+const metaPath = (id: string) => path.join(rootDir(), `${id}.json`);
+const dataPath = (id: string) => path.join(rootDir(), `${id}.bin`);
+
+function idFromUri(uri: string): string | null {
+ let parsed: URL;
+ try { parsed = new URL(uri); } catch { return null; }
+ if (parsed.protocol !== "mso-file:" || parsed.hostname || parsed.search || parsed.hash) return null;
+ const id = parsed.pathname.replace(/^\//, "");
+ return ID_RE.test(id) ? id : null;
+}
+function safeFilename(input: string): string {
+ const value = path.basename(input || "download.bin").replace(/[\u0000-\u001f\u007f"\\/]/g, "_").slice(0, 120);
+ return value || "download.bin";
+}
+function safeMime(input: string): string {
+ return /^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/i.test(input) ? input.toLowerCase() : "application/octet-stream";
+}
+async function remove(id: string) {
+ await Promise.all([fs.rm(metaPath(id), { force: true }), fs.rm(dataPath(id), { force: true })]);
+}
+async function readEntry(id: string): Promise<Entry> {
+ const raw = await fs.readFile(metaPath(id), "utf8");
+ const entry = JSON.parse(raw) as Entry;
+ if (entry.version !== VERSION || entry.id !== id || !ID_RE.test(entry.id)) throw new Error("file resource is invalid");
+ return entry;
+}
+async function writeEntry(entry: Entry) {
+ const tmp = `${metaPath(entry.id)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
+ await fs.writeFile(tmp, JSON.stringify(entry), { mode: 0o600, flag: "wx" });
+ await fs.rename(tmp, metaPath(entry.id));
+}
+
+export async function createMcpFileResource(input: {
+ data: Uint8Array | Buffer; filename: string; mimeType: string; principal: string; sessionId: string; ttlMs?: number; maxReads?: number;
+}): Promise<McpFileResourceInfo> {
+ if (!input.principal || !input.sessionId) throw new Error("authenticated MCP principal and session required");
+ const data = Buffer.from(input.data);
+ if (!data.length || data.length > MAX_BYTES) throw new Error("MCP file resource must be between 1 byte and 10 MiB");
+ const ttlMs = Math.min(Math.max(input.ttlMs ?? DEFAULT_TTL_MS, 60_000), 60 * 60_000);
+ const readsLeft = Math.min(Math.max(Math.round(input.maxReads ?? DEFAULT_READS), 1), 10);
+ const id = randomBytes(24).toString("hex"), now = Date.now();
+ const entry: Entry = {
+ version: VERSION, id, file: `${id}.bin`, filename: safeFilename(input.filename), mimeType: safeMime(input.mimeType),
+ ownerHash: ownerHash(input.principal, input.sessionId), sha256: createHash("sha256").update(data).digest("hex"),
+ bytes: data.length, createdAt: now, expiresAt: now + ttlMs, readsLeft,
+ };
+ await fs.mkdir(rootDir(), { recursive: true, mode: 0o700 });
+ try {
+ await fs.writeFile(dataPath(id), data, { mode: 0o600, flag: "wx" });
+ await writeEntry(entry);
+ } catch (error) {
+ await remove(id).catch(() => undefined);
+ throw error;
+ }
+ const timer = setTimeout(() => void remove(id), ttlMs + 1_000);
+ timer.unref?.();
+ const { ownerHash: _owner, file: _file, version: _version, ...safe } = entry;
+ return { ...safe, uri: uriOf(id) };
+}
+
+export async function readMcpFileResource(uri: string, principal?: string, sessionId?: string): Promise<({ data: Buffer } & McpFileResourceInfo) | null> {
+ const id = idFromUri(uri);
+ if (!id) return null;
+ if (!principal || !sessionId) throw new Error("authenticated MCP principal and session required for file resource");
+ let entry: Entry;
+ try { entry = await readEntry(id); } catch { throw new Error("unknown or expired file resource"); }
+ if (entry.ownerHash !== ownerHash(principal, sessionId)) throw new Error("unknown or expired file resource");
+ if (entry.expiresAt <= Date.now() || entry.readsLeft <= 0) {
+ await remove(id).catch(() => undefined);
+ throw new Error("unknown or expired file resource");
+ }
+ let data: Buffer;
+ try { data = await fs.readFile(dataPath(id)); } catch {
+ await remove(id).catch(() => undefined);
+ throw new Error("unknown or expired file resource");
+ }
+ const actual = createHash("sha256").update(data).digest("hex");
+ if (data.length !== entry.bytes || actual !== entry.sha256) {
+ await remove(id).catch(() => undefined);
+ throw new Error("file resource integrity check failed");
+ }
+ entry.readsLeft -= 1;
+ if (entry.readsLeft <= 0) await remove(id);
+ else await writeEntry(entry);
+ const { ownerHash: _owner, file: _file, version: _version, ...safe } = entry;
+ return { ...safe, uri: uriOf(id), data };
+}
diff --git a/lib/mcp/openai-file-upload-regression.test.ts b/lib/mcp/openai-file-upload-regression.test.ts
new file mode 100644
index 00000000..c440a151
--- /dev/null
+++ b/lib/mcp/openai-file-upload-regression.test.ts
@@ -0,0 +1,85 @@
+type FsApiModule = typeof import("@/lib/host/fs-api");
+import sharp from "sharp";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+vi.mock("server-only", () => ({}));
+
+const uploadOneGuarded = vi.fn(async (input: Record<string, unknown>) => ({
+ path: `/home/example/${String(input.filename)}`, filename: String(input.filename),
+ status: "created", sha256: "a".repeat(64),
+}));
+vi.mock("@/lib/host/fs-api", async (orig) => {
+ const real = await orig<FsApiModule>();
+ return { ...real, uploadOneGuarded };
+});
+
+const { importOpenAiProvidedFile } = await import("./openai-file-upload");
+let PNG: Buffer;
+const JSON_BYTES = new TextEncoder().encode('{"ok":true}');
+const ZIP = Uint8Array.from([0x50,0x4b,0x05,0x06,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);
+
+beforeAll(async () => {
+ PNG = await sharp({ create: { width: 1, height: 1, channels: 4, background: { r: 1, g: 2, b: 3, alpha: 1 } } }).png().toBuffer();
+});
+beforeEach(() => {
+ uploadOneGuarded.mockClear();
+ delete process.env.OS_MCP_OPENAI_FILE_HOSTS;
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(new Uint8Array(PNG), { status: 200, headers: { "content-type": "image/png" } })));
+});
+afterEach(() => vi.unstubAllGlobals());
+
+const call = (file: Record<string, unknown>) => importOpenAiProvidedFile({
+ file: { download_url: "https://files.oaiusercontent.com/file.png", file_id: "file_test", file_name: "file.png", ...file },
+ dest: "/home/example/generated-files",
+});
+
+describe("ChatGPT transfer regression boundaries", () => {
+ it("trusts oaiusercontent and rejects malformed Azure allowlist entries fail-closed", async () => {
+ await expect(call({ mime_type: "image/png" })).resolves.toMatchObject({ mimeType: "image/png" });
+ process.env.OS_MCP_OPENAI_FILE_HOSTS = "*.blob.core.windows.net";
+ await expect(call({ download_url: "https://oaisdmntprseasia.blob.core.windows.net/file.png", mime_type: "image/png" })).rejects.toThrow(/invalid Azure Blob hostname/i);
+ });
+
+ it("allows the rotating Azure family only when OAuth provenance marks ChatGPT fileParams", async () => {
+ const file = { download_url: "https://oaisdmntprindiasocentral.blob.core.windows.net/file.png", file_id: "file_test", file_name: "file.png", mime_type: "image/png" };
+ await expect(importOpenAiProvidedFile({ file, dest: "/home/example/generated-files" })).rejects.toThrow(/host is not allowed/i);
+ await expect(importOpenAiProvidedFile({ file, dest: "/home/example/generated-files", allowChatGptAzureFamily: true })).resolves.toMatchObject({ mimeType: "image/png" });
+ });
+
+ it("rejects redirects to untrusted hosts", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 302, headers: { location: "https://attacker.blob.core.windows.net/file.png" } })));
+ await expect(call({ mime_type: "image/png" })).rejects.toThrow(/host is not allowed/i);
+ expect(uploadOneGuarded).not.toHaveBeenCalled();
+ });
+
+ it("allows redirects only to an exact configured Azure host", async () => {
+ process.env.OS_MCP_OPENAI_FILE_HOSTS = "oaisdmntprseasia.blob.core.windows.net";
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: "https://oaisdmntprseasia.blob.core.windows.net/file.png" } }))
+ .mockResolvedValueOnce(new Response(new Uint8Array(PNG), { status: 200, headers: { "content-type": "image/png" } }));
+ vi.stubGlobal("fetch", fetchMock);
+ await expect(call({ mime_type: "image/png" })).resolves.toMatchObject({ mimeType: "image/png" });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it("normalizes ZIP MIME and can infer supported MIME from filename", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(ZIP, { status: 200, headers: { "content-type": "application/x-zip-compressed" } })));
+ await expect(call({ mime_type: "application/x-zip-compressed", file_name: "file.zip" })).resolves.toMatchObject({ mimeType: "application/zip" });
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON_BYTES, { status: 200, headers: { "content-type": "application/octet-stream" } })));
+ await expect(call({ mime_type: undefined, file_name: "data.json" })).resolves.toMatchObject({ mimeType: "application/json" });
+ });
+
+ it("does not let declared octet-stream bypass the allowlisted type matrix", async () => {
+ await expect(call({ mime_type: "application/octet-stream", file_name: "file.bin" })).rejects.toThrow(/unsupported file type/i);
+ expect(uploadOneGuarded).not.toHaveBeenCalled();
+ });
+
+ it("rejects a conflicting trusted response MIME", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON_BYTES, { status: 200, headers: { "content-type": "application/json" } })));
+ await expect(call({ mime_type: "image/png", file_name: "file.png" })).rejects.toThrow(/does not match image\/png/i);
+ });
+
+ it("rejects declared sizes beyond the 20 MiB transfer cap before download", async () => {
+ await expect(call({ mime_type: "image/png", size: 20 * 1024 * 1024 + 1 })).rejects.toThrow(/20 MiB/i);
+ expect(fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/lib/mcp/openai-file-upload.test.ts b/lib/mcp/openai-file-upload.test.ts
index 60d0727b..b32ed592 100644
--- a/lib/mcp/openai-file-upload.test.ts
+++ b/lib/mcp/openai-file-upload.test.ts
@@ -1,189 +1,84 @@
type FsApiModule = typeof import("@/lib/host/fs-api");
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import sharp from "sharp";
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
-const uploadInto = vi.fn(async () => ({ written: 1, failed: [] as string[] }));
+const uploadOneGuarded = vi.fn(async (input: Record<string, unknown>) => ({
+ path: `/home/example/${String(input.filename)}`, filename: String(input.filename),
+ status: "created", sha256: "a".repeat(64),
+}));
vi.mock("@/lib/host/fs-api", async (orig) => {
const real = await orig<FsApiModule>();
- return { ...real, uploadInto };
+ return { ...real, uploadOneGuarded };
});
const { importOpenAiProvidedFile } = await import("./openai-file-upload");
-
-const PNG = Uint8Array.from([137, 80, 78, 71, 13, 10, 26, 10]);
-const JPEG = Uint8Array.from([0xff, 0xd8, 0xff, 0x00]);
-const WEBP = new TextEncoder().encode("RIFF0000WEBP");
-const JSON_BYTES = new TextEncoder().encode('{"ok":true}');
-const ZIP = Uint8Array.from([0x50, 0x4b, 0x03, 0x04, 0x00]);
-
+let PNG: Buffer, JPEG: Buffer, WEBP: Buffer;
+const JSON_BYTES = Buffer.from('{"ok":true}');
+const ZIP = Buffer.from([0x50,0x4b,0x05,0x06,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);
+
+beforeAll(async () => {
+ const source = { create: { width: 2, height: 2, channels: 4 as const, background: { r: 4, g: 8, b: 12, alpha: 0.5 } } };
+ PNG = await sharp(source).png().toBuffer();
+ JPEG = await sharp(source).jpeg().toBuffer();
+ WEBP = await sharp(source).webp({ lossless: true }).toBuffer();
+});
beforeEach(() => {
- uploadInto.mockClear();
+ uploadOneGuarded.mockClear();
delete process.env.OS_MCP_OPENAI_FILE_HOSTS;
- vi.stubGlobal("fetch", vi.fn(async () => new Response(PNG, {
- status: 200,
- headers: { "content-type": "image/png", "content-length": String(PNG.byteLength) },
- })));
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(new Uint8Array(PNG), { status: 200, headers: { "content-type": "image/png" } })));
});
afterEach(() => vi.unstubAllGlobals());
-function importFile(input: {
- download_url?: string;
- file_id?: string;
- mime_type?: string;
- file_name?: string;
- size?: number;
-}, allowChatGptAzureFamily = false) {
+function run(file: Record<string, unknown>, options: Record<string, unknown> = {}) {
return importOpenAiProvidedFile({
- file: {
- download_url: input.download_url || "https://files.oaiusercontent.com/file",
- file_id: input.file_id || "file_test",
- mime_type: input.mime_type,
- file_name: input.file_name || "file.png",
- size: input.size,
- },
- dest: "/home/example/generated-files",
- allowChatGptAzureFamily,
+ file: { download_url: "https://files.oaiusercontent.com/file", file_id: "file_test", file_name: "file.png", ...file },
+ dest: "/home/example/generated-files", ...options,
});
}
-describe("ChatGPT file host allowlist", () => {
- it("accepts OpenAI oaiusercontent content hosts by default", async () => {
- await expect(importFile({ download_url: "https://files.oaiusercontent.com/file.png", mime_type: "image/png" })).resolves.toMatchObject({ bytes: 8 });
- });
-
- it.each(["oaisdmntprkoreacentral.blob.core.windows.net", "oaisdmntprjapaneast.blob.core.windows.net"])
- ("accepts rotating ChatGPT Azure host %s only with trusted fileParams provenance", async (host) => {
- await expect(importFile({ download_url: `https://${host}/container/file.png?sig=redacted`, mime_type: "image/png" }, true))
- .resolves.toMatchObject({ bytes: 8 });
- });
-
-
- it("rejects Azure account-name prefixes unless the exact host is configured", async () => {
- await expect(importFile({ download_url: "https://oaisdmntprseasia.blob.core.windows.net/container/file.png", mime_type: "image/png" }))
- .rejects.toThrow("host is not allowed");
- });
-
- it("accepts only an exact configured Azure Blob hostname", async () => {
+describe("ChatGPT upload trust and validation", () => {
+ it("requires exact Azure host allowlisting", async () => {
+ await expect(run({ download_url: "https://oaisdmntprseasia.blob.core.windows.net/f.png", mime_type: "image/png" })).rejects.toThrow(/host is not allowed/i);
process.env.OS_MCP_OPENAI_FILE_HOSTS = "oaisdmntprseasia.blob.core.windows.net";
- await expect(importFile({ download_url: "https://oaisdmntprseasia.blob.core.windows.net/container/file.png?sig=redacted", mime_type: "image/png" }))
- .resolves.toMatchObject({ bytes: 8 });
- await expect(importFile({ download_url: "https://oaisdmntprfuture123.blob.core.windows.net/container/file.png", mime_type: "image/png" }))
- .rejects.toThrow("host is not allowed");
+ await expect(run({ download_url: "https://oaisdmntprseasia.blob.core.windows.net/f.png", mime_type: "image/png" })).resolves.toMatchObject({ mimeType: "image/png" });
});
-
- it("rejects malformed configured Azure host entries fail-closed", async () => {
- process.env.OS_MCP_OPENAI_FILE_HOSTS = "*.blob.core.windows.net";
- await expect(importFile({ download_url: "https://files.oaiusercontent.com/file.png", mime_type: "image/png" }))
- .resolves.toMatchObject({ bytes: 8 });
- await expect(importFile({ download_url: "https://oaisdmntprseasia.blob.core.windows.net/file.png", mime_type: "image/png" }))
- .rejects.toThrow("invalid Azure Blob hostname");
- });
-
- it("rejects a redirect from an allowed OpenAI host to an unconfigured Azure host", async () => {
- vi.stubGlobal("fetch", vi.fn(async () => new Response(null, {
- status: 302,
- headers: { location: "https://attacker.blob.core.windows.net/container/file.png" },
- })));
- await expect(importFile({ download_url: "https://files.oaiusercontent.com/start/file.png", mime_type: "image/png" }))
- .rejects.toThrow("host is not allowed: attacker.blob.core.windows.net");
- });
-
- it("keeps the ChatGPT Azure exception scoped to the oaisdmntpr account family", async () => {
- await expect(importFile({ download_url: "https://attacker.blob.core.windows.net/container/file.png?sig=redacted", mime_type: "image/png" }, true))
- .rejects.toThrow("host is not allowed");
- });
-
-
- it("allows a redirect to an exact configured Azure host", async () => {
- process.env.OS_MCP_OPENAI_FILE_HOSTS = "oaisdmntprseasia.blob.core.windows.net";
- const fetchMock = vi.fn()
- .mockResolvedValueOnce(new Response(null, {
- status: 302,
- headers: { location: "https://oaisdmntprseasia.blob.core.windows.net/container/file.png?sig=next" },
- }))
- .mockResolvedValueOnce(new Response(PNG, {
- status: 200,
- headers: { "content-type": "image/png", "content-length": "8" },
- }));
- vi.stubGlobal("fetch", fetchMock);
- await expect(importFile({ download_url: "https://files.oaiusercontent.com/start/file.png", mime_type: "image/png" })).resolves.toMatchObject({ bytes: 8 });
- expect(fetchMock).toHaveBeenCalledTimes(2);
- });
-});
-
-describe("explicit ChatGPT file MIME matrix", () => {
it.each([
- ["image/png", "file.png", PNG],
- ["image/jpeg", "file.jpg", JPEG],
- ["image/webp", "file.webp", WEBP],
- ["application/json", "file.json", JSON_BYTES],
- ["application/zip", "file.zip", ZIP],
- ])("accepts %s with matching content", async (mimeType, fileName, data) => {
- vi.stubGlobal("fetch", vi.fn(async () => new Response(data, {
- status: 200,
- headers: { "content-type": mimeType, "content-length": String(data.byteLength) },
- })));
- await expect(importFile({ mime_type: mimeType, file_name: fileName, size: data.byteLength })).resolves.toMatchObject({ mimeType, bytes: data.byteLength });
- });
-
- it("normalizes the common ZIP MIME alias", async () => {
- vi.stubGlobal("fetch", vi.fn(async () => new Response(ZIP, {
- status: 200,
- headers: { "content-type": "application/x-zip-compressed" },
- })));
- await expect(importFile({ mime_type: "application/x-zip-compressed", file_name: "file.zip" })).resolves.toMatchObject({ mimeType: "application/zip" });
- });
-
- it("infers a supported type from the filename when ChatGPT omits mime_type", async () => {
- vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON_BYTES, {
- status: 200,
- headers: { "content-type": "application/octet-stream" },
- })));
- await expect(importFile({ file_name: "data.json" })).resolves.toMatchObject({ mimeType: "application/json" });
- });
-
- it("rejects generic declared octet-stream instead of bypassing the matrix", async () => {
- await expect(importFile({ mime_type: "application/octet-stream", file_name: "file.bin" })).rejects.toThrow("unsupported file type");
- expect(uploadInto).not.toHaveBeenCalled();
- });
-
- it("rejects invalid JSON content", async () => {
- vi.stubGlobal("fetch", vi.fn(async () => new Response(new TextEncoder().encode("{broken"), {
- status: 200,
- headers: { "content-type": "application/json" },
- })));
- await expect(importFile({ mime_type: "application/json", file_name: "file.json" })).rejects.toThrow("content does not match application/json");
- });
-
- it("rejects invalid ZIP content", async () => {
- vi.stubGlobal("fetch", vi.fn(async () => new Response(new TextEncoder().encode("not zip"), {
- status: 200,
- headers: { "content-type": "application/zip" },
- })));
- await expect(importFile({ mime_type: "application/zip", file_name: "file.zip" })).rejects.toThrow("content does not match application/zip");
- });
-
- it("rejects a conflicting trusted response MIME", async () => {
- vi.stubGlobal("fetch", vi.fn(async () => new Response(JPEG, {
- status: 200,
- headers: { "content-type": "image/jpeg" },
- })));
- await expect(importFile({ mime_type: "image/png", file_name: "file.png" })).rejects.toThrow("does not match image/png");
- });
-
- it("stops a chunked response at 20 MiB even without Content-Length", async () => {
+ ["image/png", "file.png", () => PNG],
+ ["image/jpeg", "file.jpg", () => JPEG],
+ ["image/webp", "file.webp", () => WEBP],
+ ["application/json", "file.json", () => JSON_BYTES],
+ ["application/zip", "file.zip", () => ZIP],
+ ])("accepts fully valid %s", async (mimeType, fileName, bytes) => {
+ const data = bytes();
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(new Uint8Array(data), { status: 200, headers: { "content-type": mimeType } })));
+ await expect(run({ mime_type: mimeType, file_name: fileName }, { filename: fileName })).resolves.toMatchObject({ mimeType });
+ });
+ it("rejects magic-only corrupt raster data", async () => {
+ const corrupt = Buffer.from([0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a]);
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(new Uint8Array(corrupt), { status: 200, headers: { "content-type": "image/png" } })));
+ await expect(run({ mime_type: "image/png" })).rejects.toThrow(/content does not match/i);
+ });
+ it("rejects malformed ZIP without an end-of-central-directory record", async () => {
+ const bad = Buffer.from([0x50,0x4b,0x03,0x04,0,0,0,0]);
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(new Uint8Array(bad), { status: 200, headers: { "content-type": "application/zip" } })));
+ await expect(run({ mime_type: "application/zip", file_name: "file.zip" }, { filename: "file.zip" })).rejects.toThrow(/content does not match/i);
+ });
+ it("rejects invalid JSON and mismatched filename extension", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(new Uint8Array(Buffer.from("{bad")), { status: 200, headers: { "content-type": "application/json" } })));
+ await expect(run({ mime_type: "application/json", file_name: "file.json" }, { filename: "file.json" })).rejects.toThrow(/content does not match/i);
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(new Uint8Array(PNG), { status: 200, headers: { "content-type": "image/png" } })));
+ await expect(run({ mime_type: "image/png", file_name: "file.png" }, { filename: "wrong.zip" })).rejects.toThrow(/extension/i);
+ });
+ it("forwards guarded conflict and expected hash semantics", async () => {
+ await run({ mime_type: "image/png" }, { filename: "file.png", conflict: "replace", expectedSha256: "b".repeat(64) });
+ expect(uploadOneGuarded).toHaveBeenCalledWith(expect.objectContaining({ conflict: "replace", expectedSha256: "b".repeat(64) }));
+ });
+ it("stops a chunked response over 20 MiB", async () => {
const chunk = new Uint8Array(1024 * 1024);
- const body = new ReadableStream<Uint8Array>({
- start(controller) {
- for (let i = 0; i < 21; i += 1) controller.enqueue(chunk);
- controller.close();
- },
- });
- vi.stubGlobal("fetch", vi.fn(async () => new Response(body, {
- status: 200,
- headers: { "content-type": "image/png" },
- })));
- await expect(importFile({ mime_type: "image/png", file_name: "large.png" })).rejects.toThrow("exceeds the 20 MiB MCP import limit");
- expect(uploadInto).not.toHaveBeenCalled();
+ const body = new ReadableStream<Uint8Array>({ start(controller) { for (let i=0;i<21;i++) controller.enqueue(chunk); controller.close(); } });
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(body, { status: 200, headers: { "content-type": "image/png" } })));
+ await expect(run({ mime_type: "image/png" })).rejects.toThrow(/20 MiB/i);
+ expect(uploadOneGuarded).not.toHaveBeenCalled();
});
});
diff --git a/lib/mcp/openai-file-upload.ts b/lib/mcp/openai-file-upload.ts
index da32bcd3..586fd4ee 100644
--- a/lib/mcp/openai-file-upload.ts
+++ b/lib/mcp/openai-file-upload.ts
@@ -1,7 +1,6 @@
-import { createHash } from "crypto";
import path from "path";
import { HostError } from "@/lib/host/request-api";
-import { uploadInto } from "@/lib/host/fs-api";
+import { uploadOneGuarded, type UploadConflictPolicy } from "@/lib/host/fs-api";
export interface OpenAiProvidedFile {
download_url: string;
@@ -13,17 +12,14 @@ export interface OpenAiProvidedFile {
}
const MAX_FILE_BYTES = 20 * 1024 * 1024;
+const MAX_IMAGE_PIXELS = 25_000_000;
const SUPPORTED_MIME = new Set(["image/png", "image/webp", "image/jpeg", "application/json", "application/zip"]);
const WIRE_MIME = new Set([...SUPPORTED_MIME, "application/octet-stream"]);
const CHATGPT_AZURE_FILE_HOST = /^oaisdmntpr[a-z0-9]{2,40}\.blob\.core\.windows\.net$/;
const MIME_ALIASES = new Map([["application/x-zip-compressed", "application/zip"]]);
const EXTENSION_MIME = new Map([
- [".png", "image/png"],
- [".webp", "image/webp"],
- [".jpg", "image/jpeg"],
- [".jpeg", "image/jpeg"],
- [".json", "application/json"],
- [".zip", "application/zip"],
+ [".png", "image/png"], [".webp", "image/webp"], [".jpg", "image/jpeg"],
+ [".jpeg", "image/jpeg"], [".json", "application/json"], [".zip", "application/zip"],
]);
function providedFile(value: unknown): OpenAiProvidedFile {
@@ -33,48 +29,35 @@ function providedFile(value: unknown): OpenAiProvidedFile {
if (typeof row.file_id !== "string" || !row.file_id) throw new HostError("file.file_id is missing");
return row as OpenAiProvidedFile;
}
-
function normalizeMime(value: string): string {
const mime = value.split(";", 1)[0]?.trim().toLowerCase() || "";
return MIME_ALIASES.get(mime) || mime;
}
-
function configuredAzureHosts(): Set<string> {
const hosts = new Set<string>();
for (const raw of (process.env.OS_MCP_OPENAI_FILE_HOSTS || "").split(",")) {
const host = raw.trim().toLowerCase();
if (!host) continue;
- if (!/^[a-z0-9-]+\.blob\.core\.windows\.net$/.test(host)) {
- throw new HostError("OS_MCP_OPENAI_FILE_HOSTS contains an invalid Azure Blob hostname");
- }
+ if (!/^[a-z0-9-]+\.blob\.core\.windows\.net$/.test(host)) throw new HostError("OS_MCP_OPENAI_FILE_HOSTS contains an invalid Azure Blob hostname");
hosts.add(host);
}
return hosts;
}
-
function trustedDownloadUrl(raw: string, allowChatGptAzureFamily = false): URL {
let url: URL;
try { url = new URL(raw); } catch { throw new HostError("file.download_url is invalid"); }
if (url.protocol !== "https:") throw new HostError("file.download_url must use HTTPS");
const host = url.hostname.toLowerCase();
-
- // Generic MCP clients get only oaiusercontent + operator-exact Azure hosts.
- // The rotating oaisdmntpr Azure family is accepted only when the OAuth client
- // is proven to use a ChatGPT-owned callback and fileParams performed the bind.
const openAiContentHost = host === "files.oaiusercontent.com" || host.endsWith(".oaiusercontent.com");
const trustedChatGptAzure = allowChatGptAzureFamily && CHATGPT_AZURE_FILE_HOST.test(host);
- if (!openAiContentHost && !trustedChatGptAzure && !configuredAzureHosts().has(host)) {
- throw new HostError(`file.download_url host is not allowed: ${host}`);
- }
+ if (!openAiContentHost && !trustedChatGptAzure && !configuredAzureHosts().has(host)) throw new HostError(`file.download_url host is not allowed: ${host}`);
return url;
}
-
async function fetchTrustedFile(initialUrl: URL, allowChatGptAzureFamily = false): Promise<Response> {
let url = initialUrl;
for (let hop = 0; hop <= 3; hop += 1) {
const response = await fetch(url, {
- redirect: "manual",
- signal: AbortSignal.timeout(60_000),
+ redirect: "manual", signal: AbortSignal.timeout(60_000),
headers: { accept: "image/png,image/webp,image/jpeg,application/json,application/zip,application/octet-stream" },
});
if (![301, 302, 303, 307, 308].includes(response.status)) return response;
@@ -84,19 +67,14 @@ async function fetchTrustedFile(initialUrl: URL, allowChatGptAzureFamily = false
}
throw new HostError("OpenAI file download exceeded the redirect limit");
}
-
async function readBoundedBody(response: Response): Promise<Buffer> {
const rawLength = response.headers.get("content-length");
if (rawLength !== null) {
const declared = Number(rawLength);
- if (!Number.isFinite(declared) || declared < 0 || declared > MAX_FILE_BYTES) {
- throw new HostError("file exceeds the 20 MiB MCP import limit");
- }
+ if (!Number.isFinite(declared) || declared < 0 || declared > MAX_FILE_BYTES) throw new HostError("file exceeds the 20 MiB MCP import limit");
}
if (!response.body) throw new HostError("OpenAI file download was empty");
-
- const reader = response.body.getReader();
- const chunks: Uint8Array[] = [];
+ const reader = response.body.getReader(), chunks: Uint8Array[] = [];
let bytes = 0;
try {
for (;;) {
@@ -109,13 +87,10 @@ async function readBoundedBody(response: Response): Promise<Buffer> {
}
chunks.push(value);
}
- } finally {
- reader.releaseLock();
- }
+ } finally { reader.releaseLock(); }
if (bytes === 0) throw new HostError("OpenAI file download was empty");
return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)), bytes);
}
-
function responseMime(response: Response): string | null {
const value = response.headers.get("content-type");
if (!value) return null;
@@ -123,89 +98,64 @@ function responseMime(response: Response): string | null {
if (!WIRE_MIME.has(mime)) throw new HostError(`unsupported response file type: ${mime}`);
return mime;
}
-
function declaredMime(file: OpenAiProvidedFile): string {
const explicit = file.mime_type ? normalizeMime(file.mime_type) : "";
if (explicit) {
if (!SUPPORTED_MIME.has(explicit)) throw new HostError(`unsupported file type: ${explicit}`);
return explicit;
}
- const candidate = file.file_name || file.name || "";
- const inferred = EXTENSION_MIME.get(path.extname(candidate).toLowerCase());
+ const inferred = EXTENSION_MIME.get(path.extname(file.file_name || file.name || "").toLowerCase());
if (!inferred) throw new HostError("file type is missing or unsupported");
return inferred;
}
-
-function validateBody(data: Buffer, mimeType: string): boolean {
- if (mimeType === "image/png") {
- return data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]));
- }
+function hasImageSignature(data: Buffer, mimeType: string): boolean {
+ if (mimeType === "image/png") return data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a]));
if (mimeType === "image/jpeg") return data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff;
- if (mimeType === "image/webp") return data.length >= 12 && data.subarray(0, 4).toString("ascii") === "RIFF" && data.subarray(8, 12).toString("ascii") === "WEBP";
- if (mimeType === "application/zip") {
- return data.length >= 4 && data[0] === 0x50 && data[1] === 0x4b && [0x03, 0x05, 0x07].includes(data[2]) && [0x04, 0x06, 0x08].includes(data[3]);
- }
+ return data.length >= 12 && data.subarray(0, 4).toString("ascii") === "RIFF" && data.subarray(8, 12).toString("ascii") === "WEBP";
+}
+async function validRaster(data: Buffer, mimeType: string): Promise<boolean> {
+ if (!hasImageSignature(data, mimeType)) return false;
+ try {
+ const sharp = (await import("sharp")).default;
+ const decoded = await sharp(data, { failOn: "error", limitInputPixels: MAX_IMAGE_PIXELS, sequentialRead: true }).raw().toBuffer({ resolveWithObject: true });
+ return decoded.info.width > 0 && decoded.info.height > 0 && decoded.data.byteLength > 0;
+ } catch { return false; }
+}
+function validZip(data: Buffer): boolean {
+ if (data.length < 22) return false;
+ const eocd = data.lastIndexOf(Buffer.from([0x50,0x4b,0x05,0x06]));
+ if (eocd < Math.max(0, data.length - 65_557) || eocd + 22 > data.length) return false;
+ return eocd + 22 + data.readUInt16LE(eocd + 20) === data.length;
+}
+async function validateBody(data: Buffer, mimeType: string): Promise<boolean> {
+ if (mimeType.startsWith("image/")) return validRaster(data, mimeType);
+ if (mimeType === "application/zip") return validZip(data);
if (mimeType === "application/json") {
- try {
- const text = new TextDecoder("utf-8", { fatal: true }).decode(data);
- JSON.parse(text);
- return true;
- } catch {
- return false;
- }
+ try { JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(data)); return true; } catch { return false; }
}
return false;
}
-
-function safeFilename(input: string | undefined, fallback: string): string {
+function safeFilename(input: string | undefined, fallback: string, mimeType: string): string {
const value = path.basename((input || fallback).trim());
if (!value || value === "." || value === ".." || value.length > 200) throw new HostError("filename is invalid");
if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) throw new HostError("filename may contain only letters, digits, dot, dash and underscore");
+ if (EXTENSION_MIME.get(path.extname(value).toLowerCase()) !== mimeType) throw new HostError("filename extension does not match the validated file type");
return value;
}
export async function importOpenAiProvidedFile(opts: {
- file: unknown;
- dest: string;
- filename?: string;
- allowChatGptAzureFamily?: boolean;
-}): Promise<{
- ok: true;
- fileId: string;
- path: string;
- filename: string;
- mimeType: string;
- bytes: number;
- sha256: string;
-}> {
- const file = providedFile(opts.file);
- const url = trustedDownloadUrl(file.download_url, opts.allowChatGptAzureFamily === true);
- const mimeType = declaredMime(file);
- if (typeof file.size === "number" && (!Number.isFinite(file.size) || file.size < 0 || file.size > MAX_FILE_BYTES)) {
- throw new HostError("file exceeds the 20 MiB MCP import limit");
- }
-
+ file: unknown; dest: string; filename?: string; conflict?: UploadConflictPolicy; expectedSha256?: string; allowChatGptAzureFamily?: boolean;
+}) {
+ const file = providedFile(opts.file), url = trustedDownloadUrl(file.download_url, opts.allowChatGptAzureFamily === true), mimeType = declaredMime(file);
+ if (typeof file.size === "number" && (!Number.isFinite(file.size) || file.size < 0 || file.size > MAX_FILE_BYTES)) throw new HostError("file exceeds the 20 MiB MCP import limit");
const response = await fetchTrustedFile(url, opts.allowChatGptAzureFamily === true);
if (!response.ok) throw new HostError(`OpenAI file download failed (${response.status})`);
const wireMime = responseMime(response);
- if (wireMime && wireMime !== "application/octet-stream" && wireMime !== mimeType) {
- throw new HostError(`response file type ${wireMime} does not match ${mimeType}`);
- }
+ if (wireMime && wireMime !== "application/octet-stream" && wireMime !== mimeType) throw new HostError(`response file type ${wireMime} does not match ${mimeType}`);
const data = await readBoundedBody(response);
- if (!validateBody(data, mimeType)) throw new HostError(`file content does not match ${mimeType}`);
-
- const fallback = file.file_name || file.name || `${file.file_id}${[...EXTENSION_MIME.entries()].find(([, mime]) => mime === mimeType)?.[0] || ".bin"}`;
- const filename = safeFilename(opts.filename, fallback);
- const result = await uploadInto(opts.dest, [{ relPath: filename, data }]);
- if (result.written !== 1 || result.failed.length) throw new HostError(`file import failed: ${result.failed.join(", ") || "not written"}`);
-
- return {
- ok: true,
- fileId: file.file_id,
- path: path.join(opts.dest, filename),
- filename,
- mimeType,
- bytes: data.byteLength,
- sha256: createHash("sha256").update(data).digest("hex"),
- };
+ if (!(await validateBody(data, mimeType))) throw new HostError(`file content does not match ${mimeType}`);
+ const fallbackExt = [...EXTENSION_MIME.entries()].find(([, mime]) => mime === mimeType)?.[0] || ".bin";
+ const filename = safeFilename(opts.filename, file.file_name || file.name || `${file.file_id}${fallbackExt}`, mimeType);
+ const stored = await uploadOneGuarded({ dest: opts.dest, filename, data, conflict: opts.conflict, expectedSha256: opts.expectedSha256 });
+ return { ok: true as const, fileId: file.file_id, mimeType, bytes: data.byteLength, ...stored };
}
diff --git a/lib/mcp/tools-file-transfer.ts b/lib/mcp/tools-file-transfer.ts
index 93a72212..7a301334 100644
--- a/lib/mcp/tools-file-transfer.ts
+++ b/lib/mcp/tools-file-transfer.ts
@@ -2,44 +2,42 @@ import { createHash } from "node:crypto";
import path from "node:path";
import { mimeFor, readFileBytes } from "@/lib/host/fs-api";
import { createTempShare, tempShareUrl } from "@/lib/host/temp-share-api";
+import { createMcpFileResource } from "./file-transfer-resource";
import { mcpDirect, PATH_P, READ_ONLY, S, str, type McpTool } from "./tool-kit";
export const FILE_TRANSFER_READ_TOOLS: McpTool[] = [
{
name: "fs_export_file",
description:
- "Export one original VPS file (max 10 MiB) from OS_FS_READ_ROOTS to a private 15-minute approved-device temp-share. Returns SHA-256 and a download/resource link; no decoding, recompression or public URL.",
+ "Export one original VPS file (max 10 MiB) from OS_FS_READ_ROOTS. Returns an owner-bound 15-minute MCP binary resource plus an approved-device browser download; bytes are never decoded or recompressed.",
scope: "read",
annotations: READ_ONLY,
limit: { key: "fs.export", max: 20, windowMs: 60_000 },
inputSchema: S(PATH_P, ["path"]),
- run: async (a) => {
+ run: async (a, context) => {
+ if (!context.principal || !context.sessionId) throw new Error("authenticated MCP principal and session required");
const requested = str(a, "path");
const bytes = await readFileBytes(requested, 10 * 1024 * 1024);
- const filename = path.basename(requested);
- const mimeType = mimeFor(requested);
+ const filename = path.basename(requested), mimeType = mimeFor(requested);
+ const resource = await createMcpFileResource({
+ data: bytes, filename, mimeType, principal: context.principal, sessionId: context.sessionId, ttlMs: 15 * 60_000, maxReads: 5,
+ });
const share = await createTempShare({ data: bytes, filename, mimeType, ttlMs: 15 * 60_000, maxDownloads: 5 });
- const previewUrl = tempShareUrl(share.id);
- const downloadUrl = tempShareUrl(share.id, true);
- const sha256 = createHash("sha256").update(bytes).digest("hex");
const result = {
- path: requested,
- filename,
- mimeType,
- bytes: bytes.byteLength,
- sha256,
- previewUrl,
- downloadUrl,
- expiresAt: share.expiresAt,
- downloadsLeft: share.downloadsLeft,
+ path: requested, filename, mimeType, bytes: bytes.byteLength,
+ sha256: createHash("sha256").update(bytes).digest("hex"),
+ resourceUri: resource.uri,
+ resourceExpiresAt: resource.expiresAt,
+ resourceReadsLeft: resource.readsLeft,
+ browserPreviewUrl: tempShareUrl(share.id),
+ browserDownloadUrl: tempShareUrl(share.id, true),
+ browserExpiresAt: share.expiresAt,
+ browserDownloadsLeft: share.downloadsLeft,
};
return mcpDirect([
{
- type: "resource_link",
- uri: downloadUrl,
- name: filename,
- description: "Authenticated original-byte download; requires an approved MSO browser session and expires automatically.",
- mimeType,
+ type: "resource_link", uri: resource.uri, name: filename,
+ description: "Owner-bound MCP original bytes. Read with resources/read before expiry.", mimeType,
},
{ type: "text", text: JSON.stringify(result) },
], false, { result });
diff --git a/lib/mcp/tools-mutate.ts b/lib/mcp/tools-mutate.ts
index 6bd5948b..21d56f9b 100644
--- a/lib/mcp/tools-mutate.ts
+++ b/lib/mcp/tools-mutate.ts
@@ -34,11 +34,9 @@ export const MUTATE_TOOLS: McpTool[] = [
name: "fs_upload_file",
limit: { key: "fs.upload", max: 20, windowMs: 60_000 },
audit: { action: "fs.upload" as const, targetArg: "dest" },
- description:
- "Import one ChatGPT conversation/generated PNG, WebP, JPEG, JSON or ZIP file into an existing VPS directory. " +
- "ChatGPT binds the top-level file through openai/fileParams; MSO validates temporary URL provenance, type, size and content before writing inside OS_FS_WRITE_ROOTS. Verified ChatGPT OAuth callbacks may use its rotating Azure file hosts; generic MCP clients require exact Azure allowlisting. Returns bytes + SHA-256; existing same-name files may be replaced.",
+ description: "Import one ChatGPT conversation/generated PNG, WebP, JPEG, JSON or ZIP file through openai/fileParams. MSO validates OAuth-bound temporary URL provenance, type, size and content before writing inside OS_FS_WRITE_ROOTS. Verified ChatGPT callbacks may use rotating Azure file hosts; generic MCP clients require exact allowlisting. Same bytes are idempotent; different existing bytes fail by default. conflict=rename is deterministic; conflict=replace requires expected_sha256.",
scope: "write",
- annotations: { destructiveHint: true, openWorldHint: true },
+ annotations: { destructiveHint: true, openWorldHint: true, idempotentHint: true },
meta: { "openai/fileParams": ["file"] },
inputSchema: S({
file: {
@@ -56,13 +54,16 @@ export const MUTATE_TOOLS: McpTool[] = [
additionalProperties: true,
},
dest: { type: "string", description: "Existing destination directory on the VPS, within OS_FS_WRITE_ROOTS." },
- filename: { type: "string", description: "Optional safe destination basename; defaults to the ChatGPT filename." },
+ filename: { type: "string", description: "Optional safe destination basename; extension must match the validated file type." },
+ conflict: { type: "string", enum: ["error", "rename", "replace"], description: "Default error. rename chooses a deterministic content-hash suffix. replace requires expected_sha256." },
+ expected_sha256: { type: "string", description: "Required only for conflict=replace; SHA-256 from a prior read/export of the current destination." },
}, ["file", "dest"]),
run: async (a, context) => importOpenAiProvidedFile({
file: a.file,
dest: str(a, "dest"),
filename: opt(a, "filename"),
- allowChatGptAzureFamily: context.trustedOpenAiFileParams === true,
+ conflict: opt(a, "conflict") as "error" | "rename" | "replace" | undefined,
+ expectedSha256: opt(a, "expected_sha256"), allowChatGptAzureFamily: context.trustedOpenAiFileParams === true,
}),
},
{
diff --git a/lib/mcp/tools-read-export.test.ts b/lib/mcp/tools-read-export.test.ts
index 9d0512f1..24f17f4d 100644
--- a/lib/mcp/tools-read-export.test.ts
+++ b/lib/mcp/tools-read-export.test.ts
@@ -2,59 +2,43 @@ import { describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
const mocks = vi.hoisted(() => ({
- readFileBytes: vi.fn(async () => Buffer.from([0x50, 0x4b, 0x03, 0x04, 0x01, 0x02])),
+ readFileBytes: vi.fn(async () => Buffer.from([0x50,0x4b,0x05,0x06, ...new Array(18).fill(0)])),
mimeFor: vi.fn(() => "application/zip"),
+ createMcpFileResource: vi.fn(async () => ({
+ id: "abc", uri: "mso-file:///aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ filename: "archive.zip", mimeType: "application/zip", sha256: "a".repeat(64), bytes: 22,
+ createdAt: 1, expiresAt: 901000, readsLeft: 5,
+ })),
createTempShare: vi.fn(async () => ({
- id: "abcdefghijklmnopqrstuvwxyzABCDEF",
- name: "archive.zip",
- mimeType: "application/zip",
- createdAt: 1,
- expiresAt: 901_000,
- downloadsLeft: 5,
- bytes: 6,
+ id: "abcdefghijklmnopqrstuvwxyzABCDEF", name: "archive.zip", mimeType: "application/zip",
+ createdAt: 1, expiresAt: 901000, downloadsLeft: 5, bytes: 22,
})),
tempShareUrl: vi.fn((id: string, download = false) => `https://mso.example.test/api/v1/temp-share/${id}${download ? "?download=1" : ""}`),
}));
-
vi.mock("@/lib/host/fs-api", async (orig) => {
const real = await orig<typeof import("@/lib/host/fs-api")>();
return { ...real, readFileBytes: mocks.readFileBytes, mimeFor: mocks.mimeFor };
});
vi.mock("@/lib/host/temp-share-api", () => ({ createTempShare: mocks.createTempShare, tempShareUrl: mocks.tempShareUrl }));
+vi.mock("./file-transfer-resource", () => ({ createMcpFileResource: mocks.createMcpFileResource }));
const { FILE_TRANSFER_READ_TOOLS } = await import("./tools-file-transfer");
-
describe("fs_export_file", () => {
- it("returns an authenticated original-byte resource link plus checksum metadata", async () => {
- const tool = FILE_TRANSFER_READ_TOOLS.find((row) => row.name === "fs_export_file");
- expect(tool).toBeDefined();
- expect(tool?.scope).toBe("read");
- expect(tool?.annotations).toMatchObject({ readOnlyHint: true });
-
- const result = await tool!.run({ path: "/home/example/archive.zip" }, { scope: "read" }) as {
- __mcpDirect: true;
- content: Array<Record<string, unknown>>;
- structuredContent?: { result?: Record<string, unknown> };
- };
- expect(mocks.readFileBytes).toHaveBeenCalledWith("/home/example/archive.zip", 10 * 1024 * 1024);
- expect(mocks.createTempShare).toHaveBeenCalledWith(expect.objectContaining({
- filename: "archive.zip",
- mimeType: "application/zip",
- ttlMs: 15 * 60_000,
- maxDownloads: 5,
- }));
+ it("returns an owner-bound MCP resource link and separate browser fallback", async () => {
+ const tool = FILE_TRANSFER_READ_TOOLS.find((row) => row.name === "fs_export_file")!;
+ const result = await tool.run({ path: "/home/example/archive.zip" }, { scope: "read", principal: "alice", sessionId: "session-a" }) as any;
+ expect(mocks.createMcpFileResource).toHaveBeenCalledWith(expect.objectContaining({ principal: "alice", sessionId: "session-a", filename: "archive.zip" }));
expect(result.content[0]).toMatchObject({
- type: "resource_link",
- uri: "https://mso.example.test/api/v1/temp-share/abcdefghijklmnopqrstuvwxyzABCDEF?download=1",
- name: "archive.zip",
- mimeType: "application/zip",
+ type: "resource_link", uri: "mso-file:///aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ name: "archive.zip", mimeType: "application/zip",
});
- expect(result.structuredContent?.result).toMatchObject({
- filename: "archive.zip",
- mimeType: "application/zip",
- bytes: 6,
- sha256: "72ddd979de80b61ca55ce309f4c2a029c78a7ef9b6259e0a3d5e17a191a4cfdf",
- downloadsLeft: 5,
+ expect(result.structuredContent.result).toMatchObject({
+ resourceUri: "mso-file:///aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ browserDownloadUrl: "https://mso.example.test/api/v1/temp-share/abcdefghijklmnopqrstuvwxyzABCDEF?download=1",
});
});
+ it("requires an authenticated MCP principal", async () => {
+ const tool = FILE_TRANSFER_READ_TOOLS.find((row) => row.name === "fs_export_file")!;
+ await expect(tool.run({ path: "/home/example/archive.zip" }, { scope: "read" })).rejects.toThrow(/principal/i);
+ });
});
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index cd684d5a..dbd82249 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -5,7 +5,7 @@ import { toolDescriptor, type McpToolProfile } from "./tool-contract";
export const MCP_SERVER_VERSION = "1.14.2";
export const MCP_TOOLSET_VERSION = "2026.09.15.1";
-export const MCP_TOOLSET_CHANGED_AT = "2026-09-15T00:10:00+07:00";
+export const MCP_TOOLSET_CHANGED_AT = "2026-09-15T00:30:00+07:00";
export type McpToolsetInfo = {
serverVersion: string;