social-kit / src / ardegazu / social / friends.cljs
  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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
;; ported-from: src/friends.ts @ v1.2.0
;;
;; Friends: from TOFU names to a real mutual list.
;;
;; A friendship starts from a capability link (fragment-only, never hits a
;; server): https://ardegazu.ro/#add=<idPub>.<xPub>.<xSig>&n=<name>
;; The requester seals a `freq` envelope into the target's identity inbox;
;; accepting seals `facc` back. Both now hold the other's certified X key, so
;; the pair channel exists with no further exchange.
;;
;; The list lives in localStorage, folds across devices with the tombstoned
;; merge the suite's room lists use, and is mirrored into the identity
;; bridge's `soc` blob so every app can read it without joining the self
;; channel. Petnames are yours; a friend's self-claimed name is a hint.
;;
;; Records are JS objects, deliberately. FriendStore's list/get/friends/blocked
;; all hand them to app code and to a hand-written .d.ts, and this dist has no
;; ClojureScript collection runtime in it at all — see
;; test/module-budget.test.mjs for what the first one costs. So the shape is
;; declared in one place (the comment on `sanitize-friend`) and every read goes
;; through `oget`, rather than being a Clojure map that would have to be
;; marshalled back at every exit anyway.
(ns ardegazu.social.friends
  (:require [ardegazu.id.profile :as id-profile]
            [ardegazu.id.xkey :as id-xkey]
            [ardegazu.social.consts :as consts]
            [shadow.cljs.modern :refer (defclass)])
  (:require-macros [ardegazu.social.macros :refer [awaits obj oget truthy?]]))

(def ^:private pub-re #"^[A-Za-z0-9_-]{43}$")
(def ^:private sig-re #"^[A-Za-z0-9_-]{20,120}$")
(def ^:private MAX-FRIENDS 500)
(def ^:private SKEW-MS 120000)
(def ^:private NOTE-MAX 200)
(def ^:private APP-MAX 64)

;; ---- validation --------------------------------------------------------------

(defn- clamp-ts
  "A timestamp we did not generate: never negative, never further into the
  future than clock skew, and `now` when it is not a number at all."
  [ts]
  (let [now (js/Date.now)]
    (if (or (not (number? ts)) (not (js/Number.isFinite ts)))
      now
      (js/Math.min (js/Math.max ts 0) (+ now SKEW-MS)))))

(defn- opt-ts
  "A timestamp that is allowed to be absent; 0 means never."
  [ts]
  (if (and (number? ts) (js/Number.isFinite ts)) (clamp-ts ts) 0))

(defn- clean-label
  "A display name from an untrusted source, through the suite's one profile
  clamp (trim, first 32 CODE POINTS)."
  [s]
  (oget (id-profile/clamp-profile (obj "name" s)) "name"))

(defn- b64url-key? [s] (and (string? s) (.test pub-re s)))
(defn- cert? [s] (and (string? s) (.test sig-re s)))

(defn- friend-state?
  "The three states a record can be in. \"out\" is a request we sent, \"in\" one
  we received, \"friend\" a settled friendship — and there is no fourth."
  [s]
  (or (identical? s "friend") (identical? s "out") (identical? s "in")))

(defn sanitize-friend
  "Validate one untrusted friend record into a fresh object, or null.

  The record shape, in storage/blob key order:
    pub x xs pet name state addedTs petTs lastSeenTs lastApp [note]
  `note` is present only when non-empty — absence is the signal, so it is set
  after the fact rather than carried as an explicit null."
  [e]
  (if (or (nil? e) (not (identical? (js* "typeof ~{}" e) "object")))
    nil
    (let [pub (oget e "pub")
          x (oget e "x")
          xs (oget e "xs")
          state (oget e "state")]
      (if-not (and (b64url-key? pub) (b64url-key? x) (cert? xs) (friend-state? state))
        nil
        (let [note (oget e "note")
              last-app (oget e "lastApp")
              out (obj "pub" pub
                       "x" x
                       "xs" xs
                       "pet" (clean-label (oget e "pet"))
                       "name" (clean-label (oget e "name"))
                       "state" state
                       "addedTs" (clamp-ts (oget e "addedTs"))
                       "petTs" (opt-ts (oget e "petTs"))
                       "lastSeenTs" (opt-ts (oget e "lastSeenTs"))
                       "lastApp" (if (string? last-app) (.slice last-app 0 APP-MAX) ""))]
          (when (and (string? note) (not (identical? note "")))
            (unchecked-set out "note" (.slice note 0 NOTE-MAX)))
          out)))))

;; ---- storage -----------------------------------------------------------------

(defn- read-list [store-key]
  (try
    (let [raw (js/JSON.parse (or (js/localStorage.getItem store-key) "[]"))]
      (if (js/Array.isArray raw)
        ;; null-prototype hygiene: rebuild every record fresh
        (-> ^js raw
            (.map (fn [f] (sanitize-friend f)))
            (.filter (fn [f] (some? f))))
        #js []))
    (catch :default _ #js []))) ; fresh list

(defn- read-blocked [store-key]
  (try
    (let [raw (js/JSON.parse (or (js/localStorage.getItem store-key) "[]"))]
      (if (js/Array.isArray raw)
        (-> ^js raw
            (.filter (fn [g] (b64url-key? (when (some? g) (oget g "pub")))))
            (.map (fn [g] (obj "pub" (oget g "pub") "ts" (clamp-ts (oget g "ts"))))))
        #js []))
    (catch :default _ #js []))) ; none

(defn- find-by-pub [arr pub]
  (let [f (.find ^js arr (fn [x] (identical? (oget x "pub") pub)))]
    (if (identical? f js/undefined) nil f)))

(defn- index-by-pub
  "pub -> record. The fold below needs membership and deletion, which is what a
  Map is for; it never becomes a Clojure map (see this file's header)."
  [arr]
  (let [m (js/Map.)
        n (.-length ^js arr)]
    (loop [i 0]
      (if (>= i n)
        m
        (let [e (aget arr i)]
          (.set m (oget e "pub") e)
          (recur (inc i)))))))

(defclass FriendStore
  (constructor [this ns]
    (unchecked-set this "_friendsKey" (str ns ":soc:friends"))
    (unchecked-set this "_blockedKey" (str ns ":soc:blocked"))
    ;; Fires after every mutation (UI re-render + bridge/self-channel push).
    (unchecked-set this "onChange" (fn [] js/undefined))))

(defn- persist
  "Write both lists back, newest first and capped, then fire onChange. A
  private-mode throw loses the write but must not lose the notification — the
  UI is still correct for this session."
  [self friends blocked]
  (try
    (js/localStorage.setItem
     (oget self "_friendsKey")
     (js/JSON.stringify (-> ^js friends
                            (.sort (fn [a b] (- (oget b "addedTs") (oget a "addedTs"))))
                            (.slice 0 MAX-FRIENDS))))
    (when (some? blocked)
      (js/localStorage.setItem
       (oget self "_blockedKey")
       (js/JSON.stringify (-> ^js blocked
                              (.sort (fn [a b] (- (oget b "ts") (oget a "ts"))))
                              (.slice 0 consts/BLOCKED-CAP)))))
    (catch :default _ nil)) ; private mode
  ((oget self "onChange"))
  js/undefined)

;; ---- the cross-device fold ---------------------------------------------------
;;
;; One shared rule, used by both the envelope path (`upsert`) and the blob path
;; (`store-merge`): a friendship is settled the moment the two sides stop
;; disagreeing about whether it exists.

(defn- upgrades-to-friend?
  "`local` is not yet a friendship and `incoming` settles it. An explicit
  \"friend\" does — an accept, or another device that already accepted. So does
  a DISAGREEMENT: \"out\" meeting \"in\" is both sides having asked, which is a
  friendship by definition. Agreeing on a non-friend state changes nothing."
  [local-state incoming-state]
  (and (not (identical? local-state "friend"))
       (or (identical? incoming-state "friend")
           (not (identical? incoming-state local-state)))))

(defn- absorb-friend!
  "Fold a validated remote record into the local one, in place.

  Every predicate is taken BEFORE any write, so no rule can read a field an
  earlier rule just changed. Returns whether the record changed in a way worth
  REPORTING: petname, state and self-claimed name count, while lastSeen/lastApp
  and addedTs do not — presence is a hint that arrives with every beacon, and
  counting it would make each one look like a real change and re-arm a
  self-sync round."
  [local re]
  (let [newer-pet? (> (oget re "petTs") (oget local "petTs"))
        upgrade? (upgrades-to-friend? (oget local "state") (oget re "state"))
        newer-seen? (> (oget re "lastSeenTs") (oget local "lastSeenTs"))
        newer-name? (and (truthy? (oget re "name"))
                         (not (identical? (oget re "name") (oget local "name"))))]
    (when newer-pet?
      (unchecked-set local "pet" (oget re "pet"))
      (unchecked-set local "petTs" (oget re "petTs")))
    (when upgrade?
      (unchecked-set local "state" "friend"))
    (when newer-seen?
      (unchecked-set local "lastSeenTs" (oget re "lastSeenTs"))
      (unchecked-set local "lastApp" (oget re "lastApp")))
    (when newer-name?
      (unchecked-set local "name" (oget re "name")))
    ;; addedTs only ever advances — it is what a tombstone races
    (unchecked-set local "addedTs"
                   (js/Math.max (oget local "addedTs") (oget re "addedTs")))
    (or newer-pet? upgrade? newer-name?)))

(defn- fold-friends!
  "Union the remote records into `by-pub`. A tombstone at least as new as a
  record kills it; a record newer than the tombstone wins and clears it.
  Returns how many records changed."
  [by-pub gone-by remote-friends]
  (let [n (.-length ^js remote-friends)]
    (loop [i 0 changed 0]
      (if (>= i n)
        changed
        (let [re (sanitize-friend (aget remote-friends i))
              pub (when (some? re) (oget re "pub"))
              tomb (when (some? re) (.get gone-by pub))]
          (cond
            (nil? re)
            (recur (inc i) changed)

            (and (some? tomb) (>= (oget tomb "ts") (oget re "addedTs")))
            (recur (inc i) changed)

            :else
            (do
              (when (some? tomb) (.delete gone-by pub))
              (let [local (.get by-pub pub)]
                (if (identical? local js/undefined)
                  (do (.set by-pub pub re)
                      (recur (inc i) (inc changed)))
                  (recur (inc i) (if (absorb-friend! local re) (inc changed) changed)))))))))))

(defn- fold-blocked!
  "Apply the remote tombstones — the other half of the same race. A record
  newer than the tombstone survives and the tombstone is dropped on the floor.
  Returns how many records were removed."
  [by-pub gone-by remote-blocked]
  (let [n (.-length ^js remote-blocked)]
    (loop [i 0 changed 0]
      (if (>= i n)
        changed
        (let [raw (aget remote-blocked i)
              pub (when (some? raw) (oget raw "pub"))]
          (if-not (b64url-key? pub)
            (recur (inc i) changed)
            (let [ts (clamp-ts (oget raw "ts"))
                  local (.get by-pub pub)]
              (if (and (some? local) (<= ts (oget local "addedTs")))
                (recur (inc i) changed)
                (let [removed (if (some? local) (do (.delete by-pub pub) 1) 0)
                      prev (.get gone-by pub)]
                  (when (or (nil? prev) (> ts (oget prev "ts")))
                    (.set gone-by pub (obj "pub" pub "ts" ts)))
                  (recur (inc i) (+ changed removed)))))))))))

(defn- store-merge
  "Fold a remote blob (another device of OUR identity — trusted for content,
  strictly re-validated for shape). Rules mirror the suite's room merge:
  union by pub; petnames by newest petTs; states upgrade toward \"friend\";
  a block tombstone newer than a record's addedTs removes it, a newer
  record beats the tombstone. Returns how many records changed."
  [self remote]
  (if-not (and (some? remote)
               (identical? 1 (oget remote "v"))
               (js/Array.isArray (oget remote "friends")))
    0
    (let [by-pub (index-by-pub (read-list (oget self "_friendsKey")))
          gone-by (index-by-pub (read-blocked (oget self "_blockedKey")))
          blocked-raw (oget remote "blocked")
          ;; friends first, then tombstones: both halves of the race read the
          ;; same two maps, and the order they run in is the tie-break
          changed (+ (fold-friends! by-pub gone-by
                                    (.slice ^js (oget remote "friends") 0 MAX-FRIENDS))
                     (fold-blocked! by-pub gone-by
                                    (if (js/Array.isArray blocked-raw)
                                      (.slice ^js blocked-raw 0 consts/BLOCKED-CAP)
                                      #js [])))]
      (persist self
               (js/Array.from (.values by-pub))
               (js/Array.from (.values gone-by)))
      changed)))

;; ---- the JS façade -----------------------------------------------------------

(let [proto (.-prototype FriendStore)]
  (unchecked-set proto "list"
                 (fn [] (this-as self (read-list (oget self "_friendsKey")))))
  (unchecked-set proto "blocked"
                 (fn [] (this-as self (read-blocked (oget self "_blockedKey")))))
  (unchecked-set proto "get"
                 (fn [pub]
                   (this-as self (find-by-pub (.list ^js self) pub))))
  (unchecked-set proto "friends"
                 (fn []
                   (this-as self
                     (.filter ^js (.list ^js self)
                              (fn [f] (identical? (oget f "state") "friend"))))))
  (unchecked-set proto "isBlocked"
                 (fn [pub]
                   (this-as self
                     (.some ^js (.blocked ^js self)
                            (fn [b] (identical? (oget b "pub") pub))))))
  ;; Insert or update; existing state only upgrades (in/out -> friend).
  (unchecked-set proto "upsert"
                 (fn [f]
                   (this-as self
                     (let [all (.list ^js self)
                           cur (find-by-pub all (oget f "pub"))]
                       (if (nil? cur)
                         (.push ^js all f)
                         (do
                           ;; the certified X key is always the freshest one
                           (unchecked-set cur "x" (oget f "x"))
                           (unchecked-set cur "xs" (oget f "xs"))
                           (when (truthy? (oget f "name"))
                             (unchecked-set cur "name" (oget f "name")))
                           (when (truthy? (oget f "note"))
                             (unchecked-set cur "note" (oget f "note")))
                           (when (upgrades-to-friend? (oget cur "state") (oget f "state"))
                             (unchecked-set cur "state" "friend"))
                           (unchecked-set cur "addedTs"
                                          (js/Math.max (oget cur "addedTs")
                                                       (oget f "addedTs")))))
                       (persist self all js/undefined)))))
  (unchecked-set proto "setPet"
                 (fn [pub pet]
                   (this-as self
                     (let [all (.list ^js self)
                           f (find-by-pub all pub)]
                       (when (some? f)
                         (unchecked-set f "pet" (clean-label pet))
                         (unchecked-set f "petTs" (js/Date.now))
                         (persist self all js/undefined))))))
  (unchecked-set proto "seen"
                 (fn [pub app]
                   (this-as self
                     (let [all (.list ^js self)
                           f (find-by-pub all pub)]
                       (when (some? f)
                         (unchecked-set f "lastSeenTs" (js/Date.now))
                         (unchecked-set f "lastApp" (.slice ^js app 0 APP-MAX))
                         (persist self all js/undefined))))))
  (unchecked-set proto "markFriend"
                 (fn [pub]
                   (this-as self
                     (let [all (.list ^js self)
                           f (find-by-pub all pub)]
                       (when (some? f)
                         (unchecked-set f "state" "friend")
                         (persist self all js/undefined))))))
  ;; Remove + tombstone: envelopes from this pub are dropped from now on.
  (unchecked-set proto "block"
                 (fn [pub]
                   (this-as self
                     (let [friends (.filter ^js (.list ^js self)
                                            (fn [f] (not (identical? (oget f "pub") pub))))
                           blocked (.filter ^js (.blocked ^js self)
                                            (fn [b] (not (identical? (oget b "pub") pub))))]
                       (.push ^js blocked (obj "pub" pub "ts" (js/Date.now)))
                       (persist self friends blocked)))))
  ;; Just forget (no tombstone): a later request shows up again.
  (unchecked-set proto "forget"
                 (fn [pub]
                   (this-as self
                     (persist self
                              (.filter ^js (.list ^js self)
                                       (fn [f] (not (identical? (oget f "pub") pub))))
                              js/undefined))))
  ;; Display name: petname beats their claim beats a fingerprint stub.
  (unchecked-set proto "labelOf"
                 (fn [f]
                   (let [pet (oget f "pet")
                         claimed (oget f "name")]
                     (cond
                       (truthy? pet) pet
                       (truthy? claimed) claimed
                       :else (.slice ^js (oget f "pub") 0 8)))))
  (unchecked-set proto "socBlob"
                 (fn []
                   (this-as self
                     (obj "v" 1
                          "friends" (.list ^js self)
                          "blocked" (.blocked ^js self)
                          "ts" (js/Date.now)))))
  (unchecked-set proto "merge"
                 (fn [remote]
                   (this-as self (store-merge self remote)))))

;; ---- friend links ------------------------------------------------------------

(defn build-friend-link [base me]
  (let [nm (oget me "name")
        frag (str "add=" (oget me "pub") "." (oget me "x") "." (oget me "xs")
                  (if (truthy? nm)
                    (str "&n=" (js/encodeURIComponent nm))
                    ""))]
    (str base "#" frag)))

(def ^:private link-re
  #"^add=([A-Za-z0-9_-]{43})\.([A-Za-z0-9_-]{43})\.([A-Za-z0-9_-]{20,120})(?:&n=([^&]*))?$")

(defn parse-friend-link
  "Parse + verify a friend link fragment; null = malformed or forged cert."
  [fragment]
  (awaits [_ (js/Promise.resolve nil)]
    (let [m (.match ^js (.replace ^js fragment #"^#" "") link-re)]
      (if (nil? m)
        nil
        (let [pub (aget m 1)
              x (aget m 2)
              xs (aget m 3)
              n (aget m 4)]
          (awaits [ok (id-xkey/verify-x-cert id-xkey/SUITE-SALT pub x xs)]
            (if-not ok
              nil
              (let [nm (try
                         (clean-label (js/decodeURIComponent (if (nil? n) "" n)))
                         (catch :default _ ""))] ; bad escape — no name
                (obj "pub" pub "x" x "xs" xs "name" nm)))))))))

;; ---- envelope handling (transport-agnostic) ----------------------------------

(defn- notify!
  "Fire one of the caller's optional callbacks."
  [ev k arg]
  (when-let [cb (oget ev k)]
    (cb arg)))

(defn- apply-freq
  "A friend request. Already friends is noise; a request meeting our own
  outstanding one is a crossed pair and settles the friendship immediately."
  [store ev from-pub base body]
  (let [existing (.get ^js store from-pub)
        existing-state (when (some? existing) (oget existing "state"))
        msg (oget body "msg")]
    (cond
      (identical? existing-state "friend")
      false

      (identical? existing-state "out")
      (do (.markFriend ^js store from-pub)
          (notify! ev "accepted" (.get ^js store from-pub))
          true)

      :else
      (do (when (and (string? msg) (not (identical? msg "")))
            (unchecked-set base "note" (.slice msg 0 NOTE-MAX)))
          (.upsert ^js store base)
          (notify! ev "request" (.get ^js store from-pub))
          true))))

(defn- apply-facc
  "An accept. Only meaningful for someone we already have a record for and are
  not already friends with."
  [store ev from-pub]
  (let [existing (.get ^js store from-pub)]
    (if (or (nil? existing) (identical? (oget existing "state") "friend"))
      false
      (do (.markFriend ^js store from-pub)
          (notify! ev "accepted" (.get ^js store from-pub))
          true))))

(defn- apply-fsync
  "A friend-list blob from another of our own devices. Inbox room ids are
  publicly derivable, so a stranger can seal a perfectly valid fsync signed
  with their own key — it is held to its sender, never folded."
  [store ev from-pub body self-pub]
  (if (and (not (identical? self-pub js/undefined))
           (not (identical? from-pub self-pub)))
    false
    (let [changed (.merge ^js store (oget body "soc"))]
      (when (pos? changed)
        (notify! ev "synced" changed))
      (pos? changed))))

(defn apply-friend-envelope
  "Fold one verified envelope into the store. The envelope is already
  authenticity-checked (openEnvelope); this applies social semantics.
  Pass `selfPub` (my identity pub) so fsync is held to its sender — the
  agent always does. Returns true when it changed anything."
  [store env ev self-pub]
  (let [ev (if (identical? ev js/undefined) (js-obj) ev)
        from (oget env "from")
        from-pub (oget from "pub")]
    (if (true? (.isBlocked ^js store from-pub))
      false
      (let [t (oget env "t")
            body (oget env "body")
            ;; the record a first-contact envelope would create: "in", because
            ;; they reached us, and never anything the sender chose
            base (obj "pub" from-pub
                      "x" (oget from "x")
                      "xs" (oget from "xs")
                      "pet" ""
                      "name" (oget from "name")
                      "state" "in"
                      "addedTs" (clamp-ts (oget env "ts"))
                      "petTs" 0
                      "lastSeenTs" 0
                      "lastApp" "")]
        (cond
          (identical? t "freq") (apply-freq store ev from-pub base body)
          (identical? t "facc") (apply-facc store ev from-pub)
          (identical? t "fsync") (apply-fsync store ev from-pub body self-pub)
          :else false)))))

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/social-kit.git