Introducing a new way to review your PRs.

Read the announcement

triliumnext / trilium

Build your personal knowledge base with Trilium Notes

View on GitHub

20 documents · Updated Nov 23, 2026

docs / server-http-api-and-sharing

Server HTTP APIs and sharing

The server HTTP layer exposes Trilium's application actions, integration points, and public note views. It turns requests into authenticated, request-scoped calls to shared core services, then presents durable note data to trusted clients or visitors of a configured share tree. See Server platform for the server lifecycle, Server storage and note services for durable note behavior, and Server intelligence and automation for model and agent endpoints.

HTTP API surface

The HTTP API is the main boundary for browser clients and external tools. It keeps product actions in shared core services while the server supplies web transport, session state, tokens, uploads, streaming, and response rules.

Application API

The application API under /api serves the signed-in client. It covers note and tree changes, attributes, attachments, revisions, search, sync, setup, authentication, imports and exports, database work, OCR, metrics, model chat, resource management, client options, and integration setup. The options endpoints expose approved user settings and selected runtime state while keeping secret values write-only. They also report safe status flags for configured secrets and server features, discover user themes and fonts, and apply a multi-option update as one database change before applying a locale change. The resource endpoints report installed resources, start or cancel downloads, and remove managed or foreign resource files. The database and setup routes support integrity checks, compaction, anonymized copies, backup restore, and restore progress. OCR routes process supported notes or attachments and can start a batch job whose progress is polled. System routes report CPU emulation checks and network URLs that another device can use for sync. Metrics returns Prometheus text by default or a structured JSON snapshot when requested. The server also supports browser capture through the clipper routes and link metadata for previews. File and attachment routes let the client read stored content, upload replacements, stream media, preview office files, and manage attachment records. A server-only media proxy gives browser media capture a short-lived local address when a remote host does not allow the required browser read. Most calls use the browser session and CSRF protection because they can read or change the user's document. A separate bootstrap response gives the client the state and view data that it needs before it starts normal API work.

Search endpoints support several client needs through one search service. Full search can limit results to a note subtree and can include archived notes or token details. Quick search follows the current hoisted subtree and returns a bounded result page with snippets and highlight information. Saved searches can return lazy result details only for notes that belong to the saved result set, while query linting reports parse errors before a search runs. Search responses also support template discovery, related-note lookup, and note MIME counts. These boundaries keep search scope and result detail under server control rather than allowing a client to request arbitrary note snippets.

The shared route catalog is used by the server and other client hosts. This keeps the browser contract close to the core feature that owns the action instead of creating a second server-only product model. The server adds routes for concerns that need Node or server state, such as login, uploads, resource downloads, OneNote access, and public sharing.

File uploads preserve the difference between content that the browser displays and content that it downloads. Image uploads wait until the stored bytes are ready before returning a usable image URL. A caller that asks to keep an image as a file link receives an attachment view link instead. Desktop file editing uses a temporary server file as a bridge between an opened file and a later update to the note or attachment. Reopening an unchanged entity reuses its temporary file, while pending edits or a changed file name create a new file so the editor keeps the right content and file type. The HTTP boundary rejects nested multipart field names and applies the real single-blob size rule when content is stored rather than imposing one compressed-archive limit on every upload.

Route familyMain purposeUsual access model
/apiApplication reads, writes, search, sync, setup, files, resource management, options, operational actions, and browser media supportTrilium session; CSRF for state-changing browser calls
/etapiStable automation API for notes, branches, attributes, attachments, revisions, backups, and app informationETAPI token
/sharePublic pages and read-only content for a configured share treeShare credentials when a shared subtree requires them
/mcpModel Context Protocol access to note-aware toolsETAPI bearer token and enabled MCP option

References: apps/…/routes.ts• L48-74 apps/…/routes.ts• L93-125 apps/…/routes.ts• L130-208 apps/…/index.ts• L20-193 packages/…/index.ts• L84-170 packages/…/index.ts• L214-259 packages/…/options.ts• L175-250 packages/…/notes.ts• L45-207 packages/…/image.ts• L101-134 apps/…/route_api.ts• L171-206 apps/…/files.ts• L31-70 apps/…/files.spec.ts• L69-115 apps/…/media_proxy.ts• L27-60 apps/…/metrics.ts• L8-20 apps/…/ocr.ts• L12-72 apps/…/system_info.ts• L13-33 apps/…/resources.ts• L7-41 apps/…/setup_restore.ts• L15-68

Integration endpoints

