eleven / messenger Public

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

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