Tea journaling on ATProto (alpha) forked from arabica.social/arabica
README.md

JSON API #

The Oolong backend serves a JSON API for every product surface. The Solid frontend under web/ consumes these endpoints. Nothing in this document depends on a frontend framework: these are the contracts an API client or another frontend implementation can build against.

Per-area contracts:

Document Covers
docs/api/entities.md Entity reads/writes (/api/{collection}/...), record models
docs/api/profile.md GET /api/profile/{actor}
docs/api/manage.md GET /api/manage
docs/api/onboarding.md GET /api/onboarding
docs/api/session.md GET /api/session, GET /api/session/status, browser auth flows
docs/api/settings.md GET /api/settings and the settings mutations
docs/api/notifications.md GET /api/notifications, POST /api/notifications/read
docs/api/feed-social.md Feed, comments, likes, reports, suggestions
docs/api/moderation.md /api/moderation/* (moderator/admin)
docs/api/frontend.md Solid frontend: build, routes, development, and E2E fixture

Handler sources: internal/handlers/*_json.go (shared platform surfaces), internal/oolong/handlers/*_json.go (tea-specific surfaces), route tables in internal/routing/routing.go and internal/oolong/handlers/routes.go.

Transport contract #

Negotiation #

internal/routing/routing.go and internal/handlers/api_json.go define one rule set for the whole server:

Request Response
Any /api/* request APIJSONMiddleware forces Accept: application/json; handlers return JSON
Page route (/my-tea, /onboarding, /profile/{actor}, /brews/new, /brews/{id}/edit, /settings, /notifications, /{collection}/{actor}/{id}, .../backlinks) that also publishes data, when the request negotiates JSON The same handler that serves the matching /api/* read (routing.SPAOrJSON), JSON body
Page route without JSON negotiation The Solid shell, which fetches /api/* itself

handlers.WantsJSON treats either Accept: application/json or Content-Type: application/json as a JSON request. JSON answers carry Vary: Accept and Cache-Control: no-store (APIJSONMiddleware). HEAD is supported wherever GET is.

Errors #

Every JSON error is:

{"error": "human readable message", "code": "invalid_request"}

The middleware turns any error written by a JSON-negotiated handler into that envelope: a body that is already JSON with a JSON content type is passed through, while plain text and HTML (several write handlers still answer with http.Error) are replaced by the envelope, so a client never has to parse HTML. Status → code mapping is codeForStatus in internal/handlers/api_json.go; handlers that write JSON directly also use session_expired (only POST /api/settings/bluesky-profile) and service_unavailable with 502 for upstream PDS failures; codeForStatus preserves that mapping for plain-text errors too. Treat the code as the stable part of the contract; the message is written for humans and may change.

The code vocabulary is closed:

Code Status Meaning
invalid_request 400, 413, 422 Malformed body, query, path, or record key
authentication_required 401 No session, or the session expired
session_expired 401 POST /api/settings/bluesky-profile only
permission_denied 403 Missing role/permission, or CSRF rejection
not_found 404 Unknown route, actor, or record
method_not_allowed 405 Wrong HTTP method
conflict 409 Duplicate (e.g. reporting the same record twice)
rate_limited 429 Per-user cap exceeded
service_unavailable 502, 503 Upstream PDS read/write failed, or a feature is disabled
internal_error 500 Unexpected local failure

HTML is never placed in an error body. A page-route 404 requested with Accept: application/json gets the envelope with the HTTP status text as error (internal/handlers/api_json.go:107-127, asserted by TestAPIJSONHTMLBodyIsNotEmbeddedInError). Server errors always report http.StatusText rather than internal detail.

Authentication and CSRF #

  • Sessions are cookies (DID cookie + session cookie) established by the OAuth flow. No token or credential is ever returned in a JSON body.
  • Anonymous access: public reads (/api/feed, /api/profile/{actor}, /api/comments, /{collection}/{actor}/{id}, /api/session, /api/session/status, /api/signup/providers) work; everything else answers 401 authentication_required.
  • Every state-changing route is wrapped in http.CrossOriginProtection (cop in internal/routing/routing.go, applied by the cop.Handler(...) registrations). A cross-site POST is rejected with 403 permission_denied before any handler runs (TestAPICSRFRejectionIsJSON in internal/routing/json_routes_test.go).
  • Moderator/admin routes are gated by RequireModerator / RequirePermission / RequireAdmin (internal/middleware/moderation.go). Moderation is served only under /api/moderation/*; /_mod is the Solid dashboard page.
  • Upstream read failures are distinguished from empty results: an authenticated read of the viewer's own data (/api/manage, /api/onboarding, /api/profile/{actor}, /api/{collection}/{id}) answers 502 service_unavailable when the PDS read fails, and 404 not_found only when the record or actor really is absent. LoadRecords and LoadPublicRecords return the failure instead of an empty list (internal/handlers/entity_view_helpers.go:30-87).
  • OAuth scope failures on PDS writes surface as 401 authentication_required (expired session) or 502 service_unavailable (PDS unreachable) — see docs/api/entities.md.
  • Rating aggregates are viewer-gated: with profile_stats_visibility set to private, tea/vendor rating_average/rating_count and per-entry ratings are zeroed for everyone except the owner (ratingStatsVisible, then hideBacklinkRatings in internal/handlers/entity_json.go), on the entity view and the backlinks endpoint alike.

Endpoint matrix #

Auth shows what the handler itself requires (— = public, user = signed in, mod = moderator, admin = admin).

Method Path Auth Notes Doc
GET /api/session — Never 401s; anonymous gets is_authenticated: false session.md
GET /api/session/status — session_expired heuristic session.md
GET /api/signup/providers — PDS provider catalog for account creation session.md
GET /api/settings user Preferences, visibility, Bluesky sync state settings.md
POST /api/settings/preferences user {temperature_unit} → {"saved":true} settings.md
POST /api/settings/profile-visibility user → {"saved":true} settings.md
POST /api/settings/bluesky-profile user multipart/form-data only settings.md
POST /settings/bluesky-profile/upgrade-scopes user Browser redirect to the auth server settings.md
GET /api/notifications user Read-only, 30/page, cursor notifications.md
POST /api/notifications/read user Marks all read notifications.md
GET /api/feed — Anonymous gets the 10-item cached public feed feed-social.md
GET /api/comments — Flat threaded list, subject_uri required feed-social.md
POST /api/comments user JSON or form feed-social.md
DELETE /api/comments/{id} user → {"deleted":true} feed-social.md
POST /api/likes/toggle user → {is_liked, like_count} feed-social.md
POST /api/report user → {report_id, submitted} feed-social.md
GET /api/suggestions/{entity} user Bare array, community typeahead feed-social.md
GET /api/data user Raw records, no joins manage.md
GET /api/manage user Records + reference joins manage.md
GET /api/onboarding user Station readiness + records onboarding.md
GET /api/profile/{actor} — Public profile bundle profile.md
GET /api/{collection}/{actor}/{id} — Rich entity detail + social + backlinks; ratings gated by the owner's stats visibility entities.md
GET /api/{collection}/{actor}/{id}/backlinks — Paged backlinks; same rating gate entities.md
GET /api/{collection}/{id} user The viewer's own record, for edit forms entities.md
POST /api/{collection} user Create; returns the model entities.md
PUT /api/{collection}/{id} user Replace; returns the model entities.md
DELETE /api/{collection}/{id} user 204 No Content entities.md
GET /api/moderation, /api/moderation/stats mod / admin Dashboard panels moderation.md
POST /api/moderation/{action} mod Shared moderation action handlers moderation.md
GET /api/moderation/export, /pds-records admin / mod Operational moderation.md
POST /api/tea/refresh user Invalidates the session cache and re-syncs the witness cache; 204 No Content manage.md

{collection} is one of teas, brews, vendors, vessels, infusers. cafe and drink are unsupported: no route serves them, and a feed type filter that names one answers 400 invalid_request.

Page routes that also answer JSON #

No route answers a successful request with server-rendered product HTML: HTML navigation gets the Solid shell. Page routes that also serve data select JSON when the request negotiates it (Accept: application/json, see handlers.WantsJSON), and otherwise hand the request to the shell:

Page route JSON answer
GET /my-tea The viewer's collections (manage.md)
GET /onboarding Onboarding state (onboarding.md)
GET /profile/{actor} profile.md
GET /brews/new, GET /brews/{id}/edit {brew, teas, vessels, infusers}; brew is null for create
GET /{collection}/{actor}/{id}, .../backlinks Record view and backlinks (entities.md)
GET /settings settings.md
GET /notifications notifications.md

Not part of the JSON product surface #

GET /login, POST /auth/login, POST /logout, POST /reauth, GET /join/create, POST /join/create, POST /settings/bluesky-profile/upgrade-scopes are browser flows: success is a redirect into (or out of) the OAuth flow. They answer JSON errors when the request negotiates JSON, and POST /join/create accepts a JSON body; POST /auth/login reads the handle form field only. None of them can be completed without navigating a browser.

GET /api/resolve-handle and GET /api/search-actors are public and in active use by the login and home screens as actor autocomplete helpers. They answer with their own shapes rather than the error envelope: resolve-handle returns the Bluesky profile (did, handle, optional displayName/avatar), and search-actors returns {"actors": [...]}, empty when the upstream lookup fails.

Known gaps #

Contract warts a client has to live with today (reported, not hidden):

  • POST /api/likes/toggle returns like_count: 0 when no firehose index is available, even though the like was written (internal/handlers/social_json.go:200-226).
  • GET /api/suggestions/{entity} returns a bare array on success while every error is an envelope.

Checking the contract #

pnpm run build:web   # refresh web/dist and internal/web/spa/build
go test ./internal/routing/ ./internal/handlers/ ./internal/oolong/handlers/ ./internal/web/spa/
go test ./...

Each area doc names the package tests that pin its shapes. For a manual check, tests/e2e/server runs the real router with an in-memory record store, a synthetic session, and the built Solid app, so it needs a frontend build first:

pnpm run build:web
OOLONG_FIXTURE_ADDR=127.0.0.1:18939 go run ./tests/e2e/server

The fixture cannot exercise real OAuth sessions, PDS writes, the moderation store, public getRecord XRPC lookups, or any success path that depends on the SQLite feed index: /api/{collection}/{actor}/{id} success bodies, likes/comments/reports mutations, and most /api/settings and /api/notifications payloads. See frontend.md for the browser suite.

Rules for adding an endpoint (keeps this document true) #

  1. One loader per surface. A page-route JSON view and its /api/* handler share the loader (loadOolongProfileBundle, loadOolongManageBundle, loadSettingsView, resolveFeedRequest, fetchBacklinks); never duplicate the query in the JSON handler.
  2. Under /api/, a success response is JSON. There is no HTML success path.
  3. Return the shared envelope (WriteJSONError) for errors; let the middleware do the HTML→JSON rewrite only as a fallback.
  4. Add the route to the matrix above, and to TestJSONReadRoutesWithoutHTMX in internal/routing/json_routes_test.go, which asserts every JSON read route answers JSON, never redirects, and sends Cache-Control: no-store.