@dotrino/vaultd 0.189.0 → 0.190.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.
@@ -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.116.0'
8
+ export const LIB_VERSION = '0.118.0'
@@ -22,7 +22,14 @@ export const NOTICE_TTL_MS = 24 * 60 * 60 * 1000
22
22
  * (`docs/pairing-protocol.md` §1.7). No pide nada: no hay a quién bloquear, porque ninguno
23
23
  * entró. Lo cuenta, con el ID y la máquina de los dos.
24
24
  */
25
- export const NOTICE_EVS = ['updated', 'update-needs-root', 'pairing-contested', 'log-anchor']
25
+ export const NOTICE_EVS = ['updated', 'update-needs-root', 'pairing-contested', 'log-anchor', 'delivered']
26
+ /**
27
+ * `delivered`: un aparato con `unattended` se llevó claves de un cajón (`kind: 'secrets'`) o
28
+ * una contraseña (`kind: 'passwords'`) sin que nadie aprobara, porque no le hacía falta (dueño,
29
+ * 2026-11-04: «equipos unattended no deben pedir aprobación, quizás sí notificar que han
30
+ * entregado contraseñas»). No pide nada: lo cuenta. Lleva `ns`, `deviceId` y `label`.
31
+ */
32
+ const DELIVERED_KINDS = ['secrets', 'passwords']
26
33
 
27
34
  const newId = () => [...crypto.getRandomValues(new Uint8Array(8))].map((b) => b.toString(16).padStart(2, '0')).join('')
28
35
 
@@ -58,8 +65,17 @@ export function openNotices ({ disk, now = Date.now }) {
58
65
  * administrador). `product`: qué (`@dotrino/vaultd` es la propia bóveda);
59
66
  * `deviceId`/`label`: el aparato, si fue uno.
60
67
  */
61
- add (ev, { version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null, devices = null, logSeq = null, head = null, tsa = null }) {
68
+ add (ev, { version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null, devices = null, logSeq = null, head = null, tsa = null, ns = null, kind = null }) {
62
69
  if (!NOTICE_EVS.includes(ev)) throw fail('bad-notice', `unknown notice: ${ev}`)
70
+ if (ev === 'delivered') {
71
+ if (!DELIVERED_KINDS.includes(kind)) throw fail('bad-notice', `${ev}: kind must be one of ${DELIVERED_KINDS.join(', ')}`)
72
+ if (typeof ns !== 'string' || !ns) throw fail('bad-notice', `${ev}: the drawer (ns) is required`)
73
+ if (typeof deviceId !== 'string' || !deviceId) throw fail('bad-notice', `${ev}: the device is required`)
74
+ const n = { id: newId(), ev, kind, ns, deviceId, label: typeof label === 'string' ? label : '', ts: now() }
75
+ items = [...items.filter(alive), n]
76
+ save()
77
+ return n
78
+ }
63
79
  // EL ANCLA DE LA BITÁCORA (`logAnchor.js`): la cabeza sellada por el signer, para que el
64
80
  // aprobador la guarde. Solo se queda la última: la anterior ya no dice nada que esta no diga.
65
81
  if (ev === 'log-anchor') {
@@ -36,6 +36,7 @@ export const PASSWORDS_CAP = 'passwords'
36
36
  * `encPubOf(pubkey)` su llave de cifrado, para sellarle la respuesta
37
37
  * `needsApproval(pubkey)` (async) si ese aparato tiene que pedir aprobación (`unattended`)
38
38
  * `approve({ pubkey, op })` pide el visto bueno (el teléfono) y espera
39
+ * `onDelivered(pubkey)` se sirvió una lectura (`pm2.get`) a ese aparato
39
40
  * `audit(op, info)` la bitácora del vault
40
41
  */
41
42
  export function createPasswordDesk (opts = {}) {
@@ -48,6 +49,7 @@ export function createPasswordDesk (opts = {}) {
48
49
  encPubOf = () => null,
49
50
  needsApproval = () => true,
50
51
  approve = async () => false,
52
+ onDelivered = () => {},
51
53
  audit = () => {},
52
54
  log = () => {},
53
55
  } = opts
@@ -73,6 +75,8 @@ export function createPasswordDesk (opts = {}) {
73
75
  // La bitácora NO lleva qué credencial se pidió: eso es contenido del usuario.
74
76
  audit('passwords', { op: r.op, outcome: r.outcome, device: (r.from || '').slice(0, 24) })
75
77
  if (r.outcome !== 'ok') log(`[vault] passwords: ${r.op} ${r.outcome}`)
78
+ // Una LECTURA servida: quien llama decide si hay que contarla (`unattended`, ver vault.js).
79
+ else if (r.op === 'pm2.get' && r.from) onDelivered(r.from)
76
80
  },
77
81
  })
78
82
 
@@ -2036,6 +2036,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2036
2036
  }
2037
2037
  audit('secrets', { device: await deviceIdOf(chk.device), ns, ...(publicOnly ? { publicOnly: true } : {}) })
2038
2038
  reply(from, { type: MSG.SECRETS_RESULT, ...res })
2039
+ if (!publicOnly) announceDelivered({ device: chk.device, ns, kind: 'secrets' })
2039
2040
  }
