| 1 | package main |
| 2 | |
| 3 | // π€ The space thread: one hidden, all-members thread per instance, backing |
| 4 | // SPACE-WIDE mini-apps (docs/space-apps.md). It is the "meta-thread" answer to |
| 5 | // "install this app for everyone, everywhere": a `spaceapps` registry app and |
| 6 | // each space-installed app's events/state fold from THIS thread's encrypted |
| 7 | // log, so one shared instance is readable and writable from any chat. |
| 8 | // |
| 9 | // Everything reuses the existing per-thread machinery β messages, state |
| 10 | // snapshots, scheduling, WS fan-out β with exactly two twists: |
| 11 | // |
| 12 | // - The key rides open_key, the open-group mechanism: the thread's AES key |
| 13 | // encrypted under the INSTANCE key, which every member (including late |
| 14 | // joiners) can already unwrap with their own private key. No per-member |
| 15 | // wraps, no new distribution path, and the "instance key never encrypts |
| 16 | // messages" invariant holds β it only wraps the space thread's key. |
| 17 | // - Membership is IMPLICIT: every member of the space is a member of the |
| 18 | // space thread by construction (db.threadMember / db.memberUserIDs), so |
| 19 | // there are no rows to backfill and no join path that can drift. Agents |
| 20 | // are excluded, mirroring joinDefaultThreads β a bot reading the space |
| 21 | // log must be a deliberate, disclosed choice (an explicit membership row |
| 22 | // added later), never a silent default. |
| 23 | // |
| 24 | // The server stays exactly as blind as for any thread: it stores the row, the |
| 25 | // wrapped key blob, and opaque ciphertext. It never learns WHICH apps are |
| 26 | // installed (that's fold state inside the log) β only that a space thread |
| 27 | // exists. The thread never appears in GET /api/threads (threadsForUser joins |
| 28 | // on membership rows, of which it has none), so old clients β including the |
| 29 | // native apps until they learn the feature β never see it; new clients fetch |
| 30 | // it explicitly here. Push fan-out is skipped for it (see pushNewMessage): |
| 31 | // registry churn must not buzz phones, and clients that don't know the thread |
| 32 | // couldn't render the notification anyway. Live WS delivery still applies. |
| 33 | |
| 34 | import ( |
| 35 | "encoding/json" |
| 36 | "net/http" |
| 37 | ) |
| 38 | |
| 39 | // getSpaceThread returns the instance's space thread β {id, open_key} β or an |
| 40 | // empty object when no one has created it yet. Member-token-gated like every |
| 41 | // data endpoint; the open_key blob is only openable by instance-key holders. |
| 42 | // |
| 43 | // Agents get the empty object unless EXPLICITLY made members: a sidecar holds |
| 44 | // the instance key (member-app blobs travel under it), so handing it open_key |
| 45 | // would let it unwrap the space key it was deliberately excluded from β the |
| 46 | // message gate (threadMember) already blocks its reads, but the key blob |
| 47 | // shouldn't leave the building either (defence in depth, docs/space-apps.md). |
| 48 | func (s *Server) getSpaceThread(w http.ResponseWriter, r *http.Request) { |
| 49 | token := r.URL.Query().Get("token") |
| 50 | if !s.tokenOK(token) { |
| 51 | httpError(w, http.StatusForbidden, "not a member") |
| 52 | return |
| 53 | } |
| 54 | id, openKey, ok, err := s.db.spaceThread() |
| 55 | if err != nil { |
| 56 | httpError(w, http.StatusInternalServerError, "db error") |
| 57 | return |
| 58 | } |
| 59 | uid, _ := s.db.deviceTokenUser(token) |
| 60 | if ok && s.db.isAgent(uid) && !s.db.threadMember(id, uid) { |
| 61 | ok = false |
| 62 | } |
| 63 | if !ok { |
| 64 | writeJSON(w, http.StatusOK, map[string]any{}) |
| 65 | return |
| 66 | } |
| 67 | writeJSON(w, http.StatusOK, map[string]any{"id": id, "open_key": openKey}) |
| 68 | } |
| 69 | |
| 70 | // resetSpaceThreadHandler is the scoped admin lever for a wedged space |
| 71 | // thread β chiefly a poisoned open_key (any member can create the thread and |
| 72 | // the stored blob is never overwritten, so a garbage blob would otherwise |
| 73 | // wedge space apps until the full instance-key break-glass, which also costs |
| 74 | // every member their sealed name/photo). Deletes ONLY the space thread and |
| 75 | // its rows; the next space-wide install mints a fresh one. Destructive for |
| 76 | // space-app data by design β admin-gated like the instance-key reset. |
| 77 | func (s *Server) resetSpaceThreadHandler(w http.ResponseWriter, r *http.Request) { |
| 78 | if !s.requireAdmin(w, r) { |
| 79 | return |
| 80 | } |
| 81 | if err := s.db.resetSpaceThread(); err != nil { |
| 82 | httpError(w, http.StatusInternalServerError, "db error") |
| 83 | return |
| 84 | } |
| 85 | writeJSON(w, http.StatusOK, map[string]any{"ok": true}) |
| 86 | } |
| 87 | |
| 88 | // postSpaceThread creates the space thread on first use: the caller's client |
| 89 | // mints a fresh AES key and sends it wrapped under the instance key (opaque to |
| 90 | // the server), exactly like opening a community group. Any member may create |
| 91 | // it β the first space-wide install does β and creation is idempotent: a |
| 92 | // racing second create gets the winner's row back, its own open_key discarded |
| 93 | // (the stored blob is never overwritten, the grantInstanceKey anti-brick rule). |
| 94 | func (s *Server) postSpaceThread(w http.ResponseWriter, r *http.Request) { |
| 95 | var body struct { |
| 96 | Token string `json:"token"` |
| 97 | OpenKey string `json:"open_key"` |
| 98 | } |
| 99 | if json.NewDecoder(r.Body).Decode(&body) != nil { |
| 100 | httpError(w, http.StatusBadRequest, "bad request") |
| 101 | return |
| 102 | } |
| 103 | if !s.tokenOK(body.Token) { |
| 104 | httpError(w, http.StatusForbidden, "not a member") |
| 105 | return |
| 106 | } |
| 107 | uid, ok := s.db.deviceTokenUser(body.Token) |
| 108 | if !ok { |
| 109 | httpError(w, http.StatusForbidden, "no user for token") |
| 110 | return |
| 111 | } |
| 112 | // Agents can't mint the space thread either (mirror of getSpaceThread's |
| 113 | // gate): the creator wraps β and therefore knows β the space key, which is |
| 114 | // exactly what a sidecar must not hold without a deliberate opt-in. |
| 115 | if s.db.isAgent(uid) { |
| 116 | httpError(w, http.StatusForbidden, "bots don't create the space thread") |
| 117 | return |
| 118 | } |
| 119 | if body.OpenKey == "" || len(body.OpenKey) > 4096 { |
| 120 | httpError(w, http.StatusBadRequest, "bad open key") |
| 121 | return |
| 122 | } |
| 123 | id, openKey, created, err := s.db.createSpaceThread(body.OpenKey) |
| 124 | if err != nil { |
| 125 | httpError(w, http.StatusInternalServerError, "db error") |
| 126 | return |
| 127 | } |
| 128 | if created { |
| 129 | // Content-free prod (like apps_changed): online clients fetch + unwrap |
| 130 | // the new thread now, so the first space install reaches everyone live. |
| 131 | out, _ := json.Marshal(map[string]any{"type": "space_thread"}) |
| 132 | s.hub.broadcast <- outbound{data: out} // members:nil β everyone |
| 133 | } |
| 134 | writeJSON(w, http.StatusOK, map[string]any{"id": id, "open_key": openKey, "created": created}) |
| 135 | } |
| 136 | |