Integration endpoints let other applications add or consume knowledge without using the browser UI. ETAPI provides a token-based resource API with JSON records and content transfers. The web clipper and sender endpoints accept captured text, images, tabs, or files and place them in inbox notes. The clipper groups captures from the same page by clipping type, while each captured file remains a new note because the file may have changed. It sanitizes captured markup, keeps only approved page labels, stores valid images and favicons as note attachments, and can turn saved tabs into local link previews. Embedded YouTube players become safe link previews instead of active players. It chooses the configured clipper inbox or an appropriate journal location when no inbox is configured. If neither destination exists, it creates the note at the top level. Link preview handling fetches bounded page metadata and stores usable preview images locally, so shared or later-viewed notes do not depend on a remote image URL. The sender uses an ETAPI token and a client-supplied local date to place text or validated images in the correct inbox note. OneNote uses a device sign-in flow, keeps provider tokens in the active web or desktop session, refreshes them during access, and then starts a long import that reports progress through the live client channel. Custom routes can also expose note-defined request handlers or static note resources through /custom/.... These external routes do not use CSRF protection; backend request handlers remain disabled when server scripting is off, while static resource providers remain available. The server rebuilds wildcard path segments before matching them so custom handlers receive the expected path shape.

The operating-system share target lets a signed-in user send text, a URL, or files from a device share sheet into the inbox. The server creates a text note for text or URLs, places one file directly in the inbox, and groups several files under one note. It redirects to the created note only after uploaded images are ready, so the opened note does not show broken image links. Share-target uploads use temporary disk files, accept at most 20 files, and enforce the single-blob content limit before note creation. The parser also accepts the boundary form produced by Samsung Internet without weakening the normal multipart checks.

The endpoint has a separate browser boundary because a share sheet does not send a CSRF token. It accepts browser-initiated share navigation but rejects form posts from another page. It rejects nested multipart fields, escapes shared text, and removes temporary upload files when the request closes.

References: apps/…/share_target.ts• L11-46 apps/…/share_target.ts• L48-103 apps/…/share_target.spec.ts• L46-176 apps/…/clipper.ts• L25-181 apps/…/clipper.ts• L189-259 apps/…/clipper.ts• L269-366 apps/…/clipper.spec.ts• L163-255 apps/…/clipper.spec.ts• L261-380 apps/…/sender.ts• L8-85 apps/…/sender.spec.ts• L17-99 apps/…/route_api.ts• L214-304 apps/…/routes.ts• L138-187

MCP interface

MCP is a separate tool interface for external agents. It exposes note-aware capabilities used by in-app intelligence, but it never trusts a session cookie, a loopback address, or a particular Host value. Each request must carry an ETAPI token in the supported Bearer or ETAPI Basic-auth form, and failed token checks are limited per source address. Valid-token requests remain available even when the source has exhausted its failed-auth budget. MCP can be disabled as a separate server option, and the HTTP transport closes its tool server and stream when request handling ends.

References: apps/…/auth.ts• L8-54 apps/…/notes.ts• L12-40 apps/…/mcp.ts• L19-27 apps/…/mcp.ts• L51-59 apps/…/mcp.ts• L99-148 apps/…/mcp.spec.ts• L40-135 apps/…/transport.spec.ts• L161-330

Response contracts

Application routes use one response path for ordinary results. It converts core entities to plain data, returns JSON or an explicit status, adds the newest entity-change position, and records request timing. HTTP errors preserve their declared status, including access and conflict errors, so clients can distinguish them from internal failures. Unknown routes become 404 responses, while invalid CSRF tokens become 403 responses. Server logs add useful detail from OAuth errors and nested network causes without exposing that diagnostic detail as the normal client response. ETAPI keeps its own error shape with a status, code, and message so automation clients can act on a stable failure contract.

Content routes return the note or attachment media type and can set a download name. Inline file reads support byte ranges for media and use content-based cache validators, while download reads keep the stored file as a download. Inline SVG is sanitized because the browser treats it as a document. Office previews return an HTML fragment for the client to place in its own view. The media proxy forwards browser range requests to a validated remote media source, then limits the response to a media body under a sandbox policy. It uses a short-lived, limited-use token so the remote address stays out of the client URL and access logs. Streaming routes are exceptions to the ordinary result path: chat sends Server-Sent Events until completion or client disconnect. It sends a comment heartbeat after 30 seconds without a model chunk and resets that timer when a chunk arrives, so idle proxies keep the live response open. A disconnect stops the heartbeat and aborts the provider turn. Backup downloads are sent as files rather than loaded into memory. Import uploads keep streamable ZIP archives on temporary disk through the import, while other imports are materialized for handlers that need a buffer and then cleaned up. Multipart field names do not accept nested fields. Metrics returns Prometheus text by default or a structured JSON snapshot when requested; unsupported formats are client errors.

