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
refactor(server): move safe fetch into dedicated module
Elian Dorane56aa18a6473
diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.tsindex 032c18b88c..adee0ea0b9 100644--- a/apps/server/src/routes/api/link_embed.spec.ts+++ b/apps/server/src/routes/api/link_embed.spec.ts@@ -1,90 +1,6 @@-import { describe, expect, it, vi } from "vitest";-import dns from "node:dns";-import { extractYouTubeVideoId } from "@triliumnext/commons";-import { validateHostResolution, validateUrl } from "./link_embed.js";--vi.mock("../../services/log.js", () => ({- default: { info: vi.fn(), error: vi.fn() }-}));--describe("validateUrl", () => {- it("accepts http URLs", () => {- const result = validateUrl("http://example.com");- expect(result.hostname).toBe("example.com");- });-- it("accepts https URLs", () => {- const result = validateUrl("https://example.com/path?q=1");- expect(result.hostname).toBe("example.com");- });-- it("rejects non-http protocols", () => {- expect(() => validateUrl("ftp://example.com")).toThrow("Only http and https");- expect(() => validateUrl("file:///etc/passwd")).toThrow("Only http and https");- expect(() => validateUrl("javascript:alert(1)")).toThrow("Only http and https");- });-- it("rejects invalid URLs", () => {- expect(() => validateUrl("not-a-url")).toThrow("Invalid URL");- expect(() => validateUrl("")).toThrow("Invalid URL");- });-});--describe("validateHostResolution", () => {- it("rejects private IPv4 literals", async () => {- await expect(validateHostResolution("127.0.0.1")).rejects.toThrow("private/internal");- await expect(validateHostResolution("10.0.0.1")).rejects.toThrow("private/internal");- await expect(validateHostResolution("192.168.1.1")).rejects.toThrow("private/internal");- await expect(validateHostResolution("172.16.0.1")).rejects.toThrow("private/internal");- await expect(validateHostResolution("169.254.1.1")).rejects.toThrow("private/internal");- await expect(validateHostResolution("0.0.0.0")).rejects.toThrow("private/internal");- });-- it("rejects private IPv6 literals", async () => {- await expect(validateHostResolution("::1")).rejects.toThrow("private/internal");- await expect(validateHostResolution("fc00::1")).rejects.toThrow("private/internal");- await expect(validateHostResolution("fd12::1")).rejects.toThrow("private/internal");- await expect(validateHostResolution("fe80::1")).rejects.toThrow("private/internal");- });+import { describe, expect, it } from "vitest";- it("allows public IP literals and returns validated addresses", async () => {- await expect(validateHostResolution("8.8.8.8")).resolves.toEqual([{ address: "8.8.8.8", family: 4 }]);- await expect(validateHostResolution("1.1.1.1")).resolves.toEqual([{ address: "1.1.1.1", family: 4 }]);- });-- it("rejects hostnames that resolve to private IPs (DNS rebinding)", async () => {- vi.spyOn(dns.promises, "lookup").mockResolvedValueOnce([- { address: "127.0.0.1", family: 4 }- ] as unknown as dns.LookupAddress);-- await expect(validateHostResolution("evil.example.com")).rejects.toThrow("private/internal");- });-- it("rejects hostnames where any resolved address is private", async () => {- vi.spyOn(dns.promises, "lookup").mockResolvedValueOnce([- { address: "93.184.216.34", family: 4 },- { address: "10.0.0.1", family: 4 }- ] as unknown as dns.LookupAddress);-- await expect(validateHostResolution("dual.example.com")).rejects.toThrow("private/internal");- });-- it("allows hostnames that resolve to public IPs and returns addresses", async () => {- vi.spyOn(dns.promises, "lookup").mockResolvedValueOnce([- { address: "93.184.216.34", family: 4 }- ] as unknown as dns.LookupAddress);-- await expect(validateHostResolution("example.com")).resolves.toEqual([- { address: "93.184.216.34", family: 4 }- ]);- });-- it("rejects hostnames that fail to resolve", async () => {- vi.spyOn(dns.promises, "lookup").mockRejectedValueOnce(new Error("ENOTFOUND"));-- await expect(validateHostResolution("nonexistent.invalid")).rejects.toThrow("Could not resolve hostname");- });-});+import { extractYouTubeVideoId } from "@triliumnext/commons";describe("extractYouTubeVideoId", () => {it("extracts ID from standard watch URL", () => {diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.tsindex d34f477730..482ea837c5 100644--- a/apps/server/src/routes/api/link_embed.ts+++ b/apps/server/src/routes/api/link_embed.ts@@ -1,117 +1,13 @@-import dns from "node:dns";-import net from "node:net";--import { type LinkEmbedMetadata, extractYouTubeVideoId } from "@triliumnext/commons";+import { extractYouTubeVideoId,type LinkEmbedMetadata } from "@triliumnext/commons";import { ValidationError } from "@triliumnext/core";import type { Request } from "express";import { parse } from "node-html-parser";-import ipaddr from "ipaddr.js";-import { Agent } from "undici";import log from "../../services/log.js";+import { safeFetch, validateUrl } from "../../services/safe_fetch.js";-const FETCH_TIMEOUT_MS = 5000;const MAX_RESPONSE_SIZE = 512 * 1024; // 512KBconst MAX_FAVICON_SIZE = 64 * 1024; // 64KB-const MAX_REDIRECTS = 5;---const ALLOWED_IP_RANGES = new Set(["unicast"]);--/**- * Checks whether an IP address is private/reserved using ipaddr.js.- * Returns true if the IP should be blocked.- */-function isBlockedIP(ip: string): boolean {- try {- let parsed = ipaddr.parse(ip);- // For IPv4-mapped IPv6 addresses, extract and check the IPv4 part- if (parsed.kind() === "ipv6" && (parsed as ipaddr.IPv6).isIPv4MappedAddress()) {- parsed = (parsed as ipaddr.IPv6).toIPv4Address();- }- return !ALLOWED_IP_RANGES.has(parsed.range());- } catch {- return true; // unparseable → treat as blocked- }-}--/**- * Resolves the hostname to IP addresses and verifies none are private/reserved.- * Returns the validated addresses so they can be pinned for the actual connection.- */-async function validateHostResolution(hostname: string): Promise<dns.LookupAddress[]> {- // If the hostname is already an IP literal, check it directly- if (net.isIP(hostname)) {- if (isBlockedIP(hostname)) {- throw new ValidationError("URLs pointing to private/internal networks are not allowed");- }- return [{ address: hostname, family: net.isIP(hostname) as 4 | 6 }];- }-- let addresses: dns.LookupAddress[];- try {- addresses = await dns.promises.lookup(hostname, { all: true });- } catch {- throw new ValidationError("Could not resolve hostname");- }-- for (const addr of addresses) {- if (isBlockedIP(addr.address)) {- throw new ValidationError("URLs pointing to private/internal networks are not allowed");- }- }-- return 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");- }-- return parsed;-}--/**- * Creates a custom DNS lookup function that only returns pre-validated IP addresses,- * preventing DNS rebinding attacks by ensuring the TCP connection uses the same IPs- * that were checked during SSRF validation.- */-function createPinnedLookup(validatedAddresses: dns.LookupAddress[]) {- // Node's net.connect calls lookup with { all: true, hints } and expects- // the callback signature (err, addresses[]). Handle both the all and- // single-address forms so this works across Node versions.- return (- _hostname: string,- options: { family?: number; all?: boolean } | number,- callback: (...args: unknown[]) => void- ) => {- const opts = typeof options === "number" ? { family: options } : options;-- let filtered = validatedAddresses;- if (opts.family === 4 || opts.family === 6) {- filtered = validatedAddresses.filter((a) => a.family === opts.family);- }-- if (filtered.length === 0) {- callback(new Error("No validated addresses available for the requested address family"));- return;- }-- if (opts.all) {- callback(null, filtered);- } else {- callback(null, filtered[0].address, filtered[0].family);- }- };-}/*** Reads the response body as text, stopping after maxBytes to avoid@@ -137,93 +33,6 @@ async function readResponseText(response: Response, maxBytes: number): Promise<sreturn result.slice(0, maxBytes);}-/**- * Wraps a Response so that reading/cancelling the body automatically- * closes the associated undici dispatcher afterwards.- */-function withDispatcherCleanup(response: Response, dispatcher: Agent): Response {- const originalBody = response.body;- if (!originalBody) {- dispatcher.close();- return response;- }-- let closed = false;- const cleanup = () => {- if (!closed) {- closed = true;- dispatcher.close();- }- };-- const reader = originalBody.getReader();- const wrappedBody = new ReadableStream({- async pull(controller) {- const { done, value } = await reader.read();- if (done) {- controller.close();- cleanup();- } else {- controller.enqueue(value);- }- },- cancel() {- reader.cancel();- cleanup();- }- });-- return new Response(wrappedBody, {- status: response.status,- statusText: response.statusText,- headers: response.headers- });-}--/**- * Fetches a URL with SSRF protection: resolves the hostname, validates- * the resulting IP, and pins the connection to that IP to prevent DNS rebinding.- */-async function safeFetch(url: string, options: RequestInit = {}): Promise<Response> {- let currentUrl = url;-- for (let i = 0; i <= MAX_REDIRECTS; i++) {- const parsed = validateUrl(currentUrl);- const validatedAddresses = await validateHostResolution(parsed.hostname);-- // Use a custom dispatcher that pins DNS to the validated IPs,- // preventing a second DNS lookup from resolving to a different (private) IP.- const dispatcher = new Agent({- connect: {- lookup: createPinnedLookup(validatedAddresses) as never- }- });-- // URL and resolved IPs are validated above and pinned via the custom dispatcher.- // Node.js fetch supports `dispatcher` at runtime (undici), but the type isn't in RequestInit.- const fetchOptions = {- ...options,- redirect: "manual" as const,- signal: options.signal ?? AbortSignal.timeout(FETCH_TIMEOUT_MS),- dispatcher- };- const response = await fetch(currentUrl, fetchOptions as RequestInit); // codeql[js/request-forgery]-- if (response.status >= 300 && response.status < 400) {- const location = response.headers.get("location");- if (!location) throw new Error("Redirect without Location header");- // Resolve relative redirects against the current URL- currentUrl = new URL(location, currentUrl).toString();- dispatcher.close();- continue;- }-- return withDispatcherCleanup(response, dispatcher);- }-- throw new Error("Too many redirects");-}-/*** Downloads a favicon and returns it as a base64 data URI.* Returns undefined if the download fails or the image is too large.@@ -398,4 +207,3 @@ async function getMetadata(req: Request) {}export default { getMetadata };-export { validateHostResolution, validateUrl };diff --git a/apps/server/src/services/safe_fetch.spec.ts b/apps/server/src/services/safe_fetch.spec.tsnew file mode 100644index 0000000000..29b8a109e7--- /dev/null+++ b/apps/server/src/services/safe_fetch.spec.ts@@ -0,0 +1,84 @@+import dns from "node:dns";++import { describe, expect, it, vi } from "vitest";++import { validateHostResolution, validateUrl } from "./safe_fetch.js";++describe("validateUrl", () => {+ it("accepts http URLs", () => {+ const result = validateUrl("http://example.com");+ expect(result.hostname).toBe("example.com");+ });++ it("accepts https URLs", () => {+ const result = validateUrl("https://example.com/path?q=1");+ expect(result.hostname).toBe("example.com");+ });++ it("rejects non-http protocols", () => {+ expect(() => validateUrl("ftp://example.com")).toThrow("Only http and https");+ expect(() => validateUrl("file:///etc/passwd")).toThrow("Only http and https");+ expect(() => validateUrl("javascript:alert(1)")).toThrow("Only http and https");+ });++ it("rejects invalid URLs", () => {+ expect(() => validateUrl("not-a-url")).toThrow("Invalid URL");+ expect(() => validateUrl("")).toThrow("Invalid URL");+ });+});++describe("validateHostResolution", () => {+ it("rejects private IPv4 literals", async () => {+ await expect(validateHostResolution("127.0.0.1")).rejects.toThrow("private/internal");+ await expect(validateHostResolution("10.0.0.1")).rejects.toThrow("private/internal");+ await expect(validateHostResolution("192.168.1.1")).rejects.toThrow("private/internal");+ await expect(validateHostResolution("172.16.0.1")).rejects.toThrow("private/internal");+ await expect(validateHostResolution("169.254.1.1")).rejects.toThrow("private/internal");+ await expect(validateHostResolution("0.0.0.0")).rejects.toThrow("private/internal");+ });++ it("rejects private IPv6 literals", async () => {+ await expect(validateHostResolution("::1")).rejects.toThrow("private/internal");+ await expect(validateHostResolution("fc00::1")).rejects.toThrow("private/internal");+ await expect(validateHostResolution("fd12::1")).rejects.toThrow("private/internal");+ await expect(validateHostResolution("fe80::1")).rejects.toThrow("private/internal");+ });++ it("allows public IP literals and returns validated addresses", async () => {+ await expect(validateHostResolution("8.8.8.8")).resolves.toEqual([{ address: "8.8.8.8", family: 4 }]);+ await expect(validateHostResolution("1.1.1.1")).resolves.toEqual([{ address: "1.1.1.1", family: 4 }]);+ });++ it("rejects hostnames that resolve to private IPs (DNS rebinding)", async () => {+ vi.spyOn(dns.promises, "lookup").mockResolvedValueOnce([+ { address: "127.0.0.1", family: 4 }+ ] as unknown as dns.LookupAddress);++ await expect(validateHostResolution("evil.example.com")).rejects.toThrow("private/internal");+ });++ it("rejects hostnames where any resolved address is private", async () => {+ vi.spyOn(dns.promises, "lookup").mockResolvedValueOnce([+ { address: "93.184.216.34", family: 4 },+ { address: "10.0.0.1", family: 4 }+ ] as unknown as dns.LookupAddress);++ await expect(validateHostResolution("dual.example.com")).rejects.toThrow("private/internal");+ });++ it("allows hostnames that resolve to public IPs and returns addresses", async () => {+ vi.spyOn(dns.promises, "lookup").mockResolvedValueOnce([+ { address: "93.184.216.34", family: 4 }+ ] as unknown as dns.LookupAddress);++ await expect(validateHostResolution("example.com")).resolves.toEqual([+ { address: "93.184.216.34", family: 4 }+ ]);+ });++ it("rejects hostnames that fail to resolve", async () => {+ vi.spyOn(dns.promises, "lookup").mockRejectedValueOnce(new Error("ENOTFOUND"));++ await expect(validateHostResolution("nonexistent.invalid")).rejects.toThrow("Could not resolve hostname");+ });+});diff --git a/apps/server/src/services/safe_fetch.ts b/apps/server/src/services/safe_fetch.tsnew file mode 100644index 0000000000..4ccf81c865--- /dev/null+++ b/apps/server/src/services/safe_fetch.ts@@ -0,0 +1,195 @@+import dns from "node:dns";+import net from "node:net";++import { ValidationError } from "@triliumnext/core";+import ipaddr from "ipaddr.js";+import { Agent } from "undici";++const FETCH_TIMEOUT_MS = 5000;+const MAX_REDIRECTS = 5;++const ALLOWED_IP_RANGES = new Set(["unicast"]);++/**+ * Checks whether an IP address is private/reserved using ipaddr.js.+ * Returns true if the IP should be blocked.+ */+function isBlockedIP(ip: string): boolean {+ try {+ let parsed = ipaddr.parse(ip);+ // For IPv4-mapped IPv6 addresses, extract and check the IPv4 part+ if (parsed.kind() === "ipv6" && (parsed as ipaddr.IPv6).isIPv4MappedAddress()) {+ parsed = (parsed as ipaddr.IPv6).toIPv4Address();+ }+ return !ALLOWED_IP_RANGES.has(parsed.range());+ } catch {+ return true; // unparseable → treat as blocked+ }+}++/**+ * Resolves the hostname to IP addresses and verifies none are private/reserved.+ * Returns the validated addresses so they can be pinned for the actual connection.+ */+async function validateHostResolution(hostname: string): Promise<dns.LookupAddress[]> {+ // If the hostname is already an IP literal, check it directly+ if (net.isIP(hostname)) {+ if (isBlockedIP(hostname)) {+ throw new ValidationError("URLs pointing to private/internal networks are not allowed");+ }+ return [{ address: hostname, family: net.isIP(hostname) as 4 | 6 }];+ }++ let addresses: dns.LookupAddress[];+ try {+ addresses = await dns.promises.lookup(hostname, { all: true });+ } catch {+ throw new ValidationError("Could not resolve hostname");+ }++ for (const addr of addresses) {+ if (isBlockedIP(addr.address)) {+ throw new ValidationError("URLs pointing to private/internal networks are not allowed");+ }+ }++ return 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");+ }++ return parsed;+}++/**+ * Creates a custom DNS lookup function that only returns pre-validated IP addresses,+ * preventing DNS rebinding attacks by ensuring the TCP connection uses the same IPs+ * that were checked during SSRF validation.+ */+function createPinnedLookup(validatedAddresses: dns.LookupAddress[]) {+ // Node's net.connect calls lookup with { all: true, hints } and expects+ // the callback signature (err, addresses[]). Handle both the all and+ // single-address forms so this works across Node versions.+ return (+ _hostname: string,+ options: { family?: number; all?: boolean } | number,+ callback: (...args: unknown[]) => void+ ) => {+ const opts = typeof options === "number" ? { family: options } : options;++ let filtered = validatedAddresses;+ if (opts.family === 4 || opts.family === 6) {+ filtered = validatedAddresses.filter((a) => a.family === opts.family);+ }++ if (filtered.length === 0) {+ callback(new Error("No validated addresses available for the requested address family"));+ return;+ }++ if (opts.all) {+ callback(null, filtered);+ } else {+ callback(null, filtered[0].address, filtered[0].family);+ }+ };+}++/**+ * Wraps a Response so that reading/cancelling the body automatically+ * closes the associated undici dispatcher afterwards.+ */+function withDispatcherCleanup(response: Response, dispatcher: Agent): Response {+ const originalBody = response.body;+ if (!originalBody) {+ dispatcher.close();+ return response;+ }++ let closed = false;+ const cleanup = () => {+ if (!closed) {+ closed = true;+ dispatcher.close();+ }+ };++ const reader = originalBody.getReader();+ const wrappedBody = new ReadableStream({+ async pull(controller) {+ const { done, value } = await reader.read();+ if (done) {+ controller.close();+ cleanup();+ } else {+ controller.enqueue(value);+ }+ },+ cancel() {+ reader.cancel();+ cleanup();+ }+ });++ return new Response(wrappedBody, {+ status: response.status,+ statusText: response.statusText,+ headers: response.headers+ });+}++/**+ * Fetches a URL with SSRF protection: resolves the hostname, validates+ * the resulting IP, and pins the connection to that IP to prevent DNS rebinding.+ */+async function safeFetch(url: string, options: RequestInit = {}): Promise<Response> {+ let currentUrl = url;++ for (let i = 0; i <= MAX_REDIRECTS; i++) {+ const parsed = validateUrl(currentUrl);+ const validatedAddresses = await validateHostResolution(parsed.hostname);++ // Use a custom dispatcher that pins DNS to the validated IPs,+ // preventing a second DNS lookup from resolving to a different (private) IP.+ const dispatcher = new Agent({+ connect: {+ lookup: createPinnedLookup(validatedAddresses) as never+ }+ });++ // URL and resolved IPs are validated above and pinned via the custom dispatcher.+ // Node.js fetch supports `dispatcher` at runtime (undici), but the type isn't in RequestInit.+ const fetchOptions = {+ ...options,+ redirect: "manual" as const,+ signal: options.signal ?? AbortSignal.timeout(FETCH_TIMEOUT_MS),+ dispatcher+ };+ const response = await fetch(currentUrl, fetchOptions as RequestInit); // codeql[js/request-forgery]++ if (response.status >= 300 && response.status < 400) {+ const location = response.headers.get("location");+ if (!location) throw new Error("Redirect without Location header");+ // Resolve relative redirects against the current URL+ currentUrl = new URL(location, currentUrl).toString();+ dispatcher.close();+ continue;+ }++ return withDispatcherCleanup(response, dispatcher);+ }++ throw new Error("Too many redirects");+}++export { safeFetch, validateHostResolution, validateUrl };