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
feat(standalone): serve custom request handlers and resource providers
Elian Doran7d48ffafb5b5
diff --git a/apps/standalone/src/lightweight/browser_router.spec.ts b/apps/standalone/src/lightweight/browser_router.spec.tsindex 6dd91342aa..e8951d7bf4 100644--- a/apps/standalone/src/lightweight/browser_router.spec.ts+++ b/apps/standalone/src/lightweight/browser_router.spec.ts@@ -45,6 +45,26 @@ describe("BrowserRouter routing", () => {expect(captured?.query).toEqual({ expand: "true", depth: "2" });});+ // What `/custom/*path` needs: a splat spans slashes, where a `:param` stops at one. The two+ // are captured in one pass so `paramNames` stays in step with the capture groups whichever+ // order they appear in.+ it("captures a *splat across segments, alongside a :param", async () => {+ const router = new BrowserRouter();+ let captured: Record<string, string> | undefined;+ router.get("/u/:userId/files/*filePath", (req) => {+ captured = req.params;+ return {};+ });++ await router.dispatch("GET", "http://localhost/u/u1/files/deep/nested/report.txt");+ expect(captured).toEqual({ userId: "u1", filePath: "deep/nested/report.txt" });++ // A splat also matches nothing, so `/custom/` itself reaches the handler.+ router.get("/custom/*path", (req) => ({ path: req.params.path }));+ expect(decodeBody((await router.dispatch("GET", "http://localhost/custom/")).body))+ .toBe(JSON.stringify({ path: "" }));+ });+it("returns 404 text for an unmatched route", async () => {const router = new BrowserRouter();const res = await router.dispatch("GET", "http://localhost/missing");diff --git a/apps/standalone/src/lightweight/browser_router.ts b/apps/standalone/src/lightweight/browser_router.tsindex 8a24dee3ed..232fec1314 100644--- a/apps/standalone/src/lightweight/browser_router.ts+++ b/apps/standalone/src/lightweight/browser_router.ts@@ -48,21 +48,25 @@ const encoder = new TextEncoder();/*** Convert an Express-style path pattern to a RegExp.- * Supports :param syntax for path parameters.+ * Supports :param syntax for path parameters and Express 5's *splat wildcard, which matches the+ * rest of the path including slashes.** Examples:* /api/notes/:noteId -> /^\/api\/notes\/([^\/]+)$/* /api/notes/:noteId/revisions -> /^\/api\/notes\/([^\/]+)\/revisions$/+ * /custom/*path -> /^\/custom\/(.*)$/*/function pathToRegex(path: string): { pattern: RegExp; paramNames: string[] } {const paramNames: string[] = [];- // Escape special regex characters except for :param patterns+ // Escape special regex characters first, so the placeholder scan below sees `\*splat` rather+ // than a `*` that could be read as a quantifier. One pass over both forms keeps `paramNames`+ // in the same order as the capture groups.const regexPattern = path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') // Escape special chars- .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, paramName) => {- paramNames.push(paramName);- return '([^/]+)';+ .replace(/\\\*([a-zA-Z_][a-zA-Z0-9_]*)|:([a-zA-Z_][a-zA-Z0-9_]*)/g, (_, splat, param) => {+ paramNames.push(splat ?? param);+ return splat ? '(.*)' : '([^/]+)';});return {diff --git a/apps/standalone/src/lightweight/browser_routes.spec.ts b/apps/standalone/src/lightweight/browser_routes.spec.tsindex 3e08062684..eae6aa997f 100644--- a/apps/standalone/src/lightweight/browser_routes.spec.ts+++ b/apps/standalone/src/lightweight/browser_routes.spec.ts@@ -1,5 +1,5 @@-import { consistency_checks, getSql, routes, sql_init } from "@triliumnext/core";-import { afterEach, describe, expect, it, vi } from "vitest";+import { cls, consistency_checks, getConfig, getSql, note_service as noteService, routes, sql_init } from "@triliumnext/core";+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";import { BrowserRouter } from "./browser_router.js";import { createConfiguredRouter, registerRoutes } from "./browser_routes.js";@@ -282,3 +282,120 @@ describe("route wrapper branches (via controlled handlers)", () => {expect(() => (ctx.checkAppNotInitialized as () => void)()).not.toThrow();});});++// `/custom/` is registered outside the shared table, so nothing else would catch its loss. Unlike+// the server's route it cannot hold the response open past the handler returning, so what the tests+// below pin down is not only that a handler runs but that its answer is complete when it is sent.+describe("custom request handlers and resource providers", () => {+ const router = createConfiguredRouter();+ const coreConfig = getConfig();+ const originalScripting = coreConfig.Security.backendScriptingEnabled;++ beforeAll(() => {+ coreConfig.Security.backendScriptingEnabled = true;++ cls.init(() => {+ createHandler("Greeter", "greet/([a-z]+)", `api.res.status(200).send("handled:" + api.pathParams[0]);`);+ createHandler("Thrower", "explode", `throw new Error("boom in handler");`);+ createHandler("Echo", "echo", `api.res.json({ method: api.req.method, body: api.req.body });`);+ // A handler that answers after an await: what the server gets for free by holding the+ // connection open, this runtime has to wait for.+ createHandler("Deferred", "deferred", `+return (async () => {+ await Promise.resolve();+ api.res.status(200).send("late");+})();`);+ // A handler that returns without answering. The server leaves such a request hanging+ // until the client gives up; here the worker has to send something.+ createHandler("Silent", "silent", `api.log("thinking about it");`);++ const resource = noteService.createNewNote({+ parentNoteId: "root",+ title: "Custom resource",+ type: "text",+ content: "<p>resource body</p>"+ }).note;+ resource.setLabel("customResourceProvider", "resource");+ });+ });++ afterAll(() => {+ coreConfig.Security.backendScriptingEnabled = originalScripting;+ });++ function createHandler(title: string, pattern: string, content: string) {+ const note = noteService.createNewNote({+ parentNoteId: "root",+ title,+ type: "code",+ mime: "application/javascript;env=backend",+ content+ }).note;+ note.setLabel("customRequestHandler", pattern);+ }++ it("runs a handler with the captured path params", async () => {+ const res = await router.dispatch("GET", "http://localhost/custom/greet/world");+ expect(res.status).toBe(200);+ expect(text(res.body)).toBe("handled:world");+ });++ it("reaches a handler over a method other than GET, carrying the parsed body", async () => {+ const body = new TextEncoder().encode(JSON.stringify({ hello: "there" })).buffer as ArrayBuffer;+ const res = await router.dispatch("POST", "http://localhost/custom/echo", body, {+ "content-type": "application/json"+ });++ expect(res.status).toBe(200);+ expect(res.headers["Content-Type"]).toContain("application/json");+ expect(parseJson(res.body)).toEqual({ method: "POST", body: { hello: "there" } });+ });++ it("waits for a handler that answers after an await", async () => {+ const res = await router.dispatch("GET", "http://localhost/custom/deferred");+ expect(res.status).toBe(200);+ expect(text(res.body)).toBe("late");+ });++ it("answers 500 when a handler returns without responding", async () => {+ const res = await router.dispatch("GET", "http://localhost/custom/silent");+ expect(res.status).toBe(500);+ expect(text(res.body)).toContain("did not send a response");+ });++ it("answers 500 when the handler throws", async () => {+ const res = await router.dispatch("GET", "http://localhost/custom/explode");+ expect(res.status).toBe(500);+ expect(text(res.body)).toContain("boom in handler");+ });++ it("serves a resource provider note", async () => {+ const res = await router.dispatch("GET", "http://localhost/custom/resource");+ expect(res.status).toBe(200);+ expect(text(res.body)).toContain("resource body");+ });++ it("answers 404 when no handler matches", async () => {+ const res = await router.dispatch("GET", "http://localhost/custom/no-such-path");+ expect(res.status).toBe(404);+ expect(text(res.body)).toContain("No handler matched");+ });++ // A resource provider executes no code, so it stays readable with scripting off; a request+ // handler runs a script and must not.+ it("gates only the request handler on the backend-scripting toggle", async () => {+ coreConfig.Security.backendScriptingEnabled = false;++ try {+ const handler = await router.dispatch("GET", "http://localhost/custom/greet/world");+ expect(handler.status).toBe(403);+ expect(text(handler.body)).toContain("Backend script execution is disabled");++ const resource = await router.dispatch("GET", "http://localhost/custom/resource");+ expect(resource.status).toBe(200);+ expect(text(resource.body)).toContain("resource body");+ } finally {+ coreConfig.Security.backendScriptingEnabled = true;+ }+ });+});diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.tsindex b0775c5b94..1389a5f9da 100644--- a/apps/standalone/src/lightweight/browser_routes.ts+++ b/apps/standalone/src/lightweight/browser_routes.ts@@ -4,7 +4,7 @@*/import { BootstrapDefinition } from '@triliumnext/commons';-import { checkIntegrity, consistency_checks, entity_changes, getContext, getPlatform, getSharedBootstrapItems, getSql, type Request, type Response, routes, sql_init } from '@triliumnext/core';+import { checkIntegrity, consistency_checks, entity_changes, getContext, getPlatform, getSharedBootstrapItems, getSql, isScriptingEnabled, type Request, type Response, routes, sql_init } from '@triliumnext/core';import llmRoute from '@triliumnext/core/src/routes/api/llm.js';import packageJson from '../../package.json' with { type: 'json' };@@ -108,12 +108,7 @@ function createRoute(router: BrowserRouter) {// If the handler used the mock response (e.g. image routes that call res.send()),// return it as a raw response so BrowserRouter doesn't JSON-serialize it.if (mockRes._used) {- return {- [RAW_RESPONSE]: true as const,- status: mockRes._status,- headers: mockRes._headers,- body: mockRes._body- };+ return toRawResponse(mockRes);}if (resultHandler) {@@ -150,12 +145,7 @@ function createAsyncRoute(router: BrowserRouter, { transactional = true } = {})// If the handler used the mock response (e.g. image routes that call res.send()),// return it as a raw response so BrowserRouter doesn't JSON-serialize it.if (mockRes._used) {- return {- [RAW_RESPONSE]: true as const,- status: mockRes._status,- headers: mockRes._headers,- body: mockRes._body- };+ return toRawResponse(mockRes);}if (resultHandler) {@@ -200,9 +190,30 @@ function createMockResponse() {},send(body: unknown) {res._used = true;+ // Express serializes an object body as JSON, and a custom request handler written+ // against it does `api.res.send({...})`. Strings and bytes are left as they are: those+ // are what the note-content routes send.+ if (body !== null && typeof body === "object" && !isBinary(body)) {+ return res.json(body);+ }res._body = body;return res;},+ json(body: unknown) {+ res._used = true;+ // Express fills in the type only when the handler has not chosen one, so a handler+ // answering `application/problem+json` keeps it.+ if (!hasHeader(res._headers, "Content-Type")) {+ res._headers["Content-Type"] = "application/json; charset=utf-8";+ }+ res._body = JSON.stringify(body);+ return res;+ },+ redirect(url: string) {+ res._used = true;+ res._status = 302;+ res._headers["Location"] = url;+ },sendStatus(code: number) {res._used = true;res._status = code;@@ -221,6 +232,16 @@ function createMockResponse() {return res;}+/** Whether a body is already bytes, which {@link BrowserRouter} sends without re-encoding. */+function isBinary(body: object): boolean {+ return body instanceof ArrayBuffer || ArrayBuffer.isView(body);+}++/** Header names are case-insensitive, while the record a handler writes them into is not. */+function hasHeader(headers: Record<string, string>, name: string): boolean {+ return Object.keys(headers).some((key) => key.toLowerCase() === name.toLowerCase());+}+/*** Standalone apiResultHandler matching the server's behavior:* - Converts Becca entities to POJOs@@ -332,6 +353,8 @@ export function registerRoutes(router: BrowserRouter): void {apiResultHandler);+ registerCustomRoute(router);+// Dummy routes for compatibility.apiRoute("get", "/api/script/widgets", () => []);apiRoute("get", "/api/script/startup", () => []);@@ -381,6 +404,53 @@ function bootstrapRoute(req: { query: Record<string, string | undefined> }): Boo};}+/** Every method a handler script can answer. The server registers its route as an Express `all`. */+const CUSTOM_HANDLER_METHODS: HttpMethod[] = ["get", "post", "put", "patch", "delete"];++/**+ * Serves `/custom/`: the notes labelled `#customRequestHandler` and `#customResourceProvider`.+ *+ * Registered here rather than in the shared table because the server answers it from a route of its+ * own, ahead of the API router and without CSRF, and because it takes any method rather than one.+ */+function registerCustomRoute(router: BrowserRouter) {+ for (const method of CUSTOM_HANDLER_METHODS) {+ router.register(method, "/custom/*path", (req: BrowserRequest) => dbLock.runShared(+ () => getContext().init(async () => {+ setContextFromHeaders(req);+ const path = req.params.path;+ const res = createMockResponse();++ // Deliberately no transaction: a handler script may await, and one held open+ // across that would block every other request on the worker's single connection.+ // The server's route opens none either.+ //+ // Awaited because this runtime cannot hold the response open past the handler+ // returning the way Express does. A script that answers after an `await` returns+ // its promise, and the body has to be complete before the router sends it.+ await routes.handleCustomRequest(path, toCoreRequest(req), res, isScriptingEnabled);++ if (!res._used) {+ res.setHeader("Content-Type", "text/plain").status(500)+ .send(`Custom handler for '${path}' did not send a response.`);+ }++ return toRawResponse(res);+ }) as Promise<unknown>+ ));+ }+}++/** Wraps what a handler wrote to its mock response so {@link BrowserRouter} sends it verbatim. */+function toRawResponse(res: ReturnType<typeof createMockResponse>) {+ return {+ [RAW_RESPONSE]: true as const,+ status: res._status,+ headers: res._headers,+ body: res._body+ };+}+/*** Create and configure a router with all routes registered.*/diff --git a/apps/standalone/src/local-bridge.spec.ts b/apps/standalone/src/local-bridge.spec.tsindex ccb7143403..a24bfaebe0 100644--- a/apps/standalone/src/local-bridge.spec.ts+++ b/apps/standalone/src/local-bridge.spec.ts@@ -458,7 +458,9 @@ describe("localFetch", () => {describe("isLocalApiRequest", () => {it("matches only the local API prefixes", async () => {const bridge = await freshBridge();- for (const path of ["/bootstrap", "/api/notes", "/sync/changed", "/search/q"]) {+ // `/custom/` carries custom request handlers and resource providers, which a frontend+ // script reaches with a plain fetch rather than through `server.ts`.+ for (const path of ["/bootstrap", "/api/notes", "/sync/changed", "/search/q", "/custom/my-handler"]) {expect(bridge.isLocalApiRequest(new URL(`http://x${path}`))).toBe(true);}expect(bridge.isLocalApiRequest(new URL("http://x/app.js"))).toBe(false);diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.tsindex af813f9dae..9d4151c480 100644--- a/apps/standalone/src/local-bridge.ts+++ b/apps/standalone/src/local-bridge.ts@@ -55,7 +55,8 @@ export function announceLeadership(): void {navigator.serviceWorker?.controller?.postMessage({ type: "LEADER_ANNOUNCE" });}-const LOCAL_API_PREFIXES = ["/bootstrap", "/api/", "/sync/", "/search/"];+/** Must stay in step with LOCAL_FIRST_PREFIXES in sw.ts, which covers the same paths on the web. */+const LOCAL_API_PREFIXES = ["/bootstrap", "/api/", "/sync/", "/search/", "/custom/"];/*** Restores the database from a backup, on the worker that owns it.diff --git a/apps/standalone/src/sw.spec.ts b/apps/standalone/src/sw.spec.tsindex 1d92f9bfdf..301c1bb7c7 100644--- a/apps/standalone/src/sw.spec.ts+++ b/apps/standalone/src/sw.spec.ts@@ -135,6 +135,12 @@ describe("fetch routing", () => {const event = fetchEvent(`${origin}/api/notes`);handlers.fetch(event);expect(event._response).toBeDefined();++ // `/custom/` carries custom request handlers and resource providers. Left off this list it+ // would be fetched as a static asset, over a network this build does not have.+ const custom = fetchEvent(`${origin}/custom/my-handler`);+ handlers.fetch(custom);+ expect(custom._response).toBeDefined();});it("serves navigations and .html network-first (which bypasses cache in dev)", async () => {diff --git a/apps/standalone/src/sw.ts b/apps/standalone/src/sw.tsindex c16d12089f..abe52b929c 100644--- a/apps/standalone/src/sw.ts+++ b/apps/standalone/src/sw.ts@@ -10,12 +10,14 @@ if (isDev) {console.log('[Service Worker] Running in DEV mode - caching disabled');}-// Adjust these to your routes:+// Adjust these to your routes. Must stay in step with LOCAL_API_PREFIXES in local-bridge.ts, which+// covers the same paths on iOS, where no service worker can register.const LOCAL_FIRST_PREFIXES = ["/bootstrap","/api/","/sync/",- "/search/"+ "/search/",+ "/custom/"];// Optional: basic precache list (keep small; you can expand later)diff --git a/packages/trilium-core/src/index.ts b/packages/trilium-core/src/index.tsindex 432f391f94..d1d80c5059 100644--- a/packages/trilium-core/src/index.ts+++ b/packages/trilium-core/src/index.ts@@ -128,6 +128,7 @@ export { type SearchParams } from "./services/search/services/types";export { checkImageAttachments, collectCanvasImageFileIds, default as note_service, findBookmarks, findLlmChatLinks, findMindMapLinks, saveLinks } from "./services/notes";export type { NoteParams } from "./services/notes";export * as sanitize from "./services/sanitizer";+export { assertScriptingEnabled, assertSqlConsoleEnabled, isScriptingEnabled } from "./services/scripting_guard";export * as routes from "./routes";export { default as ws } from "./services/ws";export { default as request } from "./services/request";