@dotrino/vaultd 0.177.0 → 0.179.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.
package/lib/src/admin.js CHANGED
@@ -55,16 +55,16 @@ export const ADMIN_OPS = Object.freeze([
55
55
  // no debe poder dejar sin configuración a los servicios.
56
56
  // `var.setMany` es la MISMA operación con varias variables dentro de un solo sobre: no
57
57
  // añade permisos, quita reinicios (ver el enrutado abajo).
58
- // Ver un valor, su histórico o volver a una versión NO están, y es a propósito: un
59
- // aparato que administra no tiene sobres de lo privado (solo el servicio dueño y la
60
- // recuperación). Eso lo hace la bóveda en su máquina (`secret show/history/revert`).
61
- // No lo cablees.
58
+ // `var.reveal`: VER el valor de una privada (dueño, 2026-10-26). Lo abre la bóveda con la
59
+ // llave del perfil (tiene que estar abierta), pide aprobación si hay quien apruebe y lo
60
+ // cierra a una llave efímera de quien pregunta (`varsDesk.reveal`). El histórico y volver
61
+ // a una versión siguen siendo solo de la máquina de la bóveda (`secret history/revert`).
62
62
  // `var.recipients` es solo LEER, y hace falta para poder escribir: la consola sella el
63
63
  // valor ella misma (§8.1) y para eso necesita saber a quién envolverle la llave. Estaba
64
64
  // documentada en `buildSealedVar` y la consola la llamaba, pero no existía — así que
65
65
  // crear una variable desde la consola contestaba «admin: invalid operation». No expone
66
66
  // nada nuevo: son llaves PÚBLICAS, las mismas que ya viajan en el acta.
67
- 'vars', 'var.set', 'var.setMany', 'var.recipients',
67
+ 'vars', 'var.set', 'var.setMany', 'var.recipients', 'var.reveal.begin', 'var.reveal',
68
68
  // ABRIR LA BÓVEDA A DISTANCIA (`docs/abrir-a-distancia.md`). Dos pasos: `unlock.begin`
69
69
  // pide una llave efímera y los parámetros del molino; `unlock` trae la derivada dentro
70
70
  // de un sobre que solo esta bóveda puede abrir. No hay una tercera.
@@ -98,7 +98,7 @@ export const ADMIN_OPS = Object.freeze([
98
98
  * enterarse de por qué no funciona y parecería rota. Así puede decir «está cerrada».
99
99
  */
100
100
  export const ADMIN_OPS_WHILE_LOCKED = Object.freeze([
101
- 'audit', 'vars', 'var.set', 'var.setMany', 'var.recipients',
101
+ 'audit', 'vars', 'var.set', 'var.setMany', 'var.recipients', 'var.reveal.begin', 'var.reveal',
102
102
  // Bloquear no sella nada: la lista es de la bóveda, no del acta.
103
103
  'blocked', 'block', 'unblock',
104
104
  // Las dos de abrir, obviamente: son las únicas que solo tienen sentido con el candado
@@ -230,6 +230,18 @@ export function createAdminDesk ({
230
230
  return { ok: true, result: { entries: readActivity(limit) } }
231
231
  }
232
232
 
233
+ // VER UNA PRIVADA (`varsDesk.reveal`). Antes que las demás de variables porque aquí no
234
+ // viaja ningún destino en claro: va dentro del sobre, y la política es de la bóveda.
235
+ if (data.op === 'var.reveal.begin' || data.op === 'var.reveal') {
236
+ if (!vars || typeof vars.reveal !== 'function') return { ok: false, error: 'admin: this vault cannot show a private variable (update it)' }
237
+ try {
238
+ const result = data.op === 'var.reveal.begin'
239
+ ? await vars.revealBegin({ caller: chk.device, by })
240
+ : await vars.reveal({ door: data.door, enc: data.enc, request: typeof data.request === 'string' ? data.request : null, caller: chk.device, by })
241
+ return { ok: true, result }
242
+ } catch (e) { return { ok: false, error: e.message, code: e.code || null } }
243
+ }
244
+
233
245
  // VARIABLES DE ENTORNO. El módulo solo enruta y audita: qué valor puede salir y con
234
246
  // qué se cifra lo decide la bóveda (`vars`), que es la que tiene la clave y el disco.
235
247
  if (data.op === 'vars' || data.op === 'var.set' || data.op === 'var.setMany' || data.op === 'var.recipients') {
@@ -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.105.0'
8
+ export const LIB_VERSION = '0.106.0'
@@ -233,6 +233,23 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
233
233
  * variables (la escritura se aplica al aprobar). Si nadie contesta, vence solo con un no:
234
234
  * nada se queda colgado para siempre.
235
235
  */
236
+ /** Lo aprobado para VER una privada desde la consola (`varsDesk.reveal`): una lectura por pedido. */
237
+ const revealGrants = new Map()
238
+ /** Las puertas de `revealBegin`: una llave efímera por pregunta, un minuto, un uso. */
239
+ const revealDoors = new Map()
240
+ /** Abre la privada y la entrega sellada a la efímera de quien preguntó, firmada y con el acta. */
241
+ async function deliverReveal ({ owner, ns, pub, key, ek, by, approved }) {
242
+ // Pudo cerrarse mientras se esperaba el sí.
243
+ if (isLocked()) throw Object.assign(new Error('the vault is closed: open it to see a private variable'), { code: 'vault-locked' })
244
+ const value = await secrets.reveal(owner, key, openKey?.() || undefined)
245
+ if (value == null) throw Object.assign(new Error('there is no such variable there'), { code: 'not-found' })
246
+ const record = await refreshActa()
247
+ const body = { op: 'var.reveal', owner, key, value, ek, ts: Date.now() }
248
+ const sealed = await seal({ ek, payload: { body, seal: await sealOrFail(body), acta: record } })
249
+ audit('admin.var.reveal', { by, ns, device: pub ? await deviceIdOf(pub).catch(() => null) : null, key, approved })
250
+ return { enc: sealed }
251
+ }
252
+
236
253
  async function awaitApproval ({ device, ns, kind, what, op = null, ctx = null, onAnswer, ttlMs = PENDING_TTL_MS }) {
237
254
  const deviceId = await deviceIdOf(device).catch(() => null)
238
255
  const record = await refreshActa()
@@ -2922,6 +2939,76 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2922
2939
  }))
2923
2940
  }
2924
2941
  },
2942
+ /**
2943
+ * VER UNA PRIVADA DESDE LA CONSOLA (dueño, 2026-10-26: «en el admin no tengo botón para ver
2944
+ * la variable; obviamente necesita aprobación si hay aprobadores»). Hasta aquí el valor de
2945
+ * una privada no salía de la máquina de la bóveda, ni hacia un aparato con `admin`.
2946
+ *
2947
+ * NADA VIAJA EN CLARO (dueño: «selladito, firmado y verificada fuente» y «NADA NUNCA EN
2948
+ * CLARO»). La petición de administración va firmada pero NO cifrada por el proxio, así que
2949
+ * aquí no puede ir ni el nombre de la variable. Dos pasos, como abrir a distancia:
2950
+ *
2951
+ * 1. `revealBegin` da una llave efímera de esta bóveda (una puerta, un minuto, un uso);
2952
+ * 2. `reveal` trae SELLADO a esa llave qué se quiere ver y la efímera de quien pregunta.
2953
+ * La respuesta va SELLADA a esa efímera, y dentro: el valor y lo pedido, FIRMADOS con
2954
+ * la llave de sellado de esta bóveda (la que nombra el acta), y el acta al lado para
2955
+ * que la consola compruebe de dónde viene antes de enseñarlo.
2956
+ *
2957
+ * Por el proxio solo pasan llaves públicas de un uso y el número del pedido.
2958
+ *
2959
+ * APROBACIÓN: si el acta tiene quien apruebe, se pide SIEMPRE, también a un aparato con
2960
+ * `unattended` (ver un valor es más que dejar que un servicio lo use). Sin aprobador no se
2961
+ * pide (la regla de siempre). UNA APROBACIÓN ES POR SOLICITUD: vale para ese valor y una
2962
+ * lectura; el sondeo solo trae el número del pedido, así que no se puede cambiar lo pedido.
2963
+ *
2964
+ * Abrir una privada exige la llave del perfil: la bóveda tiene que estar ABIERTA.
2965
+ */
2966
+ async revealBegin ({ caller }) {
2967
+ if (isLocked()) throw Object.assign(new Error('the vault is closed: open it to see a private variable'), { code: 'vault-locked' })
2968
+ const t = Date.now()
2969
+ for (const [n, v] of revealDoors) if (v.exp <= t) revealDoors.delete(n)
2970
+ const eph = await makeEphemeralKey()
2971
+ const door = [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, '0')).join('')
2972
+ revealDoors.set(door, { privateKey: eph.privateKey, caller, exp: t + 60_000 })
2973
+ return { door, ek: eph.ek }
2974
+ },
2975
+ async reveal ({ door, enc, request = null, caller, by }) {
2976
+ // SONDEO de un pedido ya hecho: solo el número; lo pedido quedó guardado al pedirlo.
2977
+ if (request) {
2978
+ const g = revealGrants.get(request)
2979
+ if (!g || g.caller !== caller || g.exp < Date.now()) throw Object.assign(new Error('that request does not exist or expired'), { code: 'no-request' })
2980
+ if (g.state === 'waiting') return { pending: request }
2981
+ revealGrants.delete(request)
2982
+ if (g.state !== 'approved') throw Object.assign(new Error('denied by the approver'), { code: 'denied' })
2983
+ return deliverReveal({ ...g, by, approved: true })
2984
+ }
2985
+ const d = revealDoors.get(door)
2986
+ revealDoors.delete(door)
2987
+ if (!d || d.exp <= Date.now() || d.caller !== caller) throw Object.assign(new Error('var.reveal: ask for a key first (var.reveal.begin), and use it within a minute'), { code: 'no-door' })
2988
+ let ask = null
2989
+ try { ask = await openSealed({ privateKey: d.privateKey, enc }) } catch (_) { ask = null }
2990
+ const toScope = typeof ask?.ns === 'string' && !!ask.ns
2991
+ const toDevice = typeof ask?.pub === 'string' && !!ask.pub
2992
+ if (!ask || toScope === toDevice || typeof ask.key !== 'string' || !ask.key || typeof ask.ek !== 'string' || !ask.ek) {
2993
+ throw Object.assign(new Error('var.reveal: the envelope does not check out'), { code: 'bad-request' })
2994
+ }
2995
+ if (isLocked()) throw Object.assign(new Error('the vault is closed: open it to see a private variable'), { code: 'vault-locked' })
2996
+ const owner = toScope ? `ns:${ask.ns}` : `dev:${ask.pub}`
2997
+ const record = await refreshActa()
2998
+ if (!record) throw Object.assign(new Error('no record: cannot decide who may see a private variable'), { code: 'no-record' })
2999
+ const target = { owner, ns: toScope ? ask.ns : null, pub: toDevice ? ask.pub : null, key: ask.key, ek: ask.ek, caller }
3000
+ if (!(record.members || []).some((m) => Acta.memberCan(record, m.pub, 'approve'))) return deliverReveal({ ...target, by, approved: false })
3001
+ let id = null
3002
+ const pend = await awaitApproval({
3003
+ device: caller, ns: target.ns || await deviceIdOf(target.pub).catch(() => null) || '?', kind: 'reveal', what: 'vars',
3004
+ // El nombre va en el contexto, que viaja SELLADO al que aprueba.
3005
+ ctx: { keys: [target.key], op: 'reveal' },
3006
+ onAnswer: async (ok) => { const g = revealGrants.get(id); if (g) g.state = ok ? 'approved' : 'denied' }
3007
+ })
3008
+ id = pend.id
3009
+ revealGrants.set(id, { ...target, state: 'waiting', exp: Date.now() + PENDING_TTL_MS })
3010
+ return { pending: id }
3011
+ },
2925
3012
  /**
2926
3013
  * PARA QUIÉN ENVOLVER. Lo contesta la bóveda porque la lista sale del ACTA
2927
3014
  * (`recipientsOf`), y tener dos sitios respondiendo a «quién puede abrir este cajón» es
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/vaultd",
3
- "version": "0.177.0",
3
+ "version": "0.179.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": {
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/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',