Files
superbrain/API.md
T
Andrew S Erwin a8bd0ab876 CalDAV calendars: each server calendar a Collection, each event a URL bookmark
Settings -> CalDAV connects an external CalDAV endpoint (any RFC 4791
service; on Core the deployment's NEXTCLOUD_URL adds a Nextcloud-calendars
one-click prefill alongside the existing files one). Each server calendar
materializes as its own Collection and every in-window event becomes a
Bookmark carrying the event's DAV .ics URL.

internal/caldav mirrors internal/webdav:
- client.go — PROPFIND discovery (accepts a calendar home via
  calendar-home-set or a single calendar), REPORT calendar-query over a
  rolling window (last 30d .. next 180d), netguard-pinned 80/443, Basic
  auth in the header only, redirects refused, bounded (50 calendars /
  500 events);
- ics.go — RFC 5545 unfolding + first-VEVENT parse (UID/SUMMARY/DTSTART);
- sync.go — RunLoop/RunOnce under a dedicated advisory lease, reconciling
  each calendar to a Collection and each event to a bookmark via the
  CalDavEvent ledger. Same tombstone/detach discipline as WebDAV: a
  vanished OR out-of-window event detaches membership but keeps the
  bookmark; a user-deleted event never resurrects; a re-deleted collection
  is recreated and re-linked; a truncated window never reconciles
  deletions; one unreadable calendar does not abort the rest.

Three tables (CalDavConnection/CalDavCalendar/CalDavEvent) via migration 021
+ schema.sql. Handlers expose /api/caldav/connections CRUD + /test + /sync
with the house credential (encrypted, masked, write-only), version (409 on
stale), and AllowConnector("caldav") plan gate on creation AND every sync.
Wired as the fifth background loop in main.go.

Settings -> CalDAV tab (web/components/caldav-settings.tsx): masked
write-only password, version on PATCH, per-row calendar list, verbatim
test/sync results, Core suggestion prefill with the viewer's email
local-part, allowed flag drives the plan notice.

Verification: full Go integration suite green incl. four TestCalDav*
(lifecycle, collection-recreation, plan gate + suggestion) on an httptest
fake CalDAV server; make db-converge passes; browser regressions all 18
PASS incl. the new CalDAV settings walkthrough; web lint/SSR-lint/build
clean. API.md, README, .env.example, Core installer and local AGENTS
documents updated.
2026-11-15 09:34:33 -06:00

38 KiB
Raw Blame History

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: every user belongs to the implicit default tenant)
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. 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).

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://<nextcloud>/remote.php/dav/files/) — DATA, not a code fork on TIER.

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://<nextcloud>/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.

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

Public HTML pages remain at /share/bookmark/{id} on the Next.js server. 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 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 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

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/<pageId>) links to another page. /pages?id=<id> and page/<id> 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:<collectionId>}} embeds the collection's live default view; {{collection:<collectionId>|view=<viewId>}} 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).

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

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:<id>) 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 channelIds 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.