Repository Public
1# SP Drive 2.0 — API reference of everything new or changed23Branch `next`, migration `003_next`. This file is the precise contract for the web application and the native4clients: when it differs from `ARCHITECTURE-NEXT.md`, **this file wins**. Every example below was produced by the5development server of this branch (`scripts/next-dev.sh`), then shortened.67Everything is additive. A 1.0 client keeps working unchanged against a 2.0 server.89## 0. Deviations from the contract (read first)1011| # | Contract | What the server does | Why |12|---|---|---|---|13| D1 | role too weak → "a failed check answers 404" | a **live grant with an insufficient role answers `403 forbidden`**; every other failed check (grant revoked / foreign / unknown, target outside the subtree, trashed) answers `404 not_found` | the member already knows the grant exists (it is in `shared-with-me`), so 403 reveals nothing and lets a client grey out an action instead of believing the folder vanished |14| D2 | `POST /ai/ask` SSE: `sources`, `delta`…, `done` | an extra event **`notice { unindexed: [{ fileId, name, status }] }`** may precede `sources` when `scope.fileIds` names files whose text is not indexed | "a file whose text is not indexed is reported as such" needed a place that keeps `sources` an array |15| D3 | `done` with `{ empty: true }` | `done` is `{ empty: true, provider, model, usage: null }` | same shape as a normal `done`, plus the flag |16| D4 | `GET /ai/providers` | adds `external: { server, account }` and per provider `usable` | a client must tell "not configured" from "not allowed for this account" |17| D5 | `storage/overview.duplicates { groups, reclaimableBytes }` | `{ groups, duplicateBytes, reclaimableBytes }` and **`reclaimableBytes` is always `0`** | identical content is stored once per account (dedup since 1.0): deleting a duplicate frees a name, not bytes. `duplicateBytes` is the logical size of the redundant copies |18| D6 | `index/status.content { ready, pending, failed, unsupported }` | adds `enabled` and `empty` | `empty` (a file with no text at all, e.g. a photo without writing) is not a failure |19| D7 | `GET /files/:id/text` | adds `error` (a displayable reason when `failed` / `unsupported`) | |20| D8 | search results reachable "through an active grant" | **search, semantic search and AI only cover the caller's own files** in 2.0; shared folders are browsed, not searched | keeps the search path owner-scoped by construction; can be added later without changing shapes |21| D9 | sync events | a `change` event is sent for the **owner's own tree only**; a member is not told when a folder shared with them changes (they re-list) | same reason as D8 |22| D10 | semantic search | `available: true` only when the on-device model answers; scores are **relative** (see §4.4) and cross-language queries do not work | measured, see `docs/progress.md` (section 2.0) and `scripts/semantic-eval.mts` |23| D11 | — | new helper routes not in the contract: `POST /collections/preview`, `PATCH /folders/:id/workspace`, `GET /collab/outgoing`, `GET /shared/:grantId/activity`, `GET|DELETE /shared/:grantId/uploads/:id` | needed by any real client |24| D12 | `duplicates?mode=similar-images` | optional `distance=0..16` (default 6) | |25| D13 | change feed | when the **thumbnail** of a content becomes ready, every live file whose current version is that content gets a new `rev` (nothing else changes in the row): `GET /sync/changes` returns it with `thumb: true` and a `change` event is sent | a client that mirrored the file before the worker ran kept `thumb: false` for ever. Text extraction becoming ready does **not** bump `rev` (`GET /files/:id/text` is polled by whoever shows it) |26| D14 | rate limits | the per-address limit (900 requests / minute) no longer counts the **chunk traffic of resumable uploads** — `PATCH` and `GET` of `/uploads/:id` and `/shared/:grantId/uploads/:id` — when the request carries a cookie or a well-formed bearer. Those requests have their own budget: **6000 / minute per account** (`429 rate_limited` with `retryAfterS` beyond). A cookie or bearer that is not a live session gets 120 such requests / minute per address; without any credential the ordinary per-address limit applies. `POST /uploads`, `…/complete`, authentication and public routes are unchanged | 6–8 parallel uploads of large files from one native client made thousands of chunk requests a minute and tripped the address limit |27| D15 | `GET /files/:id/text` | where the antivirus is optional and absent (`SPD_AV_MODE=optional`, development stacks), a file whose scan was skipped answers `pending` until its extraction ran — it used to answer `unsupported` for a moment, and a client that stops polling on `unsupported` never saw the text arrive | found by the web inspector |28| D16 | activity events | `target` gains **`name`** (see §7.2) | an activity screen could not name what an event was about without one request per line |29| D17 | `GET /sync/events` | "the stream never ends by itself" — except when the server shuts down: on SIGTERM / SIGINT every open stream is ended and its connection closed at once (same for an AI answer in flight). A client sees the end of the stream and reconnects with its usual back-off | the process used to stay alive, pinging, until the supervisor's kill timeout |30| D18 | `POST /folders/:id/members { userId \| email }` | **`email` only** (`{ email, role, workspaceName? }`, unknown keys refused with 400; 20 calls/min) | an account identifier alone must not be exchangeable for a display name and an address; the address is what `/collab/resolve` was given anyway |31| D19 | `GET /shared/:grantId/activity` returned the owner's trail for the folder | a **reduced feed** for members, see §6.2 "Member activity": seven actions, events since the grant only, live items only, people by display name only (`actor.userId` is always `null`), a short whitelist of `meta` keys | the owner's audit history (downloads, former names, other members, trashed items) is not the member's to read |32| D20 | uploader: `complete` returned `file { id, name, size }` with the final name | `file.name` is **the name the uploader sent**, even when the server stored it as "x (2).txt"; an uploader may only aim at the granted folder itself (`folderId` omitted or equal to it, else 403); `relativePath` still creates sub-folders silently | a renamed final name, or a different answer for an existing sub-folder, would let an uploader list the folder |33| D21 | grant uploads | an upload opened through a grant **expires after 24 h** (7 days for one's own); the unfinished uploads of one member on one grant may hold at most `SPD_GRANT_PENDING_GB` (default 20 GiB): beyond it `413 too_many_pending_uploads { pending, max }`. A single file sent through a grant can therefore not exceed that size | unsent bytes are reserved on the owner's quota |34| D22 | `GET /sync/events` | besides `429 too_many_streams` (16 per account) the server may answer **`503 too_many_streams`** when the whole process is at its ceiling (`SPD_EVENTS_MAX_STREAMS`, default 1000): keep polling and retry with backoff | |35| D23 | `GET /search/semantic` | may answer **`503 busy { retryAfterS }`** when the local model already has a queue of requests | the helper runs at most two at a time |3637## 1. Conventions (unchanged from 1.0)3839- Base path `/api/v1`. JSON in, JSON out, UTF-8. Dates are ISO 8601 UTC strings. Sizes are bytes (numbers).40- Authentication: the session cookie (web) or `Authorization: Bearer <device token>` (native). A browser call that41 changes state sends `X-SPD-CSRF: 1`; a bearer call needs neither that header nor an `Origin`.42- Errors: `{ "error": "<stable code>", "message": "<English text>", ...extra }` with the HTTP status. Codes used43 below: `unauthenticated` 401, `forbidden` 403, `not_found` 404, `invalid_request` 400 (with `issues`),44 `name_conflict` 409, `quota_exceeded` 413, `rate_limited` 429 (with `retryAfterS`), `infected` 451.45- A foreign or unknown identifier is always `404`, never `403`.46- `File` and `Folder` below are the 1.0 objects (`fileJson`, `folderJson`). **`Folder` gains one field:47 `workspaceName: string | null`.** Nothing else changed in them.4849```json50{ "id": "5c8a03c4-…", "type": "file", "name": "Rapport trimestriel.pdf", "folderId": "5fa9fc32-…", "size": 740,51 "sha256": "38777b16…", "kind": "pdf", "origin": "upload", "starred": false, "createdAt": "2026-11-19T18:44:54.900Z",52 "updatedAt": "2026-11-19T18:44:54.900Z", "trashedAt": null, "scan": "clean", "thumb": true, "tagIds": [],53 "versions": 1, "trashRoot": false, "rev": 13, "versionId": "ad4c0df5-…", "versionSeq": 1,54 "contentAt": "2026-11-19T18:44:54.900Z" }55```56```json57{ "id": "60a6d559-…", "type": "folder", "name": "Équipe", "parentId": "7e53e088-…", "starred": false,58 "createdAt": "…", "updatedAt": "…", "trashedAt": null, "trashRoot": false, "rev": 27, "workspaceName": "Équipe Projet" }59```6061## 2. Capability discovery and client identification6263### `GET /api/v1/meta` — no authentication64```json65{ "api": 2, "version": "2.0.0",66 "features": ["events", "content-search", "ocr", "semantic", "collab", "collections", "activity", "storage", "similar-images", "upload-history"] }67```68A feature is listed only when it works on this server right now:6970| feature | listed when |71|---|---|72| `events`, `collab`, `collections`, `activity`, `storage`, `upload-history` | always on a 2.0 server |73| `content-search` | `SPD_INDEX_CONTENT` is not `off` |74| `ocr` | content indexing on, `SPD_OCR` not `off`, the local helper `dist/spd-textkit` starts |75| `similar-images` | the local helper starts |76| `semantic` | the helper's on-device embedding model has its assets (and `SPD_SEMANTIC` is not `off`) |77| `ai` | at least one provider is configured and allowed at server level |7879A 1.0 server answers `404` to this route: treat that as `{ api: 1, features: [] }`.8081### `X-SPD-Client` request header (native clients)82`X-SPD-Client: <platform>/<app version> (<os version>)`, platform ∈ `macos | ios | ipados`, e.g.83`X-SPD-Client: macos/2.0.0 (27.0)`. The version is `[0-9A-Za-z][0-9A-Za-z.+_-]{0,23}`; the parenthesised part is84optional (≤ 40 characters). Send it on **every** request (at least on sign-in and on the first request after an app85update): the server stores it on the device session at sign-in and refreshes it whenever it is present. A malformed86header is ignored.8788### `GET /api/v1/account/sessions` — changed: each session gains `client`89```json90[{ "id": "b384a139-…", "createdAt": "…", "lastSeenAt": "…", "ip": "192.168.2.40", "userAgent": "SPDrive/2.0.0",91 "method": "passkey", "kind": "device", "deviceName": "Mac Studio", "current": true,92 "client": { "platform": "macos", "version": "2.0.0", "os": "27.0" } }]93```94`client` is `null` for web sessions and for devices that never sent the header.9596### `PATCH /api/v1/account` — changed: accepts `aiExternal`97Body `{ "displayName"?, "locale"?: "fr"|"en", "aiExternal"?: boolean }` → `{ "ok": true }`. `aiExternal` is the98account's own switch for external AI providers (§5); changing it is recorded in the account's security activity.99100## 3. Sync events101102### `GET /api/v1/sync/events` — Server-Sent Events, cookie or bearer103Response headers: `Content-Type: text/event-stream; charset=utf-8`, `Cache-Control: no-cache, no-store, no-transform`,104`X-Accel-Buffering: no`. The stream never ends by itself.105106```107event: hello108data: {"head":27}109110event: change111data: {"head":29}112113event: notify114data: {"kind":"collab.shared"}115116: ping117```118119| event | data | meaning |120|---|---|---|121| `hello` | `{ "head": number }` | once, right after connecting; `head` is the same number as `GET /sync/cursor` |122| `change` | `{ "head": number }` | the owner's head revision moved. Bursts are folded: at most one event per second per account. Carries no item: call `GET /sync/changes?since=<your cursor>` |123| `notify` | `{ "kind": string }` | a notification was created for the account (`GET /notifications` to read it) |124| comment `: ping` | — | every 25 s |125126Rules for clients: events are a hint, never the source of truth — keep a polling fallback (30 s in the foreground127while the stream is down). Reconnect with exponential backoff + jitter (1 s → 60 s). There is no `Last-Event-ID`128replay: after a reconnect, `hello.head` tells whether anything was missed. Errors before the stream starts are129ordinary JSON: `401 unauthenticated`, `429 too_many_streams` (more than 16 streams for one account). The server130closes the stream of a session that was revoked or expired (within one ping).131132## 4. Search intelligence133134### 4.1 `GET /api/v1/search` — changed135All 1.0 parameters are unchanged (`q`, `kind`, `tag`, `starred`, `from`, `to`, `minSize`, `maxSize`, `sort`, `dir`).136New: **`in=name|content|all`** (default `all`).137138- Without `q` the answer is exactly the 1.0 answer (filters only, no `match`).139- With `q`, every folder and file gains **`match`**:140141```json142{ "folders": [{ "…Folder": "…", "match": { "where": "name" } }],143 "files": [144 { "…File": "…", "name": "Budget.csv", "match": { "where": "name" } },145 { "…File": "…", "name": "Notes de réunion.txt",146 "match": { "where": "content", "snippet": "Ordre du jour Le ⟦budget⟧ de la coopérative Hirondelle est adopté.", "page": null } },147 { "…File": "…", "name": "contrat.docx", "match": { "where": "both", "snippet": "⟦Contrat⟧ de location du chalet…", "page": null } }148 ] }149```150`match.where` ∈ `name | content | both`. `snippet` (≤ 400 characters, whitespace collapsed) and `page` (1-based page151or slide number, `null` when the format has no pages) are present for `content` and `both`. Matched words are wrapped152in `⟦` `⟧` (U+27E6 / U+27E7); the snippet is plain text, never HTML. Content matching is accent- and case-insensitive,153with French and English stemming (`turbine` finds `turbines`); `q` follows web-search syntax (`"exact phrase"`,154`-word`, `or`). Folders are only matched by name. Limits unchanged: 300 folders, 500 files.155156### 4.2 `GET /api/v1/files/:id/text`157```json158{ "status": "ready", "source": "pdf-text", "pages": 1, "chars": 112,159 "excerpt": "Rapport trimestriel\nLa societe Borealis a livre 42 turbines.\nThe maintenance schedule was approved by the board.",160 "error": null }161```162- `status` ∈ `pending` (queued, or waiting for the antivirus) · `ready` · `empty` (readable, no text) ·163 `unsupported` (format never indexed, indexing off, too large, protected PDF, infected) · `failed`.164- `source` ∈ `text` · `office-xml` (docx, pptx, xlsx, odt, odp, ods) · `textutil` (doc, rtf) · `pdf-text` · `ocr` ·165 `pdf-text+ocr` · `office-pdf` (ppt, xls through their PDF rendition) · `null`.166- `pages`: page or slide count (0 when not paged). `excerpt`: the first ≤ 800 characters. `error`: a displayable167 English reason when `failed` or `unsupported`, else `null`. `404` for a foreign id.168169### 4.3 `GET /api/v1/index/status`170```json171{ "content": { "enabled": true, "ready": 5, "pending": 0, "failed": 0, "unsupported": 0, "empty": 0 },172 "semantic": { "available": true, "model": "apple-nl-contextual", "embedded": 5 } }173```174Counts are distinct stored contents behind the caller's live files. `embedded` counts passages that have a vector.175176### 4.4 `GET /api/v1/search/semantic?q=&limit=`177`q` 1–500 characters (required), `limit` 1–50 (default 10). Rate limit 60/min.178```json179{ "available": true,180 "hits": [{ "file": { "…File": "…", "name": "Contrat chalet.md" }, "score": 0.7609,181 "passage": { "text": "# Contrat de location\n\nLe locataire verse un dépôt de 500 dollars avant le 1er juin.", "page": null } }] }182```183One hit per file (its nearest passage), best first. `score` is a cosine in `[-1, 1]`; **only the order means184something** — with this model unrelated text also scores ≈ 0.7–0.85, so never show the score as a percentage and185never threshold on it. When the backend is unavailable: `{ "available": false, "hits": [] }` (HTTP 200).186187## 5. Document intelligence188189### 5.1 `GET /api/v1/ai/providers`190```json191{ "enabled": true, "externalAllowed": false, "external": { "server": false, "account": false },192 "default": { "provider": "maclustr", "model": "qwen3-30b-a3b" },193 "providers": [194 { "id": "maclustr", "label": "MacLustr (local)", "local": true, "configured": true, "usable": true,195 "models": [{ "id": "qwen3-30b-a3b", "label": "Qwen3 30B", "creator": "Alibaba" }] },196 { "id": "anthropic", "label": "Anthropic", "local": false, "configured": false, "usable": false,197 "models": [{ "id": "claude-opus-5-5", "label": "Claude Opus 5.5", "creator": "Anthropic" },198 { "id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "creator": "Anthropic" },199 { "id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "creator": "Anthropic" }] },200 { "id": "openai", "label": "OpenAI", "local": false, "configured": false, "usable": false, "models": [] },201 { "id": "openrouter", "label": "OpenRouter", "local": false, "configured": false, "usable": false, "models": [] }202 ] }203```204- `enabled`: at least one provider is usable **by this account**. `default` is `null` when none is.205- `usable` = `configured` and (`local` or (`external.server` and `external.account`)).206- `externalAllowed` = `external.server && external.account`. `external.server` is the server switch207 (`SPD_AI_EXTERNAL=on`); `external.account` is the account switch (`PATCH /account { aiExternal }`).208- `creator` is who made the model; `id` of the provider is the route to it (they differ on a router).209- The default prefers the local provider; an external one is never chosen silently when it is not allowed.210211### 5.2 `POST /api/v1/ai/ask` — answer as Server-Sent Events212Request (rate limit 20/min):213```json214{ "scope": { "fileIds": ["3398f77d-…"] },215 "question": "Quel est le montant du dépôt ?",216 "provider": "maclustr", "model": "qwen3-30b-a3b",217 "history": [{ "role": "user", "content": "…" }, { "role": "assistant", "content": "…" }] }218```219- `scope`: **exactly one** of `fileIds` (1–50 ids), `folderId` (an id or `"root"`, whole subtree), `all: true`.220- `question` 1–2000 characters. `provider`, `model` optional (default: §5.1 `default`). `history` optional, ≤ 12221 turns of ≤ 8000 characters; the last 10 are sent.222223Errors **before** the stream (plain JSON): `400 invalid_request`, `400 provider_unknown`, `400 model_unknown`,224`404 not_found` (a foreign file or folder in the scope), `403 ai_external_disabled` (`{ server, account }` tell which225switch is off), `409 provider_not_configured`, `503 ai_unavailable` (no usable provider), `429 rate_limited`.226227Stream (`Content-Type: text/event-stream`), in this order:228```229event: notice230data: {"unindexed":[{"fileId":"9b1f…","name":"film.mp4","status":"unsupported"}]}231232event: sources233data: [{"n":1,"fileId":"3398f77d-…","name":"Contrat chalet.md","page":null,"text":"# Contrat de location\n\nLe locataire verse un dépôt de 500 dollars avant le 1er juin."}]234235event: delta236data: {"text":"Le dépôt est de 500 dollars "}237238event: delta239data: {"text":"[1]."}240241event: done242data: {"provider":"maclustr","model":"qwen3-30b-a3b","usage":{"inputTokens":321,"outputTokens":7},"stopReason":"stop"}243```244| event | data | notes |245|---|---|---|246| `notice` | `{ unindexed: [{ fileId, name, status }] }` | optional, only with `scope.fileIds`; `status` as in §4.2 |247| `sources` | `[{ n, fileId, name, page, text }]` | always sent once, possibly `[]`. `n` starts at 1 and is what `[n]` in the answer refers to. `text` ≤ 1200 characters. At most 8 sources |248| `delta` | `{ text }` | pieces of the answer, to concatenate |249| `done` | `{ provider, model, usage: { inputTokens, outputTokens } \| null, stopReason }` | end of a successful answer. `usage` numbers may be `null` when the provider does not report them |250| `done` (nothing retrieved) | `{ empty: true, provider, model, usage: null }` | no model was called; show "nothing in these documents matches" |251| `error` | `{ code, message }` | instead of `done`. Codes: `provider_auth`, `provider_unreachable`, `provider_unavailable`, `provider_rate_limited`, `provider_refused` (the model declined), `model_unknown`, `provider_error` |252253The stream ends after `done` or `error`. Closing the connection cancels the model call.254Retrieval: words decide whether anything was found (French/English full-text over the scope, any word may match);255the local sentence model, when available, re-ranks and completes that result. With `scope.fileIds` and a question256that matches no word ("résume ce document"), the opening passages of those files are used. The prompt contains only257these passages — never a whole document, never another account's content.258259### 5.3 `POST /api/v1/ai/suggest`260Request `{ "fileIds": ["…", "…"], "provider"?, "model"? }` (1–20 ids, rate limit 10/min) →261```json262{ "provider": "maclustr", "model": "qwen3-30b-a3b",263 "suggestions": [264 { "fileId": "3398f77d-…", "name": "Contrat de location – chalet des Laurentides.txt", "tags": ["Juridique", "Location"],265 "folder": { "id": "0f2c…", "path": "/Contrats" }, "category": "Contrat", "reason": "Bail de location saisonnière." },266 { "fileId": "77aa…", "category": "Recette", "reason": "Recette de dessert." } ] }267```268`name`, `tags` (≤ 3 names, existing or new), `folder`, `category` are each present only when the model proposed269something valid: a name never changes the extension, a folder is always one of the caller's live folders and never270the current one. A file may be missing from the list. **Nothing is applied**: the client applies with271`PATCH /files/:id`, `POST /tags`, `POST /move` after the user confirms. Errors: as §5.2, plus `502 ai_bad_answer`.272273### 5.4 Server configuration (operators)274Environment or `~/.config/sp-drive/ai.env` (`KEY=value` lines, mode 600; the environment wins):275276| key | meaning |277|---|---|278| `SPD_AI_MACLUSTR_URL` (default `https://llm.spboucher.ai/v1`), `SPD_AI_MACLUSTR_KEY`, `SPD_AI_MACLUSTR_MODEL`, `SPD_AI_MACLUSTR_MODELS` | the local OpenAI-compatible endpoint. `…_MODELS` = `id\|label\|creator, id2\|…` |279| `SPD_AI_EXTERNAL=on` | server switch for the three external providers |280| `ANTHROPIC_API_KEY`, `SPD_AI_ANTHROPIC_MODEL` (default `claude-opus-5-5`) | Anthropic (official SDK, Messages API) |281| `OPENAI_API_KEY`, `SPD_AI_OPENAI_MODEL`, `SPD_AI_OPENAI_MODELS` | OpenAI (no model is assumed: none listed = not configured) |282| `OPENROUTER_API_KEY`, `SPD_AI_OPENROUTER_MODEL`, `SPD_AI_OPENROUTER_MODELS` | OpenRouter |283284## 6. Private sharing and workspaces285286Roles: `viewer` (browse, read, preview, download) · `editor` (viewer + create, rename, move, trash, upload, new287versions) · `uploader` (send files in; lists nothing, reads nothing).288289### 6.1 Owner routes (the folder's owner only; anyone else gets 404)290291**`POST /api/v1/collab/resolve`** `{ "email": "bob@example.test" }` → `{ "userId": "b52c6d94-…", "displayName": "Bob Gagnon" }`292or `404`. Exact address only, never the caller's own, 10 calls/min.293294**`GET /api/v1/folders/:id/members`** →295```json296{ "folder": { "…Folder": "…" },297 "members": [{ "grantId": "d315eccf-…", "userId": "b52c6d94-…", "displayName": "Bob Gagnon", "email": "bob@example.test",298 "role": "uploader", "createdAt": "2026-11-19T18:44:54.963Z" }] }299```300**`POST /api/v1/folders/:id/members`** `{ "email": "bob@example.test", "role": "viewer"|"editor"|"uploader", "workspaceName"?: "…" }` (by address only, D18)301→ one member object (as above). Errors: `400 root_immutable` (the root cannot be shared), `404` (no such account, or302oneself), `409 already_member`.303**`PATCH /api/v1/folders/:id/members/:userId`** `{ "role": "…" }` → the member object. Dropping to `viewer` aborts304that member's uploads in flight.305**`DELETE /api/v1/folders/:id/members/:userId`** → `{ "ok": true }`. Immediate; the grant id is dead for good (access306given again is a new `grantId`).307**`PATCH /api/v1/folders/:id/workspace`** `{ "name": "Atelier" | null }` → the `Folder`.308**`GET /api/v1/collab/outgoing`** → `[{ "folder": Folder, "members": 2 }]` — folders the caller shares.309**`GET /api/v1/folders/:id/activity?before=&limit=`** → `{ events, more }` (§7.2) for the folder and everything310below it, members' actions included (`meta.via: "grant"`, `meta.grantId`).311312### 6.2 Grantee routes — `/api/v1/shared/…`313314**`GET /api/v1/shared-with-me`** →315```json316[{ "grantId": "012c60d3-…", "role": "viewer", "owner": { "displayName": "Alice Tremblay" },317 "folder": { "id": "60a6d559-…", "name": "Équipe", "workspaceName": "Équipe Projet", "updatedAt": "…" },318 "createdAt": "2026-11-19T18:44:54.958Z" }]319```320Only live grants (not revoked, folder not in the trash, owner not disabled). Display `workspaceName ?? name`.321322Every route below starts by re-checking the grant; see D1 for 403 vs 404.323324| route | role | answer |325|---|---|---|326| `GET /shared/:grantId/children?folderId=` | viewer, editor | `{ grantId, role, folder, breadcrumbs, folders, files }` |327| `GET /shared/:grantId/files/:fileId` | viewer, editor | `{ grantId, role, file, path }` |328| `GET /shared/:grantId/files/:fileId/content` | viewer, editor | the bytes; `Range`, `?download=1`, `?as=text` as on the owner route. `451 infected` always (no acknowledgement for members) |329| `GET /shared/:grantId/files/:fileId/preview/:kind` | viewer, editor | as the owner route (`202 {status:"pending"}`, `404 preview_unsupported`, …) |330| `GET /shared/:grantId/activity?before=&limit=` | viewer, editor | `{ events, more }` — the reduced member feed below |331| `POST /shared/:grantId/folders` `{ parentId?, name, onConflict?: "fail"\|"rename" }` | editor | the new shared `Folder` |332| `PATCH /shared/:grantId/items/:id` `{ name?, parentId?, onConflict? }` | editor | the shared `Folder` or `File`. `:id` is a file or a folder of the grant; `parentId` must be a folder of the same grant. The granted folder itself: `403` |333| `POST /shared/:grantId/trash` `{ fileIds?, folderIds? }` | editor | `{ ok: true }`. Goes to the **owner's** trash; only the owner restores or purges |334| `POST /shared/:grantId/uploads` `{ folderId?, name, size, relativePath?, onConflict? }` | editor, uploader | the upload object `{ id, name, size, received, status, fileId }` |335| `GET /shared/:grantId/uploads/:id` | editor, uploader | the upload object |336| `PATCH /shared/:grantId/uploads/:id?offset=` (raw body, optional `X-Chunk-SHA256`) | editor, uploader | the upload object |337| `POST /shared/:grantId/uploads/:id/complete` `{ sha256? }` | editor, uploader | `{ …upload, file, created }` |338| `DELETE /shared/:grantId/uploads/:id` | editor, uploader | `{ ok: true }` |339340```json341{ "grantId": "012c60d3-…", "role": "viewer",342 "folder": { "…Folder": "…", "id": "60a6d559-…", "name": "Équipe", "parentId": null, "isGrantRoot": true },343 "breadcrumbs": [{ "id": "60a6d559-…", "name": "Équipe" }],344 "folders": [{ "…Folder": "…", "parentId": "60a6d559-…", "isGrantRoot": false }],345 "files": [{ "…File": "…", "name": "Charte.txt", "tagIds": [], "starred": false }] }346```347**Member activity** (`GET /shared/:grantId/activity`). Same envelope as §7.2, deliberately less inside:348```json349{ "events": [{ "id": "412", "at": "…", "action": "file.renamed",350 "actor": { "kind": "user", "userId": null, "displayName": "Alice Tremblay", "me": false },351 "target": { "type": "file", "id": "ff377875-…", "name": "Charte v2.txt" }, "meta": {} }],352 "more": false }353```354Only these actions, with only these `meta` keys: `file.uploaded { size }`, `file.version_added { size }`,355`file.version_restored {}`, `file.renamed {}`, `folder.created {}`, `folder.renamed {}`, `items.moved { files, folders }`356(`target` is `null` for `items.moved`). Only events dated after the member was given access, and only about items357that are live inside the granted folder now (`target.name` is the present name). `actor.userId` is always `null`;358`actor.me` tells the member its own actions. No downloads, no former names, no sharing or membership events, nothing359about trashed items.360361- Shared folders carry `isGrantRoot`; the granted folder's `parentId` is `null` and `breadcrumbs` / `path` start at362 it: nothing of the owner's tree above the grant is ever shown. Shared files always have `tagIds: []` and363 `starred: false` (those are the owner's private marks).364- `folderId` / `parentId` omitted = the granted folder.365- Uploads use the same resumable protocol as `/api/v1/uploads` (same chunk limits, same errors:366 `offset_mismatch` 409 with `received`, `chunk_corrupt` 422, `checksum_mismatch` 422, `upload_closed`).367 **Bytes count against the owner's quota** (`413 quota_exceeded` reports the owner's numbers) and go through the368 owner's antivirus pipeline. `onConflict`: `rename` (default) | `fail` | `version` — an **uploader may only use369 `rename`** (403 otherwise). There is no `fileId` / `baseVersionId` here: an editor makes a new version by uploading370 under the same name with `onConflict: "version"`.371- `complete` for an **uploader** returns `file: { id, name, size }` only, where `name` is the name it sent (D20); for an editor the shared `File`.372- An **uploader** may only omit `folderId` (or pass the granted folder's id); any other value is `403`.373- Uploads through a grant expire after 24 h and are capped per member and grant (D21).374- An upload opened through a grant is invisible to the ordinary `/api/v1/uploads/:id` routes (404) and vice versa;375 it does appear in the member's own `GET /api/v1/uploads` history with `grantId` set and `folderId: null`.376377### 6.3 Notifications (`GET /api/v1/notifications`, plus a `notify` event)378| kind | to | data |379|---|---|---|380| `collab.shared` | the member | `{ grantId, role, folderName, ownerName }` |381| `collab.role_changed` | the member | `{ grantId, role, folderName, ownerName }` |382| `collab.revoked` | the member | `{ grantId, folderName, ownerName }` |383| `collab.upload` | the owner | `{ grantId, folderId, byName }` — at most one unread per grant per 30 min |384385## 7. Collections, activity, storage, duplicates, versions, uploads386387### 7.1 Collections388A rule: `{ "match": "all"|"any", "conditions": [Condition, …1..20], "sort"?: { "by": "name"|"updated"|"size"|"created", "dir": "asc"|"desc" } }`.389Unknown keys, fields, operators or value types are `400 invalid_request`.390391| field | op | value |392|---|---|---|393| `kind` | `is`, `isNot` | `image`, `pdf`, `document`, `sheet`, `video`, `audio`, `archive`, `text` |394| `ext` | `is`, `isNot` | extension without dot, `[A-Za-z0-9]{1,10}` |395| `name` | `contains`, `is`, `isNot` | string 1–200 (accent- and case-insensitive for `contains`) |396| `tag` | `is`, `isNot` | a tag id of the caller (`404` otherwise) |397| `untagged` | `is` | boolean |398| `size` | `gt`, `lt` | bytes (integer) |399| `modified`, `created` | `gt`, `lt` | ISO date (`2026-11-01`) or date-time with offset |400| `modified`, `created` | `within` | number of days (integer 1–36500) |401| `starred` | `is` | boolean |402| `shared` | `is` | boolean — has a live public link, or sits in a folder shared by link or by grant |403| `folder` | `is`, `isNot` | a folder id of the caller: the whole subtree (`404` otherwise) |404| `text` | `contains` | string 1–200, searched in the extracted text (§4) |405406A collection always selects among the caller's own live files; it references files and never copies bytes.407408**`GET /api/v1/collections`** →409```json410[{ "id": "cf09f64a-…", "name": "Documents récents", "icon": "", "color": "blue",411 "rule": { "match": "all", "conditions": [{ "field": "modified", "op": "within", "value": 30 }, { "field": "kind", "op": "isNot", "value": "video" }],412 "sort": { "by": "updated", "dir": "desc" } },413 "createdAt": "…", "updatedAt": "…", "count": 6 }]414```415**`POST /api/v1/collections`** `{ "name": "…", "icon"?: "doc.text", "color"?: "slate|red|orange|amber|green|teal|blue|violet|pink", "rule": Rule }`416→ the collection (without `count`). `icon` is a free identifier `[A-Za-z0-9._-]{0,40}` the clients agree on.417`409 name_conflict`, `409 too_many_collections` (100).418**`PATCH /api/v1/collections/:id`** any subset of the same body → the collection. **`DELETE …/:id`** → `{ "ok": true }`.419**`GET /api/v1/collections/:id/items?limit=&offset=`** (limit ≤ 500, default 200) →420`{ "collection": {…}, "files": [File], "total": 12, "limit": 200, "offset": 0 }`.421**`POST /api/v1/collections/preview`** `{ "rule": Rule, "limit"?: 1..200 }` → `{ "files": [File], "total": 12 }` (nothing saved).422423### 7.2 Activity424**`GET /api/v1/files/:id/activity?before=&limit=`** and **`GET /api/v1/activity?before=&limit=`** (limit ≤ 200, default 50) →425```json426{ "events": [{ "id": "5", "at": "2026-11-19T18:44:54.900Z", "action": "file.uploaded",427 "actor": { "kind": "user", "userId": "1f6c3c04-…", "displayName": "Alice Tremblay", "me": true },428 "target": { "type": "file", "id": "5c8a03c4-…", "name": "Rapport trimestriel.pdf" }, "meta": { "size": 740 } }],429 "more": false }430```431Newest first. Page with `before=<id of the last event received>` while `more` is true. `actor.kind` ∈432`user | anonymous | system` (`displayName` is `null` for `system`); `target` may be `null`.433`target.name` (added for the web activity screens) is the **present** name of a file or folder that still exists in the434account — `null` once it was purged, for the root folder, and for every other target type (share, submission, object).435436| action | target | meta |437|---|---|---|438| `file.uploaded`, `file.version_added` | file | `{ size }` |439| `file.version_restored` | file | `{ from: <seq> }` |440| `file.version_deleted` | file | `{}` |441| `file.renamed`, `folder.renamed` | file / folder | `{ from: "<old name>" }` |442| `file.downloaded` | file | `{ versionId? }` — explicit downloads only (`?download=1`) |443| `folder.created` | folder | `{}` |444| `items.moved` | — | `{ files, folders, fileIds, folderIds, destinationId }` |445| `items.copied` | — | `{ files, folders, fileIds, folderIds }` |446| `items.trashed`, `items.restored` | — | `{ files, folders, fileIds, folderIds }` |447| `items.purged` | — | `{ files, folders }` or `{ all: true }` |448| `zip.downloaded` | — | `{ files }` |449| `share.created` | share | `{ target: "file"\|"folder", fileId \| folderId, password, expires }` |450| `share.updated`, `share.revoked`, `share.deleted`, `share.rotated` | share | `{}` |451| `submission.completed` | submission | `{ placed, rejected, bytes, reason }` |452| `scan.infected` | object | `{ signature, files: [fileId] }` |453| `collab.member_added`, `collab.member_updated` | folder | `{ grantId, userId, role }` |454| `collab.member_removed` | folder | `{ grantId, userId }` |455| `collab.workspace_named` | folder | `{ named }` |456457`fileIds` / `folderIds` hold at most 200 ids each (`files` / `folders` are the true counts). A file's own feed458contains the events aimed at it and the bulk events that name it. Actions done by a member through a grant also carry459`meta.via = "grant"` and `meta.grantId`. Events from before 2.0 exist but bulk ones carry no ids (they appear in460`/activity`, not in a file's feed); renames and downloads were not recorded before 2.0. Sign-ins and security changes461stay in `GET /account/activity`.462463### 7.3 Storage464**`GET /api/v1/storage/overview`** →465```json466{ "quota": { "limit": 5368709120, "used": 1018, "uploading": 0 },467 "liveBytes": 1057, "trashBytes": 0, "oldVersionBytes": 0,468 "counts": { "files": 6, "folders": 3, "versions": 6, "trashedFiles": 0 },469 "byKind": [{ "kind": "pdf", "files": 1, "bytes": 740 }, { "kind": "text", "files": 3, "bytes": 239 }, { "kind": "sheet", "files": 2, "bytes": 78 }],470 "byFolder": [{ "folder": { "…Folder": "…", "name": "Projets" }, "files": 3, "bytes": 929 },471 { "folder": { "…Folder (the root)": "…" }, "files": 2, "bytes": 78, "direct": true }],472 "largest": [File, "… up to 20"],473 "growth": [{ "date": "2026-11-19", "bytes": 1057, "versions": 6 }],474 "duplicates": { "groups": 1, "duplicateBytes": 39, "reclaimableBytes": 0 } }475```476- `quota.used` = bytes really stored (distinct contents, all versions, trash included); `uploading` = bytes promised477 to uploads in flight. `liveBytes` = sum of the sizes of live files (can exceed `used`: identical files share bytes).478- `trashBytes` = bytes only the trash still holds; `oldVersionBytes` = bytes only non-current versions still hold.479- `byKind.kind` ∈ the eight kinds of §7.1 or `other`, largest first. `byFolder`: each direct child of the root with480 its whole live subtree (largest first, ≤ 50), then one entry `direct: true` for the files directly in the root.481- `growth`: one entry per day **that had uploads** in the last 90 days (bytes and versions added that day).482483**`GET /api/v1/storage/folder/:id`** (`:id` or `root`) →484`{ "folder": Folder, "breadcrumbs": [{id,name}], "total": { "files", "bytes" }, "direct": { "files", "bytes" }, "children": [{ "folder": Folder, "files", "bytes" }], "files": [File … the 100 largest directly inside] }`.485486### 7.4 Duplicates — `GET /api/v1/duplicates?mode=exact|similar-images` (changed)487`mode=exact` (default):488```json489{ "mode": "exact", "groups": [{ "sha256": "c93340f2…", "size": 39, "distinctNames": true, "files": [File, File] }] }490```491`distinctNames: true` = same content under different names. (1.0 clients reading `groups` are unaffected.)492493`mode=similar-images` (`distance` 0–16, default 6 = number of differing bits of a 64-bit difference hash):494```json495{ "mode": "similar-images", "distance": 6,496 "groups": [{ "maxDistance": 2, "files": [{ "…File": "…", "dhash": "90d0000000000000" }, { "…File": "…", "dhash": "90c0000000000000" }] }] }497```498A group holds at least two **different** contents that look alike (resized, re-encoded, converted); exact copies of499a member are included in its group. Rotated or cropped pictures are not matched. Nothing is ever deleted.500501### 7.5 Versions502**`GET /api/v1/files/:id/versions`** →503```json504{ "fileId": "5c8a03c4-…", "currentVersionId": "ad4c0df5-…",505 "versions": [{ "id": "ad4c0df5-…", "seq": 1, "size": 740, "sha256": "38777b16…", "createdAt": "…", "note": "",506 "current": true, "scan": "clean",507 "createdBy": { "userId": "1f6c3c04-…", "displayName": "Alice Tremblay", "me": true } }] }508```509Newest first. `createdBy` is `null` for a deposit-portal file; it is a member when the version came through a grant.510**`GET /api/v1/files/:id/versions/:versionId/content`** → the bytes of that version (`Range`, `?download=1`;511`451 infected` unless `?download=1&infected=ack`). Same as the 1.0 `GET /files/:id/content?v=<versionId>`.512**`POST /api/v1/files/:id/versions/:versionId/restore`** (1.0 route, behaviour verified): the old content becomes a513**new current version** (`seq` = highest + 1, `note: "restored from version N"`); every existing version is kept.514Restoring the content that is already current records nothing.515516### 7.6 Upload history — `GET /api/v1/uploads?state=recent|active&limit=`517```json518{ "uploads": [{ "id": "3712e0bb-…", "name": "Copie du budget.csv", "size": 39, "received": 39, "status": "done",519 "fileId": "7c32cf6f-…", "fileExists": true, "folderId": "7e53e088-…", "grantId": null,520 "createdAt": "…", "updatedAt": "…" }] }521```522The caller's own uploads, most recently updated first (`limit` ≤ 500, default 200). `status` ∈523`active | completing | done | aborted`. `fileId` is set when `done`; `fileExists` is false once that file was trashed524or purged. Finished and aborted uploads are kept 7 days. `state=active`: only `active` and `completing`.525526## 8. Administration — `GET /api/v1/admin/system` (administrators; 404 for others)527All 1.0 fields are unchanged. New fields:528```json529{ "version": "2.0.0", "features": ["events", "…"],530 "worker": { "alive": true, "heartbeatAgeS": 32, "pid": 24660 },531 "jobs": [{ "kind": "extract_text", "status": "done", "count": 5, "oldestAgeS": null },532 { "kind": "scan_object", "status": "queued", "count": 2, "oldestAgeS": 4 }],533 "previewFailures": [{ "kind": "thumb", "count": 1, "lastError": "image conversion failed: …" }],534 "converter": { "available": true, "path": "/Applications/LibreOffice.app/Contents/MacOS/soffice" },535 "textkit": { "available": true, "contextual": true },536 "antivirusSignatures": { "engine": "1.4.3", "signatures": 27824, "signaturesAt": "2026-11-18T14:24:11.000Z", "ageS": 100820 },537 "index": { "enabled": true, "ocr": true, "byStatus": { "ready": 5 }, "semantic": { "available": true, "model": "apple-nl-contextual", "dim": 512 } },538 "events": { "owners": 0, "streams": 0, "timers": 0 },539 "backup": { "dir": "/Users/…/backups/sp-drive",540 "last": { "ok": true, "at": "…", "startedAt": "…", "durationS": 41, "dump": "sp-drive-20261119-0340.dump.enc", "dumpBytes": 181234, "dumpSha256": "…", "dumpsKept": 30, "blobs": 51, "blobBytes": 40912345678, "remote": null, "ageS": 37800 },541 "restoreTest": { "ok": true, "at": "…", "dump": "…", "objects": 25, "files": 25, "ageS": 86400 },542 "verify": { "ok": true, "at": "…", "host": "m5ma", "dump": "…", "dumpChecked": true, "dumpDecrypted": true, "sampled": 30, "liveCompared": 30, "mismatched": 0, "missing": 0, "objects": 51, "errors": [], "ageS": 600 },543 "offNode": null } }544```545- `worker.alive` = a heartbeat less than 180 s old. `jobs`: everything not done, plus what finished in the last 24 h;546 `oldestAgeS` only for `queued` / `running`. `converter`, `textkit`, `antivirusSignatures` are what the **worker**547 last reported (`available: null` before its first heartbeat).548- `backup.*` are the JSON status files in the backup directory, each `null` when absent, each with `ageS` computed549 from its `at`: `status.json` (written by `scripts/backup.sh`; `ok: false` with `error` when a run stopped),550 `restore-test.json` (`scripts/restore-test.sh`), `verify.json` (`scripts/backup-verify.sh`; `dumpChecked` is true only when the dump was really checked — its hash matched the one `status.json` records for that very dump (`dumpHashMatched`), or it was decrypted with the key), `offnode.json`551 (written by the off-node puller: run `scripts/backup-verify.sh <copy> --no-key --write offnode.json --label <node>`552 on the other node and copy the file back into the backup directory).553