@dotrino/vaultd 0.170.0 → 0.172.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.
@@ -0,0 +1,66 @@
1
+ /**
2
+ * exNotices.js — LOS AVISOS DE EXPULSIÓN YA FIRMADOS, uno por cada aparato que estuvo en las
3
+ * actas de la ventana del historial y ya no está (dueño, 2026-10-22).
4
+ *
5
+ * La bóveda solo atiende al acta (`gate.js`). A quien salió se le contesta UNA cosa —«¿sigo
6
+ * dentro?»— y la respuesta es su aviso, para que se borre aunque el que se le mandó al
7
+ * echarlo no le llegara (la cola del proxio dura 24 h). El aviso se firma una vez, con la
8
+ * bóveda abierta, y se guarda: contestar no firma nada, así que preguntar no sirve para que
9
+ * la maestra firme a pedido de nadie. Sin caducidad: tiene que valer el día que vuelva.
10
+ *
11
+ * Cifrado en reposo, como todo lo de la bóveda. Si no se puede leer, se para y se dice.
12
+ */
13
+ export const EX_NOTICES_FILE = 'exnotices.json'
14
+
15
+ const fail = (code, message) => Object.assign(new Error(message), { code })
16
+
17
+ export function openExNotices ({ disk }) {
18
+ const file = EX_NOTICES_FILE
19
+ const atRest = disk.atRest
20
+ /** pub → { body, signature } */
21
+ let items = load()
22
+
23
+ function load () {
24
+ let raw
25
+ try { raw = disk.read(file) } catch (e) {
26
+ throw fail('exnotices-unreadable', `cannot read ${EX_NOTICES_FILE}: ${e.message}`)
27
+ }
28
+ if (raw == null) return new Map()
29
+ let d
30
+ try { d = JSON.parse(atRest.decrypt(raw)) } catch (e) { throw fail('exnotices-unreadable', `${EX_NOTICES_FILE} cannot be opened: ${e.message}`) }
31
+ if (d?.v !== 1 || !d.items || typeof d.items !== 'object') throw fail('exnotices-unreadable', `${EX_NOTICES_FILE} has an unknown shape`)
32
+ return new Map(Object.entries(d.items))
33
+ }
34
+
35
+ function save () {
36
+ disk.write(file, atRest.encrypt(JSON.stringify({ v: 1, items: Object.fromEntries(items) })))
37
+ }
38
+
39
+ return {
40
+ has: (pub) => items.has(pub),
41
+ get: (pub) => items.get(pub) || null,
42
+ pubs: () => [...items.keys()],
43
+ /**
44
+ * Deja exactamente los avisos de `past` (los ex-miembros de la ventana): firma con `sign`
45
+ * los que falten y quita los de quien ya salió de la ventana. Devuelve cuántos firmó.
46
+ */
47
+ async sync (past, sign) {
48
+ const keep = new Set(past)
49
+ let changed = false
50
+ for (const pub of [...items.keys()]) if (!keep.has(pub)) { items.delete(pub); changed = true }
51
+ let signed = 0
52
+ for (const pub of keep) {
53
+ if (items.has(pub)) continue
54
+ // Sin `nonce` ni `exp`: habla del APARATO, no de un papel, y vale siempre.
55
+ const body = { op: 'revoke', sub: pub, iat: Date.now() }
56
+ items.set(pub, { body, signature: await sign(body) })
57
+ signed++
58
+ changed = true
59
+ }
60
+ if (changed) save()
61
+ return signed
62
+ }
63
+ }
64
+ }
65
+
66
+ export default { openExNotices, EX_NOTICES_FILE }
@@ -8,6 +8,9 @@
8
8
  * con freno por conexión y freno global, antes de cualquier trabajo.
9
9
  * · **El alta de un aparato** (`HELLO`, `ENROLL`, `ACTA_SEALED`): solo mientras hay un
10
10
  * emparejamiento abierto y el mensaje es de ESE emparejamiento. Fuera de eso, nada.
11
+ * · **Los que salieron** (`CHECK`): un aparato de las actas de la ventana que ya no está pasa
12
+ * solo a preguntar si sigue dentro, con su firma y con freno. Se le contesta con su aviso
13
+ * de expulsión ya firmado (`exNotices.js`), para que se borre.
11
14
  *
12
15
  * Lo demás se descarta EN SILENCIO: sin respuesta, sin firma, sin línea en la bitácora y sin