Shared core route behavior is tested outside Express, while the server-level transport check verifies that core GET and mutating routes are wired end to end, enforce CSRF, accept multipart uploads, and preserve byte-range responses. Its fixture disables authentication, so it focuses on transport and middleware behavior rather than the authenticated boundary.

References: apps/…/route_api.ts• L31-69 apps/…/route_api.ts• L87-169 apps/…/route_api.ts• L171-206 apps/…/media_proxy.ts• L55-129 apps/…/media_proxy.spec.ts• L27-146 apps/…/llm_chat.ts• L10-93 apps/…/metrics.ts• L8-20 packages/…/files.ts• L15-154 packages/…/image.ts• L26-99 packages/…/backup.ts• L1-80 apps/…/etapi_utils.ts• L19-45 apps/…/error_handlers.ts• L26-63 apps/…/core_routes_http.spec.ts• L8-91

Request handling

Request handling establishes the trust, data, and execution context for a call before a route reaches a product service. Middleware order matters because the same HTTP listener serves static pages, the authenticated application, integrations, and public shares.

Middleware boundary

The server builds one Express application with security headers, optional CORS, body parsing, cookies, sessions, and route groups. Desktop network access can gate web traffic before it reaches the application. MCP is mounted before session middleware because it has its own token guard and must not inherit cookie-based access. CSRF protection uses a session-bound token from the x-csrf-token header or a URL-encoded form field, which lets browser form navigation carry the same protection as an API call. The check is skipped only for the internal desktop protocol and before database initialization, when no durable authenticated session exists.

The root application can return setup, password, or login state through its bootstrap response. Once the document and password state allow normal use, the browser receives a CSRF token and the client can call protected application routes. The response also selects the desktop, mobile, or print view from request-specific signals such as an explicit query, a device cookie, or the user agent. Static assets remain separate from the dynamic bootstrap response so the application shell and its security state have different cache behavior. Direct login navigation is redirected to the root shell with a login marker, so a bare-domain redirect to public sharing cannot capture the owner's login path.

The asset layer serves the client and share-theme resources according to the runtime mode. Development uses Vite middleware for the client, while packaged deployments serve built files from the resource directory. Shared theme assets, PDF viewer files, fonts, images, documentation notes, and stable version-independent asset aliases remain available beside the application shell. The root shell is not cached because a restored browser page can otherwise reuse an invalid CSRF token; built assets can use long-lived caching because their URLs identify a release. A packaged server fails early when its public client directory is missing.

Desktop builds can serve both the trusted Electron renderer and an ordinary browser from the same HTTP listener. The server marks the renderer per request through the internal desktop protocol. It does not treat every request to a desktop build as trusted, so a browser still receives the normal password and login screens. Renderer-only values such as loopback HTTP and WebSocket URLs stay out of ordinary browser bootstrap data. The same request marker keeps the renderer on the desktop view while allowing a browser's mobile or desktop choice to take effect.

References: apps/…/app.ts• L30-63 apps/…/app.ts• L84-133 apps/…/index.ts• L20-193 apps/…/index.ts• L196-234 apps/…/index.spec.ts• L99-134 apps/…/index.spec.ts• L286-325 apps/…/login.ts• L13-27 apps/…/assets.ts• L16-166 apps/…/csrf_protection.ts• L9-60 apps/…/transport.spec.ts• L26-114

Authentication boundaries

The server uses different credentials for different trust relationships. A browser proves identity through its Trilium session. An external client proves access with an ETAPI token. A setup request can use the setup authorization held by the wizard while a document is not ready. Public shares use optional HTTP Basic credentials defined by the shared notes. Custom request handlers add a separate server-side scripting gate. The trusted Electron renderer is identified by a per-request transport marker for bootstrap behavior; the fact that the server runs in a desktop build is not a credential.

CSRF protection applies to cookie-backed state changes because another site could otherwise reuse a logged-in browser. Token endpoints do not use the browser session as their credential. This separation prevents an external integration or a public page from gaining the authority of an interactive user session. On a desktop build, the first password can also be set only by the trusted renderer; a browser on the same listener cannot claim an unconfigured instance.

