# API reference Go API: `http://localhost:8080`. The web UI uses the same paths through its server-side proxy at `http://localhost:3000` and its NextAuth session. Successful responses are JSON unless marked Markdown. Errors are `{"error":"message"}`. Data endpoints require authentication: **401** without a valid session, **404** for another user's private record, **403** for non-admin administration, **400** for invalid input, **409** for duplicates. Request bodies over 1 MiB answer **413**. Rate-limited endpoints answer **429** with `Retry-After`; public bookmark lookups are limited per effective client and per bookmark id, and previews per client. Share recipient lists are capped (100 per bookmark/tag/collection share, 200 per shared date). ## Authentication | Method | Path | Returns | |---|---|---| | GET | `/healthz` | `{"status":"ok"}` (process liveness) | | GET | `/readyz` | `{"status":"ready"}` after database ping; 503 when unavailable | | POST | `/api/signup` | 201 `{ok:true}` — the same uniform body for fresh, duplicate and operator-reserved addresses (review CR-03: no existence oracle); body `{email,password,name?}` | | POST | `/api/auth/login` | `{ok:true,user:{id,name,email,image,role,tenantId},tokenVersion}` and signed HttpOnly cookie. **403** when `AUTH_MODE=oidc` (SSO-only deployments) | | POST | `/api/password/forgot` | `{ok:true}` — identical body for unknown, OIDC-only and real addresses (no existence oracle); emails a single-use 30-minute reset link when SMTP is configured. **503** without `SMTP_*`; **403** in oidc mode | | POST | `/api/password/reset` | `{ok:true}` — body `{token,password}`; consumes the token, sets the new password and bumps `tokenVersion` (revokes all prior sessions). **400** on invalid/expired/used tokens or policy-violating passwords; **403** in oidc mode | | GET | `/api/auth/session` | `{user}` or `null` for no valid cookie | | POST | `/api/auth/signout` | `{ok:true}` and expired cookie; same-origin `Origin` required when present | | GET | `/api/me` | `{user,effectiveUser,isAdmin,viewingAs}`; real and effective identities. The user projection carries `tenantId` (tenancy phase 1) and the profile particulars `bio,location,occupation,organization,website` (nullable) | | PATCH | `/api/me` | Settings → Profile: partial `{name?,bio?,location?,occupation?,organization?,website?}` (allowlist; empty string clears to null; rune caps 120/280/120/120/120, website ≤2048 and http(s) with a host) → the fresh user projection. No version column on User (identity, not a collaborative collection); view-as writes are blocked by the middleware | | GET | `/api/auth/oidc/status` | `{enabled,issuerSet,clientIdSet,clientSecretSet}`; never includes secrets or the issuer URL | | POST | `/api/auth/oidc/identity` | Server-to-server only: requires `typ=oidc-provision` bearer token; body `{issuer,subject,email,emailVerified,name,image}`; returns the local `{user,tokenVersion}` or **409** when an existing password account needs explicit linking | | GET | `/api/auth/oidc/login` | **501**, client-owned Authelia integration stub | | GET, POST | `/api/auth/callback/authelia` | **501**, client-owned callback stub | The browser's NextAuth `/api/auth/*` endpoints remain on the Next server. Go's `/api/auth/` catch-all implements only `GET /api/auth/session` and `POST /api/auth/signout`; every other subpath (`csrf`, `providers`, `signin`, `callback/credentials`, …) answers **404** on Go and is served by Next. Direct Go API consumers use the `superbrain_session` cookie from login. `TIER=core|multi` (or an explicit `AUTH_MODE` override) decides which half of the auth surface is live: in `oidc` mode login/signup/password-reset all answer 403; in `password` mode `/api/auth/oidc/identity` answers 403 even with a valid service token. See `web/docs/AUTHELIA.md` §7. Go login accepts JSON and rejects foreign browser origins. Login and signup are throttled per client IP (429 with `Retry-After`), plus a consecutive-failure lockout per IP+email on login. Login applies to every peer, loopback included; signup exempts only a direct loopback peer. Browser traffic arrives through the trusted Next proxy, which forwards the observed client IP in `X-superbrain-Client-Ip` signed with HMAC-SHA256 under the shared secret (`X-superbrain-Client-Sig`); Go buckets on that identity only when the signature verifies and falls back to the direct peer otherwise, so proxied browsers neither share one bucket nor forge another identity. `ADMIN_EMAILS` reserves administrator addresses for operator provisioning and disables public first-admin bootstrap while set. Automatic promotion of an existing allowlisted user requires `emailVerified`; DB administrator roles remain authoritative. First-signup administrator promotion is one-shot: once bootstrap completion is recorded (AppSetting `adminBootstrap`), the absence of a qualifying administrator — e.g. after demoting the last one — never re-opens promotion through signup. Recovery is operator-driven (`ADMIN_EMAILS` + `make seed`, or promotion by an existing admin). ### Next.js server routes The web server (`web/app/api/`) exposes three route families; everything else is proxied: | Method | Path | Behavior | |---|---|---| | ALL | `/api/[...path]` | Server-side proxy to the Go API. Signs a 60s Bearer assertion from the NextAuth session, forwards the signed observed client IP, enforces the same-origin / `Sec-Fetch-Site` CSRF check and the 1 MiB streaming body cap, and passes through `X-Next-Cursor`. Does **not** forward client `Authorization` headers (so `sb_` keys only work against Go directly) | | GET, POST | `/api/auth/*` | NextAuth (Auth.js): `csrf`, `providers`, `signin`, `signout`, `session`, `callback/credentials`, `callback/authelia`. The browser session lives here; Go's `/api/auth/` only implements `session`/`signout` | | POST | `/api/session/revoke` | Explicit "sign out everywhere": calls Go `POST /api/auth/signout` with a signed assertion and reports honestly — `{revoked:true}` on success, `{revoked:false,reason}` (`no-backend-session` / `backend-error` / `unreachable`) when global revocation could not be confirmed. Same-origin `Origin` required (403 otherwise). The NextAuth `signOut` event is a fail-open backstop | ### API keys (MCP / machine clients) Personal long-lived Bearer credentials (`sb_` + 43 base64url characters) for non-browser clients: the `superbrain-mcp` server (see `mcp/`), the federated `mcpserver` gateway, or plain REST scripts. A key authenticates **every data endpoint** below as its owner — same ownership rules, same 401/403/404 semantics — with `Authorization: Bearer sb_...` instead of a cookie. Only the SHA-256 hash is stored; the plaintext is returned exactly once, by POST. | Method | Path | Returns | |---|---|---| | GET | `/api/keys` | `{keys:[{id,name,prefix,createdAt,lastUsedAt}],allowed}` — never the hash or a plaintext; `allowed` reports whether the caller's plan includes the `mcp-core` connector | | POST | `/api/keys` | 201 `{id,name,prefix,createdAt,lastUsedAt,key}` — the one and only plaintext reveal; body `{name}` (1–100 chars); **403** when the plan lacks `mcp-core`; **400** past the cap of 10 live keys | | DELETE | `/api/keys/{id}` | `{ok:true}`; revocation is deletion and takes effect immediately. 404 for another user's key | Rules and deliberate semantics: - Keys require the `mcp-core` connector (entitlements catalog: core plan) at **creation AND at every use** — a plan downgrade answers 403 on an otherwise valid key (the notify creation+delivery discipline). - Keys are independent of `tokenVersion`: "sign out everywhere" revokes browser sessions and assertions but NOT API keys, so a gateway link survives a password change. Machine credentials are revoked explicitly, by deleting the key. - API-key requests never impersonate: view-as is cookie-driven and stays browser-only. - The Next.js web proxy signs browser assertions and does not forward client-supplied `Authorization` headers, so keys only work against the Go API directly (dev: `http://localhost:8080`; federated core: `http://superbrain-app:8080` on the `core` network). - `lastUsedAt` is updated at most once a minute per key. ### MCP connections (Superbrain as MCP client) Notion-style outbound connections: users register external MCP servers (Settings → MCP) and Superbrain dials them (`internal/mcpclient`, official `modelcontextprotocol/go-sdk`) over Streamable HTTP or SSE with none / Bearer / custom-header auth. Stored in `McpConnection` (migration 018). | Method | Path | Returns | |---|---|---| | GET | `/api/mcp/connections` | `{connections:[…]}` — secret masked `••••••••` when set, never plaintext | | POST | `/api/mcp/connections` | 201 masked projection; body `{name,url,transport,authKind,headerName?,secret?}`; secret required for bearer/header; cap 10 per user | | PATCH | `/api/mcp/connections/{id}` | masked projection; **requires `version`** (409 on stale); a mask or omitted `secret` keeps the stored value; switching `authKind` to `none` clears it | | DELETE | `/api/mcp/connections/{id}` | `{ok:true}`; 404 for another user's row | | POST | `/api/mcp/connections/{id}/test` | `{ok:true,tools:[{name,description}],count}` after initialize + `tools/list`; **502** `{ok:false,error}` when the server is unreachable/refuses auth — never a silent ok | Rules: dials go through `internal/netguard` (public ranges, ports 80/443 outside tests; user-supplied hosts get no trusted-range exemption); redirects are not followed so a credential cannot be bounced to another host; tests are per-user rate limited (30/h) and draw from the shared outbound budget; header names are restricted to RFC 7230 tokens so a stored name cannot smuggle CRLF into a request. ### WebDAV file shares Users connect external WebDAV shares (Settings → WebDAV; any RFC 4918 service — Nextcloud, Synology, …). A share materializes as a **Collection** whose members are **bookmarks — one per file**, `url` = the file's DAV location. The background engine (`internal/webdav`) re-walks each enabled share every ~30 minutes under a global advisory lease; `WebDavConnection` + `WebDavItem` (migration 020) store credentials and the path↔bookmark ledger. On Core the deployment's `NEXTCLOUD_URL` makes the list carry a one-click suggestion (`https:///remote.php/dav/files/`) — DATA, not a code fork on TIER. The UI composes the viewer's username into the per-user DAV root (`/files//`), and the Core app container pins the Nextcloud hostname to the deployment's public IP (compose `extra_hosts`): the split-horizon private answer has no 443 listener and netguard stays strict. | Method | Path | Returns / behavior | |---|---|---| | GET | `/api/webdav/connections` | `{connections:[…],allowed,suggestions:[…]}` — password masked `••••••••`, never plaintext; `allowed` is the plan gate so the UI never guesses entitlements | | POST | `/api/webdav/connections` | 201 masked projection; `{name,url,username,password}`; password required; cap 10 per user; **403** when the plan lacks the `webdav` connector | | PATCH | `/api/webdav/connections/{id}` | masked projection; **requires `version`** (409 on stale); a mask or omitted `password` keeps the stored value; mask-only PATCH is a 200 no-op without a version bump | | DELETE | `/api/webdav/connections/{id}` | `{ok:true}`; 404 for another user's row. Removes ONLY the connection and its ledger — the Collection and its bookmarks are the user's and stay | | POST | `/api/webdav/connections/{id}/test` | `{ok:true}` when PROPFIND Depth:0 answers 207; **502** `{ok:false,error}` with the dial/credential failure class — never a silent ok | | POST | `/api/webdav/connections/{id}/sync` | `{ok,files,created,reused,updated,kept,removed,truncated}`; 403 when the plan dropped the connector (the engine suppresses such rows the same way); failed dials land on `lastError`, cleared on the next success | Rules: the collection's members are the share's files; re-running a sync is idempotent (etags refresh the ledger only, user-edited title/notes/tags are never overwritten). Removing a file on the server **detaches membership but keeps the bookmark** — sync never destroys user data. A bookmark the user deleted stays deleted (tombstone rows never resurrect), and a membership the user removed stays removed; only a re-created collection (after the user deleted it, FK SET NULL) re-links every still-tracked file. A truncated listing (200 dirs / 1000 files / depth 12 caps) creates new members but never reconciles deletions. Dials are netguard-pinned (ports 80/443 outside tests), credentials travel only in a Basic `Authorization` header (never the URL), and redirects are refused outright. Creation AND every sync re-check `AllowConnector("webdav")` from the entitlement catalog; a downgrade suppresses syncs instead of deleting anything. ### CalDAV calendars Users connect external CalDAV endpoints (Settings -> CalDAV; any RFC 4791 service). Each **server calendar** materializes as its **own Collection** and every in-window **event** becomes a **bookmark** whose `url` is the event's DAV `.ics` location. Discovery accepts a calendar home or a single calendar. The engine (`internal/caldav`) re-queries the rolling window (events starting in the last 30 days through the next 180) every ~30 minutes under its own advisory lease; `CalDavConnection` + `CalDavCalendar` + `CalDavEvent` (migration 021) store credentials, the calendar-to-Collection map and the event-to-bookmark ledger. `NEXTCLOUD_URL` (on Core) makes the list carry a `https:///remote.php/dav/calendars/` suggestion -- DATA, not a code fork. | Method | Path | Returns / behavior | |---|---|---| | GET | `/api/caldav/connections` | `{connections:[...],allowed,suggestions:[...]}` -- each connection carries `calendars:[{href,name,collectionId}]`; password masked, `allowed` is the plan gate | | POST | `/api/caldav/connections` | 201 masked projection; `{name,url,username,password}`; password required; cap 10 per user; **403** when the plan lacks the `caldav` connector | | PATCH | `/api/caldav/connections/{id}` | masked projection; **requires `version`** (409 on stale); a mask or omitted `password` keeps the stored value; mask-only PATCH is a 200 no-op | | DELETE | `/api/caldav/connections/{id}` | `{ok:true}`; 404 for another user's row. Removes only the connection and its ledgers -- the calendar Collections and their bookmarks stay | | POST | `/api/caldav/connections/{id}/test` | `{ok:true,calendars:[name,...]}` after discovery (PROPFIND); **502** `{ok:false,error}` with the dial/credential failure class | | POST | `/api/caldav/connections/{id}/sync` | `{ok,calendars,events,created,reused,updated,kept,removed,truncated}`; 403 when the plan dropped the connector; a failed discovery lands on `lastError` | Rules: same ledger discipline as WebDAV shares -- idempotent syncs, an event's `SUMMARY` titles the bookmark (the calendar's own name is the fallback), an etag change refreshes the ledger without touching user-edited fields, and an event that vanishes OR scrolls past the window **detaches membership but keeps the bookmark**. A user-deleted event bookmark is a tombstone and never resurrects; a user-removed membership stays removed unless its calendar's whole Collection was deleted (FK SET NULL), when the next sync re-creates it and re-links every live event. A calendar that disappears server-side detaches its members and drops its ledger row. One calendar that fails to answer does not abort the others, and a truncated window (50 calendars / 500 events) never reconciles deletions. Basic-auth headers only, no redirects, netguard-pinned; `AllowConnector("caldav")` gates creation AND every sync. ### CardDAV address books Users connect external CardDAV endpoints (Settings -> CardDAV; any RFC 6352 service). Each **server address book** materializes as its **own Collection** and every **contact** becomes a **bookmark** whose `url` is the card's DAV `.vcf` location (`FN` titles it; email/phone ride in the description as display sugar, never rewritten after creation). The engine (`internal/carddav`) re-pulls every enabled connection every ~30 minutes under its own advisory lease; `CardDavConnection` + `CardDavAddressbook` + `CardDavItem` (migration 022) store credentials, the book-to-Collection map and the card ledger. `NEXTCLOUD_URL` (on Core) adds a `…/remote.php/dav/ addressbooks/users/` suggestion. This surface is deliberately separate from the single-config Contacts sync (`POST /api/contacts/sync`, Contact rows): same transport discipline, different product model. | Method | Path | Returns / behavior | |---|---|---| | GET | `/api/carddav/connections` | `{connections:[...],allowed,suggestions:[...]}` -- each connection carries `addressbooks:[{href,name,collectionId}]`; password masked, `allowed` is the plan gate | | POST | `/api/carddav/connections` | 201 masked projection; `{name,url,username,password}`; https-only and port-443-only (Basic-auth credentials never travel elsewhere; escape hatch off in production); cap 10 per user; **403** when the plan lacks the `carddav` connector | | PATCH | `/api/carddav/connections/{id}` | masked projection; **requires `version`** (409 on stale); mask or omitted `password` keeps the stored value | | DELETE | `/api/carddav/connections/{id}` | `{ok:true}`; 404 for another user's row. Removes only the connection and its ledgers -- the collections and contact bookmarks stay | | POST | `/api/carddav/connections/{id}/test` | `{ok:true,addressbooks:[name,...]}` after discovery; **502** `{ok:false,error}` with the failure class | | POST | `/api/carddav/connections/{id}/sync` | `{ok,books,cards,created,reused,updated,kept,removed,truncated}`; 403 when the plan dropped the connector; failed discovery lands on `lastError` | Rules: identical ledger discipline to the WebDAV/CalDAV siblings (idempotent syncs, etag refreshes never touch user-edited fields, vanished cards detach membership but keep the bookmark, user-deleted bookmarks are tombstones, removed memberships stay removed unless the whole Collection was deleted, truncated listings never reconcile deletions, one unreadable book does not abort the rest). Discovery accepts a single address book or a home holding several. Dials pin to **443 only** and refuse redirects; the `carddav` connector gates creation AND every sync. ## Bookmarks Bookmark responses are permission-specific. Owners receive camelCase scalar fields plus `tags:[{tag}]`, `contact`, `sharedWith:[{userId,user}]` and `owner` (with email). Authenticated shared readers receive a narrowed allowlist — URL, title/description, notes, preview metadata, `dueDate`, `isPublic`, timestamps, `tags` and `owner:{id,name}` — never the owner's contact record, the recipient list, alerts, mailbox watches or board placement (`kanbanColumnId`/`kanbanPosition`). The legacy `kanbanStatus` badge IS included and is status, not placement; it is documented here so the projection and UI agree. Detail responses also include `pageLinks:[{pageId,page}]`, limited to the effective user's pages. | Method | Path | Returns / behavior | |---|---|---| | GET | `/api/bookmarks` | Array, newest-updated then ID descending; query `search,tagId,contactId,kanban,date,shared,limit,cursor`; default/max page size 200 | | POST | `/api/bookmarks` | 201 bookmark; body `{url,title?,description?,notes?,dueDate?,alertAt?,kanbanStatus?,contactId?,tagIds?,isPublic?,imapWatchEnabled?,imapQuery?}` | | GET | `/api/bookmarks/{id}` | Owner-full or shared-reader projection if visible; public-only access uses the redacted public endpoint | | PUT | `/api/bookmarks/{id}` | Updated bookmark, owner only; fields above plus `kanbanColumnId`; omitted fields stay unchanged; nullable fields can be cleared. **Requires `version`** (the revision the client edited from): 400 when missing, 409 when stale — success bumps `version` (review CR-04) | | DELETE | `/api/bookmarks/{id}` | `{ok:true}`, owner only | | POST | `/api/bookmarks/{id}/share` | `{ok:true}`; body `{userIds?,isPublic?}`; adds shares | | DELETE | `/api/bookmarks/{id}/share/{userId}` | `{ok:true}`; revokes that direct share | | GET | `/api/bookmarks/{id}/markdown` | Markdown attachment, owned/shared only | | GET | `/api/preview?url=...` | `{title,description,ogTitle,ogDescription,ogImage,favicon}`; nullable on fetch failure | | GET | `/api/public/bookmarks/{id}` | Public bookmark projection without login; private records return 404 | | GET | `/share/bookmark/{id}` | Go serves the same public JSON projection as `/api/public/bookmarks/{id}` at this path (per-client + per-id rate limited). The Next.js server renders the public **HTML** page at the same path for browsers | Browsers get the public **HTML** page at `/share/bookmark/{id}` from the Next.js server; the Go API serves the public **JSON** projection at that same path (table above). For pagination, read the `X-Next-Cursor` response header and pass that opaque value as `cursor` with the same filters. An absent header marks the final page. `limit` must be between 1 and 200. The web proxy forwards the cursor header. Public responses allowlist URL/preview/notes/date/tag fields only; owner identity, contacts, share recipients, mailbox queries, and alert metadata are excluded. Updating `alertAt` resets `alertSent`; replacing `tagIds` is transactional. Tags, columns and contacts are checked for accessibility/ownership. The `version` contract covers the owner-driven PUT (fields and tag replacement) and kanban card moves (`PUT /api/kanban/cards/{id}`): kanban column deletion moves bookmarks server-side and bumps their `version` too, so a stale board save 409s instead of moving a card back into a deleted column. Sharing (`POST /share`) and the server-driven `alertSent` flag are deliberately outside the contract (review CR-04). Input limits are enforced per field, not just by the 1 MiB request-body cap: bookmark `url` 2048, `title` 500, `description` 2000, `notes` 100000 and `imapQuery` 500 characters; tag names 80; page `content` 524288 characters and `icon` 64; collection names/properties/views and item values have their own documented bounds. Caps on these fields reject over-limit input with 400; a few older metadata fields (page titles, kanban labels, collection names/options) still trim to their existing limits. Outbound preview fetches are restricted to HTTP/HTTPS ports 80/443 and mailbox connections to IMAP ports 143/993 (the fixture/LAN escape hatches are test-only). CardDAV keeps the configured HTTPS port. ## Tags, kanban and pages | Method | Path | Returns / behavior | |---|---|---| | GET | `/api/tags` | Owned/shared tags with `_count.bookmarks` and `sharedWith` | | POST | `/api/tags` | 201 tag; body `{name,color?}` | | PUT | `/api/tags/{id}` | Updated tag; body `{name?,color?,shareUserIds?}`, owner only | | DELETE | `/api/tags/{id}` | `{ok:true}` | | DELETE | `/api/tags/{id}/share/{userId}` | `{ok:true}`, revokes tag share | | GET | `/api/kanban/columns` | Ordered columns; creates four defaults if none exist | | POST | `/api/kanban/columns` | 201 column; body `{label,color?}` | | PUT | `/api/kanban/columns` | Ordered columns; body `{order:[id,...]}`, complete permutation required | | PATCH | `/api/kanban/columns/{id}` | Updated column; body `{label?,color?}` | | DELETE | `/api/kanban/columns/{id}` | `{ok:true,movedTo,moved}`; moves cards, never deletes bookmarks; refuses last column | | PUT | `/api/kanban/cards/{id}` | Moved bookmark; body `{columnId,position,version}`. Reorders the target column (0-based position, clamped at the end) and normalizes every card's `kanbanPosition`. Owner only. `version` is REQUIRED: 400 when missing/invalid, 409 when stale; success bumps the moved card's `version` | | GET | `/api/pages?search=...` | Pages, pinned first, with `parentId`, `tags:[{tag}]` and `_count.{bookmarks,children}`; title/content substring search treats `%` and `_` literally and uses trigram indexes | | POST | `/api/pages` | 201 page; body `{title?,content?,parentId?}`. `parentId` must be an owned page; a missing/foreign parent is 400 | | PUT | `/api/pages` | `{ok:true}`; complete `{order:[id,...]}` | | GET | `/api/pages/{id}` | Page plus `tags:[{tag}]`, ordered `bookmarks:[{bookmark}]`, owner-scoped `backlinks:[{id,title,updatedAt}]`, resolved outgoing `links:[{id,title}]`, and `embeds:[{collectionId,viewId,position,collection,view}]` | | PATCH | `/api/pages/{id}` | Updated page; `{title?,content?,pinned?,icon?,parentId?,version?,addBookmarkId?,removeBookmarkId?}`. `version` (the base revision from GET) is REQUIRED with `content`: 400 when missing, 409 when stale. Metadata-only patches (including moving a page) stay version-free and do not bump the revision. Moving under itself or a descendant is rejected 400 (no cycles) | | GET | `/api/pages/{id}/backlinks` | Owner-scoped `[{id,title,updatedAt}]` from `PageLink` — the pages whose Markdown links here | | GET | `/api/pages/{id}/revisions` | Version history metadata `[{id,version,title,icon,createdAt,length}]`, newest first; bodies fetched separately | | GET | `/api/pages/{id}/revisions/{revisionId}` | Full immutable revision snapshot `{...,content}` | | POST | `/api/pages/{id}/revisions/{revisionId}/restore` | Restores a snapshot as a **new** version; body `{version}` (current base) — 400 missing, 409 stale. The restore itself is recorded in history | | DELETE | `/api/pages/{id}` | Moves the page to Trash; keeps bookmarks and promotes child pages. Restoring also restores its revisions and creates a new revision | | GET | `/api/pages/{id}/markdown` | Markdown attachment | | POST | `/api/pages/{id}/tags` | Attaches a tag; body `{tagId}`; returns the refreshed page projection (with `tags`). 400 missing/invalid tag, 404 foreign page. Idempotent (`ON CONFLICT DO NOTHING`) | | DELETE | `/api/pages/{id}/tags/{tagId}` | Detaches a tag; returns the refreshed page projection. 404 foreign page | ### Page tags Pages carry tags like bookmarks (`PageTag`, migration 023). A tag may be attached when it is owned by the caller **or shared with them** — the same rule as bookmark tags. Tagging is metadata: it neither requires nor bumps the page content `version`, and the join row cascades when the page or the tag is deleted. The sidebar's "Untagged Pages" list is derived client-side from the `tags` array on `GET /api/pages` (empty = untagged); dragging a page onto a tag calls `POST /api/pages/{id}/tags`. ### Connected pages (phase 3) Page hierarchy, internal links and live collection embeds are ordinary Markdown contained in the page body; the server rebuilds the resolved graph in the same transaction as every content save: - `[label](superbrain:page/)` links to another page. `/pages?id=` and `page/` are accepted as hand-written aliases. Only owned targets are stored, so a backlink can never reveal another account's page title; self-links are ignored. - `{{collection:}}` embeds the collection's live default view; `{{collection:|view=}}` pins a saved view's filters/sorts. Only owned collections are stored, and item reads still go through the normal collection endpoint, so an embed displays data without publishing it or widening bookmark access. - Deleting a page removes its links/embeds, promotes its children, and keeps its bookmarks. Deleting a collection removes its embeds; deleting a view falls the embed back to the collection's default view. ### Trust (phase 4) Deleting a bookmark, page or collection now moves it to the owner's Trash. The snapshot is taken in the same transaction as the hard delete and includes intrinsic content plus owner-scoped links (tags, page links, collection memberships, page revisions). It deliberately excludes access grants: bookmark public flags, bookmark/tag shares and collection shares are never restored, so revoking access while an item is in the Trash cannot be undone by restoring it. Deleted bookmarks keep their existing delete endpoints; the UI and docs now call this “move to trash”. | Method | Path | Returns / behavior | |---|---|---| | GET | `/api/trash` | Owner's deleted items `[{id,type,originalId,title,deletedAt}]`, newest first | | POST | `/api/trash/{id}/restore` | Restores the item; 404 for another owner. Page restores recreate their history and append a new revision. Neither bookmark `isPublic` nor any share is restored | | DELETE | `/api/trash/{id}` | Permanently removes one Trash entry (explicit purge) | | GET | `/api/export` | Owner-scoped structured JSON archive: user, bookmarks, tags, pages (content + revisions), collections (properties, views, items, shares) and contacts. Credentials are never exported | ## Collections Contextual workflows over existing bookmarks (phase 2 of the Notion-like upgrades). Collections are owner-scoped unless explicitly shared; membership references bookmarks without owning them — removing an item or a whole collection never touches the bookmark. An explicit `CollectionShare` gives a recipient read-only access to the collection and the **narrowed** bookmark projection for member bookmarks **owned by the collection owner**. A bookmark that the collection owner can only see through someone else's share is omitted, so collection sharing never passes a third-party grant onwards. Revoking the share or removing the item removes that access immediately, and mutations remain owner-only. Items whose bookmark the caller cannot see are omitted from lists/counts and behave as not-found for mutations; re-sharing restores the membership. Every mutating PATCH requires the expected `version` (400 missing, 409 stale). Indirect mutations advance revisions too (review CR-09): item reorder bumps every affected item's version, and property deletion bumps the versions of items whose value it dropped and views whose filter/sort definition it changed. Deletions are idempotent removals and take no revision — they never write state computed from a client snapshot. | Method | Path | Returns / behavior | |---|---|---| | GET | `/api/collections` | Owned **and explicitly shared** collections with `shared`, `owner`, `_count.{items,properties,views}`; item counts include only bookmarks the caller can see | | POST | `/api/collections` | 201 detail `{...collection,properties:[],views:[default Table view]}`; body `{name,description?,icon?}` | | GET | `/api/collections/{id}` | Readable collection detail (owner or share recipient) plus ordered `properties`, `views`, authorized `_count`, `shared`; owner also gets `sharedWith` | | PATCH | `/api/collections/{id}` | Updated collection; `{version,name?,description?,icon?}`, bumps `version`; owner only | | DELETE | `/api/collections/{id}` | Moves the collection to Trash; memberships/properties/views cascade, bookmarks kept; owner only | | POST | `/api/collections/{id}/share` | Owner only; `{userIds:[...]}` grants read-only access, idempotent | | DELETE | `/api/collections/{id}/share/{userId}` | Owner only; revokes read-only access immediately | | POST | `/api/collections/{id}/properties` | 201 property; `{name,type,config?}`. Types: `TEXT,NUMBER,SELECT,MULTI_SELECT,DATE,CHECKBOX,URL` (`RELATION` reserved, rejected). SELECT config `{options:[{label,color?}]}` — the server assigns stable option ids; DATE config `{mode:"date"\|"datetime"}`. Duplicate name → 409 | | PATCH | `/api/collections/{id}/properties/{propertyId}` | Updated property; `{version,name?,position?,config?}`. Type and date-mode changes are rejected (400) — conversion must never destroy values. Option updates send the full list: existing ids rename/recolor (identity preserved), omitted ids are removed but refused (400 with the using-item count) while any item still carries them | | DELETE | `/api/collections/{id}/properties/{propertyId}` | `{ok:true}`; strips the property's values from all items and its clauses/sorts/grouping from saved views | | GET | `/api/collections/{id}/items?viewId=&cursor=&limit=` | Items `{...item,bookmark}` (bookmark uses the permission-specific projection), visible bookmarks only, ≤`limit` (default/max 200) with `X-Next-Cursor`. With `viewId`: the view's filters (AND/OR over typed operator allowlists) and its FIRST sort key run server-side; ordering always tie-breaks on item id. Without `viewId`: canonical manual order (`position,id`) | | POST | `/api/collections/{id}/items` | 201 item; `{bookmarkId,propertyValues?}`. 400 if the bookmark is not currently accessible; duplicate membership → 409. Values are validated per property type; DATE values store canonically (`YYYY-MM-DD` or fixed-width UTC RFC3339) so comparisons never shift across timezones | | PUT | `/api/collections/{id}/items` | `{ok:true}`; complete `{order:[itemId,...]}` permutation | | PATCH | `/api/collections/{id}/items/{itemId}` | Updated item; `{version,propertyValues?,position?}`. `propertyValues` merges: omitted keys untouched, `null` removes a value, unknown property ids 400 | | DELETE | `/api/collections/{id}/items/{itemId}` | `{ok:true}`; membership only, bookmark untouched | | POST | `/api/collections/{id}/views` | 201 view; `{name,type?,filters?,sorts?,groupByPropertyId?,displaySettings?}`, types `TABLE,BOARD,CALENDAR,LIST` (default TABLE) | | PATCH | `/api/collections/{id}/views/{viewId}` | Updated view; `{version,name?,type?,position?,filters?,sorts?,groupByPropertyId?,displaySettings?}` | | DELETE | `/api/collections/{id}/views/{viewId}` | `{ok:true}` | Filter shape: `{operator:"AND"|"OR",clauses:[{propertyId,op,value?}]}` (max 20 clauses; no nested groups). Operator allowlists per type: TEXT/URL `eq,ne,contains,empty,notEmpty`; NUMBER/DATE `eq,ne,gt,gte,lt,lte,empty, notEmpty`; SELECT/CHECKBOX `eq,ne,empty,notEmpty`; MULTI_SELECT `contains, empty,notEmpty`. Sorts: max 3 `{field,dir}` where field is `position`, `addedAt`, `title` or a sortable property id (not multi-select); only the first drives server-side ordering/pagination in this phase. `ne` matches missing values (`IS DISTINCT FROM`). Property ids and values are bind parameters end to end — filter JSON never reaches SQL text. Collection sharing does not exist yet; views/counts can only expose what the owner can already see. ## Signals and integrations | Method | Path | Returns / behavior | |---|---|---| | GET | `/api/bookmarks/{id}/signals` | `{sources,signals,types}`, newest 50 events | | POST | `/api/bookmarks/{id}/signals` | 201 watcher for `{type:"email",config:{from?,subject?}}`; `{checked,created}` for `{action:"check"}` | | PATCH | `/api/signal-sources/{id}` | Updated watcher for `{enabled:boolean}` | | DELETE | `/api/signal-sources/{id}` | `{ok:true}` | ### Notifications Rules notify a channel when a fact appears (new signals, due bookmarks, incoming shares). The engine scans every ~60s; rows dedupe on `("ruleId","dedupeKey")`. Channel secrets are write-only: responses mask them (`••••••••`) and a PATCH echoing the mask keeps the stored value. Channel kinds are gated by the tenant's plan (403 `Not available on your plan`); the gate is the entitlement catalog, never the deployment tier. Rules can target people beyond their owner: `config.targetUserIds` (same tenant only, max 20, validated at write time) adds recipients; each targeted row is delivered through THAT user's own enabled channel of the rule's kind (a target without one is `suppressed`, visible in history), and the recipient's tenant plan gates the send. History and delivery rows carry `recipientId` (null = the owner). Deliveries for tenants on the free plan carry the footer "Managed by David's Superbrain."; paying plans and core do not (`entitlements.ManagedFooter`, per-tenant override `managed_footer`). Branded email (multipart/alternative, `internal/mailer/template.html`) carries footer links when `NEXTAUTH_URL` is set: Email preferences (`/settings?tab=notifications`), Help center (`/help`) and — ONLY when the recipient is the owner's own account email — Unsubscribe (`/unsubscribe?token=…`). The token is a stable HMAC-signed user id (`notify.UnsubscribeToken`, no stored row); owner-addressed mail also carries `List-Unsubscribe` + `List-Unsubscribe-Post` (RFC 8058 one-click). Unsubscribe disables the user's enabled email channels and pauses enabled agent email tasks addressed to the user's own email; it is idempotent and never touches transactional mail (password reset) or third-party recipients. | Method | Path | Body / Returns | |---|---|---| | GET | `/api/notifications/channels` | `[{id,kind,name,enabled,version,config(masked),createdAt}]` | | POST | `/api/notifications/channels` | `{kind,name,config,enabled?}` → 201 masked projection; kinds: `email` (optional `address`, falls back to the account email; needs server SMTP), `slack` (`webhookUrl`), `matrix` (`homeserver`,`roomId`,`accessToken`), `telegram` (`botToken`,`chatId`), `signal` (`restUrl`,`account`,`recipient` — signal-cli REST bridge; `account` masked) | | PATCH | `/api/notifications/channels/{id}` | `{version, name?,enabled?,config?}` → 200; 409 on stale version | | DELETE | `/api/notifications/channels/{id}` | `{ok:true}` | | POST | `/api/notifications/channels/{id}/test` | Sends one message immediately → `{ok:true}`; 502 with the delivery error; 429 when the per-user test budget is spent | | GET | `/api/notifications/rules` | `[{id,name,trigger,config,channelId,channelKind,channelName,cooldownMinutes,enabled,lastFiredAt,version}]` | | POST | `/api/notifications/rules` | `{name,trigger,channelId,config?,cooldownMinutes?,enabled?}` → 201; triggers: `signal_created`, `bookmark_due` (`config.leadHours`, default 24), `share_received` (bookmark/tag/collection shared with the owner); `config.targetUserIds?` adds same-tenant recipients | | PATCH | `/api/notifications/rules/{id}` | `{version, name?,enabled?,cooldownMinutes?,channelId?,config?}` → 200; 409 on stale version | | DELETE | `/api/notifications/rules/{id}` | `{ok:true}` | | GET | `/api/notifications` | Last 100 deliveries for rows you own OR were targeted on: `[{id,title,body,status,attempts,ruleName,channelKind,recipientId,sentAt,createdAt}]`; status ∈ pending/sent/failed/suppressed | | POST | `/api/notifications/unsubscribe` | Token-credentialed, NO session: `?token=…` (RFC 8058 one-click; body ignored) or JSON `{token}` → `{ok:true,channels,tasks}`; 400 for invalid/tampered tokens; per-client rate limited | ### Agent automations ("hey superbrain") Natural-language requests compile into a validated task **proposal** (nothing is stored by compile); task creation re-validates the spec server-side — the model is never a trusted source. Conditions: `url_watch` (scheduled fetch of a public URL + one LLM-extracted question, optional numeric/text comparison) and `signal` (new mailbox signals, optional keyword). Actions: `notify` (an owned notification channel), `email` (one recipient; capped at 5 fires per task and 20 per owner per day), `bookmark` (save one URL). Poll floor 15 minutes; `once` tasks complete after firing. Requires `AI_API_KEY` for compile/extraction (503 without); all fetches go through netguard + outbound budgets. | Method | Path | Body / Returns | |---|---|---| | POST | `/api/agent/compile` | `{text}` → `{name,spec,summary}` proposal; 422 with the model's reason when it refuses; 503 when AI is unconfigured; rate-limited per client | | GET | `/api/agent/tasks` | `[{id,name,spec,summary,enabled,status,fireCount,lastCheckedAt,lastFiredAt,version,createdAt}]` | | POST | `/api/agent/tasks` | `{name,spec}` → 201; spec fully re-validated; 403 at the plan's stored-task cap | | PATCH | `/api/agent/tasks/{id}` | `{version,name?,enabled?,spec?}` → 200; 409 stale version; re-enabling resets a `done` task to `active` | | DELETE | `/api/agent/tasks/{id}` | `{ok:true}` | | POST | `/api/agent/tasks/{id}/run` | Immediate evaluation → `{outcome}` ∈ checked/fired/failed/skipped | | GET | `/api/agent/runs?taskId=` | Last 50 runs `[{id,taskId,outcome,detail,createdAt}]` | ### AI configuration (per user) Provider adapters are implementation (`internal/ai`: OpenAI-compatible, Anthropic, Gemini); configuration is data: one encrypted `UserAiConfig` row per user (BYO key, masked in every response, blank/mask on PUT keeps the stored key). Resolution per request: the user's enabled config → else the server env key (`AI_*`) **only when the plan allows it** (`entitlements.AllowServerAI`: premium/core/selfhosted; free/standard are BYO-only) → else 428. Budgets are per user (`ai:user:`) or shared (`ai:server`). | Method | Path | Body / Returns | |---|---|---| | GET | `/api/ai/config` | The caller's masked config or `null` | | PUT | `/api/ai/config` | `{provider,baseUrl?,model,apiKey,enabled?,instructions?,version?}` → 201/200 masked; `version` required once a row exists (409 stale). `instructions` (≤4000 chars) are the user's custom assistant system instructions — full-replacement like `model`/`baseUrl`: omit to clear. They are appended to the assistant chat prompt only, never to the compiler/extraction prompts | | DELETE | `/api/ai/config` | `{ok:true}` | | POST | `/api/ai/test` | One probe completion through the resolved config → `{ok,source,model,reply}`; 428 when nothing is available; 502 with a truncated provider error | | GET | `/api/ai/status` | `{userConfigured,userEnabled,serverAvailable,effective,plan}` — `serverAvailable` is already plan-gated; no secrets | | POST | `/api/ai/chat` | Assistant chat (ephemeral; the browser owns history). `{messages:[{role:user\|assistant,content}]}` (≤40 sent, last 20 used, ≤8000 chars each, last must be `user`) → `{reply, proposal?}`. `proposal` = `{name,spec,summary}` when the model suggested an automation whose spec passes `agent.ValidateSpec` (invalid proposals are silently dropped; model-supplied `channelId`s are scrubbed — the UI picks real channels). Confirming a proposal is a regular `POST /api/agent/tasks`. Per-user limited (30/hour); 428 without AI; 50-second budget inside the proxy window | | GET | `/api/alerts/check` | Undismissed bookmarks due within 15 minutes, soonest first | | DELETE | `/api/alerts/{bookmarkId}` | `{ok:true}`; sets `alertSent` | | GET | `/api/contacts` | Synced contacts with `_count.bookmarks` | | POST | `/api/contacts/sync` | `{synced,removed}`; `{nextcloudUrl,username,password,cardDavPath?}`. Mirrors the configured address book: contacts previously imported from the SAME source URL that the server no longer returns are removed (`removed`), but only on a complete, non-empty snapshot — partial or empty responses never delete. Manually created contacts and other address books' imports are untouched; bookmarks keep working (contactId is SET NULL) | | GET | `/api/settings/imap` | Configuration with masked password, or `null` | | POST | `/api/settings/imap` | `{ok:true}`; `{host,port?,tls?,username,password,folder?}`; empty/masked password preserves an existing password. `port` must be 143 or 993, and TLS is required outside the test/LAN flags | | POST | `/api/imap/test` | `{ok:true}` after real connection/login; same mailbox fields and port rules | | GET | `/api/imap/check` | `{matches:[{bookmarkId,title,from,externalId,occurredAt}]}` for legacy watchers; if a search fails after finding matches, the partial `matches` are returned with an `error` field | | GET | `/api/shared-dates` | Created/received dates with `creator` and `recipient` | | POST | `/api/shared-dates` | 201 array of created shares for `{date,note?,recipientIds:[...]}`. Sharing a date also grants read-only access to the creator's bookmarks due that day (including notes); the UI discloses this. Re-sharing the same date updates its note. | | DELETE | `/api/shared-dates/{id}` | `{ok:true}`, creator only | | GET | `/api/users/search?q=...` | Safe user projections; minimum two characters, maximum ten results | Email signals are deduplicated by source and Message-ID. Failed mailbox checks are recorded on `lastStatus` rather than reported as successful email matches; messages fetched before a partial failure are still persisted (the checkpoint does not advance, so the failed batch is retried and deduplicated). Sharing a tag or date exposes associated bookmarks read-only; direct-share revocation does not remove access independently granted by a tag/date share. ## Administration Always uses the real user, even while viewing another account. | Method | Path | Returns / behavior | |---|---|---| | GET | `/api/admin/users` | Safe user projections with bookmark/page/tag counts; excludes `@example.com` test users | | PATCH | `/api/admin/users` | `{ok:true}` for `{userId,role:"USER"\|"ADMIN"}`; refuses self-demotion | | POST | `/api/admin/oidc-link` | `{ok:true}` for `{userId,subject}`; explicitly links an existing local account to an Authelia subject; `409` when that subject is already linked elsewhere | | POST | `/api/admin/view-as` | `{ok:true}`; `{userId}` sets an eight-hour HttpOnly cookie, `{userId:null}` clears it | Route registration: `internal/http/server.go`. Only the client-owned OIDC login/callback remain stubs; application data routes use PostgreSQL. The trusted Next server exchanges verified Authelia identities at `POST /api/auth/oidc/identity`; that route is not a browser session endpoint.