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
chore(server): clean up agent connection
Elian Doran579b4e9caae9
diff --git a/apps/server/src/routes/api/link_embed.ts b/apps/server/src/routes/api/link_embed.tsindex 61dccedd2f..d34f477730 100644--- a/apps/server/src/routes/api/link_embed.ts+++ b/apps/server/src/routes/api/link_embed.ts@@ -137,6 +137,49 @@ 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.@@ -171,10 +214,11 @@ async function safeFetch(url: string, options: RequestInit = {}): Promise<Responif (!location) throw new Error("Redirect without Location header");// Resolve relative redirects against the current URLcurrentUrl = new URL(location, currentUrl).toString();+ dispatcher.close();continue;}- return response;+ return withDispatcherCleanup(response, dispatcher);}throw new Error("Too many redirects");