Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(chat): stream chat videos with byte ranges instead of downloading them first
AdityaUmalefd393a7d8002
diff --git a/server/index.test.ts b/server/index.test.tsindex 3ca95bf97a..a6a7c5d0fb 100644--- a/server/index.test.ts+++ b/server/index.test.ts@@ -652,6 +652,8 @@ beforeAll(async () => {mkdirSync(privateAttachments, { recursive: true, mode: 0o700 });writeFileSync(linkedFile, "# Phone-ready report\n");writeFileSync(linkedImage, "png preview bytes");+ const linkedVideo = join(linkedWorkspace, "clip.mp4");+ writeFileSync(linkedVideo, "0123456789".repeat(100));writeFileSync(generatedImage, "generated image bytes");writeFileSync(userAttachment, "%PDF shared from the phone\n", { mode: 0o600 });// A picture a bot saved outside the room's folders, and the copy attach_file made of it.@@ -740,6 +742,11 @@ beforeAll(async () => {text: `Heidi, 51 – Sideboard\n\n.href}>)\n\nEinschätzung`,from: { botId: "test-bot-a", name: "Test bot A", color: "purple" },},+ {+ id: "linked-video-message", at: 13, parentId: "delivered-image-reply-message", role: "bot", kind: "text",+ text: `[Clip](<${pathToFileURL(linkedVideo).href}>) and [notes](<${pathToFileURL(linkedFile).href}>)`,+ from: { botId: "test-bot-a", name: "Test bot A", color: "purple" },+ },],}),);@@ -14182,6 +14189,70 @@ describe("message pages", () => {expect((await fetch(`${BASE}/api/threads/${threadId}/messages/linked-image-message/file`, { headers: asChatOnly })).status).toBe(404);});+ it("streams a linked video through a viewer-bound media link with byte ranges", async () => {+ const threadId = "test-linked-file-room-thread";+ const route = `/api/threads/${threadId}/messages/linked-video-message/file`;+ const video = join(home, ".openmausbot", "workspaces", "test-bot-a", "clip.mp4");+ const bytes = "0123456789".repeat(100);+ const issued = await fetch(`${BASE}${route}`, {+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ path: pathToFileURL(video).href, media: true }),+ });+ expect(issued.status).toBe(200);+ expect(issued.headers.get("x-openmausbot-media")).toBe("1");+ expect(issued.headers.get("cache-control")).toBe("private, no-store");+ const link = (await issued.json()) as { url: string; mime: string; bytes: number };+ expect(link.mime).toBe("video/mp4");+ expect(link.bytes).toBe(1000);+ expect(link.url).toMatch(new RegExp(`^${route}\\?media=[\\w-]{43}$`));+ // The host path never enters the URL.+ expect(link.url).not.toContain("clip");++ const whole = await fetch(`${BASE}${link.url}`);+ expect(whole.status).toBe(200);+ expect(whole.headers.get("content-type")).toBe("video/mp4");+ expect(whole.headers.get("accept-ranges")).toBe("bytes");+ expect(whole.headers.get("content-disposition")).toBe("inline");+ expect(whole.headers.get("cache-control")).toBe("private, no-store");+ expect(whole.headers.get("x-content-type-options")).toBe("nosniff");+ expect(whole.headers.get("cross-origin-resource-policy")).toBe("same-origin");+ expect(await whole.text()).toBe(bytes);++ const part = await fetch(`${BASE}${link.url}`, { headers: { range: "bytes=10-19" } });+ expect(part.status).toBe(206);+ expect(part.headers.get("content-range")).toBe("bytes 10-19/1000");+ expect(part.headers.get("content-length")).toBe("10");+ expect(await part.text()).toBe("0123456789");+ const tail = await fetch(`${BASE}${link.url}`, { headers: { range: "bytes=995-" } });+ expect(tail.status).toBe(206);+ expect(await tail.text()).toBe("56789");+ const past = await fetch(`${BASE}${link.url}`, { headers: { range: "bytes=1000-" } });+ expect(past.status).toBe(416);+ expect(past.headers.get("content-range")).toBe("bytes */1000");++ // Bound to this message and this viewer; a made-up id is refused like a missing one.+ const token = new URL(link.url, BASE).searchParams.get("media")!;+ expect((await fetch(`${BASE}/api/threads/${threadId}/messages/linked-file-message/file?media=${token}`)).status).toBe(404);+ expect((await fetch(`${BASE}${route}?media=${"A".repeat(43)}`)).status).toBe(404);+ const window = await api("POST", "/api/auth/pairing", { scopes: ["client"] });+ const paired = await fetch(`${BASE}/api/auth/pair`, {+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ code: window.body.code }),+ });+ const otherViewer = { authorization: `Bearer ${((await paired.json()) as any).token as string}` };+ expect((await fetch(`${BASE}${link.url}`, { headers: otherViewer })).status).toBe(404);++ // Only videos get a link, and only for files this message shares.+ expect((await api("POST", route, { path: pathToFileURL(join(home, ".openmausbot", "workspaces", "test-bot-a", "phone report.md")).href, media: true })).status).toBe(415);+ expect((await api("POST", route, { path: pathToFileURL(join(home, ".openmausbot", "workspaces", "test-bot-a", "preview.png")).href, media: true })).status).toBe(403);++ // The file is opened and checked again on every request.+ try {+ rmSync(video);+ expect((await fetch(`${BASE}${link.url}`)).status).toBe(404);+ } finally {+ writeFileSync(video, bytes);+ }+ });+it("shows the copy a bot delivered of an outside picture, and says why one it never delivered is refused", async () => {const threadId = "test-linked-file-room-thread";const ref = "Heidi, 51 – Sideboard\n\n".length;diff --git a/server/message-media-links.test.ts b/server/message-media-links.test.tsnew file mode 100644index 0000000000..f1fb63b2ca--- /dev/null+++ b/server/message-media-links.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from "vitest";++import { MESSAGE_MEDIA_IDLE_MS, MESSAGE_MEDIA_MAX_AGE_MS, MessageMediaLinks } from "./message-media-links.ts";+import type { RequestAuth } from "./request-auth.ts";+import type { SessionRecord } from "./sessions.ts";++const owner: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };+const session = (id: string): RequestAuth => ({ kind: "session", session: { id } as SessionRecord, via: "cookie", scopes: ["client"] });+const grant = { threadId: "t1", messageId: "m1", path: "/work/clip.mp4" };++describe("MessageMediaLinks", () => {+ it("gives the grant back only to the viewer who asked, on the same message", () => {+ const links = new MessageMediaLinks();+ const id = links.issue(grant, session("a"));+ expect(id).toMatch(/^[\w-]{43}$/);+ expect(links.use(id, "t1", "m1", session("a"))).toEqual(grant);+ expect(links.use(id, "t1", "m1", session("b"))).toBeNull();+ expect(links.use(id, "t1", "m1", owner)).toBeNull();+ expect(links.use(id, "t1", "m2", session("a"))).toBeNull();+ expect(links.use(id, "t2", "m1", session("a"))).toBeNull();+ expect(links.use("forged", "t1", "m1", session("a"))).toBeNull();+ expect(links.issue(grant, session("a"))).not.toBe(id);+ });++ it("keeps a folder entry with its grant", () => {+ const links = new MessageMediaLinks();+ const id = links.issue({ ...grant, entry: "clip.mp4" }, owner);+ expect(links.use(id, "t1", "m1", owner)).toEqual({ ...grant, entry: "clip.mp4" });+ });++ it("expires when idle, renews on use, and ends at the hard limit", () => {+ let now = 1_000;+ const links = new MessageMediaLinks(() => now);+ const idle = links.issue(grant, owner);+ now += MESSAGE_MEDIA_IDLE_MS;+ expect(links.use(idle, "t1", "m1", owner)).toBeNull();++ const busy = links.issue(grant, owner);+ const issuedAt = now;+ while (now + MESSAGE_MEDIA_IDLE_MS / 2 < issuedAt + MESSAGE_MEDIA_MAX_AGE_MS) {+ now += MESSAGE_MEDIA_IDLE_MS / 2;+ expect(links.use(busy, "t1", "m1", owner)).toEqual(grant);+ }+ now = issuedAt + MESSAGE_MEDIA_MAX_AGE_MS;+ expect(links.use(busy, "t1", "m1", owner)).toBeNull();+ });++ it("keeps at most a bounded number of links, dropping the oldest", () => {+ const links = new MessageMediaLinks();+ const first = links.issue(grant, owner);+ for (let i = 0; i < 600; i++) links.issue(grant, owner);+ expect(links.use(first, "t1", "m1", owner)).toBeNull();+ });+});diff --git a/server/message-media-links.ts b/server/message-media-links.tsnew file mode 100644index 0000000000..17cf8bcdc6--- /dev/null+++ b/server/message-media-links.ts@@ -0,0 +1,75 @@+// A <video> element cannot send the JSON body the message-file route reads, so the route hands out an opaque id+// for the exact request it just authorized. The id is not a bearer secret: each use still needs the same signed-in+// viewer, and the route re-runs every message, folder and MIME check against what the id stands for.+import { randomBytes } from "node:crypto";++import type { RequestAuth } from "./request-auth.ts";++/** Idle limit: every range request a playing video makes renews it. */+export const MESSAGE_MEDIA_IDLE_MS = 15 * 60_000;+/** Hard limit, however busy the link is. */+export const MESSAGE_MEDIA_MAX_AGE_MS = 4 * 60 * 60_000;+const MAX_LINKS = 512;++export interface MessageMediaGrant {+ threadId: string;+ messageId: string;+ /** The `path` (and folder `entry`) the viewer asked for, exactly as the POST body carried them. */+ path: string;+ entry?: string;+}++interface StoredGrant extends MessageMediaGrant {+ viewer: string;+ idleUntil: number;+ expiresAt: number;+}++/** Who may use a link: the session that asked for it, or the loopback owner. */+export function mediaViewerKey(auth: RequestAuth): string {+ return auth.kind === "session" ? `session:${auth.session.id}` : "loopback";+}++export class MessageMediaLinks {+ private readonly grants = new Map<string, StoredGrant>();+ private readonly now: () => number;++ constructor(now: () => number = Date.now) {+ this.now = now;+ }++ issue(grant: MessageMediaGrant, auth: RequestAuth): string {+ const now = this.now();+ for (const [id, stored] of this.grants) {+ if (!this.live(stored, now)) this.grants.delete(id);+ }+ // Map order is insertion order: past the cap, the oldest link goes first.+ while (this.grants.size >= MAX_LINKS) this.grants.delete(this.grants.keys().next().value!);+ const id = randomBytes(32).toString("base64url");+ this.grants.set(id, {+ ...grant,+ viewer: mediaViewerKey(auth),+ idleUntil: now + MESSAGE_MEDIA_IDLE_MS,+ expiresAt: now + MESSAGE_MEDIA_MAX_AGE_MS,+ });+ return id;+ }++ /** The grant behind `id`, only for the same viewer on the same message; a use renews the idle limit. */+ use(id: string, threadId: string, messageId: string, auth: RequestAuth): MessageMediaGrant | null {+ const stored = this.grants.get(id);+ if (!stored) return null;+ const now = this.now();+ if (!this.live(stored, now)) {+ this.grants.delete(id);+ return null;+ }+ if (stored.threadId !== threadId || stored.messageId !== messageId || stored.viewer !== mediaViewerKey(auth)) return null;+ stored.idleUntil = now + MESSAGE_MEDIA_IDLE_MS;+ return { threadId: stored.threadId, messageId: stored.messageId, path: stored.path, ...(stored.entry !== undefined ? { entry: stored.entry } : {}) };+ }++ private live(stored: StoredGrant, now: number): boolean {+ return now < stored.idleUntil && now < stored.expiresAt;+ }+}diff --git a/server/routes/threads.ts b/server/routes/threads.tsindex ef07d8d740..c70caf8184 100644--- a/server/routes/threads.ts+++ b/server/routes/threads.ts@@ -16,6 +16,7 @@ import type { Coordinator } from "../coordinator.ts";import type { WorkspaceAccess } from "../enterprise.ts";import type { GroupUsageReader } from "../group-thread-usage.ts";import { readMessage, searchMessagesAsync } from "../message-db.ts";+import { MessageMediaLinks } from "../message-media-links.ts";import {listMessageFolder, MESSAGE_FILE_DOWNLOAD_MAX_BYTES, MESSAGE_FILE_MAX_BYTES, messageAttachmentName, messageFileDisposition, messageFileDownloadName, messageFolderEntryName,messageImageTargetAt, messageReferencesFile, openMessageFile, openMessageFolderEntry, referencedFileName,@@ -72,6 +73,9 @@ export interface ThreadRouteDeps {keptAttachments?(): ReadonlySet<string> | null;}+/** The types the chat's video player accepts (AttachmentGallery.tsx); anything else is never streamed inline. */+const STREAMABLE_VIDEO_MIMES = new Set(["video/mp4", "video/webm", "video/quicktime", "video/x-m4v"]);+export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {const {store, userName: userNameFor, sessions, groupUsageReader, lendingEnabled,@@ -79,6 +83,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {pageSize, messagePage, messageWindow, publicBotQueuedMessages, publicGroupState, wireBot,botComputerControlSnapshot, messageFileRootsForThread, viewerFor, visibleTo,} = deps;+ const mediaLinks = new MessageMediaLinks();// tasks stays explicit: clients expect [] where wireBot() would omit the key.const shownBot = (bot: BotRecord, visible: VisibleSet, limit: number | undefined) => {const wired = wireBot(bot);@@ -184,7 +189,9 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {const streamsMessageImage = Boolean(m && method === "GET" && url.searchParams.get("preview") === "1",);- if (m && (method === "POST" || streamsMessageImage)) {+ // A <video> element can only GET, so a POST first trades its body for a link id (see message-media-links.ts).+ const mediaId = m && method === "GET" && !streamsMessageImage ? url.searchParams.get("media") : null;+ if (m && (method === "POST" || streamsMessageImage || mediaId)) {if (method === "POST" && !String(req.headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) {return json(res, 415, { error: "content-type must be application/json" });}@@ -199,14 +206,20 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {return json(res, 403, { error: "that message does not share this file" });}const messageText = message.text ?? "";+ // Only this viewer's link for this message; every check below runs again on what it stands for.+ const mediaGrant = mediaId ? mediaLinks.use(mediaId, threadId, message.id, auth) : null;+ if (mediaId && !mediaGrant) return json(res, 404, { error: "that video link has expired", code: "media_link_expired" });const body = method === "POST" ? await readBody(req) : null;+ const asksMediaLink = body?.media === true;const rawReference = streamsMessageImage ? url.searchParams.get("ref") : null;if (streamsMessageImage && (!rawReference || !/^\d+$/.test(rawReference))) {return json(res, 400, { error: "ref must identify a rendered image" });}- const href = method === "POST"- ? (typeof body.path === "string" ? body.path : "")- : messageImageTargetAt(messageText, Number(rawReference));+ const href = mediaGrant+ ? mediaGrant.path+ : method === "POST"+ ? (typeof body.path === "string" ? body.path : "")+ : messageImageTargetAt(messageText, Number(rawReference));if (!href) return json(res, 400, { error: "path is required" });let roots: string[];@@ -237,9 +250,11 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {roots = [...new Set([...messageFileRootsForThread(senderId, threadId), ...fromRun])];}- const folderEntry = method === "POST" && body.entry !== undefined- ? messageFolderEntryName(body.entry)- : undefined;+ const folderEntry = mediaGrant+ ? mediaGrant.entry+ : method === "POST" && body.entry !== undefined+ ? messageFolderEntryName(body.entry)+ : undefined;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;@@ -271,10 +286,32 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {await file.handle.close();return json(res, 415, { error: "only images can be previewed here" });}- res.writeHead(200, {+ if ((asksMediaLink || mediaGrant) && !STREAMABLE_VIDEO_MIMES.has(file.mime)) {+ await file.handle.close();+ return json(res, 415, { error: "only videos 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;+ const range = mediaGrant ? 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(file.bytes),- ...(streamsMessageImage+ "content-length": String(end - start + 1),+ ...(range.kind === "range" ? { "content-range": `bytes ${start}-${end}/${file.bytes}` } : {}),+ ...(mediaGrant ? { "accept-ranges": "bytes" } : {}),+ ...(inline? { "content-disposition": "inline" }: { "content-disposition": messageFileDisposition(messageFileDownloadName(downloadName, file.name)) }),"cache-control": "private, no-store",@@ -283,7 +320,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {pragma: "no-cache",vary: "Authorization","x-content-type-options": "nosniff",- ...(streamsMessageImage+ ...(inline? {"cross-origin-resource-policy": "same-origin","referrer-policy": "no-referrer",@@ -294,7 +331,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {await file.handle.close();return res.end();}- const stream = file.handle.createReadStream({ start: 0, end: file.bytes - 1, autoClose: true });+ const stream = file.handle.createReadStream({ start, end, autoClose: true });stream.on("error", () => res.destroy());res.on("close", () => stream.destroy());stream.pipe(res);diff --git a/src/components/AttachmentGallery.test.ts b/src/components/AttachmentGallery.test.tsindex cdd200f8ab..3a9645a5a2 100644--- a/src/components/AttachmentGallery.test.ts+++ b/src/components/AttachmentGallery.test.ts@@ -183,14 +183,46 @@ describe("message gallery", () => {});describe("explicit local video preview", () => {- it("posts to the same-origin message route and uses only the authorized response bytes", async () => {- const fetcher = vi.fn(async () => new Response("video bytes", { headers: { "content-type": "video/mp4" } }));+ const route = "/api/threads/thread%2Fone/messages/message%20two/file";+ const linkResponse = (body: unknown) => new Response(JSON.stringify(body), {+ headers: { "content-type": "application/json", "x-openmausbot-media": "1" },+ });++ it("asks the message route for a streaming link and plays that link without downloading the file", async () => {+ const url = `${route}?media=${"a".repeat(43)}`;+ const fetcher = vi.fn(async () => linkResponse({ url, mime: "video/mp4", bytes: 24_000_000 }));vi.stubGlobal("fetch", fetcher);- const signal = new AbortController().signal;- const blob = await loadMessageVideo(file, message, signal);- expect(fetcher).toHaveBeenCalledWith("/api/threads/thread%2Fone/messages/message%20two/file", {- method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ path: file.path }), signal: expect.any(AbortSignal),+ expect(await loadMessageVideo(file, message, new AbortController().signal)).toBe(url);+ expect(fetcher).toHaveBeenCalledTimes(1);+ expect(fetcher).toHaveBeenCalledWith(route, {+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ path: file.path, media: true }), signal: expect.any(AbortSignal),});+ });++ it("streams a video over the in-memory preview limit, since the player reads it in ranges", async () => {+ const url = `${route}?media=b`;+ vi.stubGlobal("fetch", vi.fn(async () => linkResponse({ url, mime: "video/webm", bytes: PREVIEW_MAX_BYTES * 4 })));+ expect(await loadMessageVideo(file, message, new AbortController().signal)).toBe(url);+ });++ it("refuses a link that points anywhere but this message's file route, or at something not a video", async () => {+ for (const body of [+ { url: "https://example.com/clip.mp4", mime: "video/mp4" },+ { url: "/api/threads/thread%2Fone/messages/other/file?media=abc", mime: "video/mp4" },+ { url: `${route}?media=abc&path=/etc/passwd`, mime: "video/mp4" },+ { url: `${route}?media=abc`, mime: "text/html" },+ null,+ ]) {+ vi.stubGlobal("fetch", vi.fn(async () => linkResponse(body)));+ await expect(loadMessageVideo(file, message, new AbortController().signal)).rejects.toThrow("cannot be played");+ }+ });++ it("falls back to the authorized response bytes from a server without streaming links", async () => {+ const fetcher = vi.fn(async () => new Response("video bytes", { headers: { "content-type": "video/mp4" } }));+ vi.stubGlobal("fetch", fetcher);+ const blob = await loadMessageVideo(file, message, new AbortController().signal) as Blob;+ expect(fetcher).toHaveBeenCalledTimes(1);expect(blob.type).toBe("video/mp4");expect(await blob.text()).toBe("video bytes");});@@ -254,7 +286,7 @@ describe("explicit local video preview", () => {vi.stubGlobal("fetch", fetcher);const pending = loadMessageVideo(file, message, new AbortController().signal);await vi.advanceTimersByTimeAsync(15_000);- expect(await (await pending).text()).toBe("video bytes");+ expect(await (await pending as Blob).text()).toBe("video bytes");expect(fetcher).toHaveBeenCalledTimes(2);} finally {vi.useRealTimers();diff --git a/src/components/AttachmentGallery.tsx b/src/components/AttachmentGallery.tsxindex c9d057a78b..b26a8f9da1 100644--- a/src/components/AttachmentGallery.tsx+++ b/src/components/AttachmentGallery.tsx@@ -167,12 +167,18 @@ async function withStallRetry<T>(}}-/** Security: the server's MIME is required as well as the filename, so arbitrary bytes never become UI. */+const VIDEO_MIMES = ["video/mp4", "video/webm", "video/quicktime", "video/x-m4v"];++/**+ * Security: the server's MIME is required as well as the filename, so arbitrary bytes never become UI.+ * A string is the server's link for this one file, which the player streams with byte ranges; a server without+ * links answers the same request with the bytes, read whole into a Blob as before.+ */export function loadMessageVideo(file: GalleryFile,message: MessageAttachmentContext,signal: AbortSignal,-): Promise<Blob> {+): Promise<Blob | string> {return withStallRetry(signal, t("attach.videoUnavailable"), (attempt, progress) => readMessageVideo(file, message, attempt, progress));}@@ -181,11 +187,12 @@ async function readMessageVideo(message: MessageAttachmentContext,signal: AbortSignal,progress: () => void,-): Promise<Blob> {- const response = await requestMessageFile(file.path, message, signal);+): Promise<Blob | string> {+ const response = await requestMessageFile(file.path, message, signal, { mediaLink: true });progress();+ if (response.headers.get("x-openmausbot-media") === "1") return messageVideoLink(await response.json().catch(() => null), message);const mime = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase();- if (!mime || !["video/mp4", "video/webm", "video/quicktime", "video/x-m4v"].includes(mime)) {+ if (!mime || !VIDEO_MIMES.includes(mime)) {await response.body?.cancel();throw new Error(t("attach.videoUnavailable"));}@@ -217,6 +224,17 @@ async function readMessageVideo(return new Blob(chunks, { type: mime });}+/** Security: only this message's own file route, never a URL the response could point anywhere else. */+function messageVideoLink(body: unknown, message: MessageAttachmentContext): string {+ const { url, mime } = (body ?? {}) as { url?: unknown; mime?: unknown };+ const route = `/api/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.messageId)}/file?media=`;+ if (typeof url !== "string" || !url.startsWith(route) || !/^[\w-]+$/.test(url.slice(route.length))+ || typeof mime !== "string" || !VIDEO_MIMES.includes(mime)) {+ throw new Error(t("attach.videoUnavailable"));+ }+ return url;+}+function megabytes(bytes: number): string {return `${Math.ceil(bytes / (1024 * 102.4)) / 10} MB`;}@@ -238,7 +256,7 @@ function VideoAttachment({ file, message }: { file: GalleryFile; message: MessaguseEffect(() => () => request.current?.abort(), []);useEffect(() => {if (preview) videoRef.current?.focus();- return () => { if (preview) URL.revokeObjectURL(preview); };+ return () => { if (preview?.startsWith("blob:")) URL.revokeObjectURL(preview); };}, [preview]);const load = async () => {@@ -249,8 +267,8 @@ function VideoAttachment({ file, message }: { file: GalleryFile; message: MessagsetError("");setPreview(null);try {- const blob = await loadMessageVideo(file, message, controller.signal);- if (!controller.signal.aborted) setPreview(URL.createObjectURL(blob));+ const source = await loadMessageVideo(file, message, controller.signal);+ if (!controller.signal.aborted) setPreview(typeof source === "string" ? source : URL.createObjectURL(source));} catch (reason) {if (!controller.signal.aborted) {setError(reason instanceof Error ? reason.message : t("attach.videoUnavailable"));diff --git a/src/components/AttachmentPreview.tsx b/src/components/AttachmentPreview.tsxindex 1db1299929..e9bab3d99c 100644--- a/src/components/AttachmentPreview.tsx+++ b/src/components/AttachmentPreview.tsx@@ -223,14 +223,14 @@ export async function requestMessageFile(filePath: string,message: MessageAttachmentContext,signal: AbortSignal,- folder?: { entry?: string; list?: boolean },+ options?: { entry?: string; list?: boolean; mediaLink?: boolean },): Promise<Response> {const response = await fetch(`/api/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.messageId)}/file`, {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({path: filePath,- ...(folder?.entry !== undefined ? { entry: folder.entry } : folder?.list ? { listFolder: true } : {}),+ ...(options?.entry !== undefined ? { entry: options.entry } : options?.list ? { listFolder: true } : options?.mediaLink ? { media: true } : {}),}),signal,});