CallerCredentialProtected resource
Browser clienttrilium.sid session and CSRF tokenApplication API and page state
ETAPI clientAuthorization ETAPI tokenAutomation API
MCP clientETAPI token in Bearer or ETAPI Basic-auth formNote-aware agent tools
Setup wizardSetup authorization when an existing document is behind setupRestore and document replacement actions
Share visitorOptional HTTP Basic value from shareCredentialsA shared subtree or note

References: apps/…/auth.ts• L123-176 apps/…/auth.ts• L221-245 apps/…/session_parser.ts• L121-175 apps/…/csrf_protection.ts• L25-44 apps/…/custom.ts• L7-17 apps/…/scripting_guard.ts• L6-13 packages/…/custom.ts• L89-98 apps/…/mcp.ts• L62-121 apps/…/index.ts• L34-77 apps/…/login.ts• L29-55 apps/…/setup_restore.ts• L15-24 apps/…/routes.ts• L78-100

Login and session flow

The login routes establish the browser session that protects the application API. The browser loads the login screen from the application shell, while the shared protected-session routes check either the local password and optional TOTP factor or the configured OIDC provider. The server-only routes also support sync login with a time-limited HMAC and matching sync version, plus token creation for integrations after password and TOTP checks. A successful browser check creates a new session. The remember-me choice controls whether that session survives browser restarts.

Sessions use the document database as their store. A session without remember-me is renewed while it is used and expires after up to 24 hours of inactivity. A remembered session keeps its fixed expiry. Expired rows are cleaned on a regular interval. When the password verification value changes locally or through sync, all sessions are removed and attached clients are disconnected so an old cookie cannot remain active.

The server limits failed credential checks across the main login and integration login paths. Failed responses must remain errors so the limiter can count them, while successful responses do not consume the failure budget. Logout replaces the current session and uses the provider logout flow when OIDC is active. A failed browser logout returns to the application root instead of leaving a raw error page.

The login path remains reachable when the bare domain redirects visitors to a public share. Explicit login navigation and the bootstrap response keep the owner on the login screen rather than sending the request into the share tree. The login page itself is a root-shell redirect, including a separate relative target for a trailing slash, so direct navigation does not loop.

References: apps/…/login.ts• L16-88 apps/…/login.ts• L13-150 apps/…/session_parser.ts• L14-175 apps/…/routes.ts• L48-57 apps/…/index.ts• L91-148

Request context

Each application request runs with context that identifies the calling component, the client's local time, and the note root selected by the client. Route wrappers also define whether a core action runs in a transaction and turn returned values or errors into HTTP responses. The context remains available across asynchronous work and response-close callbacks. This gives note changes one consistent path to persistence, change tracking, and client updates. Routes that replace the database during setup restore stay outside transaction wrappers, while ordinary application changes keep their normal transaction boundary.

Uploads follow the same boundary. Small files are held for the handler, while ZIP imports use temporary storage so the request does not need to keep a complete archive in memory. Streamable ZIP imports keep the temporary file through the import and remove it when the response or connection ends. Other imports are materialized for handlers that need a buffer, then their temporary files are removed before handoff. Multipart nesting errors are returned as a client error instead of reaching a handler without its file. Share-target files use the same temporary directory and are removed when the response closes.

Desktop file editing uses a second temporary-file path. The server records each file that it creates, and an update accepts only a recorded path inside the server temporary directory. Reopening an entity reuses the latest temporary file only when its stored bytes and file name still match. If an editor has changed the temporary file or the entity has a new file name, the server creates a separate file and keeps the earlier file available for the pending update. In Electron mode, each opened file is watched so changes can be sent to connected clients before the editor writes the new note or attachment content.

The request lifecycle is therefore a short chain from transport checks to core work and then to a response or a logged failure.

This diagram shows how a request moves from transport checks through shared work to a response.

flowchart LR
    A[HTTP request] --> B[Network and security middleware]
    B --> C[Session or token check]
    C --> D[Request context and body handling]
    D --> E[Core route or integration handler]
    E --> F[Transaction and durable state]
    F --> G[JSON, media, event stream, or error]

References: apps/…/route_api.ts• L71-169 apps/…/route_api.ts• L171-409 apps/…/core_routes_http.spec.ts• L21-87 apps/…/route_api.spec.ts• L314-497 apps/…/files.ts• L31-155 apps/…/error_handlers.ts• L8-63

Public sharing

