Files
superbrain/internal/http/server.go
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

290 lines
18 KiB
Go

package http
import (
"context"
"net/http"
"os"
"time"
"github.com/andrew/superbrain/internal/auth"
"github.com/andrew/superbrain/internal/authguard"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/handlers"
"github.com/andrew/superbrain/internal/oidc"
)
// NewServer builds the HTTP server with all routes registered.
// Porting guide section 4 — every data endpoint resolves the effective user,
// returns 401 if none, checks ownership, returns 404 if not theirs, then acts.
//
// All routes return JSON unless marked .md. Errors are {error: string}.
func NewServer(cfg *config.Config, database *db.DB) *http.Server {
mux := http.NewServeMux()
// Health / readiness. No auth, no DB.
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok"}`))
})
mux.HandleFunc("GET /readyz", func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := database.PingContext(ctx); err != nil {
handlers.WriteJSON(w, 503, handlers.Error{Error: "Database unavailable"})
return
}
handlers.WriteJSON(w, 200, map[string]string{"status": "ready"})
})
// 4.1 Auth and account (rate limited for non-loopback peers)
mux.HandleFunc("POST /api/signup", auth.RateLimitSignup(auth.HandleSignup))
mux.HandleFunc("POST /api/auth/login", auth.RateLimitLogin(auth.HandleLogin))
// Self-service password reset (unauthenticated; enumeration-safe and
// rate limited per effective client IP like signup).
mux.HandleFunc("POST /api/password/forgot", auth.RateLimitForgot(auth.HandleForgotPassword))
mux.HandleFunc("POST /api/password/reset", auth.RateLimitReset(auth.HandleResetPassword))
mux.HandleFunc("GET /api/auth/", auth.HandleAuth) // csrf, callbacks, session, signout
mux.HandleFunc("POST /api/auth/", auth.HandleAuth)
mux.HandleFunc("GET /api/me", authed(auth.HandleMe))
// Authelia OIDC (stub-aware; the client drives the flow via NextAuth)
mux.HandleFunc("GET /api/auth/oidc/status", oidc.HandleStatus)
mux.HandleFunc("GET /api/auth/oidc/login", oidc.HandleLogin)
// The Next server exchanges a verified Authelia identity for a local user
// here. This is server-to-server only and requires the oidc-provision
// service token; the OIDC subject is never used as a local User.id.
mux.HandleFunc("POST /api/auth/oidc/identity", auth.HandleOIDCIdentity)
mux.HandleFunc("GET /api/auth/callback/authelia", oidc.HandleCallback)
mux.HandleFunc("POST /api/auth/callback/authelia", oidc.HandleCallback)
// 4.2 Admin (use real user; 403 unless ADMIN)
mux.HandleFunc("GET /api/admin/users", admin(authguard.HandleAdminListUsers))
mux.HandleFunc("PATCH /api/admin/users", admin(authguard.HandleAdminPatchUser))
mux.HandleFunc("POST /api/admin/oidc-link", admin(authguard.HandleAdminLinkOIDC))
mux.HandleFunc("POST /api/admin/view-as", admin(authguard.HandleAdminViewAs))
// 4.3 Bookmarks
mux.HandleFunc("GET /api/bookmarks", authed(handlers.HandleBookmarksList))
mux.HandleFunc("POST /api/bookmarks", authed(handlers.HandleBookmarksCreate))
mux.HandleFunc("GET /api/bookmarks/{id}", authed(handlers.HandleBookmarksGet))
mux.HandleFunc("PUT /api/bookmarks/{id}", authed(handlers.HandleBookmarksUpdate))
mux.HandleFunc("DELETE /api/bookmarks/{id}", authed(handlers.HandleBookmarksDelete))
mux.HandleFunc("POST /api/bookmarks/{id}/share", authed(handlers.HandleBookmarksShare))
mux.HandleFunc("DELETE /api/bookmarks/{id}/share/{userId}", authed(handlers.HandleBookmarkUnshare))
mux.HandleFunc("GET /api/bookmarks/{id}/markdown", authed(handlers.HandleBookmarksMarkdown))
// 4.4 Tags
mux.HandleFunc("GET /api/tags", authed(handlers.HandleTagsList))
mux.HandleFunc("POST /api/tags", authed(handlers.HandleTagsCreate))
mux.HandleFunc("PUT /api/tags/{id}", authed(handlers.HandleTagsUpdate))
mux.HandleFunc("DELETE /api/tags/{id}", authed(handlers.HandleTagsDelete))
mux.HandleFunc("DELETE /api/tags/{id}/share/{userId}", authed(handlers.HandleTagUnshare))
// 4.5 Kanban columns
mux.HandleFunc("GET /api/kanban/columns", authed(handlers.HandleKanbanColumnsList))
mux.HandleFunc("POST /api/kanban/columns", authed(handlers.HandleKanbanColumnsCreate))
mux.HandleFunc("PUT /api/kanban/columns", authed(handlers.HandleKanbanColumnsReorder))
mux.HandleFunc("PATCH /api/kanban/columns/{id}", authed(handlers.HandleKanbanColumnsUpdate))
mux.HandleFunc("DELETE /api/kanban/columns/{id}", authed(handlers.HandleKanbanColumnsDelete))
mux.HandleFunc("PUT /api/kanban/cards/{id}", authed(handlers.HandleKanbanCardsMove))
// 4.6 Pages
mux.HandleFunc("GET /api/pages", authed(handlers.HandlePagesList))
mux.HandleFunc("POST /api/pages", authed(handlers.HandlePagesCreate))
mux.HandleFunc("PUT /api/pages", authed(handlers.HandlePagesReorder))
mux.HandleFunc("GET /api/pages/{id}", authed(handlers.HandlePagesGet))
mux.HandleFunc("PATCH /api/pages/{id}", authed(handlers.HandlePagesUpdate))
mux.HandleFunc("DELETE /api/pages/{id}", authed(handlers.HandlePagesDelete))
mux.HandleFunc("GET /api/pages/{id}/backlinks", authed(handlers.HandlePagesBacklinks))
mux.HandleFunc("GET /api/pages/{id}/revisions", authed(handlers.HandlePageRevisionsList))
mux.HandleFunc("GET /api/pages/{id}/revisions/{revisionId}", authed(handlers.HandlePageRevisionsGet))
mux.HandleFunc("POST /api/pages/{id}/revisions/{revisionId}/restore", authed(handlers.HandlePageRevisionsRestore))
mux.HandleFunc("GET /api/pages/{id}/markdown", authed(handlers.HandlePagesMarkdown))
// Trust phase: recoverable deletions and structured export.
mux.HandleFunc("GET /api/trash", authed(handlers.HandleTrashList))
mux.HandleFunc("POST /api/trash/{id}/restore", authed(handlers.HandleTrashRestore))
mux.HandleFunc("DELETE /api/trash/{id}", authed(handlers.HandleTrashPurge))
mux.HandleFunc("GET /api/export", authed(handlers.HandleExport))
// 4.7 Signals
mux.HandleFunc("GET /api/bookmarks/{id}/signals", authed(handlers.HandleSignalsList))
mux.HandleFunc("POST /api/bookmarks/{id}/signals", authed(handlers.HandleSignalsCreate))
mux.HandleFunc("PATCH /api/signal-sources/{id}", authed(handlers.HandleSignalSourcesUpdate))
mux.HandleFunc("DELETE /api/signal-sources/{id}", authed(handlers.HandleSignalSourcesDelete))
// 4.7b Notifications (DESIGN_NOTIFICATIONS.md): channels, rules, history.
mux.HandleFunc("GET /api/notifications/channels", authed(handlers.HandleNotificationChannelsList))
mux.HandleFunc("POST /api/notifications/channels", authed(handlers.HandleNotificationChannelsCreate))
mux.HandleFunc("PATCH /api/notifications/channels/{id}", authed(handlers.HandleNotificationChannelsUpdate))
mux.HandleFunc("DELETE /api/notifications/channels/{id}", authed(handlers.HandleNotificationChannelsDelete))
mux.HandleFunc("POST /api/notifications/channels/{id}/test", authed(handlers.HandleNotificationChannelsTest))
mux.HandleFunc("GET /api/notifications/rules", authed(handlers.HandleNotificationRulesList))
mux.HandleFunc("POST /api/notifications/rules", authed(handlers.HandleNotificationRulesCreate))
mux.HandleFunc("PATCH /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesUpdate))
mux.HandleFunc("DELETE /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesDelete))
mux.HandleFunc("GET /api/notifications", authed(handlers.HandleNotificationsList))
// 4.7c Agent automations ("hey superbrain"): compile NL into a validated
// proposal (never writes), then owner-confirmed task CRUD + runs.
mux.HandleFunc("POST /api/agent/compile", authed(handlers.CompileLimiter(handlers.HandleAgentCompile)))
mux.HandleFunc("GET /api/agent/tasks", authed(handlers.HandleAgentTasksList))
mux.HandleFunc("POST /api/agent/tasks", authed(handlers.HandleAgentTasksCreate))
mux.HandleFunc("PATCH /api/agent/tasks/{id}", authed(handlers.HandleAgentTasksUpdate))
mux.HandleFunc("DELETE /api/agent/tasks/{id}", authed(handlers.HandleAgentTasksDelete))
mux.HandleFunc("POST /api/agent/tasks/{id}/run", authed(handlers.HandleAgentTasksRun))
mux.HandleFunc("GET /api/agent/runs", authed(handlers.HandleAgentRunsList))
// 4.7d Per-user AI configuration (BYO provider/model/key; the server
// env key is the plan-gated fallback — see internal/ai).
mux.HandleFunc("GET /api/ai/config", authed(handlers.HandleAiConfigGet))
mux.HandleFunc("PUT /api/ai/config", authed(handlers.HandleAiConfigPut))
mux.HandleFunc("DELETE /api/ai/config", authed(handlers.HandleAiConfigDelete))
mux.HandleFunc("POST /api/ai/test", authed(handlers.HandleAiTest))
mux.HandleFunc("GET /api/ai/status", authed(handlers.HandleAiStatus))
// Assistant chat: ephemeral multi-turn with automation proposals
// (per-user rate limited; proposals ride the same validated spec path
// as the compiler — confirm-before-create on the client).
mux.HandleFunc("POST /api/ai/chat", authed(handlers.ChatLimiter(handlers.HandleAiChat)))
// 4.7e Personal API keys (Settings → API Keys): long-lived "sb_..."
// Bearer credentials for machine clients — the superbrain-mcp server the
// federated gateway spawns talks to the Go API with one. Issuance and
// use are gated on the mcp-core connector (core plan).
mux.HandleFunc("GET /api/keys", authed(handlers.HandleAPIKeysList))
mux.HandleFunc("POST /api/keys", authed(handlers.HandleAPIKeysCreate))
mux.HandleFunc("DELETE /api/keys/{id}", authed(handlers.HandleAPIKeysDelete))
// 4.7f Outbound MCP connections (Settings → MCP): user-registered
// external MCP servers Superbrain dials as a client (Notion-style).
// Secrets write-only + masked; PATCH carries version; tests are
// per-user rate limited and draw from the shared outbound budget.
mux.HandleFunc("GET /api/mcp/connections", authed(handlers.HandleMcpConnectionsList))
mux.HandleFunc("POST /api/mcp/connections", authed(handlers.HandleMcpConnectionsCreate))
mux.HandleFunc("PATCH /api/mcp/connections/{id}", authed(handlers.HandleMcpConnectionsUpdate))
mux.HandleFunc("DELETE /api/mcp/connections/{id}", authed(handlers.HandleMcpConnectionsDelete))
mux.HandleFunc("POST /api/mcp/connections/{id}/test", authed(handlers.McpTestLimiter(handlers.HandleMcpConnectionsTest)))
// 4.7g WebDAV shares (Settings → WebDAV): a connected share materializes
// as a Collection of per-file bookmark URLs, synced by internal/webdav.
// Password write-only + masked; PATCH carries version; the `webdav`
// connector entitlement gates creation AND every sync; test/sync are
// per-user rate limited and draw from the shared outbound budget. On Core
// the deployment's NEXTCLOUD_URL is returned as a one-click prefill.
mux.HandleFunc("GET /api/webdav/connections", authed(handlers.HandleWebdavConnectionsList))
mux.HandleFunc("POST /api/webdav/connections", authed(handlers.HandleWebdavConnectionsCreate))
mux.HandleFunc("PATCH /api/webdav/connections/{id}", authed(handlers.HandleWebdavConnectionsUpdate))
mux.HandleFunc("DELETE /api/webdav/connections/{id}", authed(handlers.HandleWebdavConnectionsDelete))
mux.HandleFunc("POST /api/webdav/connections/{id}/test", authed(handlers.WebdavTestLimiter(handlers.HandleWebdavConnectionsTest)))
mux.HandleFunc("POST /api/webdav/connections/{id}/sync", authed(handlers.WebdavSyncLimiter(handlers.HandleWebdavSync)))
// 4.7h CalDAV calendars (Settings → CalDAV): a connected endpoint
// materializes each server calendar as a Collection whose members are
// event bookmarks (URL = the event's DAV .ics location), synced by
// internal/caldav over a rolling window. Same disciplines as WebDAV
// shares; the `caldav` connector gates creation AND every sync; the
// Core NEXTCLOUD_URL is returned as a one-click prefill.
mux.HandleFunc("GET /api/caldav/connections", authed(handlers.HandleCalDavConnectionsList))
mux.HandleFunc("POST /api/caldav/connections", authed(handlers.HandleCalDavConnectionsCreate))
mux.HandleFunc("PATCH /api/caldav/connections/{id}", authed(handlers.HandleCalDavConnectionsUpdate))
mux.HandleFunc("DELETE /api/caldav/connections/{id}", authed(handlers.HandleCalDavConnectionsDelete))
mux.HandleFunc("POST /api/caldav/connections/{id}/test", authed(handlers.CalDavTestLimiter(handlers.HandleCalDavConnectionsTest)))
mux.HandleFunc("POST /api/caldav/connections/{id}/sync", authed(handlers.CalDavSyncLimiter(handlers.HandleCalDavSync)))
// 4.8 Alerts, contacts, email, dates, users
mux.HandleFunc("GET /api/alerts/check", authed(handlers.HandleAlertsCheck))
mux.HandleFunc("DELETE /api/alerts/{bookmarkId}", authed(handlers.HandleAlertsDismiss))
mux.HandleFunc("GET /api/contacts", authed(handlers.HandleContactsList))
mux.HandleFunc("POST /api/contacts/sync", authed(handlers.HandleContactsSync))
mux.HandleFunc("GET /api/settings/imap", authed(handlers.HandleImapGet))
mux.HandleFunc("POST /api/settings/imap", authed(handlers.HandleImapSave))
mux.HandleFunc("POST /api/imap/test", authed(handlers.HandleImapTest))
mux.HandleFunc("GET /api/imap/check", authed(handlers.HandleImapCheck))
mux.HandleFunc("GET /api/shared-dates", authed(handlers.HandleSharedDatesList))
mux.HandleFunc("POST /api/shared-dates", authed(handlers.HandleSharedDatesCreate))
mux.HandleFunc("DELETE /api/shared-dates/{id}", authed(handlers.HandleSharedDateDelete))
mux.HandleFunc("GET /api/users/search", authed(handlers.HandleUsersSearch))
// 4.9 Collections (Notion-like upgrades phase 2). Owner-scoped in this
// phase; membership never broadens bookmark access (N-08).
mux.HandleFunc("GET /api/collections", authed(handlers.HandleCollectionsList))
mux.HandleFunc("POST /api/collections", authed(handlers.HandleCollectionsCreate))
mux.HandleFunc("GET /api/collections/{id}", authed(handlers.HandleCollectionsGet))
mux.HandleFunc("PATCH /api/collections/{id}", authed(handlers.HandleCollectionsUpdate))
mux.HandleFunc("DELETE /api/collections/{id}", authed(handlers.HandleCollectionsDelete))
mux.HandleFunc("POST /api/collections/{id}/share", authed(handlers.HandleCollectionShare))
mux.HandleFunc("DELETE /api/collections/{id}/share/{userId}", authed(handlers.HandleCollectionUnshare))
mux.HandleFunc("POST /api/collections/{id}/properties", authed(handlers.HandleCollectionPropertiesCreate))
mux.HandleFunc("PATCH /api/collections/{id}/properties/{propertyId}", authed(handlers.HandleCollectionPropertiesUpdate))
mux.HandleFunc("DELETE /api/collections/{id}/properties/{propertyId}", authed(handlers.HandleCollectionPropertiesDelete))
mux.HandleFunc("GET /api/collections/{id}/items", authed(handlers.HandleCollectionItemsList))
mux.HandleFunc("POST /api/collections/{id}/items", authed(handlers.HandleCollectionItemsCreate))
mux.HandleFunc("PUT /api/collections/{id}/items", authed(handlers.HandleCollectionItemsReorder))
mux.HandleFunc("PATCH /api/collections/{id}/items/{itemId}", authed(handlers.HandleCollectionItemsUpdate))
mux.HandleFunc("DELETE /api/collections/{id}/items/{itemId}", authed(handlers.HandleCollectionItemsDelete))
mux.HandleFunc("POST /api/collections/{id}/views", authed(handlers.HandleCollectionViewsCreate))
mux.HandleFunc("PATCH /api/collections/{id}/views/{viewId}", authed(handlers.HandleCollectionViewsUpdate))
mux.HandleFunc("DELETE /api/collections/{id}/views/{viewId}", authed(handlers.HandleCollectionViewsDelete))
// 4.10 Public page (no login)
// Review SEC-10/H-2: public endpoints get two rate-limit layers keyed on
// the EFFECTIVE client identity (signed forwarded browser IP, else the
// direct peer), never the shared Next container address:
// - per client: 30 public lookups/min, 20 previews/min;
// - per public bookmark id: 120/min, so one hot shared link cannot
// exhaust the instance-wide budget.
// Preview is rate limited AFTER auth: unauthenticated requests must not
// consume the bucket and deny previews to signed-in users.
publicBookmarkLimiter := auth.NewLimiterStore()
publicBookmarkIDLimiter := auth.NewLimiterStore()
previewLimiter := auth.NewLimiterStore()
publicLimit := auth.Limiter(publicBookmarkLimiter, 30, time.Minute)
publicIDLimit := auth.LimiterKeyed(publicBookmarkIDLimiter, 120, time.Minute, func(r *http.Request) string {
return "bookmark:" + r.PathValue("id")
})
previewLimit := auth.Limiter(previewLimiter, 20, time.Minute)
mux.HandleFunc("GET /share/bookmark/{id}", publicLimit(publicIDLimit(handlers.HandlePublicBookmark)))
mux.HandleFunc("GET /api/public/bookmarks/{id}", publicLimit(publicIDLimit(handlers.HandlePublicBookmark)))
mux.HandleFunc("GET /api/preview", authed(previewLimit(handlers.HandlePreview)))
return &http.Server{
Handler: withDB(database, mux),
Addr: ":" + port(),
ReadTimeout: 15 * time.Second,
WriteTimeout: 60 * time.Second,
IdleTimeout: 60 * time.Second,
}
}
// withDB carries the database into request context so handlers can pull it via
// db.FromContext. This keeps the DB out of global state (testable, swappable).
func withDB(database *db.DB, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := db.NewContext(r.Context(), database)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// authed wraps a data route with session authentication (401 if no valid
// session). All data endpoints follow: resolve effective user -> 401 ->
// ownership -> 404 -> act (porting guide 5.1).
func authed(fn http.HandlerFunc) http.HandlerFunc {
return auth.AuthMiddleware(http.HandlerFunc(fn)).ServeHTTP
}
// admin wraps a route with auth + admin-only (403 unless ADMIN).
// AuthMiddleware runs first (attaches the session), then RequireAdmin checks it.
func admin(fn http.HandlerFunc) http.HandlerFunc {
return auth.AuthMiddleware(auth.RequireAdmin(http.HandlerFunc(fn))).ServeHTTP
}
// port returns the listen port from PORT env, defaulting to 8080.
func port() string {
if p := os.Getenv("PORT"); p != "" {
return p
}
return "8080"
}