@dotrino/identity 0.136.2 → 0.137.0

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.
Files changed (31) hide show
  1. package/package.json +1 -1
  2. package/src/index.d.ts +23 -1
  3. package/types/core.d.ts +2 -1
  4. package/vault/core.js +6 -3
  5. package/vault/vendor/opaque/VERSION.txt +1 -1
  6. package/vault/vendor/opaque/src/index.js +90 -13
  7. package/vault/vendor/proxy-client/VERSION.txt +1 -1
  8. package/vault/vendor/proxy-client/binpack.js +38 -7
  9. package/vault/vendor/proxy-client/ble/manager.js +148 -36
  10. package/vault/vendor/proxy-client/ble/wire.js +74 -9
  11. package/vault/vendor/proxy-client/canonical.js +6 -2
  12. package/vault/vendor/proxy-client/client.js +439 -130
  13. package/vault/vendor/proxy-client/encpub.js +9 -1
  14. package/vault/vendor/proxy-client/index.js +4 -0
  15. package/vault/vendor/proxy-client/parts.js +22 -2
  16. package/vault/vendor/proxy-client/sealing.js +60 -9
  17. package/vault/vendor/proxy-client/signature.js +38 -1
  18. package/vault/vendor/proxy-client/stats-log.js +29 -9
  19. package/vault/vendor/proxy-client/stats.js +36 -8
  20. package/vault/vendor/proxy-client/webrtc.js +95 -16
  21. package/vault/vendor/roadmap/VERSION.txt +1 -1
  22. package/vault/vendor/roadmap/index.js +85 -9
  23. package/vault/vendor/roadmap/manifests.js +26 -25
  24. package/vault/vendor/vault/VERSION.txt +1 -1
  25. package/vault/vendor/vault/admin.js +4 -1
  26. package/vault/vendor/vault/core/approvals.js +6 -1
  27. package/vault/vendor/vault/core/libVersion.js +1 -1
  28. package/vault/vendor/vault/core/notices.js +30 -3
  29. package/vault/vendor/vault/core/secretsStore.js +4 -1
  30. package/vault/vendor/vault/core/vault.js +35 -4
  31. package/vault/vendor/vault/passwordLogins.js +4 -2
@@ -35,7 +35,11 @@ export const ENCPUB_V = 1
35
35
  /** Para quién vale este anuncio: un propósito, no un servidor. */
36
36
  export const ENCPUB_AUD = 'dotrino:encpub'
37
37
 
38
- /** Cuerpo canónico del anuncio. Lo que se firma, ni un campo más. */
38
+ /**
39
+ * Cuerpo canónico del anuncio. Lo que se firma, ni un campo más.
40
+ * @param {{ publickey: string, encPub: string, ts?: number }} args
41
+ * @returns {import('./index.js').EncPubStatement['data']}
42
+ */
39
43
  export function encPubBody ({ publickey, encPub, ts = Date.now() }) {
40
44
  return { v: ENCPUB_V, op: 'encpub', aud: ENCPUB_AUD, publickey, encpub: encPub, ts }
41
45
  }
