SPB Git

Repository Public

SECURITY.md 28.1 KB

# Security

This document states what the code protects, how, and where it stops. File references are relative to the project root. Line numbers are those of the code at the time of writing.

# 1. Threat model

# Assets

Asset Where it lives
The administrator's access to the studio passkey_credentials, sessions, recovery_codes, setup_tokens
Unpublished work (drafts, revisions, private uploads) sheets.doc, sheet_revisions, assets with is_public = false, STORAGE_ROOT
The integrity of what is published under the author's name sheet_publications, sheets.publication_id
The Anthropic API key and the money it can spend ANTHROPIC_API_KEY (environment only), generation_usage
APP_SECRET environment only; signs render tokens
The database credentials and the backup passphrase DATABASE_URL, BACKUP_PASSPHRASE_FILE
The private network the server sits on reachable from the web and worker processes
Readers' browsers they execute what the site serves

# Actors

Actor Capability assumed
Anonymous visitor Any HTTP request to the public origin
Malicious web page open in the administrator's browser Cross-site requests carrying the administrator's cookies
Author of a document, page or file handed to Claude as source material Text that tries to instruct the model
Operator of a URL cited as a source Controls the response, redirects and DNS of that host
The model itself Returns arbitrary text where a JSON document is expected
Holder of a preview link Reads one draft until the link expires or is revoked
Someone with shell access to the server Trusted: can read .env, the database and issue enrolment links

Out of scope: a compromised server or database, a compromised administrator device, denial of service by volume.

