package main // 🤖 The space thread: one hidden, all-members thread per instance, backing // SPACE-WIDE mini-apps (docs/space-apps.md). It is the "meta-thread" answer to // "install this app for everyone, everywhere": a `spaceapps` registry app and // each space-installed app's events/state fold from THIS thread's encrypted // log, so one shared instance is readable and writable from any chat. // // Everything reuses the existing per-thread machinery — messages, state // snapshots, scheduling, WS fan-out — with exactly two twists: // // - The key rides open_key, the open-group mechanism: the thread's AES key // encrypted under the INSTANCE key, which every member (including late // joiners) can already unwrap with their own private key. No per-member // wraps, no new distribution path, and the "instance key never encrypts // messages" invariant holds — it only wraps the space thread's key. // - Membership is IMPLICIT: every member of the space is a member of the // space thread by construction (db.threadMember / db.memberUserIDs), so // there are no rows to backfill and no join path that can drift. Agents // are excluded, mirroring joinDefaultThreads — a bot reading the space // log must be a deliberate, disclosed choice (an explicit membership row // added later), never a silent default. // // The server stays exactly as blind as for any thread: it stores the row, the // wrapped key blob, and opaque ciphertext. It never learns WHICH apps are // installed (that's fold state inside the log) — only that a space thread // exists. The thread never appears in GET /api/threads (threadsForUser joins // on membership rows, of which it has none), so old clients — including the // native apps until they learn the feature — never see it; new clients fetch // it explicitly here. Push fan-out is skipped for it (see pushNewMessage): // registry churn must not buzz phones, and clients that don't know the thread // couldn't render the notification anyway. Live WS delivery still applies. import ( "encoding/json" "net/http" ) // getSpaceThread returns the instance's space thread — {id, open_key} — or an // empty object when no one has created it yet. Member-token-gated like every // data endpoint; the open_key blob is only openable by instance-key holders. // // Agents get the empty object unless EXPLICITLY made members: a sidecar holds // the instance key (member-app blobs travel under it), so handing it open_key // would let it unwrap the space key it was deliberately excluded from — the // message gate (threadMember) already blocks its reads, but the key blob // shouldn't leave the building either (defence in depth, docs/space-apps.md). func (s *Server) getSpaceThread(w http.ResponseWriter, r *http.Request) { token := r.URL.Query().Get("token") if !s.tokenOK(token) { httpError(w, http.StatusForbidden, "not a member") return } id, openKey, ok, err := s.db.spaceThread() if err != nil { httpError(w, http.StatusInternalServerError, "db error") return } uid, _ := s.db.deviceTokenUser(token) if ok && s.db.isAgent(uid) && !s.db.threadMember(id, uid) { ok = false } if !ok { writeJSON(w, http.StatusOK, map[string]any{}) return } writeJSON(w, http.StatusOK, map[string]any{"id": id, "open_key": openKey}) } // resetSpaceThreadHandler is the scoped admin lever for a wedged space // thread — chiefly a poisoned open_key (any member can create the thread and // the stored blob is never overwritten, so a garbage blob would otherwise // wedge space apps until the full instance-key break-glass, which also costs // every member their sealed name/photo). Deletes ONLY the space thread and // its rows; the next space-wide install mints a fresh one. Destructive for // space-app data by design — admin-gated like the instance-key reset. func (s *Server) resetSpaceThreadHandler(w http.ResponseWriter, r *http.Request) { if !s.requireAdmin(w, r) { return } if err := s.db.resetSpaceThread(); err != nil { httpError(w, http.StatusInternalServerError, "db error") return } writeJSON(w, http.StatusOK, map[string]any{"ok": true}) } // postSpaceThread creates the space thread on first use: the caller's client // mints a fresh AES key and sends it wrapped under the instance key (opaque to // the server), exactly like opening a community group. Any member may create // it — the first space-wide install does — and creation is idempotent: a // racing second create gets the winner's row back, its own open_key discarded // (the stored blob is never overwritten, the grantInstanceKey anti-brick rule). func (s *Server) postSpaceThread(w http.ResponseWriter, r *http.Request) { var body struct { Token string `json:"token"` OpenKey string `json:"open_key"` } if json.NewDecoder(r.Body).Decode(&body) != nil { httpError(w, http.StatusBadRequest, "bad request") return } if !s.tokenOK(body.Token) { httpError(w, http.StatusForbidden, "not a member") return } uid, ok := s.db.deviceTokenUser(body.Token) if !ok { httpError(w, http.StatusForbidden, "no user for token") return } // Agents can't mint the space thread either (mirror of getSpaceThread's // gate): the creator wraps — and therefore knows — the space key, which is // exactly what a sidecar must not hold without a deliberate opt-in. if s.db.isAgent(uid) { httpError(w, http.StatusForbidden, "bots don't create the space thread") return } if body.OpenKey == "" || len(body.OpenKey) > 4096 { httpError(w, http.StatusBadRequest, "bad open key") return } id, openKey, created, err := s.db.createSpaceThread(body.OpenKey) if err != nil { httpError(w, http.StatusInternalServerError, "db error") return } if created { // Content-free prod (like apps_changed): online clients fetch + unwrap // the new thread now, so the first space install reaches everyone live. out, _ := json.Marshal(map[string]any{"type": "space_thread"}) s.hub.broadcast <- outbound{data: out} // members:nil → everyone } writeJSON(w, http.StatusOK, map[string]any{"id": id, "open_key": openKey, "created": created}) }