2040
2041
 
2041
2042
  /** El bundle de `ns` para `devicePub`, sellado a su `ek` y firmado por la llave de sellado. */
@@ -2249,6 +2250,42 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2249
2250
  * en vez de mandárselo en claro «para que al menos lo vea»: eso sería cambiar la promesa
2250
2251
  * por comodidad, y encima sin avisar a nadie.
2251
2252
  */
2253
+ /** Un objeto pequeño sellado a un `encPub` del acta: `{ wrap, envelope }`, lo abre `openSealed`. */
2254
+ async function sealTo (encPub, obj) {
2255
+ const cek = await makeContentKey()
2256
+ const envelope = await encryptWithCek({ cek, gen: 0, plaintext: JSON.stringify(obj) })
2257
+ const wrap = await wrapForMember({ cek, memberEncPub: encPub })
2258
+ return { wrap, envelope }
2259
+ }
2260
+
2261
+ /**
2262
+ * EL ASUNTO DEL TIMBRE, SELLADO AL TELÉFONO (dueño, 2026-11-04: «que las notificaciones a
2263
+ * móviles no sean del todo anónimas sino que al menos tengan asunto, para ver quién solicita
2264
+ * qué»). El timbre que sale por FCM/APNs lo leen Google y Apple, así que el proxio lo manda
2265
+ * vacío. Lo que va aquí viaja dentro del mensaje como `ring` y el proxio lo pega al timbre
2266
+ * TAL CUAL: va cifrado a la `encPub` del aprobador, y solo su teléfono lo abre, sin red.
2267
+ *
2268
+ * Es solo el asunto. Quien aprueba sigue decidiendo con la lista (`op: 'approvals'`), que
2269
+ * es la que va firmada: un asunto falso no aprueba nada.
2270
+ *
2271
+ * Sin `encPub` en el acta no hay asunto (y el teléfono enseña el genérico): mandarlo en claro
2272
+ * sería cambiar la promesa sin avisar.
2273
+ */
2274
+ const RING_CTX_KEYS = ['op', 'fields', 'product', 'version', 'from', 'reporterLabel', 'kind']
2275
+ async function ringFor (pub, record, hint) {
2276
+ const encPub = (record?.members || []).find((m) => m.pub === pub)?.encPub || null
2277
+ if (!encPub) return null
2278
+ let ctx = null
2279
+ if (hint.ctx && typeof hint.ctx === 'object') {
2280
+ ctx = {}
2281
+ for (const k of RING_CTX_KEYS) if (hint.ctx[k] != null) ctx[k] = hint.ctx[k]
2282
+ }
2283
+ try { return await sealTo(encPub, { ...hint, ctx }) } catch (e) {
2284
+ log(`[vault] could not seal the subject of the ring for ${pub.slice(0, 24)}…: ${e.message}`)
2285
+ return null
2286
+ }
2287
+ }
2288
+
2252
2289
  async function withSealedContext (items, approver, record) {
2253
2290
  const encPub = (record?.members || []).find((m) => m.pub === approver)?.encPub || null
2254
2291
  const output = []
@@ -2257,9 +2294,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2257
2294
  if (!ctx) { output.push({ ...rest, ctx: null }); continue }
2258
2295
  if (!encPub) { output.push({ ...rest, ctx: null, ctxSealed: false, ctxReason: 'no-enc-key' }); continue }
2259
2296
  try {
2260
- const cek = await makeContentKey()
2261
- const envelope = await encryptWithCek({ cek, gen: 0, plaintext: JSON.stringify(ctx) })
2262
- const wrap = await wrapForMember({ cek, memberEncPub: encPub })
2297
+ const { wrap, envelope } = await sealTo(encPub, ctx)
2263
2298
  output.push({ ...rest, ctx: null, ctxSealed: true, ctxWrap: wrap, ctxEnvelope: envelope })
2264
2299
  } catch (e) {
2265
2300
  // NO SE TRAGA: sin esto, un fallo al sellar se vería en el teléfono igual que un
@@ -2300,7 +2335,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2300
2335
  for (const pub of who) {
2301
2336
  // A la app que APRUEBA (`vault`): en un teléfono la llave es de todas sus apps, y sin
2302
2337
  // decirlo el pedido timbraba a messenger (websocket-proxy ≥ 1.4.0).
2303
- try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal }, { app: 'vault' }) }
2338
+ const ring = await ringFor(pub, record, { ...body, ctx: pend.ctx || null })
2339
+ try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal, ...(ring ? { ring } : {}) }, { app: 'vault' }) }
2304
2340
  catch (e) { log(`[vault] could not ring ${pub.slice(0, 24)}… about ${pend.ns}: ${e.message}`) }
