--- name: Add Endpoint description: Add a new Go API endpoint the Superbrain way — handler + route registration, effective-user resolution, netguard, entitlement gate, write-only secrets, version/409 contract, and tests. Use when adding or changing an HTTP endpoint in internal/. --- # Add an endpoint Data endpoints live in `internal/handlers/*.go` and are registered in `internal/http/server.go` on the `mux`. Every data endpoint resolves the effective user, returns 401 if none, checks ownership, returns 404 if not theirs, then acts. Errors are `{error: string}`; all routes return JSON unless marked `.md`. ## Steps 1. **Handler** in the right `internal/handlers/.go` file. Use the shared helpers from `common.go`: - `user(r)` — effective user id (from the session context). - `database(r)` — the `*db.DB`. - `read(w, r)` — decode a JSON object (1 MiB cap, 413 on oversize). - `writeJSON(w, status, body)` / `Error{...}`. - `bad(...)` → 400, `conflict(...)` → 409 (optimistic concurrency). 2. **Route** in `internal/http/server.go`, e.g. `mux.HandleFunc("POST /api/things", authed(handlers.HandleThingsCreate))`. Use `authed(...)` for session endpoints; `admin(...)` for admin-only. 3. **Identity** — never trust a browser-supplied user id; never use an OIDC `sub` as a local user id. API keys (`sb_...`) resolve in `AuthMiddleware` before assertions. 4. **Secrets** (if the endpoint stores credentials) — encrypt at rest (`internal/crypto`, versioned ciphertext `base64(0x01 || ...)`), mask (`••••••••`) in EVERY response, write-only: a PATCH echoing the mask or omitting the field keeps the stored value. 5. **Outbound dials** — go through `internal/netguard` (`DialContextPorts`/`DialContext`, ports pinned, no redirect following) and draw from the shared budget via `outbound.Reserve(key, limit, window)`. User-supplied hosts get NO `NETGUARD_TRUSTED_HOSTS` exemption. 6. **Plan gate** — gate on the entitlement catalog, never `TIER`: `entitlements.For(plan).AllowConnector(name)` / `AllowChannel(name)` / `AllowServerAI(plan)`. Gate at creation AND at use (downgrade ⇒ suppress). Resolve the caller's tenant plan (see `webdavConnectorGate` in `handlers/webdav.go` for the shape). 7. **Optimistic concurrency** — mutating collection PATCHes take the expected `version`; return 409 (`conflict(...)`) on stale. Page content PATCHes must require `version`. 8. **Tests** — add `internal/http/_test.go` (DB-backed; set secrets with `t.Setenv`, no `t.Parallel()` when using `t.Setenv`). Cover auth (401), ownership (404), the plan gate, and the version/409 path. 9. **Verify** — `make test`, and `make integration` if it touches the DB (see the verify skill). ## Reference - `internal/handlers/webdav.go` — the canonical connector handler (gates, write-only secrets, netguard, version, per-user limiter). - `internal/handlers/common.go` — shared helpers. - `internal/http/server.go` — route registration. - `API.md` — endpoint documentation (keep it in sync).