@dotrino/vaultd 0.176.2 → 0.178.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.
@@ -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.104.0'
8
+ export const LIB_VERSION = '0.105.0'
@@ -464,20 +464,29 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
464
464
  * Solo lo intenta el master —es el único que sella actas— y no bloquea el arranque: sin
465
465
  * llave los sobres salen sin firma, que es lo que ya pasaba antes de §8.8.
466
466
  */
467
- try {
468
- const info = await identity.profileActa?.()
469
- const acta = info?.acta
470
- // CON EL PERFIL ABIERTO. Estrenar la llave de sellado SELLA EL ACTA, y una bóveda
471
- // cerrada no sella nada — la misma regla que el bloque de abajo. Cerrada se queda sin
472
- // llave y los sobres salen sin firma (lo que ya pasaba antes de §8.8), y se arregla sola
473
- // la primera vez que alguien abra el perfil.
474
- if (info?.isMaster && acta && !isLocked() && (!acta.sealPub || !sealKeys.has(acta.sealPub))) {
467
+ // CADA BÓVEDA, SU LLAVE (`docs/replicas.md` §11.5). Lo que se mira es la llave que el acta
468
+ // nombra para ESTA bóveda (su miembro), no la del acta: con dos bóvedas en la cuenta, la del
469
+ // acta la estrenó la última que selló, y mirar esa hacía que cada una se la quitara a la otra
470
+ // al abrirse. Se llama al arrancar y al abrir (`takeMasterKey`): un perfil con contraseña
471
+ // arranca cerrado siempre, y sin lo segundo no estrenaría la suya nunca.
472
+ async function ensureOwnSealKey () {
473
+ try {
474
+ const info = await identity.profileActa?.()
475
+ const acta = info?.acta
476
+ // CON EL PERFIL ABIERTO. Estrenar la llave de sellado SELLA EL ACTA, y una bóveda
477
+ // cerrada no sella nada. Cerrada se queda sin llave propia y lo que sirve lo firma con
478
+ // la del acta si es suya; si no, no sirve firmado hasta que se abra o una hermana se la
479
+ // nombre («presellar», op `sealkey`).
480
+ if (!info?.isMaster || !acta || isLocked()) return false
481
+ const mine = (acta.members || []).find((m) => m.pub === master)
482
+ if (mine?.sealPub && sealKeys.has(mine.sealPub)) return false
475
483
  const r = await identity.rotateSealKey()
476
484
  // Sin `%s`: este `log` va con un prefijo por delante, así que el formato no es lo
477
485
  // primero y `console.log` no lo sustituye (salía «record #%s 2»).
478
- log(`[vault] new sealing key in record #${r.seq}`)
479
- }
480
- } catch (e) { log('[vault] could not set up the sealing key:', e.message) }
486
+ log(`[vault] new sealing key for this vault in record #${r.seq}`)
487
+ return true
488
+ } catch (e) { log('[vault] could not set up the sealing key:', e.message); return false }
489
+ }
481
490
 
482
491
  /**
483
492
  * LA LLAVE DE COMUNICACIÓN, dentro del acta.
@@ -549,6 +558,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
549
558
  }
550
559
  // Lo que se selló aquí se anuncia cuando ya hay transporte (más abajo): sin el aviso, la otra
551
560
  // bóveda de la cuenta no se entera y las dos acaban con actas distintas del mismo número.
561
+ await ensureOwnSealKey()
552
562
  const commSealedAtStart = await ensureCommKeyInActa()
553
563
 
554
564
  // `announce`: el canal de ESTA cuenta, para que una máquina prestada —que no tiene
@@ -2381,8 +2391,12 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2381
2391
  // El socket se nombra por la LLAVE de esta bóveda: una máquina puede tener varias, y un
2382
2392
  // servicio solo conoce la maestra que lleva pineada. Así los dos lados calculan la misma
2383
2393
  // ruta sin mirar ningún índice.
2394
+ // Se guarda para CERRARLO con la bóveda: abierto tras `close()`, un servicio de esta máquina
2395
+ // seguía entrando por aquí (es el camino más directo) y le contestaba una identidad ya
2396
+ // destruida («Identity not ready»), en vez de salir por el proxio a otra bóveda de la cuenta.
2397
+ let localDesk = null
2384
2398
  if (identity.me?.publickey && typeof platform.openLocalDesk === 'function') {
2385
- platform.openLocalDesk({
2399
+ localDesk = platform.openLocalDesk({
2386
2400
  name: (await pubkeyId(identity.me.publickey)).slice(0, 16),
2387
2401
  onMessage, channels: channels, maxBytes: MAX_REPLY_BYTES, log
2388
2402
  })
@@ -3419,9 +3433,19 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
3419
3433
  async function signSeal (body) {
3420
3434
  try {
3421
3435
  const acta = (await identity.profileActa?.().catch(() => null))?.acta
3422
- if (!acta?.sealPub) return null
3423
- const sig = await sealKeys.sign(acta.sealPub, body)
3424
- return sig ? { seq: acta.seq, sig } : null
3436
+ if (!acta) return null
3437
+ // LA DEL ACTA, SI ES NUESTRA: es la que sabe verificar un agente de antes de §11.5.
3438
+ if (acta.sealPub && sealKeys.has(acta.sealPub)) {
3439
+ const sig = await sealKeys.sign(acta.sealPub, body)
3440
+ if (sig) return { seq: acta.seq, sig }
3441
+ }
3442
+ // LA DE ESTA BÓVEDA (`docs/replicas.md` §11.5): la firma dice de cuál es (`vault`), y quien
3443
+ // verifica busca la llave de esa bóveda en el acta. Así sirve también la bóveda que no
3444
+ // selló la última acta.
3445
+ const mine = (acta.members || []).find((m) => m.pub === master)
3446
+ if (!mine?.sealPub || !sealKeys.has(mine.sealPub)) return null
3447
+ const sig = await sealKeys.sign(mine.sealPub, body)
3448
+ return sig ? { seq: acta.seq, sig, vault: master } : null
3425
3449
  } catch (_) { return null }
3426
3450
  }
3427
3451
 
@@ -4480,6 +4504,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
4480
4504
  try {
4481
4505
  if (await ensureCommKeyInActa()) { await reidentify?.(); await notifyMembers('commkey') }
4482
4506
  } catch (_) {}
4507
+ await ensureOwnSealKey()
4483
4508
  await syncExNotices()
4484
4509
  }
4485
4510
  // Y ABSORBER LO PENDIENTE. La subacta ya lo estaba honrando con el perfil cerrado —de
@@ -4808,6 +4833,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
4808
4833
  for (const t of pendingNotices.values()) clearTimeout(t)
4809
4834
  pendingNotices.clear()
4810
4835
  closeTransport()
4836
+ try { localDesk?.close?.() } catch (_) {}
4811
4837
  try { client.close() } catch (_) {} identity.destroy()
4812
4838
  }
4813
4839
  }
@@ -25,7 +25,7 @@ import {
25
25
  makeDeviceKey, makeDeviceEncKey, importDeviceEncKey, signWithDevice,
26
26
  verifyDeviceSig, makePairingCode, commitCode, pubkeyId, keyLabel } from '@dotrino/identity/capabilities'
27
27
  import { openWrap, wrapForMember, decryptWithCek } from '@dotrino/identity/content'
28
- import { verifyActa, sealKeyAt, memberCan, checkVaultReply, accountMismatch } from '@dotrino/identity/acta'
28
+ import { verifyActa, sealKeyAt, sealersOf, memberCan, checkVaultReply, accountMismatch } from '@dotrino/identity/acta'
29
29
  import { MSG, secretsScope, isValidSecretsNs, VAULT_PROTOCOL, VAULT_SPEAKS } from './protocol.js'
30
30
  import { PKG_VERSION } from './version.js'
31
31
  import { makeEphemeralKey, openSealed } from './sealed.js'
@@ -236,9 +236,9 @@ function waitForMsg (client, predicate, timeoutMs = 30000, guard = null) {
236
236
  export const requestRef = (signature) => createHash('sha256').update(String(signature || '')).digest('hex')
237
237
 
238
238
  /** ¿Este error lo firmó una llave de sellado del acta, y es para esta petición? */
