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(search): drop the path-parameter search routes
Elian Doranc3c62108c06a
diff --git a/apps/client/src/services/server.spec.ts b/apps/client/src/services/server.spec.tsindex 07ab83f053..1cd3c068c2 100644--- a/apps/client/src/services/server.spec.ts+++ b/apps/client/src/services/server.spec.ts@@ -235,28 +235,16 @@ describe("ajax error handling", () => {expect(toastMock.showError).toHaveBeenCalledWith("Bad input");});- it("shows a reverse-proxy-blocked toast for encoded-character 400s", async () => {+ it("reports a plain 400 on a URL with encoded characters as an unknown error", async () => {(window as any).$.ajax = (opts: AjaxOptions) => {- // string response (not an object) -> falls through to the else branchopts.error({ status: 400, responseText: "plain error" });};- await expect(server.get("notes/foo%23bar")).rejects.toBeDefined();- expect(toastMock.showPersistent).toHaveBeenCalledWith(- expect.objectContaining({ id: "reverse-proxy-blocked" })- );+ await expect(server.get("quick-search?searchString=%23book%2Fa")).rejects.toBeDefined();+ expect(toastMock.showPersistent).not.toHaveBeenCalled();+ expect(toastMock.showErrorTitleAndMessage).toHaveBeenCalled();expect((window as any).logError).toHaveBeenCalled();});- it("shows a reverse-proxy-blocked toast for %2F-encoded 400s", async () => {- (window as any).$.ajax = (opts: AjaxOptions) => {- opts.error({ status: 400, responseText: "plain error" });- };- await expect(server.get("notes/foo%2Fbar")).rejects.toBeDefined();- expect(toastMock.showPersistent).toHaveBeenCalledWith(- expect.objectContaining({ id: "reverse-proxy-blocked" })- );- });-it("falls back to the '-' placeholder when the message is an empty string", async () => {(window as any).$.ajax = (opts: AjaxOptions) => {// valid JSON object with an empty message -> messageStr resolves to "-"diff --git a/apps/client/src/services/server.ts b/apps/client/src/services/server.tsindex 619109b6e8..efc6a31995 100644--- a/apps/client/src/services/server.ts+++ b/apps/client/src/services/server.ts@@ -1,6 +1,6 @@import { t } from "./i18n.js";import { getSetupAuthToken } from "./setup_auth.js";-import utils, { isShare, openInAppHelpFromUrl } from "./utils.js";+import utils, { isShare } from "./utils.js";import ValidationError from "./validation_error.js";type Headers = Record<string, string | null | undefined>;@@ -436,24 +436,10 @@ async function reportError(method: string, url: string, statusCode: number, resp...response});} else {- if (statusCode === 400 && (url.includes("%23") || url.includes("%2F"))) {- toastService.showPersistent({- id: "reverse-proxy-blocked",- icon: "bx bx-unlink",- title: t("server.reverse_proxy_blocked_title"),- message: t("server.reverse_proxy_blocked_message"),- buttons: [ {- text: t("active_content_badges.menu_docs"),- // The Traefik page of the User Guide, which documents the fix.- onClick: () => openInAppHelpFromUrl("5ERVJb9s4FRD")- } ]- });- } else {- toastService.showErrorTitleAndMessage(- t("server.unknown_http_error_title"),- t("server.unknown_http_error_content", { statusCode, method, url, message: messageStr }),- 15_000);- }+ toastService.showErrorTitleAndMessage(+ t("server.unknown_http_error_title"),+ t("server.unknown_http_error_content", { statusCode, method, url, message: messageStr }),+ 15_000);window.logError(`${statusCode} ${method} ${url} - ${message}`);}}diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex b519c05972..b3c8daa86b 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3859,9 +3859,7 @@},"server": {"unknown_http_error_title": "Communication error with the server",- "unknown_http_error_content": "Status code: {{statusCode}}\nURL: {{method}} {{url}}\nMessage: {{message}}",- "reverse_proxy_blocked_title": "Requests blocked by a reverse proxy",- "reverse_proxy_blocked_message": "Some requests were rejected (HTTP 400) before reaching Trilium, most likely by a reverse proxy that blocks percent-encoded characters in URLs.\n\nTraefik versions 3.6.4 to 3.6.6 do this by default: upgrade to Traefik 3.6.7 or newer, or allow encoded characters in its configuration."+ "unknown_http_error_content": "Status code: {{statusCode}}\nURL: {{method}} {{url}}\nMessage: {{message}}"},"tab_history_navigation_buttons": {"go-back": "Go back to previous note",diff --git a/apps/server/internal.openapi.yaml b/apps/server/internal.openapi.yamlindex 275cd2cff5..e2b94863fa 100644--- a/apps/server/internal.openapi.yaml+++ b/apps/server/internal.openapi.yaml@@ -1942,23 +1942,6 @@ paths:'400':description: Missing or empty search string- /api/search/{searchString}:- get:- tags: [Search]- summary: Full text search with a path parameter- description: Deprecated. Use `/api/search` with the `searchString` query parameter.- operationId: searchLegacy- deprecated: true- parameters:- - name: searchString- in: path- required: true- schema:- type: string- responses:- '200':- description: Search results-/api/quick-search:get:tags: [Search]@@ -1983,23 +1966,6 @@ paths:'400':description: Missing or empty search string- /api/quick-search/{searchString}:- get:- tags: [Search]- summary: Quick search with a path parameter- description: Deprecated. Use `/api/quick-search` with the `searchString` query parameter.- operationId: quickSearchLegacy- deprecated: true- parameters:- - name: searchString- in: path- required: true- schema:- type: string- responses:- '200':- description: Quick search results-/api/search-note/{noteId}:get:tags: [Search]diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Server Installation/2. Reverse proxy/Traefik.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Server Installation/2. Reverse proxy/Traefik.htmlindex b4702abe78..249d6ae095 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Server Installation/2. Reverse proxy/Traefik.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Installation & Setup/Server Installation/2. Reverse proxy/Traefik.html@@ -3,11 +3,11 @@reference.</p><h2>Breaking change in Traefik 3.6.4</h2><p>Traefik 3.6.4 introduced a <a href="https://doc.traefik.io/traefik/migrate/v3/#encoded-characters-in-request-path">breaking change</a> regarding- how percent-encoded characters are handled in URLs. Earlier Trilium clients- sent search text in paths such as <code>/api/search/%23workspace%20%23!template</code>.- Traefik automatically rejects these paths and returns HTTP 400. Updated- clients send search text in a query parameter, but a cached older client- can still use the old path.</p>+ how percent-encoded characters are handled in URLs. Trilium puts the title+ of an image or attachment in its URL path, so one whose title contains <code>#</code> or <code>/</code> is+ requested at a path such as <code>/api/images/…/diagram%231.png</code>.+ Traefik rejects these paths with HTTP 400, and the image does not load.+ Search is not affected, because it sends its text in a query parameter.</p><p>The easiest solution is to update to Traefik 3.6.7 or later which revertsthis configuration change. Alternatively, the configuration can be changedaccording to the section below.</p>@@ -21,8 +21,8 @@allowEncodedSlash: trueallowEncodedHash: true</code></pre><aside class="admonition tip">- <p>If issues continue with an older client, you might need to enable more- encoded character groups. For more information, see <a href="https://github.com/TriliumNext/Trilium/issues/7968">the relevant GitHub issue</a>;+ <p>If images still fail to load, you might need to enable more encoded character+ groups. For more information, see <a href="https://github.com/TriliumNext/Trilium/issues/7968">the relevant GitHub issue</a>;feel free to report your findings.</p></aside></details>diff --git a/docs/User Guide/User Guide/Installation & Setup/Server Installation/2. Reverse proxy/Traefik.md b/docs/User Guide/User Guide/Installation & Setup/Server Installation/2. Reverse proxy/Traefik.mdindex 8728f65cf2..47aa0ff346 100644--- a/docs/User Guide/User Guide/Installation & Setup/Server Installation/2. Reverse proxy/Traefik.md+++ b/docs/User Guide/User Guide/Installation & Setup/Server Installation/2. Reverse proxy/Traefik.md@@ -3,7 +3,7 @@ The goal of this article is to configure Traefik proxy and HTTPS. See [#7768](ht## Breaking change in Traefik 3.6.4-Traefik 3.6.4 introduced a [breaking change](https://doc.traefik.io/traefik/migrate/v3/#encoded-characters-in-request-path) regarding how percent-encoded characters are handled in URLs. Earlier Trilium clients sent search text in paths such as `/api/search/%23workspace%20%23!template`. Traefik automatically rejects these paths and returns HTTP 400. Updated clients send search text in a query parameter, but a cached older client can still use the old path.+Traefik 3.6.4 introduced a [breaking change](https://doc.traefik.io/traefik/migrate/v3/#encoded-characters-in-request-path) regarding how percent-encoded characters are handled in URLs. Trilium puts the title of an image or attachment in its URL path, so one whose title contains `#` or `/` is requested at a path such as `/api/images/…/diagram%231.png`. Traefik rejects these paths with HTTP 400, and the image does not load. Search is not affected, because it sends its text in a query parameter.The easiest solution is to update to Traefik 3.6.7 or later which reverts this configuration change. Alternatively, the configuration can be changed according to the section below.@@ -16,7 +16,7 @@ The easiest solution is to update to Traefik 3.6.7 or later which reverts this cencodedCharacters:allowEncodedSlash: trueallowEncodedHash: true</code></pre>- <aside class="admonition tip"><p>If issues continue with an older client, you might need to enable more encoded character groups. For more information, see <a href="https://github.com/TriliumNext/Trilium/issues/7968">the relevant GitHub issue</a>; feel free to report your findings.</p></aside>+ <aside class="admonition tip"><p>If images still fail to load, you might need to enable more encoded character groups. For more information, see <a href="https://github.com/TriliumNext/Trilium/issues/7968">the relevant GitHub issue</a>; feel free to report your findings.</p></aside></details>### Build the docker-compose filediff --git a/packages/trilium-core/src/routes/api/search.spec.ts b/packages/trilium-core/src/routes/api/search.spec.tsindex 7640020778..73d228e6a9 100644--- a/packages/trilium-core/src/routes/api/search.spec.ts+++ b/packages/trilium-core/src/routes/api/search.spec.ts@@ -18,7 +18,8 @@ async function createSearchNote(searchString: string): Promise<string> {/** Runs a quick search as a client hoisted into `hoistedNoteId`, or unhoisted when it is omitted. */function quickSearch(searchString: string, hoistedNoteId?: string) {- return api.get<{ searchResultNoteIds: string[] }>(`/api/quick-search/${searchString}`, {+ return api.get<{ searchResultNoteIds: string[] }>("/api/quick-search", {+ query: { searchString },headers: hoistedNoteId ? { "trilium-hoisted-note-id": hoistedNoteId } : undefined});}@@ -48,21 +49,21 @@ describe("Search API (core)", () => {const inside = await createTextNote(api, { parentNoteId: board.noteId, title: `${token} inside` });const outside = await createTextNote(api, { title: `${token} outside` });- const scoped = await api.get<string[]>(`/api/search/${token}`, {- query: { ancestorNoteId: board.noteId }+ const scoped = await api.get<string[]>("/api/search", {+ query: { searchString: token, ancestorNoteId: board.noteId }});expect(scoped.status).toBe(200);expect(scoped.body).toContain(inside.noteId);expect(scoped.body).not.toContain(outside.noteId);- const unscoped = await api.get<string[]>(`/api/search/${token}`);+ const unscoped = await api.get<string[]>("/api/search", { query: { searchString: token } });expect(unscoped.body).toContain(inside.noteId);expect(unscoped.body).toContain(outside.noteId);});it("returns note ids with token infos and the error when includeTokens is set", async () => {- const withTokens = await api.get<SearchWithTokensResponse>(`/api/search/${UNIQUE_TOKEN}`, {- query: { includeTokens: "true" }+ const withTokens = await api.get<SearchWithTokensResponse>("/api/search", {+ query: { searchString: UNIQUE_TOKEN, includeTokens: "true" }});expect(withTokens.status).toBe(200);expect(withTokens.body.searchResultNoteIds).toContain(createdNoteId);@@ -75,8 +76,8 @@ describe("Search API (core)", () => {// A query the parser rejects still answers 200, with the parse error in the body for the// client to show inline.const broken = await api.get<SearchWithTokensResponse>(- `/api/search/${encodeURIComponent("#label = ")}`,- { query: { includeTokens: "true" } }+ "/api/search",+ { query: { searchString: "#label = ", includeTokens: "true" } });expect(broken.status).toBe(200);expect(broken.body.error).toBeTruthy();@@ -108,7 +109,8 @@ describe("Search API (core)", () => {// pattern would match nothing there (silent no-op), so the server must drop regex tokens.const pattern = "ZzRegexQwerty";const res = await api.get<{ highlightedTokens: string[]; error: string | null }>(- `/api/quick-search/${encodeURIComponent(`note.content %= '${pattern}'`)}`+ "/api/quick-search",+ { query: { searchString: `note.content %= '${pattern}'` } });expect(res.status).toBe(200);@@ -162,29 +164,9 @@ describe("Search API (core)", () => {}});- it("keeps path parameters compatible with existing clients", async () => {- const legacyFull = await api.get<string[]>(`/api/search/${UNIQUE_TOKEN}`);- expect(legacyFull.status).toBe(200);- expect(legacyFull.body).toContain(createdNoteId);-- const legacyQuick = await api.get<{ searchResultNoteIds: string[] }>(- `/api/quick-search/${UNIQUE_TOKEN}`- );- expect(legacyQuick.status).toBe(200);- expect(legacyQuick.body.searchResultNoteIds).toContain(createdNoteId);-- const full = await api.get<string[]>(`/api/search/${UNIQUE_TOKEN}`, {- query: { searchString: "" }- });- expect(full.status).toBe(200);- expect(full.body).toContain(createdNoteId);-- const quick = await api.get<{ searchResultNoteIds: string[] }>(- `/api/quick-search/${UNIQUE_TOKEN}`,- { query: { searchString: "" } }- );- expect(quick.status).toBe(200);- expect(quick.body.searchResultNoteIds).toContain(createdNoteId);+ it("takes the search string only from the query", async () => {+ expect((await api.get(`/api/search/${UNIQUE_TOKEN}`)).status).toBe(404);+ expect((await api.get(`/api/quick-search/${UNIQUE_TOKEN}`)).status).toBe(404);});it("lists template note ids including a freshly-labelled template", async () => {diff --git a/packages/trilium-core/src/routes/api/search.ts b/packages/trilium-core/src/routes/api/search.tsindex 6200430ae5..161081180c 100644--- a/packages/trilium-core/src/routes/api/search.ts+++ b/packages/trilium-core/src/routes/api/search.ts@@ -126,7 +126,7 @@ function lintSearchString(req: Request): SearchLintResponse {return { error: searchService.validateSearchQuery(searchString) };}-function quickSearch(req: Request<{ searchString?: string }, { searchString?: string }>): QuickSearchResponse {+function quickSearch(req: Request<{}, { searchString?: string }>): QuickSearchResponse {const searchString = getSearchString(req);const searchContext = new SearchContext({@@ -155,7 +155,7 @@ function quickSearch(req: Request<{ searchString?: string }, { searchString?: st}function search(- req: Request<{ searchString?: string }, { searchString?: string, ancestorNoteId?: string, includeTokens?: string }>+ req: Request<{}, { searchString?: string, ancestorNoteId?: string, includeTokens?: string }>): string[] | SearchWithTokensResponse {const searchString = getSearchString(req);const { ancestorNoteId, includeTokens } = req.query;@@ -184,8 +184,8 @@ function search(};}-function getSearchString(req: Request<{ searchString?: string }, { searchString?: string, ancestorNoteId?: string, includeTokens?: string }>): string {- const searchString = req.params.searchString ?? req.query.searchString;+function getSearchString(req: Request<{}, { searchString?: string }>): string {+ const { searchString } = req.query;if (typeof searchString !== "string" || searchString.length === 0) {throw new ValidationError("Search string must be a non-empty string.");diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 74075f43b3..375be28344 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -239,16 +239,12 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTrans//#endregionapiRoute(GET, "/api/quick-search", searchRoute.quickSearch);- apiRoute(GET, "/api/quick-search/:searchString", searchRoute.quickSearch);apiRoute(GET, "/api/search-note/:noteId", searchRoute.searchFromNote);apiRoute(PST, "/api/search-note/:noteId/result-details", searchRoute.getSearchResultDetails);apiRoute(PST, "/api/search-and-execute-note/:noteId", searchRoute.searchAndExecute);apiRoute(PST, "/api/search-related", searchRoute.getRelatedNotes);- // Ahead of the `:searchString` catch-all below, which would otherwise claim the literal path- // were it ever given a POST handler too.apiRoute(PST, "/api/search/lint", searchRoute.lintSearchString);apiRoute(GET, "/api/search", searchRoute.search);- apiRoute(GET, "/api/search/:searchString", searchRoute.search);apiRoute(GET, "/api/search-templates", searchRoute.searchTemplates);// Streaming a chat is not here — it has no single form every runtime can serve.