The share subsystem publishes selected notes without exposing the private application API. It presents a share root and its descendants as pages, serves the media needed by those pages, and applies the same visibility decision to direct reads, includes, maps, and search results.

Share tree

Sharing starts at the note marked as the share root. The server builds a read-oriented view of that subtree after the document is ready. A share alias can give a note a stable public path, while a share index can expose a searchable landing page. Changes to the document invalidate this view so later requests see the current shared state.

The public tree is narrower than the stored note graph. Hidden branches and notes marked shareHiddenFromTree do not appear in navigation or search. A note with shareCredentials remains addressable only after the visitor presents a matching credential. The share root itself is not published unless the share index is enabled.

References: apps/…/sql.ts• L11-76 apps/…/shaca_loader.ts• L13-105 packages/…/handlers.ts• L258-282 packages/…/handlers.ts• L532-616 packages/…/sattribute.ts• L46-56 packages/…/snote.ts• L494-502

Share page rendering

The page route resolves a public share ID or alias and renders the note through the share theme. The renderer converts supported note types into visitor-facing HTML or media links. It can show text, Markdown, code, diagrams, images, files, spreadsheets, web views, and child navigation without giving the visitor the private editing surface. Shared attachments are read from the share view with text and binary content kept distinct, so images can render while other files remain download links. Protected notes remain non-displayable as public content.

Shared content can include other notes. A live page expands the first include level and turns deeper links into references. Static export can expand deeper nesting while still stopping circular paths. The same note can appear through separate branches without being mistaken for a cycle. Each include uses the caller's share credential decision, so an included protected subtree cannot become a side door around the direct share rule. Missing or denied includes remain non-disclosing placeholders or references.

The renderer prepares the share theme, custom style and script relations, logos, favicons, link previews, and icon resources. Link previews use safe stored images, unsafe link values become inert, and YouTube content uses a click-to-play facade before loading the remote player. Supported app views also receive a small page payload so maps, collections, and related views can draw from the shared page without exposing protected notes or share passwords. Web views accept only HTTP(S) or site-rooted sources and run in a restricted frame. Code content is escaped, and syntax highlighting is limited to bounded input so large blocks do not slow page rendering. Custom EJS templates are an owner-controlled feature and are used only when backend scripting is enabled; otherwise the default theme remains the safe fallback.

References: apps/…/routes.ts• L201-244 packages/…/handlers.ts• L119-190 packages/…/content_renderer.ts• L120-186 packages/…/content_renderer.ts• L259-375 packages/…/content_renderer.ts• L567-765 packages/…/content_renderer.spec.ts• L20-251 packages/…/handlers.spec.ts• L57-139

Share content access

The share API supports public reads for note metadata and search results, raw note or PDF content, app-view data, and attachment or image bytes. Direct content routes reject protected notes even when their placeholder can appear in a shared tree. This keeps the public page useful without allowing a raw download to reveal protected data. Share route tests also verify that protected attachments and hidden or credential-protected notes do not leak through search.

Images and SVG content receive stricter handling because a browser can execute or embed them. SVG is sanitized and served with a restrictive content policy. Inline HTML and other active documents use a sandbox where the browser can support it, while PDF views remain usable without that sandbox. Web views accept only HTTP(S) sources or paths that resolve on the share site. Generated styles and code are escaped or bounded so stored values and very large blocks do not create browser exposure or block the server event loop. Download responses use no-cache rules because share credentials and note changes must not be confused by a shared browser cache. Notes labeled shareDisallowRobotIndexing also return a search-engine exclusion header.

The share handlers are transport-neutral. A route adapter supplies the request path, parameters, query, and headers, while the shared handler returns a status, headers, body, or redirect. The same access rules therefore apply to Express routes and other hosts without making one transport a weaker path.