239
- export async function isMyVaultError (p, { re, masterPubkey, knownSeq = null }) {
239
+ export async function isMyVaultError (p, { re, masterPubkey, knownSeq = null, knownSealers = null }) {
240
240
  if (!p?.signed || p.signed.re !== re || p.signed.op !== 'secrets.error' || p.signed.error !== p.error) return false
241
- try { await verifyResponder({ body: p.signed, seal: p.seal, acta: p.acta, masterPubkey, knownSeq }); return true } catch (_) { return false }
241
+ try { await verifyResponder({ body: p.signed, seal: p.seal, acta: p.acta, masterPubkey, knownSeq, knownSealers }); return true } catch (_) { return false }
242
242
  }
243
243
 
244
244
  const identityFileOf = (dir) => path.join(dir, IDENTITY_FILE)
@@ -555,7 +555,7 @@ export async function registerEncKey ({ dir, ns, proxyUrl, masterPubkey, device,
555
555
  await identifyAsService(client, device)
556
556
  const data = { op: 'enckey', ns, encPub, publickey: device.publickey, ts: Date.now() }
557
557
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
558
- const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null })
558
+ 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 })
559
559
  client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data, signature, cert })
560
560
  const res = await pending
561
561
  if (res.type === MSG.ERROR) throw vaultError(res)
@@ -607,11 +607,11 @@ export async function storeVars ({ dir, ns, proxyUrl, masterPubkey, device, cert
607
607
  const ask = async (data) => {
608
608
  const signed = { ...data, ns, publickey: device.publickey, ts: Date.now() }
609
609
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data: signed })
610
- const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null })
610
+ 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 })
611
611
  client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data: signed, signature, cert })
612
612
  const res = await pending
613
613
  if (res.type === MSG.ERROR) throw vaultError(res)
614
- await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null })
614
+ await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
615
615
  if (res.body?.op !== data.op.replace(/^store$/, 'store.result') || res.body?.ns !== ns) throw new Error('the vault answered something else')
616
616
  return res.body
617
617
  }
@@ -661,11 +661,11 @@ export async function fetchDigest ({ dir, ns, proxyUrl, masterPubkey, device, ce
661
661
  await identifyAsService(client, device)
662
662
  const data = { op: 'digest', ns, publickey: device.publickey, ts: Date.now() }
663
663
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
664
- 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 })
664
+ 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 })
665
665
  client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data, signature, cert })
666
666
  const res = await pending
667
667
  if (res.type === MSG.ERROR) throw vaultError(res)
668
- await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null })
668
+ await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
669
669
  if (res.body.ns !== ns || typeof res.body.digest !== 'string') throw new Error('malformed digest reply')
670
670
  if (typeof res.body.ts !== 'number' || Math.abs(Date.now() - res.body.ts) > FRESH_WINDOW_MS) throw new Error('stale digest reply')
671
671
  return res.body.digest
@@ -716,7 +716,7 @@ export async function askUpdateApproval ({ product, version, from = null, dir, p
716
716
  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)
717
717
  const check = async (res) => {
718
718
  if (res.type === MSG.ERROR) throw vaultError(res)
719
- await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null })
719
+ await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
720
720
  if (typeof res.body.ts !== 'number' || Math.abs(Date.now() - res.body.ts) > FRESH_WINDOW_MS) throw new Error('stale update-ask reply')
721
721
  return res.body
722
722
  }
@@ -826,14 +826,14 @@ async function reportToVault (op, { product, version, from = null, dir, proxyUrl
826
826
  await identifyAsService(client, device)
827
827
  const data = { op, product, version, ...(typeof from === 'string' && from ? { from } : {}), publickey: device.publickey, ts: Date.now() }
828
828
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
829
- 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 })
829
+ 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 })
830
830
  client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data, signature, cert })
831
831
  const res = await pending.catch((e) => {
832
832
  if (/timeout/.test(e.message)) throw Object.assign(new Error(`${op}: the vault did not answer`), { code: 'vault-no-reply' })
833
833
  throw e
834
834
  })
835
835
  if (res.type === MSG.ERROR) throw vaultError(res)
836
- await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null })
836
+ await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
837
837
  if (res.body.ok !== true) throw new Error(`malformed ${op} reply`)
838
838
  return { ok: true }
839
839
  } finally { client.close() }
@@ -894,12 +894,16 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
894
894
  */
895
895
  const recordActa = (acta) => {
896
896
  if (typeof acta?.seq !== 'number') return
897
+ // Quién puede sellar según esta acta, que ya se aceptó: con eso se acepta la siguiente
898
+ // aunque la selle otra bóveda de la cuenta (`verifyResponder`). La primera vez se guarda
899
+ // también con el mismo `seq`, porque un agente de antes no lo tenía.
900
+ if (typeof saved?.actaSeq === 'number' && acta.seq === saved.actaSeq && !Array.isArray(saved.sealers)) remember({ sealers: sealersOf(acta) })
897
901
  if (typeof saved?.actaSeq === 'number' && acta.seq <= saved.actaSeq) return
898
902
  // Y QUIÉNES REPARTEN. Sale del acta, que llega firmada en cada respuesta, así que no
899
903
  // hay una lista que mantener a mano ni un `.env` que se olvide: darle `replica` a un
900
904
  // aparato basta para que sus servicios sepan preguntarle cuando la bóveda no esté.
901
905
  const replicas = (acta.members || []).filter((m) => memberCan(acta, m.pub, 'replica')).map((m) => m.pub)
902
- remember({ actaSeq: acta.seq, replicas })
906
+ remember({ actaSeq: acta.seq, replicas, sealers: sealersOf(acta) })
903
907
  }
904
908
 
905
909
  // DOS MOTIVOS PARA PEDIR PAPEL NUEVO:
@@ -978,7 +982,7 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
978
982
  let res = null
979
983
  let last = null
980
984
  for (const target of targets) {
981
- const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, byTarget, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null })
985
+ 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 })
982
986
  client.sendByPubkey(target, { type: MSG.SECRETS, data, signature, cert })
983
987
  try { res = await pending; break } catch (e) { last = e }
984
988
  }
@@ -989,11 +993,11 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
989
993
  // verdad llega cuando el aparato que aprueba firme — por esta misma conexión, que
990
994
  // sigue identificada. Se espera lo que dura el pedido; denegado o vencido es error.
991
995
  if (res.body?.op === 'secrets.pending' && res.body.ns === ns) {
992
- await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null })
996
+ await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
993
997
  recordActa(res.acta)
994
998
  try { onPending?.({ id: res.body.id, ns, exp: res.body.exp }) } catch (_) {}
995
999
  const until = typeof res.body.exp === 'number' ? Math.max(5000, res.body.exp - Date.now() + 5000) : approvalTimeoutMs