2305
2341
  }
2306
2342
  log(`[vault] ${pend.ns}: rang ${who.length} approver(s) for ${pend.id}`)
@@ -2331,9 +2367,12 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2331
2367
  const { id, ev, ts, ...rest } = notice
2332
2368
  const body = { ev, id, ...rest, ts }
2333
2369
  const seal = await sealOrFail(body)
2370
+ // Lo que calla no timbra: no lleva asunto. Lo que suena, sí (ver `ringFor`).
2371
+ const record = quiet ? null : await refreshActa()
2334
2372
  let sent = 0
2335
2373
  for (const pub of who) {
2336
- try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal }, { app: 'vault', ...(quiet ? { quiet: true } : {}) }); sent++ }
2374
+ const ring = quiet ? null : await ringFor(pub, record, { ev, id, ts, kind: rest.kind || null, ns: rest.ns || null, deviceId: rest.deviceId || null, label: rest.label || null, product: rest.product || null, version: rest.version || null, from: rest.from || null })
2375
+ try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal, ...(ring ? { ring } : {}) }, { app: 'vault', ...(quiet ? { quiet: true } : {}) }); sent++ }
2337
2376
  catch (e) { log(`[vault] could not tell ${pub.slice(0, 24)}… about ${what}: ${e.message}`) }
2338
2377
  }
2339
2378
  return sent
@@ -2402,6 +2441,39 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2402
2441
  return { approvers: who.length, sent, notice }
2403
2442
  }
2404
2443
 
2444
+ /**
2445
+ * «SE LLEVÓ CLAVES SIN PEDIR», a quien aprueba (dueño, 2026-11-04). Un aparato con
2446
+ * `unattended` no pide aprobación —para eso se le dio—, pero que lo haga en silencio deja al
2447
+ * dueño sin saber qué máquina se llevó qué. Se cuenta como aviso (`delivered`), no como pedido.
2448
+ *
2449
+ * UNO POR APARATO, CAJÓN Y HORA: un servicio pide su cajón en cada arranque y el gestor una
2450
+ * contraseña en cada relleno; timbrar cada vez enseña a ignorar el timbre. Solo cuando de
2451
+ * verdad no se pidió por `unattended`: sin aprobadores no hay a quién contar, y lo aprobado
2452
+ * ya lo vio quien aprobó.
2453
+ */
2454
+ const DELIVERED_EVERY_MS = 60 * 60 * 1000
2455
+ const deliveredAt = new Map()
2456
+ async function announceDelivered ({ device, ns, kind }) {
2457
+ try {
2458
+ const record = await refreshActa()
2459
+ if (!record || !Acta.memberCan(record, device, 'unattended')) return
2460
+ const who = (record.members || []).filter((m) => Acta.memberCan(record, m.pub, 'approve')).map((m) => m.pub)
2461
+ if (!who.length) return
2462
+ const key = `${device}|${kind}|${ns}`
2463
+ const now = Date.now()
2464
+ if (now - (deliveredAt.get(key) || 0) < DELIVERED_EVERY_MS) return
2465
+ deliveredAt.set(key, now)
2466
+ for (const [k, t] of deliveredAt) if (now - t >= DELIVERED_EVERY_MS) deliveredAt.delete(k)
2467
+ const deviceId = await deviceIdOf(device).catch(() => null)
2468
+ if (!deviceId) return log(`[vault] delivered: could not name the device that took ${kind} of ${ns}, so nobody is told`)
2469
+ const label = (record.members || []).find((m) => m.pub === device)?.label || ''
2470
+ const notice = notices.add('delivered', { kind, ns, deviceId, label })
2471
+ const sent = await sendNotice(notice, who, `the delivery of ${kind} of ${ns} to ${deviceId}`)
2472
+ audit('delivered.announced', { device: deviceId, ns, kind, approvers: who.length, sent })
2473
+ log(`[vault] delivered: told ${sent} of ${who.length} approver(s) that ${deviceId} took ${kind} of ${ns} without approval (unattended)`)
2474
+ } catch (e) { log(`[vault] delivered: could not tell the approvers (${e.code || 'error'}: ${e.message})`) }
2475
+ }
2476
+
2405
2477
  /**
2406
2478
  * UN INCIDENTE: un agente de la cuenta dice que OTRO aparato de la cuenta se equivocó de
2407
2479
  * clave tres veces seguidas (la terminal, `dotrino-terminal lock`). No se decide aquí
@@ -2676,6 +2748,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2676
2748
  // el permiso se seguía sirviendo solo.
2677
2749
  needsApproval: passwordsNeedApproval,
2678
2750
  approve: approvePasswordRequest,
2751
+ onDelivered: (pub) => announceDelivered({ device: pub, ns: 'passwords', kind: 'passwords' }),
2679
2752
  audit,
2680
2753
  log,
2681
2754
  }).start()
@@ -26,7 +26,7 @@ import {
26
26
  makeDeviceKey, makeDeviceEncKey, importDeviceEncKey, signWithDevice,
27
27
  verifyDeviceSig, makePairingCode, commitCode, pubkeyId, keyLabel } from '@dotrino/identity/capabilities'
28
28
  import { openWrap, wrapForMember, decryptWithCek } from '@dotrino/identity/content'
29
- import { verifyActa, sealKeyAt, sealersOf, memberCan, checkVaultReply, accountMismatch } from '@dotrino/identity/acta'
29
+ import { verifyActa, sealKeyAt, sealersOf, memberCan, checkVaultReply, accountMismatch, verifySealerChain, actaHash } from '@dotrino/identity/acta'
30
30
  import { MSG, secretsScope, isValidSecretsNs, VAULT_PROTOCOL, VAULT_SPEAKS } from './protocol.js'
31
31
  import { PKG_VERSION } from './version.js'
32
32
  import { makeEphemeralKey, openSealed } from './sealed.js'
@@ -250,9 +250,9 @@ function waitForMsg (client, predicate, timeoutMs = 30000, guard = null) {
250
250
  export const requestRef = (signature) => createHash('sha256').update(String(signature || '')).digest('hex')
251
251
 
252
252
  /** ¿Este error lo firmó una llave de sellado del acta, y es para esta petición? */