References: apps/…/routes.ts• L22-54 apps/…/routes.ts• L128-188 apps/…/routes.ts• L272-457 packages/…/handlers.ts• L27-110 packages/…/handlers.ts• L304-377 packages/…/handlers.ts• L384-503 packages/…/handlers.ts• L532-701 packages/…/handlers.spec.ts• L93-176 packages/…/handlers.spec.ts• L385-650

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the session, CSRF, ETAPI token, setup authorization, MCP token, and share credential paths separate. A new route must use the trust model of its caller.
  • Keep route registration order aligned with path specificity. A broad note route must not capture a more specific history, metadata, or content route.
  • Keep apiResultHandler, ETAPI errors, streaming responses, direct media responses, and file-send responses aligned with their clients. A stream or file send must not be passed through ordinary JSON result handling.
  • Keep request context available across awaited work and response-close callbacks. Entity changes and cleanup rely on the request's component and note context.
  • Keep upload storage aligned with the size and lifetime of each import or integration. Streamable ZIP uploads must retain their temporary path through import and clean it on completion or disconnect. Non-streamable imports must receive a buffer after the temporary file is removed.
  • Keep the multipart nesting guard and share-target parser aligned with every upload entry point. A parser error must not forward a request to a handler without its file.
  • Keep desktop file handoff paths tied to the server-created temporary-file set and its temporary directory. Reuse a temporary file only when its content and file name match the current entity, and keep pending editor files available for upload. A file update must never accept an arbitrary client path.
  • Keep image upload completion aligned with the URL returned to the editor. The image bytes must be available before the editor receives an image source.
  • Keep file open, download, byte-range, office-preview, and replacement routes aligned with their media and revision contracts. Inline reads must remain safe for SVG and active documents, while downloads must preserve stored bytes.
  • Keep media-proxy token lifetime, use count, byte cap, range forwarding, URL validation, and media-type checks aligned. The proxy must not expose the remote URL or relay arbitrary remote content.
  • Keep shared core route registration aligned with the server wrappers. A shared route that replaces a transaction or auth wrapper can behave differently on server and other hosts.
  • Keep option read and write rules aligned with client settings. Secret options must remain write-only, read-only runtime flags must not become editable, and a failed batch update must not leave earlier option changes partially applied.
  • Keep search scope and result-detail contracts aligned with the client. Full search, quick search, hoisted subtrees, archived-note filtering, token details, regex highlights, saved-search result details, and public share search do not have interchangeable response rules.
  • Keep metrics format names and content types aligned with monitoring clients. The default Prometheus response and optional JSON snapshot must not silently change shape.
  • Keep OCR note and attachment access checks aligned with the OCR service. Protected content must fail before processing, and batch start, progress, and completion states must remain meaningful to the client.
  • Keep setup restore upload state, path resolution, passphrase handling, and progress polling aligned. A restore must not run inside a database transaction or accept a client path outside the backup directories.
  • Keep sender and clipper local-date, token, approved-label, inbox, image-readiness, file-MIME, and content-sanitization rules aligned with their extension and device clients. Clipped executable or web-page content must remain opaque file data, and only the supported page labels may cross the unauthenticated clipper boundary.
  • Keep custom request handlers behind the scripting gate, while custom resource providers continue to serve only static note content.
  • Keep failed credential responses at 400 or above so the shared login limiter can count password, TOTP, setup, ETAPI, and integration failures.
  • Keep password changes and sync password changes tied to session revocation and client disconnect. A changed password must invalidate old browser sessions.
  • Keep explicit login navigation and bootstrap handling ahead of bare-domain share redirects. Otherwise the owner can be sent to public content instead of the login screen.
  • Keep CSRF form-token support and its pre-database and internal-desktop exceptions aligned with the session state. A protected setup flow must not require a session that cannot yet persist.
  • Keep the per-request Electron renderer marker separate from the process-wide desktop build flag. A browser on the desktop listener must keep the normal password and login boundary.
  • Keep bootstrap view selection ordered across print, trusted renderer, query, cookie, and user-agent signals. A change can send mobile, print, or browser clients to the wrong shell.
  • Keep system-check results and network-address URLs aligned with the bootstrap payload. The browser must not receive an unfinished CPU result as final state, and sync setup must use the configured protocol and reachable host addresses.
  • Keep error normalization aligned with navigation type. Browser logout forms need a redirect on failure, while API callers need a status and body they can process.
  • Keep share-target fetch-site checks, multipart limits, note grouping, URL and text escaping, image-write completion, redirect paths, and temporary-file cleanup aligned with the device share-sheet contract.
  • Keep sync login timestamp and version checks aligned with the HMAC contract. Keep token login failures as error responses so credential limits can count them.
  • Keep development and packaged asset roots aligned with the asset URL aliases and cache rules. A path helper change must serve the client, share theme, and PDF viewer files from the matching build output.

Important failure modes