@@ -44,6 +48,9 @@ export function encPubBody ({ publickey, encPub, ts = Date.now() }) {
44
48
  * ¿Es esto una llave de cifrado P-256 y no cualquier string? Se comprueba de verdad
45
49
  * —igual que hace el acta— porque una llave mal formada no falla al guardarla: falla
46
50
  * mucho después, al intentar sellarle algo a alguien.
51
+ *
52
+ * @param {unknown} v
53
+ * @returns {v is string}
47
54
  */
48
55
  export function isEncPub (v) {
49
56
  if (typeof v !== 'string' || !v) return false
@@ -108,4 +115,5 @@ export async function readEncPubStatement (statement, { publickey } = /** @type
108
115
  }
109
116
 
110
117
  /** Lo firmado, en texto canónico. Mismo orden en las dos puntas o las firmas no cuadran. */
118
+ /** @param {unknown} data @returns {string} */
111
119
  export const encPubSigningText = (data) => canonicalStringify(data)
@@ -18,10 +18,14 @@ export { encodeContact, decodeContact, KIND_PAIR, KIND_CONTACT } from './ble/wir
18
18
 
19
19
  import { WebSocketProxyClient } from './client.js'
20
20
 
21
+ /** @type {WebSocketProxyClient | null} */
21
22
  let _singleton = null
22
23
  /**
23
24
  * Singleton helper. Returns the same instance across calls.
24
25
  * Useful in apps that want a single global client.
26
+ *
27
+ * @param {import('./index.js').WebSocketProxyClientOptions} [options]
28
+ * @returns {WebSocketProxyClient}
25
29
  */
26
30
  export function getWebSocketProxyClient (options) {
27
31
  if (!_singleton) _singleton = new WebSocketProxyClient(options)
@@ -66,7 +66,11 @@ export function partId () {
66
66
  return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')
67
67
  }
68
68
 
69
- /** Las partes (ya como objetos para sellar) de un JSON de `json.length` > `size`. */
69
+ /**
70
+ * Las partes (ya como objetos para sellar) de un JSON de `json.length` > `size`.
71
+ * @param {string} json @param {number} size
72
+ * @returns {Array<{ [PART_TAG]: { id: string, i: number, n: number }, d: string }>}
73
+ */
70
74
  export function splitParts (json, size) {
71
75
  const n = Math.ceil(json.length / size)
72
76
  const id = partId()
@@ -78,6 +82,8 @@ export function splitParts (json, size) {
78
82
  /**
79
83
  * Las partes de un paquete de `bytes.length` > `size`, cada una ya empaquetada (lista para
80
84
  * cifrar como bytes). El rearmado une los trozos y desempaqueta el resultado.
85
+ * @param {Uint8Array} bytes @param {number} size
86
+ * @returns {Uint8Array[]}
81
87
  */
82
88
  export function splitBinParts (bytes, size) {
83
89
  const n = Math.ceil(bytes.byteLength / size)
@@ -87,6 +93,7 @@ export function splitBinParts (bytes, size) {
87
93
  return out
88
94
  }
89
95
 
96
+ /** @param {any} o @returns {boolean} */
90
97
  export const isPart = (o) => !!(o && typeof o === 'object' && o[PART_TAG])
91
98
 
92
99
  /**
@@ -94,8 +101,16 @@ export const isPart = (o) => !!(o && typeof o === 'object' && o[PART_TAG])
94
101
  * mientras falten, y lanza con `code` si la parte no vale (se dice: una parte mala no puede
95
102
  * desaparecer en silencio, porque el mensaje entero se pierde con ella).
96
103
  */
104
+ /**
105
+ * Un mensaje a medio rearmar.
106
+ * @typedef {{ n: number, bin: boolean, got: Array<string | Uint8Array>, count: number,
107
+ * chars: number, timer: ReturnType<typeof setTimeout> | null }} PendingParts
108
+ */
109
+
97
110
  export class Reassembler {
111
+ /** @param {{ onExpire?: (info: { id: string, parts: number, missing: number }) => void }} [opts] */
98
112
  constructor ({ onExpire = () => {} } = {}) {
113
+ /** @type {Map<string, PendingParts>} */
99
114
  this._open = new Map()
100
115
  this._chars = 0
101
116
  this._onExpire = onExpire
@@ -134,7 +149,11 @@ export class Reassembler {
134
149
  if (a.timer) clearTimeout(a.timer)
135
150
  if (a.count === a.n) {
136
151
  this._drop(key)
137
- try { return a.bin ? unpack(concatBytes(a.got)) : JSON.parse(a.got.join('')) }
152
+ try {
153
+ return a.bin
154
+ ? unpack(concatBytes(/** @type {Uint8Array[]} */ (a.got)))
155
+ : JSON.parse(a.got.join(''))
156
+ }
138
157
  catch (_) { throw errorWithCode('a message in parts did not join into a message', 'bad-part') }
139
158
  }
140
159
  a.timer = setTimeout(() => {
@@ -146,6 +165,7 @@ export class Reassembler {
146
165
  return null
147
166
  }
148
167
 
168
+ /** @param {string} key */
149
169
  _drop (key) {
150
170
  const a = this._open.get(key)
151
171
  if (!a) return
@@ -21,12 +21,27 @@ const ECDH = { name: 'ECDH', namedCurve: 'P-256' }
21
21
 
22
22
  const VERSION = 1
23
23
 
24
+ /**
25
+ * Lo que se usa de `@dotrino/identity/content`. Se declara aquí porque ese subpath no
26
+ * publica tipos.
27
+ * @typedef {{
28
+ * wrapForMember (args: { cek: string, memberEncPub: string }): Promise<any>,
29
+ * openWrap (args: { wrap: any, myEncPrivateKey: CryptoKey }): Promise<string>,
30
+ * makeContentKey?: () => Promise<string>,
31
+ * encryptBytesWithCek?: (args: { cek: string, bytes: Uint8Array }) => Promise<{ iv: Uint8Array, ct: Uint8Array }>,
32
+ * decryptBytesWithCek?: (args: { cek: string, iv: Uint8Array, ct: Uint8Array }) => Promise<Uint8Array>,
33
+ * }} SealingPrimitives
34
+ */
35
+
36
+ /** @type {SealingPrimitives | null} */
24
37
  let primitives = null
25
38
 
39
+ /** @returns {Promise<SealingPrimitives>} */
26
40
  async function crypto_ () {
27
41
  if (primitives) return primitives
28
42
  try {
29
- primitives = await import('@dotrino/identity/content')
43
+ // @ts-expect-error -- `@dotrino/identity/content` no publica declaraciones de tipos (dependencia).
44
+ primitives = /** @type {SealingPrimitives} */ (await import('@dotrino/identity/content'))
30
45
  } catch (e) {
31
46
  throw new Error(
32
47
  'sealing requires @dotrino/identity (peer dependency) — install it, or pass ' +
@@ -35,12 +50,18 @@ async function crypto_ () {
35
50
  return primitives
36
51
  }
37
52
 
38
- /** Inject the primitives instead of resolving `@dotrino/identity` (bundlers, tests). */
53
+ /**
54
+ * Inject the primitives instead of resolving `@dotrino/identity` (bundlers, tests).
55
+ * @param {SealingPrimitives} mod
56
+ */
39
57
  export function setSealingPrimitives (mod) {
40
58
  primitives = mod
41
59
  }
42
60
 
43
- /** A durable encryption keypair for this device. Its public half goes in the pairing code. */
61
+ /**
62
+ * A durable encryption keypair for this device. Its public half goes in the pairing code.
63
+ * @returns {Promise<{ privateKey: CryptoKey, publicKey: CryptoKey, encPub: string }>}
64
+ */
44
65
  export async function makeEncKeypair () {
45
66
  const pair = await globalThis.crypto.subtle.generateKey(ECDH, true, ['deriveBits'])
46
67
  const pub = await globalThis.crypto.subtle.exportKey('jwk', pair.publicKey)
@@ -51,15 +72,22 @@ export async function makeEncKeypair () {
51
72
  }
52
73
  }
53
74
 
75
+ /** @param {JsonWebKey} jwk @returns {Promise<CryptoKey>} */
54
76
  export async function importEncPrivate (jwk) {
55
77
  return globalThis.crypto.subtle.importKey('jwk', jwk, ECDH, true, ['deriveBits'])
56
78
  }
57
79
 
80
+ /** @param {CryptoKey} privateKey @returns {Promise<JsonWebKey>} */
58
81
  export async function exportEncPrivate (privateKey) {
59
82
  return globalThis.crypto.subtle.exportKey('jwk', privateKey)
60
83
  }
61
84
 
62
- /** Seal a message towards a peer's encryption public key. */
85
+ /**
86
+ * Seal a message towards a peer's encryption public key.
87
+ * @param {unknown} message
88
+ * @param {string} peerEncPub
89
+ * @returns {Promise<{ v: number, sealed: any }>}
90
+ */
63
91
  export async function seal (message, peerEncPub) {
64
92
  if (!peerEncPub) throw new Error('seal: missing peer encryption key')
65
93
  const { wrapForMember } = await crypto_()
@@ -67,7 +95,12 @@ export async function seal (message, peerEncPub) {
67
95
  return { v: VERSION, sealed }
68
96
  }
69
97
 
70
- /** Open a message sealed to me. Throws if it is not mine or was tampered with. */
98
+ /**
99
+ * Open a message sealed to me. Throws if it is not mine or was tampered with.
100
+ * @param {any} envelope
101
+ * @param {CryptoKey} myEncPrivateKey
102
+ * @returns {Promise<any>}
103
+ */
71
104
  export async function open (envelope, myEncPrivateKey) {
72
105
  if (!isSealed(envelope)) throw new Error('open: not a sealed envelope')
73
106
  if (!myEncPrivateKey) throw new Error('open: missing my encryption key')
@@ -75,6 +108,7 @@ export async function open (envelope, myEncPrivateKey) {
75
108
  return JSON.parse(await openWrap({ wrap: envelope.sealed, myEncPrivateKey }))
76
109
  }
77
110
 
111
+ /** @param {any} msg @returns {boolean} */
78
112
  export function isSealed (msg) {
79
113
  return !!msg && msg.v === VERSION && !!msg.sealed?.ct && !!msg.sealed?.epk
80
114
  }
@@ -104,7 +138,7 @@ export function isSealed (msg) {
104
138
  *
105
139
  * @param {any} identity cualquiera de los dos dialectos
106
140
  * @param {{ app?: string }} [opts]
107
- * @returns {{ seal:Function, open:Function, isSealed:Function }}
141
+ * @returns {Required<import('./index.js').SealingBridge>}
108
142
  */
109
143
  export function identitySealing (identity, { app = 'dotrino' } = {}) {
110
144
  // El dialecto se decide UNA vez, por lo que el objeto expone, y no por el resultado de
@@ -119,6 +153,7 @@ export function identitySealing (identity, { app = 'dotrino' } = {}) {
119
153
  }
120
154
 
121
155
  const myEncPub = () => (iframe ? identity.getEncryptionPubkey() : identity.encryptionPubkey())
156
+ /** @param {string} from @param {any} envelope @returns {Promise<string>} */
122
157
  const openEnvelope = async (from, envelope) => {
123
158
  const r = iframe
124
159
  ? await identity.decrypt(from, null, envelope)
@@ -131,6 +166,7 @@ export function identitySealing (identity, { app = 'dotrino' } = {}) {
131
166
  }
132
167
 
133
168
  return {
169
+ /** @param {unknown} msg @param {string} peerEncPub @param {{ publickey?: string }} [opts] */
134
170
  async seal (msg, peerEncPub, { publickey } = {}) {
135
171
  if (!peerEncPub) throw errorWithCode('no encryption key for the other side', 'unsealed')
136
172
  // Destinatarios como OBJETOS, y CON SU `publickey`: `encrypt` expande cada uno a
@@ -148,6 +184,7 @@ export function identitySealing (identity, { app = 'dotrino' } = {}) {
148
184
  }
149
185
  return { app, sealed, from: await myEncPub() }
150
186
  },
187
+ /** @param {any} env */
151
188
  async open (env) { return JSON.parse(await openEnvelope(env.from, env.sealed)) },
152
189
  /**
153
190
  * La llave de cifrado de QUIEN SELLÓ. El sobre de la bóveda es ECDH entre la llave de
@@ -155,7 +192,9 @@ export function identitySealing (identity, { app = 'dotrino' } = {}) {
155
192
  * es lo que dice de quién viene de verdad (el token no lo dice, y el saludo no
156
193
  * autentica). La app la compara con la que conoce de su contacto.
157
194
  */
195
+ /** @param {any} env */
158
196
  senderOf: (env) => (typeof env?.from === 'string' ? env.from : null),
197
+ /** @param {any} m */
159
198
  isSealed: (m) => !!m && m.app === app && !!m.sealed,
160
199
  }
161
200
  }
@@ -176,26 +215,38 @@ export function identitySealing (identity, { app = 'dotrino' } = {}) {
176
215
  */
177
216
  export const BIN_SEALED = 1
178
217
 
218
+ /** @param {any} env @returns {boolean} */
179
219
  export function isBinSealed (env) {
180
220
  return !!env && env.bv === BIN_SEALED && !!env.k && typeof env.k === 'object' &&
181
221
  env.iv instanceof Uint8Array && env.ct instanceof Uint8Array
182
222
  }
183
223
 
184
- /** Una CEK nueva para un mensaje con bytes. */
224
+ /**
225
+ * Una CEK nueva para un mensaje con bytes.
226
+ * @returns {Promise<string>}
227
+ */
185
228
  export async function makeMessageKey () {
186
229
  const { makeContentKey } = await crypto_()
187
230
  if (typeof makeContentKey !== 'function') throw errorWithCode('sealing bytes needs @dotrino/identity >= 0.117.0', 'no-bytes-sealing')
188
231
  return makeContentKey()
189
232
  }
190
233
 
191
- /** Cifra `bytes` con la CEK y devuelve los campos del sobre (`iv`, `ct`). */
234
+ /**
235
+ * Cifra `bytes` con la CEK y devuelve los campos del sobre (`iv`, `ct`).
236
+ * @param {string} cek @param {Uint8Array} bytes
237
+ * @returns {Promise<{ iv: Uint8Array, ct: Uint8Array }>}
238
+ */
192
239
  export async function encryptBytes (cek, bytes) {
193
240
  const { encryptBytesWithCek } = await crypto_()
194
241
  if (typeof encryptBytesWithCek !== 'function') throw errorWithCode('sealing bytes needs @dotrino/identity >= 0.117.0', 'no-bytes-sealing')
195
242
  return encryptBytesWithCek({ cek, bytes })
196
243
  }
197
244
 
198
- /** Descifra el `ct` de un sobre binario con su CEK ya abierta. */
245
+ /**
246
+ * Descifra el `ct` de un sobre binario con su CEK ya abierta.
247
+ * @param {string} cek @param {{ iv: Uint8Array, ct: Uint8Array }} env
248
+ * @returns {Promise<Uint8Array>}
249
+ */
199
250
  export async function decryptBytes (cek, env) {
200
251
  const { decryptBytesWithCek } = await crypto_()
201
252
  if (typeof decryptBytesWithCek !== 'function') throw errorWithCode('opening bytes needs @dotrino/identity >= 0.117.0', 'no-bytes-sealing')
@@ -17,7 +17,19 @@ const STORAGE_KEY = 'dotrino.proxy-client.keypair'
17
17
  const DB_NAME = 'dotrino.proxy-client'
18
18
  const DB_STORE = 'keypair'
19
19
 
20
+ /**
21
+ * El par de llaves de este cliente.
22
+ * @typedef {{ privateKey: CryptoKey, publicKey: CryptoKey, publicJwk: JsonWebKey }} Keypair
23
+ */
24
+ /**
25
+ * Dónde se guarda el par (`setKeypairStore`).
26
+ * @typedef {{ get (): Promise<Partial<Keypair> | null | undefined> | Partial<Keypair> | null | undefined,
27
+ * set (pair: Keypair): Promise<void> | void }} KeypairStore
28
+ */
29
+
30
+ /** @type {Keypair | null} */
20
31
  let cachedKeypair = null
32
+ /** @type {KeypairStore | null} */
21
33
  let injectedStore = null
22
34
  let injectedExtractable = false
23
35
 
@@ -30,6 +42,9 @@ let injectedExtractable = false
30
42
  * need it and is safer without, but a store that serializes to disk or to text has
31
43
  * to export the private key as a JWK, and that throws on a non-extractable key. Pass
32
44
  * `{ extractable: true }` for those.
45
+ *
46
+ * @param {KeypairStore | null} store
47
+ * @param {{ extractable?: boolean }} [opts]
33
48
  */
34
49
  export function setKeypairStore (store, { extractable = false } = {}) {
35
50
  injectedStore = store
@@ -37,6 +52,7 @@ export function setKeypairStore (store, { extractable = false } = {}) {
37
52
  cachedKeypair = null
38
53
  }
39
54
 
55
+ /** @returns {Promise<IDBDatabase>} */
40
56
  function idb () {
41
57
  return new Promise((resolve, reject) => {
42
58
  const req = indexedDB.open(DB_NAME, 1)
@@ -48,6 +64,12 @@ function idb () {
48
64
  })
49
65
  }
50
66
 
67
+ /**
68
+ * @param {IDBDatabase} db
69
+ * @param {IDBTransactionMode} mode
70
+ * @param {(store: IDBObjectStore) => IDBRequest} fn
71
+ * @returns {Promise<any>}
72
+ */
51
73
  function idbRequest (db, mode, fn) {
52
74
  return new Promise((resolve, reject) => {
53
75
  const tx = db.transaction(DB_STORE, mode)
@@ -57,6 +79,7 @@ function idbRequest (db, mode, fn) {
57
79
  })
58
80
  }
59
81
 
82
+ /** @type {KeypairStore} */
60
83
  const indexedDbStore = {
61
84
  async get () {
62
85
  const db = await idb()
@@ -86,12 +109,14 @@ function localStorageWorks () {
86
109
  }
87
110
  }
88
111
 
112
+ /** @returns {KeypairStore | null} */
89
113
  function fallbackStore () {
90
114
  if (injectedStore) return injectedStore
91
115
  if (!localStorageWorks() && typeof indexedDB !== 'undefined') return indexedDbStore
92
116
  return null
93
117
  }
94
118
 
119
+ /** @returns {Promise<Keypair>} */
95
120
  async function loadOrCreate () {
96
121
  if (cachedKeypair) return cachedKeypair
97
122
 
@@ -128,7 +153,7 @@ async function loadOrCreate () {
128
153
  // and every peer that knows this device by its public key stops recognising
129
154
  // it — the exact failure this whole path exists to prevent. A silent catch
130
155
  // here means finding out days later, from the other side.
131
- console.error('[proxy-client] could not persist the keypair: %s', e?.message || e)
156
+ console.error('[proxy-client] could not persist the keypair: %s', /** @type {{ message?: string } | null | undefined} */ (e)?.message || e)
132
157
  console.error('[proxy-client] identity will NOT survive a restart. If the store serializes, pass { extractable: true } to setKeypairStore.')
133
158
  }
134
159
  cachedKeypair = entry
@@ -173,6 +198,7 @@ async function loadOrCreate () {
173
198
 
174
199
  /**
175
200
  * Returns the public key as a JWK string (what the proxy stores in data.publickey).
201
+ * @returns {Promise<string>}
176
202
  */
177
203
  export async function getPublicKeyJwk () {
178
204
  const { publicJwk } = await loadOrCreate()
@@ -181,6 +207,8 @@ export async function getPublicKeyJwk () {
181
207
 
182
208
  /**
183
209
  * Sign the canonical JSON of `data` and return base64 signature.
210
+ * @param {unknown} data
211
+ * @returns {Promise<string>}
184
212
  */
185
213
  export async function signData (data) {
186
214
  const { privateKey } = await loadOrCreate()
@@ -206,6 +234,10 @@ export async function signData (data) {
206
234
  * Ojo con lo que esto NO cambia: el proxio enruta por el STRING exacto, así que la
207
235
  * dirección a la que se escribe sigue siendo la que te dio la app. Esto es para DECIDIR
208
236
  * si dos referencias hablan de la misma identidad, no para reemplazar una por otra.
237
+ *
238
+ * @param {unknown} a
239
+ * @param {unknown} b
240
+ * @returns {boolean}
209
241
  */
210
242
  export function samePubkey (a, b) {
211
243
  if (typeof a !== 'string' || typeof b !== 'string') return false
@@ -262,12 +294,14 @@ export async function verifyData (publickeyJwkStr, data, signatureB64) {
262
294
  }
263
295
  }
264
296
 
297
+ /** @param {Uint8Array} bytes @returns {string} */
265
298
  function bufferToBase64 (bytes) {
266
299
  let binary = ''
267
300
  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i])
268
301
  return btoa(binary)
269
302
  }
270
303
 
304
+ /** @param {string} b64 @returns {Uint8Array<ArrayBuffer>} */
271
305
  function base64ToBuffer (b64) {
272
306
  const bin = atob(b64)
273
307
  const out = new Uint8Array(bin.length)
@@ -277,6 +311,9 @@ function base64ToBuffer (b64) {
277
311
 
278
312
  /**
279
313
  * Build the {data, signature} envelope for a channel name.
314
+ * @param {string} channelName
315
+ * @param {Record<string, unknown>} [extraData]
316
+ * @returns {Promise<{ data: Record<string, unknown> & { name: string, publickey: string }, signature: string }>}
280
317
  */
281
318
  export async function buildSignedChannel (channelName, extraData = {}) {
282
319
  const publickey = await getPublicKeyJwk()
@@ -19,19 +19,29 @@
19
19
  */
20
20
  import { listTransports, PATHS } from './stats.js'
21
21
 
22
+ /** @typedef {import('./index.js').TransportStats} TransportStats */
23
+ /** @typedef {import('./index.js').PeerTraffic} PeerTraffic */
24
+ /** @typedef {import('./index.js').TrafficByPath} TrafficByPath */
25
+
26
+ /**
27
+ * @param {PeerTraffic[]} peers
28
+ * @param {'bytesIn' | 'bytesOut'} dir
29
+ * @returns {TrafficByPath}
30
+ */
22
31
  const sum = (peers, dir) => {
23
32
  const t = { proxy: 0, direct: 0, turn: 0, webrtc: 0, bluetooth: 0 }
24
33
  for (const p of peers) for (const k of PATHS) t[k] += p[dir][k]
25
34
  return t
26
35
  }
27
36
 
37
+ /** @param {string} prefix @param {TrafficByPath} o */
28
38
  const pairs = (prefix, o) => PATHS.map((k) => `${prefix}.${k}=${o[k]}`).join(' ')
29
39
 
30
40
  /**
31
41
  * Las líneas de UN cliente, a partir de lo que devuelve `client.stats()`.
32
42
  * La primera es el resumen; después, una por conexión.
33
43
  *
34
- * @param {object} s lo que devuelve `client.stats()` (`TransportStats` en los tipos)
44
+ * @param {TransportStats} s lo que devuelve `client.stats()`
35
45
  * @param {{ label?: string }} [opts]
36
46
  * @returns {string[]}
37
47
  */
@@ -42,10 +52,12 @@ export function formatStats (s, opts = {}) {
42
52
  // (`unanswered`), igual que en el informe del topbar y de las apps nativas.
43
53
  // `unknown`: quien nos escribió, nunca recibió respuesta y no sabemos su llave (otro aparato
44
54
  // sondeando qué máquinas están encendidas). Tampoco es una conexión.
55
+ /** @param {PeerTraffic} p */
45
56
  const isUnknown = (p) => p.msgsIn > 0 && !(p.msgsOut > 0) && !p.pubkey
46
57
  const unknown = s.peers.filter(isUnknown)
47
58
  const talking = s.peers.filter((p) => p.msgsIn > 0 && !isUnknown(p))
48
59
  const silent = s.peers.filter((p) => !(p.msgsIn > 0))
60
+ /** @type {Record<string, number>} */
49
61
  const routes = {}
50
62
  for (const p of talking) routes[p.route] = (routes[p.route] || 0) + 1
51
63
  const routeList = Object.keys(routes).sort().map((r) => `${r}=${routes[r]}`).join(',') || 'none'
@@ -75,9 +87,9 @@ export function formatStats (s, opts = {}) {
75
87
  * `flush` escribe ya (si cambió algo); `stop` escribe una última vez y para.
76
88
  */
77
89
  export function logStats (opts = {}) {
78
- const log = opts.log || ((line) => console.log(line))
90
+ const log = opts.log || (/** @param {string} line */ (line) => console.log(line))
79
91
  const everyMs = opts.everyMs || 5 * 60 * 1000
80
- /** cliente → lo último que se escribió de él */
92
+ /** @type {WeakMap<object, string>} cliente → lo último que se escribió de él */
81
93
  const last = new WeakMap()
82
94
 
83
95
  const flush = async () => {
@@ -88,7 +100,7 @@ export function logStats (opts = {}) {
88
100
  lines = formatStats(await client.stats(), opts)
89
101
  } catch (e) {
90
102
  // No poder leer NO es «no hubo tráfico»: se dice, para que no parezca silencio.
91
- lines = [`${opts.label ? `[net] ${opts.label}` : '[net]'} could not read stats: ${e?.message || e}`]
103
+ lines = [`${opts.label ? `[net] ${opts.label}` : '[net]'} could not read stats: ${/** @type {{ message?: string } | null | undefined} */ (e)?.message || e}`]
92
104
  }
93
105
  const text = lines.join('\n')
94
106
  if (last.get(client) === text) continue
@@ -108,9 +120,11 @@ export function logStats (opts = {}) {
108
120
  }
109
121
 
110
122
  /** Bytes para el informe de texto: `B`, `KB` con un decimal, `MB` con dos. */
123
+ /** @param {number} n */
111
124
  const rBytes = (n) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1024 / 1024).toFixed(2)} MB`)
125
+ /** @param {TrafficByPath | null | undefined} o */
112
126
  const rPaths = (o) => {
113
- const parts = PATHS.filter((k) => (o?.[k] || 0) > 0).map((k) => `${k} ${rBytes(o[k])}`)
127
+ const parts = PATHS.filter((k) => (o?.[k] || 0) > 0).map((k) => `${k} ${rBytes(/** @type {TrafficByPath} */ (o)[k])}`)
114
128
  return parts.length ? parts.join(', ') : '0 B'
115
129
  }
116
130
 
@@ -119,10 +133,14 @@ const rPaths = (o) => {
119
133
  * aparato apagado al que se le mandó un ping no se le llama conexión. `unknown`: quien nos
120
134
  * escribió, nunca recibió respuesta y no sabemos su llave. Tampoco es una conexión.
121
135
  *
122
- * @param {Array<object>} peers `TransportStats.peers`
136
+ * @param {PeerTraffic[]} peers `TransportStats.peers`
137
+ * @returns {{ talking: PeerTraffic[], silent: { count: number, bytesOut: number, msgsOut: number },
138
+ * unknown: { count: number, bytesIn: number, msgsIn: number } }}
123
139
  */
124
140
  export function splitPeers (peers) {
141
+ /** @param {TrafficByPath | null | undefined} o */
125
142
  const total = (o) => PATHS.reduce((n, k) => n + (o?.[k] || 0), 0)
143
+ /** @type {PeerTraffic[]} */
126
144
  const talking = []
127
145
  const silent = { count: 0, bytesOut: 0, msgsOut: 0 }
128
146
  const unknown = { count: 0, bytesIn: 0, msgsIn: 0 }
@@ -138,7 +156,7 @@ export function splitPeers (peers) {
138
156
  * (que va a un log en disco y por eso calla la llave), este se enseña en pantalla a quien lo
139
157
  * pidió, y dice con quién es cada conexión.
140
158
  *
141
- * @param {Array<object>} list lo que devolvió `client.stats()` de cada cliente (o `{ url, error }`)
159
+ * @param {Array<TransportStats | { url: string, error: string }>} list lo que devolvió `client.stats()` de cada cliente (o `{ url, error }`)
142
160
  * @param {{ label?: (pubkey: string) => string | Promise<string>, now?: Date }} [opts]
143
161
  * `label`: cómo se nombra un aparato a partir de su llave (su id `AB12-CD34`, su nombre).
144
162
  * Sin él, o si falla, sale `?`: nunca un trozo de la llave.
@@ -148,8 +166,10 @@ export async function netReport (list, opts = {}) {
148
166
  const now = opts.now || new Date()
149
167
  let out = `Dotrino network stats · ${now.toISOString().replace(/\.\d{3}Z$/, 'Z')}\n`
150
168
  if (!list.length) out += '(no transports)\n'
151
- for (const s of list) {
152
- if (s.error) { out += `Proxy ${s.url} | error: ${s.error}\n`; continue }
169
+ for (const entry of list) {
170
+ const error = /** @type {{ error?: string }} */ (entry).error
171
+ if (error) { out += `Proxy ${entry.url} | error: ${error}\n`; continue }
172
+ const s = /** @type {TransportStats} */ (entry)
153
173
  const hhmm = new Date(s.since).toTimeString().slice(0, 8)
154
174
  out += `Proxy ${s.url}${s.app ? ` | app=${s.app}` : ''}${s.node ? ` | node=${s.node}` : ''} | ${s.connected ? 'connected' : 'disconnected'} | since ${hhmm}\n`
155
175
  out += ` proxy total: in ${rBytes(s.proxy.bytesIn)} / out ${rBytes(s.proxy.bytesOut)} (frames ${s.proxy.framesIn ?? '?'}/${s.proxy.framesOut ?? '?'})\n`
@@ -18,7 +18,11 @@
18
18
  * bluetooth el escalón del Bluetooth (docs/bluetooth.md)
19
19
  */
20
20
 
21
- /** Longitud en bytes UTF-8 de un string, sin reservar un buffer por mensaje. */
21
+ /**
22
+ * Longitud en bytes UTF-8 de un string, sin reservar un buffer por mensaje.
23
+ * @param {any} s un string, o algo con `byteLength` o `size` (bytes, un Blob)
24
+ * @returns {number}
25
+ */
22
26
  export function utf8Length (s) {
23
27
  if (typeof s !== 'string') {
24
28
  if (s && typeof s.byteLength === 'number') return s.byteLength
@@ -36,19 +40,33 @@ export function utf8Length (s) {
36
40
  return n
37
41
  }
38
42
 
43
+ /** @typedef {import('./index.js').TrafficByPath} TrafficByPath */
44
+ /** Lo que se cuenta de una conexión; la ruta se le añade al leerlo (`client.stats()`). */
45
+ /** @typedef {Omit<import('./index.js').PeerTraffic, 'route'>} PeerCounters */
46
+ /** @typedef {keyof TrafficByPath} TrafficPath */
47
+
48
+ /** @type {TrafficPath[]} */
39
49
  export const PATHS = ['proxy', 'direct', 'turn', 'webrtc', 'bluetooth']
40
50
 
51
+ /** @returns {TrafficByPath} */
41
52
  const zeros = () => ({ proxy: 0, direct: 0, turn: 0, webrtc: 0, bluetooth: 0 })
42
53
 
43
54
  export class TrafficStats {
44
55
  constructor () {
45
56
  this.since = Date.now()
46
57
  this.proxy = { bytesIn: 0, bytesOut: 0, framesIn: 0, framesOut: 0 }
47
- /** clave (`t:<token>` | `k:<pubkey>`) → contadores de esa conexión */
58
+ /**
59
+ * clave (`t:<token>` | `k:<pubkey>`) → contadores de esa conexión
60
+ * @type {Map<string, PeerCounters>}
61
+ */
48
62
  this.peers = new Map()
49
63
  }
50
64
 
51
- /** Un frame entero del WebSocket del proxio. */
65
+ /**
66
+ * Un frame entero del WebSocket del proxio.
67
+ * @param {'in'|'out'} dir
68
+ * @param {number} bytes
69
+ */
52
70
  frame (dir, bytes) {
53
71
  if (dir === 'in') { this.proxy.bytesIn += bytes; this.proxy.framesIn++ } else { this.proxy.bytesOut += bytes; this.proxy.framesOut++ }
54
72
  }
@@ -56,7 +74,7 @@ export class TrafficStats {
56
74
  /**
57
75
  * Un mensaje dirigido a (o venido de) una conexión.
58
76
  * @param {'in'|'out'} dir
59
- * @param {'proxy'|'direct'|'turn'|'webrtc'|'bluetooth'} path
77
+ * @param {TrafficPath} path
60
78
  * @param {{ token?: string|null, pubkey?: string|null }} who
61
79
  * @param {number} bytes
62
80
  */
@@ -89,8 +107,9 @@ export async function routeOf (pc) {
89
107
  let report
90
108
  try { report = await pc.getStats() } catch (_) { return null }
91
109
  if (!report || typeof report.forEach !== 'function') return null
110
+ /** @type {Map<string, any>} */
92
111
  const byId = new Map()
93
- report.forEach((s) => { if (s && s.id) byId.set(s.id, s) })
112
+ report.forEach(/** @param {any} s */ (s) => { if (s && s.id) byId.set(s.id, s) })
94
113
  let pair = null
95
114
  // El par vigente lo dice el transporte; si no, el que está nominado y funcionando.
96
115
  for (const s of byId.values()) {
@@ -105,6 +124,7 @@ export async function routeOf (pc) {
105
124
  const local = byId.get(pair.localCandidateId)
106
125
  const remote = byId.get(pair.remoteCandidateId)
107
126
  if (!local && !remote) return null
127
+ /** @param {any} c */
108
128
  const typeOf = (c) => c && (c.candidateType || c.type)
109
129
  return typeOf(local) === 'relay' || typeOf(remote) === 'relay' ? 'turn' : 'direct'
110
130
  }
@@ -117,9 +137,12 @@ export async function routeOf (pc) {
117
137
  */
118
138
  const REGISTRY = Symbol.for('dotrino.transports')
119
139
 
140
+ /** @returns {Set<import('./index.js').WebSocketProxyClient>} */
120
141
  function registry () {
121
- if (!globalThis[REGISTRY]) globalThis[REGISTRY] = new Set()
122
- return globalThis[REGISTRY]
142
+ const g = /** @type {Record<symbol, Set<import('./index.js').WebSocketProxyClient> | undefined>} */ (/** @type {unknown} */ (globalThis))
143
+ let r = g[REGISTRY]
144
+ if (!r) { r = new Set(); g[REGISTRY] = r }
145
+ return r
123
146
  }
124
147
 
125
148
  function notify () {
@@ -128,6 +151,7 @@ function notify () {
128
151
  }
129
152
  }
130
153
 
154
+ /** @param {import('./index.js').WebSocketProxyClient} client */
131
155
  export function registerTransport (client) {
132
156
  const r = registry()
133
157
  if (r.has(client)) return
@@ -135,11 +159,15 @@ export function registerTransport (client) {
135
159
  notify()
136
160
  }
137
161
 
162
+ /** @param {import('./index.js').WebSocketProxyClient} client */
138
163
  export function unregisterTransport (client) {
139
164
  if (registry().delete(client)) notify()
140
165
  }
141
166
 
142
- /** Los clientes registrados en esta página (o proceso). */
167
+ /**
168
+ * Los clientes registrados en esta página (o proceso).
169
+ * @returns {import('./index.js').WebSocketProxyClient[]}
170
+ */
143
171
  export function listTransports () {
144
172
  return [...registry()]
145
173
  }