253
- export async function isMyVaultError (p, { re, masterPubkey, knownSeq = null, knownSealers = null }) {
253
+ export async function isMyVaultError (p, { re, masterPubkey, knownSeq = null, knownSealers = null, askSealerChain = null }) {
254
254
  if (!p?.signed || p.signed.re !== re || p.signed.op !== 'secrets.error' || p.signed.error !== p.error) return false
255
- try { await verifyResponder({ body: p.signed, seal: p.seal, acta: p.acta, masterPubkey, knownSeq, knownSealers }); return true } catch (_) { return false }
255
+ try { await verifyResponder({ body: p.signed, seal: p.seal, acta: p.acta, masterPubkey, knownSeq, knownSealers, askSealerChain }); return true } catch (_) { return false }
256
256
  }
257
257
 
258
258
  const identityFileOf = (dir) => path.join(dir, IDENTITY_FILE)
@@ -565,11 +565,12 @@ export async function registerEncKey ({ dir, ns, proxyUrl, masterPubkey, device,
565
565
  if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
566
566
 
567
567
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
568
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
568
569
  try {
569
570
  await identifyAsService(client, device)
570
571
  const data = { op: 'enckey', ns, encPub, publickey: device.publickey, ts: Date.now() }
571
572
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
572
- const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
573
+ const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
573
574
  client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data, signature, cert })
574
575
  const res = await pending
575
576
  if (res.type === MSG.ERROR) throw vaultError(res)
@@ -616,16 +617,17 @@ export async function storeVars ({ dir, ns, proxyUrl, masterPubkey, device, cert
616
617
  }
617
618
 
618
619
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
620
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
619
621
  try {
620
622
  await identifyAsService(client, device)
621
623
  const ask = async (data) => {
622
624
  const signed = { ...data, ns, publickey: device.publickey, ts: Date.now() }
623
625
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data: signed })
624
- const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
626
+ const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
625
627
  client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data: signed, signature, cert })
626
628
  const res = await pending
627
629
  if (res.type === MSG.ERROR) throw vaultError(res)
628
- await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
630
+ await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
629
631
  if (res.body?.op !== data.op.replace(/^store$/, 'store.result') || res.body?.ns !== ns) throw new Error('the vault answered something else')
630
632
  return res.body
631
633
  }
