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(core): move the custom-request dispatch out of the server route
Elian Doran29001683840e
diff --git a/apps/server/src/routes/custom.ts b/apps/server/src/routes/custom.tsindex 341c348efa..d1e9b8900e 100644--- a/apps/server/src/routes/custom.ts+++ b/apps/server/src/routes/custom.ts@@ -1,105 +1,8 @@-import type { ScriptRequest } from "@triliumnext/commons/src/lib/script_api.js";-import { becca, cls, getLog, routeHelpers, scriptService, utils } from "@triliumnext/core";+import { cls, type Request as CoreRequest, routes } from "@triliumnext/core";import type { Request, Response, Router } from "express";import { bindEmitter } from "../cls_provider.js";import { isScriptingEnabled } from "../services/scripting_guard.js";-import sql from "../services/sql.js";--function handleRequest(req: Request, res: Response) {-- // handle path from "*path" route wildcard- // in express v4, you could just add- // req.params.path + req.params[0], but with v5- // we get a split array that we have to join ourselves again-- // @TriliumNextTODO: remove typecasting once express types are fixed- // they currently only treat req.params as string, while in reality- // it can also be a string[], when using wildcards- const splitPath = req.params.path as unknown as string[];-- //const path = splitPath.map(segment => encodeURIComponent(segment)).join("/")- // naively join the "decoded" paths using a slash- // this is to mimick handleRequest behaviour- // as with the previous express v4.- // @TriliumNextTODO: using something like =>- // splitPath.map(segment => encodeURIComponent(segment)).join("/")- // might be safer-- const path = splitPath.join("/");-- const attributeIds = sql.getColumn<string>("SELECT attributeId FROM attributes WHERE isDeleted = 0 AND type = 'label' AND name IN ('customRequestHandler', 'customResourceProvider')");-- const attrs = attributeIds.map((attrId) => becca.getAttribute(attrId));-- for (const attr of attrs) {- if (!attr?.value.trim()) {- continue;- }-- // Get normalized patterns to handle both trailing slash cases- const patterns = utils.normalizeCustomHandlerPattern(attr.value);- let match: RegExpMatchArray | null = null;-- try {- // Try each pattern until we find a match- for (const pattern of patterns) {- const regex = new RegExp(`^${pattern}$`);- match = path.match(regex);- if (match) {- break; // Found a match, exit pattern loop- }- }- } catch (e: unknown) {- const [errMessage, errStack] = utils.safeExtractMessageAndStackFromError(e);- getLog().error(`Testing path for label '${attr.attributeId}', regex '${attr.value}' failed with error: ${errMessage}, stack: ${errStack}`);- continue;- }-- if (!match) {- continue;- }-- if (attr.name === "customRequestHandler") {- // Custom request handlers execute backend scripts, so they remain gated behind the- // scripting toggle. Resource providers only serve static note content and are not.- if (!isScriptingEnabled()) {- res.status(403).send("Backend script execution is disabled on this server.");- return;- }-- const note = attr.getNote();-- getLog().info(`Handling custom request '${path}' with note '${note.noteId}'`);-- try {- scriptService.executeNote(note, {- pathParams: match.slice(1),- // `ScriptRequest` declares `params` flat, while Express 5 types a wildcard as- // `string | string[]` — the same widening `splitPath` above works around. A- // handler reads its path through `pathParams` rather than through `params`.- req: req as unknown as ScriptRequest,- res- });- } catch (e: unknown) {- const [errMessage, errStack] = utils.safeExtractMessageAndStackFromError(e);- getLog().error(`Custom handler '${note.noteId}' failed with: ${errMessage}, ${errStack}`);- res.setHeader("Content-Type", "text/plain").status(500).send(errMessage);- }- } else if (attr.name === "customResourceProvider") {- routeHelpers.downloadNoteInt(attr.noteId, res);- } else {- throw new Error(`Unrecognized attribute name '${attr.name}'`);- }-- return; // only the first handler is executed- }-- const message = `No handler matched for custom '${path}' request.`;-- getLog().info(message);- res.setHeader("Content-Type", "text/plain").status(404).send(message);-}function register(router: Router) {// explicitly no CSRF middleware since it's meant to allow integration from external services@@ -108,10 +11,29 @@ function register(router: Router) {bindEmitter(req);bindEmitter(res);- cls.init(() => handleRequest(req, res));+ cls.init(() => routes.handleCustomRequest(+ joinWildcardPath(req), req as unknown as CoreRequest, res, isScriptingEnabled+ ));});}+/**+ * Rebuilds the path below `/custom/` from the `*path` wildcard.+ *+ * Express 5 splits a wildcard into one array entry per segment, where Express 4 passed the whole+ * remainder as a string. The segments arrive decoded, so joining them naively reproduces the+ * Express 4 behaviour a handler's pattern was written against.+ *+ * @TriliumNextTODO: remove the typecast once express types are fixed — they currently only treat+ * `req.params` as string, while in reality it can also be a string[] when using wildcards.+ * @TriliumNextTODO: `splitPath.map(segment => encodeURIComponent(segment)).join("/")` might be safer.+ */+function joinWildcardPath(req: Request): string {+ const splitPath = req.params.path as unknown as string[];++ return splitPath.join("/");+}+export default {register};diff --git a/packages/trilium-core/src/routes/custom.ts b/packages/trilium-core/src/routes/custom.tsnew file mode 100644index 0000000000..c7747d1ae1--- /dev/null+++ b/packages/trilium-core/src/routes/custom.ts@@ -0,0 +1,116 @@+import type { ScriptRequest, ScriptResponse } from "@triliumnext/commons/src/lib/script_api.js";++import becca from "../becca/becca";+import type BNote from "../becca/entities/bnote";+import type { Request, Response } from "../http_interface";+import { getLog } from "../services/log";+import scriptService from "../services/script";+import { getSql } from "../services/sql/index";+import { normalizeCustomHandlerPattern, safeExtractMessageAndStackFromError } from "../services/utils/index";+import { downloadNoteInt } from "./helpers";++/**+ * The response a custom handler writes to: core's {@link Response}, which `downloadNoteInt` needs,+ * plus the {@link ScriptResponse} surface a handler script reaches through `api.res`. Express's+ * `Response` and standalone's mock response both satisfy it.+ */+export type CustomRequestResponse = Response & ScriptResponse;++/**+ * Answers a `/custom/` request from the first `customRequestHandler` or `customResourceProvider`+ * note whose pattern matches `path`, and writes a 404 when none does.+ *+ * @param path the path below `/custom/`, without a leading slash.+ * @param isScriptingEnabled reads the host's backend-scripting toggle. A request handler executes a+ * script and is gated by it; a resource provider only serves a note's content and is not.+ * @returns what the handler script returned. A caller that cannot hold the response open past this+ * call — standalone — awaits it to let an asynchronous handler finish writing.+ */+export function handleCustomRequest(+ path: string, req: Request, res: CustomRequestResponse, isScriptingEnabled: () => boolean+): unknown {+ const attributeIds = getSql().getColumn<string>(+ "SELECT attributeId FROM attributes WHERE isDeleted = 0 AND type = 'label' "+ + "AND name IN ('customRequestHandler', 'customResourceProvider')"+ );++ for (const attributeId of attributeIds) {+ const attr = becca.getAttribute(attributeId);++ if (!attr?.value.trim()) {+ continue;+ }++ const match = matchPath(path, attr.value, attr.attributeId);++ if (!match) {+ continue;+ }++ // Only the first matching handler runs.+ if (attr.name === "customRequestHandler") {+ return runHandler(attr.getNote(), path, match, req, res, isScriptingEnabled);+ } else if (attr.name === "customResourceProvider") {+ downloadNoteInt(attr.noteId, res);+ return;+ } else {+ throw new Error(`Unrecognized attribute name '${attr.name}'`);+ }+ }++ const message = `No handler matched for custom '${path}' request.`;++ getLog().info(message);+ res.setHeader("Content-Type", "text/plain").status(404).send(message);+}++/**+ * Matches `path` against a handler's pattern, trying both the trailing-slash and no-trailing-slash+ * forms {@link normalizeCustomHandlerPattern} produces. A pattern that is not a valid regex is+ * logged and skipped, so one bad label cannot take the whole route down.+ */+function matchPath(path: string, pattern: string, attributeId: string): RegExpMatchArray | null {+ try {+ for (const candidate of normalizeCustomHandlerPattern(pattern)) {+ const match = path.match(new RegExp(`^${candidate}$`));++ if (match) {+ return match;+ }+ }+ } catch (e: unknown) {+ const [errMessage, errStack] = safeExtractMessageAndStackFromError(e);+ getLog().error(`Testing path for label '${attributeId}', regex '${pattern}' failed with error: ${errMessage}, stack: ${errStack}`);+ }++ return null;+}++function runHandler(+ note: BNote, path: string, match: RegExpMatchArray, req: Request, res: CustomRequestResponse,+ isScriptingEnabled: () => boolean+): unknown {+ // Custom request handlers execute backend scripts, so they remain gated behind the+ // scripting toggle. Resource providers only serve static note content and are not.+ if (!isScriptingEnabled()) {+ res.status(403).send("Backend script execution is disabled on this server.");+ return;+ }++ getLog().info(`Handling custom request '${path}' with note '${note.noteId}'`);++ try {+ return scriptService.executeNote(note, {+ pathParams: match.slice(1),+ // `ScriptRequest` declares `params` flat, while Express 5 types a wildcard as+ // `string | string[]` — the same widening the server's path join works around. A+ // handler reads its path through `pathParams` rather than through `params`.+ req: req as unknown as ScriptRequest,+ res+ });+ } catch (e: unknown) {+ const [errMessage, errStack] = safeExtractMessageAndStackFromError(e);+ getLog().error(`Custom handler '${note.noteId}' failed with: ${errMessage}, ${errStack}`);+ res.setHeader("Content-Type", "text/plain").status(500).send(errMessage);+ }+}diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 11d2d5d87c..57f625c4ee 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -42,6 +42,8 @@ import linkEmbedRoute from "./api/link_embed";import spreadsheetRoute from "./api/spreadsheet";import llmRoute from "./api/llm";+export { type CustomRequestResponse, handleCustomRequest } from "./custom";+// TODO: Deduplicate with routes.tsconst GET = "get",PST = "post",