Skip to content

Build your personal knowledge base with Trilium Notes

fix(standalone): serve open-partial byte ranges from the shared core routes

Elian Doranac8f3f82f3e5
diff --git a/apps/server/src/express.d.ts b/apps/server/src/express.d.ts
index 6ba2c919df..5f5f645ea0 100644
--- a/apps/server/src/express.d.ts
+++ b/apps/server/src/express.d.ts
@@ -14,6 +14,9 @@ export declare module "express-serve-static-core" {
"trilium-local-now-datetime"?: string;
"trilium-hoisted-note-id"?: string;
+ /** Byte range a media player seeks with, read by the open-partial routes. */
+ range?: string;
+
"user-agent"?: string;
};
}
diff --git a/apps/server/src/routes/api/core_routes_http.spec.ts b/apps/server/src/routes/api/core_routes_http.spec.ts
index abe7ac681d..708bb626e9 100644
--- a/apps/server/src/routes/api/core_routes_http.spec.ts
+++ b/apps/server/src/routes/api/core_routes_http.spec.ts
@@ -37,4 +37,18 @@ describe("Core routes over Express", () => {
const res = await ctx.agent.get(`/api/notes/${noteId}`).expect(200);
expect(res.body.title).toBe("Via Express");
});
+
+ // Media players stream from open-partial, and only a real Express response can show that the
+ // slice leaves as bytes: `res.send()` treats anything that is not a Buffer as JSON.
+ it("answers a byte range on open-partial with 206 and the raw slice", async () => {
+ const { noteId } = await createTextNote(ctx, { content: "<p>hello</p>" });
+
+ const full = await ctx.agent.get(`/api/notes/${noteId}/open-partial`).expect(200);
+ expect(full.headers["accept-ranges"]).toBe("bytes");
+ expect(full.text).toBe("<p>hello</p>");
+
+ const ranged = await ctx.agent.get(`/api/notes/${noteId}/open-partial`).set("Range", "bytes=3-7").expect(206);
+ expect(ranged.headers["content-range"]).toBe("bytes 3-7/12");
+ expect(ranged.text).toBe("hello");
+ });
});
diff --git a/apps/server/src/routes/api/files.spec.ts b/apps/server/src/routes/api/files.spec.ts
index 56cab1ca8a..c1f634c3e3 100644
--- a/apps/server/src/routes/api/files.spec.ts
+++ b/apps/server/src/routes/api/files.spec.ts
@@ -1,7 +1,6 @@
import { becca, cls, note_service as noteService, ValidationError } from "@triliumnext/core";
import type { Request } from "express";
import fs from "fs";
-import { Readable } from "stream";
import { beforeAll, describe, expect, it } from "vitest";
import filesRoute from "./files.js";
@@ -13,12 +12,6 @@ function fileReq(params: Record<string, string>, file?: unknown, query: Record<s
return { params, file, query, body } as unknown as Request<{ noteId: string }>;
}
-async function streamToString(stream: Readable) {
- const chunks: Buffer[] = [];
- for await (const chunk of stream) chunks.push(Buffer.from(chunk));
- return Buffer.concat(chunks).toString("utf8");
-}
-
describe("Files API", () => {
beforeAll(() => {
cls.init(() => {
@@ -62,23 +55,6 @@ describe("Files API", () => {
});
});
- describe("content providers", () => {
- it("streams full and ranged note content", async () => {
- const current = becca.getNoteOrThrow(noteId).getContent() as string;
- const provider = await filesRoute.fileContentProvider(fileReq({ noteId }));
- expect(provider.totalSize).toBe(Buffer.byteLength(current));
- expect(await streamToString(provider.getStream(undefined as never))).toBe(current);
- expect(await streamToString(provider.getStream({ start: 0, end: 0 }))).toBe(current.slice(0, 1));
- });
-
- it("streams attachment content", async () => {
- const req = fileReq({ attachmentId } as Record<string, string>) as unknown as Request<{ attachmentId: string }>;
- const provider = await filesRoute.attachmentContentProvider(req);
- expect(provider.mimeType).toBe("text/plain");
- expect(await streamToString(provider.getStream(undefined as never))).toBe("new-att");
- });
- });
-
describe("temp-dir round trip", () => {
it("saves a note to a temp file then uploads the modified content back", () => {
const { tmpFilePath } = cls.init(() => filesRoute.saveNoteToTmpDir(fileReq({ noteId })));
diff --git a/apps/server/src/routes/api/files.ts b/apps/server/src/routes/api/files.ts
index ede794a5d2..795e848f25 100644
--- a/apps/server/src/routes/api/files.ts
+++ b/apps/server/src/routes/api/files.ts
@@ -3,7 +3,6 @@ import chokidar from "chokidar";
import type { Request } from "express";
import fs from "fs";
import path from "path";
-import { Readable } from "stream";
import tmp from "tmp";
import { becca } from "@triliumnext/core";
@@ -60,48 +59,6 @@ function updateAttachment(req: Request<{ attachmentId: string }>) {
};
}
-function fileContentProvider(req: Request<{ noteId: string }>) {
- // Read the file name from route params.
- const note = becca.getNoteOrThrow(req.params.noteId);
-
- // blobId is a content hash, so it's a stable ETag that changes only when the content does.
- return streamContent(note.getContent(), note.getFileName(), note.mime, note.blobId);
-}
-
-function attachmentContentProvider(req: Request<{ attachmentId: string }>) {
- // Read the file name from route params.
- const attachment = becca.getAttachmentOrThrow(req.params.attachmentId);
-
- return streamContent(attachment.getContent(), attachment.getFileName(), attachment.mime, attachment.blobId);
-}
-
-async function streamContent(content: string | Uint8Array, fileName: string, mimeType: string, etag?: string) {
- if (typeof content === "string") {
- content = Buffer.from(content, "utf8");
- }
-
- const totalSize = content.byteLength;
-
- const getStream = (range: { start: number; end: number }) => {
- if (!range) {
- // Request if for complete content.
- return Readable.from(content);
- }
- // Partial content request.
- const { start, end } = range;
-
- return Readable.from(content.slice(start, end + 1));
- };
-
- return {
- fileName,
- totalSize,
- mimeType,
- etag,
- getStream
- };
-}
-
function saveNoteToTmpDir(req: Request<{ noteId: string }>) {
const note = becca.getNoteOrThrow(req.params.noteId);
const fileName = note.getFileName();
@@ -228,10 +185,8 @@ function uploadModifiedFileToAttachment(req: Request<{ attachmentId: string }>)
export default {
updateFile,
updateAttachment,
- fileContentProvider,
saveNoteToTmpDir,
saveAttachmentToTmpDir,
- attachmentContentProvider,
uploadModifiedFileToNote,
uploadModifiedFileToAttachment
};
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 7d4115ee9c..2eca9048cf 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -1,5 +1,4 @@
import { routes } from "@triliumnext/core";
-import { createPartialContentHandler } from "@triliumnext/express-partial-content";
import express from "express";
import rateLimit from "express-rate-limit";
@@ -113,30 +112,9 @@ function register(app: express.Application) {
});
route(PUT, "/api/notes/:noteId/file", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateFile, apiResultHandler);
- asyncRoute(
- GET,
- "/api/notes/:noteId/open-partial",
- [auth.checkApiAuthOrElectron],
- createPartialContentHandler(filesRoute.fileContentProvider, {
- debug: (string, extra) => {
- console.log(string, extra);
- }
- })
- );
apiRoute(PST, "/api/notes/:noteId/save-to-tmp-dir", filesRoute.saveNoteToTmpDir);
apiRoute(PST, "/api/notes/:noteId/upload-modified-file", filesRoute.uploadModifiedFileToNote);
- asyncRoute(
- GET,
- "/api/attachments/:attachmentId/open-partial",
- [auth.checkApiAuthOrElectron],
- createPartialContentHandler(filesRoute.attachmentContentProvider, {
- debug: (string, extra) => {
- console.log(string, extra);
- }
- })
- );
-
apiRoute(PST, "/api/attachments/:attachmentId/save-to-tmp-dir", filesRoute.saveAttachmentToTmpDir);
apiRoute(PST, "/api/attachments/:attachmentId/upload-modified-file", filesRoute.uploadModifiedFileToAttachment);
route(PUT, "/api/attachments/:attachmentId/file", [auth.checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], filesRoute.updateAttachment, apiResultHandler);
diff --git a/apps/standalone/src/lightweight/browser_router.spec.ts b/apps/standalone/src/lightweight/browser_router.spec.ts
index 156d02619c..81408f11f9 100644
--- a/apps/standalone/src/lightweight/browser_router.spec.ts
+++ b/apps/standalone/src/lightweight/browser_router.spec.ts
@@ -196,6 +196,18 @@ describe("BrowserRouter result formatting", () => {
expect(nullRes.status).toBe(304);
expect(nullRes.body).toBeNull();
});
+
+ it("sends only a view's own bytes, not the whole buffer behind it", async () => {
+ // How a byte range arrives: the handler slices the note's content, which leaves a view over
+ // the full blob. Handing over its `.buffer` would answer a seek with the entire file.
+ const router = new BrowserRouter();
+ const whole = encoder.encode("0123456789");
+ router.get("/raw-slice", () => ({ [RAW_RESPONSE]: true, status: 206, headers: {}, body: whole.subarray(3, 7) }));
+
+ const res = await router.dispatch("GET", "http://localhost/raw-slice");
+ expect(res.status).toBe(206);
+ expect(decodeBody(res.body)).toBe("3456");
+ });
});
describe("BrowserRouter error formatting", () => {
diff --git a/apps/standalone/src/lightweight/browser_router.ts b/apps/standalone/src/lightweight/browser_router.ts
index a5bdfea79f..c8e0d2635b 100644
--- a/apps/standalone/src/lightweight/browser_router.ts
+++ b/apps/standalone/src/lightweight/browser_router.ts
@@ -250,7 +250,13 @@ export class BrowserRouter {
if (raw.body instanceof ArrayBuffer) {
body = raw.body;
} else if (raw.body instanceof Uint8Array) {
- body = raw.body.buffer as ArrayBuffer;
+ // A view can cover just part of its buffer — a byte range sliced out of a note's
+ // content is exactly that — so handing over the whole buffer would answer with the
+ // entire file. Only the view's own bytes may go out, copied when it isn't the whole
+ // buffer already (the common case, which must not copy a whole video to serve it).
+ body = raw.body.byteOffset === 0 && raw.body.byteLength === raw.body.buffer.byteLength
+ ? raw.body.buffer as ArrayBuffer
+ : new Uint8Array(raw.body).buffer;
} else if (typeof raw.body === 'string') {
body = encoder.encode(raw.body).buffer as ArrayBuffer;
}
diff --git a/apps/standalone/src/lightweight/browser_routes.spec.ts b/apps/standalone/src/lightweight/browser_routes.spec.ts
index 26bfc0a84d..897447157a 100644
--- a/apps/standalone/src/lightweight/browser_routes.spec.ts
+++ b/apps/standalone/src/lightweight/browser_routes.spec.ts
@@ -60,6 +60,24 @@ describe("registerRoutes (real wiring)", () => {
expect(extra.isMainWindow).toBe(false);
});
+ // The whole standalone media path in one request: the core handler slices the note's content,
+ // the mock response carries the slice out as a raw response, and the router turns the view into
+ // exactly those bytes. This is what an <audio>/<video> element does every time it seeks.
+ it("answers a byte range on open-partial with 206 and just that slice", async () => {
+ const created = parseJson((await router.dispatch("POST", "http://localhost/api/notes/root/children?target=into",
+ { title: "clip.mp3", type: "file", mime: "audio/mpeg", content: "0123456789" })).body) as { note: { noteId: string } };
+ const { noteId } = created.note;
+
+ const res = await router.dispatch("GET", `http://localhost/api/notes/${noteId}/open-partial?v=1`, undefined, {
+ range: "bytes=2-5"
+ });
+
+ expect(res.status).toBe(206);
+ expect(text(res.body)).toBe("2345");
+ expect(res.headers["Content-Range"]).toBe("bytes 2-5/10");
+ expect(res.headers["Accept-Ranges"]).toBe("bytes");
+ });
+
it("returns the setup payload when the database is not initialized", async () => {
vi.spyOn(sql_init, "isDbInitialized").mockReturnValue(false);
const data = parseJson((await router.dispatch("GET", "http://localhost/bootstrap")).body) as Record<string, unknown>;
diff --git a/packages/trilium-core/src/routes/api/files.spec.ts b/packages/trilium-core/src/routes/api/files.spec.ts
index aad13176ea..fd50e288a4 100644
--- a/packages/trilium-core/src/routes/api/files.spec.ts
+++ b/packages/trilium-core/src/routes/api/files.spec.ts
@@ -124,6 +124,76 @@ describe("Files API (core)", () => {
});
});
+ /**
+ * What the audio/video players stream from. A media element seeks by re-requesting a byte range,
+ * so these have to answer 206 with exactly the slice asked for — a full body every time would
+ * make seeking pull the whole file down again.
+ */
+ describe("byte-range streaming (open-partial)", () => {
+ const PAYLOAD = "0123456789";
+
+ async function createMediaNote(): Promise<string> {
+ const res = await api.post<{ note: { noteId: string } }>("/api/notes/root/children?target=into", {
+ body: { title: "clip.mp3", type: "file", mime: "audio/mpeg", content: PAYLOAD }
+ });
+ expect(res.status).toBe(200);
+ return res.body.note.noteId;
+ }
+
+ function bodyOf(body: unknown): string {
+ return Buffer.isBuffer(body) ? body.toString("utf8") : String(body);
+ }
+
+ it("serves a note's full content, advertising range support", async () => {
+ const noteId = await createMediaNote();
+
+ const res = await api.get(`/api/notes/${noteId}/open-partial`);
+ expect(res.status).toBe(200);
+ expect(bodyOf(res.body)).toBe(PAYLOAD);
+ expect(res.headers["Accept-Ranges"]).toBe("bytes");
+ expect(res.headers["Content-Type"]).toBe("audio/mpeg");
+ // The ETag is the blobId, so it moves only when the content does.
+ expect(res.headers.ETag).toMatch(/^".+"$/);
+ });
+
+ it("serves a requested range of a note as 206", async () => {
+ const noteId = await createMediaNote();
+
+ const res = await api.get(`/api/notes/${noteId}/open-partial`, { headers: { range: "bytes=3-6" } });
+ expect(res.status).toBe(206);
+ expect(bodyOf(res.body)).toBe("3456");
+ expect(res.headers["Content-Range"]).toBe("bytes 3-6/10");
+ expect(res.headers["Content-Length"]).toBe("4");
+ });
+
+ it("serves a requested range of an attachment as 206", async () => {
+ const { noteId } = await createTextNote(api, { title: "Has media attachment" });
+ expect((await api.post(`/api/notes/${noteId}/attachments`, {
+ body: { role: "file", mime: "audio/mpeg", title: "clip.mp3", content: PAYLOAD }
+ })).status).toBe(204);
+ const list = await api.get<AttachmentPojo[]>(`/api/notes/${noteId}/attachments`);
+ const { attachmentId } = list.body[0];
+
+ const res = await api.get(`/api/attachments/${attachmentId}/open-partial`, { headers: { range: "bytes=-2" } });
+ expect(res.status).toBe(206);
+ expect(bodyOf(res.body)).toBe("89");
+ expect(res.headers["Content-Range"]).toBe("bytes 8-9/10");
+ });
+
+ it("416s on a range past the end of the content", async () => {
+ const noteId = await createMediaNote();
+
+ const res = await api.get(`/api/notes/${noteId}/open-partial`, { headers: { range: "bytes=99-120" } });
+ expect(res.status).toBe(416);
+ expect(res.headers["Content-Range"]).toBe("bytes */10");
+ });
+
+ it("404s for a missing note or attachment", async () => {
+ expect((await api.get("/api/notes/missingNote123/open-partial")).status).toBe(404);
+ expect((await api.get("/api/attachments/missingAttachment123/open-partial")).status).toBe(404);
+ });
+ });
+
describe("office preview", () => {
// RTF is the only office format that can be created inline as plain text, which makes
// it ideal to exercise the real officeparser conversion in both runtimes. It also
diff --git a/packages/trilium-core/src/routes/api/files.ts b/packages/trilium-core/src/routes/api/files.ts
index f23eb81655..c3d232c0c3 100644
--- a/packages/trilium-core/src/routes/api/files.ts
+++ b/packages/trilium-core/src/routes/api/files.ts
@@ -1,7 +1,11 @@
import { Request, Response } from "express";
import becca from "../../becca/becca";
+import type BAttachment from "../../becca/entities/battachment";
+import type BNote from "../../becca/entities/bnote";
import { convertOfficeToHtml } from "../../services/office_preview.js";
+import protected_session from "../../services/protected_session";
import { downloadData, downloadNoteInt } from "../helpers";
+import { serveContentWithRanges } from "../partial_content";
const downloadFile = (req: Request<{ noteId: string }>, res: Response) => downloadNoteInt(req.params.noteId, res, true);
const openFile = (req: Request<{ noteId: string }>, res: Response) => downloadNoteInt(req.params.noteId, res, false);
@@ -9,6 +13,31 @@ const openFile = (req: Request<{ noteId: string }>, res: Response) => downloadNo
const downloadAttachment = (req: Request<{ attachmentId: string }>, res: Response) => downloadAttachmentInt(req.params.attachmentId, res, true);
const openAttachment = (req: Request<{ attachmentId: string }>, res: Response) => downloadAttachmentInt(req.params.attachmentId, res, false);
+/**
+ * Serves a note's content with byte-range support, which is what an `<audio>`/`<video>` element
+ * streams from: it seeks by asking for the range it needs instead of downloading the whole file.
+ */
+function openPartialFile(req: Request<{ noteId: string }>, res: Response) {
+ const note = becca.getNote(req.params.noteId);
+
+ if (!note) {
+ return res.setHeader("Content-Type", "text/plain").status(404).send(`Note '${req.params.noteId}' doesn't exist.`);
+ }
+
+ return openPartialInt(note, req, res);
+}
+
+/** The attachment counterpart of {@link openPartialFile}. */
+function openPartialAttachment(req: Request<{ attachmentId: string }>, res: Response) {
+ const attachment = becca.getAttachment(req.params.attachmentId);
+
+ if (!attachment) {
+ return res.setHeader("Content-Type", "text/plain").status(404).send(`Attachment '${req.params.attachmentId}' doesn't exist.`);
+ }
+
+ return openPartialInt(attachment, req, res);
+}
+
/**
* Converts an office document note/attachment to an embeddable HTML fragment for the
* inline preview shown by the client. The returned HTML is unsanitized — the client
@@ -26,6 +55,20 @@ async function getAttachmentOfficePreview(req: Request<{ attachmentId: string }>
return { html: await convertOfficeToHtml(attachment.getContent(), attachment.mime) };
}
+function openPartialInt(noteOrAttachment: BNote | BAttachment, req: Request, res: Response) {
+ if (noteOrAttachment.isProtected && !protected_session.isProtectedSessionAvailable()) {
+ return res.status(401).send("Protected session not available");
+ }
+
+ return serveContentWithRanges(req, res, {
+ content: noteOrAttachment.getContent(),
+ fileName: noteOrAttachment.getFileName(),
+ mimeType: noteOrAttachment.mime,
+ // blobId is a content hash, so it is a stable ETag that changes only when the content does.
+ etag: noteOrAttachment.blobId
+ });
+}
+
function downloadAttachmentInt(attachmentId: string, res: Response, contentDisposition = true) {
const attachment = becca.getAttachment(attachmentId);
@@ -39,6 +82,8 @@ function downloadAttachmentInt(attachmentId: string, res: Response, contentDispo
export default {
openFile,
downloadFile,
+ openPartialFile,
+ openPartialAttachment,
openAttachment,
downloadAttachment,
getNoteOfficePreview,
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 3a1868bafe..c8c769dd93 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -247,6 +247,9 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout
//#region Files
route(GET, "/api/notes/:noteId/open", [checkApiAuthOrElectron], filesRoute.openFile);
+ // What the media players stream from: same content as /open, but answering byte ranges so they can seek.
+ route(GET, "/api/notes/:noteId/open-partial", [checkApiAuthOrElectron], filesRoute.openPartialFile);
+ route(GET, "/api/attachments/:attachmentId/open-partial", [checkApiAuthOrElectron], filesRoute.openPartialAttachment);
asyncApiRoute(GET, "/api/notes/:noteId/office-preview", filesRoute.getNoteOfficePreview);
asyncApiRoute(GET, "/api/attachments/:attachmentId/office-preview", filesRoute.getAttachmentOfficePreview);
route(GET, "/api/notes/:noteId/download", [checkApiAuthOrElectron], filesRoute.downloadFile);
diff --git a/packages/trilium-core/src/routes/partial_content.spec.ts b/packages/trilium-core/src/routes/partial_content.spec.ts
new file mode 100644
index 0000000000..decbdc8d41
--- /dev/null
+++ b/packages/trilium-core/src/routes/partial_content.spec.ts
@@ -0,0 +1,135 @@
+import type { Request, Response } from "express";
+import { describe, expect, it } from "vitest";
+
+import { serveContentWithRanges } from "./partial_content.js";
+
+const decoder = new TextDecoder();
+
+interface ServeResult {
+ status: number;
+ headers: Record<string, string>;
+ body: string;
+ byteLength: number;
+}
+
+/** Serves `content` through the real handler, capturing what it wrote to the response. */
+function serve(content: string | Uint8Array, range?: string, etag?: string): ServeResult {
+ const captured: ServeResult = { status: 200, headers: {}, body: "", byteLength: 0 };
+
+ const res = {
+ setHeader(name: string, value: string) {
+ captured.headers[name] = value;
+ return res;
+ },
+ status(code: number) {
+ captured.status = code;
+ return res;
+ },
+ send(body: string | Uint8Array) {
+ captured.body = typeof body === "string" ? body : decoder.decode(body);
+ captured.byteLength = typeof body === "string" ? body.length : body.byteLength;
+ return res;
+ }
+ } as unknown as Response;
+
+ const req = { headers: range ? { range } : {} } as unknown as Request;
+ serveContentWithRanges(req, res, { content, fileName: "clip.mp3", mimeType: "audio/mpeg", etag });
+
+ return captured;
+}
+
+const CONTENT = "0123456789";
+
+describe("serveContentWithRanges", () => {
+ it("serves the whole body, and the headers a client needs to start ranging, when no range is asked for", () => {
+ const res = serve(CONTENT, undefined, "blobA");
+
+ expect(res.status).toBe(200);
+ expect(res.body).toBe(CONTENT);
+ expect(res.headers).toMatchObject({
+ "Content-Type": "audio/mpeg",
+ "Accept-Ranges": "bytes",
+ "Content-Length": "10",
+ // An entity-tag has to be quoted, and one that already is stays as it was.
+ ETag: `"blobA"`
+ });
+ expect(res.headers["Content-Disposition"]).toContain("clip.mp3");
+ expect(res.headers["Content-Range"]).toBeUndefined();
+ expect(serve(CONTENT, undefined, `"quoted"`).headers.ETag).toBe(`"quoted"`);
+ expect(serve(CONTENT).headers.ETag).toBeUndefined();
+ });
+
+ it("answers a range with 206 and just that slice", () => {
+ const res = serve(CONTENT, "bytes=2-5");
+
+ expect(res.status).toBe(206);
+ expect(res.body).toBe("2345");
+ expect(res.headers["Content-Range"]).toBe("bytes 2-5/10");
+ expect(res.headers["Content-Length"]).toBe("4");
+ // A slice must not be cached as though it were the whole file.
+ expect(res.headers["Cache-Control"]).toBe("no-cache");
+ });
+
+ it("handles the open-ended, suffix and single-byte forms a player uses to probe", () => {
+ const openEnded = serve(CONTENT, "bytes=6-");
+ expect(openEnded.status).toBe(206);
+ expect(openEnded.body).toBe("6789");
+ expect(openEnded.headers["Content-Range"]).toBe("bytes 6-9/10");
+
+ // `bytes=-3` means the *last* three bytes, not a range starting at zero.
+ const suffix = serve(CONTENT, "bytes=-3");
+ expect(suffix.body).toBe("789");
+ expect(suffix.headers["Content-Range"]).toBe("bytes 7-9/10");
+
+ // A single byte is one byte long — the length must agree with the body.
+ const single = serve(CONTENT, "bytes=0-0");
+ expect(single.body).toBe("0");
+ expect(single.headers["Content-Length"]).toBe("1");
+
+ // A suffix longer than the content is the whole content.
+ expect(serve(CONTENT, "bytes=-500").headers["Content-Range"]).toBe("bytes 0-9/10");
+ });
+
+ it("clamps an end past the content instead of refusing it", () => {
+ const res = serve(CONTENT, "bytes=8-999");
+
+ expect(res.status).toBe(206);
+ expect(res.body).toBe("89");
+ expect(res.headers["Content-Range"]).toBe("bytes 8-9/10");
+ });
+
+ it("rejects a range that starts beyond the content with 416", () => {
+ for (const range of [ "bytes=10-12", "bytes=5-2", "bytes=-0" ]) {
+ const res = serve(CONTENT, range);
+ expect(res.status, range).toBe(416);
+ expect(res.headers["Content-Range"], range).toBe("bytes */10");
+ }
+ });
+
+ it("ignores a header it cannot parse, and serves the whole body", () => {
+ // RFC 9110 §14.2: an unparseable Range is ignored rather than rejected.
+ for (const range of [ "bytes=abc", "rows=1-2", "bytes=1-2, 5-6", "" ]) {
+ const res = serve(CONTENT, range);
+ expect(res.status, range).toBe(200);
+ expect(res.body, range).toBe(CONTENT);
+ }
+ });
+
+ it("slices by byte, not by character, so multi-byte content is not corrupted", () => {
+ // "é" is two bytes in UTF-8, so a two-byte range holds exactly one character.
+ const res = serve("éé", "bytes=0-1");
+
+ expect(res.status).toBe(206);
+ expect(res.body).toBe("é");
+ expect(res.headers["Content-Range"]).toBe("bytes 0-1/4");
+ });
+
+ it("serves empty content as an empty 200, range header or not", () => {
+ for (const range of [ undefined, "bytes=0-10" ]) {
+ const res = serve(new Uint8Array(), range);
+ expect(res.status).toBe(200);
+ expect(res.byteLength).toBe(0);
+ expect(res.headers["Content-Length"]).toBe("0");
+ }
+ });
+});
diff --git a/packages/trilium-core/src/routes/partial_content.ts b/packages/trilium-core/src/routes/partial_content.ts
new file mode 100644
index 0000000000..366c601e94
--- /dev/null
+++ b/packages/trilium-core/src/routes/partial_content.ts
@@ -0,0 +1,118 @@
+import type { Request, Response } from "express";
+
+import { wrapStringOrBuffer } from "../services/utils/binary.js";
+import { getContentDisposition } from "../services/utils/index.js";
+
+/** The content a (possibly ranged) request is answered from. */
+export interface RangedContent {
+ content: string | Uint8Array;
+ fileName: string;
+ mimeType: string;
+ /** A stable content identifier (a blobId is a content hash), sent as the ETag so a dropped stream can be resumed. */
+ etag?: string;
+}
+
+/** A byte range with both ends inclusive — the form the HTTP `Range` header speaks in. */
+export interface ByteRange {
+ start: number;
+ end: number;
+}
+
+/**
+ * Answers a request for `content` the way a static file server does: the whole body by default, a
+ * `206` carrying just the requested slice when the client sends a `Range` header, and a `416` when
+ * that header names bytes the content does not have. Media elements rely on this to seek without
+ * pulling the whole file down first.
+ *
+ * Deliberately transport-neutral: it touches only `status`/`setHeader`/`send`, the response surface
+ * Express and the standalone browser router both implement, so one handler serves the server,
+ * desktop and standalone (WASM) variants alike.
+ */
+export function serveContentWithRanges(req: Request, res: Response, { content, fileName, mimeType, etag }: RangedContent) {
+ const bytes = wrapStringOrBuffer(content);
+ const totalSize = bytes.byteLength;
+
+ res.setHeader("Content-Type", mimeType);
+ res.setHeader("Content-Disposition", getContentDisposition(fileName));
+ res.setHeader("Accept-Ranges", "bytes");
+ if (etag) {
+ // An entity-tag is quoted by definition; caches and proxies ignore an unquoted one.
+ res.setHeader("ETag", /^(W\/)?".*"$/.test(etag) ? etag : `"${etag}"`);
+ }
+
+ const rangeHeader = req.headers?.range;
+
+ let range: ByteRange | null;
+ try {
+ range = parseRangeHeader(rangeHeader, totalSize);
+ } catch {
+ res.setHeader("Content-Range", `bytes */${totalSize}`);
+ return res.status(416).send(`Invalid value for Range: ${rangeHeader}`);
+ }
+
+ if (!range) {
+ res.setHeader("Content-Length", String(totalSize));
+ return res.send(toResponseBody(bytes));
+ }
+
+ const { start, end } = range;
+ res.setHeader("Content-Range", `bytes ${start}-${end}/${totalSize}`);
+ res.setHeader("Content-Length", String(end - start + 1));
+ // A slice must never be cached as if it were the whole file.
+ res.setHeader("Cache-Control", "no-cache");
+ return res.status(206).send(toResponseBody(bytes.subarray(start, end + 1)));
+}
+
+const RANGE_PATTERN = /^bytes=(\d*)-(\d*)$/;
+
+/**
+ * Resolves a `Range` header against the content's size into a clamped, inclusive range, or `null`
+ * when the whole body should be served. Only a single range is supported, which is all a media
+ * element ever asks for.
+ *
+ * A header that cannot be parsed is ignored rather than rejected (RFC 9110 §14.2), so an odd client
+ * still gets its content; only a well-formed range that falls outside the content is unsatisfiable.
+ */
+function parseRangeHeader(rangeHeader: string | undefined, totalSize: number): ByteRange | null {
+ const match = rangeHeader ? RANGE_PATTERN.exec(rangeHeader.trim()) : null;
+ if (!match || totalSize === 0) {
+ return null;
+ }
+
+ const [ , startValue, endValue ] = match;
+
+ // `bytes=-500` asks for the last 500 bytes, not for a range starting at zero.
+ if (startValue === "") {
+ const suffixLength = Number(endValue);
+ if (endValue === "" || suffixLength === 0) {
+ throw new UnsatisfiableRangeError();
+ }
+
+ return { start: Math.max(totalSize - suffixLength, 0), end: totalSize - 1 };
+ }
+
+ const start = Number(startValue);
+ // `bytes=500-` runs to the end, and an end past it is clamped rather than refused.
+ const end = endValue === "" ? totalSize - 1 : Math.min(Number(endValue), totalSize - 1);
+
+ if (start > end || start >= totalSize) {
+ throw new UnsatisfiableRangeError();
+ }
+
+ return { start, end };
+}
+
+class UnsatisfiableRangeError extends Error {}
+
+/**
+ * Express only recognises a Buffer as a binary body — a plain `Uint8Array` would be JSON-serialised —
+ * while the standalone router takes either. Wraps without copying, and leaves the bytes alone in the
+ * browser, where there is no Buffer.
+ */
+function toResponseBody(bytes: Uint8Array): Uint8Array {
+ if (typeof Buffer === "undefined" || Buffer.isBuffer(bytes)) {
+ return bytes;
+ }
+
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+}