SPB Git

Repository Public

BACKEND_CONTRACT.md 11.0 KB

# Backend contract used by the native apps

Backend: note-spboucher-ai (Next.js route handlers, PostgreSQL). Production: https://note.spboucher.ai. Native additions live on the branch native-sync (commit 31b354d, owned by the macOS session) and run for tests on M4M64c at 127.0.0.1:8482 (database note_native_dev, never production data).

# Test server

ssh -N -L 8482:localhost:8482 M4M64c          # tunnel → http://localhost:8482
ssh M4M64c 'bash -lc "cd ~/dev/note-native && set -a && . ./.env && set +a && node_modules/.bin/tsx scripts/dev-session.ts"'   # prints a session token

The test server runs in production mode: the cookie is __Host-note_session=<token> there as well. Mutating requests need Origin: http://localhost:8482 on the test server and Origin: https://note.spboucher.ai in production. Do not modify that worktree and do not reset its database.

# Transport rules (all routes)

  • Authentication = session cookie __Host-note_session=<token> (43-character base64url token). Without it: 401 {"error","code":"unauthenticated"}. The token is rotated by a step-up (/api/auth/reauth/verify answers a new Set-Cookie; the old token stays valid 60 s).
  • Every mutating request (POST, PATCH, PUT, DELETE) must carry Origin: <app origin> exactly; otherwise 403 code csrf.
  • Idempotency-Key: [A-Za-z0-9_-]{8,100} on a mutating request: runs at most once per session; a retry returns the stored JSON answer with header idempotent-replay: true; 409 code in_progress while the first one is still running; 422 idempotency_mismatch if reused for another request.
  • x-request-id: [A-Za-z0-9_-]{8,64} is echoed in the answer and in the server log.
  • Errors: JSON { "error": "<message>", "code"?: "<stable code>", ...extra } with the HTTP status. Codes used: unauthenticated (401), reauth_required (403: a passkey verification younger than 5 minutes is needed), csrf (403), conflict (409, with server), bad_document (400/413), rate_limited (429), not_enrolled, confirm_expensive (409, with plan), not_configured / no_model (503), in_progress, bad_idempotency_key.
  • User-Agent of the native apps: SPNotes/<x.y.z> (iPhone|iPad|Macintosh; <os>) native → the session is labelled "SP Notes · iPhone|iPad|Mac".
  • Dates are ISO 8601 strings with milliseconds (2026-11-18T19:07:04.808Z).

# Change feed

GET /api/sync?since=<rev>&limit=<1..500, default 200> →

{ cursor, head, more, reset, serverTime, workspace: {id, name}, user: {displayName},
  pages: [{ id, parentId, databaseId, type, section, title, icon, cover, content, properties, position, pinned, archived, version,
            wordCount, createdAt, updatedAt, lastOpenedAt, deletedAt, inboxAt, captureKind, rev, tags: [sorted names] }],
  attachments: [{ id, pageId, filename, mime, size, sha256, pageCount, createdAt, deletedAt, rev }],
  tombstones: [{ id, kind: "page" | "attachment", rev, deletedAt }],
  tags: [{ name, color }] }            // complete tag list of the workspace on every call

rev is a single sequence bumped by database triggers on every write whatever the code path (trash, restore, tags, triage, agents, imports); purges leave tombstones; opening a note (lastOpenedAt) does not count. since=0 = full copy; call again while more; reset: true (the cursor is ahead of the server: database restored) → start again from 0. Send cursor back unchanged next time. Every state is included (trash, archives, inbox, database row pages). A client recognises the echo of its own write by comparing version with the one its PATCH returned.

