1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335 | ;; Room boot: crypto → libp2p transport → app store → UI. This namespace is the
;; :room module's only entry (shadow-cljs.edn), loaded via shadow.lazy from
;; __NAME__.main once a room secret is known — so the lobby stays a small chunk
;; and the libp2p/OrbitDB stack only downloads when entering a room. That is the
;; TS build's `await import("./room")` boundary, kept real; scripts/build.mjs
;; gates it.
;;
;; This is the canonical stack order (lib/README.md "Recipe: a new app"):
;; secret → RoomCrypto → identity bridge → resolve-relay-config → Net →
;; open-helia → RoomLog (entry hook wired BEFORE replication) → MailboxSync →
;; store/UI. Keep the order; swap the store/UI for your app.
;;
;; TWO RULES THIS STACK HAS AND THE GAMES DO NOT:
;;
;; 1. NEVER AUTO-ADOPT ON IDENTITY CONFLICT. game1's id/boot.cljs calls
;; `adoptBridgeSeed` the moment the bridge reports a different suite seed,
;; because nothing in a game is bound to the old key. Here the replicated
;; log's authorship and every grant ARE bound to it, so a rooms app uses
;; IdBridge directly and deliberately does NOT vendor game1's id/boot. If
;; you surface the conflict to the user, make it an explicit two-tap choice
;; (chat's identity sheet is the worked example) — never silent.
;;
;; 2. onEntry IS WIRED BEFORE REPLICATION STARTS. RoomLog.open starts sync and
;; marks hashes as seen, so a handler attached afterwards loses those
;; entries permanently. The store needs the log to exist, so the callback is
;; installed at open() time and buffers into `pending` until the store is
;; constructed. Both callbacks go to rlog/open — never assigned after.
(ns __NAME__.room
(:require ["ardegazu-id-kit" :refer (IdBridge)]
[__NAME__.app.rooms :as rooms]
[__NAME__.app.store :as store]
[__NAME__.app.ui :as ui]
[__NAME__.config :as config]
[__NAME__.i18n :as i18n :refer (t tn)]
[ardegazu.rooms.js :as j]
[ardegazu.rooms.lib.crypto :as rc]
[ardegazu.rooms.lib.descriptor :as descriptor]
[ardegazu.rooms.lib.log :as rlog]
[__NAME__.lib.mailbox :as mbx]
[ardegazu.rooms.lib.net :as net]
[__NAME__.lib.selftest :as selftest]
[ardegazu.rooms.lib.turn :as turn]
[__NAME__.stores :as stores]
[shadow.cljs.modern :refer (js-await)]
[shadow.lazy :as lazy]))
(def ^:private social-loadable (lazy/loadable __NAME__.social/attach!))
(declare setup-mailbox finish-boot)
(def ^:private DEFAULTS
(let [o (j/ordered "relayMultiaddr" config/RELAY-MULTIADDR
"turnCredsUrl" config/TURN-CREDS-URL
"discoveryTopic" config/DISCOVERY-TOPIC)]
;; offline mailbox: production discovers it via the descriptor; the env pair
;; is the dev/self-host path (a dev ip4 multiaddr skips the descriptor fetch)
(when (and (some? config/MAILBOX-URL) (some? config/MAILBOX-CREDS-URL))
(unchecked-set o "mailbox" (j/ordered "baseUrl" config/MAILBOX-URL
"credsUrl" config/MAILBOX-CREDS-URL
"maxMessageKb" 64)))
o))
(defn boot-room [root secret force-relay]
(-> (js/Promise.resolve nil)
(.then
(fn [_]
;; dev-only crypto contract check (it lives here, not in main, because
;; lib/selftest reaches lib/access, which imports @orbitdb/core — that
;; must not land in the :main module and break the lobby/room split)
(when ^boolean goog.DEBUG (selftest/run-self-test))
(let [room-entry (rooms/touch-room secret)
cell (js-obj)] ; the `let ui!: RoomUI` / `let store!: NoteStore` cell
;; network id first: per-sender keys and AADs bind to the libp2p PeerId
(js-await [session (net/new-session-key)]
(js-await [room-crypto (rc/create secret config/APP-SALT (unchecked-get session "peerId"))]
;; persistent identity: one Ed25519 seed for the WHOLE suite,
;; picked up via the identity bridge (ardegazu.ro/id/) and
;; mirrored in this app's storage so offline boots never wait on
;; the iframe (id-kit bridge-client).
(let [bridge (IdBridge. (j/ordered "ns" config/NS "bridgeUrl" config/ID-BRIDGE-URL))]
(js-await [id-boot (.boot ^js bridge)]
;; a language picked anywhere in the suite follows you here —
;; before the UI renders
(let [profile (unchecked-get id-boot "profile")
_ (i18n/absorb-suite-lang (unchecked-get profile "lang"))
identity (unchecked-get id-boot "identity")]
(js-await [self-assertion
(if (j/truthy? identity)
(js-await [sig (.assert ^js identity config/APP-SALT
(unchecked-get room-crypto "roomId")
(unchecked-get room-crypto "peerId"))]
;; {pub, sig, hue, glyph} — four keys, and the
;; profile accents ride along to peers
(j/ordered "pub" (unchecked-get identity "publicKeyB64")
"sig" sig
"hue" (unchecked-get profile "hue")
"glyph" (unchecked-get profile "glyph")))
(js/Promise.resolve nil))]
(let [stored-name (volatile! (let [n (unchecked-get profile "name")]
(if (j/truthy? n) n nil)))]
(when-not (j/truthy? @stored-name)
(try
(vreset! stored-name (js/localStorage.getItem (config/ns-key "name")))
(catch :default _ nil))) ; Safari private mode
(let [store-of (fn [] (unchecked-get cell "store"))
ui-of (fn [] (unchecked-get cell "ui"))
my-name (fn []
(let [s (store-of)]
(cond
(j/truthy? s) (store/my-name s)
(j/truthy? @stored-name) @stored-name
:else "?")))]
(js-await [cfg (descriptor/resolve-relay-config DEFAULTS)]
(let [ice (turn/IceConfig. (unchecked-get cfg "turnCredsUrl") force-relay)]
(js-await
[net-obj
(net/create
(j/ordered
"privateKey" (unchecked-get session "privateKey")
"crypto" room-crypto
"ice" ice
"relayMultiaddr" (unchecked-get cfg "relayMultiaddr")
"discoveryTopic" (unchecked-get cfg "discoveryTopic")
"myName" my-name
"events"
(j/ordered
"peerState" (fn [peer state nm]
(when-some [u (ui-of)] (ui/set-peer u peer state nm))
js/undefined)
"peerGone" (fn [peer]
(when-some [u (ui-of)] (ui/remove-peer u peer))
js/undefined)
;; ephemeral (non-logged) traffic — the store
;; routes hello/name/roomsync; add your app's
;; live payloads there
"message" (fn [from payload]
(when-some [s (store-of)] (store/on-message s from payload))
js/undefined)
;; directed binary frames — unused by the demo
"binary" (fn [_from _data] js/undefined)
"peerReady" (fn [peer]
(when-some [s (store-of)] (store/on-channel-open s peer))
js/undefined)
"status" (fn [up]
(when-some [u (ui-of)] (ui/set-signaling u up))
js/undefined))))]
;; the replicated log: Helia over the same
;; libp2p node + OrbitDB events DB
(js-await [helia (stores/open-idb-helia (unchecked-get net-obj "libp2p")
(j/ordered "blocks" (config/ns-db "blocks")
"data" (config/ns-db "data")))]
(-> (js/Promise.resolve nil)
(.then (fn [_]
;; ask Safari & friends not to evict the blockstore
(let [st (unchecked-get js/navigator "storage")]
(when (and (j/truthy? st) (j/truthy? (.-persist ^js st)))
(.persist ^js st)))))
(.catch (fn [_] nil))
(.then
(fn [_]
(let [pending (array)
apply-entry
(fn [e]
(let [s (store-of)]
(if (j/truthy? s)
(do (store/apply-entry s e)
;; live backfill may unblock
;; deferred mailbox entries
(when-some [m (unchecked-get cell "mbx")]
(mbx/on-live-entry m)))
(.push pending e)))
js/undefined)]
;; onEntry MUST exist before sync starts (see the ns docs)
(js-await [log (rlog/open
helia room-crypto identity
(j/ordered
"onEntry" apply-entry
;; undecryptable garbage from
;; non-members — expected noise
"onError" (fn [_] js/undefined)))]
(let [st (store/NoteStore.
net-obj log (j/nn @stored-name "")
(j/ordered "appSalt" config/APP-SALT
"roomId" (unchecked-get room-crypto "roomId"))
self-assertion)]
(unchecked-set cell "store" st)
(js-await [_ (setup-mailbox cell cfg room-crypto log identity st)]
(do
;; flush the entries that arrived while the
;; store did not exist yet
(doseq [e (array-seq (.splice pending 0))] (apply-entry e))
(finish-boot cell root secret room-entry net-obj
log st bridge id-boot @stored-name))))))))))))))))))))))))))
;; ---- mailbox (chat's PROTOCOL.md §9) ---------------------------------------
(defn- setup-mailbox
"A second transport for the same sealed blocks, so history reaches members who
are never online together. Constructed only when the descriptor (or env)
advertises one."
[cell cfg room-crypto log identity st]
(let [mailbox (unchecked-get cfg "mailbox")]
(if-not (j/truthy? mailbox)
(js/Promise.resolve nil)
(js-await [mbx-room-id (rc/mailbox-room-id room-crypto)]
(js-await [cipher (rc/mbx-cipher room-crypto)]
(let [room-id (unchecked-get room-crypto "roomId")
k (fn [prefix] (config/ns-key (str prefix ":" room-id)))
sync (mbx/MailboxSync.
(j/ordered
"log" log
"client" (mbx/MailboxClient. (unchecked-get mailbox "baseUrl") mbx-room-id
(mbx/MailboxAuth. (unchecked-get mailbox "credsUrl")
mbx-room-id))
"cipher" cipher
"maxMessageKb" (unchecked-get mailbox "maxMessageKb")
"keys" (j/ordered "cursor" (k "mbx-cursor")
"queue" (k "mbx-queue")
"sent" (k "mbx-sent")
"retry" (k "mbx-retry")
"ident" (k "mbx-ident"))
"hasIdentity" (not (nil? identity))
"onDisplayOnly" (fn [e] (store/apply-entry st e) js/undefined)
;; lib/ stays i18n-free; the mailbox emits exactly one
;; notice (expired offline messages), so the app boundary
;; swaps in the translation
"onNotice" (fn [_]
(when-some [u (unchecked-get cell "ui")]
(ui/toast u (str "⌛ " (t "toast.mailbox-expired"))))
js/undefined)
"onReplayed" (fn [n]
(when-some [u (unchecked-get cell "ui")]
(ui/toast u (tn "toast.offline-delivered" n)))
js/undefined)))]
(unchecked-set cell "mbx" sync)
(unchecked-set log "onAppended" (fn [h] (mbx/enqueue-entry sync h) js/undefined))
(unchecked-set log "onImageStored" (fn [c] (mbx/enqueue-image sync c) js/undefined))
;; every unixfs block must fit one mailbox frame (envelope ≈ 40
;; bytes) — only matters once your app calls put-image; harmless
;; until then
(unchecked-set log "imageChunkBytes"
(js/Math.min (* (- (unchecked-get mailbox "maxMessageKb") 1) 1024) 61440))
js/undefined))))))
;; ---- the rest of the boot --------------------------------------------------
(defn- finish-boot [cell root secret room-entry net-obj log st bridge id-boot stored-name]
(let [ui-obj (ui/UI.
root st
(j/ordered
"post" (fn [text] (store/post! st text))
"rename" (fn [nm]
(store/set-name st nm)
;; suite-wide: writes the local mirror (same
;; `<ns>:name` key) and pushes to the bridge so every
;; other app renames too
(.putProfile ^js bridge (j/ordered "name" nm))
(try (js/localStorage.setItem (config/ns-key "name") nm)
(catch :default _ nil))
js/undefined)
"inviteURL" (fn [] (str (.-origin js/location) (.-pathname js/location) "#" secret))
"roomLabel" (fn [] (unchecked-get room-entry "label"))
"goLobby" (fn []
(.replaceState js/history nil "" (.-pathname js/location))
(.reload js/location)
js/undefined)))]
(unchecked-set cell "ui" ui-obj)
(unchecked-set st "onChange" (fn [] (ui/render ui-obj) js/undefined))
(unchecked-set st "onPeerName" (fn [peer nm] (ui/set-peer-name ui-obj peer nm)))
(unchecked-set st "onIncoming" (fn [n] (ui/notify-incoming ui-obj n)))
;; same-identity device sync: directed only (never broadcast — every member
;; could decrypt a broadcast; the directed stream is pairwise-encrypted)
(unchecked-set st "onSelfDevice"
(fn [peer]
(let [payload (j/ordered "kind" "roomsync")
rs (rooms/build-room-sync)]
(unchecked-set payload "rooms" (unchecked-get rs "rooms"))
(unchecked-set payload "gone" (unchecked-get rs "gone"))
(.catch (js/Promise.resolve (net/send-to net-obj peer payload)) (fn [_] nil)))
js/undefined))
(unchecked-set st "onRoomSync"
(fn [_peer payload]
(let [n (rooms/merge-rooms payload secret)]
(when (pos? n) (ui/toast ui-obj (tn "toast.rooms-synced" n))))
js/undefined))
;; replay this device's copy of the log (works fully offline), then go live
(js-await [restored (rlog/load-tail log 500)]
(do
(store/mark-live st)
(when (pos? restored) (ui/toast ui-obj (tn "toast.restored" restored)))
;; mailbox catch-up: replay deposits from members who came and went while
;; we were offline, then flush our own queue (non-blocking; live traffic
;; never waits)
(when-some [m (unchecked-get cell "mbx")] (mbx/start m))
;; console/debug handle — grants nothing an open console doesn't already
;; have
(unchecked-set js/window "__app"
(j/ordered "net" net-obj "log" log "store" st
"mbx" (unchecked-get cell "mbx")))
;; returning users are not re-asked: a stored name joins silently
(let [trimmed (if (j/truthy? stored-name) (.trim ^string stored-name) "")
asked (not (j/truthy? trimmed))]
(js-await [nm (if (j/truthy? trimmed) (js/Promise.resolve trimmed) (ui/ask-name ui-obj nil))]
(do
(store/set-name st nm)
(try (js/localStorage.setItem (config/ns-key "name") nm) (catch :default _ nil))
;; a first-run name goes suite-wide too (the rename path already does)
(when (and asked (j/truthy? (unchecked-get id-boot "identity")))
(.putProfile ^js bridge (j/ordered "name" nm)))
;; the social side: presence to friends + live invite toasts, riding
;; this node's pubsub. Its own chunk; must never delay or break the
;; room.
(when (and (j/truthy? (unchecked-get id-boot "identity"))
(j/truthy? (unchecked-get id-boot "seed")))
(-> (lazy/load social-loadable)
(.then (fn [attach]
(attach (j/ordered "net" net-obj
"idBoot" id-boot
"bridge" bridge
"store" st
"ui" ui-obj
"secret" secret))))
(.catch (fn [_] nil))))
(.addEventListener js/window "beforeunload"
(fn []
(when-some [m (unchecked-get cell "mbx")] (mbx/stop m))
(rlog/close log)
(net/close net-obj)
js/undefined))
js/undefined)))))))
|