@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.
@@ -2,6 +2,8 @@ import { buildSignedChannel, getPublicKeyJwk, signData, samePubkey } from './sig
2
2
  import { seal, open, isSealed, isBinSealed, BIN_SEALED, makeMessageKey, encryptBytes, decryptBytes } from './sealing.js'
3
3
  import { buildEncPubStatement, readEncPubStatement, isEncPub } from './encpub.js'
4
4
  import { WebRTCManager, RTC_TAG, DEFAULT_ICE_SERVERS, loadNodePeerConnection, resolvePeerConnection, pinTurnToIPv4 } from './webrtc.js'
5
+ import { BluetoothManager } from './ble/manager.js'
6
+ import { BLE_TAG } from './ble/wire.js'
5
7
  import { TrafficStats, utf8Length, registerTransport, unregisterTransport } from './stats.js'
6
8
  import { splitParts, splitBinParts, isPart, Reassembler, DIRECT_PART_CHARS, PROXY_PART_CHARS, QUEUE_MAX_CHARS, RELAY_MAX_CHARS, DIRECT_PART_BYTES, PROXY_PART_BYTES, QUEUE_MAX_BYTES, RELAY_MAX_BYTES } from './parts.js'
7
9
  import { pack, unpack, hasBinary, encodeFrame, decodeFrame } from './binpack.js'
@@ -217,6 +219,22 @@ export class WebSocketProxyClient {
217
219
  if (this._rtc && typeof options.acceptDirectFrom === 'function') {
218
220
  this._rtc.acceptFrom = options.acceptDirectFrom
219
221
  }
222
+
223
+ // EL BLUETOOTH (docs/bluetooth.md): escalón entre WebRTC directo y TURN. Se enciende a
224
+ // propósito, con `bluetooth: true` (en Node busca BlueZ, solo en Linux) o con un
225
+ // adaptador propio. Encenderlo hace que el aparato anuncie que está ahí, y eso no lo
226
+ // decide un script cualquiera que importe el pilar: lo decide quien monta el cliente.
227
+ this._bleOption = options.bluetooth || null
228
+ this._ble = this._bleOption ? new BluetoothManager({
229
+ getSelfToken: () => this.token,
230
+ signalSend: (to, payload) => this._proxySendOne(to, payload),
231
+ deliverMessage: (from, parsed, meta) => this._deliver(from, parsed, meta),
232
+ emit: (event, ...args) => this._emit(event, ...args),
233
+ count: (dir, token, bytes, route) =>
234
+ this._traffic.peer(dir, route, { token, pubkey: this._tokenPubkeys.get(token) || null }, bytes),
235
+ }) : null
236
+ if (this._ble && typeof options.acceptDirectFrom === 'function') this._ble.acceptFrom = options.acceptDirectFrom
237
+ this._bleStarting = null
220
238
  }
221
239
 
222
240
  // ---------- public API ----------
@@ -234,7 +252,55 @@ export class WebSocketProxyClient {
234
252
  await loadNodePeerConnection()
235
253
  }
236
254
 
