Skip to content

Build your personal knowledge base with Trilium Notes

fix(llm): vet the provider endpoint address before connecting to it

Elian Dorana06502b3ee2f
diff --git a/SECURITY.md b/SECURITY.md
index a5edc7380e..11a55b98bd 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -69,6 +69,15 @@ User scripting (see Self-XSS above) still intentionally allows arbitrary JavaScr
#### Authenticated User Actions
Actions that require valid authentication and only affect the authenticated user's own data are generally not vulnerabilities.
+#### Private Addresses Reached by a Configured LLM Endpoint
+Outbound requests the server makes on behalf of note content — link previews, image fetches, imports — are vetted against a strict rule: the hostname is resolved, every address behind it must be a public unicast one, and the connection is pinned to the addresses actually checked. Note content is not entitled to the network its host can see.
+
+An LLM provider's base URL is not note content, and the same rule cannot apply to it. Running a model locally is the reason several of the providers exist: Ollama and LM Studio both default to `localhost`, and either is as likely to be another machine on the LAN. A server that refused those addresses would not be a safer Trilium, it would be one where local models do not work at all. So for that destination — and only that one — loopback, RFC1918 and unique-local addresses are deliberately permitted.
+
+Reports that reduce to "an authenticated user can point the LLM base URL at a host on the local network, and the server connects to it" are therefore out of scope, including the reachability and port information that connecting necessarily reveals.
+
+What stays refused is what no model server is ever served on: link-local (`169.254.0.0/16`, which is where a cloud instance answers with its own credentials) and carrier-grade NAT (`100.64.0.0/10`, likewise). Redirects are not followed on these requests at all, since the hop would carry the configured API key to whoever the endpoint named. Defects in **those** guards are in scope, as is any path that reaches them without authentication.
+
#### Denial of Service via Resource Exhaustion
Creating extremely large notes or performing many operations is expected user behavior in a note-taking application.
diff --git a/apps/server/src/services/request.ts b/apps/server/src/services/request.ts
index c24e332391..11e62afca2 100644
--- a/apps/server/src/services/request.ts
+++ b/apps/server/src/services/request.ts
@@ -1,6 +1,6 @@
"use strict";
-import { type CookieJar, type ExecOpts, type FetchedResource, type FetchResourceOpts, getLog, type RequestProvider, sync_options as syncOptions } from "@triliumnext/core";
+import { type CookieJar, type ExecOpts, type FetchApiOpts, 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";
@@ -208,6 +208,26 @@ export default class NodeRequestProvider implements RequestProvider {
return await readCappedResponse(response, opts.maxBytes);
}
+ /**
+ * Calls a configured API endpoint, vetted the same way {@link fetchResource} is but under a
+ * policy that fits what is being called rather than what a note linked to.
+ *
+ * Three things differ, and each is the endpoint's nature rather than a relaxation for its own
+ * sake. A private address is allowed where the caller says the operator chose the destination,
+ * because a model server on this machine is the ordinary case and the ranges that stay refused
+ * are the ones nothing is served on. No deadline is imposed, because a completion runs for
+ * however long the model takes and the caller carries its own abort. And a redirect is refused
+ * outright: the hop would be re-vetted as an address, but the request's `Authorization` header
+ * would go with it, and an API key is not something to hand to whoever a base URL names.
+ */
+ async fetchApi(url: string, init: RequestInit, opts: FetchApiOpts): Promise<Response> {
+ return await safeFetch(url, init, {
+ allowPrivateNetwork: opts.allowPrivateNetwork,
+ timeoutMs: null,
+ maxRedirects: 0
+ });
+ }
+
/**
* Fetches an image named by note content.
*
diff --git a/apps/server/src/services/safe_fetch.spec.ts b/apps/server/src/services/safe_fetch.spec.ts
index fb48a838f0..ba51b0ba23 100644
--- a/apps/server/src/services/safe_fetch.spec.ts
+++ b/apps/server/src/services/safe_fetch.spec.ts
@@ -148,6 +148,52 @@ describe("validateHostResolution", () => {
});
});
+describe("validateHostResolution, for a destination the operator configured", () => {
+ it("allows the addresses a local service is actually served on", async () => {
+ // Where Ollama and LM Studio answer out of the box, and where either sits when it has been
+ // put on another machine. A rule that refused these would leave the local providers with
+ // nothing to talk to, which is the whole reason this policy exists.
+ await expect(validateHostResolution("127.0.0.1", true)).resolves.toEqual([{ address: "127.0.0.1", family: 4 }]);
+ await expect(validateHostResolution("::1", true)).resolves.toEqual([{ address: "::1", family: 6 }]);
+ await expect(validateHostResolution("10.0.0.1", true)).resolves.toEqual([{ address: "10.0.0.1", family: 4 }]);
+ await expect(validateHostResolution("192.168.1.50", true)).resolves.toEqual([{ address: "192.168.1.50", family: 4 }]);
+ await expect(validateHostResolution("172.16.0.1", true)).resolves.toEqual([{ address: "172.16.0.1", family: 4 }]);
+ await expect(validateHostResolution("fd12::1", true)).resolves.toEqual([{ address: "fd12::1", family: 6 }]);
+ });
+
+ it("still refuses the ranges no service is served on and a metadata endpoint answers", async () => {
+ // The reason the widening is a widening rather than a switch to no checking at all.
+ await expect(validateHostResolution("169.254.169.254", true)).rejects.toThrow("link-local");
+ await expect(validateHostResolution("169.254.1.1", true)).rejects.toThrow("link-local");
+ await expect(validateHostResolution("100.100.100.200", true)).rejects.toThrow("link-local");
+ await expect(validateHostResolution("fe80::1", true)).rejects.toThrow("link-local");
+ await expect(validateHostResolution("0.0.0.0", true)).rejects.toThrow("link-local");
+ await expect(validateHostResolution("224.0.0.1", true)).rejects.toThrow("link-local");
+ await expect(validateHostResolution("255.255.255.255", true)).rejects.toThrow("link-local");
+ });
+
+ it("refuses a name that resolves to one of them, and one that hides it behind a second address", async () => {
+ vi.spyOn(dns.promises, "lookup")
+ .mockResolvedValueOnce([{ address: "169.254.169.254", family: 4 }] as unknown as dns.LookupAddress)
+ .mockResolvedValueOnce([
+ { address: "93.184.216.34", family: 4 },
+ { address: "169.254.169.254", family: 4 }
+ ] as unknown as dns.LookupAddress);
+
+ await expect(validateHostResolution("metadata.example.com", true)).rejects.toThrow("link-local");
+ await expect(validateHostResolution("dual.example.com", true)).rejects.toThrow("link-local");
+ });
+
+ it("says which rule refused the address, since one of them permits private ones", async () => {
+ // A caller told its private addresses are refused, when it is the caller that allows them,
+ // would be sent looking for the wrong thing entirely.
+ await expect(validateHostResolution("10.0.0.1")).rejects.toThrow("private/internal");
+
+ const error: Error = await validateHostResolution("169.254.169.254", true).then(() => new Error("resolved"), e => e);
+ expect(error.message).not.toContain("private/internal");
+ });
+});
+
describe("safeFetch", () => {
let fetchMock: ReturnType<typeof vi.fn>;
@@ -277,6 +323,39 @@ describe("safeFetch", () => {
await expect(safeFetch("http://8.8.8.8/loop")).rejects.toThrow("Too many redirects");
});
+ it("refuses a redirect outright for a caller that follows none, without fetching the target", async () => {
+ // The hop would be re-vetted as an address, but the request's own `Authorization` header
+ // would travel with it — which for a configured API endpoint means handing the user's key
+ // to whoever the base URL named. A caller carrying a credential follows no redirects.
+ fetchMock.mockResolvedValueOnce(
+ makeResponse(null, { status: 302, headers: { location: "https://8.8.4.4/collect" } })
+ );
+
+ await expect(safeFetch("https://8.8.8.8/v1/chat", {}, { maxRedirects: 0 }))
+ .rejects.toThrow("Refusing to follow a redirect");
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(agentInstances[0].closed).toBe(true);
+ });
+
+ it("imposes no deadline of its own on a caller that asked for none", async () => {
+ // A completion runs for as long as the model takes, and the five seconds a link preview is
+ // worth waiting would cut one off mid-answer.
+ fetchMock.mockResolvedValueOnce(makeResponse(null, { status: 200 }));
+
+ await safeFetch("http://8.8.8.8/v1/chat", {}, { timeoutMs: null });
+
+ const fetchOptions = fetchMock.mock.calls[0][1] as { signal: unknown };
+ expect(fetchOptions.signal).toBeUndefined();
+ });
+
+ it("reaches a loopback endpoint when the caller permits private addresses, and not otherwise", async () => {
+ fetchMock.mockResolvedValue(makeResponse(null, { status: 200 }));
+
+ await expect(safeFetch("http://127.0.0.1:11434/v1/models", {}, { allowPrivateNetwork: true }))
+ .resolves.toBeDefined();
+ await expect(safeFetch("http://127.0.0.1:11434/v1/models")).rejects.toThrow("private/internal");
+ });
+
it("uses a caller-provided abort signal when present", async () => {
const controller = new AbortController();
fetchMock.mockResolvedValueOnce(makeResponse(null, { status: 200 }));
diff --git a/apps/server/src/services/safe_fetch.ts b/apps/server/src/services/safe_fetch.ts
index 736a160cfb..5f8f15785a 100644
--- a/apps/server/src/services/safe_fetch.ts
+++ b/apps/server/src/services/safe_fetch.ts
@@ -11,18 +11,54 @@ const MAX_REDIRECTS = 5;
const ALLOWED_IP_RANGES = new Set(["unicast"]);
+/**
+ * What the default set refuses, minus the ranges a self-hosted service is actually served on.
+ *
+ * For an address the user typed into their own settings — a local model server being the case
+ * this exists for — a private address is the ordinary answer rather than a suspicious one:
+ * Ollama and LM Studio both default to loopback, and putting either on another machine on the
+ * LAN is common enough that refusing RFC1918 would break the feature for a large share of the
+ * people who use it at all.
+ *
+ * Link-local and carrier-grade NAT stay refused, and they are the reason this is a widening
+ * rather than a switch to no checking: nothing is legitimately served on either, while both
+ * carry a cloud instance's metadata endpoint (169.254.169.254, and 100.100.100.200).
+ */
+const ALLOWED_IP_RANGES_INCLUDING_PRIVATE = new Set(["unicast", "loopback", "private", "uniqueLocal"]);
+
+/** How hard an address is vetted, and how long the caller is prepared to wait for it. */
+export interface SafeFetchPolicy {
+ /**
+ * Permit loopback, RFC1918 and unique-local addresses. For a destination the operator
+ * configured themselves; never for one that arrived in note content.
+ */
+ allowPrivateNetwork?: boolean;
+ /**
+ * Deadline imposed when the caller passes no signal of its own. `null` for a request that
+ * must not have one — a chat completion runs for as long as the model takes.
+ */
+ timeoutMs?: number | null;
+ /**
+ * Redirects to follow. Zero makes a redirect an error, which is what a call carrying
+ * credentials wants: the hop is re-vetted as an address, but the `Authorization` header
+ * would be re-sent to whoever the destination named, and an API key is not something to
+ * hand to a redirect target.
+ */
+ maxRedirects?: number;
+}
+
/**
* Checks whether an IP address is private/reserved using ipaddr.js.
* Returns true if the IP should be blocked.
*/
-function isBlockedIP(ip: string): boolean {
+function isBlockedIP(ip: string, allowedRanges: ReadonlySet<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());
+ return !allowedRanges.has(parsed.range());
} catch {
return true; // unparseable → treat as blocked
}
@@ -32,7 +68,8 @@ function isBlockedIP(ip: string): boolean {
* 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[]> {
+async function validateHostResolution(hostname: string, allowPrivateNetwork = false): Promise<dns.LookupAddress[]> {
+ const allowedRanges = allowPrivateNetwork ? ALLOWED_IP_RANGES_INCLUDING_PRIVATE : ALLOWED_IP_RANGES;
// `URL.hostname` hands back an IPv6 literal still wrapped in its brackets ("[::1]"), which is
// not a form either net.isIP or ipaddr.js recognises. Left as-is, such an address would be
// taken for a name and looked up as one instead of being checked as the address it is.
@@ -40,8 +77,8 @@ async function validateHostResolution(hostname: string): Promise<dns.LookupAddre
// If the hostname is already an IP literal, check it directly
if (net.isIP(host)) {
- if (isBlockedIP(host)) {
- throw new ValidationError("URLs pointing to private/internal networks are not allowed");
+ if (isBlockedIP(host, allowedRanges)) {
+ throw new ValidationError(blockedAddressMessage(allowPrivateNetwork));
}
return [{ address: host, family: net.isIP(host) as 4 | 6 }];
}
@@ -54,14 +91,25 @@ async function validateHostResolution(hostname: string): Promise<dns.LookupAddre
}
for (const addr of addresses) {
- if (isBlockedIP(addr.address)) {
- throw new ValidationError("URLs pointing to private/internal networks are not allowed");
+ if (isBlockedIP(addr.address, allowedRanges)) {
+ throw new ValidationError(blockedAddressMessage(allowPrivateNetwork));
}
}
return addresses;
}
+/**
+ * Why an address was refused, in the terms the caller's policy makes true. A caller that does
+ * permit private addresses must not be told its address was refused for being one — for those
+ * the only refusals left are the metadata ranges.
+ */
+function blockedAddressMessage(allowPrivateNetwork: boolean): string {
+ return allowPrivateNetwork
+ ? "URLs pointing to link-local or carrier-grade NAT addresses are not allowed"
+ : "URLs pointing to private/internal networks are not allowed";
+}
+
/**
* 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.
@@ -156,13 +204,18 @@ function withDispatcherCleanup(response: UndiciResponse, dispatcher: Agent): Res
/**
* Fetches a URL with SSRF protection: resolves the hostname, validates
* the resulting IP, and pins the connection to that IP to prevent DNS rebinding.
+ *
+ * The default policy is the strict one — every non-unicast range refused, five redirects
+ * followed, five seconds allowed — since the callers that named no policy are the ones fetching
+ * an address out of note content. See {@link SafeFetchPolicy} for what a caller relaxes and why.
*/
-async function safeFetch(url: string, options: RequestInit = {}): Promise<Response> {
+async function safeFetch(url: string, options: RequestInit = {}, policy: SafeFetchPolicy = {}): Promise<Response> {
+ const { allowPrivateNetwork = false, timeoutMs = FETCH_TIMEOUT_MS, maxRedirects = MAX_REDIRECTS } = policy;
let currentUrl = url;
- for (let i = 0; i <= MAX_REDIRECTS; i++) {
+ for (let i = 0; i <= maxRedirects; i++) {
const parsed = validateUrl(currentUrl);
- const validatedAddresses = await validateHostResolution(parsed.hostname);
+ const validatedAddresses = await validateHostResolution(parsed.hostname, allowPrivateNetwork);
// Use a custom dispatcher that pins DNS to the validated IPs,
// preventing a second DNS lookup from resolving to a different (private) IP.
@@ -180,12 +233,16 @@ async function safeFetch(url: string, options: RequestInit = {}): Promise<Respon
const fetchOptions = {
...options,
redirect: "manual" as const,
- signal: options.signal ?? AbortSignal.timeout(FETCH_TIMEOUT_MS),
+ signal: options.signal ?? (timeoutMs === null ? undefined : AbortSignal.timeout(timeoutMs)),
dispatcher
} as UndiciRequestInit;
const response = await undiciFetch(currentUrl, fetchOptions); // codeql[js/request-forgery]
if (response.status >= 300 && response.status < 400) {
+ if (maxRedirects === 0) {
+ void dispatcher.close();
+ throw new ValidationError(`Refusing to follow a redirect from ${currentUrl}`);
+ }
const location = response.headers.get("location");
if (!location) throw new Error("Redirect without Location header");
// Resolve relative redirects against the current URL
diff --git a/apps/standalone/src/lightweight/bridged_request_provider.ts b/apps/standalone/src/lightweight/bridged_request_provider.ts
index 167aac54c6..d3cd53b9f4 100644
--- a/apps/standalone/src/lightweight/bridged_request_provider.ts
+++ b/apps/standalone/src/lightweight/bridged_request_provider.ts
@@ -1,4 +1,4 @@
-import type { ExecOpts, FetchedResource, FetchResourceOpts, RequestProvider } from "@triliumnext/core";
+import type { ExecOpts, FetchApiOpts, FetchedResource, FetchResourceOpts, RequestProvider } from "@triliumnext/core";
import { validateFetchableUrl } from "@triliumnext/core/src/services/request.js";
/**
@@ -211,6 +211,23 @@ export default class BridgedRequestProvider implements RequestProvider {
bytes: Uint8Array.from(binary, (c) => c.charCodeAt(0))
};
}
+
+ /**
+ * Calls a configured API endpoint with the WebView's own `fetch`, deliberately going around
+ * the bridge this provider exists to offer.
+ *
+ * The bridge answers once, with the whole body in hand, and a chat completion is a stream that
+ * is read as it arrives — put through here it would surface all at once, at the end, which for
+ * the one caller of this is the difference between a chat and a long silence. Where CORS is the
+ * problem the bridge solves, that is not the problem here either: the LLM endpoints are called
+ * from browsers by design and answer accordingly.
+ *
+ * `allowPrivateNetwork` is unread for the same reason as in the sibling provider — see the note
+ * there.
+ */
+ async fetchApi(url: string, init: RequestInit, _opts: FetchApiOpts): Promise<Response> {
+ return await fetch(validateFetchableUrl(url).toString(), init);
+ }
}
/**
diff --git a/apps/standalone/src/lightweight/request_provider.ts b/apps/standalone/src/lightweight/request_provider.ts
index d392d9a7dd..df1acac0dc 100644
--- a/apps/standalone/src/lightweight/request_provider.ts
+++ b/apps/standalone/src/lightweight/request_provider.ts
@@ -1,4 +1,4 @@
-import type { ExecOpts, FetchedResource, FetchResourceOpts, RequestProvider } from "@triliumnext/core";
+import type { ExecOpts, FetchApiOpts, FetchedResource, FetchResourceOpts, RequestProvider } from "@triliumnext/core";
import { readCappedResponse, validateFetchableUrl } from "@triliumnext/core/src/services/request.js";
/**
@@ -125,6 +125,22 @@ export default class FetchRequestProvider implements RequestProvider {
clearTimeout(timeoutId);
}
}
+
+ /**
+ * Calls a configured API endpoint with the page's own `fetch`, which is as far as this runtime
+ * can go and as far as it needs to.
+ *
+ * The private-address rule the server keeps has no counterpart here, and `allowPrivateNetwork`
+ * is accordingly unread: there is no resolver to ask what a name points at, and nothing to be
+ * protected if there were. The request leaves the user's own browser, over the user's own
+ * network, to a destination that same user configured — the server's rule exists because a
+ * server's network is not the network of everyone who can reach it, which is not this.
+ *
+ * What remains is {@link validateFetchableUrl}, and the same-origin policy behind it.
+ */
+ async fetchApi(url: string, init: RequestInit, _opts: FetchApiOpts): Promise<Response> {
+ return await fetch(validateFetchableUrl(url).toString(), init);
+ }
}
/** Matches the server's own fetch timeout, a preview not being worth waiting on for longer. */
diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.ts
index a7d5b5c09e..3c8b23c5a3 100644
--- a/packages/trilium-core/src/index.ts
+++ b/packages/trilium-core/src/index.ts
@@ -138,7 +138,7 @@ export { inspectImage, type InspectedImage, UNKNOWN_FORMAT } from "./services/im
export { type CoreConfig, initConfig, getConfig } from "./services/config";
export { default as imageService } from "./services/image";
export { t } from "i18next";
-export type { RequestProvider, ExecOpts, CookieJar, FetchResourceOpts, FetchedResource } from "./services/request";
+export type { RequestProvider, ExecOpts, CookieJar, FetchApiOpts, FetchResourceOpts, FetchedResource } from "./services/request";
export type * from "./meta";
export * as routeHelpers from "./routes/helpers";
diff --git a/packages/trilium-core/src/services/llm/providers/anthropic.spec.ts b/packages/trilium-core/src/services/llm/providers/anthropic.spec.ts
index 51bddb3821..dff952a486 100644
--- a/packages/trilium-core/src/services/llm/providers/anthropic.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/anthropic.spec.ts
@@ -37,6 +37,12 @@ vi.mock("../tools/helpers.js", async (importOriginal) => {
});
import { AnthropicProvider } from "./anthropic.js";
+import { installGlobalFetchAsApiTransport } from "../../../test/request_provider.js";
+import { llmFetch } from "./fetch.js";
+
+// A provider reaches its endpoint through the request provider rather than the global `fetch`, so
+// the specs that stub that global need one installed which leads back to it.
+beforeEach(installGlobalFetchAsApiTransport);
describe("AnthropicProvider construction", () => {
beforeEach(() => {
@@ -48,7 +54,8 @@ describe("AnthropicProvider construction", () => {
expect(createAnthropicMock).toHaveBeenCalledTimes(1);
expect(createAnthropicMock).toHaveBeenCalledWith({
apiKey: "sk-ant-test",
- headers: { "anthropic-dangerous-direct-browser-access": "true" }
+ headers: { "anthropic-dangerous-direct-browser-access": "true" },
+ fetch: llmFetch
});
});
@@ -57,7 +64,8 @@ describe("AnthropicProvider construction", () => {
expect(createAnthropicMock).toHaveBeenCalledWith({
apiKey: "sk-ant-test",
headers: { "anthropic-dangerous-direct-browser-access": "true" },
- baseURL: "https://proxy.example.com/v1"
+ baseURL: "https://proxy.example.com/v1",
+ fetch: llmFetch
});
});
@@ -65,7 +73,8 @@ describe("AnthropicProvider construction", () => {
new AnthropicProvider("sk-ant-test", "");
expect(createAnthropicMock).toHaveBeenCalledWith({
apiKey: "sk-ant-test",
- headers: { "anthropic-dangerous-direct-browser-access": "true" }
+ headers: { "anthropic-dangerous-direct-browser-access": "true" },
+ fetch: llmFetch
});
});
diff --git a/packages/trilium-core/src/services/llm/providers/anthropic.ts b/packages/trilium-core/src/services/llm/providers/anthropic.ts
index 0c9df8bbcf..f57a4dab55 100644
--- a/packages/trilium-core/src/services/llm/providers/anthropic.ts
+++ b/packages/trilium-core/src/services/llm/providers/anthropic.ts
@@ -4,6 +4,7 @@ import { type ModelMessage, stepCountIs, streamText, type SystemModelMessage, ty
import type { LlmProviderConfig, ModelInfo, StreamResult } from "../types.js";
import { BaseProvider, buildModelMessage, type RemoteModel, TELEMETRY_OFF } from "./base_provider.js";
+import { llmFetch } from "./fetch.js";
const OFFICIAL_BASE_URL = "https://api.anthropic.com/v1";
@@ -43,7 +44,7 @@ export class AnthropicProvider extends BaseProvider {
if (!apiKey) {
throw new Error("API key is required for Anthropic provider");
}
- this.anthropic = createAnthropic({ apiKey, headers: BROWSER_ACCESS_HEADER, ...(baseURL && { baseURL }) });
+ this.anthropic = createAnthropic({ apiKey, headers: BROWSER_ACCESS_HEADER, ...(baseURL && { baseURL }), fetch: llmFetch });
}
protected createModel(modelId: string) {
diff --git a/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts b/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts
index 94abfc7d2d..293c391573 100644
--- a/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/base_provider.spec.ts
@@ -52,6 +52,11 @@ import {
type ProviderPrices,
type RemoteModel
} from "./base_provider.js";
+import { installGlobalFetchAsApiTransport } from "../../../test/request_provider.js";
+
+// A provider reaches its endpoint through the request provider rather than the global `fetch`, so
+// the specs that stub that global need one installed which leads back to it.
+beforeEach(installGlobalFetchAsApiTransport);
const TEST_MODELS: Parameters<typeof buildModelList>[0] = [
{ id: "cheap", name: "Cheap", pricing: { input: 1, output: 2 } },
diff --git a/packages/trilium-core/src/services/llm/providers/base_provider.ts b/packages/trilium-core/src/services/llm/providers/base_provider.ts
index ade2b2e16f..dcd6ab9e2b 100644
--- a/packages/trilium-core/src/services/llm/providers/base_provider.ts
+++ b/packages/trilium-core/src/services/llm/providers/base_provider.ts
@@ -8,6 +8,7 @@ import { type FilePart, generateText, type ImagePart, type LanguageModel, type M
import { getLog } from "../../log.js";
import { resolveAttachmentPart } from "../attachment_content.js";
+import { llmFetch } from "./fetch.js";
import { buildNoteHint } from "../note_hint.js";
import { buildSystemPrompt as composeSystemPrompt } from "../system_prompt.js";
import { allToolRegistries } from "../tools/index.js";
@@ -256,7 +257,7 @@ export abstract class BaseProvider implements LlmProvider {
* API key (or base URL) is wrong rather than a generic HTTP error.
*/
protected async fetchJson(url: string, headers: Record<string, string>): Promise<unknown> {
- const response = await fetch(url, { headers, signal: AbortSignal.timeout(MODEL_LIST_TIMEOUT_MS) });
+ const response = await llmFetch(url, { headers, signal: AbortSignal.timeout(MODEL_LIST_TIMEOUT_MS) });
if (!response.ok) {
if (response.status === 401 || response.status === 403) {
throw new Error(`Authentication failed (HTTP ${response.status}) — check the API key${this.baseURL ? " and base URL" : ""}.`);
diff --git a/packages/trilium-core/src/services/llm/providers/browser_runtime.spec.ts b/packages/trilium-core/src/services/llm/providers/browser_runtime.spec.ts
index a26cc2ced7..f8b35499a3 100644
--- a/packages/trilium-core/src/services/llm/providers/browser_runtime.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/browser_runtime.spec.ts
@@ -12,6 +12,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { streamToChunks } from "../stream.js";
import { AnthropicProvider } from "./anthropic.js";
+import { installGlobalFetchAsApiTransport } from "../../../test/request_provider.js";
+
+// A provider reaches its endpoint through the request provider rather than the global `fetch`, so
+// the specs that stub that global need one installed which leads back to it.
+beforeEach(installGlobalFetchAsApiTransport);
/** Collected while a case runs; asserted empty at the end of each. */
const leaked: unknown[] = [];
diff --git a/packages/trilium-core/src/services/llm/providers/deepseek.spec.ts b/packages/trilium-core/src/services/llm/providers/deepseek.spec.ts
index d477112415..ad97349932 100644
--- a/packages/trilium-core/src/services/llm/providers/deepseek.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/deepseek.spec.ts
@@ -22,6 +22,12 @@ vi.mock("ai", async (importOriginal) => {
});
import { DeepSeekProvider, deepSeekModelName } from "./deepseek.js";
+import { installGlobalFetchAsApiTransport } from "../../../test/request_provider.js";
+import { llmFetch } from "./fetch.js";
+
+// A provider reaches its endpoint through the request provider rather than the global `fetch`, so
+// the specs that stub that global need one installed which leads back to it.
+beforeEach(installGlobalFetchAsApiTransport);
describe("DeepSeekProvider construction", () => {
beforeEach(() => {
@@ -31,13 +37,13 @@ describe("DeepSeekProvider construction", () => {
it("points at the official endpoint unless overridden, and requires a key", () => {
new DeepSeekProvider("sk-deep");
- expect(createOpenAiMock).toHaveBeenCalledWith({ apiKey: "sk-deep", baseURL: "https://api.deepseek.com/v1" });
+ expect(createOpenAiMock).toHaveBeenCalledWith({ apiKey: "sk-deep", baseURL: "https://api.deepseek.com/v1", fetch: llmFetch });
// An override reaches a gateway in front of DeepSeek; a blank one is no override.
new DeepSeekProvider("sk-deep", "https://gateway.example/v1");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "sk-deep", baseURL: "https://gateway.example/v1" });
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "sk-deep", baseURL: "https://gateway.example/v1", fetch: llmFetch });
new DeepSeekProvider("sk-deep", "");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "sk-deep", baseURL: "https://api.deepseek.com/v1" });
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "sk-deep", baseURL: "https://api.deepseek.com/v1", fetch: llmFetch });
expect(() => new DeepSeekProvider("")).toThrow(/API key is required/);
});
diff --git a/packages/trilium-core/src/services/llm/providers/deepseek.ts b/packages/trilium-core/src/services/llm/providers/deepseek.ts
index 3ff7d80b15..c36fc0442b 100644
--- a/packages/trilium-core/src/services/llm/providers/deepseek.ts
+++ b/packages/trilium-core/src/services/llm/providers/deepseek.ts
@@ -2,6 +2,7 @@ import { createOpenAI, type OpenAIProvider as OpenAISDKProvider } from "@ai-sdk/
import type { ModelInfo } from "../types.js";
import { BaseProvider, type RemoteModel } from "./base_provider.js";
+import { llmFetch } from "./fetch.js";
/**
* DeepSeek's OpenAI-compatible endpoint. The `/v1` here is the compatibility
@@ -38,7 +39,7 @@ export class DeepSeekProvider extends BaseProvider {
if (!apiKey) {
throw new Error("API key is required for DeepSeek provider");
}
- this.openai = createOpenAI({ apiKey, baseURL: this.baseURL ?? OFFICIAL_BASE_URL });
+ this.openai = createOpenAI({ apiKey, baseURL: this.baseURL ?? OFFICIAL_BASE_URL, fetch: llmFetch });
}
/**
diff --git a/packages/trilium-core/src/services/llm/providers/fetch.spec.ts b/packages/trilium-core/src/services/llm/providers/fetch.spec.ts
new file mode 100644
index 0000000000..729817ca1b
--- /dev/null
+++ b/packages/trilium-core/src/services/llm/providers/fetch.spec.ts
@@ -0,0 +1,49 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { initRequest } from "../../request.js";
+import { fakeRequestProvider } from "../../../test/request_provider.js";
+import { llmFetch } from "./fetch.js";
+
+describe("llmFetch", () => {
+ const fetchApi = vi.fn(async () => new Response("{}"));
+
+ beforeEach(() => {
+ fetchApi.mockClear();
+ initRequest(fakeRequestProvider({ fetchApi }));
+ });
+
+ it("goes through the request provider rather than the global fetch", async () => {
+ const globalFetch = vi.fn();
+ vi.stubGlobal("fetch", globalFetch);
+
+ await llmFetch("https://api.example.com/v1/models", { headers: { Authorization: "Bearer sk-x" } });
+
+ expect(globalFetch).not.toHaveBeenCalled();
+ expect(fetchApi).toHaveBeenCalledWith(
+ "https://api.example.com/v1/models",
+ { headers: { Authorization: "Bearer sk-x" } },
+ expect.anything()
+ );
+
+ vi.unstubAllGlobals();
+ });
+
+ it("asks for private addresses to be reachable, which is what makes a local model server work", async () => {
+ // The one thing about this call that is a policy decision rather than plumbing: refusing
+ // these would leave Ollama and LM Studio — both of which default to loopback — unreachable.
+ await llmFetch("http://localhost:11434/v1/models");
+
+ expect(fetchApi).toHaveBeenCalledWith(expect.anything(), expect.anything(), { allowPrivateNetwork: true });
+ });
+
+ it("accepts a URL object, and an absent init, as the SDKs may pass either", async () => {
+ await llmFetch(new URL("https://api.example.com/v1/models"));
+
+ expect(fetchApi).toHaveBeenCalledWith("https://api.example.com/v1/models", {}, expect.anything());
+ });
+
+ it("refuses a Request, whose body it would have to consume to read", async () => {
+ await expect(llmFetch(new Request("https://api.example.com/v1/models"))).rejects.toThrow(/does not accept a Request/);
+ expect(fetchApi).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/trilium-core/src/services/llm/providers/fetch.ts b/packages/trilium-core/src/services/llm/providers/fetch.ts
new file mode 100644
index 0000000000..57595ee492
--- /dev/null
+++ b/packages/trilium-core/src/services/llm/providers/fetch.ts
@@ -0,0 +1,46 @@
+/**
+ * The transport every provider talks to its endpoint through — its model listing, and the calls
+ * the vendor SDK makes on its behalf.
+ *
+ * It exists because `baseURL` is a free-text field. A provider configuration names where the
+ * requests go, and the requests are made by the server rather than by the browser that asked for
+ * them, so a base URL is an instruction to the server to connect somewhere. Left on the global
+ * `fetch`, that is an instruction it follows anywhere at all — including to the address a cloud
+ * instance answers its own credentials on.
+ *
+ * What it is *not* is a rule that endpoints must be public. Local model servers are the reason
+ * half these providers exist: Ollama and LM Studio both default to loopback, and either may as
+ * easily be a machine on the LAN. Those addresses stay reachable. Refused are the ranges no model
+ * server is served on and only a metadata endpoint answers — see the policy in the server's
+ * `safe_fetch`, which is where the address is actually vetted.
+ */
+
+import { getRequestProvider } from "../../request.js";
+
+/**
+ * A `fetch` for a provider endpoint, in the shape the AI SDKs take as their `fetch` option.
+ *
+ * On the server this resolves the host and refuses the metadata ranges; in the browser builds it
+ * is the page's own `fetch`, which is all that runtime has and all it needs. Each implementation
+ * says why on itself.
+ */
+export const llmFetch: typeof globalThis.fetch = async (input, init) =>
+ await getRequestProvider().fetchApi(urlOf(input), init ?? {}, { allowPrivateNetwork: true });
+
+/**
+ * The address out of whatever `fetch` was handed.
+ *
+ * A `Request` is refused rather than unpacked: its body is a stream that reading here would
+ * consume, so honouring one means rebuilding the whole request rather than reading a field off it.
+ * Nothing calls it that way — the SDKs pass a URL and an init, and so do we — and a silent
+ * half-translation would be worse than the throw if anything ever did.
+ */
+function urlOf(input: RequestInfo | URL): string {
+ if (typeof input === "string") {
+ return input;
+ }
+ if (input instanceof URL) {
+ return input.toString();
+ }
+ throw new Error("llmFetch does not accept a Request; pass a URL and an init instead.");
+}
diff --git a/packages/trilium-core/src/services/llm/providers/google.spec.ts b/packages/trilium-core/src/services/llm/providers/google.spec.ts
index 6e4041633c..a2d4e4bb8f 100644
--- a/packages/trilium-core/src/services/llm/providers/google.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/google.spec.ts
@@ -23,6 +23,12 @@ vi.mock("ai", async (importOriginal) => {
});
import { GoogleProvider, isGoogleChatModel } from "./google.js";
+import { installGlobalFetchAsApiTransport } from "../../../test/request_provider.js";
+import { llmFetch } from "./fetch.js";
+
+// A provider reaches its endpoint through the request provider rather than the global `fetch`, so
+// the specs that stub that global need one installed which leads back to it.
+beforeEach(installGlobalFetchAsApiTransport);
describe("GoogleProvider construction", () => {
beforeEach(() => {
@@ -32,20 +38,21 @@ describe("GoogleProvider construction", () => {
it("forwards apiKey only when no baseURL provided", () => {
new GoogleProvider("test-key");
expect(createGoogleMock).toHaveBeenCalledTimes(1);
- expect(createGoogleMock).toHaveBeenCalledWith({ apiKey: "test-key" });
+ expect(createGoogleMock).toHaveBeenCalledWith({ apiKey: "test-key", fetch: llmFetch });
});
it("forwards apiKey and baseURL when both provided", () => {
new GoogleProvider("test-key", "https://proxy.example.com/v1beta");
expect(createGoogleMock).toHaveBeenCalledWith({
apiKey: "test-key",
- baseURL: "https://proxy.example.com/v1beta"
+ baseURL: "https://proxy.example.com/v1beta",
+ fetch: llmFetch
});
});
it("omits baseURL when empty string is provided", () => {
new GoogleProvider("test-key", "");
- expect(createGoogleMock).toHaveBeenCalledWith({ apiKey: "test-key" });
+ expect(createGoogleMock).toHaveBeenCalledWith({ apiKey: "test-key", fetch: llmFetch });
});
it("throws when apiKey is missing", () => {
diff --git a/packages/trilium-core/src/services/llm/providers/google.ts b/packages/trilium-core/src/services/llm/providers/google.ts
index b8ec6c4d20..d3dbde16a5 100644
--- a/packages/trilium-core/src/services/llm/providers/google.ts
+++ b/packages/trilium-core/src/services/llm/providers/google.ts
@@ -5,6 +5,7 @@ import { stepCountIs, streamText, type ToolSet } from "ai";
import type { LlmProviderConfig, StreamResult } from "../types.js";
import { BaseProvider, type RemoteModel, TELEMETRY_OFF } from "./base_provider.js";
+import { llmFetch } from "./fetch.js";
const OFFICIAL_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
@@ -32,7 +33,7 @@ export class GoogleProvider extends BaseProvider {
if (!apiKey) {
throw new Error("API key is required for Google provider");
}
- this.google = createGoogleGenerativeAI({ apiKey, ...(baseURL && { baseURL }) });
+ this.google = createGoogleGenerativeAI({ apiKey, ...(baseURL && { baseURL }), fetch: llmFetch });
}
protected createModel(modelId: string) {
diff --git a/packages/trilium-core/src/services/llm/providers/local.spec.ts b/packages/trilium-core/src/services/llm/providers/local.spec.ts
index 96ed95d0da..1167ab0e19 100644
--- a/packages/trilium-core/src/services/llm/providers/local.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/local.spec.ts
@@ -17,6 +17,12 @@ vi.mock("@ai-sdk/openai", () => ({
}));
import { LocalProvider } from "./local.js";
+import { installGlobalFetchAsApiTransport } from "../../../test/request_provider.js";
+import { llmFetch } from "./fetch.js";
+
+// A provider reaches its endpoint through the request provider rather than the global `fetch`, so
+// the specs that stub that global need one installed which leads back to it.
+beforeEach(installGlobalFetchAsApiTransport);
/** Minimal /api/tags payload with the fields the provider reads. */
function ollamaTags(models: Array<{ name: string; parameter_size?: string; quantization_level?: string }>) {
@@ -83,36 +89,36 @@ describe("LocalProvider", () => {
describe("endpoint resolution", () => {
it("prefills each card's default endpoint", () => {
new LocalProvider("ollama");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:11434/v1" });
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:11434/v1", fetch: llmFetch });
new LocalProvider("lmstudio");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:1234/v1" });
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:1234/v1", fetch: llmFetch });
});
it("accepts a URL written with or without the /v1 suffix", () => {
new LocalProvider("openai-compatible", "", "http://box:8080");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://box:8080/v1" });
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://box:8080/v1", fetch: llmFetch });
new LocalProvider("openai-compatible", "", "http://box:8080/v1");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://box:8080/v1" });
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://box:8080/v1", fetch: llmFetch });
});
it("keeps a path prefix intact (proxied endpoints)", () => {
new LocalProvider("openai-compatible", "", "https://proxy.example.com/llm/v1");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "https://proxy.example.com/llm/v1" });
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "https://proxy.example.com/llm/v1", fetch: llmFetch });
});
it("forwards a supplied API key to the SDK", () => {
new LocalProvider("openai-compatible", "sk-proxy", "http://box:8080/v1");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "sk-proxy", baseURL: "http://box:8080/v1" });
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "sk-proxy", baseURL: "http://box:8080/v1", fetch: llmFetch });
});
it("falls back to the card's default for an invalid URL, but rejects one it cannot replace", () => {
new LocalProvider("ollama", "", "not a url");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:11434/v1" });
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:11434/v1", fetch: llmFetch });
new LocalProvider("ollama", "", "ftp://example.com");
- expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:11434/v1" });
+ expect(createOpenAiMock).toHaveBeenLastCalledWith({ apiKey: "local", baseURL: "http://localhost:11434/v1", fetch: llmFetch });
// The generic card has no default to fall back to.
expect(() => new LocalProvider("openai-compatible", "", "not a url")).toThrow(/Invalid base URL/);
diff --git a/packages/trilium-core/src/services/llm/providers/local.ts b/packages/trilium-core/src/services/llm/providers/local.ts
index 4cf1485f4f..b17f756938 100644
--- a/packages/trilium-core/src/services/llm/providers/local.ts
+++ b/packages/trilium-core/src/services/llm/providers/local.ts
@@ -19,6 +19,7 @@ import { getLog } from "../../../services/log.js";
import type { ModelInfo, ModelPricing } from "../types.js";
import { BaseProvider, type RemoteModel } from "./base_provider.js";
+import { llmFetch } from "./fetch.js";
/** Provider card ids that map to this implementation. */
export type LocalProviderKind = "ollama" | "lmstudio" | "openai-compatible";
@@ -82,7 +83,8 @@ export class LocalProvider extends BaseProvider {
this.openai = createOpenAI({
apiKey: apiKey || PLACEHOLDER_API_KEY,
- baseURL: `${this.root}/v1`
+ baseURL: `${this.root}/v1`,
+ fetch: llmFetch
});
}
@@ -194,7 +196,7 @@ export class LocalProvider extends BaseProvider {
private async probeJson(url: string): Promise<unknown | undefined> {
let response: Response;
try {
- response = await fetch(url, {
+ response = await llmFetch(url, {
headers: this.apiKey ? { Authorization: `Bearer ${this.apiKey}` } : {},
signal: AbortSignal.timeout(MODEL_LIST_TIMEOUT_MS)
});
diff --git a/packages/trilium-core/src/services/llm/providers/openai.spec.ts b/packages/trilium-core/src/services/llm/providers/openai.spec.ts
index 4cc1de6f1f..4620ffc6bc 100644
--- a/packages/trilium-core/src/services/llm/providers/openai.spec.ts
+++ b/packages/trilium-core/src/services/llm/providers/openai.spec.ts
@@ -23,6 +23,12 @@ vi.mock("ai", async (importOriginal) => {
});
import { isOpenAiChatModel, openAiModelName, OpenAiProvider } from "./openai.js";
+import { installGlobalFetchAsApiTransport } from "../../../test/request_provider.js";
+import { llmFetch } from "./fetch.js";
+
+// A provider reaches its endpoint through the request provider rather than the global `fetch`, so
+// the specs that stub that global need one installed which leads back to it.
+beforeEach(installGlobalFetchAsApiTransport);
describe("OpenAiProvider construction", () => {
beforeEach(() => {
@@ -32,20 +38,21 @@ describe("OpenAiProvider construction", () => {
it("forwards apiKey only when no baseURL provided", () => {
new OpenAiProvider("sk-test");
expect(createOpenAIMock).toHaveBeenCalledTimes(1);
- expect(createOpenAIMock).toHaveBeenCalledWith({ apiKey: "sk-test" });
+ expect(createOpenAIMock).toHaveBeenCalledWith({ apiKey: "sk-test", fetch: llmFetch });
});
it("forwards apiKey and baseURL when both provided", () => {
new OpenAiProvider("sk-test", "http://localhost:11434/v1");
expect(createOpenAIMock).toHaveBeenCalledWith({
apiKey: "sk-test",
- baseURL: "http://localhost:11434/v1"
+ baseURL: "http://localhost:11434/v1",
+ fetch: llmFetch
});
});
it("omits baseURL when empty string is provided", () => {
new OpenAiProvider("sk-test", "");
- expect(createOpenAIMock).toHaveBeenCalledWith({ apiKey: "sk-test" });
+ expect(createOpenAIMock).toHaveBeenCalledWith({ apiKey: "sk-test", fetch: llmFetch });
});
it("throws when apiKey is missing", () => {
diff --git a/packages/trilium-core/src/services/llm/providers/openai.ts b/packages/trilium-core/src/services/llm/providers/openai.ts
index e22b41af9b..ef1b5a43ad 100644
--- a/packages/trilium-core/src/services/llm/providers/openai.ts
+++ b/packages/trilium-core/src/services/llm/providers/openai.ts
@@ -3,6 +3,7 @@ import type { ToolSet } from "ai";
import type { ModelInfo } from "../types.js";
import { BaseProvider, type RemoteModel } from "./base_provider.js";
+import { llmFetch } from "./fetch.js";
const OFFICIAL_BASE_URL = "https://api.openai.com/v1";
@@ -23,7 +24,7 @@ export class OpenAiProvider extends BaseProvider {
if (!apiKey) {
throw new Error("API key is required for OpenAI provider");
}
- this.openai = createOpenAI({ apiKey, ...(baseURL && { baseURL }) });
+ this.openai = createOpenAI({ apiKey, ...(baseURL && { baseURL }), fetch: llmFetch });
}
protected createModel(modelId: string) {
diff --git a/packages/trilium-core/src/services/request.ts b/packages/trilium-core/src/services/request.ts
index b801becbf7..1c3a82728d 100644
--- a/packages/trilium-core/src/services/request.ts
+++ b/packages/trilium-core/src/services/request.ts
@@ -64,6 +64,31 @@ export interface RequestProvider {
* necessity — see the note on each.
*/
fetchResource(url: string, opts: FetchResourceOpts): Promise<FetchedResource>;
+ /**
+ * Calls an API endpoint whose address came from configuration — the LLM providers' base URL
+ * being the one that exists today — and hands back the response still open.
+ *
+ * Distinct from {@link fetchResource} in the two things calling an API needs and reading a page
+ * never did: a request of one's own, with a method and headers and a body, and an answer nobody
+ * buffers. A completion streams for as long as the model takes, so there is no ceiling to put on
+ * it and nothing here may hold it whole.
+ *
+ * The address still has to be vetted — a base URL is a free-text field, and a server that
+ * fetches whatever it is pointed at is a server that will fetch a cloud metadata endpoint. How
+ * hard, and against which ranges, is the implementation's to decide; see the note on each.
+ */
+ fetchApi(url: string, init: RequestInit, opts: FetchApiOpts): Promise<Response>;
+}
+
+/** What an API call needs vetting for, beyond the address itself. */
+export interface FetchApiOpts {
+ /**
+ * Whether the destination may sit on a private network. True for an endpoint the operator
+ * configured — a model server on this machine or this LAN is the ordinary case, and refusing
+ * it would leave the local providers with nothing to talk to. Never true for an address that
+ * arrived in note content.
+ */
+ allowPrivateNetwork: boolean;
}
let requestProvider: RequestProvider | null = null;
@@ -92,6 +117,9 @@ export default {
},
fetchResource(url: string, opts: FetchResourceOpts): Promise<FetchedResource> {
return getRequestProvider().fetchResource(url, opts);
+ },
+ fetchApi(url: string, init: RequestInit, opts: FetchApiOpts): Promise<Response> {
+ return getRequestProvider().fetchApi(url, init, opts);
}
};
diff --git a/packages/trilium-core/src/test/request_provider.ts b/packages/trilium-core/src/test/request_provider.ts
index 9b9d2813b7..009d35e7f3 100644
--- a/packages/trilium-core/src/test/request_provider.ts
+++ b/packages/trilium-core/src/test/request_provider.ts
@@ -7,17 +7,29 @@
* 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";
+import { type FetchApiOpts, type FetchedResource, type FetchResourceOpts, type ExecOpts, initRequest, type 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"),
+ fetchApi: (_url: string, _init: RequestInit, _opts: FetchApiOpts): Promise<Response> => unstubbed("fetchApi"),
...overrides
};
}
+/**
+ * Installs a provider whose {@link RequestProvider.fetchApi} is whatever `fetch` is global at the
+ * moment it is called — for the specs that stub that global and assert against the stub.
+ *
+ * Read late, on purpose: `vi.stubGlobal("fetch", …)` in a `beforeEach` replaces the global after
+ * this has run, and a provider that captured it at install time would go on calling the real one.
+ */
+export function installGlobalFetchAsApiTransport(): void {
+ initRequest(fakeRequestProvider({ fetchApi: (url, init) => fetch(url, init) }));
+}
+
function unstubbed(method: string): never {
throw new Error(`This test installed a request provider without ${method}(), and something called it.`);
}