Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(standalone): check the native transport's ceiling before decoding
Elian Doranbd682e0aa05f
diff --git a/apps/standalone/src/lightweight/bridged_request_provider.spec.ts b/apps/standalone/src/lightweight/bridged_request_provider.spec.tsindex c700a5d94b..56d787d72b 100644--- a/apps/standalone/src/lightweight/bridged_request_provider.spec.ts+++ b/apps/standalone/src/lightweight/bridged_request_provider.spec.ts@@ -264,4 +264,35 @@ describe("BridgedRequestProvider.fetchResource", () => {await expect(promise).rejects.toThrow(/exceeds the 10 byte limit/);});++ /**+ * And refuses it *before* decoding, which is the part that matters. Decoding is where an+ * oversized body multiplies — atob builds a binary string and Uint8Array.from copies that again+ * — so a check running afterwards has already paid for what it is about to refuse.+ */+ it("refuses an oversized body without decoding it", async () => {+ const decode = vi.spyOn(globalThis, "atob");+ const provider = new BridgedRequestProvider();+ const promise = provider.fetchResource("https://example.com/big", { maxBytes: 10 });++ respond({ status: 200, headers: {}, body: btoa("x".repeat(5000)) });++ await expect(promise).rejects.toThrow(/exceeds the 10 byte limit/);+ expect(decode).not.toHaveBeenCalled();+ });++ it("measures the decoded size rather than the encoded one, at every padding", async () => {+ // Base64 runs 4/3 the size of what it carries, so measuring the encoded string would refuse+ // a 30-byte body against a 30-byte ceiling. The three lengths cover the three paddings.+ for (const length of [ 30, 29, 28 ]) {+ const provider = new BridgedRequestProvider();+ const promise = provider.fetchResource("https://example.com/exact", { maxBytes: 30 });++ respond({ status: 200, headers: {}, body: btoa("x".repeat(length)) });++ await expect(promise).resolves.toMatchObject({+ bytes: new Uint8Array(length).fill("x".charCodeAt(0))+ });+ }+ });});diff --git a/apps/standalone/src/lightweight/bridged_request_provider.ts b/apps/standalone/src/lightweight/bridged_request_provider.tsindex 5fbc13a03b..167aac54c6 100644--- a/apps/standalone/src/lightweight/bridged_request_provider.ts+++ b/apps/standalone/src/lightweight/bridged_request_provider.ts@@ -158,11 +158,18 @@ export default class BridgedRequestProvider implements RequestProvider {* provider exists: the cross-origin hop happens outside the WebView, so a page that sends no* CORS headers — which is nearly every page worth previewing — can still be read.*- * Two things the server's implementation has are missing here, and neither can be had:+ * Two things the server's implementation has are missing here, and neither can be had in full:*- * - The body arrives whole, so `maxBytes` is enforced on what came back rather than on what is- * still coming. A native transport hands over a complete response; there is no stream to- * abandon partway. The ceiling still holds, it is just paid for before it is checked.+ * - The body arrives whole, so there is no stream to abandon partway. `maxBytes` is checked+ * against the encoded length the moment the reply lands and before anything is decoded from+ * it, which is the earliest point this side of the bridge can see a size at all — see+ * {@link decodedLengthOf}. What that spares is the decoding, which is where the cost+ * multiplies: `atob` yields a binary string and `Uint8Array.from` yields a copy of that, so a+ * body checked afterwards has already been held three times over.+ * It does not spare what the native side and the bridge already spent to deliver it. Bounding+ * *that* means giving the ceiling to the transport, which the plugin cannot honour — it+ * answers only once the whole response is in hand. The Android streaming proxy could, and+ * binding these two together is the fix worth making; it is not this change.* - Nothing resolves the hostname, so the private-address check cannot be made and DNS* rebinding has no meaning here anyway. What is left is {@link validateFetchableUrl}, and* the reason that is enough: this transport runs on the user's own device, reaching the@@ -189,12 +196,14 @@ export default class BridgedRequestProvider implements RequestProvider {});});- const binary = atob(msg.body ?? "");+ const encoded = msg.body ?? "";- if (binary.length > opts.maxBytes) {+ if (decodedLengthOf(encoded) > opts.maxBytes) {throw new Error(`Response exceeds the ${opts.maxBytes} byte limit`);}+ const binary = atob(encoded);+return {status: msg.status,ok: msg.status >= 200 && msg.status < 300,@@ -204,6 +213,23 @@ export default class BridgedRequestProvider implements RequestProvider {}}+/**+ * How many bytes a base64 string will decode to, counted without decoding it.+ *+ * Four characters carry three bytes, less whatever the trailing `=` padding stands in for. Exact+ * for well-formed input, which is what the bridge produces; a malformed body only ever makes this+ * an over-estimate, and over-estimating is the safe direction for a ceiling.+ */+function decodedLengthOf(base64: string): number {+ if (!base64) {+ return 0;+ }++ const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;++ return Math.floor(base64.length / 4) * 3 - padding;+}+/** What the main thread answers an HTTP_REQUEST with, for the binary shape of the exchange. */interface BridgedResponse {status: number;diff --git a/packages/trilium-core/src/routes/api/link_embed.ts b/packages/trilium-core/src/routes/api/link_embed.tsindex a9b6b55463..0ccc90a998 100644--- a/packages/trilium-core/src/routes/api/link_embed.ts+++ b/packages/trilium-core/src/routes/api/link_embed.ts@@ -17,6 +17,7 @@ import { getImageProvider } from "../../services/image_provider.js";import { getLog } from "../../services/log.js";import { findPageDescription } from "../../services/page_description.js";import request, { type FetchedResource, validateFetchableUrl } from "../../services/request.js";+import { decodeUtf8 } from "../../services/utils/binary.js";const MAX_RESPONSE_SIZE = 512 * 1024; // 512KB/** An oEmbed answer is a handful of fields; anything approaching this is not one. */@@ -81,7 +82,7 @@ const MAX_FAVICON_CANDIDATES = 3;* sake of a title that is occasionally accented.*/function asText({ bytes }: FetchedResource): string {- return new TextDecoder().decode(bytes);+ return decodeUtf8(bytes);}/**