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 shared notes from the browser build
Claude1353e9235c54
diff --git a/apps/standalone/e2e/share.spec.ts b/apps/standalone/e2e/share.spec.tsnew file mode 100644index 0000000000..8c25661b20--- /dev/null+++ b/apps/standalone/e2e/share.spec.ts@@ -0,0 +1,63 @@+import test, { expect } from "@playwright/test";++import App from "../../../packages/trilium-e2e/src/support/app";++/**+ * Shared notes in the browser-only build.+ *+ * There is no server here, so a `/share/` URL is claimed by the service worker, forwarded to the+ * tab holding the database, and rendered by `@triliumnext/core`'s share subsystem inside the+ * worker. Nobody outside this browser can reach these pages; what they make possible is working on+ * the share feature, and reading published notes, without a server build.+ *+ * Requests go through the page rather than Playwright's `request` fixture, which issues them+ * outside the browser and so never reaches the service worker.+ *+ * The fixture's share root is "Shared notes" (`y0AFOwgOgkWO`, labelled `#shareRoot`).+ */+const SHARE_ROOT_ID = "y0AFOwgOgkWO";++test("renders a published note, its tree and the share theme", async ({ context }) => {+ // The database lives in the app tab; without one open there is nothing to render the page.+ const app = new App(await context.newPage(), context);+ await app.goto();+ await expect(app.noteTree).toContainText("Trilium Integration Test");++ const share = await context.newPage();+ const response = await share.goto(`/share/${SHARE_ROOT_ID}`);++ expect(response?.status()).toBe(200);+ await expect(share.locator("h1#title")).toContainText("Shared notes");++ // The tree lists the shared children, but not the one marked #shareHiddenFromTree.+ await expect(share.locator("#menu")).toContainText("Shared that uses template");+ await expect(share.locator("#menu")).not.toContainText("Shared Note Template");++ // The theme's stylesheet is copied into the build rather than answered by a route, so a missing+ // copy step would leave the page unstyled instead of failing outright.+ const stylesStatus = await share.evaluate(async () => (await fetch("/share/assets/styles.css")).status);+ expect(stylesStatus).toBe(200);+});++test("refuses a note behind shareCredentials until they are supplied", async ({ context }) => {+ const app = new App(await context.newPage(), context);+ await app.goto();+ await expect(app.noteTree).toContainText("Trilium Integration Test");++ // "Password protected share" carries #shareCredentials=root:password.+ const anonymous = await app.page.evaluate(async () => {+ const res = await fetch("/share/YjlPRj2E9fOV");++ return { status: res.status, authenticate: res.headers.get("www-authenticate") };+ });+ expect(anonymous.status).toBe(401);+ expect(anonymous.authenticate).toContain("Basic realm=");++ const authorized = await app.page.evaluate(async () => {+ const res = await fetch("/share/YjlPRj2E9fOV", { headers: { authorization: `Basic ${btoa("root:password")}` } });++ return { status: res.status, body: await res.text() };+ });+ expect(authorized.status).toBe(200);+ expect(authorized.body).toContain("Password protected share");+});diff --git a/apps/standalone/src/lightweight/browser_routes.ts b/apps/standalone/src/lightweight/browser_routes.tsindex b0775c5b94..fbeea9bec1 100644--- a/apps/standalone/src/lightweight/browser_routes.ts+++ b/apps/standalone/src/lightweight/browser_routes.ts@@ -6,6 +6,8 @@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 llmRoute from '@triliumnext/core/src/routes/api/llm.js';+import type { ShareReply } from '@triliumnext/core/src/share/handlers.js';+import { SHARE_ROUTE_PATHS, type ShareRoutePath } from '@triliumnext/core/src/share/route_paths.js';import packageJson from '../../package.json' with { type: 'json' };import { type BrowserRequest, BrowserRouter } from './browser_router';@@ -332,6 +334,18 @@ export function registerRoutes(router: BrowserRouter): void {apiResultHandler);+ // Shared notes, served from the same database the app reads. Nobody outside this browser can+ // reach them — there is no server listening — but a published note renders at its real /share+ // URL, which is what makes the feature testable here at all. Registered by path alone and+ // loaded on the first request, so EJS, the share theme and the syntax highlighter stay out of+ // the worker's startup bundle.+ for (const path of SHARE_ROUTE_PATHS) {+ router.get(path, (req) => dispatchShare(path, req));+ }+ // The share root is addressed as `/share/`; `/share` answers with the redirect that adds the+ // slash, which the pattern above cannot match because a parameter needs a segment to fill it.+ router.get("/share", (req) => dispatchShare("/share/", req));+// Dummy routes for compatibility.apiRoute("get", "/api/script/widgets", () => []);apiRoute("get", "/api/script/startup", () => []);@@ -381,6 +395,44 @@ function bootstrapRoute(req: { query: Record<string, string | undefined> }): Boo};}+/** Answers one share request, loading the share subsystem the first time one arrives. */+async function dispatchShare(path: ShareRoutePath, req: BrowserRequest) {+ const [ share, { registerShareProvider } ] = await Promise.all([+ import("@triliumnext/core/src/share/index.js"),+ import("./share_provider.js")+ ]);++ registerShareProvider();++ /* v8 ignore next -- @preserve: BrowserRouter.dispatch always sets req.headers, so the ?? fallback is unreachable. */+ const headers = req.headers ?? {};+ const shareRequest = {+ path: req.path,+ params: req.params,+ query: req.query,+ // `fetch` lower-cases the header names it sends, which is the form BrowserRouter stores them in.+ getHeader: (name: string) => headers[name.toLowerCase()]+ };++ // Shared, and without a transaction: the share routes only read. The imports above are awaited+ // before the lock is taken, so nothing is held open across them.+ return dbLock.runShared(() => getContext().init(() => {+ const reply = share.handleShareRequest(share.getShareRoute(path), shareRequest);++ return toRawShareResponse(reply);+ }));+}++/** Marks a share reply as already formatted, so {@link BrowserRouter} sends it rather than re-wrapping it. */+function toRawShareResponse(reply: ShareReply) {+ return {+ [RAW_RESPONSE]: true as const,+ status: reply.status,+ headers: reply.redirect ? { ...reply.headers, location: reply.redirect } : reply.headers,+ body: reply.body+ };+}+/*** Create and configure a router with all routes registered.*/diff --git a/apps/standalone/src/lightweight/share_provider.ts b/apps/standalone/src/lightweight/share_provider.tsnew file mode 100644index 0000000000..2d530dd71a--- /dev/null+++ b/apps/standalone/src/lightweight/share_provider.ts@@ -0,0 +1,58 @@+import { getSql } from "@triliumnext/core";+import { initShare } from "@triliumnext/core/src/share/index.js";+import template404 from "@triliumnext/share-theme/templates/404.ejs?raw";+import templatePage from "@triliumnext/share-theme/templates/page.ejs?raw";+import templatePrevNext from "@triliumnext/share-theme/templates/prev_next.ejs?raw";+import templateTocItem from "@triliumnext/share-theme/templates/toc_item.ejs?raw";+import templateTreeItem from "@triliumnext/share-theme/templates/tree_item.ejs?raw";++/**+ * The share theme's templates, bundled rather than read from disk: this build has no filesystem to+ * read them from, and they are small enough that the lazy share chunk can carry them whole.+ */+const TEMPLATES: Record<string, string> = {+ "404": template404,+ page: templatePage,+ prev_next: templatePrevNext,+ toc_item: templateTocItem,+ tree_item: templateTreeItem+};++let registered = false;++/**+ * Registers the share subsystem against this build: one database connection rather than the+ * server's separate read-only one, and bundled templates.+ */+export function registerShareProvider() {+ if (registered) {+ return;+ }++ initShare({+ sql: {+ getRawRows: (query, params = []) => getSql().getRawRows(query, params),+ getRow: (query, params = []) => getSql().getRow(query, params),+ getColumn: (query, params = []) => getSql().getColumn(query, params)+ },+ readTemplate,+ // A shared note's own EJS template runs arbitrary JavaScript in the renderer. The server+ // gates that on backend scripting being enabled; this build has no such setting and no+ // backend scripting, so a note's template is never executed.+ isScriptingEnabled: () => false,+ // The share cache reads the same connection every other route does, so it is ready as soon+ // as the worker answers at all.+ isReady: () => true+ });+ registered = true;+}++function readTemplate(name: string) {+ const template = TEMPLATES[name];++ if (template === undefined) {+ throw new Error(`Unknown share template '${name}'.`);+ }++ return template;+}diff --git a/apps/standalone/src/local-bridge.spec.ts b/apps/standalone/src/local-bridge.spec.tsindex ccb7143403..dc36964dce 100644--- a/apps/standalone/src/local-bridge.spec.ts+++ b/apps/standalone/src/local-bridge.spec.ts@@ -464,6 +464,16 @@ describe("isLocalApiRequest", () => {expect(bridge.isLocalApiRequest(new URL("http://x/app.js"))).toBe(false);expect(bridge.isLocalApiRequest(new URL("http://x/"))).toBe(false);});++ it("claims the shared-note pages but not the share theme's own assets", async () => {+ const bridge = await freshBridge();+ for (const path of ["/share", "/share/", "/share/my-alias", "/share/api/notes/abc123"]) {+ expect(bridge.isLocalApiRequest(new URL(`http://x${path}`)), path).toBe(true);+ }+ for (const path of ["/share/assets/styles.css", "/share/assets/fonts/boxicons.woff2", "/shared-drafts"]) {+ expect(bridge.isLocalApiRequest(new URL(`http://x${path}`)), path).toBe(false);+ }+ });});describe("backup download keepalive", () => {diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.tsindex af813f9dae..916cf17443 100644--- a/apps/standalone/src/local-bridge.ts+++ b/apps/standalone/src/local-bridge.ts@@ -368,7 +368,20 @@ async function* backupChunks(passphrase: string | undefined): AsyncGenerator<Uinconst MAX_BACKUP_CHUNKS_IN_FLIGHT = 4;export function isLocalApiRequest(url: URL): boolean {- return LOCAL_API_PREFIXES.some(p => url.pathname.startsWith(p));+ return isShareRequest(url.pathname) || LOCAL_API_PREFIXES.some(p => url.pathname.startsWith(p));+}++/**+ * True for the shared-note pages and their API, which the local worker renders. `/share/assets/`+ * is the share theme's own stylesheets, scripts and fonts: those ship with the build and are+ * served like any other static file. Mirrors the same check in `sw.ts`.+ */+function isShareRequest(pathname: string): boolean {+ if (pathname.startsWith("/share/assets/")) {+ return false;+ }++ return pathname === "/share" || pathname.startsWith("/share/");}export async function localFetch(request: Request): Promise<Response> {diff --git a/apps/standalone/src/sw.spec.ts b/apps/standalone/src/sw.spec.tsindex 1d92f9bfdf..cf284eb6db 100644--- a/apps/standalone/src/sw.spec.ts+++ b/apps/standalone/src/sw.spec.ts@@ -137,6 +137,40 @@ describe("fetch routing", () => {expect(event._response).toBeDefined();});+ it("routes shared-note pages to the client bridge but serves the share theme's assets statically", async () => {+ const handlers = await loadSw();++ for (const path of [ "/share", "/share/", "/share/my-alias", "/share/api/notes/abc123" ]) {+ const event = fetchEvent(`${origin}${path}`, { mode: "navigate" });+ handlers.fetch(event);+ expect(event._response, path).toBeDefined();+ }++ // The theme's own files ship with the build, so they take the ordinary static path.+ vi.mocked(fetch).mockClear();+ const asset = fetchEvent(`${origin}/share/assets/styles.css`);+ handlers.fetch(asset);+ await awaitResponse(asset);+ expect(fetch).toHaveBeenCalled();+ });++ it("explains that Trilium must be open when a share page finds no app window", async () => {+ // A lone pdfjs frame is not an app window: it carries no local bridge to render the page.+ (self as unknown as SwGlobals).clients = {+ claim: vi.fn(),+ matchAll: vi.fn(async () => [{ url: `${origin}/pdfjs/viewer.html`, postMessage: vi.fn() }])+ };+ const handlers = await loadSw();+ const event = fetchEvent(`${origin}/share/my-alias`, { mode: "navigate" });+ handlers.fetch(event);++ const res = await awaitResponse(event);+ expect(res.status).toBe(503);+ expect(await res.text()).toContain("Open Trilium in this browser");+ // Nothing to forward to, and no server behind it either.+ expect(fetch).not.toHaveBeenCalled();+ });+it("serves navigations and .html network-first (which bypasses cache in dev)", async () => {const handlers = await loadSw();const navEvent = fetchEvent(`${origin}/index.html`, { mode: "navigate" });diff --git a/apps/standalone/src/sw.ts b/apps/standalone/src/sw.tsindex c16d12089f..02a31a8dad 100644--- a/apps/standalone/src/sw.ts+++ b/apps/standalone/src/sw.ts@@ -49,7 +49,20 @@ self.addEventListener("activate", (event) => {});function isLocalFirst(url) {- return LOCAL_FIRST_PREFIXES.some((p) => url.pathname.startsWith(p));+ return isShareRequest(url.pathname) || LOCAL_FIRST_PREFIXES.some((p) => url.pathname.startsWith(p));+}++/**+ * True for the shared-note pages and their API, which the local worker renders. `/share/assets/`+ * is the share theme's own stylesheets, scripts and fonts: those ship with the build and are+ * served like any other static file.+ */+function isShareRequest(pathname) {+ if (pathname.startsWith("/share/assets/")) {+ return false;+ }++ return pathname === "/share" || pathname.startsWith("/share/");}async function cacheFirst(request) {@@ -161,6 +174,28 @@ async function findLeaderClient() {return { client, candidates };}+/**+ * Answers a shared-note page. The pages are rendered by the tab holding the database, so with no+ * app window open there is nobody to render them and no server to fall back to — which the plain+ * forwarder would report as whatever the static host says. This says so instead.+ */+async function answerShareRequest(request, clientId) {+ // @ts-expect-error - self.clients is valid in service worker context+ const all = await self.clients.matchAll({ type: "window", includeUncontrolled: true });++ if (!all.some(isMainAppWindow)) {+ return new Response(+ "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>Trilium</title></head>"+ + "<body><h1>Trilium is not open</h1>"+ + "<p>Shared notes are rendered by the Trilium tab that holds your database. Open Trilium in this browser, then reload this page.</p>"+ + "</body></html>",+ { status: 503, headers: { "content-type": "text/html; charset=utf-8" } }+ );+ }++ return forwardToClientLocalServer(request, clientId);+}+async function forwardToClientLocalServer(request, _clientId, retried = false) {const { client, candidates } = await findLeaderClient();@@ -363,7 +398,9 @@ self.addEventListener("fetch", (event) => {// API-ish: local-first via bridge (must be checked before navigate handling,// because export triggers a navigation to an /api/ URL)if (isLocalFirst(url)) {- event.respondWith(forwardToClientLocalServer(event.request, event.clientId));+ event.respondWith(isShareRequest(url.pathname)+ ? answerShareRequest(event.request, event.clientId)+ : forwardToClientLocalServer(event.request, event.clientId));return;}diff --git a/apps/standalone/src/test_setup.ts b/apps/standalone/src/test_setup.tsindex 08e73f1116..c33f930c4d 100644--- a/apps/standalone/src/test_setup.ts+++ b/apps/standalone/src/test_setup.ts@@ -11,6 +11,7 @@ import StandaloneBackupService from "./lightweight/backup_provider.js";import BrowserExecutionContext from "./lightweight/cls_provider.js";import BrowserCryptoProvider from "./lightweight/crypto_provider.js";import StandalonePlatformProvider from "./lightweight/platform_provider.js";+import { registerShareProvider } from "./lightweight/share_provider.js";import BrowserSqlProvider from "./lightweight/sql_provider.js";import BrowserZipProvider from "./lightweight/zip_provider.js";import { standaloneImageProvider } from "./services/image_provider.js";@@ -134,4 +135,7 @@ beforeAll(async () => {onTransactionRollback: () => {}}});++ // The share specs render real share-theme templates, which the provider carries in the bundle.+ registerShareProvider();});diff --git a/apps/standalone/vite.config.mts b/apps/standalone/vite.config.mtsindex 12053e4620..4037b53678 100644--- a/apps/standalone/vite.config.mts+++ b/apps/standalone/vite.config.mts@@ -12,6 +12,13 @@ const clientAssets = ["assets", "stylesheets", "fonts", "translations"];const isDev = process.env.NODE_ENV === "development";+// The share pages resolve built-in assets against `assets/v<version>`, the same prefix the server+// serves them under. Read from trilium-core because that is the version `assetUrlFragment` is+// built from; `chore:update-version` keeps every package.json in step.+const coreVersion = JSON.parse(+ fs.readFileSync(join(__dirname, "../../packages/trilium-core/package.json"), "utf-8")+).version;+// Watch client files and trigger reload in developmentconst clientWatchPlugin = () => ({name: "client-watch",@@ -142,6 +149,29 @@ let plugins: any = [}]}),+ // What the share theme's own pages load: its bundle (stylesheets, scripts, KaTeX fonts), the+ // icon-pack fonts the client ships, and the logo, each at the path content_renderer.ts writes+ // into the page. The server answers these from express.static routes it registers in+ // routes/assets.ts; here they are copied into the build instead.+ viteStaticCopy({+ targets: [+ {+ src: "../../../packages/share-theme/dist/**/*",+ dest: "share/assets",+ rename: { stripBase: 3 }+ },+ {+ src: "../../client/src/fonts/**/*",+ dest: "share/assets/fonts",+ rename: { stripBase: 3 }+ },+ {+ src: "../../server/src/assets/images/**/*",+ dest: `assets/v${coreVersion}/images`,+ rename: { stripBase: 4 }+ }+ ]+ }),// PDF.js viewer for PDF preview support// stripBase: 4 removes packages/pdfjs-viewer/dist/web (or /build)viteStaticCopy({@@ -273,6 +303,13 @@ export default defineConfig(() => ({{find: /^puppeteer$/,replacement: join(__dirname, "src/stubs/empty.ts")+ },+ // EJS renders the share pages. Its ESM entry imports `node:fs` and `node:path` for the+ // file-loading it only reaches without an `includer`; the share renderer always passes+ // one, so the package's own browser build serves it and resolves in this bundle.+ {+ find: /^ejs$/,+ replacement: join(__dirname, "../../node_modules/ejs/ejs.min.js")}],dedupe: [diff --git a/docs/Developer Guide/Developer Guide/Concepts/Share.md b/docs/Developer Guide/Developer Guide/Concepts/Share.mdindex 22dc512f58..a7f59fd7bc 100644--- a/docs/Developer Guide/Developer Guide/Concepts/Share.md+++ b/docs/Developer Guide/Developer Guide/Concepts/Share.md@@ -12,6 +12,22 @@ The share theme represents the layout, styles and scripts behind the Share notes* In `packages/share-theme`, run `pnpm build` to trigger a build. This will generate `dist` which will then be used by the server.* Alternatively, use `pnpm dev` to watch for changes.+## Where the code lives++The share subsystem is in `packages/trilium-core/src/share`, so that every runtime that carries core can serve it:++* `shaca` is the read-only cache of the `_share` subtree, loaded from raw rows.+* `content_renderer.ts` renders one of its notes into a page.+* `handlers.ts` holds the routes as transport-neutral handlers: each takes a `ShareRequest` and returns a `ShareReply` (status, headers, body or redirect), touching no Express type. `route_paths.ts` lists the URL patterns on their own, free of imports, so a router can register them without loading the renderer behind them.++What differs per platform goes through the `ShareProvider` (`share_provider.ts`): where the rows come from, where the EJS templates come from, and whether a note is allowed to supply its own template.++| | Server / desktop | Standalone / mobile |+| --- | --- | --- |+| Rows | a second, read-only `better-sqlite3` connection (`apps/server/src/share/sql.ts`) | the one sqlite-wasm connection, shared with every other route |+| Templates | read from disk | bundled into the build with `?raw` |+| A note's own EJS template | allowed when backend scripting is enabled | never — this build has no backend scripting |+## Integration with the server for the share functionalityThe server renders the templates using EJS templating from the share theme and hosts the assets.@@ -21,7 +37,16 @@ The server renders the templates using EJS templating from the share theme and h* Changes to the template will require a restart of the server, since they are cached. Simply press Enter in the console with `pnpm server:start` to quickly trigger a restart.* In production mode, the share theme is automatically built by the server build script and copied to `dist/share-theme`.-The server route handling this functionality is in `src/share/routes.ts`.+`apps/server/src/share/routes.ts` is the Express adapter over the core handlers, and `apps/server/src/share/share_provider.ts` registers the provider above.++## Integration with the standalone (in-browser) build++`apps/standalone` serves the same pages from the browser. A `/share/` request is claimed by the service worker, forwarded to the tab that owns the database, and answered by the worker's `BrowserRouter` (`apps/standalone/src/lightweight/browser_routes.ts`); `share_provider.ts` beside it supplies the rows and the bundled templates. Nothing outside the browser can reach these pages — there is no server listening — so this is for working on the share feature and for reading published notes locally, not for publishing.++* The subsystem is loaded by a dynamic `import()` on the first `/share/` request, which keeps EJS, the share theme and the syntax highlighter (~950 KB together) out of the worker's startup bundle. That only holds while nothing in the eager graph imports `share/index.ts`, which is why it is not re-exported from the `@triliumnext/core` barrel.+* `ejs` is aliased to its own browser build in `vite.config.mts`: the package's ESM entry imports `node:fs` and `node:path`, which it only needs when no `includer` is passed, and the renderer always passes one.+* The share theme's assets are copied into the build at the paths `content_renderer.ts` writes into the page (`share/assets`, `assets/v<version>/images`), in place of the `express.static` routes the server registers.+* The pages are rendered by the tab holding the database, so at least one app tab must be open for a `/share/` URL to resolve.## Exporting to static HTML files