TriggerConsequenceGuard
A cookie-backed state-changing route omits CSRF validationAnother site may cause a logged-in browser to change the documentUse the application route wrapper or an explicit CSRF middleware path
CSRF is required before the database can persist a sessionSetup or initial-sync requests fail with 403 because each request has a new session identityAllow the documented pre-initialization path and keep the internal desktop exception request-scoped
A browser on a desktop build is treated as the trusted rendererAn ordinary browser can skip the password or login boundary and receive renderer-only stateCheck the per-request internal Electron marker instead of the process-wide build flag
A browser is allowed to set the first password on a desktop instanceA network caller can claim an unconfigured knowledge baseRequire the trusted desktop renderer for the desktop password setup path
An integration accepts a session cookie instead of its intended tokenA browser page can invoke an external tool with the user's session authorityRequire the endpoint's ETAPI token or integration credential
A credential failure returns a status below 400The rate limiter refunds the attempt and password guessing is not throttledReturn an error status for every failed credential factor
A password change does not revoke sessionsA stolen browser cookie remains valid after the password changesDelete all stored sessions and disconnect attached HTTP clients on the password change event
A route is registered before a more specific routeThe wrong handler answers a valid requestRegister specific paths before parameterized catch-all paths
A streaming or file-send response passes through normal result handlingThe server can write a second response or corrupt the streamMark the response handled and keep streaming and file-send routes outside ordinary result formatting
A chat stream has no heartbeat during a long provider pauseAn idle proxy can close the response before the next model chunk arrivesSend an SSE comment after 30 seconds of silence and reset the timer on each chunk
A client disconnect does not stop the chat streamThe provider turn and heartbeat can continue after the user leavesAbort the provider signal and stop the heartbeat on response close
A media proxy accepts an unvalidated URLThe server can be used to fetch a private or non-web addressValidate the URL before storing it and fetch it through the safe fetch service
A media proxy relays arbitrary content or an unlimited bodyA remote page can become active content or consume server and browser resourcesAccept only probed media, set nosniff and a sandbox policy, cap each response at 32 MiB, and limit token uses
A streamable ZIP import is buffered for the full requestMemory use grows with archive size and the request may failKeep ZIP uploads in temporary storage and let the importer read the path
A temporary import file is removed before a path-based importer finishesThe importer cannot read the archive or leaves a failed importKeep the file through the response or connection and remove it during cleanup
Nested multipart fields are forwarded to an upload handlerA malformed field can trigger parser risk or leave the handler without its fileReject nested field names and return a clear 400
A share-target multipart body is rejected before its boundary is normalizedSamsung Internet shares fail before note creationStrip only the known NUL byte before the declared boundary and keep normal parser errors fatal
An image upload returns before its bytes are storedThe editor saves a broken image URL and the page stays brokenWait for the image write before returning the image URL
Inline SVG or an active document is served without its browser safety ruleStored script or event handlers can run in the application's originSanitize SVG and apply a restrictive policy; sandbox other active inline documents where supported
The share read view is not readyVisitors receive incomplete data or an initialization errorReturn 503 until the share provider is ready
Search checks credentials but not tree visibilityHidden shared notes can be enumerated through searchApply per-note credential checks, protected-note checks, and visible-path checks
A protected note is allowed through a raw share routeIts content or attachment bytes become publicReject protected content before reading or sending bytes
SVG, unsafe web-view data, or generated raw style is served without its share safety ruleStored content can create script, frame, or browser security exposureSanitize or constrain the value before placing it in the public page
An included note skips the caller's access checkA public page reveals a note that a direct request would refusePass the share credential decision into include rendering
A hosted share view receives unfiltered rows or attributesA public page can expose protected notes or share passwordsBuild the payload from visible notes and omit shareCredentials before embedding it in the page
A shared attachment loses its MIME-aware content typeText can become unreadable or binary content can be decoded as textLoad attachment content according to its stored MIME type
A share-sheet form is accepted from another pageA same-site or cross-site page can post into the signed-in inbox without a CSRF tokenRequire the expected browser fetch metadata and reject same-site and cross-site submissions
The bare-domain share redirect catches /login or /bootstrapThe owner cannot reach the login screen when public sharing is enabledPreserve explicit login navigation and the logged-out bootstrap response
Express supplies wildcard path segments as an array but the server passes that shape to custom matchingA valid note-defined route can miss its pattern or receive incorrect path parametersRebuild the wildcard remainder before calling the shared custom-route matcher
The clipper stores a supplied script or web-page MIME as an executable noteCaptured content can run as active note contentStore executable and web-page MIME types as opaque application/octet-stream files
The unauthenticated clipper accepts arbitrary labels or raw embedded markupA capture can add executable behavior or unsupported note controlsKeep only approved page labels and sanitize captured content and label values
MCP trusts loopback or a logged-in browser sessionA local process or visited web page can invoke note-aware tools without the integration tokenRequire a valid ETAPI token for every MCP request and do not use Host as the trust check
MCP rate limiting runs before it knows whether authentication failedDisabled MCP or valid-token traffic can consume the guessing budget and lock out callersCharge only failed token checks and bypass the limiter for valid tokens