# Pages

  • POST /api/pages { id?: uuid, title?, parentId?, section?: notes|documents|databases|projects|research, type?: page|database|research, content?, icon?, properties? } → 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. A parent purged meanwhile → created at the root.
  • GET /api/pages/<id> → full row + breadcrumb, backlinks (trashed pages included). ?head=1 → {id, version, updatedAt, deletedAt}. ?open=1 touches lastOpenedAt.
  • PATCH /api/pages/<id> { title?, content?, icon?, cover?, properties?, parentId?, section?, position?, pinned?, archived?, versionReason?, baseVersion? } → { id, version, updatedAt, title, wordCount }. title, content, properties are versioned: with baseVersion the write only happens if the page is still at that version, else 409 { code: "conflict", server: { version, title, content, properties, updatedAt } } and nothing is written. Other fields are not version-guarded. The server assigns missing block ids to the content it stores (the client should send them itself).
  • POST /api/pages/<id>/resolve { choice: "mine"|"theirs"|"both", serverVersion, mine: { title?, content? } } → { id, version, title, content, properties, updatedAt, copyId } (both copies always survive in the server history; both creates a sibling page "… (conflict copy)"; 409 conflict again if the page moved meanwhile).
  • DELETE /api/pages/<id> → trash (page + descendants) { ok, trashed }. DELETE …?purge=1 → permanent, needs a fresh passkey verification (403 reauth_required).
  • POST /api/pages/<id>?action=restore → { ok }. POST …?action=duplicate → the new page.
  • GET /api/pages/<id>/versions → [{ id, version, title, reason, createdAt, wordCount }] (≤ 200); ?v=<n> → the full snapshot row (content, properties). POST …/versions { version } → restores that snapshot { ok, version }.
  • GET /api/pages/<id>/tags → [names]; PUT { tags: [names] } → [names] (normalised: trimmed, leading # removed, lower-cased, ≤ 40 chars, ≤ 20 tags).
  • GET /api/tags → [{ id, name, color, pages }].
  • DELETE /api/trash[?olderThanDays=N] → purge (fresh verification).

# Attachments

  • POST /api/attachments multipart form: file (required, ≤ 200 MB), pageId?, id? (uuid chosen by the client; if it exists: 200 + x-existing: 1) → 201 { id, url: "/api/files/<id>", name, size, mime, hasText, pages }. Refused types (415): application/x-msdownload, application/x-sh, text/html, application/javascript.
  • GET /api/attachments[?pageId=] → [{ id, filename, mime, size, pageId, pageCount, createdAt, hasText, url }].
  • DELETE /api/attachments?id=<id> → { ok } (soft delete).
  • GET /api/files/<id> → the bytes (authenticated; content-type, content-length, immutable).
  • In documents: image node { type: "image", attrs: { src: "/api/files/<id>", alt, title } }, file node { type: "fileBlock", attrs: { src: "/api/files/<id>", name, size, mime, attachmentId } }.

# Authentication (passkeys, WebAuthn; relying party id = host of the origin, note.spboucher.ai)

Ceremony state is carried by an HttpOnly cookie __Host-note_wa set by the options call and required by the matching verify call.

  • POST /api/auth/login/options (public) → { options } = WebAuthn PublicKeyCredentialRequestOptionsJSON (challenge base64url, rpId, userVerification: "required", allowCredentials: []).
  • POST /api/auth/login/verify (public) { response } with response = { id, rawId, type: "public-key", response: { clientDataJSON, authenticatorData, signature, userHandle? }, clientExtensionResults: {}, authenticatorAttachment? } (all binary fields base64url without padding) → { ok, next } + Set-Cookie: __Host-note_session=….
  • POST /api/auth/reauth/options / …/verify { response } (signed in) → step-up: { ok, freshForMs } + rotated session cookie.
  • GET /api/auth/state → { sessionId, fresh, verifiedAt, freshWindowMs, idleDays, absoluteDays, rpId, origins, … }.
  • POST /api/auth/logout → { ok } (revokes the session; always 200).
  • GET /api/auth/sessions → [{ id, label, ip, createdAt, lastSeenAt, expiresAt, current }]; DELETE /api/auth/sessions/<id>; DELETE /api/auth/sessions { includeCurrent } (fresh).
  • GET /api/auth/passkeys → [{ id, label, createdAt, lastUsedAt, synced, multiDevice, transports, current }]. POST /api/auth/passkeys/options (fresh) → { options } = PublicKeyCredentialCreationOptionsJSON (user.id base64url, challenge, rp, excludeCredentials); POST /api/auth/passkeys/verify (fresh) { response: { id, rawId, type, response: { clientDataJSON, attestationObject, transports? }, clientExtensionResults }, label? } → { ok, id, label }. DELETE /api/auth/passkeys/<id>, PATCH /api/auth/passkeys/<id> { label }.
  • GET /.well-known/apple-app-site-association (public): webcredentials.apps lists 3YM54G49SN.ai.spboucher.spnotes (macOS) and 3YM54G49SN.ai.spboucher.spnotes.ios (iOS).
  • Sessions: idle 30 days, hard cap 90 days, revocable.

# AI (server-sent events: lines data: <json>\n\n, terminator data: [DONE])

  • POST /api/ai/action { action, text (≤ 120 000), instruction?, model?, language?, confirmExpensive? }, action ∈ rewrite, fix, translate (needs language ∈ fr,en,es,de,it,pt), summarize, expand, explain, to_list, to_tasks, table, shorten, formal, simplify, translate_fr, translate_en, explain_math, continue, outline, study_notes, action_items, contradictions, custom (needs instruction). Events: {type:"meta", model, provider, reason, budgetNote}, {type:"text", delta}, {type:"done", usage, costUsd, latencyMs}, {type:"error", code, retryable, message}. Before streaming: 409 confirm_expensive { plan }, 503 not_configured|no_model, 400. The server returns text (Markdown) only; nothing is written to the note.
  • POST /api/ai/chat { conversationId?, clientId?, message, mode?: notes|summarise|actions|contradictions|draft|general, pageId?, model?, task?, useWorkspace?, confirmExpensive?, scopePageIds? } → SSE of meta | text | done | error | needs_confirmation events (plus source lists for grounded modes).

# Other routes used as they are

  • 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).
  • 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=.
  • Inbox: GET /api/inbox, POST /api/inbox/<id> { action: keep (section?, parentId?) | task | archive | trash | … } → { actionId, summary }, POST /api/inbox/undo { actionId }.
  • POST /api/capture { kind: note|tasks|link|photo|file|audio, text?, url?, attachmentIds? } → { id, title, kind, inboxAt }.
  • GET /api/health (public) → { ok, db, worker, passkeys, version }.

# Data conventions shared by the native apps

  • favourite = properties.favorite === true; pinned = pinned; folder = a page with properties.folder === true. properties is versioned.
  • reminder = a task { pageId, dueAt }.
  • PencilKit drawing = an image node whose alt is drawing-<uuid>.png + a companion attachment drawing-<uuid>.pkdrawing on the same page (editable source).
Files main
Menu

Theme