Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix: close conversation file handles when a download never starts (#7030)

Ooi Pin Jund8f803ce2bc9
diff --git a/server/bot-attachment.test.ts b/server/bot-attachment.test.ts
index d62d9eef32..90890d2c16 100644
--- a/server/bot-attachment.test.ts
+++ b/server/bot-attachment.test.ts
@@ -2,13 +2,29 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync,
import { tmpdir } from "node:os";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+const sourceHandles = vi.hoisted(() => ({
+ record: false,
+ opened: [] as { path: string; handle: import("node:fs/promises").FileHandle }[],
+}));
+vi.mock("node:fs/promises", async (original) => {
+ const real = await original<typeof import("node:fs/promises")>();
+ return {
+ ...real,
+ open: async (...args: Parameters<typeof real.open>) => {
+ const handle = await real.open(...args);
+ if (sourceHandles.record) sourceHandles.opened.push({ path: String(args[0]), handle });
+ return handle;
+ },
+ };
+});
// attachments.ts reads DATA_DIR at import time.
const DATA_ROOT = mkdtempSync(join(tmpdir(), "omb-bot-attachment-"));
process.env.OMB_DATA_DIR = join(DATA_ROOT, "data");
const { attachForTurn, contentUploadId, deliveredCopy, guestWorkspaceToHost, saveBotAttachment } = await import("./bot-attachment.ts");
-const { ATTACHMENTS_DIR, FILE_MAX_BYTES, PREVIEW_MAX_BYTES } = await import("./attachments.ts");
+const { ATTACHMENTS_DIR, ATTACHMENTS_MAX_BYTES, FILE_MAX_BYTES, PREVIEW_MAX_BYTES, __resetAttachmentAccountingForTests } = await import("./attachments.ts");
const WORK = join(DATA_ROOT, "work");
const VM_HOME = join(DATA_ROOT, "vm-home");
@@ -146,6 +162,34 @@ describe("saveBotAttachment", () => {
await expect(saveBotAttachment({ path: " ", roots: [WORK] })).rejects.toMatchObject({ status: 400 });
expect(existsSync(ATTACHMENTS_DIR)).toBe(true);
});
+
+ it("closes the source when the store is full before the file is read", async () => {
+ const source = join(WORK, "quota.pdf");
+ writeFileSync(source, Buffer.alloc(64 * 1024, 7));
+ mkdirSync(ATTACHMENTS_DIR, { recursive: true });
+ const filler = join(ATTACHMENTS_DIR, "quota-filler.bin");
+ writeFileSync(filler, Buffer.alloc(1));
+ truncateSync(filler, ATTACHMENTS_MAX_BYTES);
+ __resetAttachmentAccountingForTests();
+ sourceHandles.record = true;
+ sourceHandles.opened.length = 0;
+ try {
+ await expect(saveBotAttachment({ path: "quota.pdf", roots: [WORK] })).rejects.toMatchObject({
+ status: 507,
+ message: expect.stringMatching(/storage is full/),
+ });
+ const handle = sourceHandles.opened.find((entry) => entry.path === realpathSync(source))?.handle;
+ expect(handle).toBeDefined();
+ expect(handle!.fd).toBe(-1);
+ } finally {
+ sourceHandles.record = false;
+ rmSync(filler, { force: true });
+ __resetAttachmentAccountingForTests();
+ for (const entry of sourceHandles.opened) {
+ if (entry.handle.fd !== -1) await entry.handle.close().catch(() => undefined);
+ }
+ }
+ });
});
describe("saveBotAttachment by content", () => {
diff --git a/server/cloud-computer-files.test.ts b/server/cloud-computer-files.test.ts
index b6d695555c..65b68eef5b 100644
--- a/server/cloud-computer-files.test.ts
+++ b/server/cloud-computer-files.test.ts
@@ -1,11 +1,24 @@
// A loopback Boat stands in for the provider, for the Cloud's relay and for the sandbox that serves transfer links; every
// folder is a fresh temporary one.
import { randomBytes } from "node:crypto";
-import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, truncateSync, writeFileSync, writeSync } from "node:fs";
+import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, truncateSync, writeFileSync, writeSync } from "node:fs";
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+const openedFiles = vi.hoisted(() => [] as { path: string; handle: import("node:fs/promises").FileHandle }[]);
+vi.mock("node:fs/promises", async (original) => {
+ const real = await original<typeof import("node:fs/promises")>();
+ return {
+ ...real,
+ open: async (...args: Parameters<typeof real.open>) => {
+ const handle = await real.open(...args);
+ openedFiles.push({ path: String(args[0]), handle });
+ return handle;
+ },
+ };
+});
import type { AppConfig } from "./config.ts";
const BOX = "bx_23456789";
@@ -31,6 +44,8 @@ let duringDownload: (() => void) | undefined;
let midDownload: (() => Promise<void>) | undefined;
/** Runs when the sandbox gets an upload's first bytes. */
let onFirstUploadChunk: (() => void) | undefined;
+/** The sandbox refuses an upload before reading any of it. */
+let rejectUpload = false;
/** Holds the sandbox's answer to a transfer until released. */
let stall: Promise<void> | undefined;
/** What the sandbox received for each upload, by path. */
@@ -69,6 +84,12 @@ async function sandbox(req: IncomingMessage, res: ServerResponse, url: URL) {
return;
}
if (verb === "put" && req.method === "PUT") {
+ if (rejectUpload) {
+ res.writeHead(500);
+ res.end();
+ req.destroy();
+ return;
+ }
let bytes = 0, chunks = 0, head = Buffer.alloc(0), tail = Buffer.alloc(0);
for await (const part of req) {
const chunk = part as Buffer;
@@ -129,6 +150,8 @@ beforeEach(() => {
disk.clear();
uploads.clear();
expireLinks = false;
+ rejectUpload = false;
+ openedFiles.length = 0;
mintAnswer = duringDownload = midDownload = onFirstUploadChunk = stall = undefined;
root = mkdtempSync(join(tmpdir(), "omb-computer-files-"));
folder = join(root, "folder");
@@ -136,7 +159,10 @@ beforeEach(() => {
mkdirSync(folder);
mkdirSync(outside);
});
-afterEach(() => { rmSync(root, { recursive: true, force: true }); });
+afterEach(async () => {
+ await Promise.all(openedFiles.splice(0).map((entry) => (entry.handle.fd === -1 ? undefined : entry.handle.close().catch(() => undefined))));
+ rmSync(root, { recursive: true, force: true });
+});
afterAll(async () => {
vi.unstubAllEnvs();
server.closeAllConnections();
@@ -330,6 +356,30 @@ describe("copy_to_computer", () => {
expect(calls).toEqual([]);
});
+ it("closes the source when the upload is refused before its body is read", async () => {
+ const source = join(folder, "notes.txt");
+ writeFileSync(source, "hello cloud\n");
+ rejectUpload = true;
+ openedFiles.length = 0;
+ const result = await to("notes.txt", "work/notes.txt");
+ expect(result).toEqual({ error: "The cloud computer answered 500 to the copy. Try again in a minute." });
+ const handle = openedFiles.find((entry) => entry.path === realpathSync(source))?.handle;
+ expect(handle).toBeDefined();
+ expect(handle!.fd).toBe(-1);
+ });
+
+ it("closes the source when the upload is aborted after reading begins", async () => {
+ const source = join(folder, "stream.bin");
+ writeFileSync(source, Buffer.alloc(256 * 1024, 0x62));
+ const controller = new AbortController();
+ onFirstUploadChunk = () => controller.abort();
+ openedFiles.length = 0;
+ await expect(files.copyToComputer(own, BOX, folder, { from: "stream.bin", path: "work/stream.bin" }, controller.signal)).rejects.toMatchObject({ name: "AbortError" });
+ const handle = openedFiles.find((entry) => entry.path === realpathSync(source))?.handle;
+ expect(handle).toBeDefined();
+ expect(handle!.fd).toBe(-1);
+ });
+
it("reads nothing outside the folder, under its secret folder, or that is not a file", async () => {
writeFileSync(join(outside, "secret.txt"), "private");
symlinkSync(join(outside, "secret.txt"), join(folder, "linked.txt"));
diff --git a/server/page-files.test.ts b/server/page-files.test.ts
index f91fad6627..8741a0e60c 100644
--- a/server/page-files.test.ts
+++ b/server/page-files.test.ts
@@ -3,7 +3,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { Writable } from "node:stream";
import { finished } from "node:stream/promises";
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { AppDocs } from "./app-docs.ts";
import { createPageFiles, pageFilePath, PAGE_FILES_PREFIX } from "./page-files.ts";
@@ -15,6 +15,10 @@ vi.mock("node:fs/promises", async (original) => {
return { ...real, open: async (...args: Parameters<typeof real.open>) => { const handle = await real.open(...args); opened.push(handle); return handle; } };
});
+afterEach(async () => {
+ await Promise.all(opened.splice(0).map((handle) => (handle.fd === -1 ? undefined : handle.close().catch(() => undefined))));
+});
+
const PARQUET = Buffer.from("PAR1\u0000\u0001\u0002\u0003 rows and columns PAR1", "latin1");
function setup(more: Array<{ path: string; data: Buffer }> = []) {
@@ -236,4 +240,16 @@ describe("a folder page's video", () => {
res.destroy();
await expect.poll(() => opened[0]!.fd).toBe(-1);
});
+
+ it("closes the file when the response cannot be started", async () => {
+ const { files, folder } = setupVideo();
+ const res = Object.assign(new Writable({ write(_chunk, _encoding, callback) { callback(); } }), {
+ writeHead() { throw new Error("writeHead failed"); },
+ });
+ opened.length = 0;
+ files.serve({ headers: {} } as never, res as never, `${folder}clip.mp4`, "GET");
+ await expect.poll(() => res.destroyed).toBe(true);
+ expect(opened).toHaveLength(1);
+ expect(opened[0]!.fd).toBe(-1);
+ });
});
diff --git a/server/page-files.ts b/server/page-files.ts
index e06f6369cc..ef2e338d46 100644
--- a/server/page-files.ts
+++ b/server/page-files.ts
@@ -15,7 +15,7 @@ import { constants as fsConstants } from "node:fs";
import { open, type FileHandle } from "node:fs/promises";
import type { IncomingMessage, ServerResponse } from "node:http";
import { extname } from "node:path";
-import { pipeline } from "node:stream";
+import { pipeline } from "node:stream/promises";
import { PAGE_FILE_TYPES } from "../shared/published-page.ts";
import type { AppDocs } from "./app-docs.ts";
@@ -105,22 +105,25 @@ export function createPageFiles(deps: { docs: AppDocs; now?: () => number }) {
const sendVideo = async (req: IncomingMessage, res: ServerResponse, video: PageVideo, type: string, method: string) => {
const handle = await openRecordedVideo(video);
if (!handle) return answer(res, 404, "Not found.");
- const size = video.bytes, headers = { ...SHARED_HEADERS, "content-type": type, "accept-ranges": "bytes" };
- const part = req.headers.range === undefined ? null : rangeOf(String(req.headers.range), size);
- if (req.headers.range !== undefined && !part) {
- await handle.close().catch(() => {});
- res.writeHead(416, { ...headers, "content-range": `bytes */${size}` });
- res.end();
- return;
- }
- const start = part?.start ?? 0, end = part?.end ?? size - 1;
- res.writeHead(part ? 206 : 200, { ...headers, "content-length": String(end - start + 1), ...(part ? { "content-range": `bytes ${start}-${end}/${size}` } : {}) });
- if (method === "HEAD" || size === 0) {
+ try {
+ if (res.destroyed) return;
+ const size = video.bytes, headers = { ...SHARED_HEADERS, "content-type": type, "accept-ranges": "bytes" };
+ const part = req.headers.range === undefined ? null : rangeOf(String(req.headers.range), size);
+ if (req.headers.range !== undefined && !part) {
+ res.writeHead(416, { ...headers, "content-range": `bytes */${size}` });
+ res.end();
+ return;
+ }
+ const start = part?.start ?? 0, end = part?.end ?? size - 1;
+ res.writeHead(part ? 206 : 200, { ...headers, "content-length": String(end - start + 1), ...(part ? { "content-range": `bytes ${start}-${end}/${size}` } : {}) });
+ if (method === "HEAD" || size === 0) {
+ res.end();
+ return;
+ }
+ await pipeline(handle.createReadStream({ start, end }), res);
+ } finally {
await handle.close().catch(() => {});
- res.end();
- return;
}
- pipeline(handle.createReadStream({ start, end }), res, () => {});
};
return {
diff --git a/server/routes/threads-file-handle.test.ts b/server/routes/threads-file-handle.test.ts
new file mode 100644
index 0000000000..e630b543c4
--- /dev/null
+++ b/server/routes/threads-file-handle.test.ts
@@ -0,0 +1,141 @@
+import { mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
+import type { IncomingMessage, ServerResponse } from "node:http";
+import { join } from "node:path";
+import { Readable, Writable } from "node:stream";
+import { pathToFileURL } from "node:url";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { DATA_DIR } from "../config.ts";
+import type { ModelSelection } from "../contracts.ts";
+import { json, readBody } from "../harness/http.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { Store } from "../store.ts";
+import { createThreadRoutes, type ThreadRouteDeps } from "./threads.ts";
+
+const sonnet: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };
+const highWaterMark = 16 * 1024;
+const auth = { kind: "loopback", scopes: ["admin"] } as RequestAuth;
+
+const captured = vi.hoisted(() => ({
+ handles: [] as import("node:fs/promises").FileHandle[],
+ path: "",
+ hold: null as Promise<void> | null,
+ signal: null as (() => void) | null,
+}));
+
+vi.mock("node:fs/promises", async (original) => {
+ const real = await original<typeof import("node:fs/promises")>();
+ return {
+ ...real,
+ open: async (...args: Parameters<typeof real.open>) => {
+ const handle = await real.open(...args);
+ if (captured.path !== "" && String(args[0]) === captured.path) {
+ captured.handles.push(handle);
+ captured.signal?.();
+ if (captured.hold) await captured.hold;
+ }
+ return handle;
+ },
+ };
+});
+
+let releaseHold = () => {};
+let pending: Promise<unknown> = Promise.resolve();
+
+beforeEach(() => {
+ rmSync(DATA_DIR, { recursive: true, force: true });
+ captured.handles.length = 0;
+ captured.path = "";
+ captured.hold = null;
+ captured.signal = null;
+ releaseHold = () => {};
+ pending = Promise.resolve();
+});
+
+afterEach(async () => {
+ releaseHold();
+ await pending.catch(() => undefined);
+ for (const handle of captured.handles) {
+ if (handle.fd !== -1) await handle.close().catch(() => undefined);
+ }
+});
+
+function response(onHead?: () => void): ServerResponse {
+ const res = Object.assign(new Writable({
+ highWaterMark,
+ write() { /* a client that stopped reading */ },
+ }), {
+ writeHead() {
+ onHead?.();
+ return res;
+ },
+ setHeader() { return res; },
+ });
+ return res as unknown as ServerResponse;
+}
+
+async function fixture() {
+ const store = new Store(() => sonnet);
+ const bot = store.createBot({ name: "Scout" }, { seedMessages: false });
+ const root = join(DATA_DIR, "task-workspaces", bot.id, bot.threadId);
+ mkdirSync(root, { recursive: true });
+ const inventory = join(root, "repo-inventory.md");
+ writeFileSync(inventory, Buffer.alloc(highWaterMark * 4, 0x61));
+ captured.path = realpathSync(inventory);
+ const message = store.appendMessage(bot.threadId, {
+ role: "bot",
+ kind: "text",
+ text: `[inventory](<${pathToFileURL(captured.path).href}>)`,
+ });
+ const deps = {
+ store,
+ viewerFor: () => ({}),
+ visibleTo: () => ({ bot: () => true, group: () => true, thread: () => true }),
+ workspaceAccess: () => null,
+ desktopMutationToken: () => undefined,
+ companionMutationToken: () => undefined,
+ cliOwnerToken: () => undefined,
+ messageFileRootsForThread: () => [root],
+ } as unknown as ThreadRouteDeps;
+ const handle = createThreadRoutes(deps);
+ const path = `/api/threads/${bot.threadId}/messages/${message.id}/file`;
+ const call = (res: ServerResponse) => {
+ const req = Readable.from([Buffer.from(JSON.stringify({ path: captured.path }))]) as IncomingMessage;
+ req.headers = { "content-type": "application/json" };
+ req.method = "POST";
+ const result = handle({
+ req, res, url: new URL(path, "http://127.0.0.1"), path, method: "POST", auth, json, readBody,
+ });
+ pending = result;
+ return result;
+ };
+ return { call };
+}
+
+describe("POST /api/threads/:threadId/messages/:messageId/file", () => {
+ it("closes the opened file when response setup throws", async () => {
+ const { call } = await fixture();
+ const sentinel = new Error("writeHead failed");
+ await expect(call(response(() => { throw sentinel; }))).rejects.toBe(sentinel);
+ expect(captured.handles).toHaveLength(1);
+ expect(captured.handles[0]!.fd).toBe(-1);
+ });
+
+ it("closes the opened file when the client leaves while it is still being opened", async () => {
+ const { call } = await fixture();
+ let release!: () => void;
+ const opened = new Promise<void>((resolve) => { captured.signal = resolve; });
+ captured.hold = new Promise<void>((resolve) => { release = resolve; releaseHold = resolve; });
+ const res = response();
+ const result = call(res);
+ await opened;
+ expect(captured.handles).toHaveLength(1);
+ expect(captured.handles[0]!.fd).toBeGreaterThan(-1);
+ const closed = new Promise((resolve) => res.once("close", resolve));
+ res.destroy();
+ await closed;
+ release();
+ await result;
+ expect(captured.handles[0]!.fd).toBe(-1);
+ });
+});
diff --git a/server/routes/threads.ts b/server/routes/threads.ts
index 3e01b6da39..8f3937b4db 100644
--- a/server/routes/threads.ts
+++ b/server/routes/threads.ts
@@ -1,5 +1,6 @@
import { userError } from "../user-errors.ts";
import { basename, join } from "node:path";
+import { pipeline } from "node:stream/promises";
import type { BotsResponse, SearchResponse, WireBot, WireGroup } from "../../shared/wire.ts";
import { NO_SUCH_BOT } from "../../shared/bot-read.ts";
@@ -276,88 +277,87 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
if (folderEntry === null) return json(res, 400, { error: "entry must be one file name" });
// An inline image is read whole by the browser; a saved file is streamed below, so it may be larger.
const maxBytes = streamsMessageImage ? MESSAGE_FILE_MAX_BYTES : MESSAGE_FILE_DOWNLOAD_MAX_BYTES;
- let file: Awaited<ReturnType<typeof openMessageFile>>;
+ let file: Awaited<ReturnType<typeof openMessageFile>> | undefined;
try {
- // What the person sent, even when a bot has since saved over the stored file.
- const kept = message.role === "user" && !folderEntry ? keptOriginal(href, ATTACHMENTS_DIR) : null;
- file = folderEntry
- ? await openMessageFolderEntry(href, folderEntry, roots, maxBytes)
- : kept ? await openMessageFile(kept, [KEPT_ORIGINALS_DIR], maxBytes) : await openMessageFile(href, roots, maxBytes);
- // Says the bytes are exactly what the person sent, so a comparison may call them that.
- if (kept) res.setHeader("x-openmausbot-kept-original", "1");
- } catch (error) {
- const code = (error as { code?: unknown } | null)?.code;
- const status = (error as { status?: unknown } | null)?.status;
- const name = message.role === "bot" && !botAttachment && !folderEntry && (code === "outside_workspace" || status === 404)
- ? referencedFileName(href)
- : null;
- const copy = name ? deliveredCopy(store.messagesFor(threadId), message, name, href) : null;
- if (copy) {
- file = await openMessageFile(copy.path, [ATTACHMENTS_DIR], maxBytes);
- downloadName = copy.name;
- } else {
- // Only a client that asks for listings gets one; older clients keep the 400.
- if (body?.listFolder !== true || folderEntry || code !== "directory") throw error;
- const listing = await listMessageFolder(href, roots);
- res.setHeader("x-openmausbot-folder", "1");
+ try {
+ // What the person sent, even when a bot has since saved over the stored file.
+ const kept = message.role === "user" && !folderEntry ? keptOriginal(href, ATTACHMENTS_DIR) : null;
+ file = folderEntry
+ ? await openMessageFolderEntry(href, folderEntry, roots, maxBytes)
+ : kept ? await openMessageFile(kept, [KEPT_ORIGINALS_DIR], maxBytes) : await openMessageFile(href, roots, maxBytes);
+ // Says the bytes are exactly what the person sent, so a comparison may call them that.
+ if (kept) res.setHeader("x-openmausbot-kept-original", "1");
+ } catch (error) {
+ const code = (error as { code?: unknown } | null)?.code;
+ const status = (error as { status?: unknown } | null)?.status;
+ const name = message.role === "bot" && !botAttachment && !folderEntry && (code === "outside_workspace" || status === 404)
+ ? referencedFileName(href)
+ : null;
+ const copy = name ? deliveredCopy(store.messagesFor(threadId), message, name, href) : null;
+ if (copy) {
+ file = await openMessageFile(copy.path, [ATTACHMENTS_DIR], maxBytes);
+ downloadName = copy.name;
+ } else {
+ // Only a client that asks for listings gets one; older clients keep the 400.
+ if (body?.listFolder !== true || folderEntry || code !== "directory") throw error;
+ const listing = await listMessageFolder(href, roots);
+ res.setHeader("x-openmausbot-folder", "1");
+ res.setHeader("cache-control", "private, no-store");
+ return json(res, 200, listing);
+ }
+ }
+ if (!file || res.destroyed) return;
+ if ((streamsMessageImage || botAttachment?.kind === "image") && !file.mime.startsWith("image/")) {
+ return json(res, 415, { error: "only images can be previewed here" });
+ }
+ if ((asksMediaLink || mediaGrant) && !STREAMABLE_MEDIA_MIMES.has(file.mime)) {
+ return json(res, 415, { error: "only videos and audio can be played here" });
+ }
+ if (asksMediaLink) {
+ const id = mediaLinks.issue({ threadId, messageId: message.id, path: href, ...(folderEntry ? { entry: folderEntry } : {}) }, auth);
+ res.setHeader("x-openmausbot-media", "1");
res.setHeader("cache-control", "private, no-store");
- return json(res, 200, listing);
+ return json(res, 200, { url: `/api/threads/${encodeURIComponent(threadId)}/messages/${encodeURIComponent(message.id)}/file?media=${id}`, mime: file.mime, bytes: file.bytes });
}
+ const inline = streamsMessageImage || Boolean(mediaGrant);
+ const rawRange = Array.isArray(req.headers.range) ? req.headers.range[0] : req.headers.range;
+ // Without a Range header (Save As) the whole file streams; a player's range never ties up more than one chunk.
+ const range = mediaGrant ? cappedMediaRange(parseAudioRange(rawRange, file.bytes)) : { kind: "none" as const };
+ if (range.kind === "unsatisfiable") {
+ res.writeHead(416, { "content-range": `bytes */${file.bytes}`, "cache-control": "private, no-store", "x-content-type-options": "nosniff" });
+ return res.end();
+ }
+ const [start, end] = range.kind === "range" ? [range.start, range.end] : [0, file.bytes - 1];
+ res.writeHead(range.kind === "range" ? 206 : 200, {
+ "content-type": file.mime,
+ "content-length": String(end - start + 1),
+ ...(range.kind === "range" ? { "content-range": `bytes ${start}-${end}/${file.bytes}` } : {}),
+ ...(mediaGrant ? { "accept-ranges": "bytes" } : {}),
+ "content-disposition": mediaGrant
+ ? messageFileDisposition(messageFileDownloadName(downloadName, file.name), "inline")
+ : inline ? "inline" : messageFileDisposition(messageFileDownloadName(downloadName, file.name)),
+ "cache-control": "private, no-store",
+ "cdn-cache-control": "no-store",
+ "cloudflare-cdn-cache-control": "no-store",
+ pragma: "no-cache",
+ vary: "Authorization",
+ "x-content-type-options": "nosniff",
+ ...(inline
+ ? {
+ "cross-origin-resource-policy": "same-origin",
+ "referrer-policy": "no-referrer",
+ }
+ : {}),
+ });
+ if (file.bytes === 0) return res.end();
+ try {
+ await pipeline(file.handle.createReadStream({ start, end, autoClose: true }), res);
+ } catch {
+ res.destroy();
+ }
+ } finally {
+ await file?.handle.close();
}
- if ((streamsMessageImage || botAttachment?.kind === "image") && !file.mime.startsWith("image/")) {
- await file.handle.close();
- return json(res, 415, { error: "only images can be previewed here" });
- }
- if ((asksMediaLink || mediaGrant) && !STREAMABLE_MEDIA_MIMES.has(file.mime)) {
- await file.handle.close();
- return json(res, 415, { error: "only videos and audio can be played here" });
- }
- if (asksMediaLink) {
- await file.handle.close();
- const id = mediaLinks.issue({ threadId, messageId: message.id, path: href, ...(folderEntry ? { entry: folderEntry } : {}) }, auth);
- res.setHeader("x-openmausbot-media", "1");
- res.setHeader("cache-control", "private, no-store");
- return json(res, 200, { url: `/api/threads/${encodeURIComponent(threadId)}/messages/${encodeURIComponent(message.id)}/file?media=${id}`, mime: file.mime, bytes: file.bytes });
- }
- const inline = streamsMessageImage || Boolean(mediaGrant);
- const rawRange = Array.isArray(req.headers.range) ? req.headers.range[0] : req.headers.range;
- // Without a Range header (Save As) the whole file streams; a player's range never ties up more than one chunk.
- const range = mediaGrant ? cappedMediaRange(parseAudioRange(rawRange, file.bytes)) : { kind: "none" as const };
- if (range.kind === "unsatisfiable") {
- await file.handle.close();
- res.writeHead(416, { "content-range": `bytes */${file.bytes}`, "cache-control": "private, no-store", "x-content-type-options": "nosniff" });
- return res.end();
- }
- const [start, end] = range.kind === "range" ? [range.start, range.end] : [0, file.bytes - 1];
- res.writeHead(range.kind === "range" ? 206 : 200, {
- "content-type": file.mime,
- "content-length": String(end - start + 1),
- ...(range.kind === "range" ? { "content-range": `bytes ${start}-${end}/${file.bytes}` } : {}),
- ...(mediaGrant ? { "accept-ranges": "bytes" } : {}),
- "content-disposition": mediaGrant
- ? messageFileDisposition(messageFileDownloadName(downloadName, file.name), "inline")
- : inline ? "inline" : messageFileDisposition(messageFileDownloadName(downloadName, file.name)),
- "cache-control": "private, no-store",
- "cdn-cache-control": "no-store",
- "cloudflare-cdn-cache-control": "no-store",
- pragma: "no-cache",
- vary: "Authorization",
- "x-content-type-options": "nosniff",
- ...(inline
- ? {
- "cross-origin-resource-policy": "same-origin",
- "referrer-policy": "no-referrer",
- }
- : {}),
- });
- if (file.bytes === 0) {
- await file.handle.close();
- return res.end();
- }
- const stream = file.handle.createReadStream({ start, end, autoClose: true });
- stream.on("error", () => res.destroy());
- res.on("close", () => stream.destroy());
- stream.pipe(res);
return;
}