@dotrino/identity 0.126.0 → 0.126.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/identity",
3
- "version": "0.126.0",
3
+ "version": "0.126.1",
4
4
  "description": "Identidad y rating de usuarios compartidos entre apps de Dotrino (vault iframe + postMessage)",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -1,4 +1,4 @@
1
- Copia vendorizada de @dotrino/proxy-client@0.39.0 (dotrino-proxy-client/src/{binpack,canonical,client,encpub,errors,index,parts,sealing,signature,stats-log,stats,webrtc}.js).
1
+ Copia vendorizada de @dotrino/proxy-client@0.41.0 (dotrino-proxy-client/src/{binpack,ble/manager,ble/wire,canonical,client,encpub,errors,index,parts,sealing,signature,stats-log,stats,webrtc}.js).
2
2
  NO se edita a mano: la escribe `node vendor.mjs` y la vigila test/vendor-up-to-date.test.mjs.
3
3
  sealing.js resuelve @dotrino/identity/content de forma PEREZOSA (= ../../content.js
4
4
  por el import map): solo se carga si de verdad se sella algo.
@@ -0,0 +1,475 @@
1
+ /**
2
+ * EL ESCALÓN DEL BLUETOOTH (docs/bluetooth.md): va después de WebRTC directo y antes de
3
+ * TURN. Misma forma que `WebRTCManager`, así el cliente los trata igual: la señalización
4
+ * entra por `handleIncoming`, se sube con `upgrade`, se manda con `trySend` / `sendDirect`.
5
+ *
6
+ * No toca el Bluetooth: habla con un ADAPTADOR, que es lo único que cambia de una
7
+ * plataforma a otra.
8
+ *
9
+ * start(server) server = { hello(): Uint8Array, beacon(): Uint8Array,
10
+ * onWrite(centralId, bytes), onDisconnect(centralId) }
11
+ * empieza a anunciar y a servir el GATT
12
+ * notify(centralId, bytes) Promise: un valor de `tx` a ese central
13
+ * chunkFor(centralId) bytes por valor hacia ese central (MTU − 3)
14
+ * drop(centralId) Promise: desconecta a ese central
15
+ * scan(onFound) Promise<stop()>: avisa de cada periférico de Dotrino visto ({ id })
16
+ * connect(device) Promise<Link>
17
+ * Link = { chunk, read(uuid), write(bytes), subscribe(onValue), close(), onClose(cb) }
18
+ * stop()
19
+ *
20
+ * Lo implementan `bluez.js` (Linux), el aire falso de las pruebas y, si hiciera falta, un
21
+ * puente nativo.
22
+ */
23
+
24
+ import * as W from './wire.js'
25
+
26
+ const FAIL_RETRY_MS = 60_000
27
+ const SEEN_TTL_MS = 60_000
28
+
29
+ export class BluetoothManager {
30
+ /**
31
+ * @param {object} opts
32
+ * @param {() => string|null} opts.getSelfToken
33
+ * @param {(to: string, payload: any) => void} opts.signalSend trama por el proxio
34
+ * @param {(from: string, parsed: any, meta: any) => void} opts.deliverMessage
35
+ * @param {(event: string, ...args: any[]) => void} opts.emit
36
+ * @param {(dir: 'in'|'out', token: string, bytes: number, route: 'bluetooth') => void} [opts.count]
37
+ */
38
+ constructor (opts) {
39
+ this.acceptFrom = null
40
+ this.getSelfToken = opts.getSelfToken
41
+ this.signalSend = opts.signalSend
42
+ this.deliverMessage = opts.deliverMessage
43
+ this.emit = opts.emit
44
+ this.count = typeof opts.count === 'function' ? opts.count : null
45
+ this.adapter = null
46
+ this.bid = null
47
+ 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 }
52
+ this._probing = new Set()
53
+ this._scanListeners = new Set()
54
+ this._stopScan = null
55
+ this._scanStarting = null
56
+ this._connectLock = Promise.resolve()
57
+ this._rotate = null
58
+ }
59
+
60
+ /** Hay Bluetooth en marcha en este proceso. */
61
+ get available () { return !!this.adapter }
62
+
63
+ async start (adapter) {
64
+ if (this.adapter) return
65
+ this.bid = W.randomBid()
66
+ await adapter.start({
67
+ hello: () => W.encodeHello(this.bid),
68
+ beacon: () => this.beacon,
69
+ onWrite: (centralId, bytes) => this._onWrite(centralId, bytes),
70
+ onDisconnect: (centralId) => this._onCentralGone(centralId),
71
+ })
72
+ this.adapter = adapter
73
+ this._rotate = setInterval(() => { this.bid = W.randomBid() }, W.BID_ROTATE_MS)
74
+ this._rotate.unref?.()
75
+ }
76
+
77
+ async stop () {
78
+ this.closeAll()
79
+ if (this._rotate) clearInterval(this._rotate)
80
+ this._rotate = null
81
+ const a = this.adapter
82
+ this.adapter = null
83
+ if (this._stopScan) { const s = this._stopScan; this._stopScan = null; await s().catch(() => {}) }
84
+ if (a) await a.stop()
85
+ }
86
+
87
+ // ---------- señalización ----------
88
+
89
+ /** True si era una trama de este escalón (se consume aunque no haya Bluetooth). */
90
+ handleIncoming (from, parsed) {
91
+ if (!parsed || typeof parsed !== 'object' || parsed.t !== W.BLE_TAG) return false
92
+ if (this.acceptFrom && !this.acceptFrom(from)) return true
93
+ if (!this.adapter) return true
94
+ if (typeof parsed.bid !== 'string' || typeof parsed.epub !== 'string') return true
95
+ this._handleSignal(from, parsed).catch((e) => {
96
+ this.emit('error', { type: 'bluetooth_signal', error: e, peer: from })
97
+ const p = this.peers.get(from)
98
+ if (p) this._fail(p)
99
+ })
100
+ return true
101
+ }
102
+
103
+ /** Empieza a negociar con `token` si no hay nada en curso. Sin esperas y sin errores. */
104
+ upgrade (token) {
105
+ if (!this.adapter || !this.getSelfToken()) return
106
+ const p = this.peers.get(token)
107
+ if (p && p.state !== 'failed') return
108
+ if (p && Date.now() - p.failedAt < FAIL_RETRY_MS) return
109
+ this._offer(token).catch((e) => this.emit('error', { type: 'bluetooth_offer', error: e, peer: token }))
110
+ }
111
+
112
+ async _offer (token) {
113
+ const p = this._newPeer(token)
114
+ p.eph = await W.makeEphemeral()
115
+ p.state = 'offered'
116
+ p.myBid = this.bid
117
+ this._timer(p, W.ANSWER_TIMEOUT_MS)
118
+ this.signalSend(token, { t: W.BLE_TAG, kind: 'offer', bid: p.myBid, epub: p.eph.epub })
119
+ }
120
+
121
+ async _handleSignal (from, msg) {
122
+ let p = this.peers.get(from)
123
+ if (msg.kind === 'offer') {
124
+ if (p && p.state === 'offered') {
125
+ // Ofertas cruzadas: la del otro sirve de respuesta. El ECDH es simétrico, así que
126
+ // los dos llegan a la misma llave sin que nadie conteste.
127
+ } else {
128
+ if (p) this._drop(p)
129
+ p = this._newPeer(from)
130
+ p.eph = await W.makeEphemeral()
131
+ p.myBid = this.bid
132
+ this.signalSend(from, { t: W.BLE_TAG, kind: 'answer', bid: p.myBid, epub: p.eph.epub })
133
+ }
134
+ } else if (msg.kind === 'answer') {
135
+ if (!p || p.state !== 'offered') return
136
+ } else {
137
+ return
138
+ }
139
+ const self = this.getSelfToken()
140
+ if (!self) return this._fail(p)
141
+ p.key = await W.deriveKey(p.eph.privateKey, msg.epub, self, from)
142
+ p.eph = null
143
+ p.theirBid = msg.bid
144
+ p.role = self > from ? 'central' : 'peripheral'
145
+ // 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)
147
+ p.state = 'keyed'
148
+ this._timer(p, W.FIND_TIMEOUT_MS)
149
+ if (p.role === 'peripheral') this._retryHellos()
150
+ if (p.role === 'central') {
151
+ this.wanted.set(p.theirBid, p)
152
+ this._addScan(this._onFoundForPeers).catch((e) => {
153
+ this.emit('error', { type: 'bluetooth_scan', error: e })
154
+ this._fail(p)
155
+ })
156
+ }
157
+ }
158
+
159
+ // ---------- lado central ----------
160
+
161
+ _onFoundForPeers = (dev) => {
162
+ if (!this.wanted.size || this._probing.has(dev.id)) return
163
+ const seen = this._seen.get(dev.id)
164
+ if (seen && Date.now() - seen.at < SEEN_TTL_MS && !this.wanted.has(seen.bid)) return
165
+ this._probing.add(dev.id)
166
+ this._withConnectLock(async () => {
167
+ let link = null
168
+ try {
169
+ link = await this.adapter.connect(dev)
170
+ const bid = W.decodeHello(await link.read(W.HELLO_UUID))
171
+ this._seen.set(dev.id, { bid, at: Date.now() })
172
+ const p = bid ? this.wanted.get(bid) : null
173
+ if (!p || p.state !== 'keyed') { await link.close(); return }
174
+ this.wanted.delete(bid)
175
+ if (!this.wanted.size) this._removeScan(this._onFoundForPeers)
176
+ await this._attachLink(p, link)
177
+ link = null // ya es del canal: se cierra con él
178
+ } catch (e) {
179
+ // Se sigue buscando, pero se DICE: es un aparato de Dotrino (anuncia el servicio) que no
180
+ // 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 })
182
+ if (link) await link.close().catch(() => {})
183
+ } finally {
184
+ this._probing.delete(dev.id)
185
+ }
186
+ })
187
+ }
188
+
189
+ async _attachLink (p, link) {
190
+ p.link = link
191
+ p.chunk = link.chunk
192
+ link.onClose(() => this._closed(p))
193
+ const rx = new W.Reassembler(W.TAG_BYTES)
194
+ await link.subscribe((chunk) => { if (W.hasTag(chunk, p.tag)) this._onChunk(p, rx, chunk) })
195
+ this._sendRecord(p, W.TYPE_HELLO, W.encodeText(this.getSelfToken() || ''))
196
+ }
197
+
198
+ _onChunk (p, rx, chunk) {
199
+ let rec
200
+ try { rec = rx.push(chunk) } catch (_) { return this._closed(p) }
201
+ if (rec) p.recvChain = p.recvChain.then(() => this._onRecord(p, rec))
202
+ }
203
+
204
+ // ---------- lado periférico ----------
205
+
206
+ _onWrite (centralId, bytes) {
207
+ let c = this.centrals.get(centralId)
208
+ if (!c) { c = { rx: new W.Reassembler(), peer: null, pendingHello: null, chain: Promise.resolve() }; this.centrals.set(centralId, c) }
209
+ let rec
210
+ try { rec = c.rx.push(bytes) } catch (_) { this.centrals.delete(centralId); if (c.peer) this._closed(c.peer); return }
211
+ if (!rec) return
212
+ c.chain = c.chain.then(() => c.peer ? this._onRecord(c.peer, rec) : this._identify(centralId, c, rec))
213
+ }
214
+
215
+ /** Quién se conectó: la llave que descifra su saludo dice de qué negociación es. */
216
+ async _identify (centralId, c, rec) {
217
+ for (const p of this.peers.values()) {
218
+ if (p.role !== 'peripheral' || p.state !== 'keyed' || p.central != null) continue
219
+ let r
220
+ try { r = await W.openRecord(p.key, W.DIR_TO_PERIPHERAL, 0, rec) } catch (_) { continue }
221
+ if (r.type !== W.TYPE_HELLO || W.decodeText(r.body) !== p.token) continue
222
+ p.central = centralId
223
+ p.chunk = this.adapter.chunkFor(centralId)
224
+ p.recvCtr = 1
225
+ c.peer = p
226
+ this._sendRecord(p, W.TYPE_HELLO, W.encodeText(this.getSelfToken() || ''))
227
+ c.pendingHello = null
228
+ this._open(p)
229
+ return
230
+ }
231
+ // Nadie lo esperaba TODAVÍA: el central puede escribir antes de que aquí termine de
232
+ // calcularse la llave. Se guarda el saludo y se prueba otra vez cuando una negociación
233
+ // quede lista (`_retryHellos`). A quien no se negoció no se le contesta nada.
234
+ c.pendingHello = rec
235
+ }
236
+
237
+ _retryHellos () {
238
+ for (const [id, c] of this.centrals) {
239
+ if (c.peer || !c.pendingHello) continue
240
+ const rec = c.pendingHello
241
+ c.chain = c.chain.then(() => c.peer ? null : this._identify(id, c, rec))
242
+ }
243
+ }
244
+
245
+ _onCentralGone (centralId) {
246
+ const c = this.centrals.get(centralId)
247
+ this.centrals.delete(centralId)
248
+ if (c && c.peer) this._closed(c.peer)
249
+ }
250
+
251
+ // ---------- registros ----------
252
+
253
+ async _onRecord (p, rec) {
254
+ if (p.state === 'closed' || p.state === 'failed') return
255
+ const dir = p.role === 'central' ? W.DIR_TO_CENTRAL : W.DIR_TO_PERIPHERAL
256
+ let r
257
+ try {
258
+ r = await W.openRecord(p.key, dir, p.recvCtr, rec)
259
+ p.recvCtr++
260
+ } catch (_) {
261
+ this.emit('error', { type: 'bluetooth_bad_record', peer: p.token })
262
+ return this._closed(p)
263
+ }
264
+ if (r.type === W.TYPE_HELLO) {
265
+ if (W.decodeText(r.body) !== p.token) return this._closed(p)
266
+ if (p.role === 'central') this._open(p)
267
+ return
268
+ }
269
+ if (p.state !== 'open') return this._closed(p)
270
+ this.count?.('in', p.token, r.body.length, 'bluetooth')
271
+ if (r.type === W.TYPE_TEXT) {
272
+ const raw = W.decodeText(r.body)
273
+ let parsed = null
274
+ try { parsed = JSON.parse(raw) } catch (_) {}
275
+ this.deliverMessage(p.token, parsed ?? raw, { raw, timestamp: Date.now(), via: 'bluetooth' })
276
+ } else if (r.type === W.TYPE_BINARY) {
277
+ const raw = new Uint8Array(r.body)
278
+ this.deliverMessage(p.token, raw, { raw, timestamp: Date.now(), via: 'bluetooth' })
279
+ }
280
+ }
281
+
282
+ _sendRecord (p, type, body) {
283
+ const dir = p.role === 'central' ? W.DIR_TO_PERIPHERAL : W.DIR_TO_CENTRAL
284
+ p.pending += body.length
285
+ p.queue = p.queue.then(async () => {
286
+ if (p.state === 'closed' || p.state === 'failed') return
287
+ const rec = await W.sealRecord(p.key, dir, p.sendCtr++, type, body)
288
+ 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)
291
+ }
292
+ }).catch(() => this._closed(p)).finally(() => { p.pending -= body.length })
293
+ }
294
+
295
+ // ---------- envío ----------
296
+
297
+ trySend (to, wire) {
298
+ const p = this.peers.get(to)
299
+ if (!p || p.state !== 'open') return false
300
+ const isText = typeof wire === 'string'
301
+ const body = isText ? W.encodeText(wire) : wire
302
+ this._sendRecord(p, isText ? W.TYPE_TEXT : W.TYPE_BINARY, body)
303
+ this.count?.('out', to, body.length, 'bluetooth')
304
+ return true
305
+ }
306
+
307
+ /** Como `trySend`, esperando a que baje lo pendiente: para las partes de un mensaje grande. */
308
+ async sendDirect (to, wire, highWater = 256 * 1024) {
309
+ const p = this.peers.get(to)
310
+ if (!p || p.state !== 'open') return false
311
+ while (p.pending > highWater) {
312
+ await new Promise((r) => setTimeout(r, 15))
313
+ if (p.state !== 'open') return false
314
+ }
315
+ return this.trySend(to, wire)
316
+ }
317
+
318
+ isOpen (to) { return this.peers.get(to)?.state === 'open' }
319
+
320
+ describe () {
321
+ const out = new Map()
322
+ for (const p of this.peers.values()) {
323
+ out.set(p.token, p.state === 'open' ? 'bluetooth' : p.state === 'failed' ? 'failed' : 'connecting')
324
+ }
325
+ return out
326
+ }
327
+
328
+ closePeer (to) {
329
+ const p = this.peers.get(to)
330
+ if (p) this._closed(p)
331
+ }
332
+
333
+ closeAll () { for (const p of [...this.peers.values()]) this._closed(p) }
334
+
335
+ // ---------- anunciar y descubrir ----------
336
+
337
+ /**
338
+ * Pone `{kind, data}` en `beacon` (docs/bluetooth.md §3) hasta que se llame a lo que
339
+ * devuelve. Lanza `no-bluetooth` si aquí no hay Bluetooth: quien anuncia tiene que saberlo.
340
+ */
341
+ announce (kind, data) {
342
+ if (!this.adapter) throw Object.assign(new Error('bluetooth: not available here'), { code: 'no-bluetooth' })
343
+ const b = W.encodeBeacon(kind, data)
344
+ this.beacon = b
345
+ return () => { if (this.beacon === b) this.beacon = new Uint8Array(0) }
346
+ }
347
+
348
+ /**
349
+ * Busca en el aire durante `timeoutMs` lo que otros anuncian con `kind`. No necesita el
350
+ * proxio. `onFound` avisa de cada uno según aparece; la promesa devuelve todos.
351
+ * @param {{ kind: string, timeoutMs?: number, onFound?: (b: {kind: string, data: string}) => void }} opts
352
+ */
353
+ async discover ({ kind, timeoutMs = 8000, onFound }) {
354
+ if (!this.adapter) throw Object.assign(new Error('bluetooth: not available here'), { code: 'no-bluetooth' })
355
+ const found = []
356
+ const done = new Set()
357
+ const listener = (dev) => {
358
+ if (done.has(dev.id)) return
359
+ done.add(dev.id)
360
+ this._withConnectLock(async () => {
361
+ let link = null
362
+ try {
363
+ link = await this.adapter.connect(dev)
364
+ const b = W.decodeBeacon(await link.read(W.BEACON_UUID))
365
+ if (b && b.kind === kind && !found.some((f) => f.data === b.data)) {
366
+ found.push(b)
367
+ try { onFound?.(b) } catch (_) {}
368
+ }
369
+ } catch (_) {
370
+ // Uno que no se deja leer no anuncia nada para nosotros.
371
+ } finally {
372
+ if (link) await link.close().catch(() => {})
373
+ }
374
+ })
375
+ }
376
+ await this._addScan(listener)
377
+ await new Promise((r) => setTimeout(r, timeoutMs))
378
+ this._removeScan(listener)
379
+ await this._connectLock
380
+ return found
381
+ }
382
+
383
+ // ---------- internos ----------
384
+
385
+ _newPeer (token) {
386
+ const p = {
387
+ token, state: 'new', role: null, eph: null, key: null, theirBid: null, myBid: null, tag: null,
388
+ link: null, central: null, chunk: 20, sendCtr: 0, recvCtr: 0, pending: 0,
389
+ queue: Promise.resolve(), recvChain: Promise.resolve(), timer: null, failedAt: 0,
390
+ }
391
+ this.peers.set(token, p)
392
+ return p
393
+ }
394
+
395
+ _timer (p, ms) {
396
+ if (p.timer) clearTimeout(p.timer)
397
+ p.timer = setTimeout(() => { if (p.state !== 'open') this._fail(p) }, ms)
398
+ p.timer.unref?.()
399
+ }
400
+
401
+ _open (p) {
402
+ if (p.timer) clearTimeout(p.timer)
403
+ p.timer = null
404
+ p.state = 'open'
405
+ this.emit('bluetooth_open', p.token)
406
+ }
407
+
408
+ _fail (p) {
409
+ if (p.state === 'closed') return
410
+ this._release(p)
411
+ p.state = 'failed'
412
+ p.failedAt = Date.now()
413
+ }
414
+
415
+ _closed (p) {
416
+ if (p.state === 'closed') return
417
+ const wasOpen = p.state === 'open'
418
+ this._release(p)
419
+ p.state = 'closed'
420
+ if (this.peers.get(p.token) === p) this.peers.delete(p.token)
421
+ if (wasOpen) this.emit('bluetooth_close', p.token)
422
+ }
423
+
424
+ /** Quita una negociación sin avisar: la reemplaza otra del mismo token. */
425
+ _drop (p) {
426
+ this._release(p)
427
+ p.state = 'closed'
428
+ }
429
+
430
+ _release (p) {
431
+ if (p.timer) clearTimeout(p.timer)
432
+ p.timer = null
433
+ if (p.theirBid && this.wanted.get(p.theirBid) === p) {
434
+ this.wanted.delete(p.theirBid)
435
+ if (!this.wanted.size) this._removeScan(this._onFoundForPeers)
436
+ }
437
+ if (p.link) { const l = p.link; p.link = null; l.close().catch(() => {}) }
438
+ if (p.central != null) {
439
+ const id = p.central
440
+ const c = this.centrals.get(id)
441
+ if (c && c.peer === p) c.peer = null
442
+ p.central = null
443
+ this.adapter?.drop(id).catch(() => {})
444
+ }
445
+ }
446
+
447
+ _withConnectLock (fn) {
448
+ const run = this._connectLock.then(fn, fn)
449
+ this._connectLock = run.catch(() => {})
450
+ return run
451
+ }
452
+
453
+ async _addScan (listener) {
454
+ this._scanListeners.add(listener)
455
+ if (this._stopScan) return
456
+ if (!this._scanStarting) {
457
+ this._scanStarting = this.adapter.scan((dev) => {
458
+ for (const l of [...this._scanListeners]) l(dev)
459
+ }).then((stop) => {
460
+ this._stopScan = stop
461
+ this._scanStarting = null
462
+ if (!this._scanListeners.size) this._removeScan(null)
463
+ }, (e) => { this._scanStarting = null; throw e })
464
+ }
465
+ await this._scanStarting
466
+ }
467
+
468
+ _removeScan (listener) {
469
+ if (listener) this._scanListeners.delete(listener)
470
+ if (this._scanListeners.size || !this._stopScan) return
471
+ const stop = this._stopScan
472
+ this._stopScan = null
473
+ stop().catch(() => {})
474
+ }
475
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * EL CABLE DEL BLUETOOTH (docs/bluetooth.md). Módulo PURO: sin red, sin Bluetooth, solo
3
+ * WebCrypto. Lo que aquí se decide lo cumplen igual los puertos de `dotrino-native`: si
4
+ * cambia un byte, cambia en los tres.
5
+ */
6
+
7
+ const BASE = '0be25149-664d-4d28-b496-3ca98a63fb'
8
+ export const SERVICE_UUID = BASE + '00'
9
+ export const HELLO_UUID = BASE + '01'
10
+ export const BEACON_UUID = BASE + '02'
11
+ export const RX_UUID = BASE + '03'
12
+ export const TX_UUID = BASE + '04'
13
+
14
+ /** Trama de control por el proxio, hermana de la de WebRTC (`__cc_rtc__`). */
15
+ export const BLE_TAG = '__cc_ble__'
16
+
17
+ export const BID_BYTES = 8
18
+ export const BID_ROTATE_MS = 15 * 60 * 1000
19
+ export const BEACON_MAX_BYTES = 512
20
+ export const RECORD_MAX_BYTES = 1024 * 1024
21
+ export const ANSWER_TIMEOUT_MS = 10_000
22
+ export const FIND_TIMEOUT_MS = 20_000
23
+
24
+ export const DIR_TO_PERIPHERAL = 0
25
+ export const DIR_TO_CENTRAL = 1
26
+
27
+ export const TYPE_TEXT = 0
28
+ export const TYPE_BINARY = 1
29
+ export const TYPE_HELLO = 2
30
+
31
+ const LAST = 0x01
32
+ const enc = new TextEncoder()
33
+ const dec = new TextDecoder()
34
+
35
+ function subtle () {
36
+ const s = globalThis.crypto?.subtle
37
+ if (!s) throw Object.assign(new Error('bluetooth: WebCrypto is not available here'), { code: 'no-webcrypto' })
38
+ return s
39
+ }
40
+
41
+ export function b64u (bytes) {
42
+ let s = ''
43
+ for (const b of bytes) s += String.fromCharCode(b)
44
+ return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
45
+ }
46
+
47
+ export function unb64u (str) {
48
+ const s = String(str).replace(/-/g, '+').replace(/_/g, '/')
49
+ const bin = atob(s + '='.repeat((4 - s.length % 4) % 4))
50
+ const out = new Uint8Array(bin.length)
51
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
52
+ return out
53
+ }
54
+
55
+ export function randomBid () {
56
+ return b64u(globalThis.crypto.getRandomValues(new Uint8Array(BID_BYTES)))
57
+ }
58
+
59
+ // ---------- características de solo lectura ----------
60
+
61
+ export function encodeHello (bid) { return enc.encode(JSON.stringify({ v: 1, bid })) }
62
+
63
+ /** El `bid` de un `hello` leído, o null si no es de esta versión. */
64
+ export function decodeHello (bytes) {
65
+ try {
66
+ const o = JSON.parse(dec.decode(bytes))
67
+ return o && o.v === 1 && typeof o.bid === 'string' ? o.bid : null
68
+ } catch (_) { return null }
69
+ }
70
+
71
+ export function encodeBeacon (kind, data) {
72
+ if (typeof kind !== 'string' || !kind || typeof data !== 'string') {
73
+ throw Object.assign(new Error('bluetooth: announce needs a kind and a string'), { code: 'bad-beacon' })
74
+ }
75
+ const bytes = enc.encode(JSON.stringify({ kind, data }))
76
+ if (bytes.length > BEACON_MAX_BYTES) {
77
+ throw Object.assign(new Error(`bluetooth: what is announced takes ${bytes.length} bytes; at most ${BEACON_MAX_BYTES}`), { code: 'beacon-too-big' })
78
+ }
79
+ return bytes
80
+ }
81
+
82
+ /** `{kind, data}` de un `beacon` leído, o null si está vacío o no se entiende. */
83
+ export function decodeBeacon (bytes) {
84
+ if (!bytes || !bytes.length) return null
85
+ try {
86
+ const o = JSON.parse(dec.decode(bytes))
87
+ return o && typeof o.kind === 'string' && typeof o.data === 'string' ? { kind: o.kind, data: o.data } : null
88
+ } catch (_) { return null }
89
+ }
90
+
91
+ // ---------- llave del canal ----------
92
+
93
+ export async function makeEphemeral () {
94
+ const kp = await subtle().generateKey({ name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits'])
95
+ const raw = new Uint8Array(await subtle().exportKey('raw', kp.publicKey))
96
+ return { privateKey: kp.privateKey, epub: b64u(raw) }
97
+ }
98
+
99
+ /** La llave AES del canal (docs/bluetooth.md §4). El orden de los tokens no depende de quién llama. */
100
+ export async function deriveKey (privateKey, theirEpub, tokenA, tokenB) {
101
+ const s = subtle()
102
+ const pub = await s.importKey('raw', unb64u(theirEpub), { name: 'ECDH', namedCurve: 'P-256' }, false, [])
103
+ const secret = await s.deriveBits({ name: 'ECDH', public: pub }, privateKey, 256)
104
+ const ikm = await s.importKey('raw', secret, 'HKDF', false, ['deriveKey'])
105
+ const [lo, hi] = tokenA < tokenB ? [tokenA, tokenB] : [tokenB, tokenA]
106
+ return s.deriveKey(
107
+ { name: 'HKDF', hash: 'SHA-256', salt: enc.encode(lo + '|' + hi), info: enc.encode('dotrino-ble-v1') },
108
+ ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'])
109
+ }
110
+
111
+ // ---------- registros ----------
112
+
113
+ function nonce (dir, counter) {
114
+ const n = new Uint8Array(12)
115
+ n[0] = dir
116
+ new DataView(n.buffer).setBigUint64(4, BigInt(counter))
117
+ return n
118
+ }
119
+
120
+ export async function sealRecord (key, dir, counter, type, body) {
121
+ const plain = new Uint8Array(1 + body.length)
122
+ plain[0] = type
123
+ plain.set(body, 1)
124
+ return new Uint8Array(await subtle().encrypt({ name: 'AES-GCM', iv: nonce(dir, counter) }, key, plain))
125
+ }
126
+
127
+ /** `{type, body}`, o lanza si no lo selló esa llave con ese contador. */
128
+ export async function openRecord (key, dir, counter, record) {
129
+ const plain = new Uint8Array(await subtle().decrypt({ name: 'AES-GCM', iv: nonce(dir, counter) }, key, record))
130
+ if (!plain.length) throw new Error('bluetooth: empty record')
131
+ return { type: plain[0], body: plain.subarray(1) }
132
+ }
133
+
134
+ export function encodeText (str) { return enc.encode(str) }
135
+ export function decodeText (bytes) { return dec.decode(bytes) }
136
+
137
+ // ---------- trozos ----------
138
+
139
+ export const TAG_BYTES = 4
140
+
141
+ /** La etiqueta de los trozos hacia un central: los 4 primeros bytes de su `bid` (docs §5). */
142
+ export function tagOf (bid) { return unb64u(bid).subarray(0, TAG_BYTES) }
143
+
144
+ /** True si el trozo de `tx` lleva esa etiqueta. */
145
+ export function hasTag (chunk, tag) {
146
+ if (chunk.length < 1 + TAG_BYTES) return false
147
+ for (let i = 0; i < TAG_BYTES; i++) if (chunk[1 + i] !== tag[i]) return false
148
+ return true
149
+ }
150
+
151
+ /**
152
+ * Parte un registro en trozos de `chunk` bytes de valor GATT, cabecera incluida. Con `tag`
153
+ * (hacia un central, `tx`) la cabecera lleva la etiqueta detrás de las banderas.
154
+ */
155
+ export function toChunks (record, chunk, tag = null) {
156
+ const head = 1 + (tag ? TAG_BYTES : 0)
157
+ const room = Math.max(1, chunk - head)
158
+ const out = []
159
+ let i = 0
160
+ do {
161
+ const part = record.subarray(i, i + room)
162
+ i += room
163
+ const c = new Uint8Array(head + part.length)
164
+ c[0] = i >= record.length ? LAST : 0
165
+ if (tag) c.set(tag, 1)
166
+ c.set(part, head)
167
+ out.push(c)
168
+ } while (i < record.length)
169
+ return out
170
+ }
171
+
172
+ /** Rearma registros de trozos que llegan en orden. `push` devuelve el registro entero, o null. */
173
+ export class Reassembler {
174
+ /** @param {number} [skip] bytes de cabecera tras las banderas (la etiqueta, en `tx`) */
175
+ constructor (skip = 0) { this.skip = skip; this.parts = []; this.size = 0 }
176
+ push (chunk) {
177
+ if (!chunk || chunk.length < 1 + this.skip) return null
178
+ const body = chunk.subarray(1 + this.skip)
179
+ this.size += body.length
180
+ if (this.size > RECORD_MAX_BYTES + 64) {
181
+ this.parts = []; this.size = 0
182
+ throw Object.assign(new Error('bluetooth: record larger than 1 MiB'), { code: 'record-too-big' })
183
+ }
184
+ this.parts.push(body)
185
+ if (!(chunk[0] & LAST)) return null
186
+ const out = new Uint8Array(this.size)
187
+ let o = 0
188
+ for (const p of this.parts) { out.set(p, o); o += p.length }
189
+ this.parts = []; this.size = 0
190
+ return out
191
+ }
192
+ }