Key files

FileWhy to read it
apps/…/app.tsShows the middleware order and the boundary between static pages, sessions, MCP, APIs, and share routes.
apps/…/routes.tsMaps server-specific application, integration, resource, ETAPI, media-proxy, and share entry points.
apps/…/index.tsDefines the bootstrap payload, per-request desktop trust, and desktop, mobile, and print view selection.
apps/…/assets.tsShows how development and packaged builds serve the application, share theme, PDF viewer, and stable asset paths.
apps/…/route_api.tsDefines common application request, transaction, response, error, request-context, multipart, and upload behavior.
apps/…/route_api.spec.tsVerifies request context isolation, rejected handler responses, upload modes, temporary-file lifetime, share-target limits, and multipart field protection.
apps/…/core_routes_http.spec.tsVerifies the Express transport boundary for shared core routes, including CSRF, end-to-end wiring, multipart upload, and byte-range responses.
apps/…/login.tsDefines sync login and integration token creation.
apps/…/login.tsDefines local, TOTP, and OIDC login, logout, first-password setup, session persistence, and credential rate limits.
apps/…/system_info.tsDefines network URLs for sync setup and the cached CPU emulation check sent through bootstrap.
apps/…/metrics.tsDefines the monitoring response formats and validation for Prometheus and JSON output.
apps/…/ocr.tsDefines note, attachment, and batch OCR request contracts and protected-content checks.
apps/…/media_proxy.tsDefines the short-lived, bounded media relay used when browser video capture needs a same-origin source.
apps/…/setup_restore.tsDefines the setup restore upload, path selection, passphrase handoff, and progress boundary.
apps/…/files.tsBridges desktop file editing with tracked temporary files, reuse for unchanged content, file-name changes, Electron updates, and path validation.
packages/…/notes.tsDefines note reads, creation, editing, deletion, undelete, revisions, cloning-related note actions, and subtree operations.
packages/…/image.tsDefines image reads, SVG safety, image upload readiness, and image compression operations.
packages/…/files.tsDefines file open, download, range streaming, replacement, SVG handling, and office preview behavior.
packages/…/options.tsDefines the client settings contract, safe handling of write-only options, atomic batch updates, and user theme and font discovery.
apps/…/auth.tsExplains browser sessions, setup access, desktop trust, and ETAPI token checks.
apps/…/session_parser.tsShows how browser sessions persist, renew, expire, and are revoked in the document store.
apps/…/csrf_protection.tsDefines the CSRF boundary for cookie-backed requests.
apps/…/error_handlers.tsDefines status mapping, CSRF errors, navigation redirects, and diagnostic server logging.
apps/…/etapi_utils.tsDefines ETAPI authentication, validation, transactions, and error responses.
apps/…/notes.tsIllustrates the automation contract for note reads, writes, content, export, import, and revisions.
apps/…/mcp.tsDefines the public MCP trust model and streaming transport boundary.
apps/…/custom.tsReconstructs /custom/... paths and passes note-defined handlers or resource providers to the shared route logic.
packages/…/custom.tsDefines custom handler matching, static resource delivery, scripting checks, and unmatched-route behavior.
apps/…/clipper.tsShows how captured content, files, tabs, images, favicons, approved labels, and YouTube embeds become safe note content and attachments.
apps/…/clipper.spec.tsVerifies clipping destinations, append behavior, content and label sanitization, safe file MIME handling, tab previews, and image processing.
apps/…/sender.tsShows how token-authenticated device content becomes inbox notes and validated image notes.
apps/…/onenote_import.tsDefines device sign-in, session token refresh, notebook access, and long-running import start.
apps/…/share_target.tsDefines how device share-sheet content becomes inbox notes and when the redirect is safe to return.
apps/…/routes.tsAdapts public share requests to the shared route handlers and maps public pages, search, media, downloads, and access checks.
packages/…/handlers.tsDefines the transport-neutral share route contract, access checks, public reads, search filtering, and media replies.
packages/…/handlers.spec.tsShows the share contract for aliases, protected content, credentials, visibility, app views, maps, search, and safe media.
apps/…/shaca_loader.tsExplains how the configured share subtree becomes the read view used by public routes.