Skip to content

Latest commit

 

History

History
1575 lines (1091 loc) · 169 KB

API.md

File metadata and controls

1575 lines (1091 loc) · 169 KB

docs.plus Backend API

Base URL (dev): http://localhost:4000 Package: @docs.plus/hocuspocus

The REST API runs from src/index.ts on a Hono app. This document covers the HTTP surface only. For the three-process architecture and environment variables, see Readme.md and ENV.md. For the WebSocket protocol, see WebSocket API.

Machine-readable spec. The same surface is published as OpenAPI 3.1 at GET /openapi.json, with Swagger UI at GET /docs (src/modules/openapi/). Request schemas are generated from the live zod schemas, so they cannot drift from validation. Traefik routes only /api, /health and the MCP resource metadata prefix, so both paths are reachable in local and internal environments but not on the public edge. Publishing them is a routing decision, not a code change.

Contents

  1. Authentication
  2. Response envelope
  3. Health
  4. Documents
  5. Document content
  6. Document versions
  7. Document changes
  8. Document conversion
  9. MCP connector
  10. Media
  11. Link metadata
  12. Email
  13. Admin
  14. Push notifications
  15. Rate limiting
  16. WebSocket API

Authentication

Three schemes apply, by route group:

Scheme Used by Header
None /, /health/*, /openapi.json, /docs, GET /api/plugins/hypermultimedia/:documentId/:mediaId, DELETE /api/plugins/hypermultimedia/session, GET /api/documents/:documentId/card.png, /api/metadata, GET /api/metadata/icon, GET /api/metadata/image, GET /api/metadata/archive, GET/POST /api/email/unsubscribe, GET /api/email/health, GET /api/email/status, POST /api/email/validate —
Optional Supabase user JWT GET /api/documents (list without ownerId), GET /api/documents/:slug, GET /api/documents/:docName/hovercard, PUT /api/documents/:docId Authorization: Bearer <jwt> or token: <jwt>
Required Supabase user JWT GET /api/documents?ownerId=… / ?deleted=true, POST /api/documents, document lifecycle (DELETE /:id, /:id/restore, /:id/duplicate, /:id/favorite, /:id/opened, /:id/permanent, POST /trash/purge, /trash/restore), GET /api/connected-apps/redirects, POST /api/plugins/hypermultimedia/session (the Private media cookie), POST /api/plugins/hypermultimedia/:documentId (media upload; the service-role key is refused there — it is not a user token, so requireUser can resolve nobody from it) Authorization: Bearer <jwt> or token: <jwt>
Either of the two above GET /api/documents/:documentId/export, POST /api/documents/:documentId/import — the key passes every document, a user token is checked against the document's privacy and lock Authorization: Bearer <jwt>, token: <jwt>, or the service-role bearer
Supabase service-role key /api/email/send-generic, /bounce, /preview/:type, GET/PATCH /api/documents/:documentId/content, every /api/documents/:documentId/versions route, GET /api/documents/:documentId/changes, and the content / ownerId fields on POST /api/documents Authorization: Bearer <SUPABASE_SERVICE_ROLE_KEY>
Resend webhook signature POST /api/email/webhooks/resend — mounted only when RESEND_WEBHOOK_SECRET is valid svix-id, svix-timestamp, svix-signature
Supabase user JWT + admin_users row /api/admin/* Authorization: Bearer <jwt>
Supabase OAuth token with client_id /api/mcp — see MCP connector; admin routes refuse these tokens Authorization: Bearer <jwt>

GET /api/documents/:slug auth (shipped — owner-scoped private): optionalPadReader attaches the caller. Public docs return full metadata to anyone; private docs are owner-only — anonymous or ownerless-private → 403 { access: 'sign-in-required' }, signed-in non-owner → 403 { access: 'denied' }. See the slug access matrix below.

Service-role checks use a constant-time compare (verifyServiceRole in src/lib/auth.ts). When SUPABASE_SERVICE_ROLE_KEY is unset they fail closed in every environment, non-production included. Admin routes verify the JWT with Supabase, then require a matching row in admin_users (src/api/middleware/adminAuth.ts); failures return 401 (no/invalid token) or 403 (not an admin).

List owner filter (shipped): When ownerId is present on GET /api/documents, the caller must send a valid user token, in the token header or as Authorization: Bearer <jwt>. ownerId must equal the JWT subject (sub). Missing token → 401; mismatched ownerId → 403.

Unauthenticated fleet list: GET /api/documents without ownerId returns public rows only. isPrivate: true rows are clamped out for any unverified caller or owner-less list (both the page query and its total count). This closes anonymous ?title= enumeration of private titles/descriptions. Owner-scoped calls (ownerId === token.sub) are unaffected and still see the owner's private docs. The webapp Settings → Documents UI always sends ownerId + token and never uses the fleet path.

Response envelope

The canonical error shape is defined by getErrorResponse in src/lib/errors.ts:

{
  "success": false,
  "error": { "message": "Human-readable message", "code": "ERROR_CODE" }
}

A request-validation 400 (VALIDATION_ERROR) also carries error.fields: one { path, message } per rejected input, so a caller can fix it without guessing.

Outside development, getErrorResponse returns Internal server error as the error.message of every 5xx. The code is unchanged, and the server logs the original message. A handler that calls fail() keeps its own fixed 5xx message, which never carries driver text. An admin handler that answers { error } also sends a fixed 500 message and logs the original error (#413).

error.details is included only when NODE_ENV=development. AppError subclasses map to status codes and codes: VALIDATION_ERROR (400), BAD_REQUEST (400), UNAUTHORIZED (401), FORBIDDEN (403), NOT_FOUND (404), CONFLICT (409), PAYLOAD_TOO_LARGE (413), UNSUPPORTED_MEDIA_TYPE (415), UNPROCESSABLE_ENTITY (422), RATE_LIMIT_EXCEEDED (429), INTERNAL_SERVER_ERROR (500), SERVICE_UNAVAILABLE (503), DATABASE_ERROR. handlePrismaError maps Prisma codes (P2002 → conflict, P2025 → not found, etc.) into the same set. AUTH_UNAVAILABLE (503) sits outside this set: the auth middleware returns it, not an AppError, when Supabase token verification is unreachable.

The documents controller emits this envelope on error and { "success": true, "data": ... } on success.

Known inconsistency — not yet wired globally. Several handlers return ad-hoc shapes instead of the canonical envelope. Wiring getErrorResponse everywhere is a separate task. Until then expect these variants:

  • { "error": "..." } — email handlers, admin middleware, the upload no-file 400 and media file reads.
  • { "success": false, "code": "...", "message": "..." } (note code/message at top level, not nested) — /api/metadata; its code is INVALID_URL or BLOCKED_URL.
  • Email send-* and bounce success bodies are { "success": true, ... } with their own fields, not the data wrapper.

Health

Health routes are exempt from rate limiting. Each dependency route returns 200 when healthy and 503 otherwise. /health/live always answers 200. Source: src/api/routers/health.router.ts, src/api/services/health.service.ts. Each dependency check is cached for 5 s per process, and concurrent callers share one check. A failed check returns no error text. The reason goes to the server log as a Health check failed warning. The rest-api container healthcheck reads /health/database, so a Redis stall does not mark the replicas unhealthy (#405).

GET /health

Aggregate check across database, Redis, and Supabase. Returns degraded (503) only when a critical service (database, or Redis when enabled) is unhealthy; Supabase may be down without failing the overall check.

{
  "status": "ok",
  "timestamp": "2026-06-15T12:00:00.000Z",
  "services": {
    "database": { "status": "healthy", "lastCheck": "..." },
    "redis": { "status": "healthy", "lastCheck": "...", "metadata": {} },
    "supabase": { "status": "healthy", "lastCheck": "..." }
  }
}

Per-service status is one of healthy, unhealthy, or disabled (Redis/Supabase when not configured).

GET /health/live

Liveness only. Answers 200 while the process is up. It calls no dependency, so it never answers 503. The Traefik probe reads it. Use it for a load-balancer check.

GET /health/database

Database connectivity (SELECT 1).

GET /health/redis

Redis PING. disabled when Redis is not configured.

GET /health/supabase

Supabase reachability. disabled when SUPABASE_URL/SUPABASE_ANON_KEY are unset.

Documents

Base path /api/documents (src/api/routers/documents.router.ts). Success responses use { "success": true, "data": ... }.

GET /api/documents

List or search documents. With any of title/keywords/description, runs a full-text search; otherwise lists all rows. Owner profiles (snake_case, mirroring public.users) are joined in.

Param Type Default Description
title string — Search term (tokenized)
keywords string — Search term (tokenized)
description string — Search term (tokenized)
ownerId uuid — Filter by owner — requires a user token; must match JWT sub
scope string — all, owned or joined — requires a user token. See List scope below
sort string updatedAt_desc Allowlisted: updatedAt_desc, createdAt_desc, lastOpenedAt_desc, title_asc, title_desc
limit string 10 Page size (1–100)
offset string 0 Pagination offset (≥ 0)

Auth: optionalUser on the route. When ownerId is set, missing or invalid token → 401; ownerId !== token.sub → 403. Without ownerId, no auth is required (fleet list — legacy).

List rows include readOnly, isPrivate, createdAt, updatedAt, and isOwner (ownerId === token.sub). Owner live list and Owner Trash list include preview and lastOpenedAt. Owner live list also includes isFavorite. Owner Trash list omits isFavorite. Create, slug GET, update, and the public fleet omit preview and lastOpenedAt.

Sort: Optional sort query param. Allowed values: updatedAt_desc (default), createdAt_desc, lastOpenedAt_desc, title_asc, title_desc. The server maps each key to a fixed, allowlisted Prisma orderBy (an unknown value falls back to updatedAt_desc). Required for the Settings → My Documents sort dropdown — client-side sort breaks paginated Load more. An owner live list pins that user's Favorites first, then applies sort inside each group. Trash and the fleet do not pin.

Private clamp: Without a verified requester (ownerId === token.sub), private rows are excluded from both the results and total — see Unauthenticated fleet list above.

List scope: Settings → Documents sends scope. Without it, the list keeps the legacy behaviour: ownerId gives the owner list, and no ownerId gives the public fleet.

scope Rows
owned The caller's live documents. Same as ownerId=<sub>.
all owned, plus every joined row. One merged list.
joined Rows in the caller's active workspace_members set that the caller does not own. Ownerless rows count.
  • A joined row is always public and live. A private or deleted document the caller does not own is never listed, in the page or in total. Trash stays owner-only.
  • The joined set is read on the server from token.sub through the service role, by exact-case workspace_id = documentId. The client never sends ids.
  • Search composes with the scope. A search lists only matching rows inside it.
  • Every scoped row carries isOwner and preview. A non-owned row also carries owner when it has one. It never carries lastOpenedAt or isFavorite.
  • Under all, only the caller's own Favorites pin first. Under lastOpenedAt_desc, a row the caller does not own sorts as never opened.
  • No token → 401. scope with deleted=true → 400. ownerId that is not token.sub → 403. The membership read fails → 503 SERVICE_UNAVAILABLE, never an empty list.

Semantic note: updatedAt on DocumentMetadata reflects metadata changes (title, flags, keywords), not every collaborative body save. The UI label “Last modified” matches Google Docs parity.

{
  "success": true,
  "data": {
    "docs": [/* ... */],
    "total": 100
  }
}

GET /api/documents/:docName

Fetch one document by slug. When no row matches, returns a synthesized draft (createDraftDocument) rather than 404. A soft-deleted row is the one 404 case. Synthesizing a draft there would mint a new documentId under a still-unique slug, and the two would collide on persist.

Param Type Description
userId string (query) Optional; accepted for access context
card string (query) 1 asks for the social card; see below

Auth (shipped — owner-scoped private): optionalPadReader attaches the caller (owner identity is token.sub, never the userId query param), and the controller applies:

Document Viewer Result
Soft-deleted anyone 404 — never the draft path
Public anyone 200 — full metadata
Private token sent, Supabase auth unreachable 503 — AUTH_UNAVAILABLE, checked before the rows below
Private no token or anonymous JWT 403 — { access: 'sign-in-required' }
Private signed-in non-owner 403 — { access: 'denied' }
Private owner (sub === ownerId) 200 — full metadata
Private, ownerId: null any signed-in user 403 — { access: 'sign-in-required' } (sign-in wall until owner backfill)

The 403 body is { success: false, error: { code: 'FORBIDDEN', message }, access }; the top-level access hint drives the webapp private gate's CTA. Draft slugs (no DB row) are unchanged — synthesized draft, never treated as private.