@@ -671,15 +673,16 @@ export async function fetchDigest ({ dir, ns, proxyUrl, masterPubkey, device, ce
671
673
  if (!isValidSecretsNs(ns)) throw new Error('invalid ns')
672
674
  if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
673
675
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
676
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
674
677
  try {
675
678
  await identifyAsService(client, device)
676
679
  const data = { op: 'digest', ns, publickey: device.publickey, ts: Date.now() }
677
680
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
678
- const pending = waitForMsg(client, (p) => p.type === MSG.ERROR || (p.type === MSG.SECRETS_RESULT && p.body?.op === 'secrets.digest'), timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
681
+ const pending = waitForMsg(client, (p) => p.type === MSG.ERROR || (p.type === MSG.SECRETS_RESULT && p.body?.op === 'secrets.digest'), timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
679
682
  client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data, signature, cert })
680
683
  const res = await pending
681
684
  if (res.type === MSG.ERROR) throw vaultError(res)
682
- await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
685
+ await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
683
686
  if (res.body.ns !== ns || typeof res.body.digest !== 'string') throw new Error('malformed digest reply')
684
687
  if (typeof res.body.ts !== 'number' || Math.abs(Date.now() - res.body.ts) > FRESH_WINDOW_MS) throw new Error('stale digest reply')
685
688
  return res.body.digest
@@ -723,6 +726,7 @@ export async function askUpdateApproval ({ product, version, from = null, dir, p
723
726
  if (typeof product !== 'string' || !product || typeof version !== 'string' || !version) throw new Error('askUpdateApproval: needs product and version')
724
727
  if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
725
728
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
729
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
726
730
  try {
727
731
  await identifyAsService(client, device)
728
732
  const data = { op: 'update-ask', product, version, ...(typeof from === 'string' && from ? { from } : {}), publickey: device.publickey, ts: Date.now() }
@@ -730,7 +734,7 @@ export async function askUpdateApproval ({ product, version, from = null, dir, p
730
734
  const mine = (p) => p.type === MSG.ERROR || (p.type === MSG.SECRETS_RESULT && p.body?.op === 'update-ask' && p.body.product === product && p.body.version === version)
731
735
  const check = async (res) => {
732
736
  if (res.type === MSG.ERROR) throw vaultError(res)
733
- await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
737
+ await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
734
738
  if (typeof res.body.ts !== 'number' || Math.abs(Date.now() - res.body.ts) > FRESH_WINDOW_MS) throw new Error('stale update-ask reply')
735
739
  return res.body
736
740
  }
@@ -836,18 +840,19 @@ async function reportToVault (op, { product, version, from = null, dir, proxyUrl
836
840
  if (typeof product !== 'string' || !product || typeof version !== 'string' || !version) throw new Error(`${op}: needs product and version`)
837
841
  if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
838
842
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
843
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
839
844
  try {
840
845
  await identifyAsService(client, device)
841
846
  const data = { op, product, version, ...(typeof from === 'string' && from ? { from } : {}), publickey: device.publickey, ts: Date.now() }
842
847
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
843
- const pending = waitForMsg(client, (p) => p.type === MSG.ERROR || (p.type === MSG.SECRETS_RESULT && p.body?.op === op && p.body.product === product && p.body.version === version), timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
848
+ const pending = waitForMsg(client, (p) => p.type === MSG.ERROR || (p.type === MSG.SECRETS_RESULT && p.body?.op === op && p.body.product === product && p.body.version === version), timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
844
849
  client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data, signature, cert })
845
850
  const res = await pending.catch((e) => {
846
851
  if (/timeout/.test(e.message)) throw Object.assign(new Error(`${op}: the vault did not answer`), { code: 'vault-no-reply' })
847
852
  throw e
848
853
  })
849
854
  if (res.type === MSG.ERROR) throw vaultError(res)
850
- await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
855
+ await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
851
856
  if (res.body.ok !== true) throw new Error(`malformed ${op} reply`)
852
857
  return { ok: true }
853
858
  } finally { client.close() }
@@ -877,6 +882,7 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
877
882
  }
878
883
 
879
884
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
885
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
880
886
  try {
881
887
  await identifyAsService(client, device)
882
888
 
@@ -1000,7 +1006,7 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
1000
1006
  res = null
1001
1007
  let last = null
1002
1008
  for (const target of targets) {
1003
- const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, byTarget, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
1009
+ const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, byTarget, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
1004
1010
  client.sendByPubkey(target, { type: MSG.SECRETS, data, signature, cert })
1005
1011
  try { res = await pending; break } catch (e) { last = e }
1006
1012
  }
@@ -1018,11 +1024,11 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
1018
1024
  // verdad llega cuando el aparato que aprueba firme — por esta misma conexión, que
1019
1025
  // sigue identificada. Se espera lo que dura el pedido; denegado o vencido es error.
1020
1026
  if (res.body?.op === 'secrets.pending' && res.body.ns === ns) {
1021
- await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
1027
+ await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
1022
1028
  recordActa(res.acta)
1023
1029
  try { onPending?.({ id: res.body.id, ns, exp: res.body.exp }) } catch (_) {}
1024
1030
  const until = typeof res.body.exp === 'number' ? Math.max(5000, res.body.exp - Date.now() + 5000) : approvalTimeoutMs
1025
- res = await waitForMsg(client, (p) => (p.type === MSG.SECRETS_RESULT && p.body?.op === 'secrets.result') || p.type === MSG.ERROR, Math.min(until, approvalTimeoutMs), { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
1031
+ res = await waitForMsg(client, (p) => (p.type === MSG.SECRETS_RESULT && p.body?.op === 'secrets.result') || p.type === MSG.ERROR, Math.min(until, approvalTimeoutMs), { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
1026
1032
  .catch((e) => {
1027
1033
  if (/timeout/.test(e.message)) throw Object.assign(new Error('approval: nobody approved the request in time'), { code: 'unanswered' })
1028
1034
  throw e
@@ -1043,7 +1049,7 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
1043
1049
  // confía en nadie — solo saca el acta con la que SÍ se comprueba. Nada de lo que hay
1044
1050
  // dentro se usa hasta después de verificar.
1045
1051
  const payload = await openSealed({ privateKey: eph.privateKey, enc: body.enc })
1046
- await verifyResponder({ body, seal: res.seal, acta: payload?.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
1052
+ await verifyResponder({ body, seal: res.seal, acta: payload?.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
1047
1053
  recordActa(payload?.acta)
1048
1054
  // La huella de lo que se acaba de recibir: con ella se compara después (`fetchDigest`)
1049
1055
  // sin volver a pedir claves. Ya comprobada: va dentro del cuerpo firmado.
@@ -1137,7 +1143,7 @@ export function rewrapTarget (acta, targetPub, ns) {
1137
1143
  return { ok: false, why: `is neither part of «${ns}» nor a vault of the account` }
1138
1144
  }
1139
1145
 
1140
- export async function verifyResponder ({ body, seal, acta, masterPubkey, knownSeq = null, knownSealers = null }) {
1146
+ export async function verifyResponder ({ body, seal, acta, masterPubkey, knownSeq = null, knownSealers = null, askSealerChain = null }) {
1141
1147
  if (!seal?.sig) {
1142
1148
  throw new Error('the reply carries no sealing signature: this vault is too old to serve (update it)')
1143
1149
  }
@@ -1145,9 +1151,27 @@ export async function verifyResponder ({ body, seal, acta, masterPubkey, knownSe
1145
1151
  // LAS DOS SON MAESTRA (`docs/replicas.md` §11.5): el acta la puede haber sellado cualquier
1146
1152
  // bóveda de la cuenta. Vale la maestra que este agente conoce, o una a la que el acta que YA
1147
1153
  // aceptó le dejaba sellar (`knownSealers`, ver `recordActa`): es la cadena de selladoras,
1148
- // comprobada paso a paso. Una que nunca vio no vale, aunque el acta diga que sella.
1149
- if (acta.sealedBy !== masterPubkey && !(Array.isArray(knownSealers) && knownSealers.includes(acta.sealedBy))) {
1150
- throw new Error('the record was not sealed by a vault this agent knows: refusing the reply')
1154
+ // comprobada paso a paso.
1155
+ //
1156
+ // Y UNA QUE NO HA VISTO, SI LA CADENA LA LLEVA HASTA ELLA (2026-11-04). Un agente que se quedó
1157
+ // en una acta de antes de que la cuenta tuviera otra bóveda —o que nunca guardó selladoras—
1158
+ // rechazaba la primera acta que sellara la nueva, y como solo aprende de actas que acepta, se
1159
+ // quedaba trabado para siempre (aws-glassnote: conocía la #57, la #77 la selló NubeLambda).
1160
+ // Ahora pide la cadena de selladoras y la comprueba desde la maestra que conoce
1161
+ // (`sealedByChain`): si encadena, la selladora vale; si no, se rechaza como antes.
1162
+ const known = acta.sealedBy === masterPubkey || (Array.isArray(knownSealers) && knownSealers.includes(acta.sealedBy))
1163
+ if (!known) {
1164
+ if (!askSealerChain) {
1165
+ throw Object.assign(new Error('the record was not sealed by a vault this agent knows: refusing the reply'), { code: 'unknown-sealer' })
1166
+ }
1167
+ let chain
1168
+ try { chain = await askSealerChain() } catch (e) {
1169
+ throw Object.assign(new Error('the record was sealed by a vault this agent does not know, and the sealer chain could not be fetched: ' + e.message), { code: 'unknown-sealer' })
1170
+ }
1171
+ const r = await sealedByChain({ chain, acta, masterPubkey })
1172
+ if (!r.ok) {
1173
+ throw Object.assign(new Error('the record was sealed by a vault this agent does not know, and the sealer chain does not vouch for it: ' + r.reason), { code: 'unknown-sealer' })
1174
+ }
1151
1175
  }
1152
1176
  if (!(await verifyActa({ acta })).ok) throw new Error('the record does not verify')
1153
1177
 
@@ -1185,6 +1209,66 @@ export async function verifyResponder ({ body, seal, acta, masterPubkey, knownSe
1185
1209
  }
1186
1210
  }
1187
1211
 
1212
+ /**
1213
+ * ¿LA CADENA DE SELLADORAS LLEVA, DESDE LA MAESTRA QUE CONOZCO, HASTA QUIEN SELLÓ ESTA ACTA?
1214
+ *
1215
+ * `chain` es la de `identity.sealerChain()` (génesis, cambios de sellador, la vigente), tal
1216
+ * como la manda la bóveda en `vault.devices`. Puede venir de cualquiera —el proxio, otra
1217
+ * bóveda—, así que no se le cree nada: se comprueba entera.
1218
+ *
1219
+ * 1. Encadena (`verifySealerChain`): cada eslabón lo selló alguien a quien el anterior
1220
+ * dejaba sellar, desde una raíz firmada por la llave del perfil de ESTA acta.
1221
+ * 2. Es MI cuenta: algún eslabón lo firmó la maestra que este agente lleva pineada. Sin
1222
+ * esto, cualquiera fabrica una cuenta suya que nombre a mi maestra como selladora.
1223
+ * 3. El acta cuelga de esa cadena: se pone detrás del último cambio de sellador anterior a
1224
+ * ella y se vuelve a comprobar, así que quien la selló tenía permiso según ese eslabón
1225
+ * (y su ancla, si la lleva, apunta a él). Si la cadena ya la trae, tiene que ser la misma.
1226
+ */
1227
+ export async function sealedByChain ({ chain, acta, masterPubkey }) {
1228
+ if (!Array.isArray(chain) || !chain.length) return { ok: false, reason: 'empty-chain' }
1229
+ if (!acta || typeof acta.seq !== 'number') return { ok: false, reason: 'no-record' }
1230
+ const whole = await verifySealerChain(chain, { expectedProfileId: acta.profileId })
1231
+ if (!whole.ok) return { ok: false, reason: whole.reason }
1232
+ if (!chain.some((a) => a.sealedBy === masterPubkey)) return { ok: false, reason: 'not-my-account' }
1233
+ const same = chain.find((a) => a.seq === acta.seq)
1234
+ let path
1235
+ if (same) {
1236
+ if (await actaHash(same) !== await actaHash(acta)) return { ok: false, reason: 'other-record' }
1237
+ path = chain.filter((a) => a.seq <= acta.seq)
1238
+ } else {
1239
+ const before = chain.filter((a) => a.seq < acta.seq)
1240
+ // Lo último de la cadena puede ser el acta vigente de entonces, que no cambió selladores:
1241
+ // el ancla del acta apunta al último CAMBIO, así que eso se quita (la raíz se queda).
1242
+ while (before.length > 1 && !before[before.length - 1].sealerChanged) before.pop()
1243
+ if (!before.length) return { ok: false, reason: 'record-before-chain' }
1244
+ path = [...before, acta]
1245
+ }
1246
+ if (!path.some((a) => a.sealedBy === masterPubkey)) return { ok: false, reason: 'not-my-account' }
1247
+ const v = await verifySealerChain(path, { expectedProfileId: acta.profileId })
1248
+ return v.ok ? { ok: true } : { ok: false, reason: v.reason }
1249
+ }
1250
+
1251
+ /**
1252
+ * Pide la cadena de selladoras a la bóveda (`vault.devices`: la manda también a un servicio
1253
+ * sin `lee`). Una vez por operación: la segunda llamada reusa la primera respuesta.
1254
+ */
1255
+ export function sealerChainAsker ({ client, masterPubkey, device, cert, timeoutMs = 15000 }) {
1256
+ let pending = null
1257
+ return () => {
1258
+ pending = pending || (async () => {
1259
+ const data = { op: 'devices', publickey: device.publickey, ts: Date.now() }
1260
+ const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
1261
+ const wait = waitForMsg(client, (p) => p.type === MSG.DEVICES_RESULT || (p.type === MSG.ERROR && !p.signed), timeoutMs)
1262
+ client.sendByPubkey(masterPubkey, { type: MSG.DEVICES, data, signature, cert })
1263
+ const res = await wait
1264
+ if (res.type === MSG.ERROR) throw new Error('the vault refused: ' + res.error)
1265
+ if (!Array.isArray(res.sealerChain) || !res.sealerChain.length) throw new Error('the vault sent no sealer chain')
1266
+ return res.sealerChain
1267
+ })()
1268
+ return pending
1269
+ }
1270
+ }
1271
+
1188
1272
  /**
1189
1273
  * ¿SALIÓ ESTE SOBRE DE MI BÓVEDA? (§8.8 de `dotrino-vault/docs/secretos-sellados.md`)
1190
1274
  *
@@ -1367,6 +1451,9 @@ export async function watchSecretsChanges ({
1367
1451
  const inFlight = new Set() // avisos cuya firma se está comprobando ahora mismo
1368
1452
  let stopped = false
1369
1453
  let client = null
1454
+ // La cadena de selladoras, pedida por la conexión viva. Una por aviso: se rehace cada vez
1455
+ // porque la conexión cambia al reconectar.
1456
+ const watchChainAsker = () => sealerChainAsker({ client, masterPubkey: master, device: saved.device, cert: readServiceIdentity(dir)?.cert || saved.cert })
1370
1457
  let retryTimer = null
1371
1458
  // Huella de la configuración EN USO. Comparar huellas y no valores es lo que permite
1372
1459
  // decir «esto no es lo que está corriendo» sin volver a manejar los secretos.
@@ -1430,16 +1517,11 @@ export async function watchSecretsChanges ({
1430
1517
  const mineOwners = [`ns:${ns}`, `dev:${saved.device.publickey}`]
1431
1518
  if (!mineOwners.includes(body.owner)) return log('[vault] rewrap for a drawer that is not mine: ignored')
1432
1519
  try {
1433
- await verifyResponder({ body, seal: payload.seal, acta: body.acta, masterPubkey: master, knownSeq: readServiceIdentity(dir)?.actaSeq ?? null, knownSealers: readServiceIdentity(dir)?.sealers ?? null })
1520
+ await verifyResponder({ body, seal: payload.seal, acta: body.acta, masterPubkey: master, knownSeq: readServiceIdentity(dir)?.actaSeq ?? null, knownSealers: readServiceIdentity(dir)?.sealers ?? null, askSealerChain: watchChainAsker() })
1434
1521
  } catch (e) { return log(`[vault] rewrap request BADLY SIGNED: ignored (${e.message})`) }
1522
+ // Quién selló el acta ya lo comprobó `verifyResponder` (también con la cadena de
1523
+ // selladoras si era una bóveda que este agente no había visto).
1435
1524
  const acta = body.acta
1436
- // La puede haber sellado cualquier bóveda de la cuenta que este agente ya conoce
1437
- // (`docs/replicas.md` §11.5), igual que en `verifyResponder`.
1438
- const sealers = readServiceIdentity(dir)?.sealers
1439
- const knownSealer = acta && (acta.sealedBy === master || (Array.isArray(sealers) && sealers.includes(acta.sealedBy)))
1440
- if (!acta || !knownSealer || !(await verifyActa({ acta })).ok) {
1441
- return log('[vault] rewrap request without a valid record: ignored')
1442
- }
1443
1525
  const allowed = rewrapTarget(acta, body.target, ns)
1444
1526
  if (!allowed.ok) return log(`[vault] rewrap: ${String(body.target).slice(0, 12)}… ${allowed.why}: refused`)
1445
1527
  const target = allowed.member
@@ -1481,7 +1563,7 @@ export async function watchSecretsChanges ({
1481
1563
  // (la maestra solo firma el acta y reenvuelve sobres, CLAUDE.md).
1482
1564
  let bad = null
1483
1565
  try {
1484
- await verifyResponder({ body, seal: payload.seal, acta: payload.acta, masterPubkey: master, knownSeq: readServiceIdentity(dir)?.actaSeq ?? null, knownSealers: readServiceIdentity(dir)?.sealers ?? null })
1566
+ await verifyResponder({ body, seal: payload.seal, acta: payload.acta, masterPubkey: master, knownSeq: readServiceIdentity(dir)?.actaSeq ?? null, knownSealers: readServiceIdentity(dir)?.sealers ?? null, askSealerChain: watchChainAsker() })
1485
1567
  } catch (e) { bad = e } finally { inFlight.delete(body.ts) }
1486
1568
  if (bad) return log(`[vault] change notice BADLY SIGNED: ignored (${bad.message})`)
1487
1569
  if (body.ts <= lastTs) return
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/vaultd",
3
- "version": "0.189.0",
3
+ "version": "0.190.1",
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": {