SPB Git

Repository Public

BACKEND_CONTRACT.md 11.0 KB 117 lines markdown

1# Backend contract used by the native apps23Backend: `note-spboucher-ai` (Next.js route handlers, PostgreSQL). Production: `https://note.spboucher.ai`. Native additions live on the4branch `native-sync` (commit 31b354d, owned by the macOS session) and run for tests on `M4M64c` at `127.0.0.1:8482` (database5`note_native_dev`, never production data).67## Test server89    ssh -N -L 8482:localhost:8482 M4M64c          # tunnel → http://localhost:848210    ssh M4M64c 'bash -lc "cd ~/dev/note-native && set -a && . ./.env && set +a && node_modules/.bin/tsx scripts/dev-session.ts"'   # prints a session token1112The test server runs in production mode: the cookie is `__Host-note_session=<token>` there as well. Mutating requests need13`Origin: http://localhost:8482` on the test server and `Origin: https://note.spboucher.ai` in production. Do not modify that worktree and14do not reset its database.1516## Transport rules (all routes)1718- Authentication = session cookie `__Host-note_session=<token>` (43-character base64url token). Without it: `401 {"error","code":"unauthenticated"}`.19  The token is rotated by a step-up (`/api/auth/reauth/verify` answers a new `Set-Cookie`; the old token stays valid 60 s).20- Every mutating request (POST, PATCH, PUT, DELETE) must carry `Origin: <app origin>` exactly; otherwise `403 code csrf`.21- `Idempotency-Key: [A-Za-z0-9_-]{8,100}` on a mutating request: runs at most once per session; a retry returns the stored JSON answer22  with header `idempotent-replay: true`; `409 code in_progress` while the first one is still running; `422 idempotency_mismatch` if reused for another request.23- `x-request-id: [A-Za-z0-9_-]{8,64}` is echoed in the answer and in the server log.24- Errors: JSON `{ "error": "<message>", "code"?: "<stable code>", ...extra }` with the HTTP status. Codes used: `unauthenticated` (401),25  `reauth_required` (403: a passkey verification younger than 5 minutes is needed), `csrf` (403), `conflict` (409, with `server`), `bad_document` (400/413),26  `rate_limited` (429), `not_enrolled`, `confirm_expensive` (409, with `plan`), `not_configured` / `no_model` (503), `in_progress`, `bad_idempotency_key`.27- User-Agent of the native apps: `SPNotes/<x.y.z> (iPhone|iPad|Macintosh; <os>) native` → the session is labelled "SP Notes · iPhone|iPad|Mac".28- Dates are ISO 8601 strings with milliseconds (`2026-11-18T19:07:04.808Z`).2930## Change feed3132`GET /api/sync?since=<rev>&limit=<1..500, default 200>` →3334    { cursor, head, more, reset, serverTime, workspace: {id, name}, user: {displayName},35      pages: [{ id, parentId, databaseId, type, section, title, icon, cover, content, properties, position, pinned, archived, version,36                wordCount, createdAt, updatedAt, lastOpenedAt, deletedAt, inboxAt, captureKind, rev, tags: [sorted names] }],37      attachments: [{ id, pageId, filename, mime, size, sha256, pageCount, createdAt, deletedAt, rev }],38      tombstones: [{ id, kind: "page" | "attachment", rev, deletedAt }],39      tags: [{ name, color }] }            // complete tag list of the workspace on every call4041`rev` is a single sequence bumped by database triggers on every write whatever the code path (trash, restore, tags, triage, agents,42imports); purges leave tombstones; opening a note (`lastOpenedAt`) does not count. `since=0` = full copy; call again while `more`;43`reset: true` (the cursor is ahead of the server: database restored) → start again from 0. Send `cursor` back unchanged next time.44Every state is included (trash, archives, inbox, database row pages). A client recognises the echo of its own write by comparing45`version` with the one its PATCH returned.4647## Pages4849- `POST /api/pages` `{ id?: uuid, title?, parentId?, section?: notes|documents|databases|projects|research, type?: page|database|research, content?, icon?, properties? }`50  → `201` full page row. With a client `id` that already exists (even in the trash): `200`, header `x-existing: 1`, the stored page as is.51  A parent purged meanwhile → created at the root.52- `GET /api/pages/<id>` → full row + `breadcrumb`, `backlinks` (trashed pages included). `?head=1` → `{id, version, updatedAt, deletedAt}`. `?open=1` touches lastOpenedAt.53- `PATCH /api/pages/<id>` `{ title?, content?, icon?, cover?, properties?, parentId?, section?, position?, pinned?, archived?, versionReason?, baseVersion? }`54  → `{ id, version, updatedAt, title, wordCount }`. `title`, `content`, `properties` are versioned: with `baseVersion` the write only happens if the55  page is still at that version, else `409 { code: "conflict", server: { version, title, content, properties, updatedAt } }` and nothing is written.56  Other fields are not version-guarded. The server assigns missing block ids to the content it stores (the client should send them itself).57- `POST /api/pages/<id>/resolve` `{ choice: "mine"|"theirs"|"both", serverVersion, mine: { title?, content? } }` → `{ id, version, title, content, properties, updatedAt, copyId }`58  (both copies always survive in the server history; `both` creates a sibling page "… (conflict copy)"; `409 conflict` again if the page moved meanwhile).59- `DELETE /api/pages/<id>` → trash (page + descendants) `{ ok, trashed }`. `DELETE …?purge=1` → permanent, needs a fresh passkey verification (`403 reauth_required`).60- `POST /api/pages/<id>?action=restore` → `{ ok }`. `POST …?action=duplicate` → the new page.61- `GET /api/pages/<id>/versions` → `[{ id, version, title, reason, createdAt, wordCount }]` (≤ 200); `?v=<n>` → the full snapshot row (`content`, `properties`).62  `POST …/versions` `{ version }` → restores that snapshot `{ ok, version }`.63- `GET /api/pages/<id>/tags` → `[names]`; `PUT` `{ tags: [names] }` → `[names]` (normalised: trimmed, leading `#` removed, lower-cased, ≤ 40 chars, ≤ 20 tags).64- `GET /api/tags` → `[{ id, name, color, pages }]`.65- `DELETE /api/trash[?olderThanDays=N]` → purge (fresh verification).6667## Attachments6869- `POST /api/attachments` multipart form: `file` (required, ≤ 200 MB), `pageId?`, `id?` (uuid chosen by the client; if it exists: `200` + `x-existing: 1`)70  → `201 { id, url: "/api/files/<id>", name, size, mime, hasText, pages }`. Refused types (415): `application/x-msdownload`, `application/x-sh`, `text/html`, `application/javascript`.71- `GET /api/attachments[?pageId=]` → `[{ id, filename, mime, size, pageId, pageCount, createdAt, hasText, url }]`.72- `DELETE /api/attachments?id=<id>` → `{ ok }` (soft delete).73- `GET /api/files/<id>` → the bytes (authenticated; `content-type`, `content-length`, immutable).74- In documents: image node `{ type: "image", attrs: { src: "/api/files/<id>", alt, title } }`, file node75  `{ type: "fileBlock", attrs: { src: "/api/files/<id>", name, size, mime, attachmentId } }`.7677## Authentication (passkeys, WebAuthn; relying party id = host of the origin, `note.spboucher.ai`)7879Ceremony state is carried by an HttpOnly cookie `__Host-note_wa` set by the `options` call and required by the matching `verify` call.80- `POST /api/auth/login/options` (public) → `{ options }` = WebAuthn `PublicKeyCredentialRequestOptionsJSON` (`challenge` base64url, `rpId`, `userVerification: "required"`, `allowCredentials: []`).81- `POST /api/auth/login/verify` (public) `{ response }` with `response = { id, rawId, type: "public-key", response: { clientDataJSON, authenticatorData, signature, userHandle? }, clientExtensionResults: {}, authenticatorAttachment? }`82  (all binary fields base64url without padding) → `{ ok, next }` + `Set-Cookie: __Host-note_session=…`.83- `POST /api/auth/reauth/options` / `…/verify` `{ response }` (signed in) → step-up: `{ ok, freshForMs }` + rotated session cookie.84- `GET /api/auth/state` → `{ sessionId, fresh, verifiedAt, freshWindowMs, idleDays, absoluteDays, rpId, origins, … }`.85- `POST /api/auth/logout` → `{ ok }` (revokes the session; always 200).86- `GET /api/auth/sessions` → `[{ id, label, ip, createdAt, lastSeenAt, expiresAt, current }]`; `DELETE /api/auth/sessions/<id>`; `DELETE /api/auth/sessions` `{ includeCurrent }` (fresh).87- `GET /api/auth/passkeys` → `[{ id, label, createdAt, lastUsedAt, synced, multiDevice, transports, current }]`.88  `POST /api/auth/passkeys/options` (fresh) → `{ options }` = `PublicKeyCredentialCreationOptionsJSON` (`user.id` base64url, `challenge`, `rp`, `excludeCredentials`);89  `POST /api/auth/passkeys/verify` (fresh) `{ response: { id, rawId, type, response: { clientDataJSON, attestationObject, transports? }, clientExtensionResults }, label? }` → `{ ok, id, label }`.90  `DELETE /api/auth/passkeys/<id>`, `PATCH /api/auth/passkeys/<id>` `{ label }`.91- `GET /.well-known/apple-app-site-association` (public): `webcredentials.apps` lists `3YM54G49SN.ai.spboucher.spnotes` (macOS) and `3YM54G49SN.ai.spboucher.spnotes.ios` (iOS).92- Sessions: idle 30 days, hard cap 90 days, revocable.9394## AI (server-sent events: lines `data: <json>\n\n`, terminator `data: [DONE]`)9596- `POST /api/ai/action` `{ action, text (≤ 120 000), instruction?, model?, language?, confirmExpensive? }`, `action` ∈ rewrite, fix, translate (needs `language` ∈ fr,en,es,de,it,pt),97  summarize, expand, explain, to_list, to_tasks, table, shorten, formal, simplify, translate_fr, translate_en, explain_math, continue, outline, study_notes,98  action_items, contradictions, custom (needs `instruction`). Events: `{type:"meta", model, provider, reason, budgetNote}`, `{type:"text", delta}`,99  `{type:"done", usage, costUsd, latencyMs}`, `{type:"error", code, retryable, message}`. Before streaming: `409 confirm_expensive { plan }`, `503 not_configured|no_model`, `400`.100  The server returns text (Markdown) only; nothing is written to the note.101- `POST /api/ai/chat` `{ conversationId?, clientId?, message, mode?: notes|summarise|actions|contradictions|draft|general, pageId?, model?, task?, useWorkspace?, confirmExpensive?, scopePageIds? }`102  → SSE of `meta | text | done | error | needs_confirmation` events (plus source lists for grounded modes).103104## Other routes used as they are105106- `GET /api/search?q=&mode=quick|hybrid&limit=&semantic=0|1&section=&since=&until=&archived=1` (server-side search, optional online complement to the local index).107- Tasks (reminders): `GET /api/tasks[?done=1]`, `POST /api/tasks { title, dueAt?, priority?, project?, pageId? }` → row (201), `PATCH /api/tasks { id, title?, dueAt?, status?: todo|done, … }`, `DELETE /api/tasks?id=`.108- Inbox: `GET /api/inbox`, `POST /api/inbox/<id>` `{ action: keep (section?, parentId?) | task | archive | trash | … }` → `{ actionId, summary }`, `POST /api/inbox/undo { actionId }`.109- `POST /api/capture { kind: note|tasks|link|photo|file|audio, text?, url?, attachmentIds? }` → `{ id, title, kind, inboxAt }`.110- `GET /api/health` (public) → `{ ok, db, worker, passkeys, version }`.111112## Data conventions shared by the native apps113114- favourite = `properties.favorite === true`; pinned = `pinned`; folder = a page with `properties.folder === true`. `properties` is versioned.115- reminder = a task `{ pageId, dueAt }`.116- PencilKit drawing = an `image` node whose `alt` is `drawing-<uuid>.png` + a companion attachment `drawing-<uuid>.pkdrawing` on the same page (editable source).117
Files main
Menu

Theme