Deadlines (#596). optionalPadReader is optionalUser with a 2 s deadline on the Supabase Auth read of a GET. A HEAD keeps the shared bound. A late Auth read counts as unreachable, so a Private pad answers the 503 row above. The owner-profile read has its own 2 s deadline. A late one returns the pad with a null owner profile.

Social card. Next sends card=1 on a full page load, never on a client-side x-nextjs-data read. With card=1, and when a kind in SOCIAL_CARD_KINDS can draw the pad, the reply carries card: { query, title, description, alt, path }. title is the og:title, and description is the og:description sentence. Either is null when the page keeps its own value. The page head points og:image at card.png with query. The pad link's own sub-ids (id, chatroom as c, msg_id as m, filter terms as t, mode, version) pass through the same way. Without card=1, the reply has no card field and the server makes no card read. The stored card data never leaves REST.

GET /api/documents/:docName/hovercard

Answers the docs.plus link card for one pad, by slug. It never synthesizes a draft. Auth is optionalPadReader, like the slug read. Every reply sends Cache-Control: private, no-store, because the answer depends on the reader.

Query Meaning
id A heading toc-id.
chatroom A heading toc-id or a channel id.
msg_id A message uuid. Read only with chatroom.
terms One filter term per key, as in the pad URL path. At most 8, 60 characters each.
mode and or or. A missing value is or, as in the app.
version An integer of 1 or more.
history 1.

Every key is optional, and a key with a bad shape is ignored. The kind order is the app's: version, history, filter, message, chat, heading, then pad.

Document Viewer Result
Unknown or soft-deleted anyone 404 — NOT_FOUND
Private not the owner, signed out, or Auth unreachable 200 — { success: true, data: { locked: true } }
Private (owner), or public anyone allowed 200 — one of the kinds below
  • { kind: 'pad', title, sections, total }: sections holds the first two section titles from the stored card data.
  • { kind: 'heading', padTitle, title, trail, subsections, lines, messages? }
  • { kind: 'chat', padTitle, heading, trail, messages, lastMessageAt? }
  • { kind: 'message', padTitle, heading, trail, sentAt, replies, reactions }
  • { kind: 'filter', padTitle, terms, mode, shown, shownCount, total }
  • { kind: 'version', padTitle, version, name?, savedAt, sectionsChanged?, wordsAdded?, wordsRemoved? }
  • { kind: 'history', padTitle, versions, lastSavedAt? }

trail lists parent heading titles, outermost first, without the Title or the heading itself. lines holds up to 2 first lines of the section body. Chat facts are counts and dates only, never text or authors. A message count includes notices, like the count the app shows for a room. The filter follows the app's filter: the shown set adds the ancestors and descendants of each match, and total leaves out the Title. Dates are ISO strings.

The pad card answers instead for an unknown heading, room, message or version, a failed chat read on the chat or message kind, and a filter on a head over 1 MiB. A failed chat read on a heading leaves messages out. A database error answers 500, and an empty name answers 400.

GET /api/documents/:documentId/card.png

The social preview card: a 1200 × 630 PNG drawn from stored values only, never from URL text. Each kind ships off; SOCIAL_CARD_KINDS turns kinds on. The kinds are document, heading, chat, message, version and filter. The full contract is in the OpenAPI spec (getSocialCardImage).

Status Cache-Control When
200 public, max-age=3600 The card. ETag is the server's own cardVersion. X-Robots-Tag: noindex.
304 public, max-age=3600 If-None-Match equals the current ETag.
302 public, max-age=300 To the Fallback card: the kind is off, the render queue is full, a chat read failed for now, or the render threw. Never a 5xx.
404 public, max-age=60 Private, deleted, ownerless, missing, or a bad id shape. One body and header set for all of them.

The v query parameter is a cache key for crawlers only. The server never reads it, so never cache this route as immutable. The route has its own rate limit; see Rate limiting. social_card_requests_total{outcome} counts every answer, and the "Social preview card" row on the App Performance dashboard shows it.

POST /api/documents

Create a document.

{ "title": "My Document", "slug": "my-document", "description": "", "keywords": [] }

title and slug are required; description defaults to "", keywords to []. The stored title is plain text. The schema strips HTML tags. The slug is normalized via slugify; a 19-char documentId is generated.

Two further fields are accepted only under the service-role key: content (a Tiptap JSON document, seeded as version 1) and ownerId (a bare Supabase uid). A user JWT presenting either gets 403 FORBIDDEN and nothing is written. See Create with content. Without them, behavior is unchanged for user-JWT callers.

PUT /api/documents/:docId

Upsert document metadata by documentId. All fields optional: title, description, keywords (string[]), readOnly (boolean), isPrivate (boolean), slug (string). A stored title is plain text. The schema strips HTML tags. slug sets the row's slug only when this call creates the row. It is ignored on every update and never renames a live document.

A docId outside [A-Za-z0-9_-], 1 to 100 characters, answers 400 VALIDATION_ERROR with the house envelope.

Access follows ownership. An owned document accepts writes only from its owner; every other caller gets 403, private or not. An ownerless document is open: anyone, signed in or not, may set title / description / keywords. But its locks cannot move, because a document with no owner has nobody to be private for. Those changes are ignored and logged. Creating the row through this route makes a signed-in caller its owner, so they may set the locks in the same request. A soft-deleted document is 404.

A signed-in rename that changes Pad title posts a workspace-chat notice after the write. The PUT does not wait for that call. A missing RPC, a signed-out rename, a create, an unchanged title, or an empty title posts nothing. The Prisma write still succeeds.

When the owner sends isPrivate, the PUT also writes the stored flag and owner to the Supabase document_access table, which gates chat. It writes even when the flag did not change, so a retry repairs a failed write. That write is awaited, and a failed write answers 503 SERVICE_UNAVAILABLE. When the request turns Private on, the table write runs before the Prisma write, so a 503 leaves the document public. If the Prisma write then fails, the route answers an error, and the chat stays closed on a public document. For any other request, the table write runs after the Prisma write, so a failed Private-off write leaves the chat closed. In both cases the owner should send the same request again.

DELETE /api/documents/:documentId

Soft-delete (owner-only, requireUser). Stamps deletedAt; the row survives for restore and is reaped after DOC_DELETE_RETENTION_DAYS (default 30). Idempotent — a missing row returns success. Non-owner → 403.

POST /api/documents/:documentId/restore

Clear deletedAt (owner-only). Idempotent; non-owner → 403. A Private document first writes its chat access row. A failed write → 503, and the document stays in Trash.

POST /api/documents/:documentId/duplicate

Copy the source's latest Yjs bytes into a fresh owner-owned doc (owner-only). Slug is <title> (copy), uniquified. Media is cloned, not shared: the source's objects are copied under the copy's own storage prefix, and the snapshot's URLs are repointed there. Each document therefore owns its media, and purging one never strips the other. The copy runs inside the request, so a source naming more than 32 media objects outside soft-deleted documents is refused up front → 413. Non-owner → 403; soft-deleted source → 404. Media whose prefix document is soft-deleted is not copied. That URL becomes a missing image in the copy, the same as for a purged source.

PUT /api/documents/:documentId/favorite

Owner-only (requireUser). Body { favorite: boolean }. Writes a DocumentFavorite join for token.sub (userId + documentId). true upserts; false deletes. Soft-deleted → 404. Non-owner → 403. Soft-delete of the document keeps the join, so restore stays favorited. Purge cascade-drops the row with the metadata.

Response { documentId, isFavorite }.

POST /api/documents/:documentId/opened

Owner-only (requireUser). Sets lastOpenedAt with raw SQL so @updatedAt does not move. Soft-deleted → 404. Repeats inside 30 seconds are a no-op success.

DELETE /api/documents/:documentId/permanent

Purge a soft-deleted doc's full footprint (owner-only) — chat and views via the purge_document_footprint Supabase RPC, editor media via a storage-prefix delete, then the metadata row. DocumentFavorite rows cascade-drop with that metadata delete. Refuses a live doc → 400. Idempotent (already-gone → success). Shares the reaper's purge path.

GET /api/documents?deleted=true

The caller's own soft-deleted docs (Trash), newest-tombstone-first. requireUser; owner-scoped to token.sub (never a client ownerId). Same page shape as the list, but no isFavorite and no favorites-first ordering. Owner Trash list includes preview and lastOpenedAt. A SQL-NULL preview is filled the same way as the Owner live list.

POST /api/documents/trash/purge

Bulk permanent-delete (owner-only). Body { ids?: string[] } — omit ids to empty the whole trash, or pass a selection (capped at 500). Returns { purged: <count> }. Runs the per-doc purge sequentially; synchronous, so a very large trash can exceed the request timeout (small in practice — the reaper bounds growth).

POST /api/documents/trash/restore

Bulk restore (owner-only). Body { ids: string[] } (1–500). Returns { restored: <count> }. Non-owned ids are skipped. A failed chat access write for a Private id → 503. The ids before it stay restored, and a retry is safe.

Document content

Read and write a document's body from a server-side integration. Writes reach live collaborators in real time. The REST process forwards them to the collaboration process, which applies them to the in-memory Y.Doc through the same pipeline a browser edit uses. Module: src/modules/document-content/.

All three surfaces are service-role only (Authorization: Bearer <SUPABASE_SERVICE_ROLE_KEY>). A user JWT gets 401.

Identifying a document

Content routes address documents by documentId — the 19-character id that is also the collaboration room name and the snapshot key. Never by slug. The slug read never 404s: it synthesizes a draft whose documentId has no saved document yet. So a content call to that id answers 404.

Resolve a slug once with GET /api/documents/:docName and keep the documentId from the response. A synthesized draft carries no id or createdAt — that absence is how you detect a mistyped slug.

Private documents are not discoverable this way. The slug read enforces the owner-only private gate and does not honor the service-role key, and GET /api/documents?ownerId= needs that owner's JWT. Capture documentId from the create response. For a pre-existing private document it has to come out of band (the owner's own slug read, or an operator reading DocumentMetadata).

Content contract

  • Documents are title-first. The first node must be a level-1 heading. A heading-less replace or create payload is rejected with 422. The editor would otherwise synthesize a title on first open and persist a heading you never wrote.
  • Image nodes are inline. Wrap them in a paragraph or heading. A top-level image is 422.
  • The root content array is flat. A heading holds inline text only and never nests the blocks that follow it.
  • A section is a caller-side rule. A heading's section is the run of following root siblings, up to the next heading whose level is the same or smaller. Nested subsections fall inside it. Compute it from a GET; the server has no section concept.
  • Headings and tables carry a toc-id. The server assigns one where it is missing or duplicated within the payload. That id is the identity a heading's chat thread, fold state, and ?id= deep link hang off. Round-trip the toc-ids from GET through a replace to keep them stable. A toc-id equal to the documentId is replaced too, because the pad-wide chat room uses that id. A paragraph carries no toc-id, so it is not addressable.
  • On append, a duplicate toc-id is permanent. The de-duplication covers one payload: the server never reads the live document's ids. So an id you send that a heading already owns is kept as sent. Both headings then share one chat thread, one fold and one ?id= anchor. The first occurrence in document order owns the address, and the second is unaddressable. Omit toc-id and let the server mint one, or GET first and avoid ids already in use. replace cannot collide this way, because it clears the fragment before it writes.
  • Unregistered attributes are dropped at encode. ProseMirror keeps only attributes the server's extension set declares; anything else is discarded silently. GET returns what was stored, not what was sent.
  • The first editable browser open may normalize the document, so a GET after someone opens it can differ from what you wrote.

GET /api/documents/:documentId/content

Reads the persisted head snapshot. Query: format = json (default) or text.

{
  "success": true,
  "data": {
    "documentId": "kR4pZ2mQ7tY1nB8xW3v",
    "version": 12,
    "format": "json",
    "content": {
      "type": "doc",
      "content": [
        {
          "type": "heading",
          "attrs": { "level": 1, "toc-id": "a1B2c3D4e5F6g7H8" },
          "content": [{ "type": "text", "text": "Quarterly report" }]
        }
      ]
    }
  }
}

format=text returns block text, one line per textblock:

{
  "success": true,
  "data": {
    "documentId": "kR4pZ2mQ7tY1nB8xW3v",
    "version": 12,
    "format": "text",
    "content": "Quarterly report\nRevenue grew 12%."
  }
}

A document with metadata but no snapshot row yet returns version: 0 with { "type": "doc", "content": [] } (or "" for text) — not an error.

Staleness. This is the persisted head, so it can trail a document people are actively editing by the store debounce — 10 s idle, 60 s maximum. There is no live read.

Trust boundary. Content is stored and returned verbatim; the server never sanitizes it. docs.plus renders it safely through its extension render gates plus CSP. But a consumer rendering this JSON with its own renderer must apply its own URL-scheme allowlist.

PATCH /api/documents/:documentId/content

Applies content to the document. Query: mode = replace (default) or append.

{
  "content": {
    "type": "doc",
    "content": [
      { "type": "paragraph", "content": [{ "type": "text", "text": "Appended by automation." }] }
    ]
  }
}
Field Type Description
content Tiptap doc JSON Required. { "type": "doc", "content": [...] } with at least one node
commitMessage string Optional, trimmed, 1–200 characters. Names the version row this write mints

replace swaps the whole body; append adds the payload's top-level nodes after the existing ones. Appending into an empty document makes the payload the document's first node, so the title-first rule applies there too.

A 200 returns { "documentId", "mode", "version"? }. version is the saved version row that holds this write. It is present when the call waited for that row (see Durability contract).

Naming a write is permanent history. A commitMessage becomes the version row's name, and autosave retention never thins a named row — see Document versions. Name the writes a person would want to find again, and leave a bulk import's chunks unnamed. A named 500-chunk run leaves 500 rows nothing will ever prune.

Live and cold documents take the same path. If collaborators have the document open, they see the change immediately without reconnecting. If nobody has it open, it loads, applies, persists, and unloads.

Clearing a document is replace with a single empty level-1 heading: [{ "type": "heading", "attrs": { "level": 1 } }]. The applier also clears the editor's needsInitialization flag, which is what stops the starter template from overwriting that particular payload on first open.

Concurrency is CRDT last-writer-wins; there is no checksum or If-Match guard. Across replicas, replace guarantees removal of persisted content — concurrent unsynced edits on another replica may survive as a union or be superseded by CRDT order. Both are safe; neither corrupts.

Verifying a write. A 200 means the payload reached the live document and its save was handed off for persistence. A 200 with version means the write is saved. On an open document the 200 has no version, and a GET can trail the write. See Durability contract. Confirm a write by comparing the content GET /api/documents/:documentId/content?format=json returns.

One document, one write at a time. The collaboration process runs writes to one document in order. On a cold document each write waits for its saved row, up to 20 s from arrival. So a burst of parallel writes to one document can get 503 DOCUMENT_BUSY for the writes that could not start in time. Nothing was applied for those. Send writes to one document in sequence.

Retries. replace is idempotent. append is at-least-once under a 503 or timeout. After 503 SAVE_NOT_CONFIRMED, the write was applied but not saved in time, and a GET cannot see it until the save lands. Wait about a minute, then GET and verify before you retry. A retry at once can apply the change twice. 503 DOCUMENT_BUSY applied nothing, so a retry after a few seconds is safe. A retried append that carries toc-ids plants each one a second time — see Content contract. A single persist-failed 500 is retriable with mode=replace. A repeated persist-failed 500 for the same document means server-side persistence is wedged for it until the collaboration process restarts. Stop retrying and alert an operator, because further attempts keep mutating and broadcasting to live clients while never persisting. The operator signal is document_content_apply_total{outcome="error"} on the collaboration process's metrics endpoint.

Batching imports. Every PATCH persists a full document version. Prefer one replace or a few large appends over many small ones. A 500-chunk import stores roughly 500 cumulative snapshots, which survive until autosave retention thins unnamed versions to one per document per day (DOC_AUTOSAVE_RETENTION_DAYS). Many small appends also run into the global rate limiter.

Create with content

POST /api/documents with content (service-role only) encodes first, then writes the metadata row and version 1 in one transaction — an invalid payload leaves zero rows behind. ownerId sets the owner; isPrivate is not accepted. The first visitor renders the injected content rather than the starter template. A taken slug conflicts with 409 instead of being silently renamed.

Status codes

