eleven / ocho Public

Clone
git clone https://amadan.net/eleven/ocho

Plain git — no account needed to clone.

Download

Download this file

1package main
2
3import (
4 "context"
5 "crypto/ed25519"
6 "crypto/rand"
7 "crypto/sha256"
8 "database/sql"
9 "embed"
10 "encoding/base64"
11 "encoding/hex"
12 "encoding/json"
13 "errors"
14 "flag"
15 "fmt"
16 "html"
17 "io"
18 "io/fs"
19 "log"
20 "net"
21 "net/http"
22 "net/url"
23 "os"
24 "os/signal"
25 "strconv"
26 "strings"
27 "sync"
28 "syscall"
29 "time"
30 "unicode/utf8"
31
32 "lchat/internal/apns"
33)
34
35// defaultMaxUploadBytes caps an encrypted attachment upload when
36// LCHAT_MAX_UPLOAD_BYTES is unset: ~50 MB, enough for a short Signal-style video
37// clip plus AES-GCM overhead. The blob is opaque ciphertext — the server can't
38// tell a video from a document.
39const defaultMaxUploadBytes = 50 << 20
40
41// defaultBlobQuotaBytes caps total stored blob bytes per instance when
42// LCHAT_BLOB_QUOTA_BYTES is unset — the disk backstop. Uploads past it are
43// refused (507). Blobs are GC'd on message/thread delete, so this bounds
44// worst-case media growth rather than being a hard forever-ceiling.
45const defaultBlobQuotaBytes = 2 << 30
46
47// maxServerAvatarBytes caps the admin-set instance branding photo. It's tiny by
48// design (the admin console downscales it to ~400px first), so a small cap is
49// plenty and keeps this plaintext asset from being abused as bulk storage.
50const maxServerAvatarBytes = 1 << 20
51
52//go:embed web/pages/*.html web/static/*
53var webFS embed.FS
54
55// The changelog ships inside the binary: one short, user-facing entry per file,
56// named <date>-<slug>.md so filename order is announcement order. The deploy
57// announcer bot (agent/announcer.mjs) polls /api/changelog and posts entries it
58// hasn't seen — "what just shipped" needs no external service, no repo
59// credential, and no operator machine: it travels with the deploy itself.
60//
61//go:embed changelog/*.md
62var changelogFS embed.FS
63
64// The mini-app authoring guide also ships inside the binary, served as plain
65// markdown at /api/app-guide — so a member can point any LLM at that URL and
66// have it learn how to build an app for this instance, with no repo checkout.
67// The static checker the guide's delivery step points at rides along the same
68// way (GET /api/check-app.mjs), so an author without the repo can still run it.
69//
70//go:embed docs/building-apps.md docs/building-member-apps.md tools/check-app.mjs
71var appGuideFS embed.FS
72
73type Server struct {
74 db *DB
75 hub *Hub
76 pages map[string][]byte
77 changelog []ChangelogEntry
78 version string // frontend build hash; clients reload when it changes (see frontendVersion)
79 // Where the welcome page's "Get the app" button points (TestFlight / App
80 // Store link). Empty hides the button — set LCHAT_APP_STORE_URL per instance.
81 appStoreURL string
82 // The home server that hosts passkey backup enrolment. The chat page opens
83 // <homeOrigin>/enroll as a user-initiated popup to back this instance up (see
84 // the enrolment cross-origin contract); set LCHAT_HOME_ORIGIN per deployment.
85 homeOrigin string
86 // The public-web fetch service this instance's clients should prefer for
87 // unfurls (docs/fetch.md) — an origin like https://fetch.example, set via
88 // LCHAT_FETCH_URL. Empty (the default, and the self-host default on
89 // purpose) keeps unfurling on this instance's own /api/unfurl.
90 fetchURL string
91 // The cloud ledger's plan flag, mirrored into this instance's env by the
92 // provisioner (LCHAT_ENTITLEMENT, "free"/"paid"/"demo"). Gates the space
93 // menu's Upgrade entry (free) and the demo countdown band (demo); empty on
94 // self-hosted/operator instances, which have no billing surface and show
95 // nothing. Display only — a claim flips the ledger without restarting this
96 // process, so the band verifies against home's live status before showing.
97 entitlement string
98 // Where this instance's webhook-ingest sidecar is reachable from outside
99 // (LCHAT_HOOKS_BASE, e.g. "http://127.0.0.1:8090" in dev). Empty — the
100 // production default — lets clients derive https://in.<host>; set only
101 // where that derivation is wrong (local dev, unusual fronting). Served as
102 // ingest_base on GET /api/hooks/service; see hooks.go / docs/webhooks.md.
103 hooksBase string
104 vapidPub string
105 vapidPriv string
106 apns apnsSender // nil unless APNs (direct p8 or relay) is configured
107 maxUpload int64 // per-upload attachment cap (LCHAT_MAX_UPLOAD_BYTES)
108 blobQuota int64 // per-instance total blob-bytes ceiling (LCHAT_BLOB_QUOTA_BYTES)
109 // blobMirrorKick nudges the blob mirror sweep after an upload
110 // (blobmirror.go, #992). Nil unless the store is mirrored.
111 blobMirrorKick chan struct{}
112 // The usage-pipe relay (usage.go, #857): where sidecar usage reports go
113 // and the per-space meter token that authenticates them. Pushed into the
114 // env by the provisioner; empty = unmetered (self-hosted / BYO key).
115 meterURL string // LCHAT_METER_URL
116 meterToken string // LCHAT_METER_TOKEN
117 // Directory of sideloaded mini-app modules served at /static/apps-custom/
118 // (LCHAT_APPS_DIR); empty disables the feature. See customapps.go.
119 appsDir string
120 // brakes are the content-blind moderation rate limits (ratelimit.go);
121 // lazily nil-safe via s.brake() so tests constructing Server{} literals
122 // keep working.
123 brakes *modBrakes
124 // The report-notification throttle (issue #578): one push per quiet
125 // window however many reports land. In-memory on purpose — a restart at
126 // worst re-notifies once, and the queue itself is the durable record.
127 reportPushMu sync.Mutex
128 lastReportPush time.Time
129 // inflight coalesces concurrent unfurls of the same URL+language: one
130 // fetch runs, the rest wait on its *previewFlight for the shared result.
131 inflight sync.Map
132 // active tracks the last time each device token reported being open + focused
133 // (token -> unix seconds); activeUsers rolls that up per owner (user id -> unix
134 // seconds) so a new message skips push to ALL of a person's devices when they're
135 // reading on any one of them — not just the exact device they're on.
136 active sync.Map
137 activeUsers sync.Map
138 // presence tracks open sockets + last broadcast state per user, so members
139 // see who's online/away/offline (presence.go).
140 presence presenceTracker
141 // upd caches the last verified release-manifest fetch, so the admin console
142 // can say whether the tracked channel has something newer (updatecheck.go).
143 upd updateState
144 // pay is the payment provider for paid access levels (subscriptions.go).
145 // noPay unless Stripe Connect is configured — the feature is dormant then.
146 pay PayProvider
147 // subFold serializes subscription-event folds: the ordering decision
148 // (read the watermark, then write the row) spans separate statements,
149 // and webhooks arrive concurrently.
150 subFold sync.Mutex
151 // Tamper evidence (checkpoint.go): the per-instance checkpoint signing key.
152 // Empty ckptKeyPath (the default) stores the seed in the DB config so it
153 // rides restores; LCHAT_CHECKPOINT_KEY_FILE overrides to a file. ckptMu
154 // guards lazy loading (success-only caching); ckptSweepMu serializes the
155 // checkpoint sweep so the chain can't fork.
156 ckptKeyPath string
157 ckptMu sync.Mutex
158 ckptKey ed25519.PrivateKey
159 ckptSweepMu sync.Mutex
160}
161
162func main() {
163 // Subcommands: `lchat router` runs the multi-instance front door and the
164 // add-instance/instances/admin-link commands manage it; anything else (bare
165 // `lchat` plus all existing flags) runs a single instance, so existing
166 // invocations are unchanged. See docs/instance-router.md.
167 if len(os.Args) > 1 {
168 switch os.Args[1] {
169 case "router":
170 runRouter(os.Args[2:])
171 return
172 case "bootstrap":
173 runBootstrap(os.Args[2:])
174 return
175 case "add-instance":
176 runAddInstance(os.Args[2:])
177 return
178 case "mesh-seed":
179 runMeshSeed(os.Args[2:])
180 return
181 case "deploy":
182 runDeploy(os.Args[2:])
183 return
184 case "add-service":
185 runAddService(os.Args[2:])
186 return
187 case "add-bot":
188 runAddBot(os.Args[2:])
189 return
190 case "bot":
191 runBotCmd(os.Args[2:])
192 return
193 case "agents":
194 runAgentsCmd(os.Args[2:])
195 return
196 case "add-hooks":
197 runAddHooks(os.Args[2:])
198 return
199 case "hooks":
200 runHooksCmd(os.Args[2:])
201 return
202 case "links":
203 runLinksCmd(os.Args[2:])
204 return
205 case "fetch":
206 runFetchCmd(os.Args[2:])
207 return
208 case "remove":
209 runRemove(os.Args[2:])
210 return
211 case "instances":
212 runInstances(os.Args[2:])
213 return
214 case "env":
215 runEnvCmd(os.Args[2:])
216 return
217 case "hibernate":
218 runHibernate(os.Args[2:])
219 return
220 case "canary":
221 runCanary(os.Args[2:])
222 return
223 case "reset":
224 runReset(os.Args[2:])
225 return
226 case "replication":
227 runReplication(os.Args[2:])
228 return
229 case "relocate":
230 runRelocate(os.Args[2:])
231 return
232 case "admin-link":
233 runAdminLink(os.Args[2:])
234 return
235 case "setup-invite":
236 runSetupInvite(os.Args[2:])
237 return
238 case "version":
239 // The build id compiled in via -ldflags "-X main.buildVersion=<id>".
240 // `stage` reads it from a built binary; the running instance reports it
241 // at /api/version so a deploy can confirm the swap actually took.
242 fmt.Println(buildVersion)
243 return
244 case "stage":
245 runStage(os.Args[2:])
246 return
247 case "install":
248 runInstall(os.Args[2:])
249 return
250 case "rollback":
251 runRollback(os.Args[2:])
252 return
253 case "init-versions":
254 runInitVersions(os.Args[2:])
255 return
256 case "release":
257 runRelease(os.Args[2:])
258 return
259 case "update":
260 runUpdate(os.Args[2:])
261 return
262 case "controld":
263 runControld(os.Args[2:])
264 return
265 case "cloud":
266 runCloud(os.Args[2:])
267 return
268 case "try":
269 runTryCmd(os.Args[2:])
270 return
271 case "relay":
272 runRelayCmd(os.Args[2:])
273 return
274 case "tunnel":
275 runTunnelCmd(os.Args[2:])
276 return
277 }
278 // No case matched. A flag falls through to the single-instance form
279 // below (unchanged); a word does not — it is a typo, and starting a
280 // server for it is how a stray `lchat help` ran for days on a live
281 // box. See subcommands.go.
282 checkSubcommand(os.Args[1])
283 }
284
285 addr := flag.String("addr", envOr("ADDR", ":1747"), "listen address (env: ADDR)")
286 socket := flag.String("socket", envOr("LCHAT_SOCKET", ""), "unix socket to serve on instead of -addr (env: LCHAT_SOCKET); how the router fronts an instance")
287 dbPath := flag.String("db", envOr("LCHAT_DB", "lchat.db"), "path to SQLite database file (env: LCHAT_DB)")
288 resetAdmin := flag.Bool("reset-admin", false, "generate a new admin token and print its link")
289 resetDB := flag.Bool("reset-db", false, "delete and recreate the database")
290 flag.Parse()
291
292 if *resetDB {
293 _ = os.Remove(*dbPath)
294 log.Printf("database reset: %s deleted", *dbPath)
295 }
296
297 db, err := openDB(*dbPath)
298 if err != nil {
299 log.Fatalf("open db: %v", err)
300 }
301
302 // Admin token: LCHAT_ADMIN_TOKEN env wins; otherwise generate one on first run.
303 // NB: LCHAT_-prefixed on purpose — some platforms (e.g. Miren) auto-provision
304 // a secret for a bare "ADMIN_TOKEN" and silently override your value.
305 // TrimSpace guards against env-injection paths that add surrounding whitespace.
306 if tok, err := db.ensureAdminToken(strings.TrimSpace(os.Getenv("LCHAT_ADMIN_TOKEN"))); err != nil {
307 log.Fatalf("admin token: %v", err)
308 } else if tok != "" {
309 printAdminLink(*addr, tok)
310 }
311 if *resetAdmin {
312 tok, err := db.resetAdminToken()
313 if err != nil {
314 log.Fatalf("reset admin token: %v", err)
315 }
316 printAdminLink(*addr, tok)
317 }
318 if err := applySeededName(db); err != nil {
319 log.Fatalf("seeded name: %v", err)
320 }
321 if err := applySkipSetup(db); err != nil {
322 log.Fatalf("skip-setup defaults: %v", err)
323 }
324
325 pages, err := loadPages()
326 if err != nil {
327 log.Fatalf("load pages: %v", err)
328 }
329 hub := newHub()
330 go hub.run()
331 // TrimSpace guards against env-injection paths that add surrounding whitespace;
332 // fall back to the shared home server when unset.
333 homeOrigin := strings.TrimSpace(os.Getenv("LCHAT_HOME_ORIGIN"))
334 if homeOrigin == "" {
335 homeOrigin = defaultHomeOrigin
336 }
337 s := &Server{db: db, hub: hub, pages: pages, changelog: loadChangelog(), version: frontendVersion(),
338 appStoreURL: strings.TrimSpace(os.Getenv("LCHAT_APP_STORE_URL")), homeOrigin: homeOrigin,
339 fetchURL: strings.TrimRight(strings.TrimSpace(os.Getenv("LCHAT_FETCH_URL")), "/"),
340 entitlement: strings.TrimSpace(os.Getenv("LCHAT_ENTITLEMENT")),
341 maxUpload: envBytes("LCHAT_MAX_UPLOAD_BYTES", defaultMaxUploadBytes),
342 blobQuota: envBytes("LCHAT_BLOB_QUOTA_BYTES", defaultBlobQuotaBytes),
343 meterURL: strings.TrimSpace(os.Getenv("LCHAT_METER_URL")),
344 meterToken: strings.TrimSpace(os.Getenv("LCHAT_METER_TOKEN")),
345 hooksBase: strings.TrimRight(strings.TrimSpace(os.Getenv("LCHAT_HOOKS_BASE")), "/"),
346 appsDir: strings.TrimSpace(os.Getenv("LCHAT_APPS_DIR"))}
347 s.brakes = newModBrakes()
348
349 // Tamper evidence (checkpoint.go): by default the signing seed lives in
350 // the DB config so it survives hibernation wakes and migrations; set
351 // LCHAT_CHECKPOINT_KEY_FILE to keep it in a file outside the DB instead.
352 s.ckptKeyPath = strings.TrimSpace(os.Getenv("LCHAT_CHECKPOINT_KEY_FILE"))
353
354 // Web Push: self-generated VAPID keypair (no third-party account).
355 if pub, priv, err := db.ensureVAPID(); err != nil {
356 log.Fatalf("vapid: %v", err)
357 } else {
358 s.vapidPub, s.vapidPriv = pub, priv
359 }
360 s.apns = newAPNsClient()
361
362 // Paid access levels (subscriptions.go): the Stripe Connect provider, or
363 // noPay (dormant) when unconfigured. The grace→revoke sweep only matters
364 // once entitlements exist; harmless to always run.
365 s.pay = newPayProvider(db)
366 s.startBillingSweep()
367
368 // Mini-app scheduling: deliver due "future messages" (miniapps.go). Tests
369 // call sweepDueScheduled directly, so only the real server runs the ticker.
370 go s.runScheduler()
371 go s.runUpdateChecker()
372 // Presence idle sweep (presence.go). Tests call sweepPresence directly.
373 go s.runPresenceSweeper()
374 // Blob mirror + audit sweeps (blobmirror.go, #992). No-op unless the
375 // store is mirrored; tests call mirrorOnce/auditBlobsOnce directly.
376 s.startBlobMirror()
377 // Tamper evidence: fold new journal rows into signed checkpoints
378 // (checkpoint.go). Tests call sweepCheckpoint directly.
379 go s.runCheckpointer()
380 // Push release notes new in THIS binary to the admins (announce.go). Tests
381 // call announceChangelog directly.
382 go s.announceChangelog()
383
384 ln, where, err := listen(*addr, *socket)
385 if err != nil {
386 log.Fatalf("listen: %v", err)
387 }
388 log.Printf("lchat listening on %s (db: %s)", where, *dbPath)
389
390 // ReadHeaderTimeout caps how long a client may dribble request headers
391 // (Slowloris): standalone self-hosts bind this listener straight to public
392 // TCP. Same 10s the router/cloud/controld listeners use.
393 srv := &http.Server{Handler: s.handler(), ReadHeaderTimeout: 10 * time.Second}
394 go func() {
395 if err := srv.Serve(ln); err != nil && err != http.ErrServerClosed {
396 log.Fatalf("serve: %v", err)
397 }
398 }()
399
400 // Graceful shutdown on SIGTERM/SIGINT (systemd stop/restart during a deploy):
401 // stop accepting + drain in-flight HTTP, then close WebSockets so clients
402 // reconnect to the new process. The router retries dials across the brief gap,
403 // so no request is dropped. See docs/instance-router.md.
404 sigCh := make(chan os.Signal, 1)
405 signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
406 <-sigCh
407 log.Printf("lchat: draining and shutting down")
408 // Drain in-flight HTTP (e.g. a large upload) before exiting. Kept below the
409 // router's dial-retry window so the socket-absent gap during a deploy stays
410 // within what the router masks.
411 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
412 defer cancel()
413 _ = srv.Shutdown(ctx)
414 hub.shutdown()
415}
416
417// listen returns the instance's listener. With -socket set it serves on a unix
418// domain socket (how the router fronts an instance — see docs/instance-router.md);
419// otherwise it's a TCP listener on addr (the standalone default, unchanged). A
420// stale socket left by a crashed process is removed first (but a socket another
421// process is still serving on refuses to start), and the socket is chmod 0600 so
422// only the router (same user) can dial it.
423func listen(addr, socketPath string) (net.Listener, string, error) {
424 if socketPath == "" {
425 ln, err := net.Listen("tcp", addr)
426 return ln, addr, err
427 }
428 // Don't clobber a live socket: only a stale one (nothing listening) is removed.
429 if c, err := net.DialTimeout("unix", socketPath, 200*time.Millisecond); err == nil {
430 c.Close()
431 return nil, "", fmt.Errorf("socket %s is already in use by another process", socketPath)
432 }
433 if err := os.Remove(socketPath); err != nil && !os.IsNotExist(err) {
434 return nil, "", fmt.Errorf("remove stale socket %s: %w", socketPath, err)
435 }
436 ln, err := net.Listen("unix", socketPath)
437 if err != nil {
438 return nil, "", err
439 }
440 if err := os.Chmod(socketPath, 0o600); err != nil {
441 ln.Close()
442 return nil, "", fmt.Errorf("chmod socket %s: %w", socketPath, err)
443 }
444 return ln, "unix:" + socketPath, nil
445}
446
447// handler wires up all routes. It's a method so tests can exercise the full
448// router via httptest without starting a real listener.
449func (s *Server) handler() http.Handler {
450 // The moderation brakes (ratelimit.go) exist before the first request —
451 // handler() is the one door every construction path (main, tests) passes
452 // through, so the lazy s.brake() fallback never races concurrent handlers.
453 if s.brakes == nil {
454 s.brakes = newModBrakes()
455 }
456 staticFS, err := fs.Sub(webFS, "web/static")
457 if err != nil {
458 log.Fatalf("static fs: %v", err)
459 }
460
461 mux := http.NewServeMux()
462 // Pages
463 mux.HandleFunc("GET /", s.servePage("index.html"))
464 mux.HandleFunc("GET /admin", s.servePage("admin.html"))
465 mux.HandleFunc("GET /join/{token}", s.servePage("join.html"))
466 mux.Handle("GET /static/", noCache(http.StripPrefix("/static/", http.FileServer(http.FS(staticFS)))))
467 // Custom (sideloaded) mini-apps. Deliberately one segment below /static/ so a
468 // custom app's relative `import "../apps.js"` resolves to /static/apps.js —
469 // same imports as a compiled-in app. See customapps.go for the trust model.
470 mux.Handle("GET /static/apps-custom/{name}", noCache(http.HandlerFunc(s.serveCustomApp)))
471 mux.HandleFunc("GET /api/apps", s.getCustomApps)
472 // The integrations registry (public, like /api/apps): which services can
473 // be connected and exactly what each op may do. See integrations_api.go.
474 mux.HandleFunc("GET /api/integrations", s.getIntegrations)
475 // Installing/removing custom apps is admin-only, like the rest of /api/admin.
476 mux.HandleFunc("GET /api/admin/apps", s.listCustomAppsHandler)
477 mux.HandleFunc("PUT /api/admin/apps/{name}", s.putCustomAppHandler)
478 mux.HandleFunc("DELETE /api/admin/apps/{name}", s.deleteCustomAppHandler)
479 // Member-built apps (memberapps.go): instance-key-encrypted blobs the client
480 // runs only inside the sandbox frame below. Deploying is member-gated.
481 mux.HandleFunc("GET /api/member-apps", s.listMemberAppsHandler)
482 mux.HandleFunc("GET /api/member-apps/{id}/versions", s.memberAppVersionsHandler)
483 mux.HandleFunc("PUT /api/member-apps/{id}", s.putMemberAppHandler)
484 mux.HandleFunc("DELETE /api/member-apps/{id}", s.deleteMemberAppHandler)
485 // Member bots (memberbots.go): opaque charter blobs, stored like member
486 // apps; the sidecar decrypts and runs them (docs/member-bots.md).
487 mux.HandleFunc("GET /api/member-bots", s.listMemberBotsHandler)
488 mux.HandleFunc("PUT /api/member-bots/{id}", s.putMemberBotHandler)
489 mux.HandleFunc("DELETE /api/member-bots/{id}", s.deleteMemberBotHandler)
490 // The charter host's wake-time report (bot-token-gated; folded into
491 // GET /api/next-due so hibernated charters still fire on time).
492 mux.HandleFunc("POST /api/charter-next-due", s.postCharterNextDue)
493 mux.HandleFunc("POST /api/bot-usage", s.postBotUsage)
494 // Incoming webhooks (hooks.go, docs/webhooks.md): admin-managed registry of
495 // opaque definition blobs the hooks sidecar polls; deployed is the sidecar's
496 // plaintext go-live ack.
497 mux.HandleFunc("GET /api/hooks/service", s.getHooksService)
498 mux.HandleFunc("POST /api/hooks", s.createWebhookHandler)
499 mux.HandleFunc("PUT /api/hooks/{id}/blobs", s.putWebhookBlobsHandler)
500 mux.HandleFunc("GET /api/hooks", s.listWebhooksHandler)
501 mux.HandleFunc("GET /api/hooks/defs", s.listWebhookDefsHandler)
502 mux.HandleFunc("POST /api/hooks/{id}/deployed", s.webhookDeployedHandler)
503 mux.HandleFunc("DELETE /api/hooks/{id}", s.deleteWebhookHandler)
504 // The sandbox frame document: an opaque-origin cage for member-app code.
505 mux.HandleFunc("GET /app-sandbox", s.serveAppSandbox)
506
507 // Chat API (transport auth via invite token; never sees plaintext)
508 mux.HandleFunc("GET /api/messages", s.getMessages)
509 // Tamper evidence: the signed checkpoint chain over the event journal
510 // (checkpoint.go; docs/tamper-evidence.md). Member-gated like messages.
511 mux.HandleFunc("GET /api/checkpoints", s.getCheckpoints)
512 // Merkle inclusion proof that a held message is committed to the chain
513 // (checkpoint.go; docs/tamper-evidence.md client sampling). Member-gated.
514 mux.HandleFunc("GET /api/checkpoint-proof", s.getCheckpointProof)
515 mux.HandleFunc("POST /api/messages", s.postMessage)
516 // Message permalinks ("Copy link", issue #893): mint an opaque, server-
517 // sealed token for a message; resolve turns it back into ids only for a
518 // caller who is currently a thread member (links.go).
519 mux.HandleFunc("POST /api/messages/{id}/link", s.mintMessageLink)
520 mux.HandleFunc("POST /api/resolve-link", s.resolveMessageLink)
521 mux.HandleFunc("GET /ws", s.handleWS)
522
523 // Threads & roster (see docs/threads-and-dms.md). The roster is the open
524 // directory; threads (DMs/groups) carry server-blind, per-member wrapped keys.
525 mux.HandleFunc("POST /api/pubkey", s.setPubkey)
526 mux.HandleFunc("GET /api/roster", s.getRoster)
527 mux.HandleFunc("GET /api/bot-config", s.getBotConfig)
528 mux.HandleFunc("POST /api/bot-config", s.declareBotKind)
529 mux.HandleFunc("GET /api/me", s.getMe)
530 mux.HandleFunc("POST /api/device/signout", s.signout)
531 mux.HandleFunc("POST /api/apns/subscribe", s.apnsSubscribe)
532 mux.HandleFunc("POST /api/apns/unsubscribe", s.apnsUnsubscribe)
533 // Instance key + profile photos: a shared key for all-members content (avatars).
534 mux.HandleFunc("GET /api/instance-key", s.getInstanceKey)
535 mux.HandleFunc("POST /api/instance-key", s.postInstanceKey)
536
537 // The space thread — the hidden all-members thread backing space-wide apps
538 // (spacethread.go, docs/space-apps.md).
539 mux.HandleFunc("GET /api/space-thread", s.getSpaceThread)
540 mux.HandleFunc("POST /api/space-thread", s.postSpaceThread)
541 mux.HandleFunc("POST /api/admin/space-thread/reset", s.resetSpaceThreadHandler)
542 mux.HandleFunc("POST /api/instance-key/nudge", s.nudgeInstanceKey)
543 mux.HandleFunc("POST /api/admin/instance-key/reset", s.resetInstanceKeyHandler)
544 // Tiers: admin-curated member sets with their own keys (docs/community-and-tiers.md).
545 mux.HandleFunc("GET /api/tiers", s.getTiers)
546 mux.HandleFunc("POST /api/tiers", s.postTier)
547 mux.HandleFunc("DELETE /api/tiers/{id}", s.deleteTierHandler)
548 mux.HandleFunc("POST /api/tiers/{id}/members", s.postTierMember)
549 mux.HandleFunc("POST /api/tiers/{id}/remove", s.postTierRemove)
550 mux.HandleFunc("POST /api/tiers/{id}/keys", s.postTierKeys)
551 mux.HandleFunc("POST /api/tiers/{id}/nudge", s.nudgeTierKey)
552 mux.HandleFunc("POST /api/tiers/{id}/policy", s.postTierPolicy)
553 mux.HandleFunc("POST /api/tiers/{id}/show", s.postTierShow)
554 // Paid access levels (subscriptions.go): admin price + account, member
555 // subscribe/change/cancel/portal, and the provider webhook (public — its
556 // signature is the auth). Dormant when no provider is configured.
557 mux.HandleFunc("POST /api/tiers/{id}/price", s.postTierPrice)
558 mux.HandleFunc("POST /api/tiers/{id}/subscribe", s.postTierSubscribe)
559 mux.HandleFunc("POST /api/tiers/{id}/change", s.postTierChange)
560 mux.HandleFunc("POST /api/tiers/{id}/cancel-subscription", s.postTierCancelSub)
561 mux.HandleFunc("POST /api/tiers/{id}/resume", s.postTierResume)
562 mux.HandleFunc("POST /api/tiers/{id}/portal", s.postTierPortal)
563 mux.HandleFunc("POST /api/admin/billing/account", s.postBillingAccount)
564 mux.HandleFunc("GET /api/admin/billing", s.getBillingStatus)
565 mux.HandleFunc("POST /api/billing/webhook", s.stripeConnectWebhook)
566 mux.HandleFunc("POST /api/label", s.postLabel)
567 mux.HandleFunc("POST /api/label/backfill", s.postLabelBackfill)
568 mux.HandleFunc("POST /api/presence", s.postPresence)
569 mux.HandleFunc("POST /api/avatar", s.postAvatar)
570 mux.HandleFunc("POST /api/description", s.postDescription)
571 mux.HandleFunc("GET /api/nicknames", s.getNicknames)
572 mux.HandleFunc("POST /api/nicknames", s.postNicknames)
573 mux.HandleFunc("GET /api/prefs", s.getPrefs)
574 mux.HandleFunc("POST /api/prefs", s.postPrefs)
575 mux.HandleFunc("POST /api/dm-privacy", s.postDMPrivacy)
576 mux.HandleFunc("GET /api/blocks", s.getBlocks)
577 mux.HandleFunc("POST /api/blocks", s.postBlock)
578 mux.HandleFunc("DELETE /api/blocks/{id}", s.deleteBlock)
579 mux.HandleFunc("POST /api/reports", s.postReport)
580 mux.HandleFunc("GET /api/admin/reports", s.adminReports)
581 mux.HandleFunc("POST /api/admin/reports/{id}/resolve", s.resolveReportHandler)
582 mux.HandleFunc("POST /api/admin/warn", s.adminWarn)
583 mux.HandleFunc("GET /api/admin/audit", s.adminAudit)
584 mux.HandleFunc("POST /api/admin/users/{id}/ban", s.banUser)
585 mux.HandleFunc("POST /api/group-description", s.postGroupDescription)
586 mux.HandleFunc("GET /api/threads", s.getThreads)
587 mux.HandleFunc("POST /api/threads", s.postThread)
588 mux.HandleFunc("GET /api/threads/open", s.getOpenThreads)
589 mux.HandleFunc("POST /api/threads/{id}/join", s.postThreadJoin)
590 mux.HandleFunc("POST /api/threads/{id}/visibility", s.postThreadVisibility)
591 mux.HandleFunc("POST /api/threads/{id}/default", s.postThreadDefault)
592 mux.HandleFunc("POST /api/threads/{id}/members", s.postThreadMember)
593 mux.HandleFunc("POST /api/threads/{id}/name", s.postThreadName)
594 mux.HandleFunc("POST /api/threads/{id}/avatar", s.postThreadAvatar)
595 mux.HandleFunc("POST /api/threads/{id}/leave", s.postThreadLeave)
596 mux.HandleFunc("POST /api/threads/{id}/cancel-invite", s.cancelInvite)
597 mux.HandleFunc("POST /api/threads/{id}/remove", s.postThreadRemove)
598 mux.HandleFunc("POST /api/threads/{id}/hidden", s.postThreadHidden)
599 mux.HandleFunc("POST /api/threads/{id}/pinned", s.postThreadPinned)
600 mux.HandleFunc("POST /api/threads/{id}/muted", s.postThreadMuted)
601 mux.HandleFunc("POST /api/threads/{id}/close-dm", s.postCloseDM)
602 mux.HandleFunc("POST /api/threads/{id}/reopen-dm", s.postReopenDM)
603 mux.HandleFunc("POST /api/threads/{id}/read", s.postThreadRead)
604
605 // Mini-apps (miniapps.go): scheduled "future messages" + per-thread state
606 // snapshots. Both carry only client-encrypted blobs; both are member-gated.
607 mux.HandleFunc("POST /api/schedule", s.postSchedule)
608 mux.HandleFunc("GET /api/schedule", s.getSchedules)
609 mux.HandleFunc("DELETE /api/schedule/{id}", s.deleteSchedule)
610 // The activator's due-time probe (admin-gated; queried over the instance
611 // socket at sleep time so hibernated schedules still fire on time).
612 mux.HandleFunc("GET /api/next-due", s.getNextDue)
613 mux.HandleFunc("GET /api/threads/{id}/state", s.getThreadStateHandler)
614 mux.HandleFunc("PUT /api/threads/{id}/state", s.putThreadStateHandler)
615
616 // Connected third-party services (docs/connected-services.md): opaque,
617 // client-encrypted credential blobs keyed per member. Token-gated; the server
618 // never reads inside.
619 mux.HandleFunc("GET /api/connected", s.listConnected)
620 mux.HandleFunc("GET /api/connected/{service}", s.getConnected)
621 mux.HandleFunc("PUT /api/connected/{service}", s.putConnected)
622 mux.HandleFunc("DELETE /api/connected/{service}", s.deleteConnected)
623 // OAuth connect (docs/connected-services.md): public config for the browser to
624 // start a PKCE flow, and the redirect landing that relays the code back.
625 mux.HandleFunc("GET /api/oauth/config", s.oauthConfig)
626 mux.HandleFunc("GET /oauth/{service}/callback", s.oauthCallbackPage)
627
628 // Encrypted attachments: bytes are E2E-encrypted in the browser; the server
629 // stores/serves opaque blobs only. Both ends are token-gated.
630 mux.HandleFunc("POST /api/upload", s.uploadBlob)
631 mux.HandleFunc("GET /api/blob/{id}", s.getBlobHandler)
632
633 // Link previews: the server fetches a posted URL to build an OpenGraph card,
634 // caches it, and serves cached results immediately (refreshing stale ones).
635 mux.HandleFunc("GET /api/unfurl", s.unfurl)
636
637 // Key-invites (invite redesign): server stores a client-wrapped key it can't
638 // open; claiming mints a device token. See docs/invite-redesign.md.
639 mux.HandleFunc("GET /api/key-invite/{id}", s.getKeyInvite)
640 mux.HandleFunc("POST /api/key-invite/{id}/claim", s.claimKeyInvite)
641 mux.HandleFunc("POST /api/key-invite/{id}/adopt", s.adoptKeyInvite)
642 mux.HandleFunc("POST /api/admin/key-invites", s.createKeyInvite)
643 mux.HandleFunc("GET /api/admin/tiers", s.adminTiers)
644 mux.HandleFunc("GET /api/admin/users", s.listUsers)
645 mux.HandleFunc("POST /api/admin/users/{id}/remove", s.removeUser)
646 mux.HandleFunc("POST /api/admin/users/{id}/label", s.renameUser)
647 mux.HandleFunc("GET /api/admin/bots/{id}/config", s.getAdminBotConfig)
648 mux.HandleFunc("POST /api/admin/bots/{id}/config", s.setAdminBotConfig)
649 // A member can mint a fresh invite for their own account (add a device).
650 mux.HandleFunc("POST /api/device-invites", s.createDeviceInvite)
651 // A member can invite a new person straight into a DM (gated by an admin setting).
652 mux.HandleFunc("POST /api/invites", s.postUserInvite)
653
654 // Group name (public read so the page/manifest can show it; admin write)
655 mux.HandleFunc("GET /api/group", s.getGroup)
656 // Server avatar: per-instance branding photo. Public read (shown in onboarding,
657 // the home Save-passkey card, and native add-chat — all before any key exists);
658 // admin write/clear. Served in the clear like the group name (see getServerAvatar).
659 mux.HandleFunc("GET /api/server-avatar", s.getServerAvatar)
660 mux.HandleFunc("POST /api/admin/server-avatar", s.setServerAvatar)
661 mux.HandleFunc("DELETE /api/admin/server-avatar", s.deleteServerAvatar)
662 // Frontend build version — clients poll this on returning to the app and reload
663 // if it changed (auto-update). No auth: it's just a build hash.
664 mux.HandleFunc("GET /api/version", s.getVersion)
665 mux.HandleFunc("GET /api/update-prefs", s.getUpdatePrefs)
666 mux.HandleFunc("GET /api/changelog", s.getChangelog)
667 // The mini-app authoring guide. Static documentation compiled into the
668 // binary — never instance data — so, like /api/version, it isn't token-gated:
669 // the whole point is that an external LLM can be pointed straight at it.
670 mux.HandleFunc("GET /api/app-guide", s.getAppGuide)
671 mux.HandleFunc("GET /api/member-app-guide", s.getMemberAppGuide)
672 mux.HandleFunc("GET /api/check-app.mjs", s.getAppChecker)
673 mux.HandleFunc("POST /api/admin/group", s.setGroup)
674 // Sealed branding (docs/no-plaintext.md): the client-sealed branding set
675 // and its reversal. Admin-gated; the ciphertext is produced client-side.
676 mux.HandleFunc("POST /api/admin/branding/seal", s.sealBranding)
677 mux.HandleFunc("POST /api/admin/branding/unseal", s.unsealBranding)
678
679 // Admin API (requires admin token)
680 mux.HandleFunc("GET /api/admin/settings", s.getSettings)
681 mux.HandleFunc("POST /api/admin/settings", s.setSettings)
682
683 // Web Push (VAPID self-generated; pushed payload is ciphertext, decrypted in the SW)
684 mux.HandleFunc("GET /api/push/vapid", s.getVAPID)
685 mux.HandleFunc("POST /api/push/subscribe", s.subscribePush)
686 mux.HandleFunc("POST /api/push/unsubscribe", s.unsubscribePush)
687 mux.HandleFunc("POST /api/admin/test-push", s.testPush)
688
689 // PWA: the service worker must be served from the root scope; manifest for install
690 mux.HandleFunc("GET /sw.js", s.serveSW)
691 mux.HandleFunc("GET /manifest.webmanifest", s.serveManifest)
692 // Universal links: lets invite links on this instance's domain open straight
693 // into the iOS app when it's installed (every instance is its own domain, and
694 // every instance is this same binary, so each serves its own association file).
695 mux.HandleFunc("GET /.well-known/apple-app-site-association", serveAASA)
696
697 return securityHeaders(mux)
698}
699
700// securityHeaders adds defense-in-depth headers to every response. The page
701// Content-Security-Policy needs a per-request nonce, so it's set in servePage;
702// these are the static ones that apply everywhere (including the blob download,
703// where nosniff stops a mistyped blob being sniffed as HTML).
704func securityHeaders(next http.Handler) http.Handler {
705 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
706 h := w.Header()
707 h.Set("X-Content-Type-Options", "nosniff")
708 h.Set("X-Frame-Options", "DENY")
709 h.Set("Referrer-Policy", "no-referrer")
710 // Ignored by browsers over plain HTTP (e.g. local dev); applies in prod
711 // where every instance is served over TLS.
712 h.Set("Strict-Transport-Security", "max-age=31536000")
713 next.ServeHTTP(w, r)
714 })
715}
716
717// cspNonce returns a fresh per-response nonce for the pages' inline <script>
718// tags, so the CSP can allow exactly those and reject any injected script.
719func cspNonce() string {
720 var b [16]byte
721 if _, err := rand.Read(b[:]); err != nil {
722 return "" // fail closed: no inline script will match an empty nonce
723 }
724 return base64.StdEncoding.EncodeToString(b[:])
725}
726
727// ---- pages --------------------------------------------------------------
728
729func loadPages() (map[string][]byte, error) {
730 pages := map[string][]byte{}
731 for _, name := range []string{"index.html", "admin.html", "join.html"} {
732 b, err := webFS.ReadFile("web/pages/" + name)
733 if err != nil {
734 return nil, err
735 }
736 pages[name] = b
737 }
738 return pages, nil
739}
740
741// requestBase reconstructs the external scheme+host (e.g. "https://chat.paulca.com")
742// as the browser reached us. The router terminates TLS and proxies over a unix
743// socket, so the real scheme rides in X-Forwarded-Proto (SetXForwarded, router.go);
744// prod is always TLS, so default to https when unproxied.
745func requestBase(r *http.Request) string {
746 scheme := "https"
747 if xfp := r.Header.Get("X-Forwarded-Proto"); xfp != "" {
748 scheme = xfp
749 } else if r.TLS == nil {
750 scheme = "http"
751 }
752 return scheme + "://" + r.Host
753}
754
755func (s *Server) servePage(name string) http.HandlerFunc {
756 return func(w http.ResponseWriter, r *http.Request) {
757 // "GET /" matches everything; only the exact root serves the chat page.
758 if name == "index.html" && r.URL.Path != "/" {
759 http.NotFound(w, r)
760 return
761 }
762 // A per-request nonce whitelists exactly the pages' own inline <script>
763 // blocks, so an injected inline script (the highest-value attack here — it
764 // could read the private key out of localStorage) is blocked. Third-party
765 // image/frame sources are limited to what the app actually loads (preview
766 // images over https, YouTube's no-cookie embed); everything else is 'self'.
767 nonce := cspNonce()
768 // The fetch service (docs/fetch.md) is one more named connect-src host, present
769 // only when this instance opts in — img-src's blanket https: already
770 // admits its proxied card images.
771 fetchSrc := ""
772 if s.fetchURL != "" {
773 fetchSrc = " " + s.fetchURL
774 }
775 w.Header().Set("Content-Security-Policy",
776 "default-src 'self'; "+
777 "script-src 'self' 'nonce-"+nonce+"'; "+
778 "style-src 'self' 'unsafe-inline'; "+
779 "img-src 'self' data: blob: https:; "+
780 // Video/audio play from client-decrypted blob: URLs (E2E — the server
781 // only holds ciphertext), so media-src must allow blob: or the
782 // <video> is refused. Without this it falls back to default-src 'self'.
783 "media-src 'self' blob:; "+
784 // *.giphy.com is the /gif app's CLIENT-side doorway (hostBridge.gif in
785 // shell.js): search + GIF download happen in the browser, so the server
786 // never sees the query or the pick — the deliberate, disclosed sibling
787 // of the unfurl trade-off. The home origin admits exactly one call: the
788 // enrolment completion poll (backup.js startEnrolPoll), which sends only
789 // the client-random nonce. Keep connect-src pinned to named hosts.
790 "connect-src 'self' https://*.giphy.com "+s.homeOrigin+fetchSrc+"; "+
791 // 'self' admits exactly one same-origin frame: /app-sandbox, the
792 // opaque-origin cage member apps run in (memberapps.go).
793 "frame-src 'self' https://www.youtube-nocookie.com; "+
794 "object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'")
795 w.Header().Set("Content-Type", "text/html; charset=utf-8")
796 // Inject the configurable group name (HTML-escaped — it's admin-set) and the
797 // build version (so the page knows which frontend it loaded — see /api/version).
798 page := strings.ReplaceAll(string(s.pages[name]), "__GROUP_NAME__", html.EscapeString(s.db.getGroupName()))
799 page = strings.ReplaceAll(page, "__APP_VERSION__", s.version)
800 // Whether ordinary members may invite people (gates the invite UI; the server
801 // enforces it regardless). Injected so the client needs no extra round trip.
802 page = strings.ReplaceAll(page, "__USER_INVITES__", boolStr(s.db.usersCanInvite()))
803 // Per-instance feature gates (same deal: hide the entry points here, the
804 // gated endpoints enforce).
805 page = strings.ReplaceAll(page, "__ENABLE_AI__", boolStr(s.db.aiEnabled()))
806 page = strings.ReplaceAll(page, "__ENABLE_BOTS__", boolStr(s.db.botsEnabled()))
807 page = strings.ReplaceAll(page, "__ENABLE_APPS__", boolStr(s.db.appsEnabled()))
808 page = strings.ReplaceAll(page, "__ENABLE_MEMBER_APPS__", boolStr(s.db.memberAppsEnabled()))
809 // Space-install policy (client-enforced; see db.spaceInstallsAdmins).
810 page = strings.ReplaceAll(page, "__SPACE_INSTALLS_ADMINS__", boolStr(s.db.spaceInstallsAdmins()))
811 // The welcome page's "Get the app" destination; empty hides the button.
812 page = strings.ReplaceAll(page, "__APP_STORE_URL__", html.EscapeString(s.appStoreURL))
813 // The home server the chat page enrols into for passkey backup.
814 page = strings.ReplaceAll(page, "__HOME_ORIGIN__", html.EscapeString(s.homeOrigin))
815 page = strings.ReplaceAll(page, "__FETCH_URL__", html.EscapeString(s.fetchURL))
816 // The provisioner-pushed plan flag ("free"/"paid"; empty when self-hosted)
817 // — gates the space menu's Upgrade entry, enforced by nothing here: the
818 // checkout itself lives on the home server.
819 page = strings.ReplaceAll(page, "__ENTITLEMENT__", html.EscapeString(s.entitlement))
820 // Link-preview (OpenGraph) fields for the join page. Absolute URLs, since
821 // crawlers fetch with no base. The image is the server branding avatar when
822 // set, else the app logo — both plaintext branding, never user content, so
823 // this leaks nothing beyond what the group name already does.
824 if name == "join.html" {
825 base := requestBase(r)
826 ogImage := base + "/static/icon-512.png"
827 // A sealed avatar is ciphertext — crawlers can't render it, so OG
828 // cards keep the app logo (the group name is likewise the default).
829 if _, mime, _, hasAvatar := s.db.getInstanceAvatar(); hasAvatar && mime != sealedAvatarMime {
830 ogImage = base + "/api/server-avatar"
831 }
832 page = strings.ReplaceAll(page, "__OG_URL__", html.EscapeString(base+r.URL.EscapedPath()))
833 page = strings.ReplaceAll(page, "__OG_IMAGE__", html.EscapeString(ogImage))
834 }
835 page = strings.ReplaceAll(page, "__CSP_NONCE__", nonce)
836 w.Write([]byte(page))
837 }
838}
839
840// The home server that hosts passkey backup enrolment when LCHAT_HOME_ORIGIN is
841// unset. See the enrolment cross-origin contract (web/static/backup.js).
842const defaultHomeOrigin = "https://home.elevenmessenger.com"
843
844// The apps this deployment's instances associate with (team + bundle ids) —
845// public by definition (they ship in every AASA file and in the apps
846// themselves). The Mac id is the server half of Mac universal links
847// (docs/native-onboarding.md E.1/E.2, issue #1376): inert until the Mac app
848// ships its applinks entitlement (E.2), at which point /join links open the
849// app directly instead of riding the custom-scheme handoff.
850const appleAppID = "J5NDF5PCD8.com.elevenmessenger.messenger"
851const appleMacAppID = "J5NDF5PCD8.com.elevenmessenger.messenger.mac"
852
853// serveAASA answers Apple's app-site-association probe. Apple's CDN fetches it
854// when the app installs/updates; matching /join/* links then open in the app
855// instead of Safari, with the URL (fragment included) handed to the app. Public,
856// unauthenticated, and identical on every instance by design.
857func serveAASA(w http.ResponseWriter, r *http.Request) {
858 w.Header().Set("Content-Type", "application/json")
859 fmt.Fprintf(w, `{"applinks":{"details":[{"appIDs":[%q,%q],"components":[{"/":"/join/*"}]}]}}`, appleAppID, appleMacAppID)
860}
861
862// frontendVersion is a short hash of the embedded frontend (web/), computed once at
863// startup. It changes whenever any UI file changes, so a redeploy that ships new
864// frontend code yields a new version — clients notice and reload (see getVersion +
865// the visibility check in chat.js). A server-only change leaves it unchanged.
866func frontendVersion() string {
867 h := sha256.New()
868 _ = fs.WalkDir(webFS, "web", func(p string, d fs.DirEntry, err error) error {
869 if err != nil || d.IsDir() {
870 return nil
871 }
872 b, e := webFS.ReadFile(p)
873 if e != nil {
874 return nil
875 }
876 h.Write([]byte(p))
877 h.Write(b)
878 return nil
879 })
880 return fmt.Sprintf("%x", h.Sum(nil))[:12]
881}
882
883// getVersion returns the current frontend build hash (clients poll it to
884// auto-reload) plus the binary build id. `version` drives the frontend reload;
885// `build` is the compiled-in id `lchat deploy --version` health-checks against, so
886// a deploy can confirm the intended binary is actually the one now serving.
887func (s *Server) getVersion(w http.ResponseWriter, r *http.Request) {
888 writeJSON(w, http.StatusOK, map[string]any{"version": s.version, "build": buildVersion})
889}
890
891// ChangelogEntry is one embedded release note (see the changelogFS comment).
892// The text is operator-authored notes about the app itself — never user
893// content — so, like roster labels, it lives in clear.
894type ChangelogEntry struct {
895 ID string `json:"id"` // filename without .md, e.g. 2026-07-01-helpers
896 Text string `json:"text"` // the note, posted verbatim by the announcer
897}
898
899// loadChangelog reads the embedded entries once at startup, in filename order
900// (date-prefixed names, so oldest first).
901func loadChangelog() []ChangelogEntry {
902 out := []ChangelogEntry{}
903 files, _ := changelogFS.ReadDir("changelog")
904 for _, f := range files { // ReadDir returns names sorted
905 b, err := changelogFS.ReadFile("changelog/" + f.Name())
906 if err != nil {
907 continue
908 }
909 text := strings.TrimSpace(string(b))
910 if text == "" {
911 continue
912 }
913 out = append(out, ChangelogEntry{ID: strings.TrimSuffix(f.Name(), ".md"), Text: text})
914 }
915 return out
916}
917
918// getChangelog returns the embedded release notes. Token-gated like every data
919// endpoint; the announcer bot reads it with its own device token.
920func (s *Server) getChangelog(w http.ResponseWriter, r *http.Request) {
921 if !s.tokenOK(r.URL.Query().Get("token")) {
922 httpError(w, http.StatusForbidden, "not a member")
923 return
924 }
925 writeJSON(w, http.StatusOK, map[string]any{"entries": s.changelog})
926}
927
928// getAppGuide serves the embedded mini-app authoring guide as markdown. See the
929// appGuideFS comment for why this endpoint is deliberately public.
930func (s *Server) getAppGuide(w http.ResponseWriter, r *http.Request) {
931 b, err := appGuideFS.ReadFile("docs/building-apps.md")
932 if err != nil {
933 httpError(w, http.StatusInternalServerError, "guide unavailable")
934 return
935 }
936 w.Header().Set("Content-Type", "text/markdown; charset=utf-8")
937 w.Write(b)
938}
939
940// getMemberAppGuide serves the sandboxed-tier authoring guide — what the
941// assistant bot's create_app tool builds against (it fetches this exact
942// endpoint, so bot and instance can never disagree on the rules), and what a
943// member points an outside LLM at. Public like /api/app-guide.
944func (s *Server) getMemberAppGuide(w http.ResponseWriter, r *http.Request) {
945 // Apps off — or just member-built apps off — reads as "no guide": the
946 // sidecar already treats a failed fetch as app building disabled, so a 404
947 // switches its builder off with no new protocol between them.
948 if !s.db.appsEnabled() || !s.db.memberAppsEnabled() {
949 http.NotFound(w, r)
950 return
951 }
952 b, err := appGuideFS.ReadFile("docs/building-member-apps.md")
953 if err != nil {
954 httpError(w, http.StatusInternalServerError, "guide unavailable")
955 return
956 }
957 w.Header().Set("Content-Type", "text/markdown; charset=utf-8")
958 w.Write(b)
959}
960
961// getAppChecker serves the embedded static app checker, so an author following
962// the guide can run it without a repo checkout (curl -O, then node). Un-gated
963// for the same reason as the guide: static tooling, not instance data.
964func (s *Server) getAppChecker(w http.ResponseWriter, r *http.Request) {
965 b, err := appGuideFS.ReadFile("tools/check-app.mjs")
966 if err != nil {
967 httpError(w, http.StatusInternalServerError, "checker unavailable")
968 return
969 }
970 w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
971 w.Write(b)
972}
973
974// ---- chat API -----------------------------------------------------------
975
976func (s *Server) getMessages(w http.ResponseWriter, r *http.Request) {
977 token := r.URL.Query().Get("token")
978 if !s.tokenOK(token) {
979 httpError(w, http.StatusForbidden, "invalid invite")
980 return
981 }
982 q := r.URL.Query()
983 // Messages are per-thread; you must be a member of the thread you ask for.
984 threadID := q.Get("thread")
985 userID, _ := s.db.deviceTokenUser(token)
986 if threadID == "" || !s.db.threadMember(threadID, userID) {
987 httpError(w, http.StatusForbidden, "not a thread member")
988 return
989 }
990 limit := 100
991 if n, err := strconv.Atoi(q.Get("limit")); err == nil && n > 0 {
992 limit = n
993 }
994 if limit > 200 {
995 limit = 200
996 }
997 // `before` paginates older history (id < before); otherwise `after` returns
998 // the page after a cursor, or the most recent `limit` when after is 0.
999 var msgs []Message
1000 var err error
1001 if b := q.Get("before"); b != "" {
1002 before, _ := strconv.ParseInt(b, 10, 64)
1003 msgs, err = s.db.messagesBefore(threadID, before, limit)
1004 } else {
1005 after, _ := strconv.ParseInt(q.Get("after"), 10, 64)
1006 msgs, err = s.db.messagesAfter(threadID, after, limit)
1007 }
1008 if err != nil {
1009 httpError(w, http.StatusInternalServerError, "db error")
1010 return
1011 }
1012 writeJSON(w, http.StatusOK, map[string]any{"messages": msgs})
1013}
1014
1015// postMessage is a non-WebSocket doorway to the exact same path as the "msg"
1016// frame in handleWS: a caller that holds a valid invite token POSTs an already
1017// AES-GCM-encrypted ciphertext blob, and we store + broadcast + push it. It lets
1018// bots, cron jobs and webhooks post without holding a WebSocket open.
1019//
1020// The end-to-end property is preserved precisely because the caller encrypts:
1021// the group key never reaches the server, and (as everywhere else) we store only
1022// the opaque blob and the author's hashed token — never plaintext. The companion
1023// `lchat-post` helper turns plaintext into the blob in the *caller's* trust
1024// domain.
1025func (s *Server) postMessage(w http.ResponseWriter, r *http.Request) {
1026 token := r.URL.Query().Get("token")
1027 if !s.tokenOK(token) {
1028 httpError(w, http.StatusForbidden, "invalid invite")
1029 return
1030 }
1031 // Cap the body before decoding so a valid-token holder can't force a huge
1032 // allocation — the length check below would fire too late on its own. Mirrors
1033 // uploadBlob's MaxBytesReader and handleWS's SetReadLimit.
1034 r.Body = http.MaxBytesReader(w, r.Body, maxBlobBytes+1024)
1035 var body struct {
1036 ThreadID string `json:"thread_id"`
1037 Blob string `json:"blob"`
1038 }
1039 if json.NewDecoder(r.Body).Decode(&body) != nil {
1040 httpError(w, http.StatusBadRequest, "bad request")
1041 return
1042 }
1043 // Same guards as the WebSocket "msg" case: non-empty, within the blob cap.
1044 if body.Blob == "" || len(body.Blob) > maxBlobBytes {
1045 httpError(w, http.StatusBadRequest, "missing or oversized blob")
1046 return
1047 }
1048 // Thread-scoped like every other write: the poster must be a member of the
1049 // thread (a script posts only where its user belongs). Same gate as the
1050 // WebSocket "msg" case.
1051 userID, _ := s.db.deviceTokenUser(token)
1052 if body.ThreadID == "" || !s.db.threadMember(body.ThreadID, userID) {
1053 httpError(w, http.StatusForbidden, "not a member of that thread")
1054 return
1055 }
1056 // Same closed-DM gate as the WebSocket "msg" case (issue #578).
1057 if closed, _ := s.db.dmClosed(body.ThreadID); closed {
1058 httpError(w, http.StatusForbidden, "conversation closed")
1059 return
1060 }
1061 // Same content-blind message brake as the WebSocket case (issue #578).
1062 if s.db.userRole(userID) != "admin" && !s.brake().messages.allow(userID) {
1063 httpError(w, http.StatusTooManyRequests, "sending too fast — give it a moment")
1064 return
1065 }
1066 m, err := s.db.insertMessage(body.ThreadID, body.Blob, userID)
1067 if err != nil {
1068 log.Println("insert message:", err)
1069 httpError(w, http.StatusInternalServerError, "db error")
1070 return
1071 }
1072 out, _ := json.Marshal(wsOut{Type: "msg", ThreadID: body.ThreadID, ID: m.ID, CreatedAt: m.CreatedAt, Blob: m.Blob})
1073 s.broadcastToThread(body.ThreadID, out)
1074 // Notify the thread's other members (not the poster), best-effort, async.
1075 go s.pushNewMessage(m.Blob, body.ThreadID, token, m.ID, m.CreatedAt)
1076 writeJSON(w, http.StatusOK, m)
1077}
1078
1079// brake returns the rate-limit set, creating it on first use — test servers
1080// build Server directly and must brake identically to production.
1081func (s *Server) brake() *modBrakes {
1082 if s.brakes == nil {
1083 s.brakes = newModBrakes()
1084 }
1085 return s.brakes
1086}
1087
1088// tokenOK reports whether a token is a valid participant credential: either a
1089// current non-revoked invite (legacy) or a device token (invite redesign).
1090func (s *Server) tokenOK(token string) bool {
1091 if token == "" {
1092 return false
1093 }
1094 return s.db.deviceTokenValid(token)
1095}
1096
1097// ---- threads & roster (see docs/threads-and-dms.md) ---------------------
1098
1099// setPubkey registers the caller's ECDH public key in the roster (on first join,
1100// or after a key rotation). Members wrap thread keys to this.
1101func (s *Server) setPubkey(w http.ResponseWriter, r *http.Request) {
1102 var body struct {
1103 Token string `json:"token"`
1104 PublicKey string `json:"public_key"`
1105 // Key transparency (#573): HMAC of PublicKey under the invite secret T,
1106 // so a T-holder can verify the roster key. Opaque to us; stored beside
1107 // the key and served in the roster. Absent for pre-KT / add-device.
1108 BindMac string `json:"bind_mac"`
1109 }
1110 if json.NewDecoder(r.Body).Decode(&body) != nil {
1111 httpError(w, http.StatusBadRequest, "bad request")
1112 return
1113 }
1114 if !s.tokenOK(body.Token) {
1115 httpError(w, http.StatusForbidden, "not a member")
1116 return
1117 }
1118 if len(body.BindMac) > 200 {
1119 httpError(w, http.StatusBadRequest, "bad bind mac")
1120 return
1121 }
1122 uid, ok := s.db.deviceTokenUser(body.Token)
1123 if !ok {
1124 httpError(w, http.StatusForbidden, "no user for token")
1125 return
1126 }
1127 if body.PublicKey == "" || len(body.PublicKey) > 500 {
1128 httpError(w, http.StatusBadRequest, "bad public key")
1129 return
1130 }
1131 // A user's public key is set once, on first join. Refuse to overwrite it with a
1132 // DIFFERENT key — that would orphan every thread wrapped to the old key (e.g. an
1133 // admin "device link" that made a new device generate its own keypair). Adding a
1134 // device ships the SAME keypair, so re-registering the identical key is fine.
1135 // A banned key can't re-register (issue #578) — this one gate covers every
1136 // invite path, because a member only becomes real once their key does.
1137 if s.db.keyBanned(body.PublicKey) {
1138 httpError(w, http.StatusForbidden, "not a member")
1139 return
1140 }
1141 firstKey := s.db.userPublicKey(uid) == ""
1142 if cur := s.db.userPublicKey(uid); cur != "" && cur != body.PublicKey {
1143 httpError(w, http.StatusConflict, "public key already registered")
1144 return
1145 }
1146 if err := s.db.setUserPublicKey(uid, body.PublicKey, body.BindMac); err != nil {
1147 httpError(w, http.StatusInternalServerError, "db error")
1148 return
1149 }
1150 // A fresh joiner is only NOW a keyed member — tell open tabs so the inviter's
1151 // pending-invite card swaps to the live DM (pendingInvitee needs a public key
1152 // to clear). Firing at claim time raced this POST and left the card stuck.
1153 if firstKey {
1154 out, _ := json.Marshal(map[string]any{"type": "joined", "user_id": uid})
1155 s.hub.broadcast <- outbound{data: out}
1156 // A cohort joiner is only NOW wrappable-to: prod each of their levels'
1157 // key holders (targeted, keyless). The holder backfill in loadTiers
1158 // self-heals later regardless; this makes the common case immediate.
1159 for _, tid := range s.db.userTiersNeedingKeys(uid) {
1160 s.prodTierHolders(tid, uid)
1161 }
1162 }
1163 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1164}
1165
1166// getRoster returns the caller's connections — themselves plus everyone they
1167// already share a thread with (a DM or a group). It is deliberately NOT the whole
1168// instance: you reach new people by inviting them, not by browsing a directory of
1169// everyone on the server. (A legacy token with no user gets an empty roster.)
1170func (s *Server) getRoster(w http.ResponseWriter, r *http.Request) {
1171 token := r.URL.Query().Get("token")
1172 if !s.tokenOK(token) {
1173 httpError(w, http.StatusForbidden, "not a member")
1174 return
1175 }
1176 uid, ok := s.db.deviceTokenUser(token)
1177 if !ok {
1178 writeJSON(w, http.StatusOK, map[string]any{"roster": []RosterEntry{}})
1179 return
1180 }
1181 // Admin-vetted bots (agents in the Helpers catalog) see the full joined
1182 // roster, not just their connections: Eleven can't welcome a member it
1183 // can't see. This widens only what a *vetted bot* sees — people still get
1184 // connections-only, and an unvetted agent is treated like anyone else.
1185 var entries []RosterEntry
1186 var err error
1187 if s.db.isVettedAgent(uid) {
1188 entries, err = s.db.roster()
1189 } else {
1190 entries, err = s.db.connections(uid)
1191 }
1192 if err != nil {
1193 httpError(w, http.StatusInternalServerError, "db error")
1194 return
1195 }
1196 s.stampPresence(entries)
1197 writeJSON(w, http.StatusOK, map[string]any{"roster": entries})
1198}
1199
1200// getMe reports facts about the caller's own account — how many devices they
1201// have signed in (so the client can warn before signing out the last one, which
1202// loses their keys, and the chats encrypted to them, for good), and for admins
1203// whether they are the SOLE admin (so the home server's client can refuse to
1204// drop the last recovery copy of the only admin key without a teardown).
1205//
1206// The home page runs on a different origin, so this one endpoint answers CORS
1207// for exactly that origin — the response reveals nothing without a valid device
1208// token, and only the caller's own facts with one.
1209func (s *Server) getMe(w http.ResponseWriter, r *http.Request) {
1210 if o := r.Header.Get("Origin"); o != "" && o == s.homeOrigin {
1211 w.Header().Set("Access-Control-Allow-Origin", o)
1212 w.Header().Set("Vary", "Origin")
1213 }
1214 token := r.URL.Query().Get("token")
1215 if !s.tokenOK(token) {
1216 httpError(w, http.StatusForbidden, "not a member")
1217 return
1218 }
1219 uid, ok := s.db.deviceTokenUser(token)
1220 if !ok {
1221 writeJSON(w, http.StatusOK, map[string]any{"device_count": 0})
1222 return
1223 }
1224 pinned, _ := s.db.userPresenceInfo(uid)
1225 me := map[string]any{
1226 "user_id": uid,
1227 "device_count": s.db.deviceCount(uid),
1228 "role": s.db.userRole(uid),
1229 // The caller's pinned Away flag (not the effective state) — what the
1230 // profile sheet's toggle reflects.
1231 "away": pinned == presenceAway,
1232 // setup_complete gates the first-run setup conversation. It's instance
1233 // state (not a secret), but only an admin's client acts on it.
1234 "setup_complete": s.db.setupComplete(),
1235 }
1236 // Only admins learn the admin headcount fact — members have no use for it.
1237 if me["role"] == "admin" {
1238 me["sole_admin"] = s.db.adminCount() == 1
1239 }
1240 // DM privacy (issue #578): what the caller's own settings toggle reflects.
1241 me["dm_privacy"] = s.db.userDMPrivacy(uid)
1242 writeJSON(w, http.StatusOK, me)
1243}
1244
1245// signout revokes the caller's own device token (sign out on this device) and drops
1246// its push subscriptions. Other devices keep working; the key survives on them.
1247func (s *Server) signout(w http.ResponseWriter, r *http.Request) {
1248 var body struct {
1249 Token string `json:"token"`
1250 }
1251 if json.NewDecoder(r.Body).Decode(&body) != nil {
1252 httpError(w, http.StatusBadRequest, "bad request")
1253 return
1254 }
1255 // Token-gate like every data endpoint; an unknown token has nothing to revoke, so
1256 // treat it as already signed out (idempotent) rather than acting on it.
1257 if !s.tokenOK(body.Token) {
1258 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1259 return
1260 }
1261 _ = s.db.deleteDeviceToken(body.Token)
1262 _ = s.db.deleteSubscriptionsForToken(body.Token)
1263 _ = s.db.deleteAPNsTokensForToken(body.Token)
1264 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1265}
1266
1267// getThreads returns the caller's threads, each with their wrapped key + members.
1268func (s *Server) getThreads(w http.ResponseWriter, r *http.Request) {
1269 token := r.URL.Query().Get("token")
1270 if !s.tokenOK(token) {
1271 httpError(w, http.StatusForbidden, "not a member")
1272 return
1273 }
1274 uid, ok := s.db.deviceTokenUser(token)
1275 if !ok {
1276 writeJSON(w, http.StatusOK, map[string]any{"threads": []Thread{}})
1277 return
1278 }
1279 ts, err := s.db.threadsForUser(uid)
1280 if err != nil {
1281 httpError(w, http.StatusInternalServerError, "db error")
1282 return
1283 }
1284 writeJSON(w, http.StatusOK, map[string]any{"threads": ts})
1285}
1286
1287// postThread creates a DM, group, or self thread. The browser generates the
1288// thread key and wraps it to each member's roster public key; the server only
1289// stores the (server-blind) blobs. The caller must include themselves. DMs are
1290// deduped to one per pair.
1291func (s *Server) postThread(w http.ResponseWriter, r *http.Request) {
1292 var body struct {
1293 Token string `json:"token"`
1294 Kind string `json:"kind"`
1295 NameBlob string `json:"name_blob"`
1296 Members []ThreadMemberKey `json:"members"`
1297 Visibility string `json:"visibility"`
1298 OpenKey string `json:"open_key"`
1299 OpenTier string `json:"open_tier"`
1300 }
1301 if json.NewDecoder(r.Body).Decode(&body) != nil {
1302 httpError(w, http.StatusBadRequest, "bad request")
1303 return
1304 }
1305 if !s.tokenOK(body.Token) {
1306 httpError(w, http.StatusForbidden, "not a member")
1307 return
1308 }
1309 uid, ok := s.db.deviceTokenUser(body.Token)
1310 if !ok {
1311 httpError(w, http.StatusForbidden, "no user for token")
1312 return
1313 }
1314 if body.Kind != "self" && body.Kind != "dm" && body.Kind != "group" {
1315 httpError(w, http.StatusBadRequest, "bad kind")
1316 return
1317 }
1318 if (body.Kind == "self" && len(body.Members) != 1) ||
1319 (body.Kind == "dm" && len(body.Members) != 2) ||
1320 (body.Kind == "group" && len(body.Members) < 1) {
1321 httpError(w, http.StatusBadRequest, "bad member count")
1322 return
1323 }
1324 // Open community groups: group-only, and the client must supply open_key —
1325 // the thread key encrypted under the instance key (opaque to the server) —
1326 // so any member can later discover, decrypt, and self-join.
1327 if body.Visibility != "" && body.Visibility != "invite" && body.Visibility != "open" {
1328 httpError(w, http.StatusBadRequest, "bad visibility")
1329 return
1330 }
1331 open := body.Visibility == "open"
1332 if open && body.Kind != "group" {
1333 httpError(w, http.StatusBadRequest, "only groups can be open")
1334 return
1335 }
1336 if (open && (body.OpenKey == "" || len(body.OpenKey) > 4096)) || (!open && body.OpenKey != "") {
1337 httpError(w, http.StatusBadRequest, "bad open key")
1338 return
1339 }
1340 // A level gate rides only on open groups, and only a member of that level
1341 // can set it — they wrapped open_key under the level's key, which only
1342 // members hold (the server can verify membership, not the wrap itself).
1343 if body.OpenTier != "" && (!open || !s.db.tierExists(body.OpenTier) || !s.db.tierMember(body.OpenTier, uid)) {
1344 httpError(w, http.StatusBadRequest, "bad access level")
1345 return
1346 }
1347 inSet := false
1348 for _, m := range body.Members {
1349 // An open group's members may omit their per-member wrap — the key
1350 // reaches everyone via open_key instead.
1351 if (m.Wrapped == "" && !open) || len(m.Wrapped) > 4096 || !s.db.userExists(m.UserID) {
1352 httpError(w, http.StatusBadRequest, "bad member")
1353 return
1354 }
1355 if m.UserID == uid {
1356 inSet = true
1357 }
1358 }
1359 if !inSet {
1360 httpError(w, http.StatusForbidden, "must include yourself")
1361 return
1362 }
1363 // DM dedupe: one thread per pair.
1364 if body.Kind == "dm" {
1365 other := body.Members[0].UserID
1366 if other == uid {
1367 other = body.Members[1].UserID
1368 }
1369 if existing, found, _ := s.db.dmThreadFor(uid, other); found {
1370 writeJSON(w, http.StatusOK, map[string]any{"thread_id": existing, "existing": true})
1371 return
1372 }
1373 // DM privacy (issue #578): a NEW DM respects the other person's door.
1374 // An existing conversation (above) is untouched — the setting governs
1375 // opening contact, not history.
1376 if !s.dmAllowed(uid, other) {
1377 httpError(w, http.StatusForbidden, "dms closed")
1378 return
1379 }
1380 // The mass-DM brake (issue #578): fresh members get the tighter
1381 // first-day bucket — the classic spam-join opens DMs immediately.
1382 if s.db.userRole(uid) != "admin" && !s.db.isAgent(uid) && !s.allowDM(uid, s.db.userCreatedAt(uid)) {
1383 httpError(w, http.StatusTooManyRequests, "opening chats too fast — give it a moment")
1384 return
1385 }
1386 }
1387 id, err := s.db.createThreadVis(body.Kind, body.NameBlob, body.Members, body.Visibility, body.OpenKey, body.OpenTier)
1388 if err != nil {
1389 httpError(w, http.StatusInternalServerError, "db error")
1390 return
1391 }
1392 if body.Kind == "dm" {
1393 other := body.Members[0].UserID
1394 if other == uid {
1395 other = body.Members[1].UserID
1396 }
1397 // recordDMPair fails on the dm_pairs PK if a concurrent request already
1398 // created the DM. In that case drop the duplicate thread we just made and
1399 // return the winner, so a fast double-tap can't spawn two DM threads.
1400 if err := s.db.recordDMPair(uid, other, id); err != nil {
1401 if existing, found, _ := s.db.dmThreadFor(uid, other); found {
1402 _ = s.db.deleteThread(id)
1403 writeJSON(w, http.StatusOK, map[string]any{"thread_id": existing, "existing": true})
1404 return
1405 }
1406 httpError(w, http.StatusInternalServerError, "db error")
1407 return
1408 }
1409 }
1410 writeJSON(w, http.StatusOK, map[string]any{"thread_id": id})
1411}
1412
1413// getOpenThreads lists the community directory: every open group, joined or
1414// not, each carrying its instance-key-wrapped open_key so any member's client
1415// can decrypt names/photos and self-join. Members only — never public: someone
1416// outside the space sees nothing.
1417func (s *Server) getOpenThreads(w http.ResponseWriter, r *http.Request) {
1418 token := r.URL.Query().Get("token")
1419 if !s.tokenOK(token) {
1420 httpError(w, http.StatusForbidden, "not a member")
1421 return
1422 }
1423 uid, ok := s.db.deviceTokenUser(token)
1424 if !ok {
1425 writeJSON(w, http.StatusOK, map[string]any{"threads": []OpenThread{}})
1426 return
1427 }
1428 ts, err := s.db.openThreads(uid)
1429 if err != nil {
1430 httpError(w, http.StatusInternalServerError, "db error")
1431 return
1432 }
1433 writeJSON(w, http.StatusOK, map[string]any{"threads": ts})
1434}
1435
1436// postThreadJoin self-serve-joins the caller to an open group. No key material
1437// changes hands: the joiner already holds the instance key, and the group's
1438// open_key rides their next thread-list fetch.
1439func (s *Server) postThreadJoin(w http.ResponseWriter, r *http.Request) {
1440 var body struct {
1441 Token string `json:"token"`
1442 }
1443 if json.NewDecoder(r.Body).Decode(&body) != nil {
1444 httpError(w, http.StatusBadRequest, "bad request")
1445 return
1446 }
1447 if !s.tokenOK(body.Token) {
1448 httpError(w, http.StatusForbidden, "not a member")
1449 return
1450 }
1451 uid, ok := s.db.deviceTokenUser(body.Token)
1452 if !ok {
1453 httpError(w, http.StatusForbidden, "no user for token")
1454 return
1455 }
1456 if err := s.db.joinOpenThread(r.PathValue("id"), uid); err != nil {
1457 if errors.Is(err, errNotOpen) {
1458 httpError(w, http.StatusForbidden, "not an open group")
1459 return
1460 }
1461 httpError(w, http.StatusInternalServerError, "db error")
1462 return
1463 }
1464 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1465}
1466
1467// postThreadVisibility opens or closes a group for discovery. Any member may
1468// flip it (groups are flat, like rename). Opening requires open_key — the
1469// thread key encrypted under the instance key by the caller's browser; the
1470// server can open neither. An existing open_key is never overwritten (see
1471// setThreadVisibility), and closing keeps it so self-serve joiners keep their
1472// key source — 'invite' only stops discovery and new joins.
1473func (s *Server) postThreadVisibility(w http.ResponseWriter, r *http.Request) {
1474 var body struct {
1475 Token string `json:"token"`
1476 Visibility string `json:"visibility"`
1477 OpenKey string `json:"open_key"`
1478 OpenTier string `json:"open_tier"`
1479 }
1480 if json.NewDecoder(r.Body).Decode(&body) != nil {
1481 httpError(w, http.StatusBadRequest, "bad request")
1482 return
1483 }
1484 if !s.tokenOK(body.Token) {
1485 httpError(w, http.StatusForbidden, "not a member")
1486 return
1487 }
1488 uid, ok := s.db.deviceTokenUser(body.Token)
1489 if !ok {
1490 httpError(w, http.StatusForbidden, "no user for token")
1491 return
1492 }
1493 threadID := r.PathValue("id")
1494 if !s.db.threadMember(threadID, uid) {
1495 httpError(w, http.StatusForbidden, "not a thread member")
1496 return
1497 }
1498 if s.db.threadKind(threadID) != "group" {
1499 httpError(w, http.StatusBadRequest, "only groups can be open")
1500 return
1501 }
1502 open := body.Visibility == "open"
1503 if body.Visibility != "invite" && !open {
1504 httpError(w, http.StatusBadRequest, "bad visibility")
1505 return
1506 }
1507 hasKey, curTier := s.db.threadOpenInfo(threadID)
1508 // First open requires the key blob; a REOPEN must not (the stored
1509 // open_key survives closing and is never overwritten) — otherwise only
1510 // wrap-key holders could reopen, while any member could close.
1511 if (open && !hasKey && (body.OpenKey == "" || len(body.OpenKey) > 4096)) ||
1512 len(body.OpenKey) > 4096 || (!open && body.OpenKey != "") {
1513 httpError(w, http.StatusBadRequest, "bad open key")
1514 return
1515 }
1516 // A NEW gate needs its setter to be in the level (they wrapped open_key
1517 // under the level's key, which only members hold). Re-naming the stored
1518 // gate on reopen moves no key material, so it needs no such check.
1519 if body.OpenTier != "" && body.OpenTier != curTier &&
1520 (!open || !s.db.tierExists(body.OpenTier) || !s.db.tierMember(body.OpenTier, uid)) {
1521 httpError(w, http.StatusBadRequest, "bad access level")
1522 return
1523 }
1524 // The gate is fixed once an open_key exists (changing it would need the
1525 // rekey the never-overwrite rule forbids) — refuse loudly rather than
1526 // letting a caller believe the gate moved.
1527 if open && hasKey && body.OpenTier != curTier {
1528 httpError(w, http.StatusBadRequest, "access level is fixed once a group has opened")
1529 return
1530 }
1531 if err := s.db.setThreadVisibility(threadID, body.Visibility, body.OpenKey, body.OpenTier); err != nil {
1532 httpError(w, http.StatusInternalServerError, "db error")
1533 return
1534 }
1535 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1536}
1537
1538// postThreadDefault flags an open group as joined-by-default for new members
1539// (Slack's #general). Space policy rather than group housekeeping, so unlike
1540// rename/visibility it's admin-role-gated, not any-member. Only open groups
1541// can default (a default group must be self-joinable); unflagging is always
1542// allowed. Existing members are never force-joined.
1543func (s *Server) postThreadDefault(w http.ResponseWriter, r *http.Request) {
1544 var body struct {
1545 Token string `json:"token"`
1546 Default bool `json:"default"`
1547 }
1548 if json.NewDecoder(r.Body).Decode(&body) != nil {
1549 httpError(w, http.StatusBadRequest, "bad request")
1550 return
1551 }
1552 if !s.tokenOK(body.Token) {
1553 httpError(w, http.StatusForbidden, "not a member")
1554 return
1555 }
1556 uid, ok := s.db.deviceTokenUser(body.Token)
1557 if !ok || s.db.userRole(uid) != "admin" {
1558 httpError(w, http.StatusForbidden, "admins only")
1559 return
1560 }
1561 threadID := r.PathValue("id")
1562 if !s.db.threadMember(threadID, uid) {
1563 httpError(w, http.StatusForbidden, "not a thread member")
1564 return
1565 }
1566 if body.Default && !s.db.threadIsOpen(threadID) {
1567 httpError(w, http.StatusBadRequest, "only open groups can be default")
1568 return
1569 }
1570 // The default sweep deliberately skips level-gated groups (a newcomer
1571 // holds no level yet) — refuse the flag rather than save-and-ignore it.
1572 if _, gate := s.db.threadOpenInfo(threadID); body.Default && gate != "" {
1573 httpError(w, http.StatusBadRequest, "limited groups can't be default")
1574 return
1575 }
1576 if err := s.db.setThreadDefault(threadID, body.Default); err != nil {
1577 httpError(w, http.StatusInternalServerError, "db error")
1578 return
1579 }
1580 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1581}
1582
1583// postThreadMember adds an existing instance member to a thread the caller is in.
1584// The caller's browser wraps the thread key to the new member's public key.
1585func (s *Server) postThreadMember(w http.ResponseWriter, r *http.Request) {
1586 var body struct {
1587 Token string `json:"token"`
1588 UserID string `json:"user_id"`
1589 Wrapped string `json:"wrapped"`
1590 }
1591 if json.NewDecoder(r.Body).Decode(&body) != nil {
1592 httpError(w, http.StatusBadRequest, "bad request")
1593 return
1594 }
1595 if !s.tokenOK(body.Token) {
1596 httpError(w, http.StatusForbidden, "not a member")
1597 return
1598 }
1599 uid, ok := s.db.deviceTokenUser(body.Token)
1600 if !ok {
1601 httpError(w, http.StatusForbidden, "no user for token")
1602 return
1603 }
1604 threadID := r.PathValue("id")
1605 if !s.db.threadMember(threadID, uid) {
1606 httpError(w, http.StatusForbidden, "not a thread member")
1607 return
1608 }
1609 // Only groups grow. Adding to a DM/self thread would break the one-thread-per-
1610 // pair invariant (dm_pairs) and silently turn a 2-person DM into a 3-way thread.
1611 if s.db.threadKind(threadID) != "group" {
1612 httpError(w, http.StatusBadRequest, "can only add people to a group")
1613 return
1614 }
1615 if body.UserID == "" || !s.db.userExists(body.UserID) || body.Wrapped == "" || len(body.Wrapped) > 4096 {
1616 httpError(w, http.StatusBadRequest, "bad member")
1617 return
1618 }
1619 // A block cuts indirect contact too (issue #578): neither side can pull
1620 // the other into a group. Same generic refusal as elsewhere — the add just
1621 // doesn't work, with no hint of which mechanism said no.
1622 if s.db.blockedEither(uid, body.UserID) {
1623 httpError(w, http.StatusForbidden, "can't add this member")
1624 return
1625 }
1626 // Adding an existing member is a no-op, checked here on purpose: a
1627 // self-serve joiner of an open group has membership but no thread_keys
1628 // row, and that empty slot must not be fillable with another member's
1629 // arbitrary blob (addThreadMember's DO NOTHING only protects rows that
1630 // already exist). The one sanctioned fill-an-existing-member's-slot path
1631 // is invite claiming, which writes the joiner's OWN wrap (claimKeyInvite).
1632 if s.db.threadMember(threadID, body.UserID) {
1633 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1634 return
1635 }
1636 if err := s.db.addThreadMember(threadID, body.UserID, body.Wrapped); err != nil {
1637 httpError(w, http.StatusInternalServerError, "db error")
1638 return
1639 }
1640 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1641}
1642
1643// postThreadName renames a thread (the group name is client-encrypted, so the
1644// server only stores the new blob). Any member may rename.
1645func (s *Server) postThreadName(w http.ResponseWriter, r *http.Request) {
1646 var body struct {
1647 Token string `json:"token"`
1648 NameBlob string `json:"name_blob"`
1649 }
1650 if json.NewDecoder(r.Body).Decode(&body) != nil {
1651 httpError(w, http.StatusBadRequest, "bad request")
1652 return
1653 }
1654 if !s.tokenOK(body.Token) {
1655 httpError(w, http.StatusForbidden, "not a member")
1656 return
1657 }
1658 uid, ok := s.db.deviceTokenUser(body.Token)
1659 if !ok || len(body.NameBlob) > 4096 {
1660 httpError(w, http.StatusBadRequest, "bad request")
1661 return
1662 }
1663 threadID := r.PathValue("id")
1664 if !s.db.threadMember(threadID, uid) {
1665 httpError(w, http.StatusForbidden, "not a thread member")
1666 return
1667 }
1668 // The space thread has no name to set (no sidebar row, no chat view) —
1669 // with implicit membership every member would pass the gate above, so
1670 // fence the write off rather than leave a pointless scribble surface.
1671 if s.db.threadKind(threadID) == "space" {
1672 httpError(w, http.StatusBadRequest, "the space thread has no name")
1673 return
1674 }
1675 if err := s.db.setThreadName(threadID, body.NameBlob); err != nil {
1676 httpError(w, http.StatusInternalServerError, "db error")
1677 return
1678 }
1679 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1680}
1681
1682// getInstanceKey returns the caller's wrapped instance key (if granted) plus the
1683// list of users who already hold it, so a holder only re-wraps to those missing.
1684func (s *Server) getInstanceKey(w http.ResponseWriter, r *http.Request) {
1685 token := r.URL.Query().Get("token")
1686 if !s.tokenOK(token) {
1687 httpError(w, http.StatusForbidden, "not a member")
1688 return
1689 }
1690 uid, ok := s.db.deviceTokenUser(token)
1691 if !ok {
1692 writeJSON(w, http.StatusOK, map[string]any{"wrapped": "", "have": []string{}})
1693 return
1694 }
1695 wrapped, _, err := s.db.instanceKeyFor(uid)
1696 if err != nil {
1697 httpError(w, http.StatusInternalServerError, "db error")
1698 return
1699 }
1700 have, err := s.db.instanceKeyHolders()
1701 if err != nil {
1702 httpError(w, http.StatusInternalServerError, "db error")
1703 return
1704 }
1705 out := map[string]any{"wrapped": wrapped, "have": have}
1706 // A keyless member waiting on holders gets liveness alongside (#785):
1707 // whether any holder is connected right now, and the newest read
1708 // watermark among them — enough for the client to say "the members who
1709 // hold this space's key haven't been online since May" instead of an
1710 // eternal "still setting up". Metadata the server already holds (it owns
1711 // the sockets and the read marks); no key material rides on it.
1712 if wrapped == "" && len(have) > 0 {
1713 online := false
1714 for _, h := range have {
1715 if s.presence.connected(h) {
1716 online = true
1717 break
1718 }
1719 }
1720 lastActive, err := s.db.lastReadActivity(have)
1721 if err != nil {
1722 httpError(w, http.StatusInternalServerError, "db error")
1723 return
1724 }
1725 out["holders_online"] = online
1726 out["holders_last_active"] = lastActive
1727 }
1728 writeJSON(w, http.StatusOK, out)
1729}
1730
1731// resetInstanceKeyHandler is the break-glass for an orphaned instance key
1732// (#785): admin-gated, destructive by design (the old key's sealed blobs are
1733// gone for good — the web admin console spells that out before calling). The
1734// next member to load the app bootstraps a fresh key.
1735func (s *Server) resetInstanceKeyHandler(w http.ResponseWriter, r *http.Request) {
1736 if !s.requireAdmin(w, r) {
1737 return
1738 }
1739 if err := s.db.resetInstanceKey(); err != nil {
1740 httpError(w, http.StatusInternalServerError, "db error")
1741 return
1742 }
1743 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1744}
1745
1746// postInstanceKey stores the (server-blind) instance key wrapped to one or more
1747// members — used to bootstrap it and to grant it to members who lack it.
1748func (s *Server) postInstanceKey(w http.ResponseWriter, r *http.Request) {
1749 var body struct {
1750 Token string `json:"token"`
1751 Grants []ThreadMemberKey `json:"grants"`
1752 }
1753 if json.NewDecoder(r.Body).Decode(&body) != nil {
1754 httpError(w, http.StatusBadRequest, "bad request")
1755 return
1756 }
1757 if !s.tokenOK(body.Token) {
1758 httpError(w, http.StatusForbidden, "not a member")
1759 return
1760 }
1761 if _, ok := s.db.deviceTokenUser(body.Token); !ok {
1762 httpError(w, http.StatusForbidden, "no user for token")
1763 return
1764 }
1765 granted := map[string]bool{}
1766 for _, g := range body.Grants {
1767 if g.UserID == "" || g.Wrapped == "" || len(g.Wrapped) > 4096 || !s.db.userExists(g.UserID) {
1768 continue
1769 }
1770 if err := s.db.grantInstanceKey(g.UserID, g.Wrapped); err != nil {
1771 httpError(w, http.StatusInternalServerError, "db error")
1772 return
1773 }
1774 granted[g.UserID] = true
1775 }
1776 // Nudge the just-granted users' open tabs to fetch + unwrap right away, so a
1777 // member stops showing "Photo syncing…" the instant a holder wraps the key to
1778 // them — without waiting for a reload. Keyless signal, routed only to them.
1779 if len(granted) > 0 {
1780 out, _ := json.Marshal(map[string]any{"type": "instance_key_granted"})
1781 s.hub.broadcast <- outbound{members: granted, data: out}
1782 }
1783 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1784}
1785
1786// nudgeInstanceKey is called by a member who holds no copy of the instance key. It
1787// relays a keyless "someone needs it" hint to every connected client; holders
1788// respond by (re-)wrapping the key to whoever's missing it (see the WS handler +
1789// grantInstanceKeyTo in the client). Carries no key material — just a prod, so a
1790// new member doesn't have to wait for a holder to next reboot.
1791func (s *Server) nudgeInstanceKey(w http.ResponseWriter, r *http.Request) {
1792 token := r.URL.Query().Get("token")
1793 if !s.tokenOK(token) {
1794 httpError(w, http.StatusForbidden, "not a member")
1795 return
1796 }
1797 // Carry who's asking and their public key: a holder's own roster view
1798 // (connections) may not include the nudger at all — a fresh joiner shares
1799 // no thread with most members — so holders wrap to this key directly.
1800 msg := map[string]any{"type": "instance_key_nudge"}
1801 if uid, ok := s.db.deviceTokenUser(token); ok {
1802 if pub := s.db.userPublicKey(uid); pub != "" {
1803 msg["user_id"] = uid
1804 msg["public_key"] = pub
1805 }
1806 }
1807 out, _ := json.Marshal(msg)
1808 s.hub.broadcast <- outbound{data: out} // members:nil → everyone
1809 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1810}
1811
1812// adminTiers lists the access levels for the admin console's cohort picker
1813// (bearer-token surface — the console holds no member token). Same rows the
1814// member endpoint serves, unpersonalised.
1815func (s *Server) adminTiers(w http.ResponseWriter, r *http.Request) {
1816 if !s.requireAdmin(w, r) {
1817 return
1818 }
1819 ts, err := s.db.listTiers("", true)
1820 if err != nil {
1821 httpError(w, http.StatusInternalServerError, "db error")
1822 return
1823 }
1824 writeJSON(w, http.StatusOK, map[string]any{"tiers": ts})
1825}
1826
1827// ---- tiers ----------------------------------------------------------------
1828// Admin-curated member sets that carry key material (docs/community-and-tiers.md).
1829// The key machinery is the instance key's, per tier: clients mint and wrap the
1830// key, the server stores blobs it can't open, grants never overwrite, and WS
1831// prods are keyless hints. Management (create/assign/remove/delete) is
1832// admin-ROLE-gated — tiers are space policy, like default groups.
1833
1834// tierAdmin resolves the caller and requires the admin role. Returns ("",
1835// false) after writing the error when the gate fails.
1836func (s *Server) tierAdmin(w http.ResponseWriter, token string) (string, bool) {
1837 if !s.tokenOK(token) {
1838 httpError(w, http.StatusForbidden, "not a member")
1839 return "", false
1840 }
1841 uid, ok := s.db.deviceTokenUser(token)
1842 if !ok || s.db.userRole(uid) != "admin" {
1843 httpError(w, http.StatusForbidden, "admins only")
1844 return "", false
1845 }
1846 return uid, true
1847}
1848
1849// getTiers lists every tier for any member (names are plaintext space policy,
1850// like the roster), personalised with the caller's membership + key state.
1851func (s *Server) getTiers(w http.ResponseWriter, r *http.Request) {
1852 token := r.URL.Query().Get("token")
1853 if !s.tokenOK(token) {
1854 httpError(w, http.StatusForbidden, "not a member")
1855 return
1856 }
1857 uid, ok := s.db.deviceTokenUser(token)
1858 if !ok {
1859 writeJSON(w, http.StatusOK, map[string]any{"tiers": []Tier{}})
1860 return
1861 }
1862 ts, err := s.db.listTiers(uid, s.db.userRole(uid) == "admin")
1863 if err != nil {
1864 httpError(w, http.StatusInternalServerError, "db error")
1865 return
1866 }
1867 writeJSON(w, http.StatusOK, map[string]any{"tiers": ts})
1868}
1869
1870func (s *Server) postTier(w http.ResponseWriter, r *http.Request) {
1871 var body struct {
1872 Token string `json:"token"`
1873 Name string `json:"name"`
1874 }
1875 if json.NewDecoder(r.Body).Decode(&body) != nil {
1876 httpError(w, http.StatusBadRequest, "bad request")
1877 return
1878 }
1879 if _, ok := s.tierAdmin(w, body.Token); !ok {
1880 return
1881 }
1882 name := strings.TrimSpace(body.Name)
1883 if name == "" || utf8.RuneCountInString(name) > 60 {
1884 httpError(w, http.StatusBadRequest, "bad name")
1885 return
1886 }
1887 id, err := s.db.createTier(name)
1888 if err != nil {
1889 httpError(w, http.StatusInternalServerError, "db error")
1890 return
1891 }
1892 writeJSON(w, http.StatusOK, map[string]any{"id": id})
1893}
1894
1895func (s *Server) deleteTierHandler(w http.ResponseWriter, r *http.Request) {
1896 var body struct {
1897 Token string `json:"token"`
1898 }
1899 if json.NewDecoder(r.Body).Decode(&body) != nil {
1900 httpError(w, http.StatusBadRequest, "bad request")
1901 return
1902 }
1903 if _, ok := s.tierAdmin(w, body.Token); !ok {
1904 return
1905 }
1906 id := r.PathValue("id")
1907 // A level that still gates groups can't be deleted: those groups' keys
1908 // are wrapped under it forever, and for self-serve joiners that wrap is
1909 // their only key source (see deleteTier's comment).
1910 if n := s.db.tierGatesThreads(id); n > 0 {
1911 httpError(w, http.StatusConflict, "this level still limits groups")
1912 return
1913 }
1914 if err := s.db.deleteTier(id); err != nil {
1915 httpError(w, http.StatusInternalServerError, "db error")
1916 return
1917 }
1918 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1919}
1920
1921// postTierMember assigns a member to a tier ('admin' source). The prod fans
1922// out two keyless hints: holders learn someone needs the key wrapped to them
1923// (so an online holder acts immediately, no reload), and the assignee's own
1924// tabs learn their tiers changed.
1925func (s *Server) postTierMember(w http.ResponseWriter, r *http.Request) {
1926 var body struct {
1927 Token string `json:"token"`
1928 UserID string `json:"user_id"`
1929 }
1930 if json.NewDecoder(r.Body).Decode(&body) != nil {
1931 httpError(w, http.StatusBadRequest, "bad request")
1932 return
1933 }
1934 if _, ok := s.tierAdmin(w, body.Token); !ok {
1935 return
1936 }
1937 tierID := r.PathValue("id")
1938 if !s.db.tierExists(tierID) || !s.db.userExists(body.UserID) {
1939 httpError(w, http.StatusBadRequest, "bad tier or member")
1940 return
1941 }
1942 if err := s.db.assignTier(tierID, body.UserID, "admin"); err != nil {
1943 httpError(w, http.StatusInternalServerError, "db error")
1944 return
1945 }
1946 s.prodTierHolders(tierID, body.UserID)
1947 s.prodTiersChanged(body.UserID)
1948 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1949}
1950
1951func (s *Server) postTierRemove(w http.ResponseWriter, r *http.Request) {
1952 var body struct {
1953 Token string `json:"token"`
1954 UserID string `json:"user_id"`
1955 }
1956 if json.NewDecoder(r.Body).Decode(&body) != nil {
1957 httpError(w, http.StatusBadRequest, "bad request")
1958 return
1959 }
1960 uid, ok := s.tierAdmin(w, body.Token)
1961 if !ok {
1962 return
1963 }
1964 if err := s.db.unassignTier(r.PathValue("id"), body.UserID); err != nil {
1965 httpError(w, http.StatusInternalServerError, "db error")
1966 return
1967 }
1968 // Taking an access level away is a moderation-grade action (the "demote"
1969 // rung on the ladder, issue #578) — record it.
1970 s.db.addAudit(uid, "level.removed", body.UserID, "", "", r.PathValue("id"))
1971 s.prodTiersChanged(body.UserID)
1972 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
1973}
1974
1975// postTierKeys stores wrapped tier-key copies. Two callers are legitimate:
1976// the MINT moment (no copies exist yet — admin-only, their client just
1977// generated the key and wrapped it to the initial members), and a HOLDER
1978// wrapping to members who joined since. Grants only land on tier members,
1979// and never overwrite (grantTierKey).
1980func (s *Server) postTierKeys(w http.ResponseWriter, r *http.Request) {
1981 var body struct {
1982 Token string `json:"token"`
1983 Grants []ThreadMemberKey `json:"grants"`
1984 }
1985 if json.NewDecoder(r.Body).Decode(&body) != nil {
1986 httpError(w, http.StatusBadRequest, "bad request")
1987 return
1988 }
1989 if !s.tokenOK(body.Token) {
1990 httpError(w, http.StatusForbidden, "not a member")
1991 return
1992 }
1993 uid, ok := s.db.deviceTokenUser(body.Token)
1994 if !ok {
1995 httpError(w, http.StatusForbidden, "no user for token")
1996 return
1997 }
1998 tierID := r.PathValue("id")
1999 if !s.db.tierExists(tierID) {
2000 httpError(w, http.StatusBadRequest, "no such tier")
2001 return
2002 }
2003 valid := []ThreadMemberKey{}
2004 granted := map[string]bool{}
2005 for _, g := range body.Grants {
2006 if g.UserID == "" || g.Wrapped == "" || len(g.Wrapped) > 4096 || !s.db.tierMember(tierID, g.UserID) {
2007 continue
2008 }
2009 valid = append(valid, g)
2010 granted[g.UserID] = true
2011 }
2012 if !s.db.tierKeyMinted(tierID) {
2013 // The mint moment — admin-only, one-way, transactional: concurrent
2014 // minters serialize on key_minted, exactly one key ever enters a
2015 // level. The loser gets 409 and must reload (never install its key).
2016 if s.db.userRole(uid) != "admin" {
2017 httpError(w, http.StatusForbidden, "admins only")
2018 return
2019 }
2020 if err := s.db.mintTierKeys(tierID, valid); err != nil {
2021 if errors.Is(err, errAlreadyMinted) {
2022 httpError(w, http.StatusConflict, "already minted")
2023 return
2024 }
2025 httpError(w, http.StatusInternalServerError, "db error")
2026 return
2027 }
2028 } else if s.db.tierKeyCount(tierID) == 0 {
2029 // Minted once, but every holder is gone — the key is unrecoverable.
2030 // Refuse loudly instead of silently minting a second key that would
2031 // seal every group gated under the first: the honest path is to
2032 // delete this level and create a fresh one.
2033 httpError(w, http.StatusGone, "this level's key is lost — delete the level and create a new one")
2034 return
2035 } else {
2036 if !s.db.tierHolder(tierID, uid) {
2037 httpError(w, http.StatusForbidden, "not a key holder")
2038 return
2039 }
2040 for _, g := range valid {
2041 if err := s.db.grantTierKey(tierID, g.UserID, g.Wrapped); err != nil {
2042 httpError(w, http.StatusInternalServerError, "db error")
2043 return
2044 }
2045 }
2046 }
2047 if len(granted) > 0 {
2048 out, _ := json.Marshal(map[string]any{"type": "tier_key_granted", "tier_id": tierID})
2049 s.hub.broadcast <- outbound{members: granted, data: out}
2050 }
2051 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2052}
2053
2054// nudgeTierKey: a tier member with no key copy asks for one. Unlike the
2055// instance-key nudge (everyone), this prods exactly the members who can help —
2056// current holders. Keyless, like every prod.
2057func (s *Server) nudgeTierKey(w http.ResponseWriter, r *http.Request) {
2058 var body struct {
2059 Token string `json:"token"`
2060 }
2061 if json.NewDecoder(r.Body).Decode(&body) != nil {
2062 httpError(w, http.StatusBadRequest, "bad request")
2063 return
2064 }
2065 if !s.tokenOK(body.Token) {
2066 httpError(w, http.StatusForbidden, "not a member")
2067 return
2068 }
2069 uid, ok := s.db.deviceTokenUser(body.Token)
2070 if !ok {
2071 httpError(w, http.StatusForbidden, "no user for token")
2072 return
2073 }
2074 tierID := r.PathValue("id")
2075 if !s.db.tierMember(tierID, uid) {
2076 httpError(w, http.StatusForbidden, "not in this tier")
2077 return
2078 }
2079 s.prodTierHolders(tierID, uid)
2080 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2081}
2082
2083// postTierPolicy sets a level's visibility policy — admin-gated (it's space
2084// policy, like management). 'shown' | 'hidden' | 'user'.
2085func (s *Server) postTierPolicy(w http.ResponseWriter, r *http.Request) {
2086 var body struct {
2087 Token string `json:"token"`
2088 Policy string `json:"policy"`
2089 }
2090 if json.NewDecoder(r.Body).Decode(&body) != nil {
2091 httpError(w, http.StatusBadRequest, "bad request")
2092 return
2093 }
2094 if _, ok := s.tierAdmin(w, body.Token); !ok {
2095 return
2096 }
2097 if body.Policy != "shown" && body.Policy != "hidden" && body.Policy != "user" {
2098 httpError(w, http.StatusBadRequest, "bad policy")
2099 return
2100 }
2101 if !s.db.tierExists(r.PathValue("id")) {
2102 httpError(w, http.StatusBadRequest, "no such level")
2103 return
2104 }
2105 if err := s.db.setTierVisibility(r.PathValue("id"), body.Policy); err != nil {
2106 httpError(w, http.StatusInternalServerError, "db error")
2107 return
2108 }
2109 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2110}
2111
2112// postTierShow is a member's own show/hide choice for a level they're in —
2113// honoured only while the level's policy is 'user' (else the admin policy
2114// decides). Members choose whether THEIR membership shows to non-members.
2115func (s *Server) postTierShow(w http.ResponseWriter, r *http.Request) {
2116 var body struct {
2117 Token string `json:"token"`
2118 Show bool `json:"show"`
2119 }
2120 if json.NewDecoder(r.Body).Decode(&body) != nil {
2121 httpError(w, http.StatusBadRequest, "bad request")
2122 return
2123 }
2124 if !s.tokenOK(body.Token) {
2125 httpError(w, http.StatusForbidden, "not a member")
2126 return
2127 }
2128 uid, ok := s.db.deviceTokenUser(body.Token)
2129 if !ok {
2130 httpError(w, http.StatusForbidden, "no user for token")
2131 return
2132 }
2133 if !s.db.tierMember(r.PathValue("id"), uid) {
2134 httpError(w, http.StatusForbidden, "not in this level")
2135 return
2136 }
2137 if err := s.db.setUserTierVisible(r.PathValue("id"), uid, body.Show); err != nil {
2138 httpError(w, http.StatusInternalServerError, "db error")
2139 return
2140 }
2141 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2142}
2143
2144// prodTierHolders tells current key holders that userID needs the tier key
2145// wrapped to them — carrying the target's pubkey, since a holder's roster
2146// view may not include a fresh joiner (the instance-key nudge's reasoning).
2147func (s *Server) prodTierHolders(tierID, userID string) {
2148 holders, err := s.db.tierHolderIDs(tierID)
2149 if err != nil || len(holders) == 0 {
2150 return
2151 }
2152 pub := s.db.userPublicKey(userID)
2153 if pub == "" {
2154 return
2155 }
2156 set := map[string]bool{}
2157 for _, h := range holders {
2158 if h != userID {
2159 set[h] = true
2160 }
2161 }
2162 if len(set) == 0 {
2163 return
2164 }
2165 out, _ := json.Marshal(map[string]any{
2166 "type": "tier_key_nudge", "tier_id": tierID, "user_id": userID, "public_key": pub,
2167 })
2168 s.hub.broadcast <- outbound{members: set, data: out}
2169}
2170
2171// prodTiersChanged tells one member's own tabs their tier set changed.
2172func (s *Server) prodTiersChanged(userID string) {
2173 out, _ := json.Marshal(map[string]any{"type": "tiers_changed"})
2174 s.hub.broadcast <- outbound{members: map[string]bool{userID: true}, data: out}
2175}
2176
2177// postLabel sets the caller's own display name, encrypted under the instance key
2178// (a server-blind blob). This is how a person publishes their name — the server
2179// never sees the plaintext. Broadcasts so every client refreshes the roster name.
2180func (s *Server) postLabel(w http.ResponseWriter, r *http.Request) {
2181 var body struct {
2182 Token string `json:"token"`
2183 LabelBlob string `json:"label_blob"`
2184 }
2185 if json.NewDecoder(r.Body).Decode(&body) != nil {
2186 httpError(w, http.StatusBadRequest, "bad request")
2187 return
2188 }
2189 if !s.tokenOK(body.Token) {
2190 httpError(w, http.StatusForbidden, "not a member")
2191 return
2192 }
2193 uid, ok := s.db.deviceTokenUser(body.Token)
2194 if !ok || body.LabelBlob == "" || len(body.LabelBlob) > 4096 {
2195 httpError(w, http.StatusBadRequest, "bad request")
2196 return
2197 }
2198 if err := s.db.setUserLabelBlob(uid, body.LabelBlob); err != nil {
2199 httpError(w, http.StatusInternalServerError, "db error")
2200 return
2201 }
2202 out, _ := json.Marshal(map[string]any{"type": "label", "user_id": uid, "label_blob": body.LabelBlob})
2203 s.hub.broadcast <- outbound{data: out}
2204 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2205}
2206
2207// postLabelBackfill seals another member's LEGACY plaintext label under the
2208// instance key (docs/no-plaintext.md): any member's client that holds the key
2209// may do this on roster load, so one visit from anyone scrubs names members
2210// left at rest before label_blob existed. The DB gate is strictly fill-once
2211// (people only, plaintext still present, no existing blob), so an HONEST
2212// client only re-encodes the name the server already stored. The server
2213// cannot verify the blob's content (it has no key), so a malicious MEMBER
2214// could seal a different name here — a deliberate, narrow trade: it needs a
2215// roster member holding the instance key, it works once per legacy row only,
2216// it touches nothing but a display name, and the victim re-setting their name
2217// overrides it. The alternative (leaving inactive members' real names in
2218// plaintext at rest, forever) loses to that.
2219func (s *Server) postLabelBackfill(w http.ResponseWriter, r *http.Request) {
2220 var body struct {
2221 Token string `json:"token"`
2222 UserID string `json:"user_id"`
2223 LabelBlob string `json:"label_blob"`
2224 }
2225 if json.NewDecoder(r.Body).Decode(&body) != nil {
2226 httpError(w, http.StatusBadRequest, "bad request")
2227 return
2228 }
2229 if !s.tokenOK(body.Token) {
2230 httpError(w, http.StatusForbidden, "not a member")
2231 return
2232 }
2233 if body.UserID == "" || body.LabelBlob == "" || len(body.LabelBlob) > 4096 {
2234 httpError(w, http.StatusBadRequest, "bad request")
2235 return
2236 }
2237 filled, err := s.db.backfillUserLabelBlob(body.UserID, body.LabelBlob)
2238 if err != nil {
2239 httpError(w, http.StatusInternalServerError, "db error")
2240 return
2241 }
2242 if filled {
2243 out, _ := json.Marshal(map[string]any{"type": "label", "user_id": body.UserID, "label_blob": body.LabelBlob})
2244 s.hub.broadcast <- outbound{data: out}
2245 }
2246 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "filled": filled})
2247}
2248
2249// postAvatar sets the caller's profile photo (an encrypted blob id, or "" to clear).
2250func (s *Server) postAvatar(w http.ResponseWriter, r *http.Request) {
2251 var body struct {
2252 Token string `json:"token"`
2253 BlobID string `json:"blob_id"`
2254 // The photo's alt text, encrypted under the instance key by the client
2255 // (opaque here, like the label blob).
2256 AltBlob string `json:"alt_blob"`
2257 }
2258 if json.NewDecoder(r.Body).Decode(&body) != nil {
2259 httpError(w, http.StatusBadRequest, "bad request")
2260 return
2261 }
2262 if !s.tokenOK(body.Token) {
2263 httpError(w, http.StatusForbidden, "not a member")
2264 return
2265 }
2266 uid, ok := s.db.deviceTokenUser(body.Token)
2267 if !ok || len(body.BlobID) > 200 || len(body.AltBlob) > 4096 {
2268 httpError(w, http.StatusBadRequest, "bad request")
2269 return
2270 }
2271 if err := s.db.setAvatar(uid, body.BlobID, body.AltBlob); err != nil {
2272 httpError(w, http.StatusInternalServerError, "db error")
2273 return
2274 }
2275 // Tell every connected client to refresh this user's avatar (profile photos
2276 // are instance-wide). members:nil → broadcast to everyone.
2277 out, _ := json.Marshal(map[string]any{"type": "avatar", "user_id": uid, "blob_id": body.BlobID, "alt_blob": body.AltBlob})
2278 s.hub.broadcast <- outbound{data: out}
2279 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2280}
2281
2282// postDescription sets the caller's own "about me" text, encrypted under the
2283// instance key by their client ("" clears it). Opaque here, like the label blob.
2284func (s *Server) postDescription(w http.ResponseWriter, r *http.Request) {
2285 var body struct {
2286 Token string `json:"token"`
2287 DescriptionBlob string `json:"description_blob"`
2288 }
2289 if json.NewDecoder(r.Body).Decode(&body) != nil {
2290 httpError(w, http.StatusBadRequest, "bad request")
2291 return
2292 }
2293 if !s.tokenOK(body.Token) {
2294 httpError(w, http.StatusForbidden, "not a member")
2295 return
2296 }
2297 uid, ok := s.db.deviceTokenUser(body.Token)
2298 if !ok || len(body.DescriptionBlob) > 4096 {
2299 httpError(w, http.StatusBadRequest, "bad request")
2300 return
2301 }
2302 if err := s.db.setUserDescriptionBlob(uid, body.DescriptionBlob); err != nil {
2303 httpError(w, http.StatusInternalServerError, "db error")
2304 return
2305 }
2306 out, _ := json.Marshal(map[string]any{"type": "description", "user_id": uid, "description_blob": body.DescriptionBlob})
2307 s.hub.broadcast <- outbound{data: out}
2308 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2309}
2310
2311// The caller's per-viewer name overrides (issue #577): one blob holding every
2312// "I call them Dermo", sealed by the client to the caller's OWN public key.
2313// Viewer-private user content — it never rides the roster and never broadcasts
2314// (a nickname is nobody else's business, not even its subject's); only the
2315// owner's devices, which share the keypair, can open it. Opaque here, as ever.
2316func (s *Server) getNicknames(w http.ResponseWriter, r *http.Request) {
2317 token := r.URL.Query().Get("token")
2318 if !s.tokenOK(token) {
2319 httpError(w, http.StatusForbidden, "not a member")
2320 return
2321 }
2322 uid, ok := s.db.deviceTokenUser(token)
2323 if !ok {
2324 httpError(w, http.StatusForbidden, "not a member")
2325 return
2326 }
2327 blob, version, err := s.db.userNicknamesBlob(uid)
2328 if err != nil {
2329 httpError(w, http.StatusInternalServerError, "db error")
2330 return
2331 }
2332 writeJSON(w, http.StatusOK, map[string]any{"nicknames_blob": blob, "version": version})
2333}
2334
2335func (s *Server) postNicknames(w http.ResponseWriter, r *http.Request) {
2336 var body struct {
2337 Token string `json:"token"`
2338 NicknamesBlob string `json:"nicknames_blob"`
2339 // The version the writer last read (compare-and-swap). A pointer so
2340 // absent is distinguishable from 0: a pre-versioning client omits it
2341 // and keeps its unconditional write.
2342 Version *int64 `json:"version"`
2343 }
2344 if json.NewDecoder(r.Body).Decode(&body) != nil {
2345 httpError(w, http.StatusBadRequest, "bad request")
2346 return
2347 }
2348 if !s.tokenOK(body.Token) {
2349 httpError(w, http.StatusForbidden, "not a member")
2350 return
2351 }
2352 uid, ok := s.db.deviceTokenUser(body.Token)
2353 // One sealed entry is ~100 bytes of ciphertext; 64 KiB covers hundreds of
2354 // members with room to spare (the description's 4 KiB is one field, this
2355 // blob is a whole map).
2356 if !ok || len(body.NicknamesBlob) > 64*1024 {
2357 httpError(w, http.StatusBadRequest, "bad request")
2358 return
2359 }
2360 base := int64(-1)
2361 if body.Version != nil && *body.Version >= 0 {
2362 base = *body.Version
2363 }
2364 version, wrote, err := s.db.setUserNicknamesBlob(uid, body.NicknamesBlob, base)
2365 if err != nil {
2366 httpError(w, http.StatusInternalServerError, "db error")
2367 return
2368 }
2369 if !wrote {
2370 // Another device wrote since the caller's read — 409 with where the
2371 // row is now, so it can re-read, replay its queued ops, and retry.
2372 writeJSON(w, http.StatusConflict, map[string]any{"error": "version conflict", "version": version})
2373 return
2374 }
2375 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "version": version})
2376}
2377
2378// The caller's private moderation preferences (muted people, for now): one
2379// blob sealed by the client to the caller's OWN public key, exactly like the
2380// nicknames blob. Who you mute is nobody else's business — not the muted
2381// person's, not the server's; only the owner's devices can open it.
2382func (s *Server) getPrefs(w http.ResponseWriter, r *http.Request) {
2383 token := r.URL.Query().Get("token")
2384 if !s.tokenOK(token) {
2385 httpError(w, http.StatusForbidden, "not a member")
2386 return
2387 }
2388 uid, ok := s.db.deviceTokenUser(token)
2389 if !ok {
2390 httpError(w, http.StatusForbidden, "not a member")
2391 return
2392 }
2393 blob, version, err := s.db.userPrefsBlob(uid)
2394 if err != nil {
2395 httpError(w, http.StatusInternalServerError, "db error")
2396 return
2397 }
2398 writeJSON(w, http.StatusOK, map[string]any{"prefs_blob": blob, "version": version})
2399}
2400
2401func (s *Server) postPrefs(w http.ResponseWriter, r *http.Request) {
2402 var body struct {
2403 Token string `json:"token"`
2404 PrefsBlob string `json:"prefs_blob"`
2405 // The version the writer last read (compare-and-swap); absent skips
2406 // the check, like the nicknames blob.
2407 Version *int64 `json:"version"`
2408 }
2409 if json.NewDecoder(r.Body).Decode(&body) != nil {
2410 httpError(w, http.StatusBadRequest, "bad request")
2411 return
2412 }
2413 if !s.tokenOK(body.Token) {
2414 httpError(w, http.StatusForbidden, "not a member")
2415 return
2416 }
2417 uid, ok := s.db.deviceTokenUser(body.Token)
2418 // A muted-people set is one sealed entry per person (~100 bytes each);
2419 // 64 KiB is the same generous ceiling the nicknames blob uses.
2420 if !ok || len(body.PrefsBlob) > 64*1024 {
2421 httpError(w, http.StatusBadRequest, "bad request")
2422 return
2423 }
2424 base := int64(-1)
2425 if body.Version != nil && *body.Version >= 0 {
2426 base = *body.Version
2427 }
2428 version, wrote, err := s.db.setUserPrefsBlob(uid, body.PrefsBlob, base)
2429 if err != nil {
2430 httpError(w, http.StatusInternalServerError, "db error")
2431 return
2432 }
2433 if !wrote {
2434 writeJSON(w, http.StatusConflict, map[string]any{"error": "version conflict", "version": version})
2435 return
2436 }
2437 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "version": version})
2438}
2439
2440// postGroupDescription sets the space's description (admin only — the space's
2441// self-portrait is a branding decision, like its name). Plaintext, like the
2442// admin name/email: it must be editable from the keyless admin console and
2443// readable on the join card before an invitee holds any key. "" clears it.
2444func (s *Server) postGroupDescription(w http.ResponseWriter, r *http.Request) {
2445 if !s.requireAdmin(w, r) {
2446 return
2447 }
2448 if !s.requireUnsealed(w) {
2449 return
2450 }
2451 var body struct {
2452 Description string `json:"description"`
2453 }
2454 if json.NewDecoder(r.Body).Decode(&body) != nil {
2455 httpError(w, http.StatusBadRequest, "bad request")
2456 return
2457 }
2458 desc := strings.TrimSpace(body.Description)
2459 if len(desc) > 1000 { // ~500 chars even in multi-byte scripts
2460 httpError(w, http.StatusBadRequest, "too long")
2461 return
2462 }
2463 if err := s.db.setGroupDescription(desc); err != nil {
2464 httpError(w, http.StatusInternalServerError, "db error")
2465 return
2466 }
2467 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "description": desc})
2468}
2469
2470// postThreadAvatar sets a group's photo (an encrypted blob id). Any member may.
2471func (s *Server) postThreadAvatar(w http.ResponseWriter, r *http.Request) {
2472 var body struct {
2473 Token string `json:"token"`
2474 BlobID string `json:"blob_id"`
2475 }
2476 if json.NewDecoder(r.Body).Decode(&body) != nil {
2477 httpError(w, http.StatusBadRequest, "bad request")
2478 return
2479 }
2480 if !s.tokenOK(body.Token) {
2481 httpError(w, http.StatusForbidden, "not a member")
2482 return
2483 }
2484 uid, ok := s.db.deviceTokenUser(body.Token)
2485 if !ok || len(body.BlobID) > 200 {
2486 httpError(w, http.StatusBadRequest, "bad request")
2487 return
2488 }
2489 threadID := r.PathValue("id")
2490 if !s.db.threadMember(threadID, uid) {
2491 httpError(w, http.StatusForbidden, "not a thread member")
2492 return
2493 }
2494 // Same fence as postThreadName: the space thread renders nowhere, so a
2495 // photo on it is only a scribble surface implicit membership would open.
2496 if s.db.threadKind(threadID) == "space" {
2497 httpError(w, http.StatusBadRequest, "the space thread has no photo")
2498 return
2499 }
2500 if err := s.db.setThreadAvatar(threadID, body.BlobID); err != nil {
2501 httpError(w, http.StatusInternalServerError, "db error")
2502 return
2503 }
2504 // Refresh the group photo for the thread's members (only they can see it).
2505 out, _ := json.Marshal(map[string]any{"type": "thread_avatar", "thread_id": threadID, "blob_id": body.BlobID})
2506 s.broadcastToThread(threadID, out)
2507 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2508}
2509
2510// postThreadLeave removes the caller from a thread.
2511func (s *Server) postThreadLeave(w http.ResponseWriter, r *http.Request) {
2512 var body struct {
2513 Token string `json:"token"`
2514 }
2515 if json.NewDecoder(r.Body).Decode(&body) != nil {
2516 httpError(w, http.StatusBadRequest, "bad request")
2517 return
2518 }
2519 if !s.tokenOK(body.Token) {
2520 httpError(w, http.StatusForbidden, "not a member")
2521 return
2522 }
2523 uid, ok := s.db.deviceTokenUser(body.Token)
2524 if !ok {
2525 httpError(w, http.StatusForbidden, "no user for token")
2526 return
2527 }
2528 if err := s.db.removeThreadMember(r.PathValue("id"), uid); err != nil {
2529 httpError(w, http.StatusInternalServerError, "db error")
2530 return
2531 }
2532 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2533}
2534
2535// postThreadHidden closes (hidden=true) or reopens (hidden=false) a chat for the
2536// caller — a per-user marker that syncs across their devices. Any member may set
2537// it on their own view; it never affects anyone else.
2538func (s *Server) postThreadHidden(w http.ResponseWriter, r *http.Request) {
2539 var body struct {
2540 Token string `json:"token"`
2541 Hidden bool `json:"hidden"`
2542 }
2543 if json.NewDecoder(r.Body).Decode(&body) != nil {
2544 httpError(w, http.StatusBadRequest, "bad request")
2545 return
2546 }
2547 if !s.tokenOK(body.Token) {
2548 httpError(w, http.StatusForbidden, "not a member")
2549 return
2550 }
2551 uid, ok := s.db.deviceTokenUser(body.Token)
2552 if !ok {
2553 httpError(w, http.StatusForbidden, "no user for token")
2554 return
2555 }
2556 threadID := r.PathValue("id")
2557 if !s.db.threadMember(threadID, uid) {
2558 httpError(w, http.StatusForbidden, "not a thread member")
2559 return
2560 }
2561 if err := s.db.setThreadHidden(uid, threadID, body.Hidden); err != nil {
2562 httpError(w, http.StatusInternalServerError, "db error")
2563 return
2564 }
2565 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2566}
2567
2568// postThreadPinned pins (pinned=true) or unpins (pinned=false) a chat for the
2569// caller — a per-user marker that syncs across their devices and floats the
2570// thread to the top of their list. It never affects anyone else.
2571func (s *Server) postThreadPinned(w http.ResponseWriter, r *http.Request) {
2572 var body struct {
2573 Token string `json:"token"`
2574 Pinned bool `json:"pinned"`
2575 }
2576 if json.NewDecoder(r.Body).Decode(&body) != nil {
2577 httpError(w, http.StatusBadRequest, "bad request")
2578 return
2579 }
2580 if !s.tokenOK(body.Token) {
2581 httpError(w, http.StatusForbidden, "not a member")
2582 return
2583 }
2584 uid, ok := s.db.deviceTokenUser(body.Token)
2585 if !ok {
2586 httpError(w, http.StatusForbidden, "no user for token")
2587 return
2588 }
2589 threadID := r.PathValue("id")
2590 if !s.db.threadMember(threadID, uid) {
2591 httpError(w, http.StatusForbidden, "not a thread member")
2592 return
2593 }
2594 if err := s.db.setThreadPinned(uid, threadID, body.Pinned); err != nil {
2595 httpError(w, http.StatusInternalServerError, "db error")
2596 return
2597 }
2598 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2599}
2600
2601// dmAllowed says whether `from` may open a NEW DM with `to`. Admins and bots
2602// pass a closed door — the space's operator must stay reachable, and
2603// onboarding speaks through Eleven's welcome DM — and the setting's UI copy
2604// says so out loud rather than implying an absolute wall.
2605func (s *Server) dmAllowed(from, to string) bool {
2606 // Admins and bots pass both doors — the operator must stay reachable (a
2607 // reported member could otherwise dodge a formal warning by blocking the
2608 // admin), and onboarding speaks through Eleven's welcome DM.
2609 if s.db.userRole(from) == "admin" || s.db.isAgent(from) {
2610 return true
2611 }
2612 // A block cuts contact in both directions, whoever asks (issue #578) —
2613 // the blocker unblocks first if they change their mind.
2614 if s.db.blockedEither(from, to) {
2615 return false
2616 }
2617 return s.db.userDMPrivacy(to) != "nobody"
2618}
2619
2620// postDMPrivacy sets the caller's own DM door: "" / "everyone" (anyone in the
2621// space may open a DM with them) or "nobody". Enforced at DM creation — see
2622// dmAllowed.
2623func (s *Server) postDMPrivacy(w http.ResponseWriter, r *http.Request) {
2624 var body struct {
2625 Token string `json:"token"`
2626 DMPrivacy string `json:"dm_privacy"`
2627 }
2628 if json.NewDecoder(r.Body).Decode(&body) != nil {
2629 httpError(w, http.StatusBadRequest, "bad request")
2630 return
2631 }
2632 if !s.tokenOK(body.Token) {
2633 httpError(w, http.StatusForbidden, "not a member")
2634 return
2635 }
2636 uid, ok := s.db.deviceTokenUser(body.Token)
2637 if !ok {
2638 httpError(w, http.StatusForbidden, "no user for token")
2639 return
2640 }
2641 v := body.DMPrivacy
2642 if v == "everyone" {
2643 v = "" // the default, stored lean
2644 }
2645 if v != "" && v != "nobody" {
2646 httpError(w, http.StatusBadRequest, "bad dm_privacy")
2647 return
2648 }
2649 if err := s.db.setUserDMPrivacy(uid, v); err != nil {
2650 httpError(w, http.StatusInternalServerError, "db error")
2651 return
2652 }
2653 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "dm_privacy": v})
2654}
2655
2656// getBlocks lists who the caller has blocked — their own list only.
2657func (s *Server) getBlocks(w http.ResponseWriter, r *http.Request) {
2658 token := r.URL.Query().Get("token")
2659 if !s.tokenOK(token) {
2660 httpError(w, http.StatusForbidden, "not a member")
2661 return
2662 }
2663 uid, ok := s.db.deviceTokenUser(token)
2664 if !ok {
2665 httpError(w, http.StatusForbidden, "no user for token")
2666 return
2667 }
2668 list, err := s.db.blocksOf(uid)
2669 if err != nil {
2670 httpError(w, http.StatusInternalServerError, "db error")
2671 return
2672 }
2673 writeJSON(w, http.StatusOK, map[string]any{"blocked": list})
2674}
2675
2676// postBlock blocks a member (issue #578): records the no-new-contact rule and
2677// ends any existing DM with them (the closed-DM machinery, so message/edit/
2678// typing refusals and the closed banner all follow). The blocked party is
2679// never told — they see the same silence and generic refusals a closed DM
2680// door produces.
2681func (s *Server) postBlock(w http.ResponseWriter, r *http.Request) {
2682 var body struct {
2683 Token string `json:"token"`
2684 UserID string `json:"user_id"`
2685 }
2686 if json.NewDecoder(r.Body).Decode(&body) != nil {
2687 httpError(w, http.StatusBadRequest, "bad request")
2688 return
2689 }
2690 if !s.tokenOK(body.Token) {
2691 httpError(w, http.StatusForbidden, "not a member")
2692 return
2693 }
2694 uid, ok := s.db.deviceTokenUser(body.Token)
2695 if !ok {
2696 httpError(w, http.StatusForbidden, "no user for token")
2697 return
2698 }
2699 if body.UserID == "" || body.UserID == uid || !s.db.userExists(body.UserID) {
2700 httpError(w, http.StatusBadRequest, "bad user_id")
2701 return
2702 }
2703 if err := s.db.setBlocked(uid, body.UserID, true); err != nil {
2704 httpError(w, http.StatusInternalServerError, "db error")
2705 return
2706 }
2707 // Block implies the conversation ends now, not at the next refusal.
2708 if tid, found, _ := s.db.dmThreadFor(uid, body.UserID); found {
2709 if closed, _ := s.db.dmClosed(tid); !closed {
2710 _ = s.db.closeDM(tid, uid)
2711 members, _ := s.db.memberUserIDs(tid)
2712 set := map[string]bool{}
2713 for _, m := range members {
2714 _ = s.db.setThreadHidden(m, tid, true)
2715 set[m] = true
2716 }
2717 out, _ := json.Marshal(map[string]any{"type": "dm_closed", "thread_id": tid})
2718 s.hub.broadcast <- outbound{members: set, data: out}
2719 }
2720 }
2721 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2722}
2723
2724// deleteBlock unblocks. Deliberately narrow: the DM stays closed (reopen is
2725// its own step, through the other person's DM door) and any client-side mute
2726// stays put — unblocking restores the possibility of contact, nothing more.
2727func (s *Server) deleteBlock(w http.ResponseWriter, r *http.Request) {
2728 var body struct {
2729 Token string `json:"token"`
2730 }
2731 if json.NewDecoder(r.Body).Decode(&body) != nil {
2732 httpError(w, http.StatusBadRequest, "bad request")
2733 return
2734 }
2735 if !s.tokenOK(body.Token) {
2736 httpError(w, http.StatusForbidden, "not a member")
2737 return
2738 }
2739 uid, ok := s.db.deviceTokenUser(body.Token)
2740 if !ok {
2741 httpError(w, http.StatusForbidden, "no user for token")
2742 return
2743 }
2744 if err := s.db.setBlocked(uid, r.PathValue("id"), false); err != nil {
2745 httpError(w, http.StatusInternalServerError, "db error")
2746 return
2747 }
2748 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2749}
2750
2751// postCloseDM ends a DM for both parties (issue #578): it drops off both
2752// lists and the server refuses new traffic into it until someone reopens it.
2753// Distinct from hiding (which quietly returns on activity) and from blocking
2754// (which is about the person): closing is about this conversation.
2755func (s *Server) postCloseDM(w http.ResponseWriter, r *http.Request) {
2756 var body struct {
2757 Token string `json:"token"`
2758 }
2759 if json.NewDecoder(r.Body).Decode(&body) != nil {
2760 httpError(w, http.StatusBadRequest, "bad request")
2761 return
2762 }
2763 if !s.tokenOK(body.Token) {
2764 httpError(w, http.StatusForbidden, "not a member")
2765 return
2766 }
2767 uid, ok := s.db.deviceTokenUser(body.Token)
2768 if !ok {
2769 httpError(w, http.StatusForbidden, "no user for token")
2770 return
2771 }
2772 threadID := r.PathValue("id")
2773 if !s.db.threadMember(threadID, uid) {
2774 httpError(w, http.StatusForbidden, "not a thread member")
2775 return
2776 }
2777 if s.db.threadKind(threadID) != "dm" {
2778 httpError(w, http.StatusBadRequest, "not a dm")
2779 return
2780 }
2781 if err := s.db.closeDM(threadID, uid); err != nil {
2782 httpError(w, http.StatusInternalServerError, "db error")
2783 return
2784 }
2785 // Drop it from both lists (per-user hidden markers), and tell both sides'
2786 // live clients so open panes swap to the closed banner at once.
2787 members, _ := s.db.memberUserIDs(threadID)
2788 set := map[string]bool{}
2789 for _, m := range members {
2790 _ = s.db.setThreadHidden(m, threadID, true)
2791 set[m] = true
2792 }
2793 out, _ := json.Marshal(map[string]any{"type": "dm_closed", "thread_id": threadID})
2794 s.hub.broadcast <- outbound{members: set, data: out}
2795 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2796}
2797
2798// postReopenDM reopens a closed DM. Either side may — but through the other
2799// person's DM door: if they've since closed DMs, reopening follows their
2800// setting (the same dmAllowed gate as opening a fresh DM).
2801func (s *Server) postReopenDM(w http.ResponseWriter, r *http.Request) {
2802 var body struct {
2803 Token string `json:"token"`
2804 }
2805 if json.NewDecoder(r.Body).Decode(&body) != nil {
2806 httpError(w, http.StatusBadRequest, "bad request")
2807 return
2808 }
2809 if !s.tokenOK(body.Token) {
2810 httpError(w, http.StatusForbidden, "not a member")
2811 return
2812 }
2813 uid, ok := s.db.deviceTokenUser(body.Token)
2814 if !ok {
2815 httpError(w, http.StatusForbidden, "no user for token")
2816 return
2817 }
2818 threadID := r.PathValue("id")
2819 if !s.db.threadMember(threadID, uid) {
2820 httpError(w, http.StatusForbidden, "not a thread member")
2821 return
2822 }
2823 closed, _ := s.db.dmClosed(threadID)
2824 if !closed {
2825 writeJSON(w, http.StatusOK, map[string]any{"ok": true}) // already open
2826 return
2827 }
2828 other, _ := s.db.otherThreadMember(threadID, uid)
2829 if other != "" && !s.dmAllowed(uid, other) {
2830 httpError(w, http.StatusForbidden, "dms closed")
2831 return
2832 }
2833 if err := s.db.reopenDM(threadID); err != nil {
2834 httpError(w, http.StatusInternalServerError, "db error")
2835 return
2836 }
2837 // The reopener sees it again now; the other side stays hidden until the
2838 // first new message unhides it (insertMessage's clearThreadHidden).
2839 _ = s.db.setThreadHidden(uid, threadID, false)
2840 members, _ := s.db.memberUserIDs(threadID)
2841 set := map[string]bool{}
2842 for _, m := range members {
2843 set[m] = true
2844 }
2845 out, _ := json.Marshal(map[string]any{"type": "dm_reopened", "thread_id": threadID})
2846 s.hub.broadcast <- outbound{members: set, data: out}
2847 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2848}
2849
2850// postThreadMuted mutes (muted=true) or unmutes (muted=false) a chat for the
2851// caller — a per-user marker that syncs across their devices. While set, the
2852// push fan-out skips every one of their devices for this thread; the muted
2853// thread's messages still arrive normally. It never affects anyone else, and
2854// nobody else can see it.
2855func (s *Server) postThreadMuted(w http.ResponseWriter, r *http.Request) {
2856 var body struct {
2857 Token string `json:"token"`
2858 Muted bool `json:"muted"`
2859 }
2860 if json.NewDecoder(r.Body).Decode(&body) != nil {
2861 httpError(w, http.StatusBadRequest, "bad request")
2862 return
2863 }
2864 if !s.tokenOK(body.Token) {
2865 httpError(w, http.StatusForbidden, "not a member")
2866 return
2867 }
2868 uid, ok := s.db.deviceTokenUser(body.Token)
2869 if !ok {
2870 httpError(w, http.StatusForbidden, "no user for token")
2871 return
2872 }
2873 threadID := r.PathValue("id")
2874 if !s.db.threadMember(threadID, uid) {
2875 httpError(w, http.StatusForbidden, "not a thread member")
2876 return
2877 }
2878 if err := s.db.setThreadMuted(uid, threadID, body.Muted); err != nil {
2879 httpError(w, http.StatusInternalServerError, "db error")
2880 return
2881 }
2882 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2883}
2884
2885// postThreadRead advances the caller's read watermark for a thread — "read
2886// here, read everywhere". last_read_at is the time of the newest message the
2887// device has shown; when the mark advances, it fans out over WebSocket to the
2888// caller's OTHER connections so their unread dots clear live. Forward-only (a
2889// lagging device can't re-light dots), per-user only (never other members),
2890// and just a timestamp — the server still can't read anything.
2891func (s *Server) postThreadRead(w http.ResponseWriter, r *http.Request) {
2892 var body struct {
2893 Token string `json:"token"`
2894 LastReadAt int64 `json:"last_read_at"`
2895 }
2896 if json.NewDecoder(r.Body).Decode(&body) != nil || body.LastReadAt <= 0 {
2897 httpError(w, http.StatusBadRequest, "bad request")
2898 return
2899 }
2900 if !s.tokenOK(body.Token) {
2901 httpError(w, http.StatusForbidden, "not a member")
2902 return
2903 }
2904 uid, ok := s.db.deviceTokenUser(body.Token)
2905 if !ok {
2906 httpError(w, http.StatusForbidden, "no user for token")
2907 return
2908 }
2909 threadID := r.PathValue("id")
2910 if !s.db.threadMember(threadID, uid) {
2911 httpError(w, http.StatusForbidden, "not a thread member")
2912 return
2913 }
2914 advanced, err := s.db.setThreadRead(uid, threadID, body.LastReadAt)
2915 if err != nil {
2916 httpError(w, http.StatusInternalServerError, "db error")
2917 return
2918 }
2919 if advanced {
2920 out, _ := json.Marshal(wsReadOut{Type: "read", ThreadID: threadID, LastReadAt: body.LastReadAt})
2921 s.hub.broadcast <- outbound{members: map[string]bool{uid: true}, data: out}
2922 }
2923 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2924}
2925
2926// postThreadRemove removes another member from a group. Any member may remove
2927// any other (matching how adding/renaming work today — the group is flat). Like
2928// leaving, the key isn't rotated: the server just stops delivering to them.
2929func (s *Server) postThreadRemove(w http.ResponseWriter, r *http.Request) {
2930 var body struct {
2931 Token string `json:"token"`
2932 UserID string `json:"user_id"`
2933 }
2934 if json.NewDecoder(r.Body).Decode(&body) != nil {
2935 httpError(w, http.StatusBadRequest, "bad request")
2936 return
2937 }
2938 if !s.tokenOK(body.Token) {
2939 httpError(w, http.StatusForbidden, "not a member")
2940 return
2941 }
2942 uid, ok := s.db.deviceTokenUser(body.Token)
2943 if !ok {
2944 httpError(w, http.StatusForbidden, "no user for token")
2945 return
2946 }
2947 threadID := r.PathValue("id")
2948 if !s.db.threadMember(threadID, uid) {
2949 httpError(w, http.StatusForbidden, "not a thread member")
2950 return
2951 }
2952 // Only groups: removing from a DM would break the one-thread-per-pair model.
2953 if s.db.threadKind(threadID) != "group" {
2954 httpError(w, http.StatusBadRequest, "can only remove people from a group")
2955 return
2956 }
2957 if body.UserID == "" || body.UserID == uid || !s.db.threadMember(threadID, body.UserID) {
2958 httpError(w, http.StatusBadRequest, "not a member of this group") // self uses /leave
2959 return
2960 }
2961 if err := s.db.removeThreadMember(threadID, body.UserID); err != nil {
2962 httpError(w, http.StatusInternalServerError, "db error")
2963 return
2964 }
2965 // Any member can remove in a flat group; only an ADMIN doing it is a
2966 // moderation action worth the audit log (issue #578) — ordinary member
2967 // removals would drown the log in group housekeeping.
2968 if s.db.userRole(uid) == "admin" {
2969 s.db.addAudit(uid, "thread.removed", body.UserID, threadID, "", "")
2970 }
2971 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
2972}
2973
2974// ---- attachments --------------------------------------------------------
2975
2976// validBlobID guards path building for a disk-backed blob: ids are randToken
2977// (base64url), so anything with a path separator, dot, or other character is
2978// bogus and rejected before it can reach the filesystem.
2979func validBlobID(id string) bool {
2980 if id == "" || len(id) > 64 {
2981 return false
2982 }
2983 for _, c := range id {
2984 if !(c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-' || c == '_') {
2985 return false
2986 }
2987 }
2988 return true
2989}
2990
2991func (s *Server) uploadBlob(w http.ResponseWriter, r *http.Request) {
2992 if !s.tokenOK(r.URL.Query().Get("token")) {
2993 httpError(w, http.StatusForbidden, "invalid invite")
2994 return
2995 }
2996 // Quota (disk backstop): refuse up front when the instance is already at its
2997 // storage ceiling, so a full disk can't be nudged further.
2998 if total, err := s.db.blobBytesTotal(); err == nil && total >= s.blobQuota {
2999 httpError(w, http.StatusInsufficientStorage, "storage full")
3000 return
3001 }
3002 r.Body = http.MaxBytesReader(w, r.Body, s.maxUpload)
3003 id, err := randToken()
3004 if err != nil {
3005 httpError(w, http.StatusInternalServerError, "id error")
3006 return
3007 }
3008 // Stream into a staged store write (never buffer a whole video in RAM);
3009 // commit under the id only once it's fully written, so a partial/aborted
3010 // upload is never served. The sha256 rides the same pass — it's the
3011 // integrity anchor the blob mirror/audit sweeps verify against (#992).
3012 blob, err := s.db.blobs.create()
3013 if err != nil {
3014 log.Printf("upload: blob create: %v", err)
3015 httpError(w, http.StatusInternalServerError, "storage error")
3016 return
3017 }
3018 hasher := sha256.New()
3019 size, err := io.Copy(io.MultiWriter(blob, hasher), r.Body)
3020 if err != nil {
3021 blob.abort()
3022 // MaxBytesReader trips here when the body exceeds the cap.
3023 httpError(w, http.StatusRequestEntityTooLarge, "file too large")
3024 return
3025 }
3026 if size == 0 {
3027 blob.abort()
3028 httpError(w, http.StatusBadRequest, "empty upload")
3029 return
3030 }
3031 // Re-check the quota against the real size now we have it.
3032 if total, err := s.db.blobBytesTotal(); err == nil && total+size > s.blobQuota {
3033 blob.abort()
3034 httpError(w, http.StatusInsufficientStorage, "storage full")
3035 return
3036 }
3037 if err := blob.commit(id); err != nil {
3038 log.Printf("upload: blob commit %s: %v", id, err)
3039 httpError(w, http.StatusInternalServerError, "storage error")
3040 return
3041 }
3042 // Tag with the (server-known, non-secret) thread id so the blob can be GC'd
3043 // with its thread / when the referencing message is deleted. Optional: avatar
3044 // uploads carry no thread.
3045 if err := s.db.recordBlob(id, r.URL.Query().Get("thread"), size, hex.EncodeToString(hasher.Sum(nil))); err != nil {
3046 _ = s.db.blobs.remove(id)
3047 httpError(w, http.StatusInternalServerError, "db error")
3048 return
3049 }
3050 s.kickBlobMirror() // a fresh blob mirrors promptly while the space is awake
3051 writeJSON(w, http.StatusOK, map[string]any{"id": id})
3052}
3053
3054func (s *Server) getBlobHandler(w http.ResponseWriter, r *http.Request) {
3055 if !s.tokenOK(r.URL.Query().Get("token")) {
3056 httpError(w, http.StatusForbidden, "invalid invite")
3057 return
3058 }
3059 id := r.PathValue("id")
3060 if !validBlobID(id) {
3061 http.NotFound(w, r)
3062 return
3063 }
3064 // Blob ids are unique and content is immutable, so it's safe to cache hard.
3065 w.Header().Set("Cache-Control", "private, max-age=31536000, immutable")
3066 // nosniff (set globally) stops a mistyped blob being sniffed as HTML; we serve
3067 // everything as opaque bytes.
3068 w.Header().Set("Content-Type", "application/octet-stream")
3069 // Store-backed (all new blobs): stream from the store. ServeContent gives
3070 // Range support + conditional requests for free (matters for large video),
3071 // and never loads the whole blob into RAM.
3072 if f, _, modTime, err := s.db.blobs.open(id); err == nil {
3073 defer f.Close()
3074 http.ServeContent(w, r, "", modTime, f)
3075 return
3076 }
3077 // Legacy: bytes still in the DB column (photos uploaded before disk-backing).
3078 data, err := s.db.legacyBlob(id)
3079 if err != nil {
3080 httpError(w, http.StatusInternalServerError, "db error")
3081 return
3082 }
3083 if data == nil {
3084 http.NotFound(w, r)
3085 return
3086 }
3087 w.Write(data)
3088}
3089
3090// ---- link previews ------------------------------------------------------
3091
3092func (s *Server) unfurl(w http.ResponseWriter, r *http.Request) {
3093 if !s.tokenOK(r.URL.Query().Get("token")) {
3094 httpError(w, http.StatusForbidden, "invalid invite")
3095 return
3096 }
3097 raw := strings.TrimSpace(r.URL.Query().Get("url"))
3098 u, err := url.Parse(raw)
3099 if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || len(raw) > 2048 {
3100 httpError(w, http.StatusBadRequest, "bad url")
3101 return
3102 }
3103 norm := u.String()
3104 // The member's own request already carries their Accept-Language; forward
3105 // it so the page unfurls in their language, not the fetching box's locale.
3106 lang := previewLang(r.Header.Get("Accept-Language"))
3107
3108 // Cache hit: serve it now; if it's stale, refresh in the background.
3109 if pv, ok, _ := s.db.getLinkPreview(norm, lang); ok {
3110 writeJSON(w, http.StatusOK, pv)
3111 ttl := int64(previewFreshTTL)
3112 if !pv.OK {
3113 ttl = previewFailTTL
3114 }
3115 if time.Now().Unix()-pv.FetchedAt > ttl {
3116 go s.fetchAndCachePreview(norm, lang)
3117 }
3118 return
3119 }
3120 // Miss: fetch synchronously (de-duped), cache, return.
3121 writeJSON(w, http.StatusOK, s.fetchAndCachePreview(norm, lang))
3122}
3123
3124// previewFlight is one in-progress unfurl; concurrent requests for the same
3125// URL+language wait on done and share pv rather than fetching again.
3126type previewFlight struct {
3127 done chan struct{}
3128 pv LinkPreview
3129}
3130
3131// fetchAndCachePreview fetches+stores a preview, ensuring only one fetch per
3132// URL+language runs at a time. Concurrent callers WAIT for that fetch and get
3133// its result — answering them with an empty stub instead is why a recipient
3134// (whose render of a just-posted link races the poster's synchronous fetch)
3135// never saw a card the poster did. The wait is bounded by fetchOG's timeout.
3136func (s *Server) fetchAndCachePreview(norm, lang string) LinkPreview {
3137 flightKey := previewCacheKey(lang, norm)
3138 f := &previewFlight{done: make(chan struct{})}
3139 if cur, busy := s.inflight.LoadOrStore(flightKey, f); busy {
3140 flight := cur.(*previewFlight)
3141 <-flight.done
3142 return flight.pv
3143 }
3144 defer func() {
3145 s.inflight.Delete(flightKey)
3146 close(f.done)
3147 }()
3148
3149 pv, err := fetchOG(norm, lang)
3150 if err != nil {
3151 pv = LinkPreview{URL: norm, OK: false}
3152 }
3153 pv.URL = norm
3154 pv.FetchedAt = time.Now().Unix()
3155 _ = s.db.putLinkPreview(pv, lang)
3156 f.pv = pv
3157 return pv
3158}
3159
3160// ---- key-invites (invite redesign) --------------------------------------
3161
3162// createKeyInvite stores a client-wrapped group key (the admin's browser did the
3163// wrapping; the server never sees the secret or plaintext key). Creates a user
3164// when no user_id is given (re-issue passes an existing user_id).
3165// getBotConfig returns the caller's own agent config. The sidecar fetches this
3166// with its device token to pick up console-managed model/prompt/docs; it's scoped
3167// to the caller's user, so a bot only ever reads its own config.
3168func (s *Server) getBotConfig(w http.ResponseWriter, r *http.Request) {
3169 token := r.URL.Query().Get("token")
3170 if !s.tokenOK(token) {
3171 httpError(w, http.StatusForbidden, "invalid invite")
3172 return
3173 }
3174 uid, ok := s.db.deviceTokenUser(token)
3175 if !ok {
3176 writeJSON(w, http.StatusOK, BotConfig{AIEnabled: s.db.aiEnabled()})
3177 return
3178 }
3179 c, _, err := s.db.botConfig(uid)
3180 if err != nil {
3181 httpError(w, http.StatusInternalServerError, "db error")
3182 return
3183 }
3184 c.AIEnabled = s.db.aiEnabled()
3185 writeJSON(w, http.StatusOK, c)
3186}
3187
3188// declareBotKind lets a sidecar self-report its identity's kind — "ai" (LLM-backed:
3189// what it reads is sent to a model provider) or "bot" (deterministic: nothing
3190// leaves the server). Authed by the bot's OWN device token, not the admin token:
3191// it can only set its own kind, and only for an agent. This is why Eleven can
3192// badge BOT when it runs commands-only and AI once its model brain is live —
3193// the sidecar knows which, and the badge follows the truth.
3194func (s *Server) declareBotKind(w http.ResponseWriter, r *http.Request) {
3195 var body struct {
3196 Token string `json:"token"`
3197 Kind string `json:"kind"`
3198 }
3199 if json.NewDecoder(r.Body).Decode(&body) != nil {
3200 httpError(w, http.StatusBadRequest, "bad request")
3201 return
3202 }
3203 if !s.tokenOK(body.Token) {
3204 httpError(w, http.StatusForbidden, "not a member")
3205 return
3206 }
3207 uid, ok := s.db.deviceTokenUser(body.Token)
3208 if !ok || !s.db.isAgent(uid) {
3209 httpError(w, http.StatusBadRequest, "not a bot")
3210 return
3211 }
3212 if body.Kind != "ai" && body.Kind != "bot" {
3213 httpError(w, http.StatusBadRequest, "bad kind")
3214 return
3215 }
3216 if err := s.db.setBotKind(uid, body.Kind); err != nil {
3217 httpError(w, http.StatusInternalServerError, "db error")
3218 return
3219 }
3220 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
3221}
3222
3223func (s *Server) createKeyInvite(w http.ResponseWriter, r *http.Request) {
3224 if !s.requireAdmin(w, r) {
3225 return
3226 }
3227 var body struct {
3228 Label string `json:"label"`
3229 UserID string `json:"user_id"`
3230 ID string `json:"id"`
3231 Wrapped string `json:"wrapped"`
3232 ClaimHash string `json:"claim_hash"` // proof-of-secret for claiming (see deriveInvite)
3233 Expires int64 `json:"expires"`
3234 Agent bool `json:"agent"` // mark the invited user as a bot (badge only)
3235 // Agent config (only when Agent) — the sidecar applies these.
3236 Model string `json:"model"`
3237 SystemPrompt string `json:"system_prompt"`
3238 Docs string `json:"docs"`
3239 // Helpers catalog metadata (only when Agent): the one-line blurb members
3240 // see, and whether the bot shows in everyone's Helpers list (docs/bots.md).
3241 Description string `json:"description"`
3242 Available bool `json:"available_to_members"`
3243 // Listen mode (only when Agent): when the bot replies in groups —
3244 // ""/"mention" = @mention only (default), "name" = also on its bare name.
3245 Listen string `json:"listen"`
3246 // GrantsAdmin marks a setup invite: its claimer becomes an admin. Minted by
3247 // add-instance for a fresh instance's first user (and available to admins
3248 // for promoting someone at invite time). See docs/conversational-onboarding.md.
3249 GrantsAdmin bool `json:"grants_admin"`
3250 // HooksService marks the hooks sidecar's service identity invite
3251 // (add-hooks mints it — hooks.go, docs/webhooks.md): the claimer is
3252 // recorded in config so webhook creation knows which pubkey to seal
3253 // definitions to. Not an AI bot, so it bypasses the bots gate.
3254 HooksService bool `json:"hooks_service"`
3255 // TierID makes this a COHORT invite: the claimer is assigned that
3256 // access level on first-device claim ('invite' source). Admin-minted
3257 // only, which is what keeps level assignment an admin power.
3258 TierID string `json:"tier_id"`
3259 }
3260 if json.NewDecoder(r.Body).Decode(&body) != nil {
3261 httpError(w, http.StatusBadRequest, "bad request")
3262 return
3263 }
3264 // Wrapped is optional now: a fresh-person invite carries no key (the joiner
3265 // generates their own user keypair). Only an add-device invite wraps the
3266 // user's private key. See docs/threads-and-dms.md.
3267 if body.ID == "" || len(body.ID) > 200 || len(body.Wrapped) > 4096 || len(body.Description) > 300 ||
3268 body.ClaimHash == "" || len(body.ClaimHash) > 128 {
3269 httpError(w, http.StatusBadRequest, "missing id")
3270 return
3271 }
3272 // The bots gate stops NEW bot identities being minted (checked before the
3273 // user row exists, so a rejected mint leaves nothing behind); bots already
3274 // on the roster keep running — the admin retires those by removal. The
3275 // hooks service identity is exempt: it's integration plumbing (no AI, no
3276 // conversations), gated instead by webhooks being admin-only.
3277 if body.Agent && !body.HooksService && !s.db.botsEnabled() {
3278 httpError(w, http.StatusForbidden, "bots are turned off for this space")
3279 return
3280 }
3281 userID := body.UserID
3282 if userID == "" {
3283 // A person gets no plaintext name — they publish theirs encrypted (under the
3284 // instance key) after joining, and the pre-fill name rides in the invite
3285 // link's #fragment. Only bots keep an admin-authored plaintext label.
3286 newLabel := ""
3287 if body.Agent {
3288 newLabel = strings.TrimSpace(body.Label)
3289 }
3290 id, err := s.db.createUser(newLabel)
3291 if err != nil {
3292 httpError(w, http.StatusInternalServerError, "db error")
3293 return
3294 }
3295 userID = id
3296 } else if !s.db.userExists(userID) {
3297 httpError(w, http.StatusBadRequest, "unknown user")
3298 return
3299 }
3300 if body.Agent {
3301 if body.Listen != "" && body.Listen != "mention" && body.Listen != "name" {
3302 httpError(w, http.StatusBadRequest, "bad listen")
3303 return
3304 }
3305 if err := s.db.setUserAgent(userID); err != nil {
3306 httpError(w, http.StatusInternalServerError, "db error")
3307 return
3308 }
3309 if err := s.db.setBotConfig(userID, body.Model, body.SystemPrompt, body.Docs, body.Listen, strings.TrimSpace(body.Description), body.Available); err != nil {
3310 httpError(w, http.StatusInternalServerError, "db error")
3311 return
3312 }
3313 if body.HooksService {
3314 // Record which identity webhook definitions seal to, and badge it
3315 // distinctly from conversational bots. Last mint wins — re-running
3316 // add-hooks after a lost session repoints creation at the fresh
3317 // identity (stale defs sealed to the old key simply stop deploying).
3318 if err := s.db.setConfig(hooksServiceUserKey, userID); err != nil {
3319 httpError(w, http.StatusInternalServerError, "db error")
3320 return
3321 }
3322 if err := s.db.setBotKind(userID, "webhook"); err != nil {
3323 httpError(w, http.StatusInternalServerError, "db error")
3324 return
3325 }
3326 }
3327 }
3328 if body.TierID != "" && !s.db.tierExists(body.TierID) {
3329 httpError(w, http.StatusBadRequest, "bad access level")
3330 return
3331 }
3332 if err := s.db.createKeyInvite(body.ID, userID, body.Wrapped, body.ClaimHash, body.Expires); err != nil {
3333 httpError(w, http.StatusInternalServerError, "db error")
3334 return
3335 }
3336 if body.GrantsAdmin {
3337 if err := s.db.setInviteGrantsAdmin(body.ID); err != nil {
3338 httpError(w, http.StatusInternalServerError, "db error")
3339 return
3340 }
3341 }
3342 if body.TierID != "" {
3343 if err := s.db.setInviteTier(body.ID, body.TierID); err != nil {
3344 httpError(w, http.StatusInternalServerError, "db error")
3345 return
3346 }
3347 }
3348 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "user_id": userID})
3349}
3350
3351// getKeyInvite returns the wrapped key for an unused, unexpired invite. The id is
3352// the client-derived handle; without the secret the wrapped blob is useless.
3353func (s *Server) getKeyInvite(w http.ResponseWriter, r *http.Request) {
3354 ki, found, err := s.db.getKeyInvite(r.PathValue("id"))
3355 if err != nil {
3356 httpError(w, http.StatusInternalServerError, "db error")
3357 return
3358 }
3359 ok := found && !ki.Used && !ki.Expired
3360 resp := map[string]any{"ok": ok}
3361 if ok {
3362 resp["wrapped"] = ki.Wrapped
3363 // A user invite drops the joiner into a pending DM. The client uses this to
3364 // (a) re-wrap the DM key to itself and (b) know an existing member can adopt.
3365 resp["dm"] = ki.ThreadID != ""
3366 // A setup invite lands chat-first: the join page skips its name form (the
3367 // setup conversation asks instead). Only link-holders can derive the id, so
3368 // this flags nothing to anyone who couldn't claim it anyway.
3369 resp["grants_admin"] = ki.GrantsAdmin
3370 // The space's description, so the welcome card can say what this place is
3371 // before the joiner holds any key. Only link-holders can derive the invite
3372 // id, so this stays "invited people only" — it's never on the public read.
3373 if d := s.db.getGroupDescription(); d != "" {
3374 resp["description"] = d
3375 }
3376 // Sealed branding: the invite link's #fragment carries B, so the join
3377 // card decrypts the full branding set (name, description, avatar alt)
3378 // from this blob instead of the plaintext fields above.
3379 if s.db.brandingSealed() {
3380 blob, _, _ := s.db.getConfig("branding_blob")
3381 salt, _, _ := s.db.getConfig("branding_salt")
3382 resp["branding_blob"] = blob
3383 resp["branding_salt"] = salt
3384 }
3385 // A cohort invite says which access level the joiner lands in — the
3386 // level NAME is branding-class by design (plaintext space policy), and
3387 // like the description it's served to link-holders only.
3388 if ki.TierID != "" {
3389 if n := s.db.tierName(ki.TierID); n != "" {
3390 resp["tier_name"] = n
3391 }
3392 }
3393 // The suggested pre-fill name is NOT returned here — it rides in the invite
3394 // link's #fragment (never sent to the server), so the server never sees it.
3395 }
3396 writeJSON(w, http.StatusOK, resp)
3397}
3398
3399// claimKeyInvite marks the invite used (single-use) and mints a device token for
3400// ongoing auth. The secret never reaches the server — only this claim does. For a
3401// user invite, `wrapped` is the pending DM's key wrapped to the joiner's own new
3402// public key; we store it so they can read the DM straight away, and return the
3403// thread id so the client opens it first.
3404func (s *Server) claimKeyInvite(w http.ResponseWriter, r *http.Request) {
3405 var body struct {
3406 Wrapped string `json:"wrapped"`
3407 ClaimSecret string `json:"claim_secret"`
3408 }
3409 json.NewDecoder(r.Body).Decode(&body)
3410 if len(body.Wrapped) > 4096 {
3411 httpError(w, http.StatusBadRequest, "bad request")
3412 return
3413 }
3414 id := r.PathValue("id")
3415 // Grab the pending DM (if any) before the claim consumes the invite.
3416 ki, _, _ := s.db.getKeyInvite(id)
3417 // No plaintext device label: the joiner's screen name is never sent to the
3418 // server — they publish it encrypted (POST /api/label) after joining.
3419 tok, ok, err := s.db.claimKeyInvite(id, "", body.Wrapped, body.ClaimSecret)
3420 if err != nil {
3421 httpError(w, http.StatusInternalServerError, "db error")
3422 return
3423 }
3424 if !ok {
3425 httpError(w, http.StatusForbidden, "invite unavailable")
3426 return
3427 }
3428 resp := map[string]any{"ok": true, "token": tok}
3429 if ki.ThreadID != "" {
3430 resp["thread_id"] = ki.ThreadID
3431 }
3432 writeJSON(w, http.StatusOK, resp)
3433}
3434
3435func (s *Server) listUsers(w http.ResponseWriter, r *http.Request) {
3436 if !s.requireAdmin(w, r) {
3437 return
3438 }
3439 users, err := s.db.listUsers()
3440 if err != nil {
3441 httpError(w, http.StatusInternalServerError, "db error")
3442 return
3443 }
3444 writeJSON(w, http.StatusOK, map[string]any{"users": users})
3445}
3446
3447// getAdminBotConfig returns a bot's full console-managed config (persona,
3448// model, docs + Helpers-catalog metadata) so the admin can edit it after
3449// creation. 400s for a non-agent — people don't have bot config.
3450func (s *Server) getAdminBotConfig(w http.ResponseWriter, r *http.Request) {
3451 if !s.requireAdmin(w, r) {
3452 return
3453 }
3454 id := r.PathValue("id")
3455 if !s.db.isAgent(id) {
3456 httpError(w, http.StatusBadRequest, "not a bot")
3457 return
3458 }
3459 c, _, err := s.db.fullBotConfig(id) // ok=false → zero-value config, still editable
3460 if err != nil {
3461 httpError(w, http.StatusInternalServerError, "db error")
3462 return
3463 }
3464 writeJSON(w, http.StatusOK, c)
3465}
3466
3467// setAdminBotConfig updates a bot's config in place. The sidecar re-pulls its
3468// config on every reconnect (~a minute), so edits take effect without a
3469// redeploy; catalog changes (description/availability) show in rosters
3470// immediately.
3471func (s *Server) setAdminBotConfig(w http.ResponseWriter, r *http.Request) {
3472 if !s.requireAdmin(w, r) {
3473 return
3474 }
3475 id := r.PathValue("id")
3476 if !s.db.isAgent(id) {
3477 httpError(w, http.StatusBadRequest, "not a bot")
3478 return
3479 }
3480 var body FullBotConfig
3481 if json.NewDecoder(r.Body).Decode(&body) != nil {
3482 httpError(w, http.StatusBadRequest, "bad request")
3483 return
3484 }
3485 if len(body.Description) > 300 {
3486 httpError(w, http.StatusBadRequest, "description too long")
3487 return
3488 }
3489 if body.Listen != "" && body.Listen != "mention" && body.Listen != "name" {
3490 httpError(w, http.StatusBadRequest, "bad listen")
3491 return
3492 }
3493 if len(body.Welcome) > 2000 {
3494 httpError(w, http.StatusBadRequest, "welcome too long")
3495 return
3496 }
3497 if err := s.db.setBotConfig(id, body.Model, body.SystemPrompt, body.Docs, body.Listen, strings.TrimSpace(body.Description), body.Available); err != nil {
3498 httpError(w, http.StatusInternalServerError, "db error")
3499 return
3500 }
3501 // Welcome text is a narrow upsert (see setBotWelcome) so it composes with the
3502 // config write above without widening setBotConfig's signature.
3503 if err := s.db.setBotWelcome(id, strings.TrimSpace(body.Welcome)); err != nil {
3504 httpError(w, http.StatusInternalServerError, "db error")
3505 return
3506 }
3507 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
3508}
3509
3510// renameUser changes a user's roster label (admin roster management — e.g.
3511// renaming a bot after its default changes). Display only: keys and history
3512// are untouched, and messages keep the name they were sent under (it's inside
3513// the encrypted payload, which the server can't rewrite anyway).
3514func (s *Server) renameUser(w http.ResponseWriter, r *http.Request) {
3515 if !s.requireAdmin(w, r) {
3516 return
3517 }
3518 var body struct {
3519 Label string `json:"label"`
3520 }
3521 if json.NewDecoder(r.Body).Decode(&body) != nil {
3522 httpError(w, http.StatusBadRequest, "bad request")
3523 return
3524 }
3525 label := strings.TrimSpace(body.Label)
3526 if label == "" || len(label) > 60 {
3527 httpError(w, http.StatusBadRequest, "bad label")
3528 return
3529 }
3530 // Only bots have an admin-settable plaintext name. A person's name is encrypted
3531 // under the instance key and set by the member themselves (POST /api/label), so
3532 // the admin can't (and shouldn't) rename people.
3533 if !s.db.isAgent(r.PathValue("id")) {
3534 httpError(w, http.StatusBadRequest, "people set their own name")
3535 return
3536 }
3537 if err := s.db.setUserLabel(r.PathValue("id"), label); err == sql.ErrNoRows {
3538 httpError(w, http.StatusBadRequest, "unknown user")
3539 return
3540 } else if err != nil {
3541 httpError(w, http.StatusInternalServerError, "db error")
3542 return
3543 }
3544 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
3545}
3546
3547// removeUser deletes a person from the instance (admin roster management).
3548func (s *Server) removeUser(w http.ResponseWriter, r *http.Request) {
3549 if !s.requireAdmin(w, r) {
3550 return
3551 }
3552 if err := s.db.removeUser(r.PathValue("id")); err != nil {
3553 httpError(w, http.StatusInternalServerError, "db error")
3554 return
3555 }
3556 // Removal is a moderation action — it lands in the audit log (issue #578).
3557 s.db.addAudit(s.adminActor(r), "member.removed", r.PathValue("id"), "", "", "")
3558 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
3559}
3560
3561// banUser removes a member AND remembers their public key (issue #578), so
3562// the same key can't re-register through any later invite — admin, member, or
3563// cohort. removeUser's sweep already covers their content, tokens, queued
3564// scheduled messages, and level memberships.
3565func (s *Server) banUser(w http.ResponseWriter, r *http.Request) {
3566 if !s.requireAdmin(w, r) {
3567 return
3568 }
3569 uid := r.PathValue("id")
3570 if !s.db.userExists(uid) {
3571 httpError(w, http.StatusBadRequest, "no such user")
3572 return
3573 }
3574 // Capture the key BEFORE removal deletes the row; a keyless member (a
3575 // pending invitee) has nothing durable to ban — removal alone covers them.
3576 pub := s.db.userPublicKey(uid)
3577 if err := s.db.removeUser(uid); err != nil {
3578 httpError(w, http.StatusInternalServerError, "db error")
3579 return
3580 }
3581 if pub != "" {
3582 if err := s.db.addBan(pub, uid, s.adminActor(r)); err != nil {
3583 httpError(w, http.StatusInternalServerError, "db error")
3584 return
3585 }
3586 }
3587 s.db.addAudit(s.adminActor(r), "member.banned", uid, "", "", "")
3588 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
3589}
3590
3591// adminActor resolves who performed an admin action for the audit log: the
3592// admin member's uid when the bearer is a device token, else "console" (the
3593// break-glass admin token has no member identity).
3594func (s *Server) adminActor(r *http.Request) string {
3595 const p = "Bearer "
3596 h := r.Header.Get("Authorization")
3597 if strings.HasPrefix(h, p) {
3598 if uid, ok := s.db.deviceTokenUser(strings.TrimSpace(strings.TrimPrefix(h, p))); ok {
3599 return uid
3600 }
3601 }
3602 return "console"
3603}
3604
3605// postReport files a report (issue #578): queue metadata for the server, the
3606// report's words sealed to each admin's public key by the reporter's client.
3607// Reports are testimony — the server can't verify them, and the UI says so.
3608func (s *Server) postReport(w http.ResponseWriter, r *http.Request) {
3609 var body struct {
3610 Token string `json:"token"`
3611 ReportedID string `json:"reported_id"`
3612 ThreadID string `json:"thread_id"`
3613 Blobs []struct {
3614 AdminID string `json:"admin_id"`
3615 Blob string `json:"blob"`
3616 } `json:"blobs"`
3617 }
3618 r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
3619 if json.NewDecoder(r.Body).Decode(&body) != nil {
3620 httpError(w, http.StatusBadRequest, "bad request")
3621 return
3622 }
3623 if !s.tokenOK(body.Token) {
3624 httpError(w, http.StatusForbidden, "not a member")
3625 return
3626 }
3627 uid, ok := s.db.deviceTokenUser(body.Token)
3628 if !ok {
3629 httpError(w, http.StatusForbidden, "no user for token")
3630 return
3631 }
3632 if body.ReportedID == "" || body.ReportedID == uid || !s.db.userExists(body.ReportedID) {
3633 httpError(w, http.StatusBadRequest, "bad reported_id")
3634 return
3635 }
3636 if body.ThreadID != "" && !s.db.threadMember(body.ThreadID, uid) {
3637 httpError(w, http.StatusForbidden, "not a thread member")
3638 return
3639 }
3640 // The report-abuse brake (content-blind): filing is cheap for a person,
3641 // expensive as a flood. Repeat-filer counts also surface in the queue.
3642 if s.db.reportsSince(uid, time.Now().Add(-time.Hour).Unix()) >= 5 {
3643 httpError(w, http.StatusTooManyRequests, "too many reports — try again later")
3644 return
3645 }
3646 // Every blob must be addressed to a current admin, and there must be at
3647 // least one — a report nobody can read helps no one.
3648 if len(body.Blobs) == 0 || len(body.Blobs) > 32 {
3649 httpError(w, http.StatusBadRequest, "bad blobs")
3650 return
3651 }
3652 blobs := map[string]string{}
3653 for _, b := range body.Blobs {
3654 if b.Blob == "" || len(b.Blob) > 64*1024 || s.db.userRole(b.AdminID) != "admin" {
3655 httpError(w, http.StatusBadRequest, "bad blobs")
3656 return
3657 }
3658 blobs[b.AdminID] = b.Blob
3659 }
3660 id, err := s.db.createReport(uid, body.ReportedID, body.ThreadID, blobs)
3661 if err != nil {
3662 httpError(w, http.StatusInternalServerError, "db error")
3663 return
3664 }
3665 // Nudge admins' live clients so the queue updates without a reload.
3666 admins, _ := s.db.adminUserIDs()
3667 if len(admins) > 0 {
3668 set := map[string]bool{}
3669 for _, a := range admins {
3670 set[a] = true
3671 }
3672 out, _ := json.Marshal(map[string]any{"type": "report_filed", "report_id": id})
3673 s.hub.broadcast <- outbound{members: set, data: out}
3674 }
3675 // And their away devices, throttled — one push per burst, not one per report.
3676 go s.pushReportNotice()
3677 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "id": id})
3678}
3679
3680// adminReports lists the moderation queue. The metadata is admin-auth like the
3681// rest of /api/admin; the content blob in each row is the CALLER's sealed copy
3682// (only an admin member's client holds the key to open it — the break-glass
3683// console token sees metadata only, by construction).
3684func (s *Server) adminReports(w http.ResponseWriter, r *http.Request) {
3685 if !s.requireAdmin(w, r) {
3686 return
3687 }
3688 actor := s.adminActor(r)
3689 reports, err := s.db.listReports(actor)
3690 if err != nil {
3691 httpError(w, http.StatusInternalServerError, "db error")
3692 return
3693 }
3694 writeJSON(w, http.StatusOK, map[string]any{"reports": reports})
3695}
3696
3697// resolveReportHandler records a report's outcome (the action itself — remove,
3698// warn, demote — runs through its own endpoint first; this closes the loop).
3699func (s *Server) resolveReportHandler(w http.ResponseWriter, r *http.Request) {
3700 if !s.requireAdmin(w, r) {
3701 return
3702 }
3703 var body struct {
3704 Action string `json:"action"`
3705 }
3706 if json.NewDecoder(r.Body).Decode(&body) != nil {
3707 httpError(w, http.StatusBadRequest, "bad request")
3708 return
3709 }
3710 switch body.Action {
3711 case "dismissed", "warned", "removed_thread", "removed_space", "demoted", "banned":
3712 default:
3713 httpError(w, http.StatusBadRequest, "bad action")
3714 return
3715 }
3716 id := r.PathValue("id")
3717 ok, err := s.db.resolveReport(id, body.Action, s.adminActor(r))
3718 if err != nil {
3719 httpError(w, http.StatusInternalServerError, "db error")
3720 return
3721 }
3722 if !ok {
3723 httpError(w, http.StatusConflict, "already resolved")
3724 return
3725 }
3726 s.db.addAudit(s.adminActor(r), "report.resolved", "", "", id, body.Action)
3727 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
3728}
3729
3730// adminWarn records that a warning was issued (issue #578). The warning's
3731// words travel as an ordinary E2EE DM from the admin's client with a `warn`
3732// flag inside the ciphertext — the server records only that the rung was used.
3733func (s *Server) adminWarn(w http.ResponseWriter, r *http.Request) {
3734 if !s.requireAdmin(w, r) {
3735 return
3736 }
3737 var body struct {
3738 UserID string `json:"user_id"`
3739 ReportID string `json:"report_id"`
3740 }
3741 if json.NewDecoder(r.Body).Decode(&body) != nil || body.UserID == "" {
3742 httpError(w, http.StatusBadRequest, "bad request")
3743 return
3744 }
3745 if !s.db.userExists(body.UserID) {
3746 httpError(w, http.StatusBadRequest, "no such user")
3747 return
3748 }
3749 s.db.addAudit(s.adminActor(r), "member.warned", body.UserID, "", body.ReportID, "")
3750 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
3751}
3752
3753// reportPushCooldown is the report notification's quiet window: the first
3754// report of a burst notifies at once; everything else inside the window rides
3755// silently (the notification's job is "go look", and each one carries the
3756// current open count, so nothing is lost to the throttle).
3757const reportPushCooldown = 15 * time.Minute
3758
3759// pushReportNotice tells the space's admins a report arrived — at most once
3760// per quiet window. The words are server-composed metadata ("N waiting"),
3761// never report content: the same plaintext-operational class as the changelog
3762// announcement, delivered the same two ways (Web Push + APNs) and shown even
3763// while the app is open (there's no in-app badge to lean on). Returns whether
3764// this call was the one that notified, for the throttle test.
3765func (s *Server) pushReportNotice() bool {
3766 s.reportPushMu.Lock()
3767 if time.Since(s.lastReportPush) < reportPushCooldown {
3768 s.reportPushMu.Unlock()
3769 return false
3770 }
3771 s.lastReportPush = time.Now()
3772 s.reportPushMu.Unlock()
3773
3774 admins, err := s.db.adminUserIDs()
3775 if err != nil || len(admins) == 0 {
3776 return true // throttle consumed; nobody to tell
3777 }
3778 recipients := make(map[string]bool, len(admins))
3779 for _, id := range admins {
3780 recipients[id] = true
3781 }
3782 n := s.db.openReportCount()
3783 title := "New report in " + s.db.getGroupName()
3784 body := "A report is waiting for review in the Admin panel."
3785 if n > 1 {
3786 body = fmt.Sprintf("%d reports are waiting for review in the Admin panel.", n)
3787 }
3788 payload, _ := json.Marshal(map[string]any{"report": true, "title": title, "body": body})
3789 sent := s.sendToRecipients(payload, "report", "", false, recipients)
3790 sent += s.apnsAnnounce(title, body, recipients)
3791 // The same once-per-burst signal to LIVE admin sessions: each open device
3792 // lights the Admin thread's dot from this frame directly (a self-posted
3793 // bubble couldn't — your own messages never light your dots), and one
3794 // visible session writes the durable line into the Admin stream.
3795 frame, _ := json.Marshal(map[string]any{"type": "report_notice", "n": n})
3796 s.hub.broadcast <- outbound{members: recipients, data: frame}
3797 log.Printf("reports: notified admins (%d subscription(s), %d open)", sent, n)
3798 return true
3799}
3800
3801// adminAudit pages the moderation audit log, newest first.
3802func (s *Server) adminAudit(w http.ResponseWriter, r *http.Request) {
3803 if !s.requireAdmin(w, r) {
3804 return
3805 }
3806 before, _ := strconv.ParseInt(r.URL.Query().Get("before"), 10, 64)
3807 limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
3808 entries, err := s.db.listAudit(before, limit)
3809 if err != nil {
3810 httpError(w, http.StatusInternalServerError, "db error")
3811 return
3812 }
3813 writeJSON(w, http.StatusOK, map[string]any{"entries": entries})
3814}
3815
3816// createDeviceInvite lets a member mint a fresh invite for their OWN account (to
3817// add another device), authenticated by their existing token. The browser wraps
3818// the key it already holds; the server stays blind. Ties to the device token's
3819// user, or creates one for a legacy member.
3820func (s *Server) createDeviceInvite(w http.ResponseWriter, r *http.Request) {
3821 var body struct {
3822 Token string `json:"token"`
3823 ID string `json:"id"`
3824 Wrapped string `json:"wrapped"`
3825 ClaimHash string `json:"claim_hash"`
3826 }
3827 if json.NewDecoder(r.Body).Decode(&body) != nil {
3828 httpError(w, http.StatusBadRequest, "bad request")
3829 return
3830 }
3831 if !s.tokenOK(body.Token) {
3832 httpError(w, http.StatusForbidden, "not a member")
3833 return
3834 }
3835 if body.ID == "" || body.Wrapped == "" || len(body.ID) > 200 || len(body.Wrapped) > 4096 ||
3836 body.ClaimHash == "" || len(body.ClaimHash) > 128 {
3837 httpError(w, http.StatusBadRequest, "missing id/wrapped")
3838 return
3839 }
3840 userID, ok := s.db.deviceTokenUser(body.Token)
3841 if !ok {
3842 // Legacy member (joined via an old #k= link) — give them a user now. No
3843 // plaintext name: they republish it encrypted (POST /api/label) on next load.
3844 id, err := s.db.createUser("")
3845 if err != nil {
3846 httpError(w, http.StatusInternalServerError, "db error")
3847 return
3848 }
3849 userID = id
3850 }
3851 if err := s.db.createKeyInvite(body.ID, userID, body.Wrapped, body.ClaimHash, 0); err != nil {
3852 httpError(w, http.StatusInternalServerError, "db error")
3853 return
3854 }
3855 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
3856}
3857
3858// postUserInvite lets a member invite a brand-new person straight into a DM.
3859// Ordinary members are gated by the "users can invite" admin setting (off by
3860// default); an admin may always invite. The browser
3861// generates the DM key and hands us only wrapped blobs: `wrapped` is the key
3862// encrypted to the invite secret (so the joiner recovers it), `self_wrapped` is it
3863// wrapped to the inviter's own public key. With no thread_id we create the pending
3864// invitee + DM + invite in one go; with a thread_id we re-issue a fresh link for an
3865// existing pending invitee (a lost/expired link, same chat). The server stays blind.
3866func (s *Server) postUserInvite(w http.ResponseWriter, r *http.Request) {
3867 var body struct {
3868 Token string `json:"token"`
3869 LabelBlob string `json:"label_blob"` // invitee's name, encrypted to the instance key by the inviter
3870 ID string `json:"id"`
3871 Wrapped string `json:"wrapped"`
3872 SelfWrapped string `json:"self_wrapped"`
3873 ClaimHash string `json:"claim_hash"`
3874 ThreadID string `json:"thread_id"`
3875 // TierID makes this a cohort invite (claimer lands in the level on
3876 // first-device claim). Role-admins only — level assignment is an
3877 // admin power, so a member invite can't smuggle anyone in.
3878 TierID string `json:"tier_id"`
3879 }
3880 if json.NewDecoder(r.Body).Decode(&body) != nil {
3881 httpError(w, http.StatusBadRequest, "bad request")
3882 return
3883 }
3884 if !s.tokenOK(body.Token) {
3885 httpError(w, http.StatusForbidden, "not a member")
3886 return
3887 }
3888 uid, ok := s.db.deviceTokenUser(body.Token)
3889 if !ok {
3890 httpError(w, http.StatusForbidden, "no user for token")
3891 return
3892 }
3893 // The "members can invite" toggle governs ordinary members; an admin can
3894 // always invite. Without the bypass the person who just set the space up
3895 // couldn't bring anyone in without flipping the toggle in the admin
3896 // console — a path we're sunsetting.
3897 if !s.db.usersCanInvite() && s.db.userRole(uid) != "admin" {
3898 httpError(w, http.StatusForbidden, "inviting is turned off")
3899 return
3900 }
3901 // The invite-minting brake (issue #578): content-blind, admin-exempt —
3902 // nobody human mints twenty invites in a day by hand.
3903 if s.db.userRole(uid) != "admin" && !s.brake().invites.allow(uid) {
3904 httpError(w, http.StatusTooManyRequests, "that's a lot of invites — try again tomorrow")
3905 return
3906 }
3907 if body.ID == "" || len(body.ID) > 200 || body.Wrapped == "" || len(body.Wrapped) > 4096 ||
3908 body.ClaimHash == "" || len(body.ClaimHash) > 128 {
3909 httpError(w, http.StatusBadRequest, "bad request")
3910 return
3911 }
3912
3913 // Re-send: a fresh link for an existing pending invitee (same DM). Only the
3914 // inviter (a member of that pending DM) may, and only while it's still pending.
3915 if body.ThreadID != "" {
3916 if !s.db.threadMember(body.ThreadID, uid) || s.db.threadKind(body.ThreadID) != "dm" {
3917 httpError(w, http.StatusForbidden, "not your pending chat")
3918 return
3919 }
3920 invitee, found := s.db.otherThreadMember(body.ThreadID, uid)
3921 if !found {
3922 httpError(w, http.StatusBadRequest, "no invitee")
3923 return
3924 }
3925 // Only re-send while they're still a keyless placeholder. Once they've joined
3926 // (registered a public key), a fresh claimable invite for them would be an
3927 // account-takeover vector — and there's nothing to re-send anyway.
3928 if s.db.userPublicKey(invitee) != "" {
3929 httpError(w, http.StatusBadRequest, "they've already joined")
3930 return
3931 }
3932 if err := s.db.createKeyInviteWithThread(body.ID, invitee, body.Wrapped, body.ThreadID, body.ClaimHash, 0); err != nil {
3933 httpError(w, http.StatusInternalServerError, "db error")
3934 return
3935 }
3936 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "thread_id": body.ThreadID, "user_id": invitee})
3937 return
3938 }
3939
3940 if body.LabelBlob == "" || len(body.LabelBlob) > 4096 || body.SelfWrapped == "" || len(body.SelfWrapped) > 4096 {
3941 httpError(w, http.StatusBadRequest, "bad request")
3942 return
3943 }
3944 // The flat-group rule applied to levels: membership is the power to
3945 // extend membership. Anyone may cohort-invite into a level THEY belong to
3946 // (they hold its key already — the server can't pretend otherwise);
3947 // admins may mint for any level. Nobody mints access they don't hold.
3948 if body.TierID != "" && !s.db.tierExists(body.TierID) {
3949 httpError(w, http.StatusBadRequest, "bad access level")
3950 return
3951 }
3952 if body.TierID != "" && s.db.userRole(uid) != "admin" && !s.db.tierMember(body.TierID, uid) {
3953 httpError(w, http.StatusForbidden, "not in that level")
3954 return
3955 }
3956 threadID, inviteeID, err := s.db.createUserInvite(uid, body.ID, body.LabelBlob, body.Wrapped, body.SelfWrapped, body.ClaimHash, 0)
3957 if err != nil {
3958 httpError(w, http.StatusInternalServerError, "db error")
3959 return
3960 }
3961 if body.TierID != "" {
3962 if err := s.db.setInviteTier(body.ID, body.TierID); err != nil {
3963 httpError(w, http.StatusInternalServerError, "db error")
3964 return
3965 }
3966 }
3967 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "thread_id": threadID, "user_id": inviteeID})
3968}
3969
3970// adoptKeyInvite handles a user invite opened by someone who is ALREADY a member on
3971// this device: their existing account joins the pending DM (deduped if they already
3972// share one), instead of the placeholder becoming a new user. `wrapped` is the DM
3973// key wrapped to their existing public key. Auth is their own device token.
3974func (s *Server) adoptKeyInvite(w http.ResponseWriter, r *http.Request) {
3975 var body struct {
3976 Token string `json:"token"`
3977 Wrapped string `json:"wrapped"`
3978 ClaimSecret string `json:"claim_secret"`
3979 }
3980 if json.NewDecoder(r.Body).Decode(&body) != nil {
3981 httpError(w, http.StatusBadRequest, "bad request")
3982 return
3983 }
3984 if !s.tokenOK(body.Token) {
3985 httpError(w, http.StatusForbidden, "not a member")
3986 return
3987 }
3988 uid, ok := s.db.deviceTokenUser(body.Token)
3989 if !ok {
3990 httpError(w, http.StatusForbidden, "no user for token")
3991 return
3992 }
3993 // Check if this is an admin invite (no wrapped payload needed for admin invites).
3994 id := r.PathValue("id")
3995 ki, found, err := s.db.getKeyInvite(id)
3996 if err != nil || !found {
3997 httpError(w, http.StatusForbidden, "invite unavailable")
3998 return
3999 }
4000 if ki.GrantsAdmin {
4001 // Admin invite: promote the existing user to admin.
4002 if ok, err := s.db.adoptAdminInvite(id, uid, body.ClaimSecret); err != nil {
4003 httpError(w, http.StatusInternalServerError, "db error")
4004 return
4005 } else if !ok {
4006 httpError(w, http.StatusForbidden, "invite unavailable")
4007 return
4008 }
4009 // Unlike a fresh joiner's first key (which fires "joined"), promoting an
4010 // EXISTING member to admin touches no roster field a client watches for —
4011 // so every other open tab kept treating this user as a non-admin (e.g.
4012 // when building a report's admin-encryption list) until something else
4013 // happened to trigger a reload. Tell open tabs now.
4014 out, _ := json.Marshal(map[string]any{"type": "role_changed", "user_id": uid})
4015 s.hub.broadcast <- outbound{data: out}
4016 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
4017 return
4018 }
4019 // DM invite: wrapped key is required.
4020 if body.Wrapped == "" || len(body.Wrapped) > 4096 {
4021 httpError(w, http.StatusBadRequest, "bad request")
4022 return
4023 }
4024 threadID, ok, err := s.db.adoptUserInvite(id, uid, body.Wrapped, body.ClaimSecret)
4025 if err != nil {
4026 httpError(w, http.StatusInternalServerError, "db error")
4027 return
4028 }
4029 if !ok {
4030 httpError(w, http.StatusForbidden, "invite unavailable")
4031 return
4032 }
4033 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "thread_id": threadID})
4034}
4035
4036// cancelInvite tears down a pending DM whose invitee never joined (thread, keys,
4037// members, placeholder, invite). Only the inviter may, and only while it's pending.
4038func (s *Server) cancelInvite(w http.ResponseWriter, r *http.Request) {
4039 var body struct {
4040 Token string `json:"token"`
4041 }
4042 if json.NewDecoder(r.Body).Decode(&body) != nil {
4043 httpError(w, http.StatusBadRequest, "bad request")
4044 return
4045 }
4046 if !s.tokenOK(body.Token) {
4047 httpError(w, http.StatusForbidden, "not a member")
4048 return
4049 }
4050 uid, ok := s.db.deviceTokenUser(body.Token)
4051 if !ok {
4052 httpError(w, http.StatusForbidden, "no user for token")
4053 return
4054 }
4055 done, err := s.db.cancelUserInvite(r.PathValue("id"), uid)
4056 if err != nil {
4057 httpError(w, http.StatusInternalServerError, "db error")
4058 return
4059 }
4060 if !done {
4061 httpError(w, http.StatusBadRequest, "not a pending invite")
4062 return
4063 }
4064 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
4065}
4066
4067// ---- admin API ----------------------------------------------------------
4068
4069func (s *Server) requireAdmin(w http.ResponseWriter, r *http.Request) bool {
4070 const p = "Bearer "
4071 h := r.Header.Get("Authorization")
4072 if strings.HasPrefix(h, p) {
4073 bearer := strings.TrimSpace(strings.TrimPrefix(h, p))
4074 // Two ways in: the admin token (break-glass / provisioning), or a member's
4075 // own device token when their user holds the admin role — so the in-app
4076 // admin surface works with the session it already has. Either way this is
4077 // authorisation only; no key material rides on it.
4078 if s.db.checkAdmin(bearer) {
4079 return true
4080 }
4081 if uid, ok := s.db.deviceTokenUser(bearer); ok && s.db.userRole(uid) == "admin" {
4082 return true
4083 }
4084 }
4085 httpError(w, http.StatusUnauthorized, "admin auth required")
4086 return false
4087}
4088
4089// ---- push notifications -------------------------------------------------
4090
4091func (s *Server) getVAPID(w http.ResponseWriter, r *http.Request) {
4092 writeJSON(w, http.StatusOK, map[string]any{"publicKey": s.vapidPub})
4093}
4094
4095func (s *Server) subscribePush(w http.ResponseWriter, r *http.Request) {
4096 var body struct {
4097 Token string `json:"token"`
4098 Subscription struct {
4099 Endpoint string `json:"endpoint"`
4100 Keys struct {
4101 P256dh string `json:"p256dh"`
4102 Auth string `json:"auth"`
4103 } `json:"keys"`
4104 } `json:"subscription"`
4105 }
4106 if json.NewDecoder(r.Body).Decode(&body) != nil {
4107 httpError(w, http.StatusBadRequest, "bad request")
4108 return
4109 }
4110 // Only valid participants (invite or device token) may register for push.
4111 if !s.tokenOK(body.Token) {
4112 httpError(w, http.StatusForbidden, "invalid invite")
4113 return
4114 }
4115 if body.Subscription.Endpoint == "" {
4116 httpError(w, http.StatusBadRequest, "missing subscription")
4117 return
4118 }
4119 // The endpoint is attacker-controlled and the server POSTs to it; reject
4120 // anything that isn't a plain https URL so it can't be aimed at our own
4121 // network (SSRF). The pushClient dialer enforces the resolved-IP check.
4122 if err := validatePushEndpoint(body.Subscription.Endpoint); err != nil {
4123 httpError(w, http.StatusBadRequest, "bad subscription endpoint")
4124 return
4125 }
4126 uid, _ := s.db.deviceTokenUser(body.Token) // "" for a legacy (non-device) token
4127 if err := s.db.addSubscription(PushSub{
4128 Endpoint: body.Subscription.Endpoint,
4129 Token: body.Token,
4130 P256dh: body.Subscription.Keys.P256dh,
4131 Auth: body.Subscription.Keys.Auth,
4132 UserID: uid,
4133 }); err != nil {
4134 httpError(w, http.StatusInternalServerError, "db error")
4135 return
4136 }
4137 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
4138}
4139
4140func (s *Server) unsubscribePush(w http.ResponseWriter, r *http.Request) {
4141 var body struct {
4142 Token string `json:"token"`
4143 Endpoint string `json:"endpoint"`
4144 }
4145 if json.NewDecoder(r.Body).Decode(&body) != nil {
4146 httpError(w, http.StatusBadRequest, "bad request")
4147 return
4148 }
4149 // Require a valid participant token and only remove that token's own
4150 // subscription — otherwise anyone who learned an endpoint could silently
4151 // unsubscribe (deny notifications to) someone else's device.
4152 if !s.tokenOK(body.Token) {
4153 httpError(w, http.StatusForbidden, "not a member")
4154 return
4155 }
4156 if body.Endpoint != "" {
4157 _ = s.db.deleteOwnSubscription(body.Endpoint, body.Token)
4158 }
4159 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
4160}
4161
4162func (s *Server) testPush(w http.ResponseWriter, r *http.Request) {
4163 if !s.requireAdmin(w, r) {
4164 return
4165 }
4166 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "sent": s.sendTestPush()})
4167}
4168
4169// serveSW serves the service worker from the root path so its scope covers the app.
4170func (s *Server) serveSW(w http.ResponseWriter, r *http.Request) {
4171 b, err := webFS.ReadFile("web/static/sw.js")
4172 if err != nil {
4173 http.NotFound(w, r)
4174 return
4175 }
4176 w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
4177 w.Header().Set("Cache-Control", "no-cache")
4178 w.Write(b)
4179}
4180
4181// serveManifest generates the PWA manifest with the configured group name, so the
4182// Home Screen / install name matches the chat.
4183func (s *Server) serveManifest(w http.ResponseWriter, r *http.Request) {
4184 name := s.db.getGroupName()
4185 w.Header().Set("Content-Type", "application/manifest+json; charset=utf-8")
4186 json.NewEncoder(w).Encode(map[string]any{
4187 "name": name,
4188 "short_name": name,
4189 "description": "A private, end-to-end encrypted group chat",
4190 "start_url": "/",
4191 "scope": "/",
4192 "display": "standalone",
4193 "background_color": "#f6f7fb",
4194 "theme_color": "#5b6cff",
4195 "icons": []map[string]any{
4196 {"src": "/static/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any"},
4197 {"src": "/static/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any maskable"},
4198 },
4199 })
4200}
4201
4202// ---- group name ---------------------------------------------------------
4203
4204func (s *Server) getGroup(w http.ResponseWriter, r *http.Request) {
4205 // `avatar` lets clients decide whether to render /api/server-avatar without a
4206 // speculative image fetch (used by the join cards, home Save-passkey card, and
4207 // the native add-chat screens).
4208 _, _, _, hasAvatar := s.db.getInstanceAvatar()
4209 // name_set distinguishes an admin-chosen name from the compiled-in default,
4210 // so first-run setup asks for a name instead of offering "keep the default".
4211 out := map[string]any{"name": s.db.getGroupName(), "name_set": s.db.groupNameSet(), "avatar": hasAvatar}
4212 if hasAvatar {
4213 // The photo's alt text (plaintext branding, admin-set) — clients set it
4214 // on every rendering of /api/server-avatar, join cards included.
4215 alt, _, _ := s.db.getConfig("server_avatar_alt")
4216 out["avatar_alt"] = alt
4217 }
4218 // Sealed branding (docs/no-plaintext.md): the flag is public (join cards
4219 // need it to skip rendering ciphertext), but the blob + salt are NOT —
4220 // members get them below, and invitees get them via their unguessable
4221 // invite id (getKeyInvite). Serving ciphertext to bare visitors would only
4222 // widen the old plaintext gating: anyone could start the offline
4223 // brute-force, and any past link-holder could open the admin
4224 // name/email — a tier the plaintext era kept members-only. `name` above
4225 // already fell back to the compiled-in default (seal clears group_name).
4226 if s.db.brandingSealed() {
4227 out["sealed"] = true
4228 }
4229 // The administrator identity is member-only, not public branding: this
4230 // endpoint is also the unauthenticated onboarding read, so only add the
4231 // admin's name + contact email when a valid member token is presented.
4232 if s.tokenOK(r.URL.Query().Get("token")) {
4233 // Members get the sealed branding set plus the branding key wrapped
4234 // under the instance key, so nobody has to re-visit an invite link.
4235 if s.db.brandingSealed() {
4236 blob, _, _ := s.db.getConfig("branding_blob")
4237 salt, _, _ := s.db.getConfig("branding_salt")
4238 out["branding_blob"] = blob
4239 out["branding_salt"] = salt
4240 ks, _, _ := s.db.getConfig("branding_key_sealed")
4241 out["branding_key_sealed"] = ks
4242 }
4243 out["admin_name"] = s.db.getAdminName()
4244 out["admin_email"] = s.db.getAdminEmail()
4245 // The space description is member-gated like the admin identity: this
4246 // endpoint is also the public onboarding read, and invitees get the
4247 // description via their (unguessable) invite id instead — see getKeyInvite.
4248 out["description"] = s.db.getGroupDescription()
4249 // The feature gates ride the member read too — the native apps consult
4250 // them to hide entry points (the gated endpoints enforce regardless).
4251 out["ai_enabled"] = s.db.aiEnabled()
4252 out["bots_enabled"] = s.db.botsEnabled()
4253 out["apps_enabled"] = s.db.appsEnabled()
4254 out["member_apps_enabled"] = s.db.memberAppsEnabled()
4255 // The fetch service this instance prefers for unfurls (docs/fetch.md).
4256 // The web page gets it injected (__FETCH_URL__); native reads it here.
4257 out["fetch_url"] = s.fetchURL
4258 }
4259 writeJSON(w, http.StatusOK, out)
4260}
4261
4262// ---- server avatar (instance branding photo) ----------------------------
4263//
4264// A per-instance branding photo, admin-set and served in the clear like the
4265// group name — it must render before any key exists (onboarding) and to the
4266// instance-agnostic home server, so it can't be E2E-encrypted. Never user
4267// content; message/profile-photo E2E is untouched.
4268
4269// getServerAvatar serves the branding photo unauthenticated (like getGroup). 404
4270// when unset so clients fall back to the built-in app icon.
4271func (s *Server) getServerAvatar(w http.ResponseWriter, r *http.Request) {
4272 data, mime, updatedAt, ok := s.db.getInstanceAvatar()
4273 if !ok {
4274 http.NotFound(w, r)
4275 return
4276 }
4277 // ETag from the update stamp so an admin's change propagates but unchanged
4278 // photos revalidate cheaply. X-Content-Type-Options: nosniff is set globally.
4279 etag := fmt.Sprintf(`"%d"`, updatedAt)
4280 if match := r.Header.Get("If-None-Match"); match == etag {
4281 w.WriteHeader(http.StatusNotModified)
4282 return
4283 }
4284 w.Header().Set("Content-Type", mime)
4285 w.Header().Set("ETag", etag)
4286 w.Header().Set("Cache-Control", "public, max-age=60, must-revalidate")
4287 w.Write(data)
4288}
4289
4290// setServerAvatar (admin) stores a new branding photo. The body is the raw image
4291// bytes; the type is sniffed from the content, not trusted from a header.
4292// While branding is sealed, photos go through sealBranding instead (the bytes
4293// here would be readable at rest).
4294func (s *Server) setServerAvatar(w http.ResponseWriter, r *http.Request) {
4295 if !s.requireAdmin(w, r) {
4296 return
4297 }
4298 if !s.requireUnsealed(w) {
4299 return
4300 }
4301 r.Body = http.MaxBytesReader(w, r.Body, maxServerAvatarBytes)
4302 data, err := io.ReadAll(r.Body)
4303 if err != nil {
4304 httpError(w, http.StatusRequestEntityTooLarge, "image too large (max 1 MB)")
4305 return
4306 }
4307 if len(data) == 0 {
4308 httpError(w, http.StatusBadRequest, "empty upload")
4309 return
4310 }
4311 // Sniff the real type rather than trusting the client. Only raster images we
4312 // know are safe to serve inline — no SVG (it can carry script).
4313 mime := http.DetectContentType(data)
4314 switch mime {
4315 case "image/png", "image/jpeg", "image/webp":
4316 default:
4317 httpError(w, http.StatusUnsupportedMediaType, "must be a PNG, JPEG, or WebP image")
4318 return
4319 }
4320 if err := s.db.setInstanceAvatar(data, mime, time.Now().Unix()); err != nil {
4321 httpError(w, http.StatusInternalServerError, "db error")
4322 return
4323 }
4324 // Optional alt text rides as a query param (the body is the raw image).
4325 // Plaintext branding like the photo itself — it must be readable on keyless
4326 // surfaces (the join card). A new photo always resets it (empty clears).
4327 if err := s.db.setConfig("server_avatar_alt", trimAltText(r.URL.Query().Get("alt"))); err != nil {
4328 httpError(w, http.StatusInternalServerError, "db error")
4329 return
4330 }
4331 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
4332}
4333
4334// deleteServerAvatar (admin) clears the branding photo (reverts to the app icon).
4335func (s *Server) deleteServerAvatar(w http.ResponseWriter, r *http.Request) {
4336 if !s.requireAdmin(w, r) {
4337 return
4338 }
4339 if err := s.db.clearInstanceAvatar(); err != nil {
4340 httpError(w, http.StatusInternalServerError, "db error")
4341 return
4342 }
4343 _ = s.db.setConfig("server_avatar_alt", "") // the alt text goes with the photo
4344 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
4345}
4346
4347func (s *Server) setGroup(w http.ResponseWriter, r *http.Request) {
4348 if !s.requireAdmin(w, r) {
4349 return
4350 }
4351 if !s.requireUnsealed(w) {
4352 return
4353 }
4354 var body struct {
4355 Name string `json:"name"`
4356 AdminName string `json:"admin_name"`
4357 AdminEmail string `json:"admin_email"`
4358 }
4359 json.NewDecoder(r.Body).Decode(&body)
4360 name := strings.TrimSpace(body.Name)
4361 if name == "" || len(name) > 60 {
4362 httpError(w, http.StatusBadRequest, "name must be 1–60 characters")
4363 return
4364 }
4365 // The administrator name + contact email are optional (empty clears them).
4366 adminName := strings.TrimSpace(body.AdminName)
4367 adminEmail := strings.TrimSpace(body.AdminEmail)
4368 if len(adminName) > 60 {
4369 httpError(w, http.StatusBadRequest, "administrator name must be at most 60 characters")
4370 return
4371 }
4372 // A light sanity check, not full RFC validation: a contact email should look
4373 // like one (an @ with something either side) and stay short.
4374 if adminEmail != "" && (len(adminEmail) > 120 || !isRoughEmail(adminEmail)) {
4375 httpError(w, http.StatusBadRequest, "contact email doesn't look valid")
4376 return
4377 }
4378 if err := s.db.setGroupName(name); err != nil {
4379 httpError(w, http.StatusInternalServerError, "db error")
4380 return
4381 }
4382 if err := s.db.setAdminName(adminName); err != nil {
4383 httpError(w, http.StatusInternalServerError, "db error")
4384 return
4385 }
4386 if err := s.db.setAdminEmail(adminEmail); err != nil {
4387 httpError(w, http.StatusInternalServerError, "db error")
4388 return
4389 }
4390 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "name": name, "admin_name": adminName, "admin_email": adminEmail})
4391}
4392
4393// applySeededName seeds the space's name from LCHAT_GROUP_NAME — the create
4394// flow asks for the name up front now, and the provisioner delivers it via the
4395// instance env (control.go writes it at add-instance). Seed-only, never an
4396// override: a name the admin has since changed (or sealed) always wins, so
4397// restarts can't clobber it. The setup conversation composes with this — it
4398// offers "Keep "{name}"" when a name is already set rather than asking cold.
4399func applySeededName(db *DB) error {
4400 name := strings.TrimSpace(os.Getenv("LCHAT_GROUP_NAME"))
4401 if name == "" || db.groupNameSet() {
4402 return nil
4403 }
4404 // The create path caps at 60 too; belt-and-suspenders, at a rune boundary.
4405 if len(name) > 60 {
4406 cut := 60
4407 for cut > 0 && !utf8.RuneStart(name[cut]) {
4408 cut--
4409 }
4410 name = strings.TrimSpace(name[:cut])
4411 }
4412 if name == "" {
4413 return nil
4414 }
4415 return db.setGroupName(name)
4416}
4417
4418// applySkipSetup is a TEST/DEV convenience (LCHAT_SKIP_SETUP=1): mark the
4419// first-run setup conversation complete and seed workable defaults, so a
4420// scratch instance is usable the moment its setup link is claimed — the
4421// claimer still becomes the admin, they just skip the conversation. Values an
4422// admin can change are seeded only when unset, so restarts never clobber
4423// in-test edits. Never set this on a real instance: it forfeits onboarding.
4424func applySkipSetup(db *DB) error {
4425 if strings.TrimSpace(os.Getenv("LCHAT_SKIP_SETUP")) == "" {
4426 return nil
4427 }
4428 log.Printf("LCHAT_SKIP_SETUP set: first-run setup conversation disabled (test/dev)")
4429 if err := db.setSetupComplete(true); err != nil {
4430 return err
4431 }
4432 // applySeededName already consumed LCHAT_GROUP_NAME; this only backfills the
4433 // dev default when nothing named the space at all.
4434 if !db.groupNameSet() {
4435 if err := db.setGroupName("Test Space"); err != nil {
4436 return err
4437 }
4438 }
4439 // Members can invite — the joiner flow is usually what a test instance is for.
4440 if _, ok, _ := db.getConfig("user_invites_enabled"); !ok {
4441 if err := db.setUsersCanInvite(true); err != nil {
4442 return err
4443 }
4444 }
4445 return nil
4446}
4447
4448// trimAltText caps the photo's alt text at a RUNE boundary — a plain byte slice
4449// mid-emoji would store invalid UTF-8 and render as U+FFFD on the join card.
4450func trimAltText(s string) string {
4451 s = strings.TrimSpace(s)
4452 if len(s) <= 300 {
4453 return s
4454 }
4455 cut := 300
4456 for cut > 0 && !utf8.RuneStart(s[cut]) {
4457 cut--
4458 }
4459 return s[:cut]
4460}
4461
4462// isRoughEmail is a deliberately loose check — just enough to reject obvious
4463// typos in the admin's optional contact address without pretending to validate
4464// deliverability. "a@b.c" passes; "not an email" doesn't.
4465func isRoughEmail(s string) bool {
4466 at := strings.IndexByte(s, '@')
4467 if at <= 0 || at == len(s)-1 {
4468 return false
4469 }
4470 return strings.Contains(s[at+1:], ".") && !strings.ContainsAny(s, " \t\n")
4471}
4472
4473// ---- instance settings (admin) ------------------------------------------
4474
4475// getSettings returns the instance settings the admin console manages.
4476func (s *Server) getSettings(w http.ResponseWriter, r *http.Request) {
4477 if !s.requireAdmin(w, r) {
4478 return
4479 }
4480 writeJSON(w, http.StatusOK, map[string]any{
4481 "user_invites": s.db.usersCanInvite(),
4482 "ai_enabled": s.db.aiEnabled(),
4483 "bots_enabled": s.db.botsEnabled(),
4484 "apps_enabled": s.db.appsEnabled(),
4485 "member_apps_enabled": s.db.memberAppsEnabled(),
4486 "space_installs_admins": s.db.spaceInstallsAdmins(),
4487 "admin_name": s.db.getAdminName(),
4488 "admin_email": s.db.getAdminEmail(),
4489 "description": s.db.getGroupDescription(),
4490 "setup_complete": s.db.setupComplete(),
4491 "update_auto": s.db.updateAuto(),
4492 "update_download": s.db.updateDownload(),
4493 "update_channel": s.db.updateChannel(),
4494 "update_pin": s.db.updatePin(),
4495 "update_major": s.db.updateMajor(),
4496 "update": s.updateInfo(),
4497 })
4498}
4499
4500// setSettings toggles instance settings. Fields are pointers so an omitted field
4501// is left unchanged (a partial update).
4502func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
4503 if !s.requireAdmin(w, r) {
4504 return
4505 }
4506 var body struct {
4507 UserInvites *bool `json:"user_invites"`
4508 // The feature gates (default on; see db.go): AI replies, bot creation,
4509 // apps, and members building their own apps. Enforcement lives at the
4510 // gated endpoints.
4511 AIEnabled *bool `json:"ai_enabled"`
4512 BotsEnabled *bool `json:"bots_enabled"`
4513 AppsEnabled *bool `json:"apps_enabled"`
4514 MemberAppsEnabled *bool `json:"member_apps_enabled"`
4515 // Space-install policy: true = only admins may add apps for everyone.
4516 SpaceInstallsAdmins *bool `json:"space_installs_admins"`
4517 // The setup conversation marks itself done (or the admin dismisses it).
4518 SetupComplete *bool `json:"setup_complete"`
4519 // The photo's alt text, editable without re-uploading the image (the
4520 // admin panel's alt field). Plaintext branding, like the photo itself.
4521 AvatarAlt *string `json:"avatar_alt"`
4522 // Auto-update prefs (docs/server-releases.md); the box updater acts on
4523 // them, the instance just stores + reports them.
4524 UpdateAuto *bool `json:"update_auto"`
4525 UpdateDownload *bool `json:"update_download"`
4526 UpdateChannel *string `json:"update_channel"`
4527 // Pin to one exact version ("" clears): the updater skips a pinned
4528 // instance entirely. Set by `lchat update pin` / `deploy --pin`; cleared
4529 // from the admin UI by picking a channel.
4530 UpdatePin *string `json:"update_pin"`
4531 // Stay on one major version ("" clears): minors/patches follow the
4532 // channel, a major bump holds until the admin raises this.
4533 UpdateMajor *string `json:"update_major"`
4534 }
4535 if json.NewDecoder(r.Body).Decode(&body) != nil {
4536 httpError(w, http.StatusBadRequest, "bad request")
4537 return
4538 }
4539 // Validate everything before writing anything, so a rejected request never
4540 // half-applies (fields are independent config keys, not one transaction).
4541 if body.UpdateChannel != nil && !validChannel(*body.UpdateChannel) {
4542 httpError(w, http.StatusBadRequest, "unknown channel (edge, beta, or stable)")
4543 return
4544 }
4545 if body.UpdatePin != nil && *body.UpdatePin != "" && !validVersion(*body.UpdatePin) {
4546 httpError(w, http.StatusBadRequest, "invalid pin version")
4547 return
4548 }
4549 if body.UpdateMajor != nil && !validMajor(*body.UpdateMajor) {
4550 httpError(w, http.StatusBadRequest, "invalid major version (a number, or empty to follow everything)")
4551 return
4552 }
4553 if body.UserInvites != nil {
4554 was := s.db.usersCanInvite()
4555 if err := s.db.setUsersCanInvite(*body.UserInvites); err != nil {
4556 httpError(w, http.StatusInternalServerError, "db error")
4557 return
4558 }
4559 // The invite pause is the moderation panic switch (issue #578) —
4560 // flips get a paper trail like every other moderation action.
4561 if was != *body.UserInvites {
4562 act := "invites.resumed"
4563 if !*body.UserInvites {
4564 act = "invites.paused"
4565 }
4566 s.db.addAudit(s.adminActor(r), act, "", "", "", "")
4567 // Every connected client baked USER_INVITES into its page at load
4568 // (index.html's meta tag) — without this, the toggle's effect on
4569 // the invite UI only ever showed up after a reload (issue #346).
4570 out, _ := json.Marshal(map[string]any{"type": "user_invites_changed", "enabled": *body.UserInvites})
4571 s.hub.broadcast <- outbound{data: out} // members:nil → everyone
4572 }
4573 }
4574 if body.AIEnabled != nil {
4575 // EXPLICIT consent is what signals, not the implicit default:
4576 // aiEnabled() reads true on a fresh space (absent key, the compat
4577 // default), so a plain was/now comparison would swallow the very
4578 // first "Bring Eleven in" — the feature's core case. Explicitly-on
4579 // before the write is the one state that stays silent.
4580 wasExplicitlyOn := s.db.aiEnabledExplicitly()
4581 if err := s.db.setAIEnabled(*body.AIEnabled); err != nil {
4582 httpError(w, http.StatusInternalServerError, "db error")
4583 return
4584 }
4585 // An explicit enable asks the provisioner to make sure this space's
4586 // sidecar exists (#858) — from ANY admin surface (setup flow, admin
4587 // console, Admin app), so the toggle and the provisioning can't
4588 // drift. Async and best-effort: idempotent end to end, no-op on
4589 // self-hosted instances (no meter env), and a lost signal is
4590 // re-sent by the next flip.
4591 if *body.AIEnabled && !wasExplicitlyOn {
4592 go s.signalAIOptIn()
4593 }
4594 }
4595 if body.BotsEnabled != nil {
4596 if err := s.db.setBotsEnabled(*body.BotsEnabled); err != nil {
4597 httpError(w, http.StatusInternalServerError, "db error")
4598 return
4599 }
4600 }
4601 if body.AppsEnabled != nil {
4602 if err := s.db.setAppsEnabled(*body.AppsEnabled); err != nil {
4603 httpError(w, http.StatusInternalServerError, "db error")
4604 return
4605 }
4606 }
4607 if body.MemberAppsEnabled != nil {
4608 if err := s.db.setMemberAppsEnabled(*body.MemberAppsEnabled); err != nil {
4609 httpError(w, http.StatusInternalServerError, "db error")
4610 return
4611 }
4612 }
4613 if body.SpaceInstallsAdmins != nil {
4614 if err := s.db.setSpaceInstallsAdmins(*body.SpaceInstallsAdmins); err != nil {
4615 httpError(w, http.StatusInternalServerError, "db error")
4616 return
4617 }
4618 }
4619 if body.SetupComplete != nil {
4620 if err := s.db.setSetupComplete(*body.SetupComplete); err != nil {
4621 httpError(w, http.StatusInternalServerError, "db error")
4622 return
4623 }
4624 }
4625 if body.AvatarAlt != nil {
4626 // The one branding field in this settings grab-bag — while sealed it
4627 // must 409 like every other plaintext branding setter (alt text rides
4628 // inside the sealed blob instead).
4629 if !s.requireUnsealed(w) {
4630 return
4631 }
4632 if err := s.db.setConfig("server_avatar_alt", trimAltText(*body.AvatarAlt)); err != nil {
4633 httpError(w, http.StatusInternalServerError, "db error")
4634 return
4635 }
4636 }
4637 if body.UpdateAuto != nil {
4638 if err := s.db.setUpdateAuto(*body.UpdateAuto); err != nil {
4639 httpError(w, http.StatusInternalServerError, "db error")
4640 return
4641 }
4642 }
4643 if body.UpdateDownload != nil {
4644 if err := s.db.setUpdateDownload(*body.UpdateDownload); err != nil {
4645 httpError(w, http.StatusInternalServerError, "db error")
4646 return
4647 }
4648 }
4649 if body.UpdateChannel != nil {
4650 if err := s.db.setUpdateChannel(*body.UpdateChannel); err != nil {
4651 httpError(w, http.StatusInternalServerError, "db error")
4652 return
4653 }
4654 }
4655 if body.UpdatePin != nil {
4656 if err := s.db.setUpdatePin(*body.UpdatePin); err != nil {
4657 httpError(w, http.StatusInternalServerError, "db error")
4658 return
4659 }
4660 }
4661 if body.UpdateMajor != nil {
4662 if err := s.db.setUpdateMajor(*body.UpdateMajor); err != nil {
4663 httpError(w, http.StatusInternalServerError, "db error")
4664 return
4665 }
4666 }
4667 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "user_invites": s.db.usersCanInvite()})
4668}
4669
4670// ---- helpers ------------------------------------------------------------
4671
4672// noCache makes browsers revalidate static assets, so deploys take effect without
4673// a hard reload.
4674func noCache(h http.Handler) http.Handler {
4675 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
4676 w.Header().Set("Cache-Control", "no-cache")
4677 h.ServeHTTP(w, r)
4678 })
4679}
4680
4681func writeJSON(w http.ResponseWriter, status int, v any) {
4682 w.Header().Set("Content-Type", "application/json")
4683 w.WriteHeader(status)
4684 json.NewEncoder(w).Encode(v)
4685}
4686
4687func httpError(w http.ResponseWriter, status int, msg string) {
4688 writeJSON(w, status, map[string]any{"error": msg})
4689}
4690
4691func boolStr(b bool) string {
4692 if b {
4693 return "1"
4694 }
4695 return "0"
4696}
4697
4698func envOr(key, fallback string) string {
4699 if v := os.Getenv(key); v != "" {
4700 return v
4701 }
4702 return fallback
4703}
4704
4705// envBytes reads a byte-count env var (a plain integer number of bytes), falling
4706// back to def when unset, unparseable, or non-positive.
4707func envBytes(key string, def int64) int64 {
4708 if v := strings.TrimSpace(os.Getenv(key)); v != "" {
4709 if n, err := strconv.ParseInt(v, 10, 64); err == nil && n > 0 {
4710 return n
4711 }
4712 }
4713 return def
4714}
4715
4716func printAdminLink(addr, token string) {
4717 host := addr
4718 if strings.HasPrefix(host, ":") {
4719 host = "localhost" + host
4720 }
4721 log.Printf("\n\n Admin link (open once, keep it secret):\n http://%s/admin#token=%s\n\n", host, token)
4722}
4723
4724// ---- APNs (native iOS app) -----------------------------------------------
4725
4726// apnsSubscribe registers an iPhone's APNs device token against the caller's
4727// session token, so the same suppression rules as Web Push apply. sandbox marks
4728// tokens from development builds (delivered via Apple's sandbox gateway).
4729func (s *Server) apnsSubscribe(w http.ResponseWriter, r *http.Request) {
4730 var body struct {
4731 Token string `json:"token"`
4732 APNsToken string `json:"apns_token"`
4733 Sandbox bool `json:"sandbox"`
4734 }
4735 if json.NewDecoder(r.Body).Decode(&body) != nil {
4736 httpError(w, http.StatusBadRequest, "bad request")
4737 return
4738 }
4739 if !s.tokenOK(body.Token) {
4740 httpError(w, http.StatusForbidden, "not a member")
4741 return
4742 }
4743 if !apns.ValidDeviceToken(body.APNsToken) {
4744 httpError(w, http.StatusBadRequest, "bad request")
4745 return
4746 }
4747 if err := s.db.addAPNsToken(APNsToken{APNsToken: body.APNsToken, Token: body.Token, Sandbox: body.Sandbox}); err != nil {
4748 httpError(w, http.StatusInternalServerError, "db error")
4749 return
4750 }
4751 writeJSON(w, http.StatusOK, map[string]any{"ok": true, "enabled": s.apns != nil})
4752}
4753
4754func (s *Server) apnsUnsubscribe(w http.ResponseWriter, r *http.Request) {
4755 var body struct {
4756 Token string `json:"token"`
4757 APNsToken string `json:"apns_token"`
4758 }
4759 if json.NewDecoder(r.Body).Decode(&body) != nil {
4760 httpError(w, http.StatusBadRequest, "bad request")
4761 return
4762 }
4763 if !s.tokenOK(body.Token) {
4764 httpError(w, http.StatusForbidden, "not a member")
4765 return
4766 }
4767 _ = s.db.deleteAPNsToken(body.APNsToken)
4768 writeJSON(w, http.StatusOK, map[string]any{"ok": true})
4769}
4770