@dotrino/identity 0.136.2 → 0.136.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -38,12 +38,14 @@ function subtle () {
38
38
  return s
39
39
  }
40
40
 
41
+ /** @param {Uint8Array} bytes @returns {string} */
41
42
  export function b64u (bytes) {
42
43
  let s = ''
43
44
  for (const b of bytes) s += String.fromCharCode(b)
44
45
  return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
45
46
  }
46
47
 
48
+ /** @param {string} str @returns {Uint8Array<ArrayBuffer>} */
47
49
  export function unb64u (str) {
48
50
  const s = String(str).replace(/-/g, '+').replace(/_/g, '/')
49
51
  const bin = atob(s + '='.repeat((4 - s.length % 4) % 4))
@@ -52,15 +54,21 @@ export function unb64u (str) {
52
54
  return out
53
55
  }
54
56
 
57
+ /** @returns {string} */
55
58
  export function randomBid () {
56
59
  return b64u(globalThis.crypto.getRandomValues(new Uint8Array(BID_BYTES)))
57
60
  }
58
61
 
59
62
  // ---------- características de solo lectura ----------
60
63
 
64
+ /** @param {string} bid @returns {Uint8Array} */
61
65
  export function encodeHello (bid) { return enc.encode(JSON.stringify({ v: 1, bid })) }
62
66
 
63
- /** El `bid` de un `hello` leído, o null si no es de esta versión. */
67
+ /**
68
+ * El `bid` de un `hello` leído, o null si no es de esta versión.
69
+ * @param {Uint8Array} bytes
70
+ * @returns {string | null}
71
+ */
64
72
  export function decodeHello (bytes) {
65
73
  try {
66
74
  const o = JSON.parse(dec.decode(bytes))
@@ -68,6 +76,7 @@ export function decodeHello (bytes) {
68
76
  } catch (_) { return null }
69
77
  }
70
78
 
79
+ /** @param {string} kind @param {string} data @returns {Uint8Array} */
71
80
  export function encodeBeacon (kind, data) {
72
81
  if (typeof kind !== 'string' || !kind || typeof data !== 'string') {
73
82
  throw Object.assign(new Error('bluetooth: announce needs a kind and a string'), { code: 'bad-beacon' })
@@ -79,7 +88,11 @@ export function encodeBeacon (kind, data) {
79
88
  return bytes
80
89
  }
81
90
 
82
- /** `{kind, data}` de un `beacon` leído, o null si está vacío o no se entiende. */
91
+ /**
92
+ * `{kind, data}` de un `beacon` leído, o null si está vacío o no se entiende.
93
+ * @param {Uint8Array | null | undefined} bytes
94
+ * @returns {{ kind: string, data: string } | null}
95
+ */
83
96
  export function decodeBeacon (bytes) {
84
97
  if (!bytes || !bytes.length) return null
85
98
  try {
@@ -93,7 +106,11 @@ export const KIND_CONTACT = 'contact'
93
106
  export const CONTACT_NICK_MAX = 40
94
107
  export const CONTACT_NICK_MAX_BYTES = 60
95
108
 
96
- /** El apodo recortado a 40 unidades UTF-16 y 60 bytes UTF-8, por puntos de código enteros: así cabe en el beacon. */
109
+ /**
110
+ * El apodo recortado a 40 unidades UTF-16 y 60 bytes UTF-8, por puntos de código enteros: así cabe en el beacon.
111
+ * @param {unknown} nickname
112
+ * @returns {string}
113
+ */
97
114
  export function trimNick (nickname) {
98
115
  let out = ''
99
116
  let bytes = 0
@@ -111,6 +128,9 @@ export function trimNick (nickname) {
111
128
  * `#to=` del messenger, `to=<publickey en base64url>&nick=<apodo>`. La `publickey` es la cadena
112
129
  * JWK tal cual la escribe la identidad. El apodo va recortado con `trimNick` y codificado como
113
130
  * `encodeURIComponent` (lo que no es `A-Za-z0-9-_.!~*'()` va en %XX de sus bytes UTF-8).
131
+ *
132
+ * @param {{ publickey: string, nickname?: string }} card
133
+ * @returns {string}
114
134
  */
115
135
  export function encodeContact ({ publickey, nickname = '' }) {
116
136
  if (typeof publickey !== 'string' || !publickey) {
@@ -120,9 +140,14 @@ export function encodeContact ({ publickey, nickname = '' }) {
120
140
  return 'to=' + b64u(enc.encode(publickey)) + (nick ? '&nick=' + encodeURIComponent(nick) : '')
121
141
  }
122
142
 
123
- /** `{ publickey, nickname }` de una tarjeta anunciada, o null si no se entiende. */
143
+ /**
144
+ * `{ publickey, nickname }` de una tarjeta anunciada, o null si no se entiende.
145
+ * @param {unknown} data
146
+ * @returns {{ publickey: string, nickname: string } | null}
147
+ */
124
148
  export function decodeContact (data) {
125
149
  if (typeof data !== 'string') return null
150
+ /** @param {string} k */
126
151
  const param = (k) => { const m = data.match(new RegExp('(?:^|&)' + k + '=([^&]*)')); return m ? m[1] : null }
127
152
  try {
128
153
  const to = param('to')
@@ -137,13 +162,21 @@ export function decodeContact (data) {
137
162
 
138
163
  // ---------- llave del canal ----------
139
164
 
165
+ /** @returns {Promise<{ privateKey: CryptoKey, epub: string }>} */
140
166
  export async function makeEphemeral () {
141
167
  const kp = await subtle().generateKey({ name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits'])
142
168
  const raw = new Uint8Array(await subtle().exportKey('raw', kp.publicKey))
143
169
  return { privateKey: kp.privateKey, epub: b64u(raw) }
144
170
  }
145
171
 
146
- /** La llave AES del canal (docs/bluetooth.md §4). El orden de los tokens no depende de quién llama. */
172
+ /**
173
+ * La llave AES del canal (docs/bluetooth.md §4). El orden de los tokens no depende de quién llama.
174
+ * @param {CryptoKey} privateKey
175
+ * @param {string} theirEpub
176
+ * @param {string} tokenA
177
+ * @param {string} tokenB
178
+ * @returns {Promise<CryptoKey>}
179
+ */
147
180
  export async function deriveKey (privateKey, theirEpub, tokenA, tokenB) {
148
181
  const s = subtle()
149
182
  const pub = await s.importKey('raw', unb64u(theirEpub), { name: 'ECDH', namedCurve: 'P-256' }, false, [])
@@ -157,6 +190,7 @@ export async function deriveKey (privateKey, theirEpub, tokenA, tokenB) {
157
190
 
158
191
  // ---------- registros ----------
159
192
 
193
+ /** @param {number} dir @param {number | bigint} counter @returns {Uint8Array<ArrayBuffer>} */
160
194
  function nonce (dir, counter) {
161
195
  const n = new Uint8Array(12)
162
196
  n[0] = dir
@@ -164,6 +198,11 @@ function nonce (dir, counter) {
164
198
  return n
165
199
  }
166
200
 
201
+ /**
202
+ * @param {CryptoKey} key @param {number} dir @param {number | bigint} counter
203
+ * @param {number} type @param {Uint8Array} body
204
+ * @returns {Promise<Uint8Array>}
205
+ */
167
206
  export async function sealRecord (key, dir, counter, type, body) {
168
207
  const plain = new Uint8Array(1 + body.length)
169
208
  plain[0] = type
@@ -171,24 +210,39 @@ export async function sealRecord (key, dir, counter, type, body) {
171
210
  return new Uint8Array(await subtle().encrypt({ name: 'AES-GCM', iv: nonce(dir, counter) }, key, plain))
172
211
  }
173
212
 
174
- /** `{type, body}`, o lanza si no lo selló esa llave con ese contador. */
213
+ /**
214
+ * `{type, body}`, o lanza si no lo selló esa llave con ese contador.
215
+ * @param {CryptoKey} key @param {number} dir @param {number | bigint} counter
216
+ * @param {Uint8Array<ArrayBuffer>} record
217
+ * @returns {Promise<{ type: number, body: Uint8Array }>}
218
+ */
175
219
  export async function openRecord (key, dir, counter, record) {
176
220
  const plain = new Uint8Array(await subtle().decrypt({ name: 'AES-GCM', iv: nonce(dir, counter) }, key, record))
177
221
  if (!plain.length) throw new Error('bluetooth: empty record')
178
222
  return { type: plain[0], body: plain.subarray(1) }
179
223
  }
180
224
 
225
+ /** @param {string} str @returns {Uint8Array} */
181
226
  export function encodeText (str) { return enc.encode(str) }
227
+ /** @param {Uint8Array} bytes @returns {string} */
182
228
  export function decodeText (bytes) { return dec.decode(bytes) }
183
229
 
184
230
  // ---------- trozos ----------
185
231
 
186
232
  export const TAG_BYTES = 4
187
233
 
188
- /** La etiqueta de los trozos hacia un central: los 4 primeros bytes de su `bid` (docs §5). */
234
+ /**
235
+ * La etiqueta de los trozos hacia un central: los 4 primeros bytes de su `bid` (docs §5).
236
+ * @param {string} bid
237
+ * @returns {Uint8Array}
238
+ */
189
239
  export function tagOf (bid) { return unb64u(bid).subarray(0, TAG_BYTES) }
190
240
 
191
- /** True si el trozo de `tx` lleva esa etiqueta. */
241
+ /**
242
+ * True si el trozo de `tx` lleva esa etiqueta.
243
+ * @param {Uint8Array} chunk @param {Uint8Array} tag
244
+ * @returns {boolean}
245
+ */
192
246
  export function hasTag (chunk, tag) {
193
247
  if (chunk.length < 1 + TAG_BYTES) return false
194
248
  for (let i = 0; i < TAG_BYTES; i++) if (chunk[1 + i] !== tag[i]) return false
@@ -198,10 +252,14 @@ export function hasTag (chunk, tag) {
198
252
  /**
199
253
  * Parte un registro en trozos de `chunk` bytes de valor GATT, cabecera incluida. Con `tag`
200
254
  * (hacia un central, `tx`) la cabecera lleva la etiqueta detrás de las banderas.
255
+ *
256
+ * @param {Uint8Array} record @param {number} chunk @param {Uint8Array | null} [tag]
257
+ * @returns {Uint8Array[]}
201
258
  */
202
259
  export function toChunks (record, chunk, tag = null) {
203
260
  const head = 1 + (tag ? TAG_BYTES : 0)
204
261
  const room = Math.max(1, chunk - head)
262
+ /** @type {Uint8Array[]} */
205
263
  const out = []
206
264
  let i = 0
207
265
  do {
@@ -219,7 +277,14 @@ export function toChunks (record, chunk, tag = null) {
219
277
  /** Rearma registros de trozos que llegan en orden. `push` devuelve el registro entero, o null. */
220
278
  export class Reassembler {
221
279
  /** @param {number} [skip] bytes de cabecera tras las banderas (la etiqueta, en `tx`) */
222
- constructor (skip = 0) { this.skip = skip; this.parts = []; this.size = 0 }
280
+ constructor (skip = 0) {
281
+ this.skip = skip
282
+ /** @type {Uint8Array[]} */
283
+ this.parts = []
284
+ this.size = 0
285
+ }
286
+
287
+ /** @param {Uint8Array | null | undefined} chunk @returns {Uint8Array | null} */
223
288
  push (chunk) {
224
289
  if (!chunk || chunk.length < 1 + this.skip) return null
225
290
  const body = chunk.subarray(1 + this.skip)
@@ -1,6 +1,9 @@
1
1
  /**
2
2
  * Canonical JSON serialization (sorted keys recursively).
3
3
  * Necessary so that signatures match across implementations.
4
+ *
5
+ * @param {unknown} value
6
+ * @returns {string}
4
7
  */
5
8
  export function canonicalStringify (value) {
6
9
  if (value === null || typeof value !== 'object') {
@@ -9,7 +12,8 @@ export function canonicalStringify (value) {
9
12
  if (Array.isArray(value)) {
10
13
  return '[' + value.map(canonicalStringify).join(',') + ']'
11
14
  }
12
- const keys = Object.keys(value).sort()
13
- const parts = keys.map(k => JSON.stringify(k) + ':' + canonicalStringify(value[k]))
15
+ const obj = /** @type {Record<string, unknown>} */ (value)
16
+ const keys = Object.keys(obj).sort()
17
+ const parts = keys.map((k) => JSON.stringify(k) + ':' + canonicalStringify(obj[k]))
14
18
  return '{' + parts.join(',') + '}'
15
19
  }