@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
@@ -23,6 +23,41 @@
23
23
 
24
24
  import * as W from './wire.js'
25
25
 
26
+ /** @typedef {import('../index.js').BluetoothAdapter} BluetoothAdapter */
27
+ /** @typedef {Awaited<ReturnType<BluetoothAdapter['connect']>>} Link */
28
+ /** @typedef {{ id: string }} Device */
29
+
30
+ /**
31
+ * Una negociación (y después el canal) con un token. Los campos que son `null` al nacer se
32
+ * rellenan según avanza `state`: `key`, `role` y `tag` desde `keyed`; `link` (central) o
33
+ * `central` (periférico) desde que hay enlace.
34
+ * @typedef {{
35
+ * token: string,
36
+ * state: 'new' | 'offered' | 'keyed' | 'open' | 'failed' | 'closed',
37
+ * role: 'central' | 'peripheral' | null,
38
+ * eph: { privateKey: CryptoKey, epub: string } | null,
39
+ * key: CryptoKey | null,
40
+ * theirBid: string | null,
41
+ * myBid: string | null,
42
+ * tag: Uint8Array | null,
43
+ * link: Link | null,
44
+ * central: string | null,
45
+ * chunk: number,
46
+ * sendCtr: number,
47
+ * recvCtr: number,
48
+ * pending: number,
49
+ * queue: Promise<void>,
50
+ * recvChain: Promise<void>,
51
+ * timer: ReturnType<typeof setTimeout> | null,
52
+ * failedAt: number,
53
+ * }} BlePeer
54
+ */
55
+
56
+ /**
57
+ * Un central conectado a nosotros (lado periférico).
58
+ * @typedef {{ rx: InstanceType<typeof W.Reassembler>, peer: BlePeer | null, pendingHello: Uint8Array | null, chain: Promise<unknown> }} Central
59
+ */
60
+
26
61
  const FAIL_RETRY_MS = 60_000
27
62
  const SEEN_TTL_MS = 60_000
28
63
 