# Trust boundaries

  1. Internet → reverse proxy → web process. The web process trusts the proxy for the client address (X-Forwarded-For) and for TLS.
  2. Browser → /api/admin/*: crossed only with a passkey session and a CSRF token.
  3. Model output → database: crossed only through extractJson → normalizeModelDoc → parseSheet (or applyPatch).
  4. Upload → storage: crossed only through sniff, the SVG sanitiser and, if configured, ClamAV.
  5. Server → Internet for source material and reference checks: crossed only through safeFetch.
  6. Worker's browser → web process: crossed with an HMAC token naming one document.
  7. Draft → public: crossed only by publish().

# 2. Authentication: WebAuthn passkeys

Code: src/lib/auth.ts, src/lib/api/authroutes.ts, src/components/admin/passkey.ts, scripts/bootstrap.ts, scripts/setup-token.ts. Library: @simplewebauthn/server 14.1.0 and @simplewebauthn/browser.

There is no password anywhere and no sign-up route. One administrator row is created by scripts/bootstrap.ts from ADMIN_EMAIL / ADMIN_NAME.

Aspect Implementation
RP ID WEBAUTHN_RP_ID, default the host name of APP_URL (src/lib/env.ts). Changing it invalidates every enrolled passkey.
Expected origin new URL(APP_URL).origin, compared by the library on registration and on every assertion (expectedOrigin, expectedRPID).
RP name Sheet
Algorithms ES256 (−7), EdDSA (−8), RS256 (−257)
Attestation attestationType: "none". The authenticator model is not verified. aaguid is stored for information.
Discoverable credentials residentKey: "required". Sign-in sends no allowCredentials, so the options reveal nothing about the account.
User verification userVerification: "required" in the options and requireUserVerification: true at verification, for registration, sign-in and re-authentication.
Challenge generation By the library; stored in webauthn_challenges with kind, optional user_id, binding, 5-minute expiry. The client receives a challengeId, not a cookie-borne challenge.
Challenge binding Anonymous ceremonies: SHA-256 of a random sheet_preauth cookie (HttpOnly, SameSite=Strict, path /api/auth, 10 minutes). Authenticated ceremonies: SHA-256 of the session id. Compared with a constant-time function.
Single use consumeChallenge deletes the row with DELETE … RETURNING before anything is checked, so a challenge cannot be replayed even when verification fails.
Counters Stored per credential and updated after each assertion; the library refuses a counter that goes backwards. Synchronised passkeys report 0 forever, which is accepted.
Excluded credentials Registration options list the user's active credentials (excludeCredentials).
Stored material Credential id, public key, counter, transports, device type, backed-up flag, AAGUID, a name. Nothing biometric reaches the server.
Failure responses Sign-in failures all return 401 login_failed with the same message; the reason goes to the audit trail only.

# When a passkey can be enrolled

registrationOptions / verifyRegistration accept exactly three situations:

  1. A valid one-time setup token (first setup, or setup-token.ts).
  2. A session opened with a recovery code.
  3. A normal session whose passkey verification is recent (10 minutes).

A setup token is consumed inside the same transaction that stores the credential (UPDATE … WHERE used_at IS NULL RETURNING), so two concurrent enrolments cannot both succeed.

# Bootstrap

scripts/bootstrap.ts is idempotent and meant to run at every deployment. While the administrator has no passkey it issues a 24-hour, one-use token and writes APP_URL/admin/setup#<token> to SETUP_URL_FILE (file mode 0600, directory 0700). Without SETUP_URL_FILE it prints the link only to a terminal and otherwise fails rather than write it to a log. Once a passkey exists the script issues nothing. Only the SHA-256 of a token is stored. Issuing a token invalidates the previous unused ones.

The token travels in the URL fragment, which browsers do not send to servers. SetupForm reads it, removes it from the address bar (history.replaceState) and sends it in request bodies. /admin/setup sets referrer: no-referrer.

# 3. Sessions and cookies

Aspect Implementation
Storage sessions table. The cookie carries a 32-byte random token; the table stores its SHA-256.
Cookie sheet_session: HttpOnly, Secure when NODE_ENV=production, SameSite=Lax, Path=/, host-only (no Domain).
Lifetime 14 days from creation (SESSION_DAYS), and 7 days without use (last_seen_at, checked in src/lib/session-store.ts); 30 minutes for a recovery-code session.
Rotation createSession revokes the session of the cookie presented and issues a new token at every authentication.
Revocation Sign-out revokes the session; sessions are listed and revocable in the settings; a recovery enrolment revokes all of them. Lookups require revoked_at IS NULL AND expires_at > now() and an enabled user.
Recorded User agent (300 characters), client address, last_seen_at (refreshed at most once a minute).
Clean-up The worker deletes sessions expired or revoked for more than 30 days.

Other cookies: sheet_preauth (above) and sheet_locale (interface language, set by client script, not sensitive).

# 4. CSRF

assertSameOrigin refuses a request whose Origin header differs from the origin of APP_URL, or whose Sec-Fetch-Site is present and is neither same-origin nor none. A request with neither header passes this check (non-browser clients).

assertCsrf runs assertSameOrigin and then requires the X-CSRF-Token header to equal the session's token (24 random bytes, constant-time comparison). The token is delivered to studio pages by the server layout (src/app/admin/(studio)/layout.tsx) and by GET /api/auth/session, and attached by src/lib/client-api.ts.

  • /api/admin/*: requireAdmin applies assertCsrf to every method other than GET and HEAD.
  • /api/auth/*: anonymous ceremonies apply assertSameOrigin; routes that act on a session apply assertCsrf.
  • /api/public/views is the only anonymous POST; it refuses a request whose Origin header is not the site's own.

The session cookie is SameSite=Lax, so cross-site POSTs do not carry it in current browsers; the header check does not depend on that.

# 5. Re-authentication

requireRecentAuth demands a passkey verification within the last 10 minutes (sessions.reauth_at) for: adding a passkey from a normal session, revoking a passkey, regenerating recovery codes. The client helper withReauth runs the ceremony (/api/auth/reauth/options → /reauth/verify) and retries once. The re-auth challenge is bound to the session and restricted to the user's own credentials.

reauth_at is set when a passkey or setup session is created, so the ten minutes after sign-in count as recent.

Renaming a passkey and revoking a session do not require re-authentication. The last passkey cannot be revoked (409 last_passkey).

# 6. Recovery

Path What it does
Recovery code Ten codes of 64 random bits (xxxx-xxxx-xxxx-xxxx, hex) are shown once after an enrolment with a token or from a recovery session; only hashes are stored. POST /api/auth/recovery consumes one code atomically and opens a limited session (method = 'recovery_code', 30 minutes).
Limited session requireAdmin answers 403 passkey_required; the studio layout redirects to /admin/setup; passkey-management routes refuse it. Its only use is to enrol a passkey. That enrolment revokes every other passkey and every session, replaces the recovery codes, and opens a full session.
CLI, add tsx scripts/setup-token.ts issues a 30-minute setup token: the new passkey is added, existing ones are kept, recovery codes are replaced.
CLI, replace tsx scripts/setup-token.ts --recovery: enrolling with it revokes every other passkey and signs out every device.

setup-token.ts refuses to run without a terminal unless --force-print is given, and writes an audit event recovery.cli.

# 7. Lock-out and rate limits

Rate limits are fixed-window counters in rate_limits (src/lib/ratelimit.ts), shared by processes and persistent.

Key Limit Applied to
auth:<ip> 30 / 10 min setup info, register options/verify, login options/verify, reauth options/verify
recovery:<ip> 5 / 15 min recovery-code sign-in
pub:<ip> 600 / 10 min every /api/public GET
view:<ip> 120 / 10 min view counter
upload:<user> 120 / h uploads
export:<user> 120 / h export requests
jobs:<user> aiJobsPerHour (default 40) / h AI jobs (not source checks)

Progressive lock-out (assertNotLockedOut): failures recorded as login.failed in the audit trail for the same client address during the last hour — 5 → wait 1 minute since the last failure, 10 → 5 minutes, 20 → 1 hour. It applies to sign-in options, sign-in verification and recovery codes, and survives restarts because it is computed from the audit table.

The client address is the last value of X-Forwarded-For — the one appended by the reverse proxy; earlier values are whatever the client sent and are ignored — or the literal local when the header is absent (src/lib/http.ts). It is trustworthy as long as the web port is reachable only through the proxy (see residual risks).

# 8. Authorization model

Surface Who Reads Writes
/api/public/*, public pages, /rss.xml, /sitemap.xml anyone Published snapshots only, through sheets.publication_id with status = 'published' AND deleted_at IS NULL. Every query lives in the "public queries" section of src/server/sheets.ts. One counter increment per view.
/api/auth/* anyone for ceremonies; a full session for credential management Own passkeys, sessions, number of recovery codes left Credentials and sessions of the signed-in user
/api/admin/* a session with method passkey or setup Everything Everything in the studio
/media/<id> anyone Assets with is_public = true only; anything else is a 404 whether it exists or not —
/preview/<token> and /preview/<token>/asset/<id> holder of an unexpired, unrevoked token The working copy of one sheet, and only the images listed in that draft's assets —
/render/<token> and /render/<token>/asset/<id> holder of a valid HMAC token (5–10 minutes) One revision or publication, and only the images its document references —
/api/health anyone { ok } —

There are no roles: the single administrator can do everything. Studio pages redirect unauthenticated visitors (src/app/admin/(studio)/layout.tsx); the comment there is accurate — that is navigation, the API re-checks every request.

# 9. Draft isolation

  • Public code paths never read sheets.doc or sheet_revisions. Search text is sheet_publications.search_text, built at publication.
  • Uploaded files are private by default. publish() flags as public only the image assets listed in the published document (and the sharing image). unpublish() withdraws the flag from the sheet's reader PDFs and from the images of that publication that no other published sheet uses.
  • Preview links: 32 random bytes, stored hashed, 24 hours, revocable per sheet; the page is noindex, nocache, referrer: no-referrer; robots.txt disallows /preview/.
  • The editor page loads a draft only for a full session (not a recovery-code session) and returns 404 otherwise.
  • Imported JSON always arrives as a draft.
  • Nothing in the system calls publish() except the administrator's request and scripts/seed.ts --publish-examples.

# 10. Uploads

Code: src/server/assets.ts, src/server/sniff.ts, src/renderer/sanitize-svg.ts, src/server/storage.ts.

Control Implementation
Type Decided from the bytes: PNG, JPEG, WebP, GIF, PDF by signature; otherwise the content must be valid UTF-8 without NUL bytes and is classified as SVG, JSON, CSV/TSV or plain text. The declared MIME type is ignored; the file name only disambiguates text formats. Text that contains <script, <html, <body or <iframe in its first 4 000 characters is refused. Anything else: 415.
Size UPLOAD_MAX_MB (default 20). The request body is read under a hard cap before multipart parsing (readBody: bytes are counted while reading, whatever Content-Length claims), then the file size is checked again on the parsed file and in createAsset. JSON bodies go through the same reader (2 MB by default). Images above 12 000 px a side are refused. SVG above 400 kB is refused.
Quota Sum of bytes of live uploads (exports are not counted) plus the new file must stay under STORAGE_QUOTA_GB (default 5).
Rate 120 uploads per hour.
SVG Parsed with htmlparser2 in XML mode into a tree of whitelisted tags and attributes, then re-serialised; the original markup is not stored. Removed: every tag outside the list (so script, foreignObject, style, use, image, a, animation elements), on* attributes, any value containing javascript:, vbscript:, data:, expression(, @import, character references or CSS escapes, href other than a local #fragment, url() other than a local fragment, entity declarations. Limits: depth 24, 6 000 nodes, 400 children per node.
Antivirus With CLAMD_SOCKET set, the bytes are streamed to clamd (INSTREAM). Infected → 422 and an audit event; scanner unavailable → 503 and nothing is stored. Without it, files are stored with scan_status = 'unscanned' and the studio says so.
Storage Opaque keys ab/cd/<uuid> under STORAGE_ROOT, validated by a regular expression before any path is built; files 0600, directories 0700; write-then-rename. Nothing under STORAGE_ROOT is served statically.
File names Path separators and control characters replaced, 120 characters kept; used only in Content-Disposition, where everything outside [\w.@-] becomes _.
Serving /api/admin/assets/<id>/file (session), /media/<id> (public assets) and /preview/<token>/asset/<id> (preview holder) send the sniffed MIME type, X-Content-Type-Options: nosniff and Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox. In the studio, only raster images and PNG exports are sent inline; SVG, PDF and text are attachments.
Deletion Refused while a working copy, a sharing image or a current publication references the asset.

SVG illustrations inside documents (svg blocks) are stored as the sanitised tree, drawn with React elements, and every attribute is checked again at render time (safeSvgAttr, safeStyle in src/renderer/blocks/SvgTree.tsx). Uploaded SVG files used as images are displayed through <img>.

# 11. XSS posture

  1. Documents are data. A sheet is a JSON value validated by SheetSchema with .strict() objects at every level; there is no HTML, CSS or script field. Unknown keys are rejected, not ignored.
  2. Inline text. parseInline (src/renderer/inline.tsx) produces React nodes for bold, italic, code, math, links and citations. Everything else is a text node, escaped by React. Links pass safeHref: https: or mailto: only, no whitespace, quotes, angle brackets, backslashes or control characters; they render with target="_blank" rel="noopener noreferrer".
  3. KaTeX is the only producer of HTML that the renderer injects (src/renderer/math.tsx). Options: trust: false (no \href, \url, \includegraphics, \htmlClass…), maxExpand: 1000, throwOnError: false.
  4. Code blocks are tokenised to React spans by src/renderer/code-highlight.ts.
  5. Simulations take numbers, a seed and a small config; function-plot expressions are parsed by a recursive-descent parser (src/sim/core/expr.ts) with a fixed function list — no eval, no Function.
  6. JSON-LD is serialised by the server with < escaped.
  7. Other dangerouslySetInnerHTML: one static script in src/app/layout.tsx that applies the stored light/dark choice.

# Content-Security-Policy

Set by next.config.ts for every path except the routes that serve stored files (/media/…, /api/admin/assets/…, /render/<token>/asset/…), which answer with their own stricter, sandboxed policy (§10). In production the site policy is:

text
default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';
img-src 'self' data: blob:; media-src 'self' blob:; manifest-src 'self'; worker-src 'self';
font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self';
form-action 'self'; object-src 'none'

Outside production, script-src also contains 'unsafe-eval' (React's development build).

'unsafe-inline' is in script-src because Next.js emits inline bootstrap scripts on every page and the policy is static; removing it requires rendering every page with a per-request nonce, which the code does not do (comment at the top of next.config.ts). The layout's mode script and the JSON-LD blocks are inline as well. 'unsafe-inline' in style-src covers the inline styles of React components, KaTeX and the diagram and chart drawings.

What the policy does give: no third-party origin can be loaded or contacted (default-src 'self', connect-src 'self'), no framing (frame-ancestors 'none'), no plugin content, no <base> hijack, forms post only to the site. upgrade-insecure-requests is deliberately absent (it breaks WebKit on http://127.0.0.1 in tests).

# 12. Outbound requests (SSRF)

Every server-initiated fetch of a user- or model-supplied URL goes through safeFetch (src/ai/net.ts): links in a brief, DOI lookups, source URL checks.

  • https: only, default port only, no credentials in the URL.
  • The host must resolve to public addresses only, and this is enforced twice: assertPublicUrl checks every address before the request, and the connection itself (node:https with a custom lookup, publicLookup) hands only public addresses to the socket, so a host cannot pass the first check and then answer with a private address (DNS rebinding). Refused: 0/8, 10/8, 127/8, 100.64/10 (CGNAT, Tailscale), 169.254/16, 172.16/12, 192.168/16, 192.0/16, 198.18/15, ≥ 224; IPv6 ::, ::1, fc00::/7, fe80::/10, ff00::/8, IPv4-mapped and NAT64 forms.
  • Redirects are followed by hand, at most 5, each hop re-validated.
  • Timeout 15 s; body capped (1.5–3 MB depending on the caller); no cookie or credential is sent; a fixed User-Agent; Accept-Encoding: identity.
  • For links in a brief, only text/html and text/plain responses with status 200 are accepted.

The worker's export browser is restricted separately: every request whose origin is not the origin of INTERNAL_URL is aborted (src/worker/export.ts). The block id of an export request must match the id pattern (src/server/exports.ts).

# 13. Prompt injection and what the model can do

  • The model has no tools. A call is text in, text out; nothing the model writes is executed, fetched or sent anywhere.
  • Source material is wrapped in <source_material> tags, announced as data, and the system prompt says instructions inside it are not to be followed. A closing tag inside the material is neutralised (fence). Text attachments and fetched pages are scanned for phrases addressed to an AI (scanInjection); matches are reported to the administrator as warnings and change nothing else. PDFs and images are not scanned.
  • Whatever the model returns is parsed as JSON, normalised and validated. Regardless of its output the model cannot: publish; set the author, the schema version, the slug or the example flag; mark a source as checked; reference an upload it was not given; add cross-block interactions; change a locked block or a tab group that contains one; with a selection, change blocks outside it, insert anywhere but right after a selected block, or touch metadata, theme, claims or remove sources; change the language of a sheet; alter sources, numbers, LaTeX or structure in a translation. See AI_PIPELINE.md.
  • What it can do: write wrong content into a draft. The defences there are the quality report, the "unverified" status of every model-supplied reference, the claims list, and the administrator's review before publication.

# 14. Secrets

  • ANTHROPIC_API_KEY, APP_SECRET, DATABASE_URL and the backup passphrase exist only in the environment or in files outside the repository. .env is git-ignored; scripts/secrets-scan.ts fails on private keys, PostgreSQL URLs with a password, an APP_SECRET value or sk-… keys in tracked or about-to-be-tracked files.
  • settings holds non-secret values only. GET /api/admin/settings reports whether the key is set, never its value.
  • src/lib/log.ts truncates anything that looks like sk-ant-… in a log line. API errors return { code: "internal" } without detail; the JSON log line (api.unhandled) carries the error name and message, not the request body.
  • scripts/test.sh greps the client bundle and the logs for the test key and APP_SECRET.
  • APP_SECRET must be at least 32 characters (checked on first use).

# 15. Audit trail

audit_events records, with actor and client address where known: login.passkey, login.recovery_code, login.failed (with a reason), logout, reauth.ok, reauth.failed, passkey.enrolled.*, passkey.added, passkey.revoked, recovery_codes.regenerated, setup_token.issued.*, recovery.cli, session.revoked, settings.updated (keys only), sheet.created, sheet.settings, sheet.published, sheet.unpublished, sheet.reverted, sheet.deleted, asset.uploaded, asset.deleted, asset.rejected.infected, job.queued.<kind>, job.cancel, job.failed.

meta never holds cookies, tokens, codes, challenges, keys or document bodies (contract stated in src/lib/audit.ts). Ordinary saves are not audit events; they are revisions. The trail is readable in the studio (Revisions → audit tab) and through GET /api/admin/audit. Nothing prunes it.

# 16. Response headers

From next.config.ts, on every path: X-Content-Type-Options: nosniff, Referrer-Policy: strict-origin-when-cross-origin, X-Frame-Options: DENY, Permissions-Policy: camera=(), microphone=(), geolocation=(), Strict-Transport-Security: max-age=31536000; includeSubDomains; and the site CSP on every path except the stored-file routes, which set their own. X-Powered-By is off. API JSON responses send Cache-Control: no-store (public API responses send a short public cache instead). robots.txt disallows /admin, /api/, /preview/, /render/.

# 17. Known limits and residual risks

  1. CSP allows inline scripts. script-src 'unsafe-inline' means the policy would not stop an injected inline script. The protection against XSS is the schema-only document model and React escaping, not the CSP.
  2. A single administrator, no roles. Any full session can do everything, including changing budgets and deleting sheets. There is no second approver for publication.
  3. No attestation verification. attestationType: "none": any authenticator that performs user verification is accepted.
  4. A stolen session cookie works until the session ends: 14 days at most, 7 days without use, or until it is revoked. Re-authentication protects only passkey addition/removal and recovery codes.
  5. The client address is the last X-Forwarded-For value. That is correct behind one proxy that appends or sets the header. If the web port is reachable without the proxy (HOST defaults to 0.0.0.0), a direct client chooses its own address and rate limits, lock-out and audit addresses can be spoofed; with a second proxy in front, every client appears under the inner proxy's address. Bind the web process to loopback or a private interface.
  6. Lock-out is per address. It slows guessing from one address; it does not stop a distributed attempt. With passkeys there is nothing to guess; recovery codes are 64-bit.
  7. ClamAV is optional. Without CLAMD_SOCKET uploads are not scanned. PDFs are stored as uploaded and never rendered in the site's origin, but they are sent to the Anthropic API when attached to a brief.
  8. Request bodies are held in memory while they are read (up to the cap: UPLOAD_MAX_MB plus overhead for uploads, 2 MB for JSON). The cap is enforced by the application; a proxy limit is still worth having.
  9. Public flags are withdrawn on unpublish only. An image removed from a sheet that stays published, or a sharing image that is not part of the document, keeps its public flag and stays readable at /media/<id> by its UUID.
  10. /render/<token> is reachable with a valid token. It is not restricted to loopback; access depends on the short-lived HMAC token (5–10 minutes). A proxy rule can deny the path externally (see infra/).
  11. Preview links are bearer tokens. Anyone who obtains the link reads the draft and its images for up to 24 hours.
  12. The view counter is unauthenticated. A non-browser client can inflate it within the rate limit (the Origin check only stops other web pages).
  13. Backups. Archives are encrypted and carry an HMAC that restore.sh verifies, but they are written to a local directory (same disk unless BACKUP_DIR points elsewhere), pg_dump receives the database URL on its command line, and the HMAC step passes the passphrase to openssl dgst as a command-line argument — both visible in the process list while they run. See BACKUP_RESTORE.md.
  14. The audit trail is in the same database as everything else and is not tamper-evident.
  15. Asset deletion does not look at old revisions. A file no working copy or current publication uses can be deleted; reverting to an older revision that referenced it gives a missing image.
  16. Locks protect a block and the tab group around it, not the reverse: a locked tabs block does not make each of its children individually locked for a patch that addresses a child by id.
  17. No error-reporting or intrusion-detection service is integrated; detection relies on logs and the audit page.
  18. Model-written content can be wrong. The quality report is mechanical. A "resolved" source means a record with that title exists, not that the sheet represents it faithfully.
  19. One worker process is assumed. Nothing prevents starting a second one, which would re-queue the first one's running jobs.
Files main
Menu

Theme