996
- 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 })
1000
+ 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 })
997
1001
  .catch((e) => {
998
1002
  if (/timeout/.test(e.message)) throw Object.assign(new Error('approval: nobody approved the request in time'), { code: 'unanswered' })
999
1003
  throw e
@@ -1014,7 +1018,7 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
1014
1018
  // confía en nadie — solo saca el acta con la que SÍ se comprueba. Nada de lo que hay
1015
1019
  // dentro se usa hasta después de verificar.
1016
1020
  const payload = await openSealed({ privateKey: eph.privateKey, enc: body.enc })
1017
- await verifyResponder({ body, seal: res.seal, acta: payload?.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null })
1021
+ await verifyResponder({ body, seal: res.seal, acta: payload?.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null })
1018
1022
  recordActa(payload?.acta)
1019
1023
  // La huella de lo que se acaba de recibir: con ella se compara después (`fetchDigest`)
1020
1024
  // sin volver a pedir claves. Ya comprobada: va dentro del cuerpo firmado.
@@ -1085,13 +1089,40 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
1085
1089
  * @param {number|null} [knownSeq] El `seq` más alto que este agente ya vio de esta cuenta.
1086
1090
  * `null`/ausente = no conoce la cuenta, y entonces un replicador no vale.
1087
1091
  */
1088
- export async function verifyResponder ({ body, seal, acta, masterPubkey, knownSeq = null }) {
1092
+ /**
1093
+ * A QUIÉN LE PUEDE ENVOLVER UN SERVICIO LA LLAVE DE SU CAJÓN, cuando la bóveda se lo pide
1094
+ * (`rewrap`). Solo de SU cajón —eso lo mira quien llama—, y solo a dos tipos de miembro:
1095
+ *
1096
+ * · los de ese cajón (`cn === ns`): un hermano del servicio;
1097
+ * · las BÓVEDAS de la cuenta (las que el acta deja sellar). Son clones y tienen que tener
1098
+ * todos los cajones (dueño, 2026-10-26: «el sellado delegado verificarás que un
1099
+ * dispositivo sella para las bóvedas existentes» y «si sella de su propio cajón pero para
1100
+ * todas las bóvedas, entendería»). Sin esto, una bóveda nueva se quedaba para siempre sin
1101
+ * el cajón cuya llave solo tiene el servicio.
1102
+ *
1103
+ * Cualquier otro aparato, no: un servicio no amplía el acceso a lo suyo. Y la llave pública
1104
+ * sale del ACTA, nunca del mensaje.
1105
+ *
1106
+ * @returns {{ ok: true, member: object } | { ok: false, why: string }}
1107
+ */
1108
+ export function rewrapTarget (acta, targetPub, ns) {
1109
+ const member = (acta?.members || []).find((m) => m.pub === targetPub)
1110
+ if (!member?.encPub) return { ok: false, why: 'is not in the record (or has no encryption key)' }
1111
+ if (member.cn === ns || memberCan(acta, member.pub, 'sealer')) return { ok: true, member }
1112
+ return { ok: false, why: `is neither part of «${ns}» nor a vault of the account` }
1113
+ }
1114
+
1115
+ export async function verifyResponder ({ body, seal, acta, masterPubkey, knownSeq = null, knownSealers = null }) {
1089
1116
  if (!seal?.sig) {
1090
1117
  throw new Error('the reply carries no sealing signature: this vault is too old to serve (update it)')
1091
1118
  }
1092
1119
  if (!acta) throw new Error('the reply carries no record: cannot tell which key was allowed to sign it')
1093
- if (acta.sealedBy !== masterPubkey) {
1094
- throw new Error('the record was not sealed by the master this agent knows: refusing the reply')
1120
+ // LAS DOS SON MAESTRA (`docs/replicas.md` §11.5): el acta la puede haber sellado cualquier
1121
+ // bóveda de la cuenta. Vale la maestra que este agente conoce, o una a la que el acta que YA
1122
+ // aceptó le dejaba sellar (`knownSealers`, ver `recordActa`): es la cadena de selladoras,
1123
+ // comprobada paso a paso. Una que nunca vio no vale, aunque el acta diga que sella.
1124
+ if (acta.sealedBy !== masterPubkey && !(Array.isArray(knownSealers) && knownSealers.includes(acta.sealedBy))) {
1125
+ throw new Error('the record was not sealed by a vault this agent knows: refusing the reply')
1095
1126
  }
1096
1127
  if (!(await verifyActa({ acta })).ok) throw new Error('the record does not verify')
1097
1128
 
@@ -1121,7 +1152,8 @@ export async function verifyResponder ({ body, seal, acta, masterPubkey, knownSe
1121
1152
  if (typeof seal.seq !== 'number') {
1122
1153
  throw new Error('the reply carries no sealing signature: this vault is too old to serve (update it)')
1123
1154
  }
1124
- const pub = sealKeyAt(acta, seal.seq)
1155
+ // `seal.vault`: la firmó la llave de sellado de UNA bóveda, la que el acta nombra para ella.
1156
+ const pub = sealKeyAt(acta, seal.seq, seal.vault ?? null)
1125
1157
  if (!pub) throw new Error(`the record names no sealing key for #${seal.seq}`)
1126
1158
  if (!(await verifyDeviceSig({ publickey: pub, data: body, signature: seal.sig }))) {
1127
1159
  throw new Error('the reply signature does not check out against the key the record names')
@@ -1141,12 +1173,14 @@ export async function verifyResponder ({ body, seal, acta, masterPubkey, knownSe
1141
1173
  * cazar. Un sobre SIN firma se acepta y se avisa: los hay de antes de que esto existiera
1142
1174
  * y negarse a arrancar por eso apagaría servicios que llevan meses bien.
1143
1175
  */
1144
- export async function makeSealCheck (acta, masterPubkey, log = console.log) {
1176
+ export async function makeSealCheck (acta, masterPubkey, log = console.log, knownSealers = null) {
1145
1177
  if (!acta) return () => {}
1146
1178
  // El acta tiene que venir firmada por la maestra que este agente ya conoce. Si la
1147
1179
  // selló otro (un traspaso que este agente no ha visto), no se puede establecer
1148
1180
  // procedencia: se dice y se sigue, en vez de fingir que se comprobó.
1149
- const ok = acta.sealedBy === masterPubkey && (await verifyActa({ acta })).ok
1181
+ // O una bóveda que el acta ya aceptada dejaba sellar (`docs/replicas.md` §11.5).
1182
+ const known = acta.sealedBy === masterPubkey || (Array.isArray(knownSealers) && knownSealers.includes(acta.sealedBy))
1183
+ const ok = known && (await verifyActa({ acta })).ok
1150
1184
  if (!ok) {
1151
1185
  log('[vault] ⚠ the record does not come from the master this agent knows: envelope provenance NOT checked')
1152
1186
  return () => {}
@@ -1157,7 +1191,7 @@ export async function makeSealCheck (acta, masterPubkey, log = console.log) {
1157
1191
  if (!warned) { warned = true; log('[vault] ⚠ some envelopes carry no signature (sealed before this vault could sign)') }
1158
1192
  return
1159
1193
  }
1160
- const pub = sealKeyAt(acta, seal.seq)
1194
+ const pub = sealKeyAt(acta, seal.seq, seal.vault ?? null)
1161
1195
  if (!pub) throw new Error(`${key}: the record has no sealing key for #${seal.seq} (the envelope claims a record that does not exist)`)
1162
1196
  const good = await verifyDeviceSig({ publickey: pub, data: { owner, key, gen, iv: e.iv, ct: e.ct }, signature: seal.sig })
1163
1197
  if (!good) throw new Error(`${key}: the envelope signature does not check out — it did not come from this vault`)
@@ -1192,7 +1226,7 @@ async function openSealedBundle (sealed, ident, acta = null, masterPubkey = null
1192
1226
  return cek
1193
1227
  }
1194
1228
 
1195
- const checkSignature = await makeSealCheck(acta, masterPubkey)
1229
+ const checkSignature = await makeSealCheck(acta, masterPubkey, undefined, ident?.sealers ?? null)
1196
1230
 
1197
1231
  const out = {}
1198
1232
  for (const [key, e] of Object.entries(sealed.entries || {})) {
@@ -1371,15 +1405,19 @@ export async function watchSecretsChanges ({
1371
1405
  const mineOwners = [`ns:${ns}`, `dev:${saved.device.publickey}`]
1372
1406
  if (!mineOwners.includes(body.owner)) return log('[vault] rewrap for a drawer that is not mine: ignored')
1373
1407
  try {
1374
- await verifyResponder({ body, seal: payload.seal, acta: body.acta, masterPubkey: master, knownSeq: readServiceIdentity(dir)?.actaSeq ?? null })
1408
+ await verifyResponder({ body, seal: payload.seal, acta: body.acta, masterPubkey: master, knownSeq: readServiceIdentity(dir)?.actaSeq ?? null, knownSealers: readServiceIdentity(dir)?.sealers ?? null })
1375
1409
  } catch (e) { return log(`[vault] rewrap request BADLY SIGNED: ignored (${e.message})`) }
1376
1410
  const acta = body.acta
1377
- if (!acta || acta.sealedBy !== master || !(await verifyActa({ acta })).ok) {
1411
+ // La puede haber sellado cualquier bóveda de la cuenta que este agente ya conoce
1412
+ // (`docs/replicas.md` §11.5), igual que en `verifyResponder`.
1413
+ const sealers = readServiceIdentity(dir)?.sealers
1414
+ const knownSealer = acta && (acta.sealedBy === master || (Array.isArray(sealers) && sealers.includes(acta.sealedBy)))
1415
+ if (!acta || !knownSealer || !(await verifyActa({ acta })).ok) {
1378
1416
  return log('[vault] rewrap request without a valid record: ignored')
1379
1417
  }
1380
- const target = (acta.members || []).find((m) => m.pub === body.target)
1381
- if (!target?.encPub) return log('[vault] rewrap: the target is not in the record (or has no encryption key)')
1382
- if (target.cn !== ns) return log(`[vault] rewrap: ${String(body.target).slice(0, 12)}… is not part of «${ns}»: refused`)
1418
+ const allowed = rewrapTarget(acta, body.target, ns)
1419
+ if (!allowed.ok) return log(`[vault] rewrap: ${String(body.target).slice(0, 12)}… ${allowed.why}: refused`)
1420
+ const target = allowed.member
1383
1421
 
1384
1422
  try {
1385
1423
  const ident = readServiceIdentity(dir)
@@ -1418,7 +1456,7 @@ export async function watchSecretsChanges ({
1418
1456
  // (la maestra solo firma el acta y reenvuelve sobres, CLAUDE.md).
1419
1457
  let bad = null
1420
1458
  try {
1421
- await verifyResponder({ body, seal: payload.seal, acta: payload.acta, masterPubkey: master, knownSeq: readServiceIdentity(dir)?.actaSeq ?? null })
1459
+ await verifyResponder({ body, seal: payload.seal, acta: payload.acta, masterPubkey: master, knownSeq: readServiceIdentity(dir)?.actaSeq ?? null, knownSealers: readServiceIdentity(dir)?.sealers ?? null })
1422
1460
  } catch (e) { bad = e } finally { inFlight.delete(body.ts) }
1423
1461
  if (bad) return log(`[vault] change notice BADLY SIGNED: ignored (${bad.message})`)
1424
1462
  if (body.ts <= lastTs) return
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/vaultd",
3
- "version": "0.176.2",
3
+ "version": "0.178.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,7 +22,7 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@dotrino/compat": "0.4.0",
25
- "@dotrino/identity": "0.127.0",
25
+ "@dotrino/identity": "0.128.0",
26
26
  "@dotrino/opaque": "0.1.0",
27
27
  "@dotrino/passmanager": "0.18.6",
28
28
  "@dotrino/proxy-client": "^0.45.0",
package/src/ctl.js CHANGED
@@ -35,7 +35,8 @@ import { isValidSecretsNs } from './protocol.js'
35
35
  import { parseEnvText, PAIR_RE } from '../lib/src/envtext.js'
36
36
  import { qrToString } from './qr.js'
37
37
  import { encodeInvite, inviteUrl, parseInvite } from '../lib/src/invite.js'
38
- import { atRestFor, readConfig as readKekConfig, probe as probeKek, rekeyDir, encryptedFilesIn, CONFIG_FILE as KEK_CONFIG_FILE } from '../lib/src/atrest.js'
38
+ import { atRestFor, kekFor, readConfig as readKekConfig, probe as probeKek, rekeyDir, encryptedFilesIn, CONFIG_FILE as KEK_CONFIG_FILE } from '../lib/src/atrest.js'
39
+ import { rewrapMachineLayer } from './profiles.js'
39
40
  import { VERSION } from './version.js'
40
41
  import * as hw from './hwkeys.js'
41
42
  import { isNewer } from './update.js'
@@ -199,7 +200,7 @@ function cmdStatus () {
199
200
 
200
201
  /** Una línea por perfil: nombre, id, huella y estado del candado. */
201
202
  function describeProfile (p) {
202
- const lock = !p.protected ? 'sin candado' : `${p.locked ? `${B}🔒 bloqueado${Z}` : '🔓 desbloqueado'} · ${doorsSummary(p)}`
203
+ const lock = !p.protected ? 'sin contraseña' : `${p.locked ? `${B}🔒 bloqueado${Z}` : '🔓 desbloqueado'} · ${doorsSummary(p)}`
203
204
  // ALCANZABLE, Y SE DICE AQUÍ. Una bóveda puede estar corriendo y fuera de la red —si el
204
205
  // proxio le rechazó el `identify`, nadie la alcanza por su pubkey— y desde fuera eso se ve
205
206
  // igual que «no hay nada que aprobar»: el teléfono no timbra y no hay nada que mirar.
@@ -1057,9 +1058,24 @@ function cmdAtrest (rest) {
1057
1058
  console.error(' dotrino-vault atrest rekey %s --anyway', file)
1058
1059
  process.exitCode = 1; return
1059
1060
  }
1061
+ let oldKek
1062
+ try { oldKek = Buffer.from(kekFor(dir)) } catch (e) {
1063
+ console.error('NO se cambió nada (' + (e.code || 'error') + '): ' + e.message)
1064
+ process.exitCode = 1; return
1065
+ }
1060
1066
  try {
1061
1067
  const r = rekeyDir(dir, cfg)
1062
1068
  console.log('Listo: ' + r.from + ' → ' + r.to + '. Recifrados ' + r.files.length + ' archivos.')
1069
+ // La contraseña del perfil lleva por fuera la llave de la máquina: con la llave nueva,
1070
+ // esa capa también. Si esto falla, el perfil no abre hasta restaurar las copias.
1071
+ try {
1072
+ const n = rewrapMachineLayer(vaultRoot, path.basename(dir), oldKek, Buffer.from(kekFor(dir)))
1073
+ if (n) console.log('La contraseña del perfil quedó cerrada con la clave nueva (' + n + ' puerta' + (n === 1 ? '' : 's') + ').')
1074
+ } catch (e) {
1075
+ console.error('OJO: los datos ya están con la clave nueva, pero la contraseña del perfil no (' + e.message + ').')
1076
+ console.error('Restaura las copias .bak-rekey (también ' + path.join(vaultRoot, 'profiles.json.bak-rekey') + ' si existe) antes de reiniciar.')
1077
+ process.exitCode = 1
1078
+ }
1063
1079
  if (r.backups.length) {
1064
1080
  console.log('Copias de seguridad (bórralas cuando compruebes que todo abre):')
1065
1081
  for (const b of r.backups) console.log(' ' + b)
@@ -2219,7 +2235,7 @@ async function cmdProfileKey (args) {
2219
2235
  const p = await targetProfile()
2220
2236
  if (!p) { console.error('el perfil no existe: %s', PROFILE); process.exit(1) }
2221
2237
  if (action === 'ls') {
2222
- console.log('%s se abre con: %s', p.name || p.id, p.protected ? doorsSummary(p) : 'nada (sin candado)')
2238
+ console.log('%s se abre con: %s', p.name || p.id, p.protected ? doorsSummary(p) : 'nada (sin contraseña)')
2223
2239
  for (const d of hwDoors(p)) {
2224
2240
  console.log(' %s %s %s%s', d.id, doorName(d), d.label || '', d.createdAt ? ` (${new Date(d.createdAt).toISOString().slice(0, 10)})` : '')
2225
2241
  }
package/src/daemon.js CHANGED
@@ -576,7 +576,7 @@ export async function runDaemon () {
576
576
  await mgr.unlock(id, { password: req.password })
577
577
  }
578
578
  const r = await mgr.removeDoor(id, 'password')
579
- return { done: r.protected ? 'contraseña quitada · el perfil sigue cerrándose con su llave de seguridad' : 'contraseña quitada · el perfil ya no tiene candado: se abre con la llave de esta máquina' }
579
+ return { done: r.protected ? 'contraseña quitada · el perfil sigue cerrándose con su llave de seguridad' : 'contraseña quitada · el perfil queda sin contraseña: se abre con la llave de esta máquina' }
580
580
  }
581
581
  // LLAVES DE SEGURIDAD (YubiKey). Quien habla con la llave es la CLI; aquí llegan la
582
582
  // credencial o el reto, y los bytes que devolvió — nunca un secreto que la abra sin ella.
@@ -595,7 +595,7 @@ export async function runDaemon () {
595
595
  const id = ref()
596
596
  if (!req.door) throw Object.assign(new Error('which door? (dotrino-vault profile key ls)'), { code: 'NO_SUCH_DOOR' })
597
597
  const r = await mgr.removeDoor(id, req.door)
598
- return { done: r.protected ? 'llave de seguridad quitada' : 'llave de seguridad quitada · el perfil ya no tiene candado: se abre con la llave de esta máquina' }
598
+ return { done: r.protected ? 'llave de seguridad quitada' : 'llave de seguridad quitada · el perfil queda sin contraseña: se abre con la llave de esta máquina' }
599
599
  }
600
600
  // ----- LA CONTRASEÑA DEL ADMIN (`docs/abrir-a-distancia.md`) -----
601
601
  //
package/src/manager.js CHANGED
@@ -137,7 +137,8 @@ export async function startVaultManager ({ root = dataDir(), proxyUrl, log = con
137
137
  id = await profiles.ensureNamedByKey(p.id, mintKey)
138
138
  if (id !== p.id) log('[vault] profile %s renamed to %s (the folder is named after its key)', p.id, id)
139
139
  } catch (e) { log('[vault] could not name the folder of %s after its key: %s', p.id, e.message) }
140
- try { await open(id) } catch (e) { log('[vault] could not open profile %s: %s', id, e.message) }
140
+ try { await open(id) } catch (e) { log('[vault] could not open profile %s: %s', id, e.message); continue }
141
+ await ensureProfileKey(id)
141
142
  }
142
143
 
143
144
  const get = (id) => {
@@ -227,6 +228,28 @@ export async function startVaultManager ({ root = dataDir(), proxyUrl, log = con
227
228
  return door
228
229
  }
229
230
 
231
+ /**
232
+ * TODO PERFIL TIENE LLAVE (dueño, 2026-10-25: «la contraseña puede ser vacía para no estar
233
+ * peleando con el código»). Uno que nació sin ella —todos los anteriores a 0.178 que nunca
234
+ * tuvieron contraseña— lleva la maestra bajo la llave de la máquina; aquí recibe la contraseña
235
+ * VACÍA por el mismo camino que poner cualquier contraseña, que ya sella la maestra y la copia
236
+ * de recuperación con la llave nueva. A partir de ahí hay un solo caso: la maestra va sellada
237
+ * con `K`, y «sin contraseña» es una contraseña más.
238
+ *
239
+ * Si falla no se arrastra: el perfil sigue sirviendo como hasta ahora, y se dice.
240
+ */
241
+ async function ensureProfileKey (id) {
242
+ if (profiles.hasKey(id)) return false
243
+ try {
244
+ await addDoor(id, { kind: 'password', password: '' })
245
+ log('[vault] profile %s now has its own key (empty password): the master key is sealed with it', id)
246
+ return true
247
+ } catch (e) {
248
+ log('[vault] could not give profile %s its own key: %s', id, e.message)
249
+ return false
250
+ }
251
+ }
252
+
230
253
  /** Quitar una puerta (por id, o `'password'`). Sin la última, el perfil queda sin candado. */
231
254
  async function removeDoor (id, which) {
232
255
  return profiles.removeDoor(id, which)
@@ -271,6 +294,7 @@ export async function startVaultManager ({ root = dataDir(), proxyUrl, log = con
271
294
  async add (name, { adopt = false, kek = null } = {}) {
272
295
  const p = await profiles.add(name, { adopt, kek, mintKey })
273
296
  await open(p.id)
297
+ await ensureProfileKey(p.id)
274
298
  log('[vault] profile created%s: %s (%s)', adopt ? ' (waiting to adopt an account)' : '', p.name || '(no name)', p.id)
275
299
  return profiles.get(p.id)
276
300
  },
package/src/profiles.js CHANGED
@@ -127,9 +127,25 @@ async function derivePwd (password, saltB64, iter) {
127
127
  * · `chalresp` HKDF(respuesta HMAC-SHA1 de la ranura 2), sin toque.
128
128
  * · las dos de hardware con `withPassword`: HKDF(scrypt(contraseña) ‖ secreto de la llave).
129
129
  * Hacen falta las DOS cosas.
130
- * · `machine` la llave de esta máquina — la de un perfil sin candado.
130
+ * · `machine` la llave de esta máquina — la de un perfil sin candado. YA NO SE CREA: la
131
+ * sustituye la contraseña VACÍA (ver abajo) y se convierte al leerla.
131
132
  *
132
133
  * El `info` de HKDF lleva el tipo: los bytes de una llave no pueden abrir la puerta de otro tipo.
134
+ *
135
+ * LA CONTRASEÑA SIEMPRE LLEVA LA LLAVE DE LA MÁQUINA (dueño, 2026-10-25). Una puerta de
136
+ * contraseña nueva (`machine: true`) son dos capas: dentro, `K` cerrada con scrypt(contraseña);
137
+ * fuera, eso cerrado con la llave de la máquina del perfil (`kekFor`, que con KMS es la del KMS).
138
+ * Para abrirla hacen falta las dos cosas, así que una copia del disco sin la máquina no se
139
+ * ataca a fuerza de diccionario.
140
+ *
141
+ * Y LA CONTRASEÑA PUEDE SER VACÍA (`empty: true`): es el perfil «sin contraseña». Abre solo, como
142
+ * abría la puerta `machine`, y protege lo mismo que ella —la capa de la máquina—, pero es el
143
+ * mismo camino que cualquier otra contraseña: todo perfil tiene llave `K` y la maestra siempre va
144
+ * sellada con ella. Antes un perfil sin candado podía no tener `K` y llevar la maestra bajo la
145
+ * llave de la máquina, que era otro caso que cuidar en cada sitio.
146
+ *
147
+ * La capa de fuera se puede volver a cerrar SIN la contraseña: es lo que hace `atrest rekey`
148
+ * al cambiar la llave de la máquina (`rewrapMachineLayer`).
133
149
  */
134
150
  const HW_INFO = { fido2: 'dotrino-vault/door/fido2/v1', chalresp: 'dotrino-vault/door/chalresp/v1' }
135
151
  const HW_KINDS = Object.keys(HW_INFO)
@@ -138,7 +154,7 @@ const scryptKey = (password, saltB64) => crypto2.scryptSync(String(password), Bu
138
154
 
139
155
  /** La llave de una puerta con lo que se trae, o `null` si falta algo para esa puerta. */
140
156
  function doorKey (door, { password = null, secret = null } = {}) {
141
- if (door.kind === 'password') return password ? scryptKey(password, door.salt) : null
157
+ if (door.kind === 'password') return password || (door.empty && password === '') ? scryptKey(password, door.salt) : null
142
158
  if (!HW_INFO[door.kind] || !secret?.length) return null
143
159
  if (door.withPassword && !password) return null
144
160
  const ikm = door.withPassword ? Buffer.concat([scryptKey(password, door.salt), Buffer.from(secret)]) : Buffer.from(secret)
@@ -147,14 +163,24 @@ function doorKey (door, { password = null, secret = null } = {}) {
147
163
  return k
148
164
  }
149
165
 
166
+ /** Saca `K` de una puerta con la llave de esa puerta; la capa de la máquina, si la lleva, con `kek`. */
167
+ function openDoor (door, k, kek) {
168
+ const inner = door.machine ? decryptText(door.wrapped, kek) : door.wrapped
169
+ return Buffer.from(decryptText(inner, k), 'base64')
170
+ }
171
+
150
172
  const newDoorId = () => crypto2.randomBytes(4).toString('hex')
151
- const realDoors = (p) => (p.doors || []).filter((d) => d.kind !== 'machine')
173
+ const isEmptyDoor = (d) => d.kind === 'password' && !!d.empty
174
+ /** Las puertas que CIERRAN: todas menos la de la máquina (heredada) y la contraseña vacía. */
175
+ const realDoors = (p) => (p.doors || []).filter((d) => d.kind !== 'machine' && !isEmptyDoor(d))
152
176
  /** Tiene candado: alguna puerta de verdad, o la contraseña de antes de las puertas. */
153
177
  const isProtected = (p) => !!p.pwd || realDoors(p).length > 0
154
178
  /** Ya tiene llave de perfil (con o sin candado). */
155
179
  const hasKey = (p) => !!p.pwd || (p.doors || []).length > 0
156
180
 
157
181
  function checkPassword (password) {
182
+ // Vacía vale: es «sin contraseña» (ver las puertas).
183
+ if (password === '') return
158
184
  if (!password || String(password).length < PWD_MIN) {
159
185
  throw Object.assign(new Error(`password must be at least ${PWD_MIN} characters: use several random words`),
160
186
  { code: 'PASSWORD_TOO_SHORT', min: PWD_MIN })
@@ -162,14 +188,17 @@ function checkPassword (password) {
162
188
  }
163
189
 
164
190
  /** Fabrica una puerta: el sobre de `K` y lo que hace falta para volver a pedírselo a la llave. */
165
- function makeDoor (K, spec = {}, { checkMin = true } = {}) {
191
+ function makeDoor (K, spec = {}, { checkMin = true, kek = null } = {}) {
166
192
  const kind = spec.kind
167
193
  if (kind !== 'password' && !HW_INFO[kind]) throw Object.assign(new Error('unknown door kind: ' + kind), { code: 'BAD_DOOR' })
168
194
  const withPassword = kind !== 'password' && !!spec.password
169
195
  if ((kind === 'password' || withPassword) && checkMin) checkPassword(spec.password)
170
- if ((kind === 'password' || withPassword) && !spec.password) throw Object.assign(new Error('a password is required'), { code: 'BAD_DOOR' })
196
+ if (kind === 'password' && typeof spec.password !== 'string') throw Object.assign(new Error('a password is required'), { code: 'BAD_DOOR' })
197
+ // Sin la llave de la máquina no se fabrica una contraseña: saldría sin su capa de fuera.
198
+ if (kind === 'password' && !kek) throw Object.assign(new Error('a password door needs the machine key'), { code: 'BAD_DOOR' })
171
199
  const door = { id: newDoorId(), kind, createdAt: Date.now(), ...(spec.label ? { label: String(spec.label).slice(0, MAX_NAME) } : {}) }
172
200
  if (kind === 'password' || withPassword) door.salt = b64(crypto2.randomBytes(32))
201
+ if (kind === 'password') { door.machine = true; if (spec.password === '') door.empty = true }
173
202
  if (withPassword) door.withPassword = true
174
203
  if (kind === 'fido2') {
175
204
  if (!spec.credId || !spec.hsalt) throw Object.assign(new Error('a fido2 door needs credId and hsalt'), { code: 'BAD_DOOR' })
@@ -182,9 +211,10 @@ function makeDoor (K, spec = {}, { checkMin = true } = {}) {
182
211
  const secret = spec.secret ? Buffer.from(spec.secret) : null
183
212
  if (HW_INFO[kind] && !secret?.length) throw Object.assign(new Error('the key gave nothing to seal the door with'), { code: 'BAD_DOOR' })
184
213
  const k = doorKey(door, { password: spec.password, secret })
185
- door.wrapped = encryptText(b64(K), k)
214
+ const inner = encryptText(b64(K), k)
215
+ door.wrapped = door.machine ? encryptText(inner, kek) : inner
186
216
  // Se comprueba ANTES de guardar: una puerta que no abre es peor que no tenerla.
187
- const back = Buffer.from(decryptText(door.wrapped, k), 'base64')
217
+ const back = openDoor(door, k, kek)
188
218
  k.fill(0)
189
219
  if (!back.equals(Buffer.from(K))) throw Object.assign(new Error('the new door does not open: not saved'), { code: 'BAD_DOOR' })
190
220
  return door
@@ -224,6 +254,33 @@ function normCreds (c) {
224
254
  const stagingName = () => '.new-' + crypto.randomUUID().slice(0, 8)
225
255
  const cleanName = (name) => String(name || '').slice(0, MAX_NAME)
226
256
 
257
+ /**
258
+ * LA CAPA DE LA MÁQUINA, CUANDO CAMBIA LA LLAVE DE LA MÁQUINA (`atrest rekey`).
259
+ *
260
+ * La contraseña de un perfil va cerrada por fuera con la llave de la máquina de ESE perfil. Si
261
+ * `atrest rekey` cambia esa llave y no esto, el perfil no vuelve a abrir. No hace falta la
262
+ * contraseña: solo se quita la capa de fuera con la llave vieja y se pone con la nueva.
263
+ * Devuelve cuántas puertas tocó; deja `profiles.json.bak-rekey` si tocó alguna.
264
+ */
265
+ export function rewrapMachineLayer (root, id, oldKek, newKek) {
266
+ const file = path.join(root, REGISTRY)
267
+ const atRest = atRestFor(root)
268
+ const data = readJson(file, null, atRest)
269
+ const p = data?.profiles?.find((x) => x.id === id)
270
+ if (!p) return 0
271
+ let n = 0
272
+ p.doors = (p.doors || []).map((d) => {
273
+ if (!d.machine && d.kind !== 'machine') return d
274
+ n++
275
+ return { ...d, wrapped: encryptText(decryptText(d.wrapped, oldKek), newKek) }
276
+ })
277
+ if (n) {
278
+ fs.copyFileSync(file, file + '.bak-rekey')
279
+ writeJson(file, data, atRest)
280
+ }
281
+ return n
282
+ }
283
+
227
284
  /**
228
285
  * @param {string} root dir de datos
229
286
  * @param {{ autoLockMs?: number, onAutoLock?: (id: string) => void }} [opts]
@@ -315,6 +372,8 @@ export function openProfiles (root = dataDir(), { autoLockMs = AUTO_LOCK_MS, onA
315
372
 
316
373
  const find = (id) => data.profiles.find((p) => p.id === id) || null
317
374
  const dirOf = (id) => path.join(root, 'p', id)
375
+ /** La llave de la máquina de ESE perfil (con KMS, la del KMS): la capa de fuera de su contraseña. */
376
+ const machineKek = (id) => Buffer.from(kekFor(dirOf(id)))
318
377
 
319
378
  const entry = (p) => ({
320
379
  id: p.id,
@@ -383,13 +442,15 @@ export function openProfiles (root = dataDir(), { autoLockMs = AUTO_LOCK_MS, onA
383
442
  throw Object.assign(new Error('nothing to open the profile with'), { code: 'NO_CREDENTIALS' })
384
443
  }
385
444
  const tries = throttle(p)
445
+ const kek = machineKek(p.id)
386
446
  let K = null
447
+ let opened = null
387
448
  for (const d of cands) {
388
449
  const k = doorKey(d, { password, secret })
389
450
  if (!k) continue
390
- try { K = Buffer.from(decryptText(d.wrapped, k), 'base64') } catch (_) { K = null }
451
+ try { K = openDoor(d, k, kek) } catch (_) { K = null }
391
452
  k.fill(0)
392
- if (K?.length === 32) break
453
+ if (K?.length === 32) { opened = d; break }
393
454
  K = null
394
455
  }
395
456
  let legacy = false
@@ -402,6 +463,7 @@ export function openProfiles (root = dataDir(), { autoLockMs = AUTO_LOCK_MS, onA
402
463
  }
403
464
  }
404
465
  if (!K) {
466
+ kek.fill(0)
405
467
  p.tries = { n: tries.n + 1, at: Date.now() }
406
468
  save()
407
469
  throw Object.assign(new Error(door ? 'the key did not open this profile' : 'wrong password'), { code: 'WRONG_PASSWORD', tries: p.tries.n })
@@ -410,9 +472,14 @@ export function openProfiles (root = dataDir(), { autoLockMs = AUTO_LOCK_MS, onA
410
472
  if (legacy) {
411
473
  // A PUERTA: la misma `K`, ahora en un sobre de la contraseña. El verificador y el salt de
412
474
  // derivación directa se van — de aquí en adelante la contraseña es una puerta más.
413
- p.doors = [...real, makeDoor(K, { kind: 'password', password }, { checkMin: false })]
475
+ p.doors = [...real, makeDoor(K, { kind: 'password', password }, { checkMin: false, kek })]
414
476
  delete p.pwd; delete p.kdf
477
+ } else if (opened?.kind === 'password' && !opened.machine) {
478
+ // UNA CONTRASEÑA DE ANTES DE LA CAPA DE LA MÁQUINA: se vuelve a cerrar con ella. Es el único
479
+ // momento en que se tiene la contraseña en la mano. Misma `K`, nada más que sellar.
480
+ p.doors = p.doors.map((d) => (d === opened ? makeDoor(K, { kind: 'password', password }, { checkMin: false, kek }) : d))
415
481
  }
482
+ kek.fill(0)
416
483
  save()
417
484
  return K
418
485
  }
@@ -651,6 +718,8 @@ export function openProfiles (root = dataDir(), { autoLockMs = AUTO_LOCK_MS, onA
651
718
  // ----- candado -----
652
719
 
653
720
  isProtected: (id) => { const p = find(id); return !!p && isProtected(p) },
721
+ /** Tiene llave de perfil `K`. Uno sin ella lleva la maestra bajo la llave de la máquina (de antes de 0.178). */
722
+ hasKey: (id) => { const p = find(id); return !!p && hasKey(p) },
654
723
  isLocked: (id) => { const p = find(id); return !!p && isProtected(p) && !isOpen(id) },
655
724
  /** Cuánto dura abierto el candado sin usarse (ms). 0 = no se cierra solo. */
656
725
  get autoLockMs () { return autoLockMs },
@@ -758,21 +827,24 @@ export function openProfiles (root = dataDir(), { autoLockMs = AUTO_LOCK_MS, onA
758
827
  assertExists(id)
759
828
  const K = api.openKey(id)
760
829
  if (!K) throw Object.assign(new Error('unlock the profile first'), { code: 'PROFILE_LOCKED' })
761
- return makeDoor(K, spec)
830
+ return makeDoor(K, spec, { kek: machineKek(id) })
762
831
  },
763
832
 
764
833
  addDoor (id, spec) {
765
834
  const p = assertExists(id)
766
835
  const K = api.openKey(id)
767
836
  if (!K) throw Object.assign(new Error('unlock the profile first'), { code: 'PROFILE_LOCKED' })
768
- const door = spec?.prepared || makeDoor(K, spec)
769
- let doors = (p.doors || []).filter((d) => d.kind !== 'machine')
837
+ const door = spec?.prepared || makeDoor(K, spec, { kek: machineKek(id) })
838
+ let doors = (p.doors || []).filter((d) => d.kind !== 'machine' && !isEmptyDoor(d))
770
839
  // UNA contraseña por perfil: poner otra la sustituye, también a la de antes de las puertas.
771
840
  if (door.kind === 'password') { doors = doors.filter((d) => d.kind !== 'password'); delete p.pwd }
772
841
  // El salt de derivación directa solo sirve para recuperar (ver `ensureKey`); con la llave
773
842
  // ya en una puerta, sobra.
774
843
  delete p.kdf
775
- p.doors = [...doors, door]
844
+ // LA VACÍA solo queda si no hay otra puerta: junto a una llave de seguridad la dejaría
845
+ // abierta para cualquiera, así que ahí poner la vacía es quitar la contraseña.
846
+ p.doors = door.empty ? (doors.length ? doors : [door]) : [...doors, door]
847
+ if (!realDoors(p).length) delete p.kdf2
776
848
  delete p.tries
777
849
  save()
778
850
  // Si la llave venía de la de la máquina (perfil sin candado), ahora es la del perfil
@@ -797,14 +869,15 @@ export function openProfiles (root = dataDir(), { autoLockMs = AUTO_LOCK_MS, onA
797
869
  p.doors = (p.doors || []).filter((d) => d.kind !== 'password')
798
870
  delete p.pwd; delete p.kdf
799
871
  } else {
800
- if (!(p.doors || []).some((d) => d.id === which && d.kind !== 'machine')) {
872
+ if (!realDoors(p).some((d) => d.id === which)) {
801
873
  throw Object.assign(new Error('that door does not exist: ' + which), { code: 'NO_SUCH_DOOR' })
802
874
  }
803
875
  p.doors = p.doors.filter((d) => d.id !== which)
804
876
  }
805
877
  const removed = before - realDoors(p).length
806
878
  if (!realDoors(p).length) {
807
- p.doors = [{ id: newDoorId(), kind: 'machine', createdAt: Date.now(), wrapped: encryptText(b64(K), Buffer.from(kekFor(dirOf(id)))) }]
879
+ // SIN PUERTA QUE CIERRE queda la contraseña vacía: la misma `K`, bajo la llave de la máquina.
880
+ p.doors = [makeDoor(K, { kind: 'password', password: '' }, { kek: machineKek(id) })]
808
881
  // Sin candado no hay nada que abrir a distancia.
809
882
  delete p.kdf2
810
883
  }
@@ -914,16 +987,27 @@ export function openProfiles (root = dataDir(), { autoLockMs = AUTO_LOCK_MS, onA
914
987
  * tendrá que pedirla, que es exactamente el comportamiento de antes.
915
988
  */
916
989
  openKey (id) {
917
- if (isOpen(id)) return keys.get(id) || null
918
- // SIN CANDADO PERO CON LLAVE: un perfil al que se le quitó la última puerta. Su `K` vive
919
- // bajo la llave de la máquina y se abre sola, como el resto del disco.
990
+ if (isOpen(id) && keys.get(id)) return keys.get(id)
991
+ // SIN CONTRASEÑA: la puerta vacía abre sola, con la llave de la máquina, como el resto del disco.
920
992
  const p = find(id)
921
- const m = p && !isProtected(p) ? (p.doors || []).find((d) => d.kind === 'machine') : null
922
- if (!m) return null
993
+ if (!p || isProtected(p)) return null
923
994
  if (!byMachine.has(id)) {
924
- const K = Buffer.from(decryptText(m.wrapped, Buffer.from(kekFor(dirOf(id)))), 'base64')
995
+ const empty = (p.doors || []).find(isEmptyDoor)
996
+ const m = (p.doors || []).find((d) => d.kind === 'machine')
997
+ if (!empty && !m) return null
998
+ const kek = machineKek(id)
999
+ let K
1000
+ try {
1001
+ K = empty ? openDoor(empty, scryptKey('', empty.salt), kek) : Buffer.from(decryptText(m.wrapped, kek), 'base64')
1002
+ } finally { kek.fill(0) }
925
1003
  if (K.length !== 32) throw Object.assign(new Error('the profile key under this machine key is malformed'), { code: 'BAD_PROFILE_KEY' })
926
1004
  byMachine.set(id, new Uint8Array(K))
1005
+ // MIGRACIÓN (hasta 2027-04-01, cuando no queden bóvedas anteriores a 0.178): la puerta
1006
+ // `machine` pasa a contraseña vacía. Misma `K`, así que no hay nada más que sellar.
1007
+ if (!empty) {
1008
+ p.doors = [makeDoor(K, { kind: 'password', password: '' }, { kek: machineKek(id) })]
1009
+ save()
1010
+ }
927
1011
  }
928
1012
  return byMachine.get(id)
929
1013
  },
package/src/replica.js CHANGED
@@ -198,9 +198,12 @@ export async function runReplica ({ dir = replicaDir(), proxyUrl, wakeUrl = null
198
198
  if (!body || body.op !== 'replica.push') return
199
199
  const acta = body.acta || store.acta
200
200
  if (!acta) return log('[replica] a push arrived with no record and none is stored: ignored')
201
- if (acta.sealedBy !== link.iss) return log('[replica] the pushed record was sealed by another master: ignored')
201
+ // LAS DOS SON MAESTRA (`docs/replicas.md` §11.5): vale la que enroló a este replicador o una
202
+ // bóveda a la que el acta que ya guarda le dejaba sellar.
203
+ const known = acta.sealedBy === link.iss || (store.acta && sealersOf(store.acta).includes(acta.sealedBy))
204
+ if (!known) return log('[replica] the pushed record was sealed by a vault this replica does not know: ignored')
202
205
  if (!(await verifyActa({ acta })).ok) return log('[replica] the pushed record does not verify: ignored')
203
- const pub = sealKeyAt(acta, p.seal?.seq)
206
+ const pub = sealKeyAt(acta, p.seal?.seq, p.seal?.vault ?? null)
204
207
  if (!pub || !(await verifyDeviceSig({ publickey: pub, data: body, signature: p.seal?.sig }))) {
205
208
  return log('[replica] the push is not signed by the key the record names: ignored')
206
209
  }
package/src/tui/i18n.js CHANGED
@@ -222,13 +222,13 @@ const es = {
222
222
  doorAdded: 'Llave añadida. Deja otra forma de abrir de repuesto: perder la única es perder la bóveda.',
223
223
  doorAddedNoTouch: 'Llave sin toque añadida. Desenchúfala cuando no la uses. Deja otra forma de abrir de repuesto.',
224
224
  removeDoorConfirm: (what) => `¿Quitar «${what}» como forma de abrir?`,
225
- removeLastDoorConfirm: (what) => `¿Quitar «${what}»? Es la última: la bóveda quedará sin candado.`,
225
+ removeLastDoorConfirm: (what) => `¿Quitar «${what}»? Es la última: la bóveda quedará sin contraseña.`,
226
226
  removingDoor: 'Quitando…',
227
227
  doorRemoved: 'Quitada',
228
228
  titleJoin: 'Entrar en la cuenta de otra bóveda',
229
229
 
230
230
  // bóvedas (perfiles)
231
- noPassword: 'sin candado',
231
+ noPassword: 'sin contraseña',
232
232
  noPasswordWarn: 'Este perfil no tiene contraseña: una copia de este disco abre las variables privadas.',
233
233
  pendingSeal: (owner, kind, who) => kind === 'rotate' ? `${owner}: sin rotar (salió un aparato). Guarda una variable con la contraseña.` : `${owner}: sin llave todavía en ${who}. Se reparte sola con otro aparato del grupo encendido, o al abrir la bóveda.`,
234
234
  locked: '🔒 bloqueada',
@@ -761,12 +761,12 @@ const en = {
761
761
  doorAdded: 'Key added. Keep a spare way in: losing the only one means losing the vault.',
762
762
  doorAddedNoTouch: 'No-touch key added. Unplug it when not in use. Keep a spare way in.',
763
763
  removeDoorConfirm: (what) => `Remove “${what}” as a way in?`,
764
- removeLastDoorConfirm: (what) => `Remove “${what}”? It is the last one: the vault will be left without a lock.`,
764
+ removeLastDoorConfirm: (what) => `Remove “${what}”? It is the last one: the vault will be left without a password.`,
765
765
  removingDoor: 'Removing…',
766
766
  doorRemoved: 'Removed',
767
767
  titleJoin: 'Join the account of another vault',
768
768
 
769
- noPassword: 'no lock',
769
+ noPassword: 'no password',
770
770
  noPasswordWarn: 'This profile has no password: a copy of this disk opens the private variables.',
771
771
  pendingSeal: (owner, kind, who) => kind === 'rotate' ? `${owner}: not rotated (a device left). Save a variable with the password.` : `${owner}: no key yet on ${who}. It is handed out by another device of the group that is on, or when the vault is opened.`,
772
772
  locked: '🔒 locked',