@@ -36,35 +71,52 @@ export class BluetoothManager {
36
71
  * @param {(dir: 'in'|'out', token: string, bytes: number, route: 'bluetooth') => void} [opts.count]
37
72
  */
38
73
  constructor (opts) {
74
+ /** @type {((from: string) => boolean) | null} */
39
75
  this.acceptFrom = null
40
76
  this.getSelfToken = opts.getSelfToken
41
77
  this.signalSend = opts.signalSend
42
78
  this.deliverMessage = opts.deliverMessage
43
79
  this.emit = opts.emit
44
80
  this.count = typeof opts.count === 'function' ? opts.count : null
81
+ /** @type {BluetoothAdapter | null} */
45
82
  this.adapter = null
83
+ /** @type {string | null} */
46
84
  this.bid = null
85
+ /** @type {Uint8Array} */
47
86
  this.beacon = new Uint8Array(0)
48
- this.peers = new Map() // token -> estado de la negociación / canal
49
- this.centrals = new Map() // centralId -> { rx, peer, chain } (lado periférico)
50
- this.wanted = new Map() // bid -> peer que buscamos en el aire (lado central)
51
- this._seen = new Map() // deviceId -> { bid, at }
87
+ /** @type {Map<string, BlePeer>} token -> estado de la negociación / canal */
88
+ this.peers = new Map()
89
+ /** @type {Map<string, Central>} centralId -> { rx, peer, chain } (lado periférico) */
90
+ this.centrals = new Map()
91
+ /** @type {Map<string, BlePeer>} bid -> peer que buscamos en el aire (lado central) */
92
+ this.wanted = new Map()
93
+ /** @type {Map<string, { bid: string | null, at: number }>} deviceId -> { bid, at } */
94
+ this._seen = new Map()
95
+ /** @type {Set<string>} */
52
96
  this._probing = new Set()
97
+ /** @type {Set<(dev: Device) => void>} */
53
98
  this._scanListeners = new Set()
99
+ /** @type {(() => Promise<void>) | null} */
54
100
  this._stopScan = null
101
+ /** @type {Promise<void> | null} */
55
102
  this._scanStarting = null
103
+ /** @type {Promise<void> | null} */
104
+ this._scanStopping = null
105
+ /** @type {Promise<unknown>} */
56
106
  this._connectLock = Promise.resolve()
107
+ /** @type {ReturnType<typeof setInterval> | null} */
57
108
  this._rotate = null
58
109
  }
59
110
 
60
111
  /** Hay Bluetooth en marcha en este proceso. */
61
112
  get available () { return !!this.adapter }
62
113
 
114
+ /** @param {BluetoothAdapter} adapter */
63
115
  async start (adapter) {
64
116
  if (this.adapter) return
65
117
  this.bid = W.randomBid()
66
118
  await adapter.start({
67
- hello: () => W.encodeHello(this.bid),
119
+ hello: () => W.encodeHello(/** @type {string} */ (this.bid)),
68
120
  beacon: () => this.beacon,
69
121
  onWrite: (centralId, bytes) => this._onWrite(centralId, bytes),
70
122
  onDisconnect: (centralId) => this._onCentralGone(centralId),
@@ -86,7 +138,12 @@ export class BluetoothManager {
86
138
 
87
139
  // ---------- señalización ----------
88
140
 
89
- /** True si era una trama de este escalón (se consume aunque no haya Bluetooth). */
141
+ /**
142
+ * True si era una trama de este escalón (se consume aunque no haya Bluetooth).
143
+ * @param {string} from
144
+ * @param {any} parsed
145
+ * @returns {boolean}
146
+ */
90
147
  handleIncoming (from, parsed) {
91
148
  if (!parsed || typeof parsed !== 'object' || parsed.t !== W.BLE_TAG) return false
92
149
  if (this.acceptFrom && !this.acceptFrom(from)) return true
@@ -100,7 +157,10 @@ export class BluetoothManager {
100
157
  return true
101
158
  }
102
159
 
103
- /** Empieza a negociar con `token` si no hay nada en curso. Sin esperas y sin errores. */
160
+ /**
161
+ * Empieza a negociar con `token` si no hay nada en curso. Sin esperas y sin errores.
162
+ * @param {string} token
163
+ */
104
164
  upgrade (token) {
105
165
  if (!this.adapter || !this.getSelfToken()) return
106
166
  const p = this.peers.get(token)
@@ -109,15 +169,18 @@ export class BluetoothManager {
109
169
  this._offer(token).catch((e) => this.emit('error', { type: 'bluetooth_offer', error: e, peer: token }))
110
170
  }
111
171
 
172
+ /** @param {string} token */
112
173
  async _offer (token) {
113
174
  const p = this._newPeer(token)
114
- p.eph = await W.makeEphemeral()
175
+ const eph = await W.makeEphemeral()
176
+ p.eph = eph
115
177
  p.state = 'offered'
116
178
  p.myBid = this.bid
117
179
  this._timer(p, W.ANSWER_TIMEOUT_MS)
118
- this.signalSend(token, { t: W.BLE_TAG, kind: 'offer', bid: p.myBid, epub: p.eph.epub })
180
+ this.signalSend(token, { t: W.BLE_TAG, kind: 'offer', bid: p.myBid, epub: eph.epub })
119
181
  }
120
182
 
183
+ /** @param {string} from @param {{ kind?: string, bid: string, epub: string }} msg */
121
184
  async _handleSignal (from, msg) {
122
185
  let p = this.peers.get(from)
123
186
  if (msg.kind === 'offer') {
@@ -127,9 +190,10 @@ export class BluetoothManager {
127
190
  } else {
128
191
  if (p) this._drop(p)
129
192
  p = this._newPeer(from)
130
- p.eph = await W.makeEphemeral()
193
+ const eph = await W.makeEphemeral()
194
+ p.eph = eph
131
195
  p.myBid = this.bid
132
- this.signalSend(from, { t: W.BLE_TAG, kind: 'answer', bid: p.myBid, epub: p.eph.epub })
196
+ this.signalSend(from, { t: W.BLE_TAG, kind: 'answer', bid: p.myBid, epub: eph.epub })
133
197
  }
134
198
  } else if (msg.kind === 'answer') {
135
199
  if (!p || p.state !== 'offered') return
@@ -138,47 +202,50 @@ export class BluetoothManager {
138
202
  }
139
203
  const self = this.getSelfToken()
140
204
  if (!self) return this._fail(p)
141
- p.key = await W.deriveKey(p.eph.privateKey, msg.epub, self, from)
205
+ p.key = await W.deriveKey(/** @type {NonNullable<BlePeer['eph']>} */ (p.eph).privateKey, msg.epub, self, from)
142
206
  p.eph = null
143
207
  p.theirBid = msg.bid
144
208
  p.role = self > from ? 'central' : 'peripheral'
145
209
  // Los trozos de `tx` llevan la etiqueta del CENTRAL (docs §5): BlueZ notifica a todos.
146
- p.tag = W.tagOf(p.role === 'central' ? p.myBid : p.theirBid)
210
+ p.tag = W.tagOf(/** @type {string} */ (p.role === 'central' ? p.myBid : p.theirBid))
147
211
  p.state = 'keyed'
148
212
  this._timer(p, W.FIND_TIMEOUT_MS)
149
213
  if (p.role === 'peripheral') this._retryHellos()
150
214
  if (p.role === 'central') {
151
- this.wanted.set(p.theirBid, p)
215
+ this.wanted.set(msg.bid, p)
216
+ const peer = p
152
217
  this._addScan(this._onFoundForPeers).catch((e) => {
153
218
  this.emit('error', { type: 'bluetooth_scan', error: e })
154
- this._fail(p)
219
+ this._fail(peer)
155
220
  })
156
221
  }
157
222
  }
158
223
 
159
224
  // ---------- lado central ----------
160
225
 
226
+ /** @param {Device} dev */
161
227
  _onFoundForPeers = (dev) => {
162
228
  if (!this.wanted.size || this._probing.has(dev.id)) return
163
229
  const seen = this._seen.get(dev.id)
164
- if (seen && Date.now() - seen.at < SEEN_TTL_MS && !this.wanted.has(seen.bid)) return
230
+ if (seen && Date.now() - seen.at < SEEN_TTL_MS && !this.wanted.has(/** @type {string} */ (seen.bid))) return
165
231
  this._probing.add(dev.id)
166
232
  this._withConnectLock(async () => {
233
+ /** @type {Link | null} */
167
234
  let link = null
168
235
  try {
169
- link = await this.adapter.connect(dev)
236
+ link = await /** @type {BluetoothAdapter} */ (this.adapter).connect(dev)
170
237
  const bid = W.decodeHello(await link.read(W.HELLO_UUID))
171
238
  this._seen.set(dev.id, { bid, at: Date.now() })
172
239
  const p = bid ? this.wanted.get(bid) : null
173
240
  if (!p || p.state !== 'keyed') { await link.close(); return }
174
- this.wanted.delete(bid)
241
+ this.wanted.delete(/** @type {string} */ (bid))
175
242
  if (!this.wanted.size) this._removeScan(this._onFoundForPeers)
176
243
  await this._attachLink(p, link)
177
244
  link = null // ya es del canal: se cierra con él
178
245
  } catch (e) {
179
246
  // Se sigue buscando, pero se DICE: es un aparato de Dotrino (anuncia el servicio) que no
180
247
  // se dejó leer o se fue a mitad, y callarlo es dejar un canal que no abre sin un porqué.
181
- this.emit('error', { type: 'bluetooth_probe', device: dev.id, error: e, code: e?.code || null })
248
+ this.emit('error', { type: 'bluetooth_probe', device: dev.id, error: e, code: /** @type {{ code?: string } | null | undefined} */ (e)?.code || null })
182
249
  if (link) await link.close().catch(() => {})
183
250
  } finally {
184
251
  this._probing.delete(dev.id)
@@ -186,41 +253,51 @@ export class BluetoothManager {
186
253
  })
187
254
  }
188
255
 
256
+ /** @param {BlePeer} p @param {Link} link */
189
257
  async _attachLink (p, link) {
190
258
  p.link = link
191
259
  p.chunk = link.chunk
192
260
  link.onClose(() => this._closed(p))
193
261
  const rx = new W.Reassembler(W.TAG_BYTES)
194
- await link.subscribe((chunk) => { if (W.hasTag(chunk, p.tag)) this._onChunk(p, rx, chunk) })
262
+ await link.subscribe((chunk) => { if (W.hasTag(chunk, /** @type {Uint8Array} */ (p.tag))) this._onChunk(p, rx, chunk) })
195
263
  this._sendRecord(p, W.TYPE_HELLO, W.encodeText(this.getSelfToken() || ''))
196
264
  }
197
265
 
266
+ /** @param {BlePeer} p @param {InstanceType<typeof W.Reassembler>} rx @param {Uint8Array} chunk */
198
267
  _onChunk (p, rx, chunk) {
268
+ /** @type {Uint8Array | null} */
199
269
  let rec
200
270
  try { rec = rx.push(chunk) } catch (_) { return this._closed(p) }
201
- if (rec) p.recvChain = p.recvChain.then(() => this._onRecord(p, rec))
271
+ if (rec) { const r = rec; p.recvChain = p.recvChain.then(() => this._onRecord(p, r)) }
202
272
  }
203
273
 
204
274
  // ---------- lado periférico ----------
205
275
 
276
+ /** @param {string} centralId @param {Uint8Array} bytes */
206
277
  _onWrite (centralId, bytes) {
207
278
  let c = this.centrals.get(centralId)
208
279
  if (!c) { c = { rx: new W.Reassembler(), peer: null, pendingHello: null, chain: Promise.resolve() }; this.centrals.set(centralId, c) }
280
+ const central = c
281
+ /** @type {Uint8Array | null} */
209
282
  let rec
210
- try { rec = c.rx.push(bytes) } catch (_) { this.centrals.delete(centralId); if (c.peer) this._closed(c.peer); return }
283
+ try { rec = central.rx.push(bytes) } catch (_) { this.centrals.delete(centralId); if (central.peer) this._closed(central.peer); return }
211
284
  if (!rec) return
212
- c.chain = c.chain.then(() => c.peer ? this._onRecord(c.peer, rec) : this._identify(centralId, c, rec))
285
+ const r = rec
286
+ central.chain = central.chain.then(() => central.peer ? this._onRecord(central.peer, r) : this._identify(centralId, central, r))
213
287
  }
214
288
 
215
- /** Quién se conectó: la llave que descifra su saludo dice de qué negociación es. */
289
+ /**
290
+ * Quién se conectó: la llave que descifra su saludo dice de qué negociación es.
291
+ * @param {string} centralId @param {Central} c @param {Uint8Array} rec
292
+ */
216
293
  async _identify (centralId, c, rec) {
217
294
  for (const p of this.peers.values()) {
218
295
  if (p.role !== 'peripheral' || p.state !== 'keyed' || p.central != null) continue
219
296
  let r
220
- try { r = await W.openRecord(p.key, W.DIR_TO_PERIPHERAL, 0, rec) } catch (_) { continue }
297
+ try { r = await W.openRecord(/** @type {CryptoKey} */ (p.key), W.DIR_TO_PERIPHERAL, 0, /** @type {Uint8Array<ArrayBuffer>} */ (rec)) } catch (_) { continue }
221
298
  if (r.type !== W.TYPE_HELLO || W.decodeText(r.body) !== p.token) continue
222
299
  p.central = centralId
223
- p.chunk = this.adapter.chunkFor(centralId)
300
+ p.chunk = /** @type {BluetoothAdapter} */ (this.adapter).chunkFor(centralId)
224
301
  p.recvCtr = 1
225
302
  c.peer = p
226
303
  this._sendRecord(p, W.TYPE_HELLO, W.encodeText(this.getSelfToken() || ''))
@@ -242,6 +319,7 @@ export class BluetoothManager {
242
319
  }
243
320
  }
244
321
 
322
+ /** @param {string} centralId */
245
323
  _onCentralGone (centralId) {
246
324
  const c = this.centrals.get(centralId)
247
325
  this.centrals.delete(centralId)
@@ -250,12 +328,13 @@ export class BluetoothManager {
250
328
 
251
329
  // ---------- registros ----------
252
330
 
331
+ /** @param {BlePeer} p @param {Uint8Array} rec */
253
332
  async _onRecord (p, rec) {
254
333
  if (p.state === 'closed' || p.state === 'failed') return
255
334
  const dir = p.role === 'central' ? W.DIR_TO_CENTRAL : W.DIR_TO_PERIPHERAL
256
335
  let r
257
336
  try {
258
- r = await W.openRecord(p.key, dir, p.recvCtr, rec)
337
+ r = await W.openRecord(/** @type {CryptoKey} */ (p.key), dir, p.recvCtr, /** @type {Uint8Array<ArrayBuffer>} */ (rec))
259
338
  p.recvCtr++
260
339
  } catch (_) {
261
340
  this.emit('error', { type: 'bluetooth_bad_record', peer: p.token })
@@ -279,32 +358,38 @@ export class BluetoothManager {
279
358
  }
280
359
  }
281
360
 
361
+ /** @param {BlePeer} p @param {number} type @param {Uint8Array} body */
282
362
  _sendRecord (p, type, body) {
283
363
  const dir = p.role === 'central' ? W.DIR_TO_PERIPHERAL : W.DIR_TO_CENTRAL
284
364
  p.pending += body.length
285
365
  p.queue = p.queue.then(async () => {
286
366
  if (p.state === 'closed' || p.state === 'failed') return
287
- const rec = await W.sealRecord(p.key, dir, p.sendCtr++, type, body)
367
+ const rec = await W.sealRecord(/** @type {CryptoKey} */ (p.key), dir, p.sendCtr++, type, body)
288
368
  for (const chunk of W.toChunks(rec, p.chunk, p.role === 'central' ? null : p.tag)) {
289
- if (p.role === 'central') await p.link.write(chunk)
290
- else await this.adapter.notify(p.central, chunk)
369
+ if (p.role === 'central') await /** @type {Link} */ (p.link).write(chunk)
370
+ else await /** @type {BluetoothAdapter} */ (this.adapter).notify(/** @type {string} */ (p.central), chunk)
291
371
  }
292
372
  }).catch(() => this._closed(p)).finally(() => { p.pending -= body.length })
293
373
  }
294
374
 
295
375
  // ---------- envío ----------
296
376
 
377
+ /** @param {string} to @param {string | Uint8Array} wire @returns {boolean} */
297
378
  trySend (to, wire) {
298
379
  const p = this.peers.get(to)
299
380
  if (!p || p.state !== 'open') return false
381
+ const body = typeof wire === 'string' ? W.encodeText(wire) : wire
300
382
  const isText = typeof wire === 'string'
301
- const body = isText ? W.encodeText(wire) : wire
302
383
  this._sendRecord(p, isText ? W.TYPE_TEXT : W.TYPE_BINARY, body)
303
384
  this.count?.('out', to, body.length, 'bluetooth')
304
385
  return true
305
386
  }
306
387
 
307
- /** Como `trySend`, esperando a que baje lo pendiente: para las partes de un mensaje grande. */
388
+ /**
389
+ * Como `trySend`, esperando a que baje lo pendiente: para las partes de un mensaje grande.
390
+ * @param {string} to @param {string | Uint8Array} wire @param {number} [highWater]
391
+ * @returns {Promise<boolean>}
392
+ */
308
393
  async sendDirect (to, wire, highWater = 256 * 1024) {
309
394
  const p = this.peers.get(to)
310
395
  if (!p || p.state !== 'open') return false
@@ -315,9 +400,12 @@ export class BluetoothManager {
315
400
  return this.trySend(to, wire)
316
401
  }
317
402
 
403
+ /** @param {string} to @returns {boolean} */
318
404
  isOpen (to) { return this.peers.get(to)?.state === 'open' }
319
405
 
406
+ /** @returns {Map<string, 'bluetooth' | 'failed' | 'connecting'>} */
320
407
  describe () {
408
+ /** @type {Map<string, 'bluetooth' | 'failed' | 'connecting'>} */
321
409
  const out = new Map()
322
410
  for (const p of this.peers.values()) {
323
411
  out.set(p.token, p.state === 'open' ? 'bluetooth' : p.state === 'failed' ? 'failed' : 'connecting')
@@ -325,6 +413,7 @@ export class BluetoothManager {
325
413
  return out
326
414
  }
327
415
 
416
+ /** @param {string} to */
328
417
  closePeer (to) {
329
418
  const p = this.peers.get(to)
330
419
  if (p) this._closed(p)
@@ -337,6 +426,9 @@ export class BluetoothManager {
337
426
  /**
338
427
  * Pone `{kind, data}` en `beacon` (docs/bluetooth.md §3) hasta que se llame a lo que
339
428
  * devuelve. Lanza `no-bluetooth` si aquí no hay Bluetooth: quien anuncia tiene que saberlo.
429
+ *
430
+ * @param {string} kind @param {string} data
431
+ * @returns {() => void}
340
432
  */
341
433
  announce (kind, data) {
342
434
  if (!this.adapter) throw Object.assign(new Error('bluetooth: not available here'), { code: 'no-bluetooth' })
@@ -349,18 +441,23 @@ export class BluetoothManager {
349
441
  * Busca en el aire durante `timeoutMs` lo que otros anuncian con `kind`. No necesita el
350
442
  * proxio. `onFound` avisa de cada uno según aparece; la promesa devuelve todos.
351
443
  * @param {{ kind: string, timeoutMs?: number, onFound?: (b: {kind: string, data: string}) => void }} opts
444
+ * @returns {Promise<Array<{ kind: string, data: string }>>}
352
445
  */
353
446
  async discover ({ kind, timeoutMs = 8000, onFound }) {
354
447
  if (!this.adapter) throw Object.assign(new Error('bluetooth: not available here'), { code: 'no-bluetooth' })
448
+ /** @type {Array<{ kind: string, data: string }>} */
355
449
  const found = []
450
+ /** @type {Set<string>} */
356
451
  const done = new Set()
452
+ /** @param {Device} dev */
357
453
  const listener = (dev) => {
358
454
  if (done.has(dev.id)) return
359
455
  done.add(dev.id)
360
456
  this._withConnectLock(async () => {
457
+ /** @type {Link | null} */
361
458
  let link = null
362
459
  try {
363
- link = await this.adapter.connect(dev)
460
+ link = await /** @type {BluetoothAdapter} */ (this.adapter).connect(dev)
364
461
  const b = W.decodeBeacon(await link.read(W.BEACON_UUID))
365
462
  if (b && b.kind === kind && !found.some((f) => f.data === b.data)) {
366
463
  found.push(b)
@@ -382,7 +479,9 @@ export class BluetoothManager {
382
479
 
383
480
  // ---------- internos ----------
384
481
 
482
+ /** @param {string} token @returns {BlePeer} */
385
483
  _newPeer (token) {
484
+ /** @type {BlePeer} */
386
485
  const p = {
387
486
  token, state: 'new', role: null, eph: null, key: null, theirBid: null, myBid: null, tag: null,
388
487
  link: null, central: null, chunk: 20, sendCtr: 0, recvCtr: 0, pending: 0,
@@ -392,12 +491,15 @@ export class BluetoothManager {
392
491
  return p
393
492
  }
394
493
 
494
+ /** @param {BlePeer} p @param {number} ms */
395
495
  _timer (p, ms) {
396
496
  if (p.timer) clearTimeout(p.timer)
397
- p.timer = setTimeout(() => { if (p.state !== 'open') this._fail(p) }, ms)
398
- p.timer.unref?.()
497
+ const t = setTimeout(() => { if (p.state !== 'open') this._fail(p) }, ms)
498
+ p.timer = t
499
+ t.unref?.()
399
500
  }
400
501
 
502
+ /** @param {BlePeer} p */
401
503
  _open (p) {
402
504
  if (p.timer) clearTimeout(p.timer)
403
505
  p.timer = null
@@ -405,6 +507,7 @@ export class BluetoothManager {
405
507
  this.emit('bluetooth_open', p.token)
406
508
  }
407
509
 
510
+ /** @param {BlePeer} p */
408
511
  _fail (p) {
409
512
  if (p.state === 'closed') return
410
513
  this._release(p)
@@ -412,6 +515,7 @@ export class BluetoothManager {
412
515
  p.failedAt = Date.now()
413
516
  }
414
517
 
518
+ /** @param {BlePeer} p */
415
519
  _closed (p) {
416
520
  if (p.state === 'closed') return
417
521
  const wasOpen = p.state === 'open'
@@ -422,11 +526,13 @@ export class BluetoothManager {
422
526
  }
423
527
 
424
528
  /** Quita una negociación sin avisar: la reemplaza otra del mismo token. */
529
+ /** @param {BlePeer} p */
425
530
  _drop (p) {
426
531
  this._release(p)
427
532
  p.state = 'closed'
428
533
  }
429
534
 
535
+ /** @param {BlePeer} p */
430
536
  _release (p) {
431
537
  if (p.timer) clearTimeout(p.timer)
432
538
  p.timer = null
@@ -444,12 +550,17 @@ export class BluetoothManager {
444
550
  }
445
551
  }
446
552
 
553
+ /**
554
+ * @param {() => Promise<void>} fn
555
+ * @returns {Promise<void>}
556
+ */
447
557
  _withConnectLock (fn) {
448
558
  const run = this._connectLock.then(fn, fn)
449
559
  this._connectLock = run.catch(() => {})
450
560
  return run
451
561
  }
452
562
 
563
+ /** @param {(dev: Device) => void} listener */
453
564
  async _addScan (listener) {
454
565
  this._scanListeners.add(listener)
455
566
  if (this._stopScan) return
@@ -457,7 +568,7 @@ export class BluetoothManager {
457
568
  // Una búsqueda que se está parando todavía ocupa el adaptador: BlueZ contesta `InProgress`
458
569
  // a la siguiente si no se espera a que acabe (dos `discover` seguidos).
459
570
  const stopping = this._scanStopping || Promise.resolve()
460
- this._scanStarting = stopping.then(() => this.adapter.scan((dev) => {
571
+ this._scanStarting = stopping.then(() => /** @type {BluetoothAdapter} */ (this.adapter).scan((dev) => {
461
572
  for (const l of [...this._scanListeners]) l(dev)
462
573
  })).then((stop) => {
463
574
  this._stopScan = stop
@@ -468,6 +579,7 @@ export class BluetoothManager {
468
579
  await this._scanStarting
469
580
  }
470
581
 
582
+ /** @param {((dev: Device) => void) | null} listener */
471
583
  _removeScan (listener) {
472
584
  if (listener) this._scanListeners.delete(listener)
473
585
  if (this._scanListeners.size || !this._stopScan) return