Status Code When
400 VALIDATION_ERROR Malformed documentId, unknown format or mode, or a body that is not a non-empty Tiptap doc
401 UNAUTHORIZED Missing, wrong, or user-JWT bearer; also when SUPABASE_SERVICE_ROLE_KEY is unset (fails closed)
403 FORBIDDEN content or ownerId on POST without the service-role key
404 NOT_FOUND No metadata row, or the document is soft-deleted. PATCH never creates — use POST
409 CONFLICT POST slug already taken
413 PAYLOAD_TOO_LARGE Body over 5 MiB, on PATCH and POST alike
422 UNPROCESSABLE_ENTITY Unknown node or mark, a content-expression violation, a missing level-1 title heading, or over 50 000 nodes / 100 levels of nesting. Nothing is written
429 RATE_LIMIT_EXCEEDED Global rate limiter. The house envelope; the retry seconds ride the Retry-After header — see Rate limiting
500 INTERNAL_SERVER_ERROR Snapshot decode failure on GET; persist failure on PATCH (see the durability contract); or the REST and collaboration processes holding different service-role keys, which the message names explicitly
503 SERVICE_UNAVAILABLE The collaboration process is unreachable or did not answer within 30 s
503 DOCUMENT_BUSY Earlier writes to the same document were still saving at the 20 s deadline. Nothing was applied
503 SAVE_NOT_CONFIRMED Applied, but the saved row did not appear within 20 s. It may still be saved. Wait about a minute before you verify with GET

Access semantics under the service key

Document state GET PATCH
Public 200 200
Private 200 200 — the service key is the admin plane; user gates are untouched
Read-only 200 200 — the read-only lock keeps blocking non-owner users
Soft-deleted 404 404
No metadata row 404 404

Durability contract

A PATCH 200 means the change was applied to the document, broadcast to any live collaborators, and pushed into the normal store pipeline:

  • Cold document (nobody has it open): the call waits until a saved version row holds the write, and the 200 carries that version. If the row does not appear within 20 s, the answer is 503 SAVE_NOT_CONFIRMED, never a false 200.
  • Open document: the room stays loaded, so the call does not wait, and the 200 has no version. In production the immediate store can lose the cross-replica lock to a peer and abort silently. The release flush and any later client-driven store heal it — the same crash window normal collaborative edits have. If the last person leaves before that save lands, the next write to the document waits for it first.

A 500 with the persist-failed message means the change may already be visible to live clients but did not persist.

Security posture

Content surfaces sit behind the constant-time, fail-closed service-role check; the caps and guards below are availability and hygiene, not access control.

  • 5 MiB per content-bearing request body, enforced before parse.
  • 50 000 nodes and 100 levels of nesting, enforced before the payload reaches the Yjs transformer. Node count, not bytes, is what bounds encode cost.
  • documentId is shape-checked against the 19-character alphanumeric id format before any database round-trip or internal hop.
  • No server-side content sanitizer, deliberately: it is dead defense against a service-role caller. Stored-content XSS is handled at render time by the extension gates and CSP — see the trust boundary above.

Internal apply endpoint

POST /internal/documents/:documentId/content on the collaboration process's internal listener (port HOCUSPOCUS_INTERNAL_HTTP_PORT, default 4003, shared with /metrics). Not Traefik-routed and not reachable from the public edge. REST forwards to it over HOCUSPOCUS_INTERNAL_URL with the same service-role bearer and the caller's x-request-id. Deploy hocuspocus-server before rest-api whenever this wire shape changes.

Document versions

Read, compare, name, delete, and restore a document's history. Module: src/modules/document-versions/.

Route Does
GET /api/documents/:documentId/versions List the history, newest first
POST /api/documents/:documentId/versions Name the next stored version — a checkpoint
GET /api/documents/:documentId/versions/:version Read one version's content
GET /api/documents/:documentId/versions/:version/diff Compare a version with an earlier one, block by block
DELETE /api/documents/:documentId/versions/:version Delete one version, as long as it is not the newest
POST /api/documents/:documentId/versions/:version/restore Put a version's content back into the live document

All six are service-role only (Authorization: Bearer <SUPABASE_SERVICE_ROLE_KEY>); a user JWT gets 401. They address documents by documentId, never by slug — see Identifying a document.

Reads and the delete run straight off Postgres in the REST process. The checkpoint and the restore need the live Y.Doc. So REST forwards them to the collaboration process over the same internal hop the content applier uses.

Every save is already a version

The collaboration server persists a full snapshot per debounced save — 10 s after typing stops, 60 s at the latest. So rows accumulate whether or not anyone asks for them. There is no versioning schedule to configure: that debounce envelope is the granularity, and it is the same window the content read can trail by.

A checkpoint therefore creates no history that would otherwise be missing. What it adds is a name, and the name is what the retention sweep keys off. Unnamed rows older than DOC_AUTOSAVE_RETENTION_DAYS (default 30) are thinned to one per document per day, while a row named by a person is never pruned. Spend names on the moments a person would want to find again.

Names the server mints for itself are the exception — see trigger. They read like any other named row but the sweep thins them, so a restore older than the retention window stops being undoable.

Snapshots are cumulative full state, not deltas, so deleting or pruning an old row never damages a newer one.

GET /api/documents/:documentId/versions

Metadata for the document's versions, newest first. No snapshot bytes — read those one version at a time.

Param Type Default Description
limit int 50 Page size, 1–100
offset int 0 Rows to skip, ≥ 0
{
  "success": true,
  "data": {
    "documentId": "kR4pZ2mQ7tY1nB8xW3v",
    "versions": [
      {
        "version": 14,
        "name": "Before the board review",
        "trigger": "checkpoint",
        "triggeredBy": null,
        "contributors": [],
        "createdAt": "2026-07-25T14:02:11.301Z"
      },
      {
        "version": 13,
        "name": null,
        "trigger": "websocket",
        "triggeredBy": {
          "id": "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed",
          "avatar_url": "https://example.test/ada.png",
          "avatar_updated_at": "2026-07-01T09:12:00.000Z",
          "full_name": "Ada Lovelace",
          "display_name": "Ada"
        },
        "contributors": [],
        "createdAt": "2026-07-25T13:58:40.117Z"
      }
    ],
    "total": 14,
    "limit": 50,
    "offset": 0
  }
}

total counts every row for the document. It is read in the same transaction as the page, so it cannot describe a different history than the rows beside it.

Field Meaning
version Monotonic per document, starting at 1. Gaps are normal — retention and DELETE both leave them
name The row's commit message, or null for an unnamed autosave
trigger What caused the row: websocket, api, checkpoint, revert, revert-backup, schema-migration, or null on rows stored before attribution shipped
triggeredBy Profile of whoever caused the row, or null
contributors Profiles of everyone whose edits landed in this row
createdAt Commit time of the row, not of the edits inside it

Profiles are the public.users columns the history sidebar renders, snake_case as that table spells them. Attribution is decoration: when the profile lookup fails, triggeredBy falls back to null and unresolvable ids drop out of contributors rather than failing the request. An id that resolves to no profile disappears the same way.

triggeredBy on a websocket row is the collaborator whose edit flushed the debounce window. On a checkpoint or revert row it is whoever asked for the operation. Both REST write routes leave it null — the service key is nobody, and only the editor's own in-app revert carries a real account.

contributors is best-effort and per-replica. It is the set of accounts whose updates reached this collaboration replica since its previous save. So a room split across replicas records each replica's own set. Anonymous editors are stored in the column: they carry a Supabase sub like anyone else. But they resolve to no profile, so they never appear in the rendered list. Read the column's length as a floor on the rendered one, never as its equal.

The server names some rows itself, and their trigger is what tells them apart from a name a person typed. Before restore of version N carries revert-backup and Schema migration carries schema-migration; both list like any other named version, but retention thins them once they pass the window. Restored version N carries revert — a person asked for it, so it survives retention like a checkpoint.

POST /api/documents/:documentId/versions

Names the next stored version.

{ "name": "Before the board review" }

name is required, trimmed, and 1–200 characters. The document's body is untouched. The checkpoint opens the document, commits an empty transaction to trigger one immediate save, and lets that save carry the name.

{
  "success": true,
  "data": { "documentId": "kR4pZ2mQ7tY1nB8xW3v", "name": "Before the board review" }
}

A 200 means the save pipeline was triggered, not that a row exists. The row is written by the worker. When its transaction commits, the worker publishes doc:<documentId>:saved on Redis, and the collaboration process re-broadcasts it into the room as a document:saved stateless message. That broadcast is the signal the row landed. A REST caller gets no such push — poll GET …/versions for the name if you need certainty.

One gap to know about: when the enqueue fails, the collaboration process falls back to saving directly to Postgres. The row still lands, but nothing publishes doc:*:saved, so the room never sees a confirmation for it. That is pre-existing behavior of the fallback, not specific to checkpoints.

A checkpoint always lands, even when the bytes have not changed. The store pipeline deduplicates saves of identical content within a ten-second window. A checkpoint taken right after an autosave would otherwise be swallowed by it and lose the name. A checkpoint widens its own job id with a random key to stay off that dedupe. So naming an unchanged document produces a named row whose content duplicates the row before it. That is the intent — the name is the point.

GET /api/documents/:documentId/versions/:version

One version's content, through the same decoder as GET /content. Query: format = json (default) or text.

{
  "success": true,
  "data": {
    "documentId": "kR4pZ2mQ7tY1nB8xW3v",
    "version": 13,
    "format": "json",
    "content": { "type": "doc", "content": [] }
  }
}

The same trust boundary applies: stored content is returned verbatim and the server never sanitizes it.

GET /api/documents/:documentId/versions/:version/diff

Which top-level blocks differ between two versions, and whose text sits in them now. :version is the newer side.

Param Type Default Description
base int the nearest version below The older side of the comparison

The default is the greatest version below :version, which is not always :version - 1 — retention and DELETE leave gaps. A base at or above :version is a 400. That check runs before the document is looked up, so it answers 400 rather than 404 even for a document that does not exist. A base naming a version that does not exist is a 404. An omitted base on a document's oldest version is not, and comes back as fromVersion: 0 with the whole document read as added.

{
  "success": true,
  "data": {
    "documentId": "kR4pZ2mQ7tY1nB8xW3v",
    "fromVersion": 16,
    "toVersion": 17,
    "blocksBefore": 269,
    "blocksAfter": 269,
    "changes": [
      {
        "kind": "changed",
        "index": 65,
        "nodeType": "taskList",
        "from": 9610,
        "to": 11033,
        "before": "Capture the goal\nDraft the first pass",
        "after": "Capture the goal\nDraft the second pass",
        "clientIds": [3728007124]
      }
    ],
    "totalChanges": 4,
    "coarse": false,
    "unattributed": false,
    "authors": []
  }
}
Field Meaning
fromVersion The older side. 0 when the newer version has no predecessor
blocksBefore / blocksAfter Top-level block counts on each side
changes added, removed, and changed blocks, in the newer document's order, capped at 500 entries
totalChanges The true count before the cap. changes.length < totalChanges means the list was clipped
coarse Matching hit its cell budget and fell back to remove-all plus add-all. Positions and previews still hold, the pairing does not
unattributed The stored Yjs items did not line up with the decoded blocks, so every clientIds is empty

Each entry in changes carries index, the top-level index in the newer document — in the older one on removed. from and to are ProseMirror positions in the newer document, absent on removed. before and after are the first 200 characters of the block's text.

Comparison is over whole top-level blocks of decoded ProseMirror content, not over words, so a one-word edit reports the paragraph. Editor-regenerated toc-id and keyId attributes are stripped first: re-anchoring a heading or a picture is not a change.

Authorship. clientIds lists the Yjs clientIDs holding live content in the block, and authors names them — one entry per clientID that has a binding row.

{ "clientId": 3728007124, "user": { "id": "1b9d…", "display_name": "Ada" }, "anonymous": false }

user carries the same public.users columns the history sidebar renders, or null when the binding exists but no profile resolved. anonymous records that the account was anonymous when the clientID was bound. Identity is joined at read time. So an anonymous editor who later signs up gets their real name here across their whole history, with no backfill.

A clientID that appears in changes[].clientIds but not in authors is unattributed. Bindings exist only for edits made after attribution capture shipped, so on an older document authors is [] while clientIds stays populated. That is how a caller tells "unknown writer" apart from "nobody attributed".

The diff answers who wrote the text currently in this block. It does not answer who made this change, and it does not answer who deleted this. removed blocks carry no authorship, and no server setting changes that. Yjs records no deleter. createDeleteSetFromStructStore keys the delete set by the clientID that created each deleted item, and each entry stores only a clock and a length (yjs 13.6.31). Disabling garbage collection would keep the removed text and the name of whoever wrote it, and would still name nobody as the remover.

Server-side writes leave content with no bindable author. A binding is recorded only when a live socket announces the clientID it writes under (src/lib/client-authors.ts). Restore, import, and PATCH /content apply through a direct connection that has no socket, and applyContentToDoc clones every node. The new items therefore carry the server document's own clientID. After any of those operations the affected blocks return clientIds with no matching authors entry. Read that as an unknown writer, never as a wrong one. The version's trigger field names which operation did it.

clientID bindings are a first-claim record, not an audit trail. Yjs clientIDs are asserted by the client. The server records the account that first claimed one on a live socket and never overwrites it. So a legitimate editor cannot be displaced by a later forger. But the row is not proof of authorship, and nothing built on it should imply that it is.

Identical versions. A checkpoint of an unchanged document mints a named row whose content duplicates the row before it. Diffing that pair returns 200 with changes: [] and both block counts 0. The bytes are compared without decoding either side, so the counts are never taken. Zero here means not counted, not empty.

Neither 503 nor 413 can come back from this route. It reads straight off Postgres and never touches the collaboration process, and a GET carries no body to overrun.

DELETE /api/documents/:documentId/versions/:version

Deletes one version permanently.

{ "success": true, "data": { "documentId": "kR4pZ2mQ7tY1nB8xW3v", "version": 7, "deleted": true } }

The newest version cannot be deleted — 409 CONFLICT. It is the base a cold load reads, so removing it rewinds the document to an older snapshot. Worse, a room still open would then flush its newer live state back over that older base as a revert nobody asked for. Checking "is this the head" and deleting happen under one row lock, so the answer cannot go stale between the two.

To drop the current state, restore an earlier version instead: that moves history forward rather than truncating it.

POST /api/documents/:documentId/versions/:version/restore

Puts a version's content back into the live document.

Not to be confused with POST /api/documents/:documentId/restore, which is the trash restore — it clears deletedAt on a soft-deleted document and touches no content.