13
16
  * tocar el disco. Antes un desconocido conseguía que la bóveda le contestara con el acta
@@ -77,9 +80,10 @@ export function claimOf (MSG, p) {
77
80
  * @param {object} o.MSG los tipos del protocolo
78
81
  * @param {() => Promise<object|null>} o.acta el acta vigente de esta bóveda
79
82
  * @param {(type: string, p: object, from: string) => boolean} o.pairing ¿es de un emparejamiento abierto?
83
+ * @param {(pub: string) => boolean} [o.former] ¿estuvo en el acta (y tiene su aviso)?
80
84
  * @param {ReturnType<typeof makeLimiter>} [o.limiter]
81
85
  */
82
- export function createGate ({ MSG, acta, pairing, limiter = makeLimiter(), verify = verifyDeviceSig }) {
86
+ export function createGate ({ MSG, acta, pairing, former = () => false, limiter = makeLimiter(), verify = verifyDeviceSig }) {
83
87
  const LOGIN = new Set([MSG.LOGIN_START, MSG.LOGIN_FINISH, MSG.LOGIN_CLOSE])
84
88
  const PAIRING = new Set([MSG.HELLO, MSG.ENROLL, MSG.ACTA_SEALED])
85
89
  const stats = { dropped: 0, throttled: 0, since: Date.now() }
@@ -100,7 +104,12 @@ export function createGate ({ MSG, acta, pairing, limiter = makeLimiter(), verif
100
104
  if (!claim || typeof claim.pub !== 'string' || !claim.pub) { stats.dropped++; return { ok: false } }
101
105
  // NADA QUE DECIDIR SIN ACTA: se para (no hay a quién atender), no se deja pasar.
102
106
  const record = await acta()
103
- if (!record || !(record.members || []).some((m) => m?.pub === claim.pub)) { stats.dropped++; return { ok: false } }
107
+ if (!record) { stats.dropped++; return { ok: false } }
108
+ const member = (record.members || []).some((m) => m?.pub === claim.pub)
109
+ // Un ex-miembro, solo a preguntar si sigue dentro, y con freno.
110
+ const leaving = !member && type === MSG.CHECK && former(claim.pub)
111
+ if (!member && !leaving) { stats.dropped++; return { ok: false } }
112
+ if (leaving && !limiter.take('check:' + from)) { stats.throttled++; return { ok: false } }
104
113
  if (claim.signature !== null) {
105
114
  const ok = typeof claim.signature === 'string' && claim.data &&
106
115
  await verify({ publickey: claim.pub, data: claim.data, signature: claim.signature }).catch(() => false)
@@ -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.98.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()
@@ -25,6 +25,7 @@ import { openThreadStore, STORE_READ_METHODS, PROFILE_EDIT_METHODS } from './thr
25
25
  import { openSecretsStore, assertVar, RECOVERY as RECOVERY_WRAP, PROFILE_OWNER } from './secretsStore.js'
26
26
  import { openSubacta } from './subacta.js'
27
27
  import { openBlocked } from './blocked.js'
28
+ import { openExNotices } from './exNotices.js'
28
29
  import { openNotifiable } from './notifiable.js'
29
30
  import { openMachines } from './machines.js'
30
31
  import { machineLine } from '@dotrino/identity/machine'
@@ -265,6 +266,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
265
266
  const passwordsAtRest = disk.atRest
266
267
  // Los aparatos BLOQUEADOS por un aprobador (`src/blocked.js`). Cifrado en reposo como lo demás.
267
268
  const blocked = openBlocked({ disk })
269
+ const exNotices = openExNotices({ disk })
268
270
  // Qué aprobadores dijeron que pueden recibir avisos (`src/notifiable.js`). No decide nada: se enseña.
269
271
  const notifiable = openNotifiable({ disk })
270
272
  // Dónde corre cada aparato, según lo último que dijo firmado (`src/machines.js`). Se enseña.
@@ -473,6 +475,19 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
473
475
  * maestra o quedándose mudos. Se vio el 2026-09-02: de dos perfiles, el que tenía
474
476
  * contraseña era el que no tenía `commkey.json`.
475
477
  */
478
+ /**
479
+ * LOS AVISOS DE LOS QUE SALIERON (`exNotices.js`): uno firmado por cada aparato de las actas
480
+ * de la ventana que ya no está. Solo con la bóveda ABIERTA y si esta sella: cerrada no firma.
481
+ */
482
+ async function syncExNotices () {
483
+ try {
484
+ if (isLocked() || identity.masterLocked || !(await identity.isMaster?.())) return
485
+ const past = ((await identity.pastMembers()).members || []).map((m) => m.pub)
486
+ const n = await exNotices.sync(past, async (body) => (await identity.signData(body)).signature)
487
+ if (n) log(`[vault] signed the leaving notice of ${n} former member(s): they get it when they ask`)
488
+ } catch (e) { log('[vault] could not prepare the notices for former members:', e.message) }
489
+ }
490
+
476
491
  async function ensureCommKeyInActa () {
477
492
  try {
478
493
  const info = await identity.profileActa?.()
@@ -505,7 +520,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
505
520
  // ninguna llave y solo sabe la dirección `nombre@AB12-CD34-EF56`— pueda encontrar a quien
506
521
  // la atiende. Lo construye la pieza compartida, porque quien lo busca es la extensión.
507
522
  const { client, identify: reidentify, isIdentified, listen } = await createTransport({
508
- 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
509
525
  })
510
526
 
511
527
  // El registro público de cadenas de selladores: deposita, si hay a dónde, los eslabones
@@ -513,6 +529,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
513
529
  // `sealers.js` — es una comodidad para quien lee, nunca una dependencia de la bóveda.
514
530
  startSealersPublisher({ identity, client, log })
515
531
  if (commSealedAtStart) await notifyMembers('commkey')
532
+ await syncExNotices()
516
533
 
517
534
  async function revocationSet () {
518
535
  const { revoked } = await identity.listDelegations()
@@ -862,6 +879,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
862
879
  markRotationDue(sub).catch((e) => log('[vault] could not rotate after the removal:', e.message))
863
880
  },
864
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
+ },
865
889
  onChallenge ({ deviceId, scope, machine }) {
866
890
  log(`\n[vault] Un dispositivo quiere conectarse:`)
867
891
  log(` deviceId: ${deviceId}`)
@@ -1321,9 +1345,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
1321
1345
  }
1322
1346
  const record = (await identity.profileActa?.().catch(() => null))?.acta || null
1323
1347
  const inside = (record?.members || []).some((m) => m?.pub === pub)
1324
- audit('check', { device: await deviceIdOf(pub).catch(() => null), in: inside })
1348
+ // Solo de los de dentro: un ex-miembro pregunta con freno y no escribe en la bitácora.
1349
+ if (inside) audit('check', { device: await deviceIdOf(pub).catch(() => null), in: true })
1325
1350
  if (inside) return reply(from, { type: MSG.CHECKED, in: true })
1326
- await notifyIfRevoked(pub, null, null, 'revoked')
1351
+ // UN EX-MIEMBRO: su aviso, el que se firmó una vez (`exNotices`). Primero el aviso y luego
1352
+ // el «no»: el aparato deja de escuchar al recibir el «no». Aquí no se firma nada.
1353
+ const notice = exNotices.get(pub)
1354
+ if (notice) reply(from, { type: MSG.REVOKED, body: notice.body, signature: notice.signature })
1327
1355
  reply(from, { type: MSG.CHECKED, in: false })
1328
1356
  }
1329
1357
 
@@ -2158,6 +2186,39 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2158
2186
  * marcador hasta que el aviso salió, y tragarlo sería borrarlo sin haber avisado.
2159
2187
  * @returns {Promise<{ approvers: number, sent: number, notice: object|null }>}
2160
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
+
2161
2222
  async function announceUpdate ({ version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null, ev = 'updated' }) {
2162
2223
  const record = await refreshActa()
2163
2224
  const who = (record?.members || []).filter((m) => Acta.memberCan(record, m.pub, 'approve')).map((m) => m.pub)
@@ -2165,14 +2226,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2165
2226
  // `deviceId`/`label`: solo cuando quien se actualizó es un APARATO (`update-done`). El
2166
2227
  // aviso de la propia bóveda no los lleva.
2167
2228
  const notice = notices.add(ev, { version, from, product, ...(deviceId ? { deviceId, label: label || '' } : {}) })
2168
- const { id, ev: _ev, ts, ...rest } = notice
2169
- const body = { ev, id, ...rest, ts }
2170
- const seal = await sealOrFail(body)
2171
- let sent = 0
2172
- for (const pub of who) {
2173
- try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal }, { app: 'vault' }); sent++ }
2174
- catch (e) { log(`[vault] could not tell ${pub.slice(0, 24)}… about the update of ${product} to ${version}: ${e.message}`) }
2175
- }
2229
+ const sent = await sendNotice(notice, who, `the update of ${product} to ${version}`)
2176
2230
  audit(ev === 'updated' ? 'update.announced' : 'update.needs-root', { product, version, from: notice.from, device: deviceId, approvers: who.length, sent })
2177
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}`)
2178
2232
  if (!sent) throw Object.assign(new Error('no approver could be told'), { code: 'announce-failed' })
@@ -2235,7 +2289,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2235
2289
  const gate = createGate({
2236
2290
  MSG,
2237
2291
  acta: async () => (await identity.profileActa?.().catch(() => null))?.acta || null,
2238
- pairing: (type, p) => desk.ownsPairing(type, p)
2292
+ pairing: (type, p) => desk.ownsPairing(type, p),
2293
+ former: (pub) => exNotices.has(pub)
2239
2294
  })
2240
2295
 
2241
2296
  // `listen` y no `client.on`: entrega también lo que llegó encolado antes de este punto.
@@ -2564,6 +2619,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2564
2619
  * `sendByPubkey`, así que al que está apagado le llega cuando encienda (cola 24 h).
2565
2620
  */
2566
2621
  async function notifyMembers (ev, info = {}) {
2622
+ // El acta pudo cambiar (alguien salió): su aviso tiene que estar listo para cuando pregunte.
2623
+ await syncExNotices()
2567
2624
  try {
2568
2625
  // SIN FIRMA, y no falta nada: quien lo usa es el ACTA que viaja al lado, que se
2569
2626
  // autentica sola (otra bóveda la adopta por `canAdopt`; el teléfono solo refresca y
@@ -4328,6 +4385,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
4328
4385
  try {
4329
4386
  if (await ensureCommKeyInActa()) { await reidentify?.(); await notifyMembers('commkey') }
4330
4387
  } catch (_) {}
4388
+ await syncExNotices()
4331
4389
  }
4332
4390
  // Y ABSORBER LO PENDIENTE. La subacta ya lo estaba honrando con el perfil cerrado —de
4333
4391
  // eso vive—, pero mientras siga ahí solo lo sabe esta máquina: al sellarlo, entra en
package/lib/src/enroll.js CHANGED
@@ -32,6 +32,7 @@
32
32
  import { verifyDeviceSig, pubkeyId, commitCode } from '@dotrino/identity/capabilities'
33
33
  import { verifyContinuity, canSeal, DEVICE_CAPS, VAULT_CN } from '@dotrino/identity/acta'
34
34
  import { cleanMachine } from '@dotrino/identity/machine'
35
+ import { encodeInvite } from './invite.js'
35
36
 
36
37
  /** Un token de emparejamiento vale 5 min. */
37
38
  export const PAIRING_TTL_MS = 5 * 60 * 1000
@@ -132,7 +133,13 @@ export function createEnrollDesk ({
132
133
  encPub = null, vaultLabel = '',
133
134
  // Token de CONEXIÓN de esta bóveda en el proxy (4 chars): su dirección. Es lo
134
135
  // único que necesita el QR corto para que el aparato le hable punto a punto.
135
- connToken = null
136
+ connToken = null,
137
+ // ANUNCIAR LA INVITACIÓN cerca (pairing-protocol.md §1.6): `(kind, data) => stop | null`.
138
+ // Lo da quien tiene Bluetooth; la invitación se anuncia mientras la sesión vive.
139
+ announce = null,
140
+ // DOS APARATOS RESPONDIERON a la misma invitación (§1.7): la sesión ya se canceló aquí;
141
+ // quien monta la bóveda lo cuenta como incidente. `{ devices: [{ deviceId, machine }], mode }`.
142
+ onContested = () => {}
136
143
  } = {}) {
137
144
  if (!identity) throw new Error('createEnrollDesk: missing identity')
138
145
  if (!iss) throw new Error('createEnrollDesk: missing iss (master pubkey)')
@@ -159,7 +166,16 @@ export function createEnrollDesk ({
159
166
  try { ({ signature } = await identity.signData(signed)) } catch (e) { log('[vault] could not sign the reply:', e.message); return }
160
167
  reply(to, { ...obj, signed, vsig: signature })
161
168
  }
162
- const fail = (to, error, sn) => tell(to, { type: MSG_ERROR, error }, sn)
169
+ const fail = (to, error, sn, code) => tell(to, { type: MSG_ERROR, error, ...(code ? { code } : {}) }, sn)
170
+
171
+ /** Anuncia la invitación de la sesión, si hay con qué. Devuelve con qué pararlo, o null. */
172
+ const announceInvite = (qr) => {
173
+ if (typeof announce !== 'function') return null
174
+ try { return announce('pair', encodeInvite(qr)) || null } catch (e) {
175
+ log('[vault] could not announce the invitation nearby:', e.message)
176
+ return null
177
+ }
178
+ }
163
179
  const isFresh = (d) => typeof d?.ts === 'number' && Math.abs(Date.now() - d.ts) <= FRESH_WINDOW_MS
164
180
 
165
181
  /**
@@ -216,13 +232,18 @@ export function createEnrollDesk ({
216
232
  const conn = typeof connToken === 'function' ? await connToken() : connToken
217
233
  if (conn) {
218
234
  const sn = randToken(8)
219
- pending.set(sn, { token: sn, exp: Date.now() + PAIRING_TTL_MS, scope, caps, ttlMs, label, sn, mode, account: acct, state: 'AWAITING_ENROLL' })
220
- return { token: sn, qr: { v: 2, conn, sn, m: mode, proxy }, expiresInMs: PAIRING_TTL_MS }
235
+ const qr = { v: 2, conn, sn, m: mode, proxy }
236
+ const stopAnnounce = announceInvite(qr)
237
+ pending.set(sn, { token: sn, exp: Date.now() + PAIRING_TTL_MS, scope, caps, ttlMs, label, sn, mode, account: acct, state: 'AWAITING_ENROLL', stopAnnounce })
238
+ return { token: sn, qr, expiresInMs: PAIRING_TTL_MS, nearby: !!stopAnnounce }
221
239
  }
222
240
  const token = randToken(PAIR_TOKEN_BYTES)
223
241
  const sn = randToken(PAIR_TOKEN_BYTES)
224
- pending.set(token, { token, exp: Date.now() + PAIRING_TTL_MS, scope, caps, ttlMs, label, sn, mode, account: acct, state: 'AWAITING_ENROLL' })
225
- return { token, qr: { v: 2, iss, proxy, token, sn, m: mode, ...(acct ? { acct } : {}) }, expiresInMs: PAIRING_TTL_MS }
242
+ const qr = { v: 2, iss, proxy, token, sn, m: mode, ...(acct ? { acct } : {}) }
243
+ const stopAnnounce = announceInvite(qr)
244
+ pending.set(token, { token, exp: Date.now() + PAIRING_TTL_MS, scope, caps, ttlMs, label, sn, mode, account: acct, state: 'AWAITING_ENROLL', stopAnnounce })
245
+ // `nearby`: la invitación también se anuncia por Bluetooth (§1.6), para decirlo en pantalla.
246
+ return { token, qr, expiresInMs: PAIRING_TTL_MS, nearby: !!stopAnnounce }
226
247
  }
227
248
 
228
249
  function stopPairing (token) { forget(token) }
@@ -238,6 +259,8 @@ export function createEnrollDesk ({
238
259
  pending.delete(key)
239
260
  if (!pend) return
240
261
  gone.add(pend.token); if (pend.sn) gone.add(pend.sn)
262
+ // Cerrada la sesión, la invitación deja de anunciarse.
263
+ if (pend.stopAnnounce) { try { pend.stopAnnounce() } catch (_) {} pend.stopAnnounce = null }
241
264
  while (gone.size > 200) gone.delete(gone.values().next().value)
242
265
  }
243
266
 
@@ -331,10 +354,25 @@ export function createEnrollDesk ({
331
354
  audit('rejected', { what: 'enroll', reason: 'no-commit' })
332
355
  return fail(from, 'this device speaks an old pairing version (no code commitment). Update it and try again.', d.sn)
333
356
  }
334
- // Un solo dispositivo a la vez esperando su código (así aprobar no es ambiguo).
335
- if (pend.state === 'PENDING_CONFIRM' && pend.dpub && pend.dpub !== d.dpub) {
336
- return fail(from, 'another device is already using this pairing session', d.sn)
357
+ // DOS APARATOS RESPONDIERON A LA MISMA INVITACIÓN (pairing-protocol.md §1.7): se cancela
358
+ // la sesión, no se aprueba a ninguno y es un incidente. Antes se rechazaba al segundo y el
359
+ // primero seguía: si el primero era el intruso, el legítimo se quedaba fuera y el dueño solo
360
+ // veía un código que no cuadraba. El reclamo se apunta SIN esperar (`claimed`), así dos
361
+ // ENROLL que llegan juntos no pasan los dos por aquí antes de que el primero lo marque.
362
+ if (pend.claimed && pend.claimed.dpub !== d.dpub) {
363
+ const first = pend.claimed
364
+ const [firstId, secondId] = await Promise.all([deviceIdOf(first.dpub), deviceIdOf(d.dpub)])
365
+ const devices = [{ deviceId: firstId, machine: first.machine }, { deviceId: secondId, machine: cleanMachine(d.machine) }]
366
+ forget(d.token)
367
+ audit('incident', { what: 'enroll', reason: 'pairing-contested', devices: [firstId, secondId] })
368
+ log(`[vault] pairing cancelled: ${firstId} and ${secondId} both answered the same invitation — reported as an incident`)
369
+ const why = 'pairing cancelled: another device answered this invitation. Start again.'
370
+ await Promise.all([fail(first.from, why, d.sn, 'pairing-contested'), fail(from, why, d.sn, 'pairing-contested')])
371
+ fire(onContested, { devices, mode: pend.mode || 'join' })
372
+ fire(onPendingChange)
373
+ return { contested: true }
337
374
  }
375
+ if (!pend.claimed) pend.claimed = { dpub: d.dpub, from, machine: cleanMachine(d.machine) }
338
376
 
339
377
  const deviceId = await deviceIdOf(d.dpub)
340
378
  pend.state = 'PENDING_CONFIRM'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/vaultd",
3
- "version": "0.170.0",
3
+ "version": "0.172.0",
4
4
  "type": "module",
5
5
  "description": "Certificador personal de Dotrino: daemon headless que custodia la clave maestra y delega capacidades a tus dispositivos por el proxy. Tu CA propia.",
6
6
  "bin": {
@@ -22,10 +22,10 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@dotrino/compat": "0.4.0",
25
- "@dotrino/identity": "0.125.0",
25
+ "@dotrino/identity": "0.126.0",
26
26
  "@dotrino/opaque": "0.1.0",
27
27
  "@dotrino/passmanager": "0.18.4",
28
- "@dotrino/proxy-client": "0.39.0",
28
+ "@dotrino/proxy-client": "0.41.0",
29
29
  "@dotrino/roadmap": "0.4.30",
30
30
  "@dotrino/store": "0.12.3",
31
31
  "@dotrino/update": "0.9.0",
package/src/ctl.js CHANGED
@@ -404,6 +404,7 @@ async function cmdPair (args = []) {
404
404
  console.log(`${R} NO lo compartas con nadie, ni con "soporte". Solo escanéalo en TU dispositivo.${Z}`)
405
405
  console.log('\nO abre esta dirección en el dispositivo:\n ' + url)
406
406
  console.log('\nO pega este código en vault.dotrino.com/vault :\n ' + b64)
407
+ if (pair.nearby) console.log('\nO, en un teléfono cerca, pulsa «Descubrir»: esta invitación también se anuncia por Bluetooth.')
407
408
 
408
409
  // --save [archivo]: escribe la invitación (.dpair) para transferirla y abrirla en profile.
409
410
  const saveIdx = args.indexOf('--save')
package/src/daemon.js CHANGED
@@ -270,8 +270,8 @@ export async function runDaemon () {
270
270
  // perfil de esta bóveda tiene que haber nacido para eso (`--adopt`
271
271
  // crea uno vacío), o no habría dónde meterla.
272
272
  const mode = pairReq?.mode === 'adopt' ? 'adopt' : 'join'
273
- const { qr, expiresInMs } = await vault.startPairing({ scope, label, ttlMs: DEVICE_TTL_MS, mode, account: profileName, ...(caps ? { caps } : {}) })
274
- ipcWrite(pairFile, { v: 2, at: Date.now(), qr, expiresAt: Date.now() + expiresInMs, profile: profileId, profileName })
273
+ const { qr, expiresInMs, nearby } = await vault.startPairing({ scope, label, ttlMs: DEVICE_TTL_MS, mode, account: profileName, ...(caps ? { caps } : {}) })
274
+ ipcWrite(pairFile, { v: 2, at: Date.now(), qr, expiresAt: Date.now() + expiresInMs, profile: profileId, profileName, nearby: !!nearby })
275
275
  // El token es un secreto efímero: no debe quedar en disco más allá de su
276
276
  // vida. Se borra al VENCER (aquí) y al APROBARSE (abajo, consumido).
277
277
  const tok = qr.token
package/src/platform.js CHANGED
@@ -110,6 +110,10 @@ export function nodePlatform (dir) {
110
110
  readProcContext,
111
111
  openLocalDesk,
112
112
  noticeGroupMs: Number(process.env.DOTRINO_VAULT_NOTICE_MS) || 3000,
113
+ // EL BLUETOOTH del transporte (proxy-client docs/bluetooth.md): en Linux, por BlueZ; en
114
+ // otro sistema el pilar no encuentra con qué y sigue sin él. Sirve para anunciar cerca la
115
+ // invitación de emparejar (pairing-protocol.md §1.6) y como escalón directo.
116
+ bluetooth: true,
113
117
  async openIdentity ({ openKey = null, log = console.log } = {}) {
114
118
  // CIFRADO EN REPOSO ligado a esta máquina: ningún archivo del dir queda en claro, así
115
119
  // que copiarlos a otro equipo no sirve de nada. La identidad se migra AQUÍ (verificando
package/src/tui/app.js CHANGED
@@ -2825,6 +2825,7 @@ function pairingBody (st, t, cols, height, { qr: withQr = true } = {}) {
2825
2825
  lines.push(t.muted(i.pairPaste))
2826
2826
  lines.push(info.b64 || info.payload)
2827
2827
  lines.push('')
2828
+ if (info.nearby) { lines.push(t.muted(i.pairNearby)); lines.push('') }
2828
2829
  lines.push(t.danger(i.pairWarning))
2829
2830
  lines.push('')
2830
2831
  if (st.pending) {
package/src/tui/i18n.js CHANGED
@@ -471,6 +471,7 @@ const es = {
471
471
  pairScan: 'Escanéalo, o abre esta dirección en el dispositivo:',
472
472
  pairUrl: 'URL: ',
473
473
  pairPaste: 'O pega este código en vault.dotrino.com/vault:',
474
+ pairNearby: 'O, en un teléfono cerca, pulsa «Descubrir»: también se anuncia por Bluetooth.',
474
475
  pairWarning: '⚠ Este código deja LEER tus datos y FIRMAR con tu identidad. No lo compartas.',
475
476
  pairConnected: (id) => `⧗ Se conectó: ${id} — pulsa A y escribe el código que muestra.`,
476
477
  pairWaiting: 'Esperando a que el dispositivo se conecte…',
@@ -990,6 +991,7 @@ const en = {
990
991
  pairScan: 'Scan it, or open this address on the device:',
991
992
  pairUrl: 'URL: ',
992
993
  pairPaste: 'Or paste this code into vault.dotrino.com/vault:',
994
+ pairNearby: 'Or, on a phone nearby, tap «Discover»: it is also announced over Bluetooth.',
993
995
  pairWarning: '⚠ This code lets someone READ your data and SIGN as you. Do not share it.',
994
996
  pairConnected: (id) => `⧗ Connected: ${id} — press A and type the code it shows.`,
995
997
  pairWaiting: 'Waiting for the device to connect…',
@@ -846,7 +846,8 @@ export async function startPairing ({ profile, service, label, caps } = {}) {
846
846
  // `profile`/`profileName`: DE QUÉ CUENTA del vault sale este QR. El vault
847
847
  // puede tener varias y el emparejamiento mete al dispositivo en UNA; la TUI
848
848
  // y la CLI lo muestran para que no se enrole en la equivocada.
849
- return { qr: pr.qr, expiresAt: pr.expiresAt, url, payload, code, b64: code, profile: pr.profile || null, profileName: pr.profileName || '' }
849
+ // `nearby`: la invitación también se anuncia por Bluetooth (pairing-protocol.md §1.6).
850
+ return { qr: pr.qr, expiresAt: pr.expiresAt, url, payload, code, b64: code, profile: pr.profile || null, profileName: pr.profileName || '', nearby: !!pr.nearby }
850
851
  }
851
852
  }
852
853
  throw coded('the daemon did not start the pairing', 'PAIR_FAILED')