@dotrino/vaultd 0.191.0 → 0.192.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.
package/lib/src/admin.js CHANGED
@@ -241,7 +241,10 @@ export function createAdminDesk ({
241
241
  // VER UNA PRIVADA (`varsDesk.reveal`). Antes que las demás de variables porque aquí no
242
242
  // viaja ningún destino en claro: va dentro del sobre, y la política es de la bóveda.
243
243
  if (data.op === 'var.reveal.begin' || data.op === 'var.reveal') {
244
- if (!vars || typeof vars.reveal !== 'function') return { ok: false, error: 'admin: this vault cannot show a private variable (update it)' }
244
+ // Se comprueba el método que se va a llamar. Antes se miraba siempre `reveal`, y una
245
+ // bóveda sin `revealBegin` reventaba con un TypeError en vez de decirlo.
246
+ const method = data.op === 'var.reveal.begin' ? 'revealBegin' : 'reveal'
247
+ if (!vars || typeof vars[method] !== 'function') return { ok: false, error: 'admin: this vault cannot show a private variable (update it)' }
245
248
  try {
246
249
  const result = data.op === 'var.reveal.begin'
247
250
  ? await vars.revealBegin({ caller: chk.device, by })
@@ -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.119.0'
8
+ export const LIB_VERSION = '0.120.1'
@@ -1448,7 +1448,10 @@ export function openSecretsStore (disk, { sealer = null, recipients = null, sign
1448
1448
  dev: {},
1449
1449
  recovery: { pub: pair.pub, priv: await sealer.sealMaster(pair.priv, keyOr(adminKey)) },
1450
1450
  // El histórico empieza aquí: de lo de antes no se guardó ninguna versión previa.
1451
- history: []
1451
+ history: [],
1452
+ // Las lápidas se conservan. Faltaba el campo, y el primer `delete` tras convertir
1453
+ // reventaba en `_drop` (`data.deleted[owner]` sobre `undefined`) hasta reiniciar.
1454
+ deleted: data.deleted
1452
1455
  }
1453
1456
  const antes = {}
1454
1457
  const noKey = {}
@@ -81,12 +81,16 @@ export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey
81
81
  // CON QUÉ SE ABRE LO QUE NOS SELLAN (`commKey.encKeypair`): sin esto la bóveda no podía
82
82
  // recibir nada sellado, y una hermana cerrada no habría podido abrir los cajones que le
83
83
  // manda la otra. El pilar anuncia la pública al identificarse con la llave de comunicación.
84
- const enc = commKey?.pub?.() && typeof commKey.encKeypair === 'function'
84
+ let enc = commKey?.pub?.() && typeof commKey.encKeypair === 'function'
85
85
  ? await commKey.encKeypair().catch((e) => { log('[vault] no transport encryption key: ' + e.message); return null })
86
86
  : null
87
- const client = makeClient ? makeClient({ url, acceptDirectFrom: inActa }) : new WebSocketProxyClient({
87
+ // Y A QUIEN CREA EL CLIENTE TAMBIÉN se le pasa (la extensión, la pestaña): sin esto una bóveda
88
+ // de navegador no anunciaba llave de cifrado, y lo que sus aparatos le sellan
89
+ // (`docs/sealed-requests.md`) no tenía con qué abrirse.
90
+ const encOpts = enc ? { myEncPub: enc.encPub, myEncPrivateKey: enc.privateKey } : {}
91
+ const client = makeClient ? makeClient({ url, acceptDirectFrom: inActa, ...encOpts }) : new WebSocketProxyClient({
88
92
  url, enableWebRTC: true, acceptDirectFrom: inActa, autoReconnect: true,
89
- ...(enc ? { myEncPub: enc.encPub, myEncPrivateKey: enc.privateKey } : {}),
93
+ ...encOpts,
90
94
  maxReconnectAttempts: 100000, reconnectDelay: 4000,
91
95
  // EL BLUETOOTH (proxy-client docs/bluetooth.md) lo decide la plataforma: el binario en
92
96
  // Linux sí; la pestaña y la extensión no pueden. Misma puerta que WebRTC (`inActa`).
@@ -118,6 +122,14 @@ export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey
118
122
  const record = (await identity.profileActa?.().catch(() => null))?.acta || null
119
123
  seenActa = record // la copia que mira la puerta del canal directo
120
124
  const comm = commKey?.pub?.() || null
125
+ // LA LLAVE DE CIFRADO TAMBIÉN SI LA DE COMUNICACIÓN SE ESTRENÓ DESPUÉS de crear el cliente
126
+ // (un perfil con contraseña la estrena al abrirse). Sin esto la bóveda volvía a la red con
127
+ // su llave nueva pero sin anunciar con qué se le sella, y lo que sus aparatos le mandan
128
+ // sellado (`docs/sealed-requests.md`) no tenía con qué abrirse.
129
+ if (comm && !enc && typeof commKey.encKeypair === 'function') {
130
+ enc = await commKey.encKeypair().catch((e) => { log('[vault] no transport encryption key: ' + e.message); return null })
131
+ if (enc) client.updateConfig?.({ myEncPub: enc.encPub, myEncPrivateKey: enc.privateKey })
132
+ }
121
133
  // ¿Nos nombra el acta? Con `cn` o sin él, lo que el proxio mira es la pertenencia.
122
134
  const isMember = comm && (record?.members || []).some((m) => m?.pub === comm)
123
135
 
@@ -46,7 +46,7 @@ import { BACKUP_VERSION, PASSWORDS_DRAWER, wants, assertSelected, planImport, re
46
46
  import { openSealKeys } from './sealKey.js'
47
47
  import { openCommKey, COMM_CN, COMM_CAPS } from './commKey.js'
48
48
  import { seal } from '../sealed.js'
49
- import { MSG, SCOPE, secretsScope, isValidSecretsNs, VAULT_PROTOCOL, VAULT_SPEAKS } from '../protocol.js'
49
+ import { MSG, SCOPE, secretsScope, isValidSecretsNs, VAULT_PROTOCOL, VAULT_SPEAKS, SEALED_REQUEST_TYPES, unsealedRequestsAllowed, UNSEALED_REQUESTS_UNTIL_TEXT } from '../protocol.js'
50
50
  import { sha256Hex } from './sha256.js'
51
51
  import { sealHead, ANCHOR_EVERY_MS, ANCHOR_FIRST_MS } from './logAnchor.js'
52
52
  import { createGate } from './gate.js'
@@ -656,6 +656,63 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
656
656
  */
657
657
  const channels = new Map()
658
658
 
659
+ /**
660
+ * LA RESPUESTA A UNA PETICIÓN SELLADA VUELVE SELLADA (`docs/sealed-requests.md`).
661
+ *
662
+ * El aparato mete en lo firmado una llave de un solo uso (`data.rek`), y a esa llave se le
663
+ * sella todo lo que se le conteste a ESA petición. Se hace con un canal más de `channels`
664
+ * —como el socket local—, así que ningún mostrador tiene que saber nada: contesta a `from`
665
+ * como siempre y el canal sella. El canal es por conexión Y llave: dos peticiones por la
666
+ * misma conexión con llaves distintas no se pisan, y un tercero que escriba «desde» ese
667
+ * token con otra llave se lleva su propio canal, no el del aparato.
668
+ *
669
+ * Viven lo que puede tardar la respuesta más lenta (un pedido que espera al teléfono) y se
670
+ * podan por antigüedad; si ya no está, la respuesta a un pedido aprobado sale por la cola
671
+ * del aparato, como antes.
672
+ */
673
+ const SEALED_CHANNEL_TTL_MS = 24 * 60 * 60 * 1000
674
+ const SEALED_CHANNELS_MAX = 5000
675
+ const sealedChannelAt = new Map()
676
+ function sealedChannel (token, rek) {
677
+ const id = `sealed:${token}:${sha256Hex(rek).slice(0, 16)}`
678
+ const now = Date.now()
679
+ if (!channels.has(id)) {
680
+ for (const [k, t] of sealedChannelAt) {
681
+ if (now - t < SEALED_CHANNEL_TTL_MS && sealedChannelAt.size < SEALED_CHANNELS_MAX) break
682
+ sealedChannelAt.delete(k); channels.delete(k)
683
+ }
684
+ // EN ORDEN: sellar es asíncrono, y dos respuestas seguidas podían adelantarse una a la
685
+ // otra. El orden importa (el aviso firmado de expulsión va ANTES del «no», porque el
686
+ // aparato deja de escuchar al recibir el «no»), así que salen en fila.
687
+ let tail = Promise.resolve()
688
+ channels.set(id, (obj) => {
689
+ tail = tail.then(() => client.sendSealedTo(token, obj, { peerEncPub: rek, pilar: true }))
690
+ .catch((e) => log(`[vault] could not send a sealed reply (${e.code || 'error'}): ${e.message}`))
691
+ })
692
+ }
693
+ sealedChannelAt.delete(id)
694
+ sealedChannelAt.set(id, now)
695
+ return id
696
+ }
697
+ const unsealedTold = new Map()
698
+ /** MIGRACIÓN (caduca 2026-12-15): una petición en claro de un cliente viejo. */
699
+ function unsealedRequest (from, payload) {
700
+ const type = String(payload.type)
701
+ if (!unsealedRequestsAllowed()) {
702
+ audit('rejected', { what: type, reason: 'unsealed' })
703
+ reply(from, { type: MSG.ERROR, error: `${type}: requests must be sealed to this vault — update the client`, code: 'request-unsealed' })
704
+ return false
705
+ }
706
+ const t = Date.now()
707
+ if (t - (unsealedTold.get(type) || 0) > 60 * 60 * 1000) {
708
+ unsealedTold.set(type, t)
709
+ log(`[vault] ${type} arrived UNSEALED from an old client: served until ${UNSEALED_REQUESTS_UNTIL_TEXT} (migration), then refused — update it`)
710
+ }
711
+ return true
712
+ }
713
+ const SEALED_TYPES = new Set(SEALED_REQUEST_TYPES)
714
+
715
+
659
716
  /**
660
717
  * QUÉ SOMOS, Y QUÉ CORRE CADA APARATO (CONVENCIONES §14, `@dotrino/compat`).
661
718
  *
@@ -2575,6 +2632,19 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2575
2632
  if (pass.throttled) reply(from, { type: MSG.ERROR, error: 'too many tries: wait before trying again', code: 'too-many-tries', waitMs: pass.waitMs })
2576
2633
  return
2577
2634
  }
2635
+ // ¿SELLADA? Por el socket local (`channels`) no hace falta: no toca la red. Por el proxio,
2636
+ // lo que pide un aparato tiene que venir sellado, y su respuesta vuelve sellada a `rek`.
2637
+ if (SEALED_TYPES.has(payload.type) && !channels.has(from)) {
2638
+ if (meta?.sealed) {
2639
+ const rek = payload?.data?.rek
2640
+ if (!ActaPilar.isEncPub(rek)) {
2641
+ // Sellada pero sin a dónde sellar la respuesta: contestar en claro sería deshacer el
2642
+ // sobre de la petición. Se dice, en claro y sin nada del aparato dentro.
2643
+ return reply(from, { type: MSG.ERROR, error: `${payload.type}: a sealed request needs data.rek to seal the reply to`, code: 'no-reply-key' })
2644
+ }
2645
+ from = sealedChannel(from, rek)
2646
+ } else if (!unsealedRequest(from, payload)) return
2647
+ }
2578
2648
  try {
2579
2649
  if (payload.type === MSG.HELLO) return desk.handleHello(from, payload)
2580
2650
  if (payload.type === MSG.ENROLL) return await desk.handleEnroll(from, payload)
@@ -2873,6 +2943,16 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2873
2943
  })
2874
2944
  }
2875
2945
  function scheduleDeviceNotice (pub) { schedule('dev:' + pub, () => notifyDeviceChange(pub)) }
2946
+ /**
2947
+ * El aviso del cajón que se tocó: el de un namespace o el de un aparato. `varsDesk` escribe en
2948
+ * los dos, y avisaba siempre al namespace —con `ns` null cuando el cajón era de un aparato—,
2949
+ * así que el aparato no se enteraba de que su configuración había cambiado.
2950
+ */
2951
+ function noticeFor (ns, pub) {
2952
+ if (ns) return scheduleNotice(ns)
2953
+ if (!pub) throw new Error('vars: a drawer needs its ns or its device pub')
2954
+ scheduleDeviceNotice(pub)
2955
+ }
2876
2956
 
2877
2957
  function schedule (key, fn) {
2878
2958
  clearTimeout(pendingNotices.get(key))
@@ -3380,7 +3460,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
3380
3460
  await checkAuthor(owner, key, sealed, caller, { allowOverwrite: ask })
3381
3461
  await checkRecipients(owner, sealed.wraps, !!isPublic)
3382
3462
  await secrets.putSealed(owner, key, sealed, { by: who, public: isPublic })
3383
- audit('secret.set', { ns: ns || null, key, sealed: true }); scheduleNotice(ns)
3463
+ audit('secret.set', { ns: ns || null, key, sealed: true }); noticeFor(ns, pub)
3384
3464
  await settleDebts(owner)
3385
3465
  }
3386
3466
  // Comprobado ANTES de dejarlo en espera: un sobre malo falla al guardarlo, no cinco
@@ -3452,7 +3532,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
3452
3532
  await secrets.putSealed(owner, it.key, it.sealed, { by: who, public: !!it.public })
3453
3533
  keys.push(it.key)
3454
3534
  }
3455
- audit('secret.setMany', { ns: ns || null, keys }); scheduleNotice(ns)
3535
+ audit('secret.setMany', { ns: ns || null, keys }); noticeFor(ns, pub)
3456
3536
  await settleDebts(owner)
3457
3537
  }
3458
3538
  const pending = await holdWrite({ caller, ns, pub, keys: items.map((it) => it.key), apply, ask })
@@ -5058,7 +5138,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
5058
5138
  // La bóveda de contraseñas (`passwords.js`). Aquí SÍ se lista: es donde está la
5059
5139
  // llave. Lo que no puede es listarla un aparato.
5060
5140
  passwordDevices,
5061
- passwordsVault: () => passwords?.vault || null,
5141
+ // (Aquí estaba `passwordsVault`, que siempre daba null: el mostrador sellado ya no tiene
5142
+ // `vault` —no hay llave que guardar— y nadie lo llamaba. Quitado, no arreglado.)
5062
5143
  // La política de las contraseñas, para quien atiende su propio almacén (la extensión).
5063
5144
  passwordsNeedApproval,
5064
5145
  approvePasswordRequest,
@@ -66,3 +66,20 @@ export function formatDeviceInfo (info) {
66
66
  const w = Math.max(...rows.map(([k]) => k.length))
67
67
  return rows.map(([k, v]) => `${(k + ':').padEnd(w + 2)}${v}`).join('\n')
68
68
  }
69
+
70
+ /**
71
+ * Cómo se describe el papel (cert) de un servicio: por el ACTA a la que se ató, o, si es del
72
+ * modelo viejo, con la fecha en que vence — lo único que todavía caduca. Sin ninguna de las
73
+ * dos se dice `?`. Antes `dotrino-env enroll` hacía `new Date(undefined).toISOString()` en la
74
+ * rama vieja, que lanza RangeError justo al terminar de enrolar.
75
+ *
76
+ * @param {{ seq?: unknown, exp?: unknown } | null | undefined} cert
77
+ * @param {{ old?: string }} [words] cómo se llama el modelo viejo en la salida
78
+ * @returns {string}
79
+ */
80
+ export function describePaper (cert, { old = 'modelo viejo' } = {}) {
81
+ if (typeof cert?.seq === 'number') return `acta #${cert.seq}`
82
+ if (typeof cert?.exp === 'number' && Number.isFinite(cert.exp)) return `${old} · vence ${new Date(cert.exp).toISOString().slice(0, 10)}`
83
+ return '?'
84
+ }
85
+
package/lib/src/env.js CHANGED
@@ -114,11 +114,13 @@ export function resolveNs (ns) {
114
114
  return ns
115
115
  }
116
116
  const found = listEnrolled()
117
- if (found.length === 1) return found[0]
117
+ // `listEnrolled` da `{ vault, ns }`: lo que se devuelve es el ns. Devolvía el objeto entero,
118
+ // y `serviceDir` lo rechazaba como «invalid ns» justo en el caso «el único enrolado».
119
+ if (found.length === 1) return found[0].ns
118
120
  if (found.length === 0) {
119
121
  throw new Error('no service enrolled on this machine: run `npx dotrino-env enroll --ns <your-app>`')
120
122
  }
121
- throw new Error(`several services are enrolled (${found.join(', ')}): pick one with DOTRINO_NS=<ns> or loadEnv({ ns })`)
123
+ throw new Error(`several services are enrolled (${found.map((e) => e.vault ? `${e.vault}/${e.ns}` : e.ns).join(', ')}): pick one with DOTRINO_NS=<ns> or loadEnv({ ns })`)
122
124
  }
123
125
 
124
126
  /**
@@ -501,10 +501,12 @@ export function createLoginDesk ({ load, save, now = () => Date.now(), opaque =
501
501
  export async function createPasswordLogin ({ user, password, label, caps, begin, finish, opaque = opaqueClientePorDefecto } = {}) {
502
502
  if (!isValidUser(user)) throw Object.assign(new Error('invalid user name'), { code: 'bad-user' })
503
503
  if (typeof password !== 'string' || !password) throw Object.assign(new Error('a password is required'), { code: 'no-password' })
504
- const start = opaque.registrationStart({ password })
504
+ // `opaque` se inyecta, y el resto de este archivo ya lo espera con `await`: una
505
+ // implementación asíncrona devolvía aquí una promesa y `start.request` salía `undefined`.
506
+ const start = await opaque.registrationStart({ password })
505
507
  const begun = await begin({ user, request: start.request })
506
508
  // La bóveda contesta con su mitad; el registro se termina AQUÍ, con la contraseña.
507
- const fin = opaque.registrationFinish({ state: start.state, response: begun.response, password })
509
+ const fin = await opaque.registrationFinish({ state: start.state, response: begun.response, password })
508
510
  const device = await makeDeviceKey({ label })
509
511
  const enc = await makeDeviceEncKey()
510
512
  const blob = await sealDeviceKeys(fin.exportKey, { sign: device.privateJwk, enc: enc.encPrivateJwk })
@@ -168,3 +168,28 @@ export const VAULT_PROTOCOL = 1
168
168
 
169
169
  /** Los protocolos que esta build entiende. Al añadir el 2, aquí van `[1, 2]`. */
170
170
  export const VAULT_SPEAKS = [1]
171
+
172
+ /**
173
+ * LAS PETICIONES DE UN APARATO A SU BÓVEDA VAN SELLADAS (regla `encrypted`, dueño 2026-10-26:
174
+ * nada viaja en claro por la red). El aparato sella la petición ENTERA a la llave de cifrado
175
+ * del transporte de la bóveda (`sendSealed` del pilar, `@dotrino/identity/vault-seal`) y mete
176
+ * dentro de lo firmado la llave de un solo uso a la que se le sella la respuesta (`data.rek`).
177
+ * Diseño: `docs/sealed-requests.md`.
178
+ *
179
+ * Estos son los tipos que lo exigen: lo que pide un aparato con su firma. El emparejamiento,
180
+ * la entrada con contraseña y lo que se cruzan las bóvedas siguen su propio camino.
181
+ */
182
+ export const SEALED_REQUEST_TYPES = Object.freeze([
183
+ MSG.SIGN, MSG.GET, MSG.STORE, MSG.CHECK, MSG.DEVICES, MSG.RENEW, MSG.SECRETS,
184
+ MSG.ADMIN, MSG.RENOUNCE, MSG.INCIDENT, MSG.REWRAP_OK
185
+ ])
186
+
187
+ /**
188
+ * MIGRACIÓN — CADUCA EL 2026-12-15. Hasta esa fecha una petición de esos tipos que llega en
189
+ * claro (un cliente viejo) se atiende y se apunta en el log; desde esa fecha se rechaza con
190
+ * `request-unsealed`. Lo cubre `test/sealed-requests.test.mjs`. Quitar en cuanto pase.
191
+ */
192
+ export const UNSEALED_REQUESTS_UNTIL = Date.UTC(2026, 11, 15)
193
+ export const UNSEALED_REQUESTS_UNTIL_TEXT = '2026-12-15'
194
+ /** ¿Todavía se atiende una petición en claro? (migración, ver arriba) */
195
+ export const unsealedRequestsAllowed = (now = Date.now()) => now < UNSEALED_REQUESTS_UNTIL
@@ -27,6 +27,7 @@ import {
27
27
  verifyDeviceSig, makePairingCode, commitCode, pubkeyId, keyLabel } from '@dotrino/identity/capabilities'
28
28
  import { openWrap, wrapForMember, decryptWithCek } from '@dotrino/identity/content'
29
29
  import { verifyActa, sealKeyAt, sealersOf, memberCan, checkVaultReply, accountMismatch, verifySealerChain, actaHash } from '@dotrino/identity/acta'
30
+ import { sendToVault, acceptReply } from '@dotrino/identity/vault-seal'
30
31
  import { MSG, secretsScope, isValidSecretsNs, VAULT_PROTOCOL, VAULT_SPEAKS } from './protocol.js'
31
32
  import { PKG_VERSION } from './version.js'
32
33
  import { makeEphemeralKey, openSealed } from './sealed.js'
@@ -189,7 +190,13 @@ async function freshClient (proxyUrl, connectTimeoutMs = 20000, master = null) {
189
190
  // preferir. Se mira si está, en vez de apagarlo a mano para siempre: el día que este
190
191
  // código corra en un navegador —o que Node lo traiga— se enciende solo.
191
192
  const hasWebRTC = typeof globalThis.RTCPeerConnection === 'function'
192
- const client = new WebSocketProxyClient({ url: proxyUrl, enableWebRTC: hasWebRTC, autoReconnect: false })
193
+ // LA LLAVE DE UN SOLO USO de esta conexión (`docs/sealed-requests.md`): va dentro de cada
194
+ // petición firmada (`rek`) y la bóveda le sella la respuesta. Sin `myEncPub`, para no
195
+ // anunciarla: no es la llave de cifrado del servicio.
196
+ const { makeEncKeypair } = await import('@dotrino/proxy-client')
197
+ const replyKey = await makeEncKeypair()
198
+ const client = new WebSocketProxyClient({ url: proxyUrl, enableWebRTC: hasWebRTC, autoReconnect: false, myEncPrivateKey: replyKey.privateKey })
199
+ client.replyKey = replyKey.encPub
193
200
  // connect() del cliente solo se resuelve con 'connected' y solo rechaza en el
194
201
  // evento 'error' de transporte: si el socket cierra LIMPIO antes de 'connected'
195
202
  // (p.ej. el proxy banea la IP y envía close 1008), la promesa quedaría colgada
@@ -218,6 +225,22 @@ async function identifyAsService (client, device) {
218
225
  await client.identifyAs({ publickey: device.publickey, sign: (d) => signWithDevice({ privateJwk: device.privateJwk, data: d }) })
219
226
  }
220
227
 
228
+ /** `rek` dentro de lo firmado: a esa llave se sella la respuesta. El socket local no la lleva. */
229
+ const rekOf = (client) => (client?.replyKey ? { rek: client.replyKey } : {})
230
+
231
+ const toldOnce = new Set()
232
+ const warnOnce = (line) => { if (toldOnce.has(line)) return; toldOnce.add(line); console.error(line) }
233
+
234
+ /**
235
+ * MANDA UNA PETICIÓN A LA BÓVEDA, SELLADA (`@dotrino/identity/vault-seal`): entera, a la llave
236
+ * de transporte de cada bóveda de la cuenta (las de `acta`, la última que este servicio
237
+ * verificó, o una más nueva que encadene con ella), y enrutada a `dest`. A un replicador
238
+ * (`to`), solo a él.
239
+ */
240
+ function sendVault (client, dest, payload, { acta = null, to = null } = {}) {
241
+ return sendToVault(client, { dest, to, acta, payload, warn: warnOnce })
242
+ }
243
+
221
244
  /** Cuánto espera un agente a que alguien apruebe (el pedido vive 5 min en la bóveda). */
222
245
  export const APPROVAL_TIMEOUT_MS = 5 * 60 * 1000 + 10 * 1000
223
246
 
@@ -232,8 +255,11 @@ export const APPROVAL_TIMEOUT_MS = 5 * 60 * 1000 + 10 * 1000
232
255
  function waitForMsg (client, predicate, timeoutMs = 30000, guard = null) {
233
256
  return new Promise((resolve, reject) => {
234
257
  let unverified = null
235
- const off = client.on('message', async (_from, payload) => {
258
+ const off = client.on('message', async (_from, payload, meta) => {
236
259
  if (!payload || typeof payload !== 'object' || !predicate(payload)) return
260
+ // Lo que no es un error tiene que volver SELLADO (salvo por el socket local, y durante la
261
+ // migración, que se dice). Un error sin firma no decide nada de todos modos.
262
+ if (payload.type !== MSG.ERROR && !acceptReply({ meta, local: !!client.local, type: payload.type, warn: warnOnce })) return
237
263
  if (guard && payload.type === MSG.ERROR && !await isMyVaultError(payload, guard)) { unverified = payload; return }
238
264
  cleanup(); resolve(payload)
239
265
  })
@@ -475,7 +501,7 @@ export async function enrollWithVault ({ qr, label = 'agent', expectedScope = nu
475
501
  })
476
502
  if (!chk.ok) throw new Error('the vault reply does not check out: ' + chk.reason)
477
503
 
478
- return { device, enc: enc ? { publickey: enc.encPublickey, privateJwk: enc.encPrivateJwk } : null, cert: res.cert, iss: qr.iss, proxy: qr.proxy || 'wss://proxy.dotrino.com' }
504
+ return { device, enc: enc ? { publickey: enc.encPublickey, privateJwk: enc.encPrivateJwk } : null, cert: res.cert, iss: qr.iss, proxy: qr.proxy || 'wss://proxy.dotrino.com', acta: res.acta || null }
479
505
  } finally { client.close() }
480
506
  }
481
507
 
@@ -528,10 +554,11 @@ export async function enrollService ({ qr, ns, dir, label, onCode, onReplace, ap
528
554
  try { onReplace?.(replaced) } catch (_) {}
529
555
  }
530
556
 
531
- const { device, enc, cert, iss, proxy } = await enrollWithVault({ qr, label, expectedScope: secretsScope(ns), onCode, approveTimeoutMs })
557
+ const { device, enc, cert, iss, proxy, acta } = await enrollWithVault({ qr, label, expectedScope: secretsScope(ns), onCode, approveTimeoutMs })
532
558
  // v2: suma `enc`. El `device` (la llave de FIRMA) no se toca — de él sale el
533
- // id de nodo del proxio y la fila del acta.
534
- writeServiceIdentity(dir, { v: 2, ns, iss, proxy, device, enc, cert, enrolledAt: Date.now() })
559
+ // id de nodo del proxio y la fila del acta. `acta` (ya verificada aquí dentro): a qué
560
+ // bóvedas se le sella lo que pide; se pone al día con cada respuesta.
561
+ writeServiceIdentity(dir, { v: 2, ns, iss, proxy, device, enc, cert, acta, enrolledAt: Date.now() })
535
562
  return { device, enc, cert, iss, replaced }
536
563
  }
537
564
 
@@ -565,13 +592,13 @@ export async function registerEncKey ({ dir, ns, proxyUrl, masterPubkey, device,
565
592
  if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
566
593
 
567
594
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
568
- const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
595
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
569
596
  try {
570
597
  await identifyAsService(client, device)
571
- const data = { op: 'enckey', ns, encPub, publickey: device.publickey, ts: Date.now() }
598
+ const data = { op: 'enckey', ns, encPub, ...rekOf(client), publickey: device.publickey, ts: Date.now() }
572
599
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
573
600
  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 })
574
- client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data, signature, cert })
601
+ await sendVault(client, masterPubkey, { type: MSG.SECRETS, data, signature, cert }, { acta: saved?.acta })
575
602
  const res = await pending
576
603
  if (res.type === MSG.ERROR) throw vaultError(res)
577
604
  return { encPub, created, ok: true }
@@ -617,14 +644,14 @@ export async function storeVars ({ dir, ns, proxyUrl, masterPubkey, device, cert
617
644
  }
618
645
 
619
646
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
620
- const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
647
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
621
648
  try {
622
649
  await identifyAsService(client, device)
623
650
  const ask = async (data) => {
624
- const signed = { ...data, ns, publickey: device.publickey, ts: Date.now() }
651
+ const signed = { ...data, ns, ...rekOf(client), publickey: device.publickey, ts: Date.now() }
625
652
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data: signed })
626
653
  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 })
627
- client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data: signed, signature, cert })
654
+ await sendVault(client, masterPubkey, { type: MSG.SECRETS, data: signed, signature, cert }, { acta: saved?.acta })
628
655
  const res = await pending
629
656
  if (res.type === MSG.ERROR) throw vaultError(res)
630
657
  await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
@@ -673,13 +700,13 @@ export async function fetchDigest ({ dir, ns, proxyUrl, masterPubkey, device, ce
673
700
  if (!isValidSecretsNs(ns)) throw new Error('invalid ns')
674
701
  if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
675
702
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
676
- const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
703
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
677
704
  try {
678
705
  await identifyAsService(client, device)
679
- const data = { op: 'digest', ns, publickey: device.publickey, ts: Date.now() }
706
+ const data = { op: 'digest', ns, ...rekOf(client), publickey: device.publickey, ts: Date.now() }
680
707
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
681
708
  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 })
682
- client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data, signature, cert })
709
+ await sendVault(client, masterPubkey, { type: MSG.SECRETS, data, signature, cert }, { acta: saved?.acta })
683
710
  const res = await pending
684
711
  if (res.type === MSG.ERROR) throw vaultError(res)
685
712
  await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
@@ -726,10 +753,10 @@ export async function askUpdateApproval ({ product, version, from = null, dir, p
726
753
  if (typeof product !== 'string' || !product || typeof version !== 'string' || !version) throw new Error('askUpdateApproval: needs product and version')
727
754
  if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
728
755
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
729
- const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
756
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
730
757
  try {
731
758
  await identifyAsService(client, device)
732
- const data = { op: 'update-ask', product, version, ...(typeof from === 'string' && from ? { from } : {}), publickey: device.publickey, ts: Date.now() }
759
+ const data = { op: 'update-ask', product, version, ...(typeof from === 'string' && from ? { from } : {}), ...rekOf(client), publickey: device.publickey, ts: Date.now() }
733
760
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
734
761
  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)
735
762
  const check = async (res) => {
@@ -743,7 +770,11 @@ export async function askUpdateApproval ({ product, version, from = null, dir, p
743
770
  // día por algo que ya se contestó).
744
771
  const queue = []
745
772
  let wake = null
746
- const off = client.on('message', (_from, p) => { if (p && typeof p === 'object' && mine(p)) { queue.push(p); wake?.() } })
773
+ const off = client.on('message', (_from, p, meta) => {
774
+ if (!p || typeof p !== 'object' || !mine(p)) return
775
+ if (p.type !== MSG.ERROR && !acceptReply({ meta, local: !!client.local, type: p.type, warn: warnOnce })) return
776
+ queue.push(p); wake?.()
777
+ })
747
778
  const next = (ms, code, message) => new Promise((resolve, reject) => {
748
779
  if (queue.length) return resolve(queue.shift())
749
780
  const t = setTimeout(() => { wake = null; reject(Object.assign(new Error(message), { code })) }, ms)
@@ -751,7 +782,7 @@ export async function askUpdateApproval ({ product, version, from = null, dir, p
751
782
  })
752
783
  let body
753
784
  try {
754
- client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data, signature, cert })
785
+ await sendVault(client, masterPubkey, { type: MSG.SECRETS, data, signature, cert }, { acta: saved?.acta })
755
786
  body = await check(await next(timeoutMs, 'vault-no-reply', 'update-ask: the vault did not answer'))
756
787
  if (body.pending === true) {
757
788
  try { onPending?.({ id: body.id, exp: body.exp }) } catch (_) {}
@@ -840,13 +871,13 @@ async function reportToVault (op, { product, version, from = null, dir, proxyUrl
840
871
  if (typeof product !== 'string' || !product || typeof version !== 'string' || !version) throw new Error(`${op}: needs product and version`)
841
872
  if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
842
873
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
843
- const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
874
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
844
875
  try {
845
876
  await identifyAsService(client, device)
846
- const data = { op, product, version, ...(typeof from === 'string' && from ? { from } : {}), publickey: device.publickey, ts: Date.now() }
877
+ const data = { op, product, version, ...(typeof from === 'string' && from ? { from } : {}), ...rekOf(client), publickey: device.publickey, ts: Date.now() }
847
878
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
848
879
  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 })
849
- client.sendByPubkey(masterPubkey, { type: MSG.SECRETS, data, signature, cert })
880
+ await sendVault(client, masterPubkey, { type: MSG.SECRETS, data, signature, cert }, { acta: saved?.acta })
850
881
  const res = await pending.catch((e) => {
851
882
  if (/timeout/.test(e.message)) throw Object.assign(new Error(`${op}: the vault did not answer`), { code: 'vault-no-reply' })
852
883
  throw e
@@ -882,7 +913,7 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
882
913
  }
883
914
 
884
915
  const client = await freshClient(proxyUrl, 20000, masterPubkey)
885
- const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
916
+ const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
886
917
  try {
887
918
  await identifyAsService(client, device)
888
919
 
@@ -918,12 +949,15 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
918
949
  // aunque la selle otra bóveda de la cuenta (`verifyResponder`). La primera vez se guarda
919
950
  // también con el mismo `seq`, porque un agente de antes no lo tenía.
920
951
  if (typeof saved?.actaSeq === 'number' && acta.seq === saved.actaSeq && !Array.isArray(saved.sealers)) remember({ sealers: sealersOf(acta) })
952
+ // A QUIÉN SE SELLA (`docs/sealed-requests.md`): las bóvedas de la cuenta salen de esta acta,
953
+ // que ya se aceptó. Un agente de antes no la tenía guardada: se apunta también con el mismo `seq`.
954
+ if (!saved?.acta || (typeof saved.acta.seq === 'number' && acta.seq > saved.acta.seq)) remember({ acta })
921
955
  if (typeof saved?.actaSeq === 'number' && acta.seq <= saved.actaSeq) return
922
956
  // Y QUIÉNES REPARTEN. Sale del acta, que llega firmada en cada respuesta, así que no
923
957
  // hay una lista que mantener a mano ni un `.env` que se olvide: darle `replica` a un
924
958
  // aparato basta para que sus servicios sepan preguntarle cuando la bóveda no esté.
925
959
  const replicas = (acta.members || []).filter((m) => memberCan(acta, m.pub, 'replica')).map((m) => m.pub)
926
- remember({ actaSeq: acta.seq, replicas, sealers: sealersOf(acta) })
960
+ remember({ actaSeq: acta.seq, replicas, sealers: sealersOf(acta), acta })
927
961
  }
928
962
 
929
963
  // DOS MOTIVOS PARA PEDIR PAPEL NUEVO:
@@ -942,10 +976,10 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
942
976
  // insiste: si falla, se sigue con el papel que hay — que probablemente valga.
943
977
  const renewCert = async () => {
944
978
  try {
945
- const data = { op: 'renew', publickey: device.publickey, ts: Date.now() }
979
+ const data = { op: 'renew', ...rekOf(client), publickey: device.publickey, ts: Date.now() }
946
980
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
947
981
  const pending = waitForMsg(client, (p) => p.type === MSG.RENEWED || p.type === MSG.ERROR, 15000)
948
- client.sendByPubkey(masterPubkey, { type: MSG.RENEW, data, signature, cert })
982
+ await sendVault(client, masterPubkey, { type: MSG.RENEW, data, signature, cert }, { acta: saved?.acta })
949
983
  const res = await pending
950
984
  // SE VERIFICA ANTES DE GUARDARLO. Aquí solo se miraba que fuera para esta llave: un
951
985
  // papel cualquiera, sin firma que valga, sustituía al bueno y el servicio se quedaba
@@ -987,7 +1021,7 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
987
1021
  const ctx = client.local ? selfContext() : null
988
1022
  // `publicOnly` VIAJA FIRMADO (va dentro de `data`), así que nadie lo puede quitar ni
989
1023
  // poner por el camino. Quien decide qué se manda es la bóveda; esto solo es la petición.
990
- data = { op: 'secrets', ns, ek: eph.ek, publickey: device.publickey, ts: Date.now(), v: declarationOf({ product, version, needs }), machine: selfMachine(), ...(ctx ? { ctx } : {}), ...(publicOnly ? { publicOnly: true } : {}) }
1024
+ data = { op: 'secrets', ns, ek: eph.ek, ...rekOf(client), publickey: device.publickey, ts: Date.now(), v: declarationOf({ product, version, needs }), machine: selfMachine(), ...(ctx ? { ctx } : {}), ...(publicOnly ? { publicOnly: true } : {}) }
991
1025
  ;({ signature } = await signWithDevice({ privateJwk: device.privateJwk, data }))
992
1026
  // A QUIÉN SE LE PREGUNTA: primero a la bóveda, y si no contesta, a los REPLICADORES
993
1027
  // que el acta nombraba la última vez que la vimos (`docs/replicas.md` §8: «el servicio
@@ -1007,8 +1041,10 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
1007
1041
  let last = null
1008
1042
  for (const target of targets) {
1009
1043
  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 })
1010
- client.sendByPubkey(target, { type: MSG.SECRETS, data, signature, cert })
1011
- try { res = await pending; break } catch (e) { last = e }
1044
+ try {
1045
+ await sendVault(client, target, { type: MSG.SECRETS, data, signature, cert }, target === masterPubkey ? { acta: saved?.acta } : { to: target })
1046
+ res = await pending; break
1047
+ } catch (e) { last = e }
1012
1048
  }
1013
1049
  if (!res) throw last || new Error('nobody answered: neither the vault nor any replica')
1014
1050
  }
@@ -1252,14 +1288,14 @@ export async function sealedByChain ({ chain, acta, masterPubkey }) {
1252
1288
  * Pide la cadena de selladoras a la bóveda (`vault.devices`: la manda también a un servicio
1253
1289
  * sin `lee`). Una vez por operación: la segunda llamada reusa la primera respuesta.
1254
1290
  */
1255
- export function sealerChainAsker ({ client, masterPubkey, device, cert, timeoutMs = 15000 }) {
1291
+ export function sealerChainAsker ({ client, masterPubkey, device, cert, acta = null, timeoutMs = 15000 }) {
1256
1292
  let pending = null
1257
1293
  return () => {
1258
1294
  pending = pending || (async () => {
1259
- const data = { op: 'devices', publickey: device.publickey, ts: Date.now() }
1295
+ const data = { op: 'devices', ...rekOf(client), publickey: device.publickey, ts: Date.now() }
1260
1296
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
1261
1297
  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 })
1298
+ await sendVault(client, masterPubkey, { type: MSG.DEVICES, data, signature, cert }, { acta })
1263
1299
  const res = await wait
1264
1300
  if (res.type === MSG.ERROR) throw new Error('the vault refused: ' + res.error)
1265
1301
  if (!Array.isArray(res.sealerChain) || !res.sealerChain.length) throw new Error('the vault sent no sealer chain')
@@ -1453,7 +1489,7 @@ export async function watchSecretsChanges ({
1453
1489
  let client = null
1454
1490
  // La cadena de selladoras, pedida por la conexión viva. Una por aviso: se rehace cada vez
1455
1491
  // porque la conexión cambia al reconectar.
1456
- const watchChainAsker = () => sealerChainAsker({ client, masterPubkey: master, device: saved.device, cert: readServiceIdentity(dir)?.cert || saved.cert })
1492
+ const watchChainAsker = () => sealerChainAsker({ client, masterPubkey: master, device: saved.device, cert: readServiceIdentity(dir)?.cert || saved.cert, acta: readServiceIdentity(dir)?.acta || saved.acta })
1457
1493
  let retryTimer = null
1458
1494
  // Huella de la configuración EN USO. Comparar huellas y no valores es lo que permite
1459
1495
  // decir «esto no es lo que está corriendo» sin volver a manejar los secretos.
@@ -1531,9 +1567,9 @@ export async function watchSecretsChanges ({
1531
1567
  if (!ident?.enc?.privateJwk) return log('[vault] rewrap: this agent has no encryption key')
1532
1568
  const cek = await openWrap({ wrap: body.wrap, myEncPrivateKey: await importDeviceEncKey(ident.enc.privateJwk) })
1533
1569
  const wrap = await wrapForMember({ cek, memberEncPub: target.encPub })
1534
- const data = { op: 'rewrap.ok', owner: body.owner, gen: body.gen, target: body.target, wrap, ts: Date.now() }
1570
+ const data = { op: 'rewrap.ok', owner: body.owner, gen: body.gen, target: body.target, wrap, ...rekOf(client), ts: Date.now() }
1535
1571
  const { signature } = await signWithDevice({ privateJwk: saved.device.privateJwk, data })
1536
- client.sendByPubkey(master, { type: MSG.REWRAP_OK, data, signature, cert: saved.cert })
1572
+ await sendVault(client, master, { type: MSG.REWRAP_OK, data, signature, cert: saved.cert }, { acta: readServiceIdentity(dir)?.acta || saved.acta })
1537
1573
  log(`[vault] key handed to ${String(body.target).slice(0, 12)}… for ${body.owner} (gen ${body.gen})`)
1538
1574
  } catch (e) {
1539
1575
  log('[vault] rewrap failed: ' + e.message)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/vaultd",
3
- "version": "0.191.0",
3
+ "version": "0.192.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": {
@@ -22,10 +22,10 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@dotrino/compat": "0.5.0",
25
- "@dotrino/identity": "0.135.0",
25
+ "@dotrino/identity": "0.136.0",
26
26
  "@dotrino/opaque": "0.1.0",
27
27
  "@dotrino/passmanager": "0.18.6",
28
- "@dotrino/proxy-client": "^0.46.0",
28
+ "@dotrino/proxy-client": "^0.47.0",
29
29
  "@dotrino/roadmap": "0.4.63",
30
30
  "@dotrino/store": "0.13.0",
31
31
  "@dotrino/update": "0.9.0",
package/src/client.js CHANGED
@@ -17,6 +17,8 @@ import { myContentKey, encryptWithCek, decryptWithKeyring } from '@dotrino/ident
17
17
  import { checkVaultReply } from '@dotrino/identity/acta'
18
18
  import { installNodeGlobals } from './node-globals.js'
19
19
  import { MSG } from './protocol.js'
20
+ // SELLADO (`docs/sealed-requests.md`): la petición entera a las bóvedas del acta, la respuesta a `rek`.
21
+ import { sendToVault, acceptReply } from '@dotrino/identity/vault-seal'
20
22
 
21
23
  async function freshClient ({ proxyUrl, dir = '.dotrino-vault-device' }) {
22
24
  installNodeGlobals(dir)
@@ -24,11 +26,19 @@ async function freshClient ({ proxyUrl, dir = '.dotrino-vault-device' }) {
24
26
  // WEBRTC SOLO DONDE EXISTE (ver `lib/src/service.js`): en Node no hay
25
27
  // `RTCPeerConnection` y encenderlo reventaría al negociar; en un navegador es nativo y es
26
28
  // el camino directo que hay que preferir. Se mira, en vez de apagarlo para siempre.
27
- const client = new WebSocketProxyClient({ url: proxyUrl, enableWebRTC: typeof globalThis.RTCPeerConnection === 'function', autoReconnect: false })
29
+ // La llave de un solo uso de la respuesta (`rek`): abre lo que la bóveda le sella, y no se anuncia.
30
+ const { makeEncKeypair } = await import('@dotrino/proxy-client')
31
+ const replyKey = await makeEncKeypair()
32
+ const client = new WebSocketProxyClient({ url: proxyUrl, enableWebRTC: typeof globalThis.RTCPeerConnection === 'function', autoReconnect: false, myEncPrivateKey: replyKey.privateKey })
33
+ client.replyKey = replyKey.encPub
28
34
  await client.connect()
29
35
  return client
30
36
  }
31
37
 
38
+ const warn = (line) => console.error(line)
39
+ /** Manda a la bóveda SELLADO a las bóvedas que nombra `acta`. */
40
+ const toVault = (client, masterPubkey, acta, payload) => sendToVault(client, { dest: masterPubkey, acta, payload, warn })
41
+
32
42
  /** Identifica la conexión bajo la pubkey de dispositivo D (para ser direccionable). */
33
43
  async function identifyAsDevice (client, device) {
34
44
  if (!client.token) return
@@ -38,8 +48,10 @@ async function identifyAsDevice (client, device) {
38
48
 
39
49
  function waitFor (client, predicate, timeoutMs = 30000) {
40
50
  return new Promise((resolve, reject) => {
41
- const off = client.on('message', (_from, payload) => {
42
- if (payload && typeof payload === 'object' && predicate(payload)) { cleanup(); resolve(payload) }
51
+ const off = client.on('message', (_from, payload, meta) => {
52
+ if (!payload || typeof payload !== 'object' || !predicate(payload)) return
53
+ if (payload.type !== MSG.ERROR && !acceptReply({ meta, type: payload.type, warn })) return
54
+ cleanup(); resolve(payload)
43
55
  })
44
56
  const t = setTimeout(() => { cleanup(); reject(new Error('timeout waiting for the vault response')) }, timeoutMs)
45
57
  const cleanup = () => { off(); clearTimeout(t) }
@@ -115,13 +127,13 @@ export async function verifyRevoke ({ body, signature, master, devicePubkey }) {
115
127
  }
116
128
 
117
129
  /** Pide a la maestra que firme `payload` (scope vault:sign). */
118
- export async function requestSign ({ masterPubkey, proxyUrl, device, cert, payload, dir } = {}) {
130
+ export async function requestSign ({ masterPubkey, proxyUrl, device, cert, acta = null, payload, dir } = {}) {
119
131
  const client = await freshClient({ proxyUrl, dir })
120
132
  try {
121
- const data = { op: 'sign', payload, publickey: device.publickey, ts: Date.now() }
133
+ const data = { op: 'sign', payload, rek: client.replyKey, publickey: device.publickey, ts: Date.now() }
122
134
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
123
135
  const pending = waitFor(client, (p) => p.type === MSG.SIGNED || p.type === MSG.ERROR)
124
- client.sendByPubkey(masterPubkey, { type: MSG.SIGN, data, signature, cert })
136
+ await toVault(client, masterPubkey, acta, { type: MSG.SIGN, data, signature, cert })
125
137
  const res = await pending
126
138
  if (res.type === MSG.ERROR) throw new Error(res.error)
127
139
  return { signature: res.signature, publickey: res.publickey }
@@ -129,13 +141,13 @@ export async function requestSign ({ masterPubkey, proxyUrl, device, cert, paylo
129
141
  }
130
142
 
131
143
  /** Lee un nodo del árbol del vault (scope vault:read). */
132
- export async function requestGet ({ masterPubkey, proxyUrl, device, cert, id = 'root', dir } = {}) {
144
+ export async function requestGet ({ masterPubkey, proxyUrl, device, cert, acta = null, id = 'root', dir } = {}) {
133
145
  const client = await freshClient({ proxyUrl, dir })
134
146
  try {
135
- const data = { op: 'get', id, publickey: device.publickey, ts: Date.now() }
147
+ const data = { op: 'get', id, rek: client.replyKey, publickey: device.publickey, ts: Date.now() }
136
148
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
137
149
  const pending = waitFor(client, (p) => p.type === MSG.DATA || p.type === MSG.ERROR)
138
- client.sendByPubkey(masterPubkey, { type: MSG.GET, data, signature, cert })
150
+ await toVault(client, masterPubkey, acta, { type: MSG.GET, data, signature, cert })
139
151
  const res = await pending
140
152
  if (res.type === MSG.ERROR) throw new Error(res.error)
141
153
  return { id: res.id, node: res.node }
@@ -150,13 +162,13 @@ export async function requestGet ({ masterPubkey, proxyUrl, device, cert, id = '
150
162
  * después de emparejarlo —y como se le cae uno que le quitaron—. Un cert vencido o
151
163
  * revocado no se renueva: ahí toca volver a emparejar.
152
164
  */
153
- export async function requestRenew ({ masterPubkey, proxyUrl, device, cert, dir } = {}) {
165
+ export async function requestRenew ({ masterPubkey, proxyUrl, device, cert, acta = null, dir } = {}) {
154
166
  const client = await freshClient({ proxyUrl, dir })
155
167
  try {
156
- const data = { op: 'renew', publickey: device.publickey, ts: Date.now() }
168
+ const data = { op: 'renew', rek: client.replyKey, publickey: device.publickey, ts: Date.now() }
157
169
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
158
170
  const pending = waitFor(client, (p) => p.type === MSG.RENEWED || p.type === MSG.ERROR)
159
- client.sendByPubkey(masterPubkey, { type: MSG.RENEW, data, signature, cert })
171
+ await toVault(client, masterPubkey, acta, { type: MSG.RENEW, data, signature, cert })
160
172
  const res = await pending
161
173
  if (res.type === MSG.ERROR) throw new Error(res.error)
162
174
  // Se valida antes de devolverlo, igual que en el enrolamiento: un cert que no firmó la
@@ -181,10 +193,10 @@ export async function requestStore ({ masterPubkey, proxyUrl, device, cert, acta
181
193
  const enc = await encryptWithCek({ cek: mine.cek, gen: mine.gen, plaintext: JSON.stringify(args ?? {}) })
182
194
  const client = await freshClient({ proxyUrl, dir })
183
195
  try {
184
- const data = { op: 'store', method, enc, publickey: device.publickey, ts: Date.now() }
196
+ const data = { op: 'store', method, enc, rek: client.replyKey, publickey: device.publickey, ts: Date.now() }
185
197
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
186
198
  const pending = waitFor(client, (p) => p.type === MSG.STORE_RESULT || p.type === MSG.ERROR)
187
- client.sendByPubkey(masterPubkey, { type: MSG.STORE, data, signature, cert })
199
+ await toVault(client, masterPubkey, acta, { type: MSG.STORE, data, signature, cert })
188
200
  const res = await pending
189
201
  if (res.type === MSG.ERROR) throw Object.assign(new Error(res.error), res.code ? { code: res.code } : {})
190
202
  if (!res.result?.__enc) throw Object.assign(new Error('the vault replied to the store without encrypting it'), { code: 'vault-reply-unsealed' })
@@ -200,7 +212,7 @@ export async function requestStore ({ masterPubkey, proxyUrl, device, cert, acta
200
212
  * El `nonce` de un solo uso NO es decorativo: `approve` y `revoke` cambian estado, así
201
213
  * que la ventana de frescura de ±5 min no basta para descartar un replay.
202
214
  */
203
- export async function requestAdmin ({ masterPubkey, proxyUrl, device, cert, op, dir, nonce: dado, ...rest } = {}) {
215
+ export async function requestAdmin ({ masterPubkey, proxyUrl, device, cert, acta = null, op, dir, nonce: dado, ...rest } = {}) {
204
216
  const client = await freshClient({ proxyUrl, dir })
205
217
  try {
206
218
  // EL NONCE SE PUEDE DAR. Abrir la bóveda a distancia lo mete TAMBIÉN dentro del sobre
@@ -209,10 +221,10 @@ export async function requestAdmin ({ masterPubkey, proxyUrl, device, cert, op,
209
221
  const nonce = typeof dado === 'string' && dado.length >= 16
210
222
  ? dado
211
223
  : [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, '0')).join('')
212
- const data = { op, ...rest, publickey: device.publickey, ts: Date.now(), nonce }
224
+ const data = { op, ...rest, rek: client.replyKey, publickey: device.publickey, ts: Date.now(), nonce }
213
225
  const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
214
226
  const pending = waitFor(client, (p) => p.type === MSG.ADMIN_RESULT || p.type === MSG.ERROR)
215
- client.sendByPubkey(masterPubkey, { type: MSG.ADMIN, data, signature, cert })
227
+ await toVault(client, masterPubkey, acta, { type: MSG.ADMIN, data, signature, cert })
216
228
  const res = await pending
217
229
  if (res.type === MSG.ERROR) {
218
230
  // CON LO QUE TRAE: el `code` y —al abrir— el freno. Emparejar por el TEXTO es lo que
package/src/replica.js CHANGED
@@ -23,10 +23,10 @@
23
23
  import fs from 'node:fs'
24
24
  import path from 'node:path'
25
25
  import os from 'node:os'
26
- import { WebSocketProxyClient } from '@dotrino/proxy-client'
26
+ import { WebSocketProxyClient, makeEncKeypair, exportEncPrivate, importEncPrivate, isEncPub } from '@dotrino/proxy-client'
27
27
  import { signWithDevice, verifyDeviceSig, verifyChain, pubkeyId, keyLabel } from '@dotrino/identity/capabilities'
28
28
  import { verifyActa, memberCan, memberCanReadSecrets, sealKeyAt, sealersOf } from '@dotrino/identity/acta'
29
- import { MSG, secretsScope, isValidSecretsNs } from '../lib/src/protocol.js'
29
+ import { MSG, secretsScope, isValidSecretsNs, unsealedRequestsAllowed, UNSEALED_REQUESTS_UNTIL_TEXT } from '../lib/src/protocol.js'
30
30
  import { FRESH_WINDOW_MS } from '../lib/src/enroll.js'
31
31
  import { seal } from '../lib/src/sealed.js'
32
32
  import { atRestFor } from './atrest.js'
@@ -165,7 +165,19 @@ export async function runReplica ({ dir = replicaDir(), proxyUrl, wakeUrl = null
165
165
  // Por llave solo se habla con la BÓVEDA (`link.iss`), que es a quien queremos alcanzar
166
166
  // aunque no esté conectada ahora mismo.
167
167
 
168
- const client = new WebSocketProxyClient({ url })
168
+ /**
169
+ * LA LLAVE DE TRANSPORTE (`docs/sealed-requests.md`): con ella abre lo que los servicios le
170
+ * sellan —qué cajón piden, desde qué máquina— y nada más. No es una llave del acta: el acta
171
+ * sigue sin nombrarle llave de cifrado, así que ningún sobre de secretos puede ir a ella.
172
+ * Se estrena una vez y se guarda con el enlace (cifrado en reposo); su pública la anuncia el
173
+ * pilar, firmada por la llave del aparato, al identificarse.
174
+ */
175
+ if (!link.transport?.priv || !isEncPub(link.transport?.encPub)) {
176
+ const kp = await makeEncKeypair()
177
+ store.setLink({ ...link, transport: { encPub: kp.encPub, priv: await exportEncPrivate(kp.privateKey) } })
178
+ }
179
+ const transport = store.link.transport
180
+ const client = new WebSocketProxyClient({ url, myEncPub: transport.encPub, myEncPrivateKey: await importEncPrivate(transport.priv) })
169
181
  await client.connect()
170
182
  // El sobre lo arma el pilar (`identifyAs`), que le pone el destinatario.
171
183
  await client.identifyAs({ publickey: link.device.publickey, sign: (d) => sign(d) })
@@ -246,12 +258,31 @@ export async function runReplica ({ dir = replicaDir(), proxyUrl, wakeUrl = null
246
258
  * y no hace falta: quitar un aparato es sacarlo del acta (`docs/acta-de-perfil.md`), y de
247
259
  * eso se ocupa `memberCanReadSecrets` con el acta de abajo.
248
260
  */
249
- async function onSecrets (from, p) {
261
+ async function onSecrets (from, p, meta) {
250
262
  const ns = p?.data?.ns
251
263
  const ek = p?.data?.ek
252
264
  if (!isValidSecretsNs(ns) || typeof ek !== 'string') return
253
- if (!store.acta) return client.send(from, { type: MSG.ERROR, error: 'replica: no record yet' })
254
- const no = (error) => client.send(from, { type: MSG.ERROR, error })
265
+ // LO QUE SE CONTESTA VUELVE SELLADO a la llave de un solo uso de la petición (`data.rek`)
266
+ // cuando la petición vino sellada. En claro solo durante la migración (caduca 2026-12-15).
267
+ const rek = p?.data?.rek
268
+ const send = (obj) => {
269
+ if (meta?.sealed && isEncPub(rek)) {
270
+ return client.sendSealedTo(from, obj, { peerEncPub: rek, pilar: true })
271
+ .catch((e) => log(`[replica] could not send a sealed reply (${e.code || 'error'}): ${e.message}`))
272
+ }
273
+ client.send(from, obj)
274
+ }
275
+ if (!meta?.sealed) {
276
+ if (!unsealedRequestsAllowed()) {
277
+ log('[replica] a secrets request arrived UNSEALED: refused (the migration window is over)')
278
+ return client.send(from, { type: MSG.ERROR, error: 'replica: requests must be sealed — update the client', code: 'request-unsealed' })
279
+ }
280
+ if (!unsealedTold) { unsealedTold = true; log(`[replica] a secrets request arrived UNSEALED from an old client: served until ${UNSEALED_REQUESTS_UNTIL_TEXT} (migration), then refused`) }
281
+ } else if (!isEncPub(rek)) {
282
+ return client.send(from, { type: MSG.ERROR, error: 'replica: a sealed request needs data.rek to seal the reply to', code: 'no-reply-key' })
283
+ }
284
+ if (!store.acta) return send({ type: MSG.ERROR, error: 'replica: no record yet' })
285
+ const no = (error) => send({ type: MSG.ERROR, error })
255
286
  const acta = store.acta
256
287
 
257
288
  if (typeof p?.data?.ts !== 'number' || Math.abs(Date.now() - p.data.ts) > FRESH_WINDOW_MS) {
@@ -280,7 +311,7 @@ export async function runReplica ({ dir = replicaDir(), proxyUrl, wakeUrl = null
280
311
  const b = store.bundleFor(ns, who)
281
312
  if (!b) {
282
313
  log(`[replica] asked for "${ns}" and has nothing stored for that device`)
283
- return client.send(from, {
314
+ return send({
284
315
  type: MSG.ERROR,
285
316
  error: `replica: nothing stored for "${ns}" and this device — ask the vault once while it is up`
286
317
  })
@@ -290,18 +321,19 @@ export async function runReplica ({ dir = replicaDir(), proxyUrl, wakeUrl = null
290
321
  // `by` y no `seq`: no tenemos la llave de sellado y no debemos tenerla. Quien recibe
291
322
  // mira el acta, ve que a esta llave le reconoce `replica`, y acepta.
292
323
  const { signature } = await sign(body)
293
- client.send(from, { type: MSG.SECRETS_RESULT, body, seal: { by: link.device.publickey, sig: signature } })
324
+ send({ type: MSG.SECRETS_RESULT, body, seal: { by: link.device.publickey, sig: signature } })
294
325
  log(`[replica] served "${ns}" from record #${store.seq}`)
295
326
  }
296
327
 
297
328
  /** Todo lo que DECIDE algo se contesta que no, y se dice por qué. */
298
329
  const NO_DECIDE = new Set([MSG.ENROLL, MSG.ADMIN, MSG.RENEW, MSG.RENOUNCE, MSG.SIGN, MSG.ACTA_SEALED])
299
330
 
300
- client.on('message', (from, p) => {
331
+ let unsealedTold = false
332
+ client.on('message', (from, p, meta) => {
301
333
  onActivity?.()
302
334
  const t = p?.type
303
335
  if (t === MSG.REPLICA_PUSH) return onPush(from, p).catch((e) => log('[replica] push: ' + e.message))
304
- if (t === MSG.SECRETS) return onSecrets(from, p).catch((e) => log('[replica] secrets: ' + e.message))
336
+ if (t === MSG.SECRETS) return onSecrets(from, p, meta).catch((e) => log('[replica] secrets: ' + e.message))
305
337
  if (NO_DECIDE.has(t)) {
306
338
  log(`[replica] refused "${t}": a replica hands things out, it does not decide`)
307
339
  return client.send(from, {
package/src/tui/app.js CHANGED
@@ -1153,7 +1153,7 @@ async function refreshMembers (term, st) {
1153
1153
  * que nadie está mirando.
1154
1154
  */
1155
1155
  async function refreshLogins (term, st, api = vc) {
1156
- const r = await guard(term, st, L(st).refreshing, () => api.listLogins(activeId(st)))
1156
+ const r = await guard(term, st, L(st).loadingLogins, () => api.listLogins(activeId(st)))
1157
1157
  if (r.ok) st.logins = r.v
1158
1158
  else st.logins = []
1159
1159
  }
@@ -2217,7 +2217,7 @@ async function onKeySecrets (term, st, key) {
2217
2217
  function promptRenameVariable (term, st, cur) {
2218
2218
  const i = L(st)
2219
2219
  setInput(st, {
2220
- label: i.renameLabel(cur.key),
2220
+ label: i.renameVarLabel(cur.key),
2221
2221
  hint: i.renameHint,
2222
2222
  value: cur.key,
2223
2223
  onSubmit: async (newer) => {
package/src/tui/i18n.js CHANGED
@@ -262,6 +262,7 @@ const es = {
262
262
  loadingDevices: 'Cargando dispositivos…',
263
263
  loadingSecrets: 'Cargando secretos…',
264
264
  loadingVaults: 'Cargando bóvedas…',
265
+ loadingLogins: 'Cargando los inicios de sesión…',
265
266
  switchingVault: 'Cambiando de bóveda…',
266
267
  vaultNowActive: (name) => `Bóveda activa: ${name}`,
267
268
  newVaultLabel: 'Nombre de la nueva bóveda',
@@ -388,9 +389,8 @@ const es = {
388
389
  newVarPrivateAsk: '¿Es privada?',
389
390
  makePublicConfirm: '¿Hacerla pública?',
390
391
  changingVisibility: 'Cambiando…',
391
- renameLabel: (k) => `Nuevo nombre para ${k}`,
392
+ renameVarLabel: (k) => `Nuevo nombre para ${k}`,
392
393
  renameHint: 'MAYUSCULAS_CON_GUION_BAJO · el valor no se toca · Esc cancela',
393
- renaming: 'Renombrando…',
394
394
  renamed: (a, b) => `${a} ahora se llama ${b} — el servicio que la lee se reinicia; si busca el nombre viejo, ya no lo encuentra`,
395
395
  nowPublic: 'Pública: se entrega sin pedirte permiso',
396
396
  nowPrivate: 'Privada: para entregarla te pide permiso',
@@ -813,6 +813,7 @@ const en = {
813
813
  loadingDevices: 'Loading devices…',
814
814
  loadingSecrets: 'Loading secrets…',
815
815
  loadingVaults: 'Loading vaults…',
816
+ loadingLogins: 'Loading the sign-ins…',
816
817
  switchingVault: 'Switching vault…',
817
818
  vaultNowActive: (name) => `Active vault: ${name}`,
818
819
  newVaultLabel: 'Name of the new vault',
@@ -926,9 +927,8 @@ const en = {
926
927
  newVarPrivateAsk: 'Is it private?',
927
928
  makePublicConfirm: 'Make it public?',
928
929
  changingVisibility: 'Changing…',
929
- renameLabel: (k) => `New name for ${k}`,
930
+ renameVarLabel: (k) => `New name for ${k}`,
930
931
  renameHint: 'UPPERCASE_WITH_UNDERSCORES · the value is not touched · Esc cancels',
931
- renaming: 'Renaming…',
932
932
  renamed: (a, b) => `${a} is now ${b} — the service that reads it restarts; if it looks for the old name, it will not find it`,
933
933
  nowPublic: 'Public: handed over without asking you',
934
934
  nowPrivate: 'Private: handing it over asks you first',