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
feat(request): add fetchResource, the seam a page fetch can cross runtimes on
Elian Doran5642274d0c9a
diff --git a/apps/server/src/services/request.ts b/apps/server/src/services/request.tsindex 84a75b55f2..c24e332391 100644--- a/apps/server/src/services/request.ts+++ b/apps/server/src/services/request.ts@@ -1,9 +1,10 @@"use strict";-import { type CookieJar, type ExecOpts, getLog, type RequestProvider, sync_options as syncOptions } from "@triliumnext/core";+import { type CookieJar, type ExecOpts, type FetchedResource, type FetchResourceOpts, getLog, type RequestProvider, sync_options as syncOptions } from "@triliumnext/core";+import { readCappedResponse } from "@triliumnext/core/src/services/request.js";import url from "url";-import { createPinnedLookup, validateHostResolution, validateUrl } from "./safe_fetch.js";+import { createPinnedLookup, safeFetch, validateHostResolution, validateUrl } from "./safe_fetch.js";// this service provides abstraction over node's HTTP/HTTPS modules.// Subclasses (e.g. apps/desktop's ElectronRequestProvider) can override@@ -193,6 +194,20 @@ export default class NodeRequestProvider implements RequestProvider {});}+ /**+ * Fetches a third-party resource, hardened the same way {@link getImage} is: the address is+ * vetted, the name resolved, the private ranges refused, and the connection pinned to the+ * addresses that were actually checked, so a second lookup cannot answer differently.+ *+ * This is the runtime where all of that is possible, and where it is most needed — the network+ * a server can see is not one the author of a note is entitled to reach through it.+ */+ async fetchResource(resourceUrl: string, opts: FetchResourceOpts): Promise<FetchedResource> {+ const response = await safeFetch(resourceUrl, { headers: opts.headers });++ return await readCappedResponse(response, opts.maxBytes);+ }+/*** Fetches an image named by note content.*diff --git a/apps/server/src/services/safe_fetch.ts b/apps/server/src/services/safe_fetch.tsindex cc72dd607b..736a160cfb 100644--- a/apps/server/src/services/safe_fetch.ts+++ b/apps/server/src/services/safe_fetch.ts@@ -2,6 +2,7 @@ import dns from "node:dns";import net from "node:net";import { ValidationError } from "@triliumnext/core";+import { validateFetchableUrl } from "@triliumnext/core/src/services/request.js";import ipaddr from "ipaddr.js";import { Agent, fetch as undiciFetch, type RequestInit as UndiciRequestInit, type Response as UndiciResponse } from "undici";@@ -61,27 +62,11 @@ async function validateHostResolution(hostname: string): Promise<dns.LookupAddrereturn addresses;}-function validateUrl(urlString: string): URL {- let parsed: URL;- try {- parsed = new URL(urlString);- } catch {- throw new ValidationError("Invalid URL");- }-- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {- throw new ValidationError("Only http and https URLs are supported");- }-- // `https://user:pass@host/` would put the credentials on the wire, and — for a link preview —- // into the note's stored URL and the server log along with them. Nothing here needs to- // authenticate, so refuse the URL rather than carry a secret around.- if (parsed.username || parsed.password) {- throw new ValidationError("URLs containing credentials are not supported");- }-- return parsed;-}+/**+ * The address checks, which are core's — they are about the URL rather than about the network, so+ * every runtime makes them and only this one can follow them with a resolution.+ */+const validateUrl = validateFetchableUrl;/*** Creates a custom DNS lookup function that only returns pre-validated IP addresses,diff --git a/apps/standalone/src/lightweight/bridged_request_provider.spec.ts b/apps/standalone/src/lightweight/bridged_request_provider.spec.tsindex 8a5198d45c..c700a5d94b 100644--- a/apps/standalone/src/lightweight/bridged_request_provider.spec.ts+++ b/apps/standalone/src/lightweight/bridged_request_provider.spec.ts@@ -209,3 +209,59 @@ describe("BridgedRequestProvider.getImage", () => {await expect(promise).rejects.toThrow("404 GET");});});++describe("BridgedRequestProvider.fetchResource", () => {+ it("asks the native side for the bytes and reports what they came under", async () => {+ const provider = new BridgedRequestProvider();+ const promise = provider.fetchResource("https://example.com/p", {+ maxBytes: 1000,+ headers: { "user-agent": "TriliumNotes" }+ });++ expect(lastPosted().request).toMatchObject({+ method: "GET",+ url: "https://example.com/p",+ headers: { "user-agent": "TriliumNotes" },+ responseType: "arraybuffer"+ });++ respond({ status: 200, headers: { "content-type": "text/html; charset=utf-8" }, body: btoa("<html/>") });++ await expect(promise).resolves.toEqual({+ status: 200,+ ok: true,+ contentType: "text/html",+ bytes: new TextEncoder().encode("<html/>")+ });+ });++ it("answers a non-2xx rather than throwing, the page having said something", async () => {+ const provider = new BridgedRequestProvider();+ const promise = provider.fetchResource("https://example.com/gone", { maxBytes: 1000 });++ respond({ status: 404, headers: {}, body: btoa("nope") });++ await expect(promise).resolves.toMatchObject({ status: 404, ok: false, contentType: "" });+ });++ it("refuses an address before anything is posted for it", async () => {+ const provider = new BridgedRequestProvider();+ const posted = postSpy.mock.calls.length;++ await expect(provider.fetchResource("file:///etc/passwd", { maxBytes: 10 })).rejects.toThrow(/http and https/);+ expect(postSpy.mock.calls.length).toBe(posted);+ });++ /**+ * The ceiling is checked on what arrived rather than on what is arriving — a native transport+ * hands over a whole response, so there is no stream to abandon. It still has to hold.+ */+ it("refuses a body over the ceiling once it is back", async () => {+ const provider = new BridgedRequestProvider();+ const promise = provider.fetchResource("https://example.com/big", { maxBytes: 10 });++ respond({ status: 200, headers: {}, body: btoa("x".repeat(50)) });++ await expect(promise).rejects.toThrow(/exceeds the 10 byte limit/);+ });+});diff --git a/apps/standalone/src/lightweight/bridged_request_provider.ts b/apps/standalone/src/lightweight/bridged_request_provider.tsindex aee83d66d4..ad5c6d7f77 100644--- a/apps/standalone/src/lightweight/bridged_request_provider.ts+++ b/apps/standalone/src/lightweight/bridged_request_provider.ts@@ -1,4 +1,5 @@-import type { ExecOpts, RequestProvider } from "@triliumnext/core";+import type { ExecOpts, FetchedResource, FetchResourceOpts, RequestProvider } from "@triliumnext/core";+import { validateFetchableUrl } from "@triliumnext/core/src/services/request.js";/*** A RequestProvider that delegates HTTP requests to the main thread via postMessage.@@ -151,4 +152,54 @@ export default class BridgedRequestProvider implements RequestProvider {const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));return bytes.buffer;}++ /**+ * Fetches a third-party resource over the native transport, which is the whole reason this+ * 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:+ *+ * - 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.+ * - 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+ * network that user is already on, at the address that user just pasted. The server's rule —+ * that note content is not entitled to the network its host can see — is about a host reached+ * by people who are not its owner, which is not this.+ */+ async fetchResource(resourceUrl: string, opts: FetchResourceOpts): Promise<FetchedResource> {+ const validated = validateFetchableUrl(resourceUrl).toString();+ const id = String(this.nextId++);++ const msg = await new Promise<any>((resolve, reject) => {+ this.pending.set(id, { resolve, reject });++ (self as unknown as Worker).postMessage({+ type: "HTTP_REQUEST",+ id,+ request: {+ method: "GET",+ url: validated,+ headers: opts.headers ?? {},+ responseType: "arraybuffer"+ }+ });+ });++ const binary = atob(msg.body ?? "");++ if (binary.length > opts.maxBytes) {+ throw new Error(`Response exceeds the ${opts.maxBytes} byte limit`);+ }++ return {+ status: msg.status,+ ok: msg.status >= 200 && msg.status < 300,+ contentType: (msg.headers?.["content-type"] ?? "").split(";")[0].trim().toLowerCase(),+ bytes: Uint8Array.from(binary, (c) => c.charCodeAt(0))+ };+ }}diff --git a/apps/standalone/src/lightweight/request_provider.spec.ts b/apps/standalone/src/lightweight/request_provider.spec.tsindex 3cfa07badc..f9a2fa6062 100644--- a/apps/standalone/src/lightweight/request_provider.spec.ts+++ b/apps/standalone/src/lightweight/request_provider.spec.ts@@ -150,3 +150,51 @@ describe("FetchRequestProvider.getImage", () => {await expect(provider.getImage(`${location.origin}/missing.png`)).rejects.toThrow("404 GET");});});++describe("FetchRequestProvider.fetchResource", () => {+ it("reads a capped body and the type it came under", async () => {+ const spy = vi.spyOn(globalThis, "fetch").mockResolvedValue(+ new Response("<html/>", { headers: { "content-type": "text/html; charset=utf-8" } })+ );++ const read = await provider.fetchResource("https://example.com/p", {+ maxBytes: 1000,+ headers: { "user-agent": "TriliumNotes" }+ });++ expect(read).toEqual({+ status: 200,+ ok: true,+ contentType: "text/html",+ bytes: new TextEncoder().encode("<html/>")+ });+ expect(spy.mock.calls[0][1]).toMatchObject({ headers: { "user-agent": "TriliumNotes" } });+ });++ it("refuses an address before a request is made of it", async () => {+ const spy = vi.spyOn(globalThis, "fetch");++ await expect(provider.fetchResource("file:///etc/passwd", { maxBytes: 10 })).rejects.toThrow(/http and https/);+ await expect(provider.fetchResource("https://u:[email protected]/", { maxBytes: 10 })).rejects.toThrow(/credentials/);+ expect(spy).not.toHaveBeenCalled();+ });++ it("refuses a body over the ceiling", async () => {+ vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("x".repeat(50)));++ await expect(provider.fetchResource("https://example.com/big", { maxBytes: 10 }))+ .rejects.toThrow(/exceeds the 10 byte limit/);+ });++ /**+ * The case with no server behind it: a site that sends no CORS headers fails the fetch itself,+ * however healthy the response was. Nothing here can fix that — what matters is that it surfaces+ * as a rejection the caller can degrade on, rather than as an empty preview.+ */+ it("propagates the failure a cross-origin refusal shows up as", async () => {+ vi.spyOn(globalThis, "fetch").mockRejectedValue(new TypeError("Failed to fetch"));++ await expect(provider.fetchResource("https://example.com/p", { maxBytes: 10 }))+ .rejects.toThrow(/Failed to fetch/);+ });+});diff --git a/apps/standalone/src/lightweight/request_provider.ts b/apps/standalone/src/lightweight/request_provider.tsindex cdaa3a34e9..d392d9a7dd 100644--- a/apps/standalone/src/lightweight/request_provider.ts+++ b/apps/standalone/src/lightweight/request_provider.ts@@ -1,4 +1,5 @@-import type { ExecOpts, RequestProvider } from "@triliumnext/core";+import type { ExecOpts, FetchedResource, FetchResourceOpts, RequestProvider } from "@triliumnext/core";+import { readCappedResponse, validateFetchableUrl } from "@triliumnext/core/src/services/request.js";/*** Fetch-based implementation of RequestProvider for browser environments.@@ -90,4 +91,41 @@ export default class FetchRequestProvider implements RequestProvider {return await response.arrayBuffer();}++ /**+ * Fetches a third-party resource with the page's own `fetch`, which means the same-origin+ * policy decides whether the answer can be read at all.+ *+ * A great many sites do not send `Access-Control-Allow-Origin`, and for those this throws+ * however healthy the response was — the request goes out, the browser refuses to hand back+ * what came of it. That is not a fault to work around here: it is what running with no server+ * costs, and the caller is expected to degrade rather than to retry.+ *+ * Notably it is not universal. Static and documentation hosting frequently sends `*`, and the+ * oEmbed endpoints of the large video and audio providers all do, so a good deal is readable+ * this way. Where it is not, the native transport in the sibling provider is the way through.+ *+ * `credentials` stays at its default of `same-origin`: nothing here should carry the user's+ * cookies to a third party just because a link to it was pasted into a note.+ */+ async fetchResource(resourceUrl: string, opts: FetchResourceOpts): Promise<FetchedResource> {+ const validated = validateFetchableUrl(resourceUrl).toString();++ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), FETCH_RESOURCE_TIMEOUT_MS);++ try {+ const response = await fetch(validated, {+ headers: opts.headers,+ signal: controller.signal+ });++ return await readCappedResponse(response, opts.maxBytes);+ } finally {+ clearTimeout(timeoutId);+ }+ }}++/** Matches the server's own fetch timeout, a preview not being worth waiting on for longer. */+const FETCH_RESOURCE_TIMEOUT_MS = 5000;diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex ae67bb9d25..38df33b942 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -116,7 +116,7 @@ export { inspectImage, type InspectedImage, UNKNOWN_FORMAT } from "./services/imexport { type CoreConfig, initConfig, getConfig } from "./services/config";export { default as imageService } from "./services/image";export { t } from "i18next";-export type { RequestProvider, ExecOpts, CookieJar } from "./services/request";+export type { RequestProvider, ExecOpts, CookieJar, FetchResourceOpts, FetchedResource } from "./services/request";export type * from "./meta";export * as routeHelpers from "./routes/helpers";diff --git a/packages/trilium-core/src/services/image_download.spec.ts b/packages/trilium-core/src/services/image_download.spec.tsindex e6d8c1e014..c6d29ddf9c 100644--- a/packages/trilium-core/src/services/image_download.spec.ts+++ b/packages/trilium-core/src/services/image_download.spec.ts@@ -5,6 +5,7 @@ import { getContext } from "./context.js";import { downloadImages, downloadPictureToAttachment, storeLinkPreviewPictures } from "./image_download.js";import noteService from "./notes.js";import optionService from "./options.js";+import { fakeRequestProvider } from "../test/request_provider.js";import { initRequest } from "./request.js";/**@@ -49,8 +50,7 @@ let asked: string[] = [];let answerWith: (url: string) => Buffer | undefined = () => PIXEL_PNG;beforeAll(() => {- initRequest({- exec: async () => { throw new Error("Not used by these tests."); },+ initRequest(fakeRequestProvider({getImage: async (url: string) => {asked.push(url);const bytes = answerWith(url);@@ -61,14 +61,11 @@ beforeAll(() => {return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;}- });+ }));});afterAll(() => {- initRequest({- exec: async () => { throw new Error("Request provider not initialized. Call initRequest() first."); },- getImage: async () => { throw new Error("Request provider not initialized. Call initRequest() first."); }- });+ initRequest(fakeRequestProvider());});beforeEach(() => {diff --git a/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts b/packages/trilium-core/src/services/import/notion/importer.integration.spec.tsindex 2478eb5ed0..b4c6414b4d 100644--- a/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts+++ b/packages/trilium-core/src/services/import/notion/importer.integration.spec.ts@@ -5,6 +5,7 @@ import { describe, expect, it } from "vitest";import becca from "../../../becca/becca.js";import type BNote from "../../../becca/entities/bnote.js";import { getContext } from "../../context.js";+import { fakeRequestProvider } from "../../../test/request_provider.js";import { initRequest } from "../../request.js";import TaskContext from "../../task_context.js";import notionImporter from "./importer.js";@@ -1087,13 +1088,12 @@ describe("Notion importer — integration", () => {+ `<img src="https://cdn.example.com/cover.png" class="bookmark-image"/></a></figure>`;const asked: string[] = [];- initRequest({- exec: async () => { throw new Error("Not used by this test."); },+ initRequest(fakeRequestProvider({getImage: async (address: string) => {asked.push(address);return PIXEL_PNG.buffer.slice(PIXEL_PNG.byteOffset, PIXEL_PNG.byteOffset + PIXEL_PNG.byteLength) as ArrayBuffer;}- });+ }));try {const importRoot = await importNotion({@@ -1113,10 +1113,7 @@ describe("Notion importer — integration", () => {expect(content).not.toContain("https://cdn.example.com/cover.png");expect(content).toContain("api/attachments/");} finally {- initRequest({- exec: async () => { throw new Error("Request provider not initialized. Call initRequest() first."); },- getImage: async () => { throw new Error("Request provider not initialized. Call initRequest() first."); }- });+ initRequest(fakeRequestProvider());}});diff --git a/packages/trilium-core/src/services/notes.spec.ts b/packages/trilium-core/src/services/notes.spec.tsindex 8a76546b01..3267f470be 100644--- a/packages/trilium-core/src/services/notes.spec.ts+++ b/packages/trilium-core/src/services/notes.spec.ts@@ -7,6 +7,7 @@ import { disableEntityEvents, getContext } from "./context.js";import { getLog } from "./log.js";import noteService, { prepareTitle, saveLinks } from "./notes.js";import optionService from "./options.js";+import { fakeRequestProvider } from "../test/request_provider.js";import { initRequest } from "./request.js";import { getSql } from "./sql/index.js";@@ -419,8 +420,7 @@ describe("notes service (real DB)", () => {// The pass itself is covered in image_download.spec.ts. What matters here is the wiring:// saving content is the only thing that starts it.const asked: string[] = [];- initRequest({- exec: async () => { throw new Error("Not used by this test."); },+ initRequest(fakeRequestProvider({getImage: async (address: string) => {asked.push(address);const png = Buffer.from(@@ -429,7 +429,7 @@ describe("notes service (real DB)", () => {);return png.buffer.slice(png.byteOffset, png.byteOffset + png.byteLength) as ArrayBuffer;}- });+ }));const { note } = createNote("root", {title: "spec-preview-wiring",diff --git a/packages/trilium-core/src/services/request.spec.ts b/packages/trilium-core/src/services/request.spec.tsindex f95b346647..994c0b72ba 100644--- a/packages/trilium-core/src/services/request.spec.ts+++ b/packages/trilium-core/src/services/request.spec.ts@@ -1,11 +1,15 @@import { describe, expect, it, vi } from "vitest";+import { fakeRequestProvider } from "../test/request_provider.js";import requestService, {type ExecOpts,+ type FetchedResource,getRequestProvider,initRequest,isRequestInitialized,- type RequestProvider+ readCappedResponse,+ type RequestProvider,+ validateFetchableUrl} from "./request.js";describe("request provider (core)", () => {@@ -16,13 +20,15 @@ describe("request provider (core)", () => {expect(() => getRequestProvider()).toThrow(/not initialized/);});- it("delegates exec/getImage to the installed provider", async () => {+ it("delegates exec/getImage/fetchResource to the installed provider", async () => {const image = new ArrayBuffer(8);+ const resource: FetchedResource = { status: 200, ok: true, contentType: "text/html", bytes: new Uint8Array([ 1 ]) };const execMock = vi.fn(async (_opts: ExecOpts) => ({ ok: true }));- const fake: RequestProvider = {+ const fake: RequestProvider = fakeRequestProvider({exec: execMock as unknown as RequestProvider["exec"],- getImage: vi.fn(async () => image)- };+ getImage: vi.fn(async () => image),+ fetchResource: vi.fn(async () => resource)+ });initRequest(fake);expect(isRequestInitialized()).toBe(true);@@ -34,5 +40,82 @@ describe("request provider (core)", () => {await expect(requestService.getImage("http://localhost/img.png")).resolves.toBe(image);expect(fake.getImage).toHaveBeenCalledWith("http://localhost/img.png");++ await expect(requestService.fetchResource("http://localhost/p", { maxBytes: 10 })).resolves.toBe(resource);+ expect(fake.fetchResource).toHaveBeenCalledWith("http://localhost/p", { maxBytes: 10 });+ });++ it("refuses an address before anything is sent to it", () => {+ expect(validateFetchableUrl("https://example.com/p").toString()).toBe("https://example.com/p");++ expect(() => validateFetchableUrl("not a url")).toThrow(/Invalid URL/);+ expect(() => validateFetchableUrl("file:///etc/passwd")).toThrow(/http and https/);+ expect(() => validateFetchableUrl("javascript:alert(1)")).toThrow(/http and https/);+ // Credentials would otherwise reach the wire, the stored URL and the log alike.+ expect(() => validateFetchableUrl("https://user:[email protected]/")).toThrow(/credentials/);+ expect(() => validateFetchableUrl("https://[email protected]/")).toThrow(/credentials/);+ });+});++describe("readCappedResponse", () => {+ it("reads a body whole and normalises what it came under", async () => {+ const read = await readCappedResponse(+ new Response("hello", { headers: { "content-type": "Text/HTML; charset=UTF-8" } }),+ 1000+ );++ expect(read).toEqual({+ status: 200,+ ok: true,+ contentType: "text/html",+ bytes: new TextEncoder().encode("hello")+ });+ });++ it("answers a non-2xx rather than throwing, so the caller can read what it was", async () => {+ const read = await readCappedResponse(new Response("nope", { status: 404 }), 1000);++ expect(read.status).toBe(404);+ expect(read.ok).toBe(false);+ });++ it("names no content type where the server named none", async () => {+ const read = await readCappedResponse(new Response(null, { headers: {} }), 1000);++ expect(read.contentType).toBe("");+ expect(read.bytes).toEqual(new Uint8Array());+ });++ it("refuses a size the server advertises over the ceiling, without reading it", async () => {+ const body = "x".repeat(100);+ const response = new Response(body, { headers: { "content-length": "100" } });++ await expect(readCappedResponse(response, 10)).rejects.toThrow(/100 bytes exceeds the 10 byte limit/);+ });++ /**+ * The case the advertised size cannot cover: a chunked response states no length at all, so the+ * only place to catch it is mid-stream. Written as a real stream of several chunks so that the+ * refusal has to happen partway rather than after the whole body has arrived.+ */+ it("abandons a stream that goes over the ceiling partway through", async () => {+ let pulled = 0;+ const stream = new ReadableStream<Uint8Array>({+ pull(controller) {+ pulled++;+ controller.enqueue(new Uint8Array(40));+ }+ });++ await expect(readCappedResponse(new Response(stream), 100)).rejects.toThrow(/exceeds the 100 byte limit/);++ // Three chunks of 40 is the first total over 100 — a fourth would mean it read on regardless.+ expect(pulled).toBe(3);+ });++ it("keeps a body that fits exactly", async () => {+ const read = await readCappedResponse(new Response(new Uint8Array(100)), 100);++ expect(read.bytes.byteLength).toBe(100);});});diff --git a/packages/trilium-core/src/services/request.ts b/packages/trilium-core/src/services/request.tsindex ac0a5ec944..b801becbf7 100644--- a/packages/trilium-core/src/services/request.ts+++ b/packages/trilium-core/src/services/request.ts@@ -1,3 +1,5 @@+import { ValidationError } from "../errors.js";+export interface CookieJar {header?: string;}@@ -19,9 +21,49 @@ export interface ExecOpts {body?: string | {};}+/** What a resource fetch is allowed to cost, and what it asks for. */+export interface FetchResourceOpts {+ /**+ * Refuse a body larger than this — both up front, where the server advertises a size, and while+ * it streams, where it does not.+ *+ * Required rather than defaulted, because the ceiling is the whole point: what arrives is a+ * third party's answer, held whole in memory, and on the runtime where that memory is a browser+ * tab there is no second line of defence behind it.+ */+ maxBytes: number;+ headers?: Record<string, string>;+}++/** A resource that arrived whole, within its ceiling. */+export interface FetchedResource {+ status: number;+ ok: boolean;+ /** The media type alone, parameters stripped; empty where the server named none. */+ contentType: string;+ bytes: Uint8Array;+}+export interface RequestProvider {exec<T>(opts: ExecOpts): Promise<T>;getImage(imageUrl: string): Promise<ArrayBuffer>;+ /**+ * Fetches a third-party resource named by note content or by the user, capped at+ * {@link FetchResourceOpts.maxBytes}.+ *+ * Distinct from {@link getImage} in the two things a caller reading a page needs and a caller+ * downloading a picture never did: a ceiling on what it will hold, and the media type it came+ * under. Distinct from {@link exec} in that it is neither JSON nor Trilium's own protocol — the+ * body is handed back as bytes, and what they mean is the caller's business.+ *+ * Throws rather than answering when the resource cannot be had at all: the URL is refused, the+ * transport fails, or the body exceeds its ceiling. A non-2xx *answer* is not that — it comes+ * back with its status, since a caller may well want to read an error page's content type.+ *+ * How hard the address is vetted is the implementation's to decide, and differs by runtime by+ * necessity — see the note on each.+ */+ fetchResource(url: string, opts: FetchResourceOpts): Promise<FetchedResource>;}let requestProvider: RequestProvider | null = null;@@ -47,5 +89,93 @@ export default {},getImage(imageUrl: string): Promise<ArrayBuffer> {return getRequestProvider().getImage(imageUrl);+ },+ fetchResource(url: string, opts: FetchResourceOpts): Promise<FetchedResource> {+ return getRequestProvider().fetchResource(url, opts);}};++/**+ * The checks on an outbound address that hold on every runtime, being about the address itself+ * rather than about what it resolves to.+ *+ * Resolving the name and refusing the private addresses behind it is the other half of this, and it+ * cannot live here: it needs a resolver, which is a Node module on one runtime and does not exist+ * at all on another. So an implementation that has one does that too — see the server's safeFetch —+ * and one that does not still gets these, which are the checks that need no network to make.+ */+export function validateFetchableUrl(urlString: string): URL {+ let parsed: URL;+ try {+ parsed = new URL(urlString);+ } catch {+ throw new ValidationError("Invalid URL");+ }++ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {+ throw new ValidationError("Only http and https URLs are supported");+ }++ // `https://user:pass@host/` would put the credentials on the wire, and — for a link preview —+ // into the note's stored URL and the log along with them. Nothing here needs to authenticate,+ // so refuse the URL rather than carry a secret around.+ if (parsed.username || parsed.password) {+ throw new ValidationError("URLs containing credentials are not supported");+ }++ return parsed;+}++/**+ * Reads a `Response` into a {@link FetchedResource}, refusing a body over `maxBytes`.+ *+ * Shared by every implementation that has a real `Response` to read — the server's, which gets one+ * from its SSRF-hardened fetch, and the browser's, which gets one from `fetch` itself. Only the+ * getting of it differs between those two; the counting does not, and counting is the part with the+ * edge cases: a size advertised and a size not, a body that lies about the first, a stream that has+ * to be abandoned mid-flight rather than read to the end just to discover it was too long.+ */+export async function readCappedResponse(response: Response, maxBytes: number): Promise<FetchedResource> {+ const contentType = (response.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();+ const base = { status: response.status, ok: response.ok, contentType };++ // Bail before reading a byte where the server says how many there will be.+ const advertised = response.headers.get("content-length");+ if (advertised && Number(advertised) > maxBytes) {+ void response.body?.cancel();+ throw new Error(`Response of ${advertised} bytes exceeds the ${maxBytes} byte limit`);+ }++ const reader = response.body?.getReader();+ if (!reader) {+ return { ...base, bytes: new Uint8Array() };+ }++ const chunks: Uint8Array[] = [];+ let total = 0;++ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;++ total += value.byteLength;++ // Checked as it streams, because content-length is a claim and a chunked response makes no+ // claim at all. Abandoned at the moment it goes over rather than read to the end.+ if (total > maxBytes) {+ void reader.cancel();+ throw new Error(`Response exceeds the ${maxBytes} byte limit`);+ }++ chunks.push(value);+ }++ const bytes = new Uint8Array(total);+ let offset = 0;+ for (const chunk of chunks) {+ bytes.set(chunk, offset);+ offset += chunk.byteLength;+ }++ return { ...base, bytes };+}diff --git a/packages/trilium-core/src/services/setup.spec.ts b/packages/trilium-core/src/services/setup.spec.tsindex 220df56331..39b901b0f4 100644--- a/packages/trilium-core/src/services/setup.spec.ts+++ b/packages/trilium-core/src/services/setup.spec.ts@@ -3,16 +3,17 @@ import { afterEach, describe, expect, it, vi } from "vitest";import appInfo from "./app_info.js";import * as cls from "./context.js";import options from "./options.js";+import { fakeRequestProvider } from "../test/request_provider.js";import { type ExecOpts, initRequest, type RequestProvider } from "./request.js";import setupService from "./setup.js";import sqlInit from "./sql_init.js";import syncService from "./sync.js";let execImpl: (opts: ExecOpts) => Promise<unknown> = async () => ({});-const fakeRequest: RequestProvider = {- exec: <T>(opts: ExecOpts) => execImpl(opts) as Promise<T>,+const fakeRequest: RequestProvider = fakeRequestProvider({+ exec: <T,>(opts: ExecOpts) => execImpl(opts) as Promise<T>,getImage: async () => new ArrayBuffer(0)-};+});initRequest(fakeRequest);const flush = () => new Promise((resolve) => setTimeout(resolve, 0));diff --git a/packages/trilium-core/src/services/sync.spec.ts b/packages/trilium-core/src/services/sync.spec.tsindex abdcf23f9d..61b87dac9c 100644--- a/packages/trilium-core/src/services/sync.spec.ts+++ b/packages/trilium-core/src/services/sync.spec.ts@@ -8,6 +8,7 @@ import * as cls from "./context.js";import entityChangesService from "./entity_changes.js";import getInstanceId from "./instance_id.js";import options from "./options.js";+import { fakeRequestProvider } from "../test/request_provider.js";import { type ExecOpts, initRequest, type RequestProvider } from "./request.js";import { getSql } from "./sql/index.js";import setupService from "./setup.js";@@ -41,8 +42,8 @@ let changedIdx = 0;let checkIdx = 0;const requestLog: Array<{ method: string; url: string }> = [];-const fakeRequest: RequestProvider = {- exec: (<T>(opts: ExecOpts): Promise<T> => {+const fakeRequest: RequestProvider = fakeRequestProvider({+ exec: (<T,>(opts: ExecOpts): Promise<T> => {requestLog.push({ method: opts.method, url: opts.url });const url = opts.url;const reply = (value: unknown) => Promise.resolve(value as T);@@ -68,7 +69,7 @@ const fakeRequest: RequestProvider = {return reply({});}) as RequestProvider["exec"],getImage: async () => new ArrayBuffer(0)-};+});initRequest(fakeRequest);const runSync = () => cls.init(() => syncService.sync());diff --git a/packages/trilium-core/src/test/request_provider.ts b/packages/trilium-core/src/test/request_provider.tsnew file mode 100644index 0000000000..9b9d2813b7--- /dev/null+++ b/packages/trilium-core/src/test/request_provider.ts@@ -0,0 +1,23 @@+/**+ * A {@link RequestProvider} standing in for the real one, with only the parts a given test needs.+ *+ * Every test that installs a provider wants one or two of its methods and has no opinion about the+ * rest, and writing the rest out by hand meant that adding a method to the interface broke six+ * unrelated specs at once. Here the unstubbed parts fail loudly instead, which is what a test that+ * reaches one of them should do — it has wandered somewhere it did not mean to go.+ */++import type { FetchedResource, FetchResourceOpts, ExecOpts, RequestProvider } from "../services/request.js";++export function fakeRequestProvider(overrides: Partial<RequestProvider> = {}): RequestProvider {+ return {+ exec: <T,>(_opts: ExecOpts): Promise<T> => unstubbed("exec"),+ getImage: (_imageUrl: string): Promise<ArrayBuffer> => unstubbed("getImage"),+ fetchResource: (_url: string, _opts: FetchResourceOpts): Promise<FetchedResource> => unstubbed("fetchResource"),+ ...overrides+ };+}++function unstubbed(method: string): never {+ throw new Error(`This test installed a request provider without ${method}(), and something called it.`);+}