255
+ /**
256
+ * ENCIENDE EL BLUETOOTH, una vez. Corre por detrás desde `connect()`: tiene que estar
257
+ * anunciando antes de que el otro quiera subir de escalón. Que no haya Bluetooth es el caso
258
+ * normal y no se dice; que lo haya y no arranque, sí (`bluetooth_unavailable`).
259
+ */
260
+ _prepareBluetooth () {
261
+ if (!this._ble || this._ble.available || this._bleStarting) return this._bleStarting
262
+ this._bleStarting = (async () => {
263
+ let adapter = this._bleOption
264
+ if (adapter === true) {
265
+ const mod = './ble/bluez.js'
266
+ const { openBluez } = await import(/* @vite-ignore */ mod)
267
+ adapter = await openBluez()
268
+ if (!adapter) return
269
+ }
270
+ await this._ble.start(adapter)
271
+ })().catch((e) => {
272
+ this._emit('error', { type: 'bluetooth_unavailable', error: e, code: e?.code || null })
273
+ }).finally(() => { this._bleStarting = null })
274
+ return this._bleStarting
275
+ }
276
+
277
+ /** Hay Bluetooth encendido en este cliente. */
278
+ get bluetoothAvailable () { return !!this._ble?.available }
279
+
280
+ /**
281
+ * Anuncia `{kind, data}` por Bluetooth hasta que se llame a lo que devuelve
282
+ * (docs/bluetooth.md §3). `kind: 'pair'` es la invitación de emparejar; `'contact'`, la
283
+ * tarjeta de contacto. Lanza `no-bluetooth` si aquí no lo hay.
284
+ * @returns {() => void}
285
+ */
286
+ announceBluetooth (kind, data) {
287
+ if (!this._ble) throw errorWithCode('bluetooth: this client was made without it (option `bluetooth`)', 'no-bluetooth')
288
+ return this._ble.announce(kind, data)
289
+ }
290
+
291
+ /**
292
+ * Lo que anuncian por Bluetooth los aparatos de alrededor con ese `kind`. No necesita el
293
+ * proxio. `onFound` avisa de cada uno según aparece.
294
+ * @returns {Promise<{kind: string, data: string}[]>}
295
+ */
296
+ async discoverBluetooth ({ kind, timeoutMs, onFound } = /** @type {any} */ ({})) {
297
+ if (!this._ble) throw errorWithCode('bluetooth: this client was made without it (option `bluetooth`)', 'no-bluetooth')
298
+ await this._prepareBluetooth()
299
+ return this._ble.discover({ kind, timeoutMs, onFound })
300
+ }
301
+
237
302
  connect () {
303
+ this._prepareBluetooth()
238
304
  return new Promise((resolve, reject) => {
239
305
  if (this._connected) return resolve(this.token)
240
306
  // Un reintento que estaba esperando su turno sobra: este `connect()` ya abre uno.
@@ -257,6 +323,7 @@ export class WebSocketProxyClient {
257
323
  this._turnTimer = null
258
324
  }
259
325
  if (this._rtc) this._rtc.closeAll()
326
+ if (this._ble) this._ble.stop().catch(() => {})
260
327
  if (this.ws) {
261
328
  try { this.ws.close(1000) } catch (_) {}
262
329
  }
@@ -342,13 +409,13 @@ export class WebSocketProxyClient {
342
409
  }
343
410
  const tokens = Array.isArray(to) ? to : [to]
344
411
  const messageStr = this._wire(payload)
345
- if (!this._rtc) {
412
+ if (!this._rtc && !this._ble) {
346
413
  this._sendRaw({ to: tokens, message: messageStr })
347
414
  return
348
415
  }
349
416
  const proxyTokens = []
350
417
  for (const t of tokens) {
351
- if (!this._rtc.trySend(t, messageStr)) proxyTokens.push(t)
418
+ if (!this._tryDirect(t, messageStr)) proxyTokens.push(t)
352
419
  }
353
420
  if (proxyTokens.length) {
354
421
  this._sendRaw({ to: proxyTokens, message: messageStr })
@@ -374,6 +441,8 @@ export class WebSocketProxyClient {
374
441
  * el siguiente mensaje vuelve a intentarlo.
375
442
  */
376
443
  _upgradeDirect (tokens) {
444
+ // El Bluetooth negocia en paralelo con WebRTC y deduplica solo (ble/manager.js).
445
+ if (this._ble?.available) for (const t of tokens) if (!this._ble.isOpen(t)) this._ble.upgrade(t)
377
446
  if (!this._rtc) return
378
447
  this._rtcTried = this._rtcTried || new Set()
379
448
  for (const t of tokens) {
@@ -404,6 +473,25 @@ export class WebSocketProxyClient {
404
473
  return !!(this._rtc && this._rtc.isOpen(token))
405
474
  }
406
475
 
476
+ /**
477
+ * EL MEJOR CANAL ABIERTO, en el orden de la escalera (docs/bluetooth.md §1): WebRTC si va
478
+ * directo, si no Bluetooth, si no WebRTC por TURN. False = por el proxio.
479
+ */
480
+ _directFor (token) {
481
+ const rtcOpen = !!this._rtc?.isOpen(token)
482
+ if (rtcOpen && this._rtc.peers?.get(token)?.route !== 'turn') return this._rtc
483
+ if (this._ble?.isOpen(token)) return this._ble
484
+ if (rtcOpen) return this._rtc
485
+ return null
486
+ }
487
+
488
+ /** Manda por el mejor canal abierto; si no hay, deja que WebRTC empiece a negociar y da false. */
489
+ _tryDirect (token, wire) {
490
+ const d = this._directFor(token)
491
+ if (d) return d.trySend(token, wire)
492
+ return this._rtc ? this._rtc.trySend(token, wire) : false
493
+ }
494
+
407
495
  _proxySendOne (to, payload) {
408
496
  if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return
409
497
  this._sendRaw({
@@ -576,7 +664,7 @@ export class WebSocketProxyClient {
576
664
  // mensaje del camino que toca sale en partes. El tamaño de parte lo decide el camino
577
665
  // de ahora: el canal directo admite mucho menos por mensaje que el proxio.
578
666
  const m = this._measure(payload)
579
- const direct = tokens.length === 1 && !!this._rtc?.isOpen(tokens[0])
667
+ const direct = tokens.length === 1 && !!this._directFor(tokens[0])
580
668
  const size = m.bin ? (direct ? DIRECT_PART_BYTES : PROXY_PART_BYTES) : (direct ? DIRECT_PART_CHARS : PROXY_PART_CHARS)
581
669
  const relayMax = m.bin ? RELAY_MAX_BYTES : RELAY_MAX_CHARS
582
670
  const queueMax = m.bin ? QUEUE_MAX_BYTES : QUEUE_MAX_CHARS
@@ -619,12 +707,14 @@ export class WebSocketProxyClient {
619
707
  * existe esto: que la app lo enseñe antes de que el usuario intente algo que no cabe.
620
708
  * `webrtc` es un canal directo abierto del que todavía no se sabe si va por TURN.
621
709
  * @param {string|null} token
622
- * @returns {Promise<'socket'|'direct'|'turn'|'webrtc'|'proxy'|'offline'>}
710
+ * @returns {Promise<'socket'|'direct'|'turn'|'webrtc'|'bluetooth'|'proxy'|'offline'>}
623
711
  */
624
712
  async routeTo (token) {
625
713
  if (!this._connected) return 'offline'
626
714
  if (!token) return 'offline'
627
- if (this._rtc?.isOpen(token)) {
715
+ const d = this._directFor(token)
716
+ if (d && d === this._ble) return 'bluetooth'
717
+ if (d) {
628
718
  const peer = this._rtc.peers.get(token)
629
719
  try { return (await this._rtc.probeRoute(peer)) || 'webrtc' } catch (_) { return 'webrtc' }
630
720
  }
@@ -637,7 +727,8 @@ export class WebSocketProxyClient {
637
727
  * una pausa corta entre partes, para no chocar con su límite de mensajes por segundo.
638
728
  */
639
729
  async _sendPiece (token, envelope, peerPubkey, queueFallback, relayFallback = true) {
640
- if (this._rtc && await this._rtc.sendDirect(token, this._wire(envelope))) return
730
+ const d = this._directFor(token)
731
+ if (d && await d.sendDirect(token, this._wire(envelope))) return
641
732
  if (!relayFallback) {
642
733
  throw errorWithCode('the direct channel closed in the middle of a message too big for the proxy', 'direct-lost')
643
734
  }
@@ -683,7 +774,7 @@ export class WebSocketProxyClient {
683
774
  throw errorWithCode('requireSealed: refusing to send a directed message in the clear — use sendSealedTo()', 'unsealed')
684
775
  }
685
776
  const messageStr = this._wire(envelope)
686
- if (!skipDirect && this._rtc && this._rtc.trySend(token, messageStr)) return
777
+ if (!skipDirect && this._tryDirect(token, messageStr)) return
687
778
  const id = `msg_${this._nextId++}`
688
779
  const timer = setTimeout(() => this._tokenWatch.delete(id), 15000)
689
780
  timer.unref?.()
@@ -1453,7 +1544,9 @@ export class WebSocketProxyClient {
1453
1544
  spec.fireAt = fireAt
1454
1545
  }
1455
1546
  if (payload) spec.payload = payload
1456
- const data = { op: 'schedule-push', publickey: publicKey, spec: JSON.stringify(spec), ts: Date.now() }
1547
+ // La app va firmada, como en enablePush: el recordatorio suena solo en ella (proxio ≥ 1.9.0;
1548
+ // uno más viejo la ignora y suena en todas, como antes).
1549
+ const data = { op: 'schedule-push', publickey: publicKey, spec: JSON.stringify(spec), ts: Date.now(), ...this._appField() }
1457
1550
  const signature = await normalizeSignature(sign, data)
1458
1551
  const res = await this._request({ type: 'schedule-push', data, signature }, 'push-scheduled')
1459
1552
  return { jobId: res.jobId, nextFire: res.nextFire }
@@ -1476,7 +1569,7 @@ export class WebSocketProxyClient {
1476
1569
 
1477
1570
  /**
1478
1571
  * Listar los push programados propios.
1479
- * @returns {Promise<Array<{ jobId:number, nextFire:number, cron:string|null, tz:string|null, payload:object|null }>>}
1572
+ * @returns {Promise<Array<{ jobId:number, app:string|null, nextFire:number, cron:string|null, tz:string|null, payload:object|null }>>}
1480
1573
  */
1481
1574
  async listScheduledPushes ({ publicKey, sign } = {}) {
1482
1575
  if (!publicKey || typeof sign !== 'function') throw new Error('listScheduledPushes requires { publicKey, sign }')
@@ -1712,6 +1805,11 @@ export class WebSocketProxyClient {
1712
1805
  this._rtc.handleIncoming(from, parsed)
1713
1806
  break
1714
1807
  }
1808
+ // La señalización del Bluetooth tampoco sube a la app, haya Bluetooth o no.
1809
+ if (parsed && parsed.t === BLE_TAG) {
1810
+ this._ble?.handleIncoming(from, parsed)
1811
+ break
1812
+ }
1715
1813
  // El saludo se atiende AQUÍ, antes de `_deliver`: es del transporte y no sube a
1716
1814
  // la app, así que `requireSealed` no lo ve pasar ni tiene que hacerle una
1717
1815
  // excepción.
@@ -1733,6 +1831,7 @@ export class WebSocketProxyClient {
1733
1831
  this.forgetToken(data.token)
1734
1832
  this._emit('peer_disconnected', data.token, data.channel || null)
1735
1833
  if (this._rtc && data.token) this._rtc.closePeer(data.token)
1834
+ if (this._ble && data.token) this._ble.closePeer(data.token)
1736
1835
  this._resolvePending(data, 'token')
1737
1836
  break
1738
1837
  case 'joined':
@@ -1842,6 +1941,13 @@ export class WebSocketProxyClient {
1842
1941
  async stats () {
1843
1942
  const t = this._traffic
1844
1943
  const routes = this._rtc ? await this._rtc.describe() : new Map()
1944
+ // Un canal de Bluetooth abierto manda sobre un WebRTC que no salió o va por TURN (§1).
1945
+ if (this._ble) {
1946
+ for (const [tok, r] of this._ble.describe()) {
1947
+ const cur = routes.get(tok)
1948
+ if (r === 'bluetooth' ? cur !== 'direct' : !cur) routes.set(tok, r)
1949
+ }
1950
+ }
1845
1951
  const peers = [...t.peers.values()].map((p) => {
1846
1952
  const pubkey = p.pubkey || (p.token && this._tokenPubkeys.get(p.token)) || null
1847
1953
  const rtc = p.token ? routes.get(p.token) : null
@@ -1865,6 +1971,7 @@ export class WebSocketProxyClient {
1865
1971
  publickey: this.myPublickey,
1866
1972
  connected: this._connected,
1867
1973
  webrtc: !!this._rtc,
1974
+ bluetooth: !!this._ble?.available,
1868
1975
  // El relevo: null si nunca se pidió; si no, activo o por qué no (`code`, `retryAt`).
1869
1976
  turn: this._turn ? { ...this._turn } : null,
1870
1977
  since: t.since,
@@ -20,7 +20,7 @@
20
20
  import { listTransports, PATHS } from './stats.js'
21
21
 
22
22
  const sum = (peers, dir) => {
23
- const t = { proxy: 0, direct: 0, turn: 0, webrtc: 0 }
23
+ const t = { proxy: 0, direct: 0, turn: 0, webrtc: 0, bluetooth: 0 }
24
24
  for (const p of peers) for (const k of PATHS) t[k] += p[dir][k]
25
25
  return t
26
26
  }
@@ -15,6 +15,7 @@
15
15
  * direct WebRTC sin relevo
16
16
  * turn WebRTC por un relevo TURN
17
17
  * webrtc WebRTC sin saber todavía cuál de los dos (getStats no contestó)
18
+ * bluetooth el escalón del Bluetooth (docs/bluetooth.md)
18
19
  */
19
20
 
20
21
  /** Longitud en bytes UTF-8 de un string, sin reservar un buffer por mensaje. */
@@ -35,9 +36,9 @@ export function utf8Length (s) {
35
36
  return n
36
37
  }
37
38
 
38
- export const PATHS = ['proxy', 'direct', 'turn', 'webrtc']
39
+ export const PATHS = ['proxy', 'direct', 'turn', 'webrtc', 'bluetooth']
39
40
 
40
- const zeros = () => ({ proxy: 0, direct: 0, turn: 0, webrtc: 0 })
41
+ const zeros = () => ({ proxy: 0, direct: 0, turn: 0, webrtc: 0, bluetooth: 0 })
41
42
 
42
43
  export class TrafficStats {
43
44
  constructor () {
@@ -55,7 +56,7 @@ export class TrafficStats {
55
56
  /**
56
57
  * Un mensaje dirigido a (o venido de) una conexión.
57
58
  * @param {'in'|'out'} dir
58
- * @param {'proxy'|'direct'|'turn'|'webrtc'} path
59
+ * @param {'proxy'|'direct'|'turn'|'webrtc'|'bluetooth'} path
59
60
  * @param {{ token?: string|null, pubkey?: string|null }} who
60
61
  * @param {number} bytes
61
62
  */
@@ -1,3 +1,3 @@
1
- Copia vendorizada de @dotrino/roadmap@0.4.51 (dotrino-roadmap/src/{index,manifests}.js).
1
+ Copia vendorizada de @dotrino/roadmap@0.4.55 (dotrino-roadmap/src/{index,manifests}.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
  El registro de versiones rotas que viaja con cada versión. Importa @dotrino/compat/ranges.
@@ -31,7 +31,7 @@ export const MANIFESTS = Object.freeze({
31
31
  "identity": {
32
32
  "repo": "imdotrino/dotrino-identity",
33
33
  "npm": "@dotrino/identity",
34
- "current": "0.124.0",
34
+ "current": "0.126.0",
35
35
  "protocol": 1,
36
36
  "requires": {
37
37
  "proxy-client": ">=0.13.1"
@@ -109,7 +109,7 @@ export const MANIFESTS = Object.freeze({
109
109
  },
110
110
  "proxy": {
111
111
  "repo": "imdotrino/dotrino-proxy",
112
- "current": "1.8.0",
112
+ "current": "1.9.0",
113
113
  "protocol": 2,
114
114
  "requires": {
115
115
  "vault": ">=0.87.0",
@@ -121,7 +121,7 @@ export const MANIFESTS = Object.freeze({
121
121
  "proxy-client": {
122
122
  "repo": "imdotrino/dotrino-proxy-client",
123
123
  "npm": "@dotrino/proxy-client",
124
- "current": "0.39.0",
124
+ "current": "0.40.0",
125
125
  "protocol": 2,
126
126
  "requires": {
127
127
  "identity": ">=0.53.0",
@@ -253,12 +253,12 @@ export const MANIFESTS = Object.freeze({
253
253
  "vault": {
254
254
  "repo": "imdotrino/dotrino-vault",
255
255
  "npm": "@dotrino/vault",
256
- "current": "0.96.0",
256
+ "current": "0.99.0",
257
257
  "protocol": 1,
258
258
  "requires": {
259
259
  "vaultd": ">=0.105.0",
260
260
  "proxy-client": ">=0.39.0",
261
- "identity": ">=0.124.0",
261
+ "identity": ">=0.126.0",
262
262
  "opaque": ">=0.1.0",
263
263
  "compat": ">=0.4.0",
264
264
  "roadmap": ">=0.4.26",
@@ -269,10 +269,10 @@ export const MANIFESTS = Object.freeze({
269
269
  "vaultd": {
270
270
  "repo": "imdotrino/dotrino-vault",
271
271
  "npm": "@dotrino/vaultd",
272
- "current": "0.168.0",
272
+ "current": "0.171.0",
273
273
  "protocol": 1,
274
274
  "requires": {
275
- "identity": ">=0.124.0",
275
+ "identity": ">=0.126.0",
276
276
  "proxy-client": ">=0.39.0",
277
277
  "store": ">=0.11.0",
278
278
  "passmanager": ">=0.18.4",
@@ -320,7 +320,7 @@ export const MANIFESTS = Object.freeze({
320
320
  },
321
321
  "passmanager-extension": {
322
322
  "repo": "imdotrino/dotrino-passmanager",
323
- "current": "0.54.0",
323
+ "current": "0.56.2",
324
324
  "protocol": 1,
325
325
  "requires": {
326
326
  "identity": ">=0.118.0",
@@ -388,6 +388,18 @@ export const MANIFESTS = Object.freeze({
388
388
  "protocol": 1,
389
389
  "requires": {}
390
390
  },
391
+ "expenses-agent": {
392
+ "repo": "imdotrino/dotrino-expenses-agent",
393
+ "npm": "@dotrino/expenses-agent",
394
+ "current": "0.1.2",
395
+ "protocol": 1,
396
+ "requires": {
397
+ "remote-agent": ">=0.23.1",
398
+ "vault": ">=0.96.0",
399
+ "update": ">=0.9.2",
400
+ "vaultd": ">=0.154.0"
401
+ }
402
+ },
391
403
  "pay": {
392
404
  "repo": "imdotrino/dotrino-pay",
393
405
  "npm": "@dotrino/pay",
@@ -1,9 +1,10 @@
1
- Copia vendorizada de @dotrino/vault@0.99.0 (dotrino-vault/lib/src/{admin,b64,browser,core/approvals,core/backup,core/blocked,core/browserDisk,core/commKey,core/disk,core/exNotices,core/gate,core/libVersion,core/machines,core/notices,core/notifiable,core/passwords,core/sealKey,core/sealer,core/sealers,core/secretsStore,core/sha256,core/store,core/subacta,core/threadStore,core/transport,core/vault,enroll,index,loginClient,passwordLogins,procContext,protocol,revocation,sealed}.js).
1
+ Copia vendorizada de @dotrino/vault@0.100.0 (dotrino-vault/lib/src/{admin,b64,browser,core/approvals,core/backup,core/blocked,core/browserDisk,core/commKey,core/disk,core/exNotices,core/gate,core/libVersion,core/machines,core/notices,core/notifiable,core/passwords,core/sealKey,core/sealer,core/sealers,core/secretsStore,core/sha256,core/store,core/subacta,core/threadStore,core/transport,core/vault,enroll,index,invite,loginClient,passwordLogins,procContext,protocol,revocation,sealed}.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
  browser.js es la bóveda de esta pestaña: el MISMO núcleo que el binario (core/), con
4
4
  el disco en IndexedDB. Importa @dotrino/{compat,roadmap,passmanager,store/core} y
5
5
  @dotrino/identity/{facade,machine,content}, todos por el import map de index.html.
6
- index.js importa ./enroll.js y ./protocol.js (relativos, van en esta misma copia),
6
+ index.js importa ./enroll.js y ./protocol.js (relativos, van en esta misma copia);
7
+ enroll.js importa ./invite.js para anunciar la invitación por Bluetooth.
7
8
  @dotrino/identity/{capabilities,acta} (= ../../{capabilities,acta}.js) y
8
9
  @dotrino/proxy-client (= ../proxy-client/), todos por el import map de index.html.
9
10
  passwordLogins.js es el aparato que se abre con usuario y contraseña: lo carga
@@ -5,4 +5,4 @@
5
5
  * si no coincide con la del paquete: una versión anunciada que no es la que corre es peor
6
6
  * que no anunciar ninguna.
7
7
  */
8
- export const LIB_VERSION = '0.99.0'
8
+ export const LIB_VERSION = '0.100.0'
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * LO QUE LA BÓVEDA TIENE QUE CONTARLE A QUIEN APRUEBA, y que no es un pedido.
3
3
  *
4
- * Son dos, de la bóveda o de uno de sus aparatos: «me actualicé» y «hay versión nueva y
4
+ * Son tres. Dos de la bóveda o de uno de sus aparatos: «me actualicé» y «hay versión nueva y
5
5
  * necesita permisos de administrador: instálala a mano» (`update-needs-root`). (`ev: 'updated'`, dueño 2026-10-08: «las actualizaciones, que se
6
6
  * envíe una notificación de que ocurrieron a los aprobadores»). Sale como aviso por el
7
7
  * proxio, pero el timbre de una app nativa llega VACÍO —lo leen Google y Apple—, así que la
@@ -16,8 +16,15 @@
16
16
  export const NOTICES_FILE = 'notices.json'
17
17
  /** Cuánto se sigue contando un aviso. */
18
18
  export const NOTICE_TTL_MS = 24 * 60 * 60 * 1000
19
- /** Los avisos que existen. */
20
- export const NOTICE_EVS = ['updated', 'update-needs-root']
19
+ /**
20
+ * Los avisos que existen. El tercero, `pairing-contested`, es un INCIDENTE: dos aparatos
21
+ * respondieron a la misma invitación de emparejar y la sesión se canceló
22
+ * (`docs/pairing-protocol.md` §1.7). No pide nada: no hay a quién bloquear, porque ninguno
23
+ * entró. Lo cuenta, con el ID y la máquina de los dos.
24
+ */
25
+ export const NOTICE_EVS = ['updated', 'update-needs-root', 'pairing-contested']
26
+
27
+ const newId = () => [...crypto.getRandomValues(new Uint8Array(8))].map((b) => b.toString(16).padStart(2, '0')).join('')
21
28
 
22
29
  const fail = (code, message) => Object.assign(new Error(message), { code })
23
30
 
@@ -51,12 +58,23 @@ export function openNotices ({ disk, now = Date.now }) {
51
58
  * administrador). `product`: qué (`@dotrino/vaultd` es la propia bóveda);
52
59
  * `deviceId`/`label`: el aparato, si fue uno.
53
60
  */
54
- add (ev, { version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null }) {
61
+ add (ev, { version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null, devices = null }) {
55
62
  if (!NOTICE_EVS.includes(ev)) throw fail('bad-notice', `unknown notice: ${ev}`)
63
+ if (ev === 'pairing-contested') {
64
+ if (!Array.isArray(devices) || devices.length < 2) throw fail('bad-notice', `${ev}: the devices that answered are required`)
65
+ const n = {
66
+ id: newId(), ev,
67
+ devices: devices.slice(0, 8).map((d) => ({ deviceId: String(d?.deviceId || ''), machine: d?.machine || null })),
68
+ ts: now()
69
+ }
70
+ items = [...items.filter(alive), n]
71
+ save()
72
+ return n
73
+ }
56
74
  if (typeof version !== 'string' || !version) throw fail('bad-notice', `${ev}: a version is required`)
57
75
  if (typeof product !== 'string' || !product) throw fail('bad-notice', `${ev}: a product is required`)
58
76
  const n = {
59
- id: [...crypto.getRandomValues(new Uint8Array(8))].map((b) => b.toString(16).padStart(2, '0')).join(''), ev, product, version, from: typeof from === 'string' ? from : null,
77
+ id: newId(), ev, product, version, from: typeof from === 'string' ? from : null,
60
78
  ...(typeof deviceId === 'string' && deviceId ? { deviceId, label: typeof label === 'string' ? label : '' } : {}),
61
79
  ts: now()
62
80
  }
@@ -36,7 +36,7 @@ export async function masterPubkeyOf (identity) {
36
36
  * @param {string} [opts.url] URL del proxy (default wss://proxy.dotrino.com).
37
37
  * @returns {Promise<{ client, token:string, identify():Promise<void> }>}
38
38
  */
39
- export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey = null, log = () => {}, makeClient = null, announce = null, wakeUrl = null, recheckMs = 60_000, patienceMs = 5 * 60_000, reannounceMs = 10 * 60_000 }) {
39
+ export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey = null, log = () => {}, makeClient = null, announce = null, wakeUrl = null, bluetooth = null, recheckMs = 60_000, patienceMs = 5 * 60_000, reannounceMs = 10 * 60_000 }) {
40
40
  // Import dinámico DESPUÉS de instalar los globals que el paquete usa.
41
41
  // `WebSocketProxyClient` (la clase) y NO el helper `getWebSocketProxyClient`:
42
42
  // ese es un SINGLETON de proceso, y con multi-perfil el vault necesita una
@@ -80,7 +80,10 @@ export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey
80
80
  }
81
81
  const client = makeClient ? makeClient({ url, acceptDirectFrom: inActa }) : new WebSocketProxyClient({
82
82
  url, enableWebRTC: true, acceptDirectFrom: inActa, autoReconnect: true,
83
- maxReconnectAttempts: 100000, reconnectDelay: 4000
83
+ maxReconnectAttempts: 100000, reconnectDelay: 4000,
84
+ // EL BLUETOOTH (proxy-client docs/bluetooth.md) lo decide la plataforma: el binario en
85
+ // Linux sí; la pestaña y la extensión no pueden. Misma puerta que WebRTC (`inActa`).
86
+ ...(bluetooth ? { bluetooth } : {})
84
87
  })
85
88
 
86
89
  await client.connect()
@@ -520,7 +520,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
520
520
  // ninguna llave y solo sabe la dirección `nombre@AB12-CD34-EF56`— pueda encontrar a quien
521
521
  // la atiende. Lo construye la pieza compartida, porque quien lo busca es la extensión.
522
522
  const { client, identify: reidentify, isIdentified, listen } = await createTransport({
523
- identity, url: proxyUrl, commKey, log, announce: vaultChannel(fp), makeClient: platform.makeClient || null, wakeUrl: platform.wakeUrl || null
523
+ identity, url: proxyUrl, commKey, log, announce: vaultChannel(fp), makeClient: platform.makeClient || null, wakeUrl: platform.wakeUrl || null,
524
+ bluetooth: platform.bluetooth || null
524
525
  })
525
526
 
526
527
  // El registro público de cadenas de selladores: deposita, si hay a dónde, los eslabones
@@ -878,6 +879,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
878
879
  markRotationDue(sub).catch((e) => log('[vault] could not rotate after the removal:', e.message))
879
880
  },
880
881
  defaultScope: [SCOPE.READ],
882
+ // EMPAREJAR CERCA (pairing-protocol.md §1.6): la invitación se anuncia por Bluetooth
883
+ // mientras la sesión vive, si este cliente lo tiene. Sin Bluetooth, el QR de siempre.
884
+ announce: (kind, data) => client.bluetoothAvailable ? client.announceBluetooth(kind, data) : null,
885
+ // DOS APARATOS RESPONDIERON (§1.7): la sesión ya se canceló; aquí se cuenta como incidente.
886
+ onContested: ({ devices }) => {
887
+ announcePairingContested(devices).catch((e) => log('[vault] could not tell the approvers about the contested pairing:', e.message))
888
+ },
881
889
  onChallenge ({ deviceId, scope, machine }) {
882
890
  log(`\n[vault] Un dispositivo quiere conectarse:`)
883
891
  log(` deviceId: ${deviceId}`)
@@ -2178,6 +2186,39 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2178
2186
  * marcador hasta que el aviso salió, y tragarlo sería borrarlo sin haber avisado.
2179
2187
  * @returns {Promise<{ approvers: number, sent: number, notice: object|null }>}
2180
2188
  */
2189
+ /** Manda un aviso ya apuntado (`notices`) a cada aprobador, sellado. Devuelve a cuántos salió. */
2190
+ async function sendNotice (notice, who, what) {
2191
+ const { id, ev, ts, ...rest } = notice
2192
+ const body = { ev, id, ...rest, ts }
2193
+ const seal = await sealOrFail(body)
2194
+ let sent = 0
2195
+ for (const pub of who) {
2196
+ try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal }, { app: 'vault' }); sent++ }
2197
+ catch (e) { log(`[vault] could not tell ${pub.slice(0, 24)}… about ${what}: ${e.message}`) }
2198
+ }
2199
+ return sent
2200
+ }
2201
+
2202
+ /**
2203
+ * UN INCIDENTE DE EMPAREJAMIENTO (pairing-protocol.md §1.7): dos aparatos respondieron a la
2204
+ * misma invitación y la sesión ya se canceló. Se cuenta a quien aprueba como aviso
2205
+ * (`pairing-contested`): no hay nada que aprobar ni a quién bloquear, porque nadie entró.
2206
+ * Sin aprobadores queda en la bitácora (ya lo apuntó el mostrador) y se dice en el log.
2207
+ */
2208
+ async function announcePairingContested (devices) {
2209
+ const record = await refreshActa()
2210
+ const who = (record?.members || []).filter((m) => Acta.memberCan(record, m.pub, 'approve')).map((m) => m.pub)
2211
+ if (!who.length) {
2212
+ log('[vault] contested pairing: nobody can approve, so nobody is told (grant it with: dotrino-vault caps <ID> +aprueba)')
2213
+ return { approvers: 0, sent: 0 }
2214
+ }
2215
+ const notice = notices.add('pairing-contested', { devices })
2216
+ const sent = await sendNotice(notice, who, 'the contested pairing')
2217
+ log(`[vault] contested pairing: told ${sent} of ${who.length} approver(s)`)
2218
+ if (!sent) throw Object.assign(new Error('no approver could be told'), { code: 'announce-failed' })
2219
+ return { approvers: who.length, sent }
2220
+ }
2221
+
2181
2222
  async function announceUpdate ({ version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null, ev = 'updated' }) {
2182
2223
  const record = await refreshActa()
2183
2224
  const who = (record?.members || []).filter((m) => Acta.memberCan(record, m.pub, 'approve')).map((m) => m.pub)
@@ -2185,14 +2226,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2185
2226
  // `deviceId`/`label`: solo cuando quien se actualizó es un APARATO (`update-done`). El
2186
2227
  // aviso de la propia bóveda no los lleva.
2187
2228
  const notice = notices.add(ev, { version, from, product, ...(deviceId ? { deviceId, label: label || '' } : {}) })
2188
- const { id, ev: _ev, ts, ...rest } = notice
2189
- const body = { ev, id, ...rest, ts }
2190
- const seal = await sealOrFail(body)
2191
- let sent = 0
2192
- for (const pub of who) {
2193
- try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal }, { app: 'vault' }); sent++ }
2194
- catch (e) { log(`[vault] could not tell ${pub.slice(0, 24)}… about the update of ${product} to ${version}: ${e.message}`) }
2195
- }
2229
+ const sent = await sendNotice(notice, who, `the update of ${product} to ${version}`)
2196
2230
  audit(ev === 'updated' ? 'update.announced' : 'update.needs-root', { product, version, from: notice.from, device: deviceId, approvers: who.length, sent })
2197
2231
  log(`[vault] update: told ${sent} of ${who.length} approver(s) that ${deviceId ? `${deviceId} (${product})` : 'this vault'} ${ev === 'updated' ? 'now runs' : 'needs administrator rights to install'} ${version}`)
2198
2232
  if (!sent) throw Object.assign(new Error('no approver could be told'), { code: 'announce-failed' })