@dotrino/identity 0.126.0 → 0.126.2
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 +1 -1
- package/vault/core.js +7 -2
- package/vault/vendor/proxy-client/VERSION.txt +1 -1
- package/vault/vendor/proxy-client/ble/manager.js +480 -0
- package/vault/vendor/proxy-client/ble/wire.js +239 -0
- package/vault/vendor/proxy-client/client.js +116 -9
- package/vault/vendor/proxy-client/index.js +1 -0
- package/vault/vendor/proxy-client/stats-log.js +1 -1
- package/vault/vendor/proxy-client/stats.js +4 -3
- package/vault/vendor/roadmap/VERSION.txt +1 -1
- package/vault/vendor/roadmap/manifests.js +31 -12
- package/vault/vendor/vault/VERSION.txt +3 -2
- package/vault/vendor/vault/core/libVersion.js +1 -1
- package/vault/vendor/vault/core/notices.js +23 -5
- package/vault/vendor/vault/core/transport.js +5 -2
- package/vault/vendor/vault/core/vault.js +43 -9
- package/vault/vendor/vault/enroll.js +47 -9
- package/vault/vendor/vault/invite.js +385 -0
package/package.json
CHANGED
package/vault/core.js
CHANGED
|
@@ -3322,7 +3322,8 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
3322
3322
|
// El acta es la nuestra: no hay nada que adoptar.
|
|
3323
3323
|
if ((!v?.cert || !device) && adminLink()?.self) {
|
|
3324
3324
|
const self = adminLink()
|
|
3325
|
-
|
|
3325
|
+
const res = await remoteDevices({ master: self.v.master, proxy: self.v.proxy, device: self.device, cert: self.v.cert, sinceSeq: loadActa()?.seq ?? 0 })
|
|
3326
|
+
return { ...res, acta: loadActa() }
|
|
3326
3327
|
}
|
|
3327
3328
|
if (!v?.cert || !device) {
|
|
3328
3329
|
// SOLO SE AVISA SI ES RARO. Un aparato que manda en su propia cuenta —o que aún no
|
|
@@ -3350,7 +3351,11 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
3350
3351
|
// comprobación de arriba corrió ANTES de tenerla, así que sin esto haría falta una
|
|
3351
3352
|
// segunda visita para estrenar un permiso recién concedido.
|
|
3352
3353
|
maybeRenewVaultCert()
|
|
3353
|
-
|
|
3354
|
+
// EL ACTA QUE SE DEVUELVE ES LA ADOPTADA, no la que llegó: la respuesta no trae
|
|
3355
|
+
// remitente comprobable, y quien llama decide con ella quién es de la cuenta (la
|
|
3356
|
+
// terminal, a qué máquina le abre una consola). Si la recibida no se pudo adoptar,
|
|
3357
|
+
// vale la que ya se tenía comprobada.
|
|
3358
|
+
return { ...res, acta: loadActa() }
|
|
3354
3359
|
} catch (e) { return handleVaultError(e) }
|
|
3355
3360
|
},
|
|
3356
3361
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Copia vendorizada de @dotrino/proxy-client@0.
|
|
1
|
+
Copia vendorizada de @dotrino/proxy-client@0.42.1 (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,480 @@
|
|
|
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
|
+
// Una búsqueda que se está parando todavía ocupa el adaptador: BlueZ contesta `InProgress`
|
|
458
|
+
// a la siguiente si no se espera a que acabe (dos `discover` seguidos).
|
|
459
|
+
const stopping = this._scanStopping || Promise.resolve()
|
|
460
|
+
this._scanStarting = stopping.then(() => this.adapter.scan((dev) => {
|
|
461
|
+
for (const l of [...this._scanListeners]) l(dev)
|
|
462
|
+
})).then((stop) => {
|
|
463
|
+
this._stopScan = stop
|
|
464
|
+
this._scanStarting = null
|
|
465
|
+
if (!this._scanListeners.size) this._removeScan(null)
|
|
466
|
+
}, (e) => { this._scanStarting = null; throw e })
|
|
467
|
+
}
|
|
468
|
+
await this._scanStarting
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
_removeScan (listener) {
|
|
472
|
+
if (listener) this._scanListeners.delete(listener)
|
|
473
|
+
if (this._scanListeners.size || !this._stopScan) return
|
|
474
|
+
const stop = this._stopScan
|
|
475
|
+
this._stopScan = null
|
|
476
|
+
const stopping = this._scanStopping = stop().catch(() => {}).then(() => {
|
|
477
|
+
if (this._scanStopping === stopping) this._scanStopping = null
|
|
478
|
+
})
|
|
479
|
+
}
|
|
480
|
+
}
|