The route says restore and the internals say revert; they name the same operation.

{
  "success": true,
  "data": { "documentId": "kR4pZ2mQ7tY1nB8xW3v", "restoredFrom": 7, "backupVersion": 15 }
}

Three things happen, in order:

  1. The stored snapshot is decoded and re-encoded against the current schema. A version the schema can no longer express is rejected with 422 before anything is opened or written.
  2. The live document — including edits still inside the debounce window — is captured and committed as a new version named Before restore of version N. backupVersion is that row.
  3. The body is replaced with the target content, and the save that follows is named Restored version N.

So a restore appends two versions and never rewinds the counter. Undoing one is a restore of the backup it wrote. Repeating the same restore is safe but not free: each call banks another backup and another restore row.

backupVersion is number | null. Null means the collaboration process's reply could not be read, not that no backup was taken — the row exists either way. A history UI should render the absence rather than reporting "no backup".

When the backup cannot be committed, nothing is restored. The 500 says so explicitly and the document is unchanged. That ordering is deliberate, so a worker that dies mid-operation still leaves the pre-restore state recoverable.

When persistence is wedged, the backup is already committed and the replacement may already be visible to live collaborators without ever reaching the database. That is the persist-failed 500, and it carries the same rule as PATCH /content. Verify with GET before retrying, and treat a repeat for the same document as persistence being wedged for it until the collaboration process restarts.

A restore waits its turn, like PATCH /content. Writes to one document run in order. On a cold document a restore waits up to 20 s from arrival for its saved row. 503 DOCUMENT_BUSY means earlier writes to the document were still saving at that deadline. Nothing was restored, so a retry after a few seconds is safe. If the restore's own save is slow, it still answers 200: the backup and the replacement exist, and the next write waits for them.

The editor's in-app revert runs the same operation over the collaboration server's stateless channel instead of this route. That path requires an authenticated, writable connection, which is why it can attribute the resulting rows to a person and this one cannot.

Status codes

Status Code When
400 VALIDATION_ERROR Malformed documentId; a version or base that is not a positive integer within int4; a base at or above the version it is compared to; limit outside 1–100; negative offset; unknown format; a name that is empty after trimming or over 200 characters
401 UNAUTHORIZED Missing, wrong, or user-JWT bearer; also when SUPABASE_SERVICE_ROLE_KEY is unset (fails closed)
404 NOT_FOUND No metadata row, the document is soft-deleted, or no such version — including an explicitly named base
409 CONFLICT DELETE targeting the newest version
413 PAYLOAD_TOO_LARGE Write body over 16 KiB. These routes carry a name at most — content never rides them
422 DRAFT_DOCUMENT Checkpoint or restore on a document that has never been saved. A draft has no history to name or roll back to
422 UNPROCESSABLE_ENTITY Restore whose stored snapshot cannot be decoded, or cannot be re-encoded against the current schema. Nothing is written
429 RATE_LIMIT_EXCEEDED Global rate limiter. The house envelope; the retry seconds ride the Retry-After header — see Rate limiting
500 INTERNAL_SERVER_ERROR Snapshot decode failure on read; the document could not be opened; the pre-restore backup failed; the save failed; or the REST and collaboration processes holding different service-role keys, which the message names explicitly
503 SERVICE_UNAVAILABLE The collaboration process is unreachable or did not answer within 30 s. Only the checkpoint and the restore hop, so no read route can return this
503 DOCUMENT_BUSY Restore only. Earlier writes to the same document were still saving at the 20 s deadline. Nothing was restored

DRAFT_DOCUMENT is specific to these routes. It shares the 422 status with invalid content, so a caller that only reads the status still behaves correctly. It also carries its own code, so one can be told from the other.

Internal version endpoints

POST /internal/documents/:documentId/versions and POST /internal/documents/:documentId/versions/:version/restore on the collaboration process's internal listener, beside the content apply endpoint and /metrics. Not Traefik-routed. REST forwards to them over HOCUSPOCUS_INTERNAL_URL with the same service-role bearer and the caller's x-request-id. Deploy hocuspocus-server before rest-api whenever this wire shape changes.

Document changes

Compares the newest stored snapshot at or before since with the newest at or before until, and reports the result per heading section. Read-only: nothing is written and no live document is loaded. Module: src/modules/document-changes/.

The one route is service-role only (Authorization: Bearer <SUPABASE_SERVICE_ROLE_KEY>); a user JWT gets 401. That check runs ahead of validation, so a bad key with a malformed since answers 401 and never 400. The route addresses the document by documentId, never by slug — see Identifying a document.

It reads Postgres in the REST process and never opens the live document. Neither 413 nor 503 can occur: the route takes no body, and it never hops to the collaboration process.

The window bounds commit time

since and until bound the version row's createdAt. They never bound the version number. Both take an ISO 8601 instant carrying an offset, and Z counts as one. The accepted shape is YYYY-MM-DDTHH:MM:SS, then an optional fraction, then Z or ±HH:MM. Several forms a reader may call valid ISO 8601 are refused with a 400: a bare local timestamp 2026-08-01T00:00:00, a minute-precision 2026-08-01T00:00Z, an hour-only offset 2026-08-01T00:00:00+01, and the basic format 20260801T000000Z. In a query string a literal + decodes to a space, so a numeric offset must be percent-encoded as %2B01:00. until is optional and defaults to the moment the request is served, which is why the published OpenAPI carries no frozen date. Equal ends are allowed and take a fast path that reports no change. A since later than until is a caller error and answers 400, but only when you send until. With until omitted, a since in the future resolves both ends to the newest row and reports no change. That reads exactly like the equal-ends answer above, so a mis-computed future date looks like a quiet document.

createdAt is commit time, not edit time. A version row is inserted by the persistence worker, after a debounce of 10 s idle or 60 s maximum. So until=now can miss the last minute of typing. Day-scale windows are unaffected; minute-precision windows are illusory.

The anchor rule. Each end resolves to the newest row whose createdAt is at or before it — resolveAnchor in infra/changesStore.ts, ordered createdAt desc, version desc. So baseline and head echo the rows the comparison actually used. baseline.createdAt is usually older than the since you asked for. Report what the response's anchors say, never what your own query asked for.

A since older than every surviving row resolves to null, not to the oldest row. baseline comes back null, and the whole document is then reported as added. That is correct, not a fault. Nothing stored describes the document at that instant, so there is no earlier side to compare against. Retention thins autosave rows, so this is the ordinary answer for a window reaching back past DOC_AUTOSAVE_RETENTION_DAYS.

A null baseline also widens versions, triggers and contributors to the whole history. The row count then takes its lower bound at version 0. So it covers every version from 1 up to head.version, not only the versions inside the requested window. With a real baseline the bound is exact: it excludes the baseline row and includes the head row. The section counts are unaffected either way, because they come from the two snapshots alone.

GET /api/documents/:documentId/changes

Param Type Default Description
since ISO instant — (required) Anchors the baseline: the newest row at or before it. See the anchor rule
until ISO instant the request instant Anchors the head, the same way. Same shape as since
scope enum summary summary returns counts only; headings adds the sections tree
{
  "success": true,
  "data": {
    "documentId": "kR4pZ2mQ7tY1nB8xW3v",
    "since": "2026-08-01T00:00:00.000Z",
    "until": "2026-08-31T23:59:59.000Z",
    "baseline": { "version": 11, "createdAt": "2026-07-29T16:40:02.884Z" },
    "head": { "version": 18, "createdAt": "2026-08-30T09:14:51.220Z" },
    "changed": true,
    "summary": {
      "sectionsAdded": 1,
      "sectionsRemoved": 0,
      "sectionsModified": 2,
      "sectionsMoved": 0,
      "wordsAdded": 74,
      "wordsRemoved": 12,
      "versions": 7,
      "triggers": ["websocket", "checkpoint"],
      "contributors": [
        {
          "id": "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed",
          "avatar_url": "https://example.test/ada.png",
          "avatar_updated_at": "2026-07-01T09:12:00.000Z",
          "full_name": "Ada Lovelace",
          "display_name": "Ada"
        }
      ]
    }
  }
}

The baseline above is older than the requested since. That is the anchor rule, not a bug.

Field Meaning
since The window as the server read it, echoed back
until The same, filled in with the request instant when the caller omitted it
baseline { version, createdAt } of the older row used, or null when no row is old enough
head { version, createdAt } of the newer row used, or null when no row exists at or before until
changed Whether any section is added, removed, modified, or moved
summary The rollup, described below
sections The outline tree. Present only for scope=headings
summary field Meaning
sectionsAdded / sectionsRemoved / sectionsModified / sectionsMoved How many sections carry that status, counted over the whole tree and not only its roots
wordsAdded / wordsRemoved The section magnitudes summed. A null magnitude contributes 0
versions How many rows were stored in the window, counted by version number
triggers The distinct non-null trigger values on those rows. A debounced save carries websocket
contributors Profiles for every account those rows name, the triggeredBy of each row included

contributors carries the same public.users columns the history sidebar renders. The field is named for contributors, and it holds every account the window's rows name, so it is a superset of the editors.

changed is derived from the section statuses, never from the bytes. A window that only spans the editor's first-open toc-id stamping pass has different bytes and no real edit, and reports changed: false.

summary is identical under both scopes. The rollup is computed before the scope branch, so scope=headings adds sections and changes nothing else. Both scopes run the same comparison. summary is not a cheaper mode.

Four windows come back with changed: false. Each one is a real answer, not an error. The sections column assumes scope=headings; under scope=summary the key is absent in every row.

Window What comes back
No row at or before until baseline and head both null, versions: 0, sections: []
Both ends land on the same row Both anchors set to that row, versions: 0, sections: []
The two rows hold identical bytes Both anchors set, a real versions count, sections: []. Neither side is decoded
Both rows decode, and every section matches Both anchors set, a real versions count, sections full of unchanged nodes

A named checkpoint of an unchanged document mints a row whose bytes duplicate its predecessor, which is the third case above.

The section tree

sections is absent on scope=summary and present on scope=headings. Present and empty is not the same answer as absent. An empty array has two causes. The comparison ran and found no sections, or one of the fast paths above skipped it.

{
  "tocId": "hK2p9QmTvB4nX7Lc",
  "text": "Rollout plan",
  "level": 2,
  "status": "modified",
  "magnitude": { "wordsAdded": 31, "wordsRemoved": 4, "blocksBefore": 5, "blocksAfter": 6 },
  "excerpt": "We move the beta group first and hold the rest for a week.",
  "children": []
}
Field Meaning
tocId The heading's stored toc-id, or null. Sanitized and cut at 200 characters
text The heading's text, sanitized and cut at 200 characters. "" on the preamble
level The heading level, clamped to 1–6. A non-numeric stored level reads as 1. 0 marks the preamble
status One of added, removed, modified, moved, unchanged — see Section status
magnitude { wordsAdded, wordsRemoved, blocksBefore, blocksAfter }, or null when nothing countable moved
previousLevel The baseline heading level. Set only on a modified section whose level changed
excerpt Up to 140 characters of the text that arrived. The key is omitted when there is nothing to show
removedExcerpt Up to 140 characters of the text that left. A removed section puts its body here. Omitted when empty
runs Ordered same, removed, and added text around each edit. A gap run (no text) marks skipped context
children Nested sections. Always an array, often empty

A section is one heading plus the top-level nodes up to the next heading of any level. So a section does not contain its subsections, and editing a child never marks its parent modified. The document title is a section like any other.

Nesting is by level, not by containment. A node becomes the child of the nearest preceding node with a strictly smaller level. A level-3 heading directly under a level-1 heading becomes its direct child; no level-2 node is invented. A leading level-3 heading followed by a level-1 heading gives two roots.

Nodes that sit before the first heading become one synthetic preamble. It carries level: 0, tocId: null and text: "". It is always a root sibling with no children, never the parent of the outline that follows. Only legacy documents that break the title-first rule carry one.

The tree is in head order. Each removed section is emitted just after the last head section that did pair, and removals with nothing before them come first. A removed node carries the baseline's level and text, so it can nest under a head section by that older level.

excerpt is not verbatim. Whitespace collapses to single spaces, C0 and C1 control characters are stripped, and the result is cut at 140 characters. Both caps keep a newline from forging a whole entry in a plain-text reader. The Change digest paints only runs, and their text is cleaned the same way.

When present, runs holds at least one added or removed run, and it never ends in a gap. An edit with no visible text gives no runs. Whitespace, U+00A0, a zero-width space, non-joiner or joiner, a word joiner, a bidi mark (LRM, RLM or ALM) and U+FE0F alone are such edits. The excerpts are cleared with it, and an excerpt with no visible text is left out. The status and the magnitude stay. An added or removed media node has no text, so it reads image, video or embed in runs. A whole added or removed section uses the same words in its excerpt. Word counts never include them.

Section status

status When magnitude
added The section has no baseline side Every word and block in it, counted as added
removed The section has no head side Every word and block in it, counted as removed. The body is removedExcerpt, not excerpt
modified Both sides exist and their canonical forms differ Word deltas plus the block count on each side, or null — see below
moved Both sides exist, the canonical forms are equal, and the shared toc-id sits outside one common subsequence Always null
unchanged Both sides exist and their canonical forms are equal Always null. An unchanged pair is never measured

The canonical form covers the heading node and the body together. So a heading level change from 2 to 3 stays visible, even when both node lists are otherwise identical. It drops the toc-id attribute, because the editor stamps that on first open and it is churn, not an edit.

On added and removed the heading's own words and its own node count are included. A one-word heading over a three-word paragraph reports wordsAdded: 4 and blocksAfter: 2.

The excerpt on a modified section is the single widest inserted run, not every insertion. On an added section it is the section body, without the heading. Both are then cut at 140 characters.

How sections are paired

Identity is resolved in four steps, in this order.

  1. The preamble, by position. When both sides open with a level: 0 preamble, those two pair. A preamble carries no toc-id and no name, so position is its only identity.
  2. By toc-id. Both sides must carry one. Inside each snapshot the first occurrence wins, so a duplicate id falls through to the next step. A stable id beats position. A reorder that keeps the text and the toc-id is moved. A toc-id rewrite that keeps the canonical form stays unchanged.
  3. By longest common subsequence, as unchanged. The key is the canonical hash of the whole section. An unstamped baseline section still matches a freshly stamped head section here, because the canonical form drops toc-id. That is what stops the editor's first-open pass reading as a whole new document.
  4. By longest common subsequence, as modified. A leftover removal is zipped with a leftover addition under two conditions. The two levels must be equal, and at least one of the two ids must be null.

That last condition is deliberate. Two sections that both carry a toc-id and still did not match are two different sections. Merging them would hide a deletion and call a new section an edit. So a rename that also mints a new id reports one removed plus one added, never one modified. A heading whose text and level both changed comes out the same way, because the levels have to match for the zip.

Every section is keyed with the same node type, so an adjacent removal and addition can reach the zip at all. Unbalanced runs keep their leftovers: extra removals stay removed, and extra additions stay added.

There is no coarse field on this response, unlike the versions diff. The matcher's fallback needs about 1000 unpaired headings on each side, so no real document reaches it. Stop looking for the field.

What this route does not tell you

A formatting-only edit reports magnitude: null. The default token encoder reads neither marks nor attributes. Bold on existing words, a changed link address, and a heading level change all measure zero. The status still says modified: the edit happened, and only its size is unknown. A measurement that throws also reports magnitude: null, and the response cannot tell the two apart.

Word counting is whitespace splitting. It is not language-aware, so a script that does not separate words with spaces counts as one word.

A parent's magnitude says nothing about its subtree. Sections own no descendants, so a child edit leaves the parent unchanged.

A pure reorder of stamped sections reports changed: false. The moved sections pair by toc-id and compare equal, so every status is unchanged. scope=headings still shows the new order, which is where a caller can see the move. Reordering sections that carry no toc-id is different: those fall to the matcher and can come back as removed plus added.

A caller that rotates every toc-id defeats pairing. Nothing then matches by id, everything falls to the matcher, and an edited section reads removed plus added rather than modified. The webapp keeps its ids. A Settings replace carries each one by level, text and parent path, then by text alone, then by a unique unchanged section text. So a replace shows this only for a new heading, or a renamed one whose section text also changed. A REST caller can rotate every id, because PATCH /content stores a caller-supplied toc-id verbatim. The result is coarser, never false: the section is still reported as changed, and no edit is attributed to a section nobody touched.

A toc-id or keyId rewrite on its own is unchanged. The canonical form drops both attributes, so re-anchoring a heading or a picture is not an edit.

Attribution is decoration. It is per-replica and best-effort, anonymous editors are omitted, and retention thinning under-reports contributors on windows longer than the autosave retention. A profile-lookup outage empties contributors rather than failing the request. The content comparison stays correct in every one of those cases.

A document only reaches followers once a signed-in person has opened it at least once. The audience for a content-change notification is workspace membership, and only a signed-in browser open creates the workspace row. So a document created through this API, which nobody has opened while signed in, notifies nobody — the owner included. This is a recorded gap, not a fault. Closing it would put a write into a read path and would record a first visitor who never visited. See issue #203.

The echoed tocId is sanitized, so it is not guaranteed to equal the stored attribute. Whitespace collapses, control characters go, and the value is cut at 200 characters. A server-stamped id is 16 alphanumeric characters, which the sanitizer never alters, so pairing stays consistent. A stranger-written id of another shape can come back changed, and a deep link built from it then resolves to nothing.

Status codes

Status Code When
400 VALIDATION_ERROR Malformed documentId; a since or until that is not an ISO instant with an offset; a missing since; a since later than until, checked only when until is sent; a scope other than summary or headings
401 UNAUTHORIZED Missing, wrong, or user-JWT bearer; also when SUPABASE_SERVICE_ROLE_KEY is unset (fails closed). Checked before validation
404 NOT_FOUND Told apart by the message: there is no metadata row; the document is soft-deleted; or retention removed a version this window anchors on while the request ran
429 RATE_LIMIT_EXCEEDED Global rate limiter. The house envelope; the retry seconds ride the Retry-After header — see Rate limiting
500 INTERNAL_SERVER_ERROR A stored snapshot on either side could not be decoded. Nothing partial is returned

Only the retention case is worth retrying: the document exists, and only the anchor row went. A missing metadata row and a soft-deleted document are both permanent, so retrying either just repeats the 404.

Document conversion

Turn a document into a file, or a file into document content. Module: src/modules/document-conversion/.

Direction Formats Route
Export docx, md, odt GET /api/documents/:documentId/export?format=…
Import docx, md POST /api/documents/:documentId/import

The asymmetry is deliberate: nothing reads ODT back, and a legacy .doc is refused rather than guessed at.

Both routes take either the service-role key (Authorization: Bearer <SUPABASE_SERVICE_ROLE_KEY>) or a Supabase user token (token: <jwt>, or the same JWT as a bearer). They address the document by documentId, never by slug — see Identifying a document.

A token is required whatever the document's privacy. Both routes fall back to requireUser, not optionalUser, so a call with no credential is a 401 even on a public document. That is the rule a browser caller gets wrong most often. Send the Supabase access token on every request, in the token header or as a bearer, public documents included.

Access matrix. The service-role key passes every row. A user token runs the same private-document predicate as the WebSocket gate and GET /api/documents/:slug (resolvePrivateAccess in src/lib/privateAccess.ts) — one rule, three surfaces.

Document GET /export POST /import
Public, unlocked any signed-in caller any signed-in caller
Private, caller owns it 200 200
Private, caller signed in as someone else 403 FORBIDDEN 403 FORBIDDEN
Private, caller anonymous or ownerId null 401 UNAUTHORIZED 401 UNAUTHORIZED
Public and readOnly, caller does not own it 200 — the lock is write-only 403 FORBIDDEN

The privacy rule runs first, so a document that is both private and locked answers with the privacy outcome. Import gates on write access because a locked document's readers can never apply what it returns, and the conversion costs real CPU either way. The readOnly rule is the one the WebSocket handshake enforces: the owner keeps edit rights, everyone else is refused.

Import writes no content. It returns Tiptap JSON and leaves the document untouched. The caller applies it with PATCH /content, which enforces the read-only lock on the write itself. Import enforces it on admission. It is not side-effect free, though: images embedded in the uploaded file are re-hosted to object storage before the JSON returns. So a caller that discards the response leaves those objects behind. Read the fidelity contract before converting anything you cannot re-create.

GET /api/documents/:documentId/export

Renders the document to a file. Query: format = docx (default), md, or odt.

The 200 body is the raw file, not the house envelope; errors still carry it. Content-Disposition is attachment with the slugified title. It falls back to the slug and then the documentId, so a title that slugifies to nothing — all emoji — cannot produce a bare .docx.

Staleness. Export reads the persisted head, the same snapshot GET /content serves, so it trails an actively edited document by the store debounce — 10 s idle, 60 s maximum.

A document whose metadata exists but has no snapshot yet exports as an empty file, not a 404.

POST /api/documents/:documentId/import

Body is multipart/form-data with field name documentFile (not file, and not the media route's mediaFile). There is no raw-body variant: one field means one size cap and one format check for every upload.

The container decides the format, not the filename or the declared MIME type. Both lie too often to trust:

First bytes Read as
50 4B 03 04 .docx (zip)
D0 CF 11 E0 legacy OLE2 .doc → 415, re-save as .docx
anything else Markdown, if it decodes as strict UTF-8 — otherwise 422

The strict decode is Markdown's real gate. A BOM is stripped, so a Windows-written .md keeps its opening # instead of importing as one long paragraph.

Any non-.docx zip lands on the Word error. ODT is a zip, so re-importing your own ODT export returns 422 The upload could not be read as a Word document. That is the sniff working, not a mis-detected file — ODT import does not exist.

The size caps depend on who imports (maintainer ruling on #722, 2026-11-09). The server reads the document's stored owner; a client flag never counts.

Caller Upload Unpacked .docx Markdown
The document owner 40 MiB (MAX_OWNER_IMPORT_BYTES) 40 MiB 65 536 characters
Anyone else 10 MiB (MAX_IMPORT_BYTES, the pad's media cap) 40 MiB 65 536 characters

The unpacked cap is the same for the owner until #724. 40 MiB of unpacked Word text already costs about 820 MiB of memory, and the converter runs before the result guards below.

The body limit follows the caller. The server reads the document's owner before it reads the body, then limits the body to that caller's cap. It reads Content-Length when the request has one. A chunked body is counted as it arrives and refused at the cap.

Six different 413s.

  • PAYLOAD_TOO_LARGE: the upload is over the caller's cap. Nobody's body is read past their own cap.
  • PAYLOAD_TOO_LARGE: a .docx that really unpacks past 40 MiB is refused before the converter opens it. A zip bounds its compressed size, never its inflated one, and 200 KiB of deflated padding reaches 200 MiB.
  • PAYLOAD_TOO_LARGE: Markdown over 65 536 characters, for every caller. That cap rejects; it never truncates, since half a document is worse than a refused one. Larger hostile Markdown blocks the server for minutes or passes 1 GiB of memory (scripts/bench-import.ts). Convert the file to .docx to get past it.
  • TOO_MANY_NODES: the converted result holds more than 50 000 nodes (MAX_CONTENT_NODES), the cap on every content write.
  • TOO_DEEP: the converted result nests deeper than 100 levels (MAX_CONTENT_DEPTH), the same cap as every content write.
  • TOO_LARGE_TO_OPEN: the result encodes to more than 12 MiB of Yjs state. A browser applies the replace as one update, and a socket message over 16 MiB (MAX_WS_MESSAGE_BYTES) is refused, so the document could not load. The 4 MiB margin covers the replaced document's delete set.

The last three run on the result of both formats, before the server answers, so a refused import is never applied and never saved. Pictures a refused Word file held are already rehosted, as with any discarded import.

Images embedded in a Word file are re-hosted through the media route so the result carries URLs the editor can parse instead of data: payloads. This needs PUBLIC_RESTAPI_URL — see ENV.md. Without it, every image becomes a warning and the text still imports.

A lone media URL becomes a player node. A paragraph that is only [url](url) or an autolink, and whose href is a video, audio, or embed host, becomes that media node. A provider address written as an image — ![youtube](https://youtu.be/…), and the same for vimeo, video, audio, and the other embed hosts — is lifted out of its paragraph so PATCH /content accepts the JSON. A labeled link, a filter link, a media URL next to other text, and a media URL inside a list item stay links. Picture width and height stay empty on this JSON unless an option block sets them. Settings replace writes natural picture size in the browser.

{
  "success": true,
  "data": {
    "content": { "type": "doc", "content": [/* ... */] },
    "title": "Quarterly report",
    "warnings": [{ "code": "title-promoted-paragraph", "message": "…" }]
  }
}

The result always opens on a level-1 heading, so it satisfies PATCH's title-first rule. An existing first heading is forced to level 1. A first paragraph is promoted to one (losing its marks). A document with no usable opening text gets a heading synthesized from the slug. Each of the last two reports a warning — a paragraph silently becoming the document title is a change the caller has to see.

Fidelity contract

Conversion is lossy in named ways. Import reports what it changed through warnings. Export has no warning channel — a downloaded file is the only evidence — so the table below is the contract.

What export drops

Content DOCX Markdown ODT
The eight media embeds (youtube, vimeo, loom, x, spotify, soundcloud, video, audio) link to the source ![youtube](src) link to the source
Images picture — own origin, PNG/JPEG only ![alt](src) link to the source
Highlight dropped ==text== kept
In-progress upload placeholders removed removed removed

DOCX is the one format whose converter fetches: it downloads every <img src> to embed the bytes. src is ordinary pad content, so only images on this server's own media origin (PUBLIC_RESTAPI_URL) are kept. A third-party or unreachable one is dropped rather than fetched, and with no PUBLIC_RESTAPI_URL set no image is embedded at all. An embed becomes a paragraph holding its caption, or its URL when it has no caption. ODF draws a picture through a measured frame. A remote image has no measured width, so ODT gives the reader a link it can follow rather than an empty box.

The origin filter is not the last gate. A second filter sniffs the fetched bytes and keeps only PNG and JPEG, so a same-origin GIF, WebP or SVG is dropped as well. A redirect is refused rather than followed, because following one leaves the origin already checked. The run is budgeted at 128 images, 8 MiB inlined, 5 s per image and 30 s in total. Anything past the budget is removed. Both filters are security boundaries, not gaps. The origin check stops SSRF. The byte sniff keeps crafted headers away from the bundled image-size parsers, which loop forever on them.

What a DOCX round trip loses. Export to .docx and import it back, and the following do not survive: underline, blockquote, code block, horizontal rules, and table header cells. Blockquote and code block each flatten to a paragraph, and table header cells demote to normal cells. Word's own Title, Subtitle and Quote styles are mapped on the way in. So a file authored in Word fares better than one that made this round trip.

Markdown keeps the media, its caption and its placement. An image exports as ![alt](src), and an embed as ![youtube](src) with its own node name. The caption rides the title slot, ![youtube](src "My caption"). Placement rides an option block after it, {width=800 float=right}, with only the values that differ from the default. video, audio and x also carry their player options there. Import reads all of it back. The page Media in Markdown lists the keys. Markdown still drops the image title and the provider player options, such as SoundCloud's visual and the YouTube start time. Export to .docx, or apply Tiptap JSON through PATCH /api/documents/:documentId/content, when those matter.

No export format carries toc-id. That id is the identity a heading's chat channel, fold state and ?id= deep link hang off. Imported content has none, so applying it with mode=replace re-keys every heading in the document and orphans all three, permanently. Re-editing does not bring them back. Default to mode=append and reserve replace for a document whose heading identities nobody depends on yet. An appended import brings its own title heading with it, and the title-first check only looks at the document's first node. Drop or demote content[0] unless you want a second title heading in the middle of the document.

Warning codes

An empty warnings array does not prove that nothing was lost. The converter drops comments, headers, charts and diagrams with no warning.

Code Meaning
media-placeholder-dropped One image could not be re-hosted and was dropped; the rest of the file imported
title-promoted-paragraph The first paragraph became the document title
title-synthesized No usable opening text, so the title came from the slug
tracked-changes-accepted Tracked deletions were dropped, and tracked insertions became plain text
unsupported-element The converter met something it does not model

Status codes

Status Code When
400 VALIDATION_ERROR Malformed documentId, unknown format, a body that is not multipart/form-data, or no documentFile field
401 UNAUTHORIZED Missing, wrong, or user-JWT bearer; also when SUPABASE_SERVICE_ROLE_KEY is unset (fails closed)
404 NOT_FOUND No metadata row, or the document is soft-deleted
413 PAYLOAD_TOO_LARGE Upload over the caller's cap (40 MiB owner, 10 MiB anyone else), a .docx that unpacks past 40 MiB, or Markdown over 65 536 characters
413 TOO_MANY_NODES Import result over 50 000 nodes
413 TOO_DEEP Import result nested deeper than 100 levels
413 TOO_LARGE_TO_OPEN Import result over 12 MiB of encoded Yjs state
415 UNSUPPORTED_MEDIA_TYPE Import of a legacy OLE2 .doc
422 UNPROCESSABLE_ENTITY Import of a file that is neither a zip nor UTF-8 text, or one too damaged for its converter to open. Retrying will not fix it
429 RATE_LIMIT_EXCEEDED Global rate limiter. The house envelope; the retry seconds ride the Retry-After header — see Rate limiting
500 INTERNAL_SERVER_ERROR Export only: the stored snapshot could not be decoded, or the converter threw
503 AUTH_UNAVAILABLE Supabase token verification was unreachable

MCP connector

/api/mcp is a Model Context Protocol server (src/modules/mcp/). A person adds docs.plus to an AI app as a connector and signs in as themselves. The app's agent then reads and edits that person's documents through the tools below. It uses @modelcontextprotocol/server 2.4.0 with createMcpHandler. Every request gets a fresh server, so the endpoint holds no session between requests or replicas.

Supported hosts. claude.ai, Claude Desktop and ChatGPT add it as a remote connector. Tested against production on 2026-10-20 through dynamic client registration (DCR): Claude Code (sign-in plus all ten tools), Codex and Cursor. Other hosts, such as Copilot CLI, Cline, VS Code, LM Studio and Replit, are not tested yet (#357).

Endpoints

Route Auth What it does
GET /api/mcp/.well-known/oauth-protected-resource None RFC 9728 metadata: resource is <PUBLIC_RESTAPI_URL>/api/mcp, authorization_servers is [MCP_AUTH_ISSUER]
GET /.well-known/oauth-protected-resource and GET /.well-known/oauth-protected-resource/api/mcp None The same RFC 9728 metadata at the standard root URLs, for clients that probe instead of reading the 401 header
POST, GET, DELETE /api/mcp OAuth bearer The MCP transport. Legacy (2025) clients get GET and DELETE answered 405

PUBLIC_RESTAPI_URL unset (local) makes the metadata use the request origin. MCP_AUTH_ISSUER unset means ${SUPABASE_URL}/auth/v1. Set it to the exact issuer from Supabase's /auth/v1/.well-known/openid-configuration, or hosts reject the metadata.

Authorization

  • Supabase Auth is the authorization server. Hosts register with DCR, then run OAuth 2.1 with PKCE.
  • Only Authorization: Bearer is read. The house token header is ignored here.
  • A request without a valid token gets 401 and WWW-Authenticate: Bearer resource_metadata="…/api/mcp/.well-known/oauth-protected-resource", scope="openid email profile". The resource metadata lists the same three in scopes_supported. When a token was sent, the header also carries error="invalid_token". Hosts start sign-in from this header.
  • The token is verified with Supabase Auth (getUser, cached 60 s). An Auth outage returns 503 AUTH_UNAVAILABLE.
  • The token must carry client_id. Only an OAuth grant mints one; a browser session token never does. A token without it gets 401 with error="invalid_token", and the description says to connect through OAuth.
  • Audience is a known gap. Supabase always sets aud to authenticated and never writes the RFC 8707 resource into the token (supabase/auth#2610). So this server cannot prove a token was minted for it. The client_id rule is the strongest check Supabase allows today.
  • A request with an Origin header outside the CORS allowlist (ALLOWED_ORIGINS, else APP_URL) gets 403 before anything else. Hosted apps call from their servers and send no Origin. A browser client, such as the MCP inspector, needs its origin on that list.
  • On this server, only /api/mcp accepts a token that carries client_id. The other REST routes that need a user answer 403, and /api/admin/* does too. Routes where sign-in is optional treat the caller as signed out. The WebSocket refuses the connection.

Tools

Every tool except find_documents and create_document takes a document slug. Each runs as the signed-in person. The five read tools (find_documents, get_outline, read_document, list_chat_rooms, read_chat_thread) return text only. Other results also carry structuredContent, whose keys are snake_case like the inputs. Each tool first applies the access rule the rest of the API uses. A private document opens for its owner only. A read-only document takes document writes from its owner only.

Tool Hints What it does
find_documents read-only scope: "mine" lists the caller's documents. scope: "public" searches public documents by title and needs query. limit is at most 50. Each result says whether it is the caller's
create_document open world Makes a new document the caller owns. The title becomes its # heading, and optional markdown follows. Returns slug, title, url and version
get_outline read-only The heading tree. A heading holds every later heading until one of the same or a smaller level. Each heading line shows its title, section_id, level and rev, indented under its parent
read_document read-only The document as Markdown. With section_id, one heading and its body, plus that section's rev. Each body block is numbered [1], [2] and so on
append_to_document open world Adds Markdown at the end
edit_blocks destructive, open world In one section, removes remove_blocks blocks after block after_block (0 is right after the heading) and inserts markdown there, if rev still matches. Returns no rev: read the section again
replace_text destructive, open world In one section body, replaces old_text, found exactly once in one text run, with plain new_text, if rev still matches. Returns the new rev
move_block destructive, open world In one section, moves block from to stand after block after_block (0 is right after the heading), if rev still matches. The node moves whole, with every attribute. Returns no rev
rewrite_section destructive, open world Replaces one section body with markdown, if rev still matches. Each media block stays as it is, at the place the Markdown names it as [n]. Returns no rev
list_chat_rooms read-only The chat rooms of the document's headings. Each has the heading's section_id, title, level, message count and last activity
read_chat_thread read-only Messages in one heading's room, newest last. limit is 30 by default and at most 50. before_seq pages to older messages
post_chat_message open world Posts plain text, at most 2000 characters, in one existing heading room, as the caller

Section rules. A section body is the nodes after its heading, up to the next heading of any level. So an edit in a subsection never conflicts with its parent. No tool changes a heading node or its toc-id, so the heading's chat room and digest links stay attached. get_outline shows the containing tree for navigation; rev always hashes the heading plus its body.

Reads. A read uses the live document when this collaboration replica holds the room. Otherwise REST decodes the stored head. A write that is still saving may not show yet. Output stops at 100 000 characters, or at max_chars when smaller, and the text says where it stopped. Every picture, video, audio file and embed shows as a placeholder such as [image] or [video]. A file attachment keeps its name and loses its link. No media URL reaches the agent. The text is framed as document data, with a note that says whether the caller owns the document.

Writes.

  • Markdown goes through the import parser with no title rule. The cap is 65 536 characters.
  • A level-1 heading (#) is refused, because it is the document title. One exception: append_to_document on an empty document must start with exactly one # heading, the title.
  • An AI app changes only the blocks or text it names, never a heading, and it never deletes media. The internal hop has four section modes: blocks, text, move and rewrite. REST keeps replace and append.
  • rewrite_section is the one tool that replaces a whole section body (maintainer ruling, 2026-11-09, #719). The Markdown names each media block of the section once, by its read_document number alone on a line, such as [3]. The tool refuses a media block that is missing or named twice, a number for a block without media, a number outside the section, and a media block after a new heading, which would leave the section. The kept nodes are the original nodes, moved into place; they are never rebuilt from Markdown. Every other block is rebuilt from the Markdown.
  • move_block moves one whole node inside one section body (maintainer ruling, 2026-11-09, #720). The body holds no heading, so a move never crosses one. A move to where the block already stands is refused.
  • In edit_blocks and rewrite_section, a heading at or above the target heading's level is refused. It would move the following subsections under a new parent. A deeper heading may go only at the end of the section; anywhere else it would move the blocks after it into a new subsection.
  • edit_blocks refuses to remove a block that holds media at any depth: image, an embed, mediaUploadPlaceholder, or a link to the media route. The agent sees media only as a placeholder, so it could never restore it.
  • replace_text refuses to remove text that carries a link to the media route, because that text is a file attachment. It may add text next to it.
  • replace_text edits characters inside one Y.XmlText, so it cannot reach a block, a picture or a heading. Words repeated at both ends of old_text and new_text are not rewritten. A replacement takes the formatting of the first character it replaces, and a pure insert keeps only the marks on both sides of the caret. old_text found zero times or more than once is refused, and the text says which. If it is not found as given, Markdown escapes such as \_ are removed and it is tried once more.
  • A stale rev is refused: "The section changed since you read it. Call read_document or get_outline again, then retry with the new rev." An unknown section_id is refused with a text that names the field and points to get_outline.
  • append_to_document is at-least-once. After an unclear failure, the error tells the agent to wait about a minute and read the document before it retries. A read at once cannot see a write that is still saving.
  • A write credits the caller, never the document owner. The version row gets trigger: "mcp".
  • create_document refuses an anonymous caller. It checks markdown before it writes anything, so refused text leaves no document. The slug comes from the title through the house slug rules. A title that normalizes to nothing uses untitled. A taken slug gets a suffix. A slug that is a webapp page, such as privacy, gets -document. The document ID is random. The new document is public, like any new docs.plus document, so other people can find, open and edit it. The document row and version 1 (the title heading plus the Markdown) are written in one transaction, so a failure leaves no document. The new-document notice mail is sent after the reply. The url is APP_URL plus the slug.
  • In markdown, a line that holds only a video, audio or embed URL, such as a YouTube link, becomes a player. An image in Markdown image syntax becomes a picture. The picture keeps its source URL; nothing is uploaded.
  • A fenced code block whose language is exactly mermaid becomes a diagram. Before create_document, append_to_document, edit_blocks, rewrite_section or replace_text writes, the server parses each diagram with Pele (modules/mcp/domain/checkDiagrams.ts). It refuses an empty diagram, an unknown type, a parse error, or a diagram over 10 000 characters or 250 edges (the pad's limits, measured on real phones), and nothing is written. The text names the field and the reason, for example markdown: diagram 2 cannot be drawn. …. The check parses only; it does not lay the diagram out.

Writes and posts need ownership. append_to_document, edit_blocks, replace_text, move_block, rewrite_section and post_chat_message work only in documents the caller owns. create_document makes a document the caller owns. Any other document is refused, even a public editable one, with a text that tells the person to make the change in docs.plus. Reads follow the normal access rule.

Chat. A heading's chat room is found by the document and the heading's toc-id, so a room id is a section_id from get_outline. Rooms start lazily: a heading nobody has opened chat on has no room, so the room list is a subset of the outline. The chat tools pass the same document gate as the other tools before any chat query. A private document gives the same refusal, never an empty list. Posting needs read access and ownership, like the write tools; the read-only lock guards the document text, not chat. A post notifies room members who follow every message and are not online. A read shows the author's username, the time and the plain text, never html, and never a media path. Deleted messages are left out. The text is framed as chat data that other people wrote. Output stops at 100 000 characters by leaving out older messages, and the result gives before_seq for the next page. The message count comes from a counter that a job fills once a minute. So it can lag by about a minute, and a new room can show 0. A post removes every @, so it cannot send mention or @everyone notifications. The text is at most 2000 characters, and the stored html is at most 3000. Each line break adds 7 characters to the html, and each & adds 4. So many short lines can pass the first limit and fail the second. A post needs a live heading that already has a room; otherwise it is refused. Each post gets a new message id, so a retry after an unclear failure can post twice.

Hints. They follow OpenAI's definitions. Read tools set destructiveHint: false and openWorldHint: false. Write tools set openWorldHint: true, because documents are public by default and a write publishes. post_chat_message only adds, so it is not destructive; room members who follow every message and are away get a notification.

Server instructions. The initialize result carries instructions. They say that these tools act as the signed-in person, and that a browser session is not signed in as them. They name create_document for a new document. A host may ignore them. The server info also carries title, websiteUrl (APP_URL), description and icons (one 192 px PNG at APP_URL/icons/icon-192x192.png).

Errors. A tool error is an MCP result with isError: true. Its text gives the next step. When one argument is at fault, the text starts with that field. A bad argument never reaches the tool: the SDK answers with the failing field.

Budget and logs. Each person gets 60 tool calls a minute, kept in Redis (mcp-sub). Every request with an accepted token also spends a per-person request bucket of 300 a minute (mcp-req), so initialize and tools/list are bounded too. Over it, the transport answers 429 RATE_LIMIT_EXCEEDED with Retry-After. With no Redis, or a Redis fault, calls run without either bucket. A transport call with an accepted OAuth token skips the per-address rate limit while the address has budget left. Rate limiting gives the rules (#551). Each call logs one line with the keys tool, sub, clientId, outcome and durationMs. Arguments, headers and tokens are never logged.

Usage counts. After each call, one Redis pipeline adds to three keys for the UTC day (YYYY-MM-DD). Each key expires 35 days after its first write.

Key Type Holds
mcp:usage:<day> hash Calls per <tool>:<outcome>. A budget refusal is rate-limited
mcp:clients:<day> hash Calls per OAuth client_id
mcp:callers:<day> HyperLogLog Distinct callers (sub). It gives a count and cannot list them

The write never blocks or fails the call. It is skipped when Redis is not connected. No argument, result or document text goes into these keys. GET /api/admin/mcp/usage reads them.

GET /api/connected-apps/redirects

The registered redirect URIs of the caller's own connected apps, keyed by OAuth client_id. The webapp needs them because Supabase grants omit them. It names a known app (Claude, ChatGPT or Cursor) only when every URI is that app's exact callback, whatever name the app registered.

{
  "success": true,
  "data": { "redirects": { "<client_id>": ["https://claude.ai/api/mcp/auth_callback"] } }
}

It reads the grants with the caller's own token, then each client with the service-role key. So a caller sees only their own apps. A connected app's token gets 403. Without the service-role key, or when Supabase fails, the answer is an empty map, and every app shows as unverified.

Media

Base path /api/plugins/hypermultimedia (src/api/routers/hypermultimedia.router.ts). Backs the editor's hypermultimedia extension. Storage targets local disk when PERSIST_TO_LOCAL_STORAGE=true, otherwise S3-compatible (DigitalOcean Spaces).

POST /api/plugins/hypermultimedia/:documentId

Upload one media file. Body is multipart/form-data with field name mediaFile (not file).

Allowed MIME types, 34 in all (source of truth: src/schemas/hypermultimedia.schema.ts ALLOWED_MIME_TYPES): image/jpeg, image/jpg, image/png, image/gif, image/webp, image/bmp, image/heic, image/heif, image/svg+xml, video/mp4, video/webm, video/quicktime, video/ogg, video/x-matroska, audio/mpeg, audio/webm, audio/wav, audio/ogg, audio/mp4, audio/aac, audio/flac, audio/opus, application/pdf, text/plain, text/csv, text/markdown, application/json, application/msword, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-powerpoint, application/vnd.openxmlformats-officedocument.presentationml.presentation, application/zip. The list is a superset of the chat media allowlist, so any chat attachment can be re-hosted into a document. Max size is DO_STORAGE_MAX_FILE_SIZE (default 10 MB; see ENV.md).

Returns 201. Shape depends on the backend (type: "s3" or local), including fileType, fileName, and fileAddress. Oversized files return 413 (PAYLOAD_TOO_LARGE); disallowed types return 415 (UNSUPPORTED_MEDIA_TYPE).

A missing or invalid token is 401. A body more than 1 MiB over that cap is refused with 413 before the handler runs. The document row is then checked before the file's bytes are examined: a missing or soft-deleted document is 404. A private document the caller does not own is 403, carrying the same top-level access hint the slug read returns. A readOnly document the caller does not own is 403 too.

GET /api/plugins/hypermultimedia/:documentId/:mediaId

Stream a media file with its Content-Type. This read is charged to the larger media budget, not the global one — see Rate limiting.

The document row is checked before storage is read. A soft-deleted document is 404 NOT_FOUND in the house envelope. After Restore, the file serves again. A document with no metadata row still serves. The check reads the document that the URL names, so media under another document's prefix follows that document. A missing file is 404 with the legacy { "error": "File not found" } body. New S3 objects are private, so every public read of them goes through this route. Older objects stay public until the operator runs the Migration step in CHANGELOG.md.

A Private document's media serves only with its owner's dp_media cookie, and the response carries Cache-Control: private, no-cache. Without a valid cookie it answers 404 NOT_FOUND, the same as Trash, so the route reveals nothing (#439).

POST /api/plugins/hypermultimedia/session

Trades the caller's token for the HttpOnly dp_media cookie: one hour, SameSite=Lax, path /api/plugins/hypermultimedia. The webapp posts it after sign-in and on each token refresh, because an image request carries no token. Returns 204. A missing token is 401, and an anonymous user is 403. An unset MEDIA_COOKIE_SECRET answers 503, because Private media is then off for everyone. REST must be same-site with the webapp, or the browser does not send the cookie with an image request.

DELETE /api/plugins/hypermultimedia/session

Expires the cookie and returns 204. It takes no auth, because a signed-out page has no token and JavaScript cannot clear an HttpOnly cookie.

Link metadata

Base path /api/metadata (self-contained module at src/modules/link-metadata). Unfurls a URL through a cache → oEmbed → special → HTML-scrape pipeline with SSRF protection.

GET /api/metadata?url=<http(s) url>

url is required, must be http(s), and ≤ 2048 chars. Honors Accept-Language.

Success (200) returns the MetadataResponse contract from src/modules/link-metadata/domain/types.ts — success: true, url, requested_url, title, optional description/image/author/publisher/oembed/etc., plus cached and fetched_at. Each 200 answer sets Cache-Control (positive cache for hits, short negative cache for fallbacks) and Vary: Accept-Language.

A fallback result's favicon, when present, is this server's GET /api/metadata/icon URL for the site's origin.

Optional kind (repo only; a plain page has none) and facts (at most three { icon, text }). icon is one of location, work, posted, stars, language, updated, answers or accepted. fallback: true marks the fallback card, also on a cache hit. A card built after a miss that may clear soon, such as a special-stage miss or a cut body read, gets the short negative Cache-Control. The short entry stays 10 minutes in Redis and sends public, max-age=600. Any other card stays 24 h in Redis and sends public, max-age=3600, stale-while-revalidate=86400.

A fallback card may carry miss, which says why there is no preview. A cache hit returns the same value, and any other card has none.

miss Cause
blocked The page answered 4xx.
no-preview The page answered, but its head has no title.
unreachable The page answered 5xx, timed out or failed. Or a site API timed out, failed, hit a rate limit or answered 5xx.

A site API miss wins over the page's own miss, because that API may answer later.

A busy server answers the fallback card without caching it. Each process runs at most 64 cold link-metadata requests at once: a metadata cache miss, an image fetch, an icon fetch or an archive lookup (#787). Past that, a cache miss answers the fallback card with miss: "unreachable" and Cache-Control: no-store, and nothing is written to Redis. A cache hit is still served.

A docs.plus pad link loses its cached card when the pad's access narrows. A URL on a host in APP_HOSTS is a pad URL, and its cache key carries the pad's generation. When the pad turns Private, moves to Trash or is erased, the server sets a new generation, so no old card of that pad is read again. The next request that reaches the server then shows the pad's current state; a browser or proxy may still hold a copy for the Cache-Control time. The switch is best-effort: if Redis fails, the old cards expire by their TTL (24 h at most). A page that redirects into a pad is not cached.

Errors (400) use this module's own shape — top-level code and message, not the nested envelope:

{ "success": false, "code": "INVALID_URL", "message": "..." }

code is INVALID_URL or BLOCKED_URL (SSRF guard).

GET /api/metadata/icon?origin=<origin>

Returns the favicon for one origin's site. The server first reduces origin to its registrable domain, by the ICANN public suffix list only, so https://a.b.example.co.uk becomes https://example.co.uk. An IP origin stays as it is. A host with no registrable domain, such as a bare public suffix like https://co.uk, is a clean miss. localhost never gets this far: the SSRF check answers 400 BLOCKED_URL. The longer host is never looked up or fetched: a link written by an AI agent can hide data in a host label. Below, <origin> means that site origin.

The server fetches <origin>/favicon.ico through the same SSRF guard, with User-Agent: DocsplusBot/1.0 and Accept: image/*. It forwards no caller header. HEAD runs the same handler and sends no body.

Sometimes /favicon.ico misses: a status that is not 2xx, bytes that are not an image, or a body over the cap. The server then reads the HTML page <origin>/, at most 64 KiB, and stops at the head end (</head or <body). It takes the href of <link rel="icon">, rel="shortcut icon" or rel="apple-touch-icon", resolved against the page URL. It prefers rel="icon", then PNG or ICO, then the size nearest 32 px. It skips SVG and data: URLs, and fetches one href. A thrown favicon fetch, such as a DNS error, a timeout or the SSRF guard, ends the request without the HTML step.

The page, the chosen href and every redirect go through the same SSRF guard and the same byte cap. One 3 s timer covers every hop, the DNS checks and every body read.

origin must be a bare origin, exactly as new URL(href).origin gives it:

  • http or https, with no path, no trailing slash and no query;
  • no explicit port, so https://example.com:8443 is refused;
  • a lowercase host in punycode form: https://xn--bcher-kva.de passes, and https://bücher.de is refused;
  • at most 300 characters.
Status Body Cache-Control When
200 The icon bytes public, max-age=604800 The bytes are PNG, ICO, GIF, JPEG or WebP. Content-Type comes from the bytes, never from the upstream site.
400 { success, code, message }, module shape public, max-age=86400 INVALID_URL: origin is missing, repeated, too long or not a bare origin. BLOCKED_URL: the SSRF guard refused it.
204 Empty public, max-age=86400 A clean miss: upstream 4xx other than 408 and 429, a 204, a 3xx with no Location, an empty body, bytes that are not one of the five types, or a body over the cap.
204 Empty public, max-age=600 An error miss: a timeout, a network or DNS error, the SSRF guard on any hop, too many redirects, or upstream 5xx, 408 or 429.
204 Empty no-store Busy: the process already runs 64 cold link-metadata requests (#787). Ask again later.

A miss answers 204, not 404, because Chrome logs a console error for every image that gets a 404. An <img> still fires onerror on the empty 204. A miss is max-age=600 when any step had an error miss, and max-age=86400 otherwise.

The body cap is LINK_ICON_MAX_BYTES bytes, default 32768. Each request holds up to that many bytes in memory, plus up to 64 KiB of HTML. SVG, HTML and CUR files are always a miss. The route sends no ETag and keeps nothing in Redis, so the browser HTTP cache does all the caching.

The route has its own rate limit. See Rate limiting.

Accepted risk. safeFetch checks the DNS answer and then connects in a separate step. A host that changes its DNS answer between those two steps can reach a private address. This route returns bytes from that fetch. So the leak is limited to bytes that pass the image check, up to the cap, within 3 s. The HTML step lets a site's own page name any public image URL for the server to fetch. That URL gets the same guard, cap, sniff and timer.

GET /api/metadata/image?url=<http(s) url>

Takes a page URL and relays its page image (PNG, ICO, GIF, JPEG or WebP, up to 2 MiB) through the SSRF guard. SVG never passes. A miss is an empty 204. The reader's browser never contacts the linked site. url is the page URL, with the same rules as GET /api/metadata.

The server runs the same pipeline as GET /api/metadata, usually a cache hit, and takes the page image (image.url) from that result. That is an og:image, or an oEmbed or site thumbnail. A fallback result has no image. It fetches that one URL through the SSRF guard, with User-Agent: DocsplusBot/1.0 and Accept: image/*, a 5 s timer and a 2 MiB cap. The timer covers only that fetch; on a cache miss the pipeline runs first. When the image declares a Content-Length of 2 MiB or less, the route sniffs its first bytes and then streams the rest. The 200 is sent chunked. A body shorter or longer than it declared ends the transfer without its last chunk, so the browser drops it. An image with no declared length is read whole first, and at most 32 such reads run at once (#786). The 200 and 204 answers set Vary: Accept-Language, because the pipeline reads that header.

Status Body Cache-Control When
200 The image bytes public, max-age=86400 The bytes are PNG, ICO, GIF, JPEG or WebP. Content-Type comes from the bytes, never from the upstream site.
200 The image bytes public, max-age=600 As above, when the page card was built after a special-stage miss or a cut body read.
400 { success, code, message }, module shape none INVALID_URL: url is missing or not a valid http(s) URL.
204 Empty public, max-age=600 No image: a fallback page, no page image, the SSRF guard, a timeout, a non-2xx answer, SVG or other bytes, or an oversized body.
204 Empty no-store Busy: the process already runs 64 cold link-metadata requests (#787), or 32 images with no declared length are being read. Ask again later.

It shares the /api/metadata rate-limit bucket. See Rate limiting.

A docs.plus pad link never leaves the process. When the page image is this server's own card.png (same origin as PUBLIC_RESTAPI_URL), the route reads it in process. Over the network, every reader's hover would arrive from the server's one address and share one card bucket. A 302 from the card still goes over the network, to the Fallback card on the web app host.

Accepted risk. The same DNS rebinding risk as the icon route is accepted here, limited to sniffed image bytes up to 2 MiB within 5 s.

GET /api/metadata/archive?url=<http(s) url>

Finds the Wayback Machine's closest copy of a page. The webapp calls it only when a reader clicks "View archived copy" on the no-preview card. url has the same rules as GET /api/metadata.

The server asks the availability API, https://archive.org/wayback/available?url=<url>, through the same SSRF guard. It sends LINK_PREVIEW_USER_AGENT and reads at most 64 KiB, within one 4 s timer. It never fetches the page itself and never resolves its host. It never calls Save Page Now, so it never asks archive.org to save a page.

Before the lookup, the server drops tracking params and the fragment from url. A docs.plus pad URL (a host in APP_HOSTS) is never sent to archive.org, so a Private pad's slug stays on our server. It answers miss: "none".

The API names snapshots with http://. The server upgrades the scheme, then accepts only a URL whose origin is exactly https://web.archive.org and whose path starts with /web/. Any other URL is a miss.

Status Body Cache-Control When
200 { success: true, url, snapshot: { url, timestamp } } public, max-age=3600 The archive holds a copy. timestamp is ISO 8601 in UTC.
200 { success: true, url, snapshot: null, miss: "none" } public, max-age=600 The archive holds no copy, its snapshot URL failed the check, or url is a pad URL.
200 { success: true, url, snapshot: null, miss: "unreachable" } no-store archive.org timed out, failed, or answered non-2xx or a body that is not JSON. Or the server was busy (#787).
400 { success, code, message }, module shape none INVALID_URL: url is missing or not a valid http(s) URL. BLOCKED_URL: a private or local address.

url in the body is the canonical URL the server asked about. Redis keeps a hit for 1 hour and none for 10 minutes, under meta:archive:v1:{sha1(url)}. It never keeps unreachable. The log line names the host only. The route shares the /api/metadata rate-limit bucket. See Rate limiting.

Email

Base path /api/email (src/api/email.ts). Notification delivery runs through a pgmq consumer, not HTTP: email_queue → pg_cron → pgmq → worker → BullMQ → the configured provider, SMTP or Resend. The /api/email/send and /api/email/send-digest endpoints were removed. Digests send only through the queue. Most endpoints below are internal triggers and webhooks. send-generic, bounce and preview/:type require the service-role key. webhooks/resend takes a signature instead. health, status, validate, and both unsubscribe routes need no credential. A rejected JSON or query body on send-generic, bounce, validate, and POST /unsubscribe is the house envelope (VALIDATION_ERROR), not a raw Zod body.

POST /api/email/send-generic

Send one email directly. Body: to, subject, html, optional text, replyTo (validated by sendGenericEmailSchema). Returns { "success": true, "message_id": "..." }, where message_id is the queue job id. Without Redis, the mail sends once, inline, and message_id is the provider's message id. A failed or skipped inline send answers 500 with error, and nothing sends it again.

POST /api/email/bounce

Record a provider bounce event. Body: email, bounce_type, optional provider, reason. Hard bounces auto-suppress the user; returns { "success": true, "bounce_id": ..., "auto_suppressed": <bool> }.

POST /api/email/webhooks/resend

Receives Resend delivery events. The route exists only when RESEND_WEBHOOK_SECRET holds a valid secret. Otherwise it answers 404. The source is src/modules/email-webhooks/.

The request carries no key. The route checks the Svix signature instead: an HMAC-SHA256 over <svix-id>.<svix-timestamp>.<raw body>, keyed by the decoded whsec_ secret. It refuses a svix-id that does not match ^msg_[A-Za-z0-9]{1,64}$. It refuses a timestamp more than 5 minutes from server time, in either direction. Every refusal answers the same 401 body and logs email webhook signature rejected with a reason.

Event Action
email.bounced Permanent only: a hard row, with the bounce subType as the reason
email.complained a complaint row
email.suppressed a hard row, reason resend-suppressed
email.failed no row; an operator error line, so incident-email-operator fires
anything else none

Each row goes through record_email_bounce, one row per address in to. An event with several addresses is not atomic. If a later address fails, the key is released, and the retry can write an earlier address again. A hard or complaint row turns email off for that person. An event whose ns tag names another environment is ignored. An event with no ns tag, such as Supabase Auth mail, still counts.

Each svix-id is recorded once. The Redis key email:webhook:<svix-id> is pending for 60 s while one request records it, then done for 24 h. Without Redis there is no dedupe.

Status Meaning
200 Recorded, ignored, or already recorded. Body { "success": true, "data": { "received": true } }
400 The signed body is not JSON
401 The signature check failed
409 Another request is still recording this svix-id; Svix retries later
413 The body is over 64 KiB
500 A row was not written; the key is released, so a retry records it
503 Redis failed before the claim, so nothing was written

GET /api/email/health

Email gateway status (no auth). Public, so it returns status only: { "status": "ok" | "degraded", "queue_connected": <bool> }. ok means email is ready and the queue is connected. The provider, the config detail and the queue counts are on GET /api/admin/email/setup (see Admin).

GET /api/email/status

{ "operational": <bool>, "timestamp": "..." } (no auth).

POST /api/email/validate

Public magic-link check. Body: { "email": "<string>" }. Returns { "isValid": <bool> } on HTTP 200 for both results. Uses the house regex, then an MX lookup. Does not return MX records or DNS errors. Success is not wrapped in ok(). A missing or non-string email is the house envelope (VALIDATION_ERROR on 400).

GET /api/email/preview/:type

Render a template (notification or digest) with sample data, as HTML. Service-role only.

GET /api/email/unsubscribe?token=

The email link. No auth (the token is the credential). Verifies the token in lib/unsubscribeToken.ts and returns an HTML page with an Unsubscribe button. It changes nothing. Mail link scanners open every link, so a GET must never write.

POST /api/email/unsubscribe?token=

The only route that writes. It applies the change through the apply_unsubscribe Supabase RPC. The confirm page's button posts the form field confirm=yes and gets an HTML result page. Any other body gets JSON ({ "success": true } or an { "error": ... } body). That covers the RFC 8058 List-Unsubscribe=One-Click post from mail clients.

Admin

Base path /api/admin (src/api/routers/admin.router.ts). Every route requires a valid Supabase JWT for a user present in admin_users. The tables below list the routes the dashboard uses most, grouped as in the router. GET /openapi.json is the complete list.

Two audit routes are easy to misread. /audit/media-storage and /audit/media-storage/summary report the Supabase chat media bucket, not editor media.

Dashboard & users

Method Path Purpose
GET /stats Dashboard overview stats
GET /push/gateway Push gateway status
GET /users/document-counts Document count per user
GET /users/admins All admin user IDs
POST /users/:id/toggle-admin Grant or revoke admin
DELETE /users/:id Soft-delete one account

DELETE /users/:id clears the profile, removes the avatar and bans the user. It turns off push and email, removes the push subscriptions and drops pending queued email. The email address is kept. It answers 409 { error } for an unknown id or an admin, and 400 VALIDATION_ERROR for an id that is not a UUID. A 500 may leave the profile cleared. Retry: every step is safe to repeat.

Documents

Method Path Purpose
GET /documents List documents (paginated)
GET /documents/stats Document statistics
PATCH /documents/:id Update document flags
GET /documents/:id/deletion-impact Preview deletion cascade
DELETE /documents/:id Delete (requires confirmSlug in body)
GET /documents/:slug/views View stats for one document
GET /documents/:slug/preview Content preview

View analytics

Method Path Purpose
GET /stats/views Overall view summary
GET /stats/views/top Top viewed documents
GET /stats/views/trend View trend series
GET /stats/views/batch-trends Per-document sparkline trends

Retention & activity

Method Path Purpose
GET /stats/retention DAU/WAU/MAU
GET /stats/user-lifecycle Lifecycle segments
GET /stats/dau-trend Daily active users trend
GET /stats/activity-heatmap Activity by hour
GET /stats/top-active-documents Most active by message count
GET /stats/communication Communication stats
GET /stats/notification-reach Notification delivery stats

Stale documents audit

Method Path Purpose
GET /documents/stale/summary Stale summary
GET /documents/stale List stale documents
POST /documents/stale/bulk-delete Bulk delete stale

All three answer 500 when the view-stats read fails or Supabase is not set. The bulk delete then purges nothing (#578).

Notification audit

Method Path Purpose
GET /audit/notifications/health Combined health score
GET /audit/notifications/push-failures Push failure breakdown
GET /audit/notifications/email-failures Email failure/bounce breakdown
GET /audit/notifications/failed-subscriptions Failed push subscriptions
GET /audit/notifications/email-bounces Bounce list
POST /audit/notifications/disable-failed Disable dead subscriptions
GET /audit/notifications/dlq BullMQ dead-letter contents

The dlq route returns push and email, each with jobs and count. Each job is a summary: id, name, timestamp, type, failureKind, failureCode, a masked to list, and failedReason. It never returns the job data, which holds the raw address and the mail body.

Email digest

Method Path Purpose
GET /email/digest-grouping Digest grouping and size cap
PUT /email/digest-grouping Set digest grouping or size cap

Both answer { grouping, maxKb }. grouping is document (one mail per document, the default) or aggregate. maxKb is an integer from 10 to 102. The PUT body takes either field or both. The values live in Redis, so the PUT answers 503 without Redis.

MCP connector usage

Method Path Purpose
GET /mcp/usage?days=1..35 Tool call counts, distinct callers and connected apps

days defaults to 7. The data holds available (false when Redis is off), days (per UTC day, oldest first: day, calls, callers), callers (distinct across the window), tools (tool, outcome, calls), apps (calls grouped by app name) and registeredApps (each registered OAuth client: name, createdAt, redirectOrigins). Each callers value is a number, or the string '<5' for 1 to 4 people, so an exact small count never leaves the server. registeredApps is null when Supabase Auth cannot list the clients. Counts are grouped by app name, never by client id or caller. A deleted client counts as Unknown app, and so does every client when the list fails. The server asks for up to 1000 clients in one call. If Supabase Auth ever pages the list, the clients past that page also count as Unknown app, and the server logs a warning. Success uses the house envelope.

Email setup

Method Path Purpose
GET /email/setup Email config status, checks and lines to add
POST /email/setup/test-send Send one test email to yourself

The module lives in src/modules/email-setup/. Both routes use the house envelope. The page only reads: no route writes .env or any secret.

GET returns status (ready, off or invalid), problems for invalid, provider and from (EMAIL_FROM in full). It also returns namespace, smtp (host, port), publicUrl, and secrets, which holds set or missing for RESEND_API_KEY, SMTP_USER, SMTP_PASS and EMAIL_UNSUBSCRIBE_SECRET. webhook holds the secret state (set, missing or invalid) and the webhook URL. connection is a live provider check on each read, bounded at 10 s. It is an object with a state: ok, failed with kind and code, timeout, or skipped when email is not ready. An ok state can carry note: 'send_only_key'. latestBounce is also an object with a state: none, unavailable or found. A found bounce carries email (masked), bounceType, provider, reason (at most 80 characters) and bouncedAt. queue holds connected, pending and the email dlqDepth. envToAdd lists the .env lines to add, blank where the value is a secret or unknown.

POST /email/setup/test-send takes no body. It sends through deliverEmail to the signed-in admin's own address, with the key <namespace>/inline/<uuid>. It answers { "sent": true, "messageId", "to" } with to masked, or { "sent": false, "kind", "code" }. One send per admin per minute: past it, 429 RATE_LIMITED. Without Redis, 503, because the limit fails closed. 400 NO_EMAIL when the account has no address.

Ghost accounts audit

Method Path Purpose
GET /audit/ghost-accounts List ghost accounts
GET /audit/ghost-accounts/summary Category summary
GET /audit/ghost-accounts/:id/impact FK dependency check
DELETE /audit/ghost-accounts/:id Smart-delete one
POST /audit/ghost-accounts/bulk-delete Bulk delete (max 50)
POST /audit/ghost-accounts/resend-confirmation Resend magic link
POST /audit/ghost-accounts/cleanup-anonymous Clean stale anon sessions

Both ghost-account delete routes check each id again before they delete. They refuse a user who signed in after the list loaded, an admin, and an unknown id. DELETE /audit/ghost-accounts/:id then answers 409 with { error }. A non-uuid id answers 400 VALIDATION_ERROR. The bulk route counts a refused id under failed and adds a line to errors. A failed impact read or admin read also stops the delete. So does an Auth read error other than 404. The single route answers 500, and the bulk route counts the id as failed. A soft delete bans the user and clears the public profile: name, photo, bio and links. It also removes the user_avatars objects and sets the username to deleted_ plus 12 hex characters of the id. It turns off push and email the same way DELETE /users/:id does. A failed avatar, ban, push or queued-email step answers 500 on the single route. The bulk route counts that id as failed.

Push notifications

There is no HTTP push endpoint — /api/push was removed. Push delivery runs through pgmq the same way email does. A Supabase trigger enqueues to pgmq, and the worker polls it and delivers via BullMQ and the Web Push API. Devices register through Supabase RPCs:

await supabase.rpc('register_push_subscription', {
  p_device_id: 'unique-device-id',
  p_device_name: 'Chrome on MacBook',
  p_platform: 'web',
  p_push_credentials: { endpoint: '...', keys: { p256dh: '...', auth: '...' } }
})

await supabase.rpc('unregister_push_subscription', { p_device_id: 'unique-device-id' })

Admins read the gateway status on GET /api/admin/push/gateway: vapid_configured, vapid_subject, queue_connected, pending_jobs, failed_jobs and sent_last_hour. It always answers 200 with the status, even when push is not set up.

Rate limiting

Five Redis-backed limiters (src/middleware/index.ts) cover every non-OPTIONS request except /health, /health/* and a verified /api/mcp call. All five are keyed on client IP alone, and when Redis is unavailable, rate limiting is disabled (requests pass). User-Agent is not part of the key: a client that varied that header earned a fresh budget on every request. Requests with no x-forwarded-for and no x-real-ip (direct/internal traffic) skip all five.

The global limit is RATE_LIMIT_MAX requests (default 100) per 15-minute window. Production runs 500. There is no separate per-role tier in the REST middleware, so a service-role caller shares the same per-IP budget as a browser. Issue #166 tracks whether that should change.

Public media reads have their own, larger budget. A GET under /api/plugins/hypermultimedia/ is charged to a second limiter, which holds ten times the global points over its own 15-minute window. So a pad holding 20 images does not spend 20 points of the global budget on a cold load. The upload POST on that path stays on the global budget, as does every route not named below. The multiplier is a constant in the middleware, not an environment variable.

Favicons have their own budget too. GET and HEAD on /api/metadata/icon are charged to a third limiter. It holds ten times the global points over its own 15-minute window. A cold pad spends one point for each distinct link origin, so a page full of links does not spend the global budget. Like the media multiplier, this one is a constant in the middleware.

Link previews have their own budget (maintainer ruling, 2026-10-26). GET /api/metadata, GET /api/metadata/image and GET /api/metadata/archive share a fourth limiter, with ten times the global points over its own 15-minute window. A hovercard spends one point on its metadata and one on its page image. A click on "View archived copy" spends one more. So hovering many links never spends the budget that pad saves and chat calls need. This multiplier is a constant in the middleware too.

The social card has a fifth budget. GET and HEAD on /api/documents/:documentId/card.png are charged to their own limiter, with four times the global points over its own 15-minute window. Crawlers fetch the card from their own addresses, so they never spend a reader's budget. The hovercard relay reads the card in process and spends none of it.

A verified /api/mcp call skips the global limiter (#551). It must be a POST, GET or DELETE on /api/mcp whose bearer token the MCP transport accepts. Supabase Auth must verify the token. It must carry a client_id claim and no past exp. It spends two per-person buckets instead: 300 requests a minute for every call, and 60 tool calls a minute for its tool calls. A missing, fake, invalid or browser-session token, an Auth outage, and the MCP resource-metadata routes (.well-known/oauth-protected-resource) still spend the global budget. A hosted AI app sends many people from one address, so the person is the fair unit. The server checks the token only while the address has global budget left. So a call from a spent address gets a 429 before its token is checked, even a token that would pass. That keeps a spent address from making Supabase Auth calls. A token with no client_id claim or a past exp is refused before the Auth call.

A response that a limiter charges carries X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset (ISO timestamp). A verified /api/mcp call carries none of them. A media read, an icon read, a link-preview read and a card read report their own limiter's numbers in those headers. On 429, the body is the house envelope with code RATE_LIMIT_EXCEEDED, and a Retry-After header carries the seconds until the window resets.

WebSocket API

The collaboration server (src/hocuspocus.server.ts, default port 4001) speaks the Hocuspocus protocol over Y.js. Connections authenticate with a JWT passed in the Hocuspocus token field (JSON with accessToken, slug, deviceType).

import { HocuspocusProvider } from '@hocuspocus/provider'

const provider = new HocuspocusProvider({
  url: 'ws://localhost:4001',
  name: documentId,
  // A function, so a reconnect after the 4408 close sends a fresh token.
  token: async () =>
    JSON.stringify({ accessToken: await getAccessToken(), slug, deviceType: 'desktop' })
})

The document name is the room id (Prisma documentId); the server never trusts a client-supplied id in the token for authorization. A room name outside [A-Za-z0-9_-], 1 to 100 characters, is refused (#426).

A signed-in socket closes with code 4408 at its access token's exp. A client should reconnect with a fresh token, and the server then checks the identity again. The webapp provider does this. In production, a token already past exp is refused like an invalid one. Elsewhere, it falls back to anonymous (#430).

One inbound message may be at most 16 MiB. A larger message closes the socket with code 1009 (#651).

Private documents

Breaking change (shipped): isPrivate now allows the owner only (user.sub === ownerId). Anonymous and signed-in non-owners are rejected — previously any signed-in (non-anonymous) user could connect. Ownerless-private rooms (ownerId: null) reject everyone until owner backfill. When the metadata lookup fails, the server can no longer determine privacy, so it fails closed (rejects) instead of admitting the connection as public. A successful public-doc lookup still connects without auth. The decision is a pure resolver (src/lib/wsAccess.ts) with a matrix unit test.

Read-only: When readOnly is true and the connector is not the owner, the connection is marked read-only on the write path (existing behavior).

See the Hocuspocus documentation for the wire protocol.