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 | ;; ported-from: src/canon.ts @ v1.2.0
;;
;; Canonical JSON + hashing for signed records. Sorted keys, no whitespace,
;; rejects undefined/functions/cycles by construction (JSON-safe values only),
;; so every device serializes the same object to the same bytes.
;;
;; This whole namespace lives BELOW the JS boundary and stays there. `canon` is
;; a re-implementation of JSON.stringify's type dispatch with one deliberate
;; difference (undefined throws instead of vanishing), so its subject is
;; JavaScript values, not Clojure ones, and every corner of that dispatch is
;; pinned by a golden vector. Reaching for Clojure collections here would
;; replace the thing being specified with a translation of it.
;;
;; Byte-compat quirks the golden vectors pin (all inherited from
;; JSON.stringify semantics — this port leans on the SAME primitive):
;; NaN/Infinity -> "null"; -0 -> "0"; 2^53+1 -> "9007199254740992";
;; 1e21 -> "1e+21"; undefined-valued keys are filtered from objects but an
;; undefined ARRAY element throws; functions/symbols/bigints throw; key order
;; is Array.prototype.sort() default = UTF-16 code-unit order; lone surrogates
;; escape as \udXXX; U+2028/2029 and DEL emit raw; a Date is "{}"; a
;; Uint8Array serializes its numeric enumerable keys.
(ns ardegazu.social.canon
(:require [ardegazu.id.crypto :as id-crypto])
(:require-macros [ardegazu.social.macros :refer [awaits obj]]))
(defn- js-type
"JavaScript's `typeof`. Named because it is the dispatch canon() specifies:
`typeof null` is \"object\", which is why null has to be taken first below,
and `typeof undefined` is \"undefined\", which is what falls through to the
throw."
[v]
(js* "typeof ~{}" v))
(defn- json-scalar?
"The three typeof results JSON.stringify emits verbatim. null is handled
separately — it is `=== null`, not a typeof."
[t]
(or (identical? t "number") (identical? t "boolean") (identical? t "string")))
(defn- stringify [v]
(let [t (js-type v)]
(cond
;; `v === null` — NOT nil?, which in ClojureScript is `== null` and would
;; swallow undefined into "null" instead of throwing on it
(or (identical? v nil) (json-scalar? t))
(js/JSON.stringify v)
;; Array.prototype.map/join, not a Clojure seq: map skips holes in a
;; sparse array (giving ",,"), a seq would materialize them as null. No
;; vector covers sparse arrays, which is exactly why the primitive stays.
(js/Array.isArray v)
(str "[" (.join (.map ^js v (fn [x] (stringify x))) ",") "]")
(identical? t "object")
(let [ks (-> (js/Object.keys v)
;; an undefined VALUE drops its key (JSON.stringify does the
;; same); an undefined array ELEMENT throws, above
(.filter (fn [k] (not (identical? (unchecked-get v k) js/undefined))))
;; default sort = UTF-16 code-unit order, which is the key
;; order every signature in this suite is taken over
(.sort))]
(str "{"
(.join (.map ks (fn [k]
(str (js/JSON.stringify k) ":" (stringify (unchecked-get v k)))))
",")
"}"))
;; undefined, function, symbol, bigint
:else
(throw (js/Error. (str "canon: unsupported value of type " t))))))
(defn canon [value]
(stringify value))
;; ---- hashing + derivation ----------------------------------------------------
;;
;; Each of these opens on `(js/Promise.resolve nil)` so that a synchronous
;; throw — no crypto.subtle in this context, a detached ArrayBuffer — arrives
;; as a rejection rather than blowing up the caller's expression. Every
;; parameter bag is built with STRING keys (macros/obj): a `#js {:name …}`
;; literal emits an unquoted property that :advanced is free to rename, while a
;; quoted one is off-limits to the renamer for the whole compilation.
(defn sha256 [data]
(awaits [_ (js/Promise.resolve nil)
digest (js/crypto.subtle.digest "SHA-256" data)]
(js/Uint8Array. digest)))
(defn sha256-b64url [s]
(awaits [h (sha256 (id-crypto/utf8 s))]
(id-crypto/to-b64url h)))
(defn hkdf-id
"HKDF-SHA256 -> base64url string id (the suite's standard derivation shape)."
[ikm salt info]
(awaits [_ (js/Promise.resolve nil)
k (js/crypto.subtle.importKey "raw" ikm "HKDF" false #js ["deriveBits"])
bits (js/crypto.subtle.deriveBits
(obj "name" "HKDF"
"hash" "SHA-256"
"salt" (id-crypto/utf8 salt)
"info" (id-crypto/utf8 info))
k 256)]
(id-crypto/to-b64url (js/Uint8Array. bits))))
(defn hkdf-aes-key
"HKDF-SHA256 -> AES-GCM key."
[ikm salt info]
(awaits [_ (js/Promise.resolve nil)
k (js/crypto.subtle.importKey "raw" ikm "HKDF" false #js ["deriveKey"])]
(js/crypto.subtle.deriveKey
(obj "name" "HKDF"
"hash" "SHA-256"
"salt" (id-crypto/utf8 salt)
"info" (id-crypto/utf8 info))
k
(obj "name" "AES-GCM" "length" 256)
false
#js ["encrypt" "decrypt"])))
|