apps/api)Owner: WP-C. ADRs 0022 (API-first), 0011 (auth), 0023 (security), 0021 (topology), 0301-0305 (service design). Contracts: shared/src/api.ts (route table + schemas), schema.ts, auth-token.ts, realtime half in messages.ts/codec.ts. Generated spec: docs/api/openapi.json.
Every route in API is implemented.
apps/realtime and against a protocol-level peer for error paths.503 unavailable until the wave-2 tier exists (LINORA_DOCWORKER_URLS empty).@linorahq/doc/json, /keys and /empty, through src/doc-interop.ts.One versioned surface, /v1, used by the web app, the MCP adapter, scripts and future integrations alike.
| Area | Routes (see API in shared/src/api.ts) |
Tier |
|---|---|---|
| Auth | signup, login, logout, me, realtimeToken | api |
| Sessions | listSessions, revokeSession, revokeOtherSessions (browser session only; ADR 0307) | api |
| Tokens | listTokens, createToken (scopes, project allow-list, expiry), revokeToken | api |
| Projects & members | list/create/update/delete project, list/add/update/remove member, listAudit | api |
| Files & pages | list/create/get/update/delete file, allocClientId, create/update/delete page | api |
| Content | snapshot (gzip binary), applyOps (JSON or application/vnd.linora.ops) |
api / realtime |
| Queries | summary, outline, getNodes, searchNodes, changes, render (PNG/SVG) | docworker |
| Realtime | WS /v1/realtime?file= : ops, ACK verdicts, broadcasts, presence |
realtime |
Conventions:
format: uuid|email.ApiError with stable codes. fields maps JSON paths to messages."client:counter". Query results are paged with opaque cursors, field selection, depth limits, and minSeq for read-your-writes. Timestamps are ISO-8601.docs/api/openapi.json by tools/gen-openapi.mjs (--check fails when stale; apps/api/test/openapi.test.ts runs it). Each operation carries x-linora-scope, x-linora-role and x-linora-tier.linora_session cookie (HttpOnly, SameSite=Lax, 30-day sliding; __Host-linora_session + Secure in production). The variant is chosen per request from Host: in production, only a host listed in LINORA_COOKIE_INSECURE_ORIGINS (plain-HTTP LAN origins, where browsers drop Secure cookies) gets linora_session without Secure, and only that host reads it (ADR 0905).
X-CSRF-Token and an allowed Origin (LINORA_ALLOWED_ORIGINS, or same origin as Host).X-CSRF-Token response header of signup, login and GET /v1/me, and in the readable linora_csrf cookie.Content-Type: application/json.Authorization: Bearer linora_pat_.... An Authorization header always wins over cookies. PATs cannot call logout, token routes or session routes (SESSION_ONLY), so a leaked PAT cannot mint others or sign its owner out. A PAT with a project allow-list cannot create projects.404.403.404.clientGrant, the batch runs in the API’s own id space (SET/DELETE only; CREATEs would be foreign_id).POST .../client-ids first. Then send clientGrant with a strictly increasing clientSeq; clientSeq without a grant (or a grant without it) is 400.503 busy / 429 on clientSeq k, resend k and every later batch, in order (realtime ordering rule).X-Linora-Client-Grant / X-Linora-Client-Seq.ETag: "pageId:seq", X-Linora-Seq, Content-Encoding: gzip, Cache-Control: private, no-cache (the URL serves the newest seq, so copies are revalidated; ADR 0311); If-None-Match gives 304.POST /v1/files/:fileId/pages/:pageId/ops:
files:write scope, editor role on the file’s project). The page must belong to the file (cached page -> file map).@linorahq/doc/json + the shared codec); a binary body is passed through byte for byte.kind: 'agent' and scp for PATs.mode: 'write': no tail, broadcasts or presence, invisible to peers.ScanBatch, owner StructIndex.check, sequence, journal, broadcast.{seq, applied, rejected: [{index, reason, hint}]} after the ACK.
reason is the Reject name (NODE_MISSING, …). hint is an op-aware fix suggestion from @linorahq/doc/json, the same text the MCP shows.apps/api/src/
main.ts process entry: config (refuses to start without secrets), /v1 server, metrics + health port, drain
server.ts createApi: App wiring, node:http server, security/CORS headers, error mapping, timers
router.ts route table -> matcher; pipeline: CORS -> IP limit -> authn -> session-only -> CSRF ->
user/PAT limits -> scope -> tenant/role -> body/query limits + schema -> handler
context.ts App (deps), Ctx (per request), authorize() (tenant isolation)
config.ts API env (ports, origins, cookies, limits, realtime/doc-worker URLs)
http.ts HttpError, cookies, bounded body reader + process-wide body budget, query coercion
access.ts membership/file/page caches (TTL, invalidated by linora_auth)
ratelimit.ts token buckets + global sync (RateSync), in-flight gate, TTL cache (bounded)
events.ts NOTIFY senders (in-transaction) + linora_auth listener (cache invalidation)
audit.ts audit_log writes, rate-aggregated login failures
doc-interop.ts the only @linorahq/doc bridge: JSON -> op list, page keys, empty snapshot, reject names/hints
auth/ password.ts (argon2id, capped), credentials.ts (sessions, PATs, caches),
realtime-token.ts (claims + minting)
routes/ auth, sessions (list/revoke own), tokens, projects (+members, audit), files (+pages)
content/ snapshot.ts (streaming), ops.ts (applyOps), realtime-link.ts (writer-mode WS pool)
queries/ routes.ts (proxy handlers), docworker.ts (rendezvous hash, svc token, streaming)
linora_auth (LISTEN). A LISTEN reconnect clears them. The API also applies its own events locally right after commit.
user|project -> role, including “not a member”), file -> project, page -> file: 30 s TTL.LINORA_API_CACHE_MAX (50k entries each).last_used_at is flushed in one UPDATE every 30 s.LINORA_API_RATE_*; ADR 0306):
api_rate_buckets (UNLOGGED) in one statement every LINORA_API_RATE_SYNC_MS (250). Overshoot is bounded by one tick and repaid as debt. If Postgres fails, limits fall back to per replica. LINORA_API_RATE_STORE=local disables the sync.LINORA_TRUSTED_PROXIES (IPs/CIDRs: the edge, the hosted MCP). IP keys bucket IPv6 by /64 (SR-06, SR-10).LINORA_API_RATE_MEMBER_LOOKUP_*; SR-19 enumeration).LINORA_SIGNUP=open|invite. The default is invite in production and open in dev/test. Invite admits only LINORA_SIGNUP_ALLOWLIST entries (exact addresses or @domain), checked before any account lookup.LINORA_API_RATE_SEARCH_*), plus at most 1 search in flight per user and 4 per IP on each replica (LINORA_API_SEARCH_USER_INFLIGHT, LINORA_API_SEARCH_IP_INFLIGHT); 429 + Retry-After beyond.LINORA_API_BODY_BUDGET, 64 MiB) bounds buffered bodies over 64 KiB; when it is full, requests get 503.413, a declared body up to 8 MiB is drained (not buffered) so clients see the response; larger or undeclared bodies close the connection.LINORA_ARGON2_CONCURRENCY (default 2) hashes at once (64 MiB each), queue bounded (LINORA_ARGON2_QUEUE), then 503. Unknown accounts run a dummy verify so timing does not reveal them. Weaker hashes are re-hashed on login.nosniff, CSP default-src 'none'; frame-ancestors 'none', X-Frame-Options: DENY, Referrer-Policy: no-referrer, CORP same-site; HSTS in production.Cache-Control: no-store.NOTIFY linora_file (pages_changed); realtime pushes file_event. File rename sends file_renamed.NOTIFY linora_auth.LINORA_BLOB_STORE; ADR 0308) through a 64 KiB buffer with backpressure. A missing blob is 503.substring slices (STORAGE EXTERNAL); the next slice is fetched only after the socket drains.[A-Za-z0-9._-] segments) are refused by the store.LINORA_DOCWORKER_LARGE_PAGE_BYTES (1 GiB) go to the large-memory pool LINORA_DOCWORKER_LARGE_URLS. So does a page a regular worker refused as too large: it is retried once and remembered for 10 min (ADR 0706).{typ:'svc', svc:'api', fid} (ADR 0304).Retry-After and X-Linora-Seq back. Timeout 10 s.LINORA_API_METRICS_PORT (default 9465) serves /metrics and /healthz, kept off the public port.
linora_api_request_ms{route} histograms and linora_api_responses_total{class}.Token keys (ADR 0310): the API holds rt (user realtime tokens) and svc:api (doc-worker calls): LINORA_TOKEN_KEYS_RT + LINORA_TOKEN_KEYS_SVC_API, or the dev master LINORA_TOKEN_KEYS. Database: the linora_api role.
Env: LINORA_API_PORT (8787), LINORA_API_HOST, LINORA_ALLOWED_ORIGINS (normalised like an Origin header: lower-case, no default port), LINORA_COOKIE_SECURE, LINORA_COOKIE_INSECURE_ORIGINS (plain-HTTP, non-loopback origins that are also allowed; ADR 0905), LINORA_REALTIME_URL (public base in RealtimeTokenRes.url), LINORA_REALTIME_SAME_ORIGIN (1 = a token requested from an allowed origin carries that origin’s own ws(s) URL; others get LINORA_REALTIME_URL; ADR 0905), LINORA_REALTIME_INTERNAL_URL (default = public), LINORA_DOCWORKER_URLS, LINORA_DOCWORKER_LARGE_URLS, LINORA_DOCWORKER_LARGE_PAGE_BYTES (1 GiB), LINORA_TRUSTED_PROXIES (IPs/CIDRs whose X-Forwarded-For is honoured), LINORA_API_RATE_STORE (pg), LINORA_API_RATE_SYNC_MS (250), LINORA_API_DB_POOL (16), LINORA_API_RATE_{IP,USER,TOKEN}_{PER_SEC,BURST}, LINORA_API_AUTH_BURST, LINORA_ARGON2_CONCURRENCY, LINORA_ARGON2_QUEUE, LINORA_API_BODY_BUDGET, LINORA_API_CACHE_TTL_MS, LINORA_API_CACHE_MAX, LINORA_API_METRICS_PORT.
docs/api/openapi.json is generated and current. Every route has auth, scope and role, and a test for 401/403/404 (foreign tenant): test/tenancy.test.ts walks the whole route table.test/pipeline.test.ts).test/pipeline.test.ts runs apps/realtime and sends one batch both ways; it covers 7 different rejection reasons, identical on both paths.npm run bench -w @linorahq/api: p99 5.6 ms, p50 2.3 ms, 0 errors (median of 3 runs, M4 Pro, API and Postgres on one machine).