@dotrino/vaultd 0.164.1 → 0.165.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/src/daemon.js CHANGED
@@ -62,9 +62,9 @@ function assertSingleInstance (dir) {
62
62
  const { release } = takeLock(dir)
63
63
  // Se suelta al salir por las buenas. Si el proceso muere de golpe el candado se queda,
64
64
  // y por eso caduca por latido: uno inmortal sería peor que ninguno.
65
- const soltar = () => { try { release() } catch (_) {} }
66
- process.once('exit', soltar)
67
- for (const sig of ['SIGINT', 'SIGTERM']) process.once(sig, () => { soltar(); process.exit(0) })
65
+ const releaseLock = () => { try { release() } catch (_) {} }
66
+ process.once('exit', releaseLock)
67
+ for (const sig of ['SIGINT', 'SIGTERM']) process.once(sig, () => { releaseLock(); process.exit(0) })
68
68
  } catch (e) {
69
69
  if (e?.code !== 'vault-locked') throw e
70
70
  console.error('A vault is already running on this data.')
@@ -99,21 +99,21 @@ export async function runDaemon () {
99
99
  // Lo que deja quien instala una versión nueva, para que la nueva lo cuente al arrancar.
100
100
  const updatedFile = path.join(dir, 'updated.json')
101
101
  /** Los perfiles que están atendiendo ahora mismo, con su nombre para los mensajes. */
102
- const perfilesEnMarcha = () => [...mgr.running.entries()].map(([id, vault]) => ({ id, vault, name: mgr.profiles.get(id)?.name || id }))
102
+ const runningProfiles = () => [...mgr.running.entries()].map(([id, vault]) => ({ id, vault, name: mgr.profiles.get(id)?.name || id }))
103
103
  const daemonVersion = VERSION
104
104
  /** `{ version, checkedAt }` de la última consulta que salió bien, o null si aún ninguna. */
105
- let ultimaPublicada = null
105
+ let latestPublished = null
106
106
  /**
107
107
  * EL PEDIDO DE ACTUALIZACIÓN: `{ version, askedAt, result, approvers }`, o null. `result`
108
108
  * es `pending` mientras espera (un día) y `denied`/`expired` cuando no se aprobó — y
109
109
  * entonces no se vuelve a pedir por esa versión. Va en la foto para que `status` y la TUI
110
110
  * lo DIGAN: una bóveda que no se actualiza por esto se vería igual que una al día.
111
111
  */
112
- let pedidoSinRespuesta = null
112
+ let unansweredRequest = null
113
113
  // Los campos de la raíz (fingerprint/iss) son los del perfil ACTIVO: los leen el
114
114
  // instalador y la web, que son anteriores al multi-perfil. La lista completa va
115
115
  // en `profiles`.
116
- const ajusteActualizar = () => { try { return readSettings(dir).updateApproval } catch (_) { return null } }
116
+ const updateSetting = () => { try { return readSettings(dir).updateApproval } catch (_) { return null } }
117
117
  const writeState = () => {
118
118
  const cur = mgr.summary().find((p) => p.current) || {}
119
119
  ipcWrite(stateFile, {
@@ -125,11 +125,11 @@ export async function runDaemon () {
125
125
  // LO QUE HAY PUBLICADO, si se pudo mirar. Va en la foto para que `status` lo enseñe
126
126
  // sin salir a la red: una pantalla de estado tiene que contestar al instante y
127
127
  // también sin conexión.
128
- ...(ultimaPublicada ? { latest: ultimaPublicada } : {}),
129
- ...(pedidoSinRespuesta ? { updateAsk: pedidoSinRespuesta } : {}),
128
+ ...(latestPublished ? { latest: latestPublished } : {}),
129
+ ...(unansweredRequest ? { updateAsk: unansweredRequest } : {}),
130
130
  // Si para actualizarse pide permiso (`src/settings.js`). `null` = el ajuste no se
131
131
  // pudo leer, que `status` dice distinto de «no».
132
- updateApproval: ajusteActualizar(),
132
+ updateApproval: updateSetting(),
133
133
  current: mgr.currentId(), profiles: mgr.summary()
134
134
  })
135
135
  }
@@ -313,10 +313,10 @@ export async function runDaemon () {
313
313
  // Un perfil nace vacío y `adopt: true`, que es la marca que deja a `joinProfile`
314
314
  // cambiar su acta recién nacida por la que traiga la otra bóveda; sin ella, unirse
315
315
  // sería pisar una cuenta con datos y se rechaza, que es lo correcto por defecto.
316
- let nacido = null
316
+ let born = null
317
317
  try {
318
318
  const p = await mgr.add(join.name || 'cuenta de la otra bóveda', { adopt: true, kek: join.kek || null })
319
- nacido = p.id
319
+ born = p.id
320
320
  const id = mgr.get(p.id)?.identity
321
321
  if (!id) throw new Error('no identity for the new profile')
322
322
  const off = id.onVault?.((e) => {
@@ -347,7 +347,7 @@ export async function runDaemon () {
347
347
  console.error('[vault] could not join:', e.message)
348
348
  // El perfil nació para esto y está vacío: si el intento no llegó a término se va
349
349
  // con él. Si no, cada reintento dejaba una cuenta fantasma en el conmutador.
350
- if (nacido) { try { await mgr.remove(nacido) } catch (_) {} }
350
+ if (born) { try { await mgr.remove(born) } catch (_) {} }
351
351
  answer({ state: 'error', error: e.message })
352
352
  }
353
353
  }
@@ -393,14 +393,14 @@ export async function runDaemon () {
393
393
  * candado esconde nombres igual que con las variables—. Lo público sí: la bóveda ya se lo
394
394
  * da a cualquiera por el proxio (`profilePublic`), así que no revela nada.
395
395
  */
396
- function perfilParaMostrar (vault, { conPrivados }) {
396
+ function profileToShow (vault, { conPrivados: withPrivate }) {
397
397
  const v = vault.profileView()
398
- const lista = (s) => { if (typeof s !== 'string') return undefined; try { const a = JSON.parse(s); return Array.isArray(a) ? a : undefined } catch (_) { return undefined } }
398
+ const list = (s) => { if (typeof s !== 'string') return undefined; try { const a = JSON.parse(s); return Array.isArray(a) ? a : undefined } catch (_) { return undefined } }
399
399
  const { avatar, links, fields, ...rest } = v.public
400
- if (!Object.keys(v.public).length && !(conPrivados && v.private.length)) return null
400
+ if (!Object.keys(v.public).length && !(withPrivate && v.private.length)) return null
401
401
  return {
402
- ...rest, avatar: avatarInfo(avatar), links: lista(links), fields: lista(fields),
403
- ...(conPrivados ? { privateKeys: v.private } : {}), updatedAt: v.updatedAt
402
+ ...rest, avatar: avatarInfo(avatar), links: list(links), fields: list(fields),
403
+ ...(withPrivate ? { privateKeys: v.private } : {}), updatedAt: v.updatedAt
404
404
  }
405
405
  }
406
406
 
@@ -409,7 +409,7 @@ export async function runDaemon () {
409
409
  if (typeof avatar !== 'string' || !avatar) return null
410
410
  const m = /^data:([^;,]+)?(?:;base64)?,(.*)$/s.exec(avatar)
411
411
  if (!m) return { type: null, bytes: avatar.length }
412
- return { type: m[1] || 'desconocido', bytes: Math.floor(m[2].length * 3 / 4) }
412
+ return { type: m[1] || null, bytes: Math.floor(m[2].length * 3 / 4) }
413
413
  }
414
414
 
415
415
  /**
@@ -615,10 +615,10 @@ export async function runDaemon () {
615
615
  // máquina y acaba de teclear la principal; cuando se USA a distancia lo hace el
616
616
  // navegador, y por eso la bóveda publica estos mismos parámetros.
617
617
  const params = mgr.profiles.secondaryParams(id, { mint: true })
618
- const derivada = new Uint8Array(crypto.scryptSync(
618
+ const derived = new Uint8Array(crypto.scryptSync(
619
619
  String(req.password), Buffer.from(params.salt, 'base64'),
620
620
  params.len, { N: params.N, r: params.r, p: params.p }))
621
- try { mgr.profiles.setSecondary(id, derivada) } finally { wipe(derivada) }
621
+ try { mgr.profiles.setSecondary(id, derived) } finally { wipe(derived) }
622
622
  return { done: 'contraseña del admin guardada · solo sirve desde el admin, no aquí' }
623
623
  }
624
624
  case 'admin-password-rm': {
@@ -779,8 +779,8 @@ export async function runDaemon () {
779
779
  if (!r.migrated) console.log('[vault] nothing to migrate: %s', r.reason)
780
780
  else {
781
781
  console.log('[vault] secrets SEALED (v%d -> v5). Backup left at secrets.json.v%d.bak', r.from, r.from)
782
- for (const [owner, sin] of Object.entries(r.sinLlave || {})) {
783
- console.log('[vault] WARNING %s: %d member(s) without an encryption key will NOT read their variables', owner, sin.length)
782
+ for (const [owner, without] of Object.entries(r.sinLlave || {})) {
783
+ console.log('[vault] WARNING %s: %d member(s) without an encryption key will NOT read their variables', owner, without.length)
784
784
  }
785
785
  }
786
786
  } else if (sec.op === 'batch') {
@@ -932,7 +932,7 @@ export async function runDaemon () {
932
932
  rm(meReqFile)
933
933
  if (meReq) {
934
934
  let me = null
935
- try { me = perfilParaMostrar(t.vault, { conPrivados: false }) } catch (e) { console.error('[vault] could not dump the profile:', e.message) }
935
+ try { me = profileToShow(t.vault, { conPrivados: false }) } catch (e) { console.error('[vault] could not dump the profile:', e.message) }
936
936
  ipcWrite(meFile, { ...closed, req: meReq.id || null, me })
937
937
  }
938
938
  return
@@ -980,7 +980,7 @@ export async function runDaemon () {
980
980
  rm(meReqFile)
981
981
  try {
982
982
  const tm = resolveTarget(meReq) || { id: mgr.currentId(), vault: mgr.current() }
983
- const me = perfilParaMostrar(tm.vault, { conPrivados: true })
983
+ const me = profileToShow(tm.vault, { conPrivados: true })
984
984
  ipcWrite(meFile, { v: 1, at: Date.now(), req: meReq.id || null, profile: tm.id, me })
985
985
  } catch (e) { console.error('[vault] could not dump the profile:', e.message) }
986
986
  }
@@ -1079,11 +1079,11 @@ export async function runDaemon () {
1079
1079
  const raw = process.env.DOTRINO_JOIN_FILE
1080
1080
  ? (() => { try { return fs.readFileSync(process.env.DOTRINO_JOIN_FILE, 'utf8') } catch (e) { console.error('[vault] could not read DOTRINO_JOIN_FILE: %s', e.message); return '' } })()
1081
1081
  : (process.env.DOTRINO_JOIN || '')
1082
- const texto = String(raw).trim()
1083
- if (!texto) return
1082
+ const text = String(raw).trim()
1083
+ if (!text) return
1084
1084
 
1085
1085
  let qr = null
1086
- try { qr = parseInvite(texto) } catch (_) {}
1086
+ try { qr = parseInvite(text) } catch (_) {}
1087
1087
  // Lo mismo que `dotrino-vault join` (ver `ctl.js`): basta `sn` + la cita del proxio o
1088
1088
  // la llave. Exigir `iss` dejaba fuera a la invitación corta, que es la única que emite
1089
1089
  // `pair` hoy — así que este camino de despliegue no había forma de que funcionara.
@@ -1091,11 +1091,11 @@ export async function runDaemon () {
1091
1091
  console.error('[vault] the invitation in DOTRINO_JOIN is not valid; ignoring it')
1092
1092
  return
1093
1093
  }
1094
- const marca = path.join(dir, 'bootstrap.json')
1095
- const hecho = readJsonSafe(marca)
1096
- if (hecho?.sn === qr.sn) return // ya se usó: un reinicio no vuelve a pedir entrar
1094
+ const mark = path.join(dir, 'bootstrap.json')
1095
+ const done = readJsonSafe(mark)
1096
+ if (done?.sn === qr.sn) return // ya se usó: un reinicio no vuelve a pedir entrar
1097
1097
 
1098
- ipcWrite(marca, { at: Date.now(), sn: qr.sn, ...(qr.iss ? { iss: qr.iss } : {}) })
1098
+ ipcWrite(mark, { at: Date.now(), sn: qr.sn, ...(qr.iss ? { iss: qr.iss } : {}) })
1099
1099
  ipcWrite(path.join(dir, 'join-request.json'), {
1100
1100
  qr,
1101
1101
  label: 'bóveda',
@@ -1111,11 +1111,11 @@ export async function runDaemon () {
1111
1111
  // (somos un servicio de USUARIO y él corre como root), así que lo hacemos nosotros: si
1112
1112
  // el binario cambia en el disco, nos vamos y systemd nos levanta con el nuevo. Solo bajo
1113
1113
  // systemd; ver `src/selfupdate.js` para por qué eso no es negociable.
1114
- const vigia = watchBinary({
1114
+ const watchdog = watchBinary({
1115
1115
  log: console.log,
1116
1116
  exit: () => shutdown('new binary installed')
1117
1117
  })
1118
- if (vigia) console.log('[vault] watching for updates: a new binary restarts the service on its own')
1118
+ if (watchdog) console.log('[vault] watching for updates: a new binary restarts the service on its own')
1119
1119
 
1120
1120
  /**
1121
1121
  * ¿SALIÓ UNA VERSIÓN NUEVA? Una lectura al día, y nada más.
@@ -1134,19 +1134,19 @@ export async function runDaemon () {
1134
1134
  * 0.130.0 con la 0.131.0 publicada y el log no decía nada: no había forma de saber si
1135
1135
  * estaba al día o si no había podido preguntar.
1136
1136
  */
1137
- let ultimoFallo = null
1138
- const mirarRelease = async () => {
1137
+ let lastFailure = null
1138
+ const checkRelease = async () => {
1139
1139
  let r
1140
1140
  try { r = await latestRelease() } catch (e) { r = { ok: false, reason: e?.message || String(e) } }
1141
1141
  if (!r.ok) {
1142
- if (r.reason !== ultimoFallo) console.log(`[vault] could not check for a new version: ${r.reason} · trying again in an hour`)
1143
- ultimoFallo = r.reason
1142
+ if (r.reason !== lastFailure) console.log(`[vault] could not check for a new version: ${r.reason} · trying again in an hour`)
1143
+ lastFailure = r.reason
1144
1144
  // Un fallo al arrancar (la red todavía no está) no puede costar un día entero.
1145
- setTimeout(mirarRelease, 60 * 60_000).unref?.()
1145
+ setTimeout(checkRelease, 60 * 60_000).unref?.()
1146
1146
  return
1147
1147
  }
1148
- ultimoFallo = null
1149
- ultimaPublicada = { version: r.version, checkedAt: Date.now() }
1148
+ lastFailure = null
1149
+ latestPublished = { version: r.version, checkedAt: Date.now() }
1150
1150
  writeState()
1151
1151
  if (!isNewer(r.version, daemonVersion)) return
1152
1152
 
@@ -1169,8 +1169,8 @@ export async function runDaemon () {
1169
1169
  */
1170
1170
  // SI EL AJUSTE NO SE PUEDE LEER, NO SE ACTUALIZA: el valor por defecto es no preguntar,
1171
1171
  // así que suponerlo sería saltarse la aprobación que el dueño pidió.
1172
- let pedirPermiso
1173
- try { pedirPermiso = readSettings(dir).updateApproval } catch (e) {
1172
+ let askPermission
1173
+ try { askPermission = readSettings(dir).updateApproval } catch (e) {
1174
1174
  console.log(`[vault] version ${r.version} is out, but the settings could not be read (${e?.message || e}) · not updating`)
1175
1175
  return
1176
1176
  }
@@ -1180,15 +1180,15 @@ export async function runDaemon () {
1180
1180
  // Y si hay que pedir y no se puede saber a quién, tampoco se actualiza: una lista vacía
1181
1181
  // o a medias sería «nadie aprueba, adelante», el repliegue que abre la puerta justo
1182
1182
  // cuando algo se rompió.
1183
- const enMarcha = perfilesEnMarcha()
1184
- let quienAprueba = []
1185
- if (pedirPermiso) {
1186
- try { quienAprueba = await approversOfAll(enMarcha) } catch (e) {
1183
+ const inProgress = runningProfiles()
1184
+ let whoApproves = []
1185
+ if (askPermission) {
1186
+ try { whoApproves = await approversOfAll(inProgress) } catch (e) {
1187
1187
  console.log(`[vault] version ${r.version} is out, but the approvers could not be read (${e?.message || e}) · not updating`)
1188
1188
  return
1189
1189
  }
1190
1190
  }
1191
- const conAvisos = quienAprueba.filter((a) => a.notifiedAt).length
1191
+ const withNotices = whoApproves.filter((a) => a.notifiedAt).length
1192
1192
 
1193
1193
  // CÓMO SE INSTALÓ decide si puede instalar ella misma (update.js, `installKind`): la de
1194
1194
  // usuario de Linux, el instalador de Windows y la app de macOS, sí. Por npm, Docker o un
@@ -1196,7 +1196,7 @@ export async function runDaemon () {
1196
1196
  // falta root», y avisar eso al teléfono sería mentirle).
1197
1197
  const kind = installKind()
1198
1198
  if (kind === 'other') {
1199
- if (avisadoOtra !== r.version) { avisadoOtra = r.version; console.log(`[vault] version ${r.version} is out (this one is ${daemonVersion}) · update it the way you installed it (npm, Docker, git)`) }
1199
+ if (warnedOther !== r.version) { warnedOther = r.version; console.log(`[vault] version ${r.version} is out (this one is ${daemonVersion}) · update it the way you installed it (npm, Docker, git)`) }
1200
1200
  return
1201
1201
  }
1202
1202
  // INSTALADA COMO PAQUETE DEL SISTEMA (.deb o .rpm en /usr/bin, o una app en una carpeta
@@ -1207,76 +1207,76 @@ export async function runDaemon () {
1207
1207
  // requiere root por algún motivo, simplemente se notifica al aprobador que hay
1208
1208
  // actualización y necesita root»). El log no lo lee nadie; el teléfono sí. UNA vez por
1209
1209
  // versión, apuntado para que un reinicio no lo repita (`update-root-told.json`).
1210
- let dicho
1211
- try { dicho = readRootTold(dir) } catch (e) {
1210
+ let said
1211
+ try { said = readRootTold(dir) } catch (e) {
1212
1212
  console.log(`[vault] update: whether the approvers were already told could not be read (${e?.message || e}) · not telling them again`)
1213
1213
  return
1214
1214
  }
1215
- if (shouldTellRoot(dicho, r.version, isNewer) && avisandoRoot !== r.version) {
1216
- avisandoRoot = r.version
1217
- contarATodos({ ev: 'update-needs-root', version: r.version, from: daemonVersion }, ({ todos, alguno }) => {
1218
- avisandoRoot = null
1215
+ if (shouldTellRoot(said, r.version, isNewer) && warningRoot !== r.version) {
1216
+ warningRoot = r.version
1217
+ tellEveryone({ ev: 'update-needs-root', version: r.version, from: daemonVersion }, ({ todos: all, alguno: anyOne }) => {
1218
+ warningRoot = null
1219
1219
  // Con que salió en algún perfil ya está dicho: repetirlo mañana a los que sí lo
1220
1220
  // oyeron por uno que no pudo sería timbrar de más.
1221
- if (todos || alguno) { try { writeRootTold(dir, { version: r.version, at: Date.now() }) } catch (e) { console.log(`[vault] update: could not note that the approvers were told: ${e.message}`) } }
1221
+ if (all || anyOne) { try { writeRootTold(dir, { version: r.version, at: Date.now() }) } catch (e) { console.log(`[vault] update: could not note that the approvers were told: ${e.message}`) } }
1222
1222
  else console.log(`[vault] update: the approvers could not be told that ${r.version} needs administrator rights · it will try again on the next check`)
1223
1223
  })
1224
1224
  }
1225
1225
  return
1226
1226
  }
1227
- if (actualizando) return
1228
- actualizando = true
1227
+ if (updating) return
1228
+ updating = true
1229
1229
  try {
1230
1230
  // (`aprobada`: ya dijeron que sí a esta versión y la instalación falló; no se vuelve a
1231
1231
  // preguntar por lo que ya se aprobó, se reintenta instalar.)
1232
- if (quienAprueba.length && aprobada !== r.version) {
1232
+ if (whoApproves.length && approved !== r.version) {
1233
1233
  // UNA VEZ POR VERSIÓN (dueño, 2026-10-08): el pedido dura un día y no se repite. Si
1234
1234
  // se denegó o venció, esa versión queda sin aprobar y se vuelve a preguntar solo
1235
1235
  // cuando salga una MÁS NUEVA. Lo preguntado se apunta al pedir y sobrevive a un
1236
1236
  // reinicio (`update-asked.json`); si no se puede leer, no se actualiza y se dice.
1237
- let preguntado
1238
- try { preguntado = readAsked(dir) } catch (e) {
1237
+ let asked
1238
+ try { asked = readAsked(dir) } catch (e) {
1239
1239
  console.log(`[vault] version ${r.version} is out, but what was already asked could not be read (${e?.message || e}) · not updating`)
1240
1240
  return
1241
1241
  }
1242
- const quienes = quienAprueba.map((a) => ({ profile: a.profile, id: a.id, label: a.label, notifiedAt: a.notifiedAt }))
1243
- if (!shouldAsk(preguntado, r.version, isNewer)) {
1242
+ const whom = whoApproves.map((a) => ({ profile: a.profile, id: a.id, label: a.label, notifiedAt: a.notifiedAt }))
1243
+ if (!shouldAsk(asked, r.version, isNewer)) {
1244
1244
  // Un «pendiente» que no es de este proceso es de antes de un reinicio: el pedido
1245
1245
  // murió con él, y nadie puede contestarlo ya.
1246
- if (preguntado.result === 'pending') { preguntado = { ...preguntado, result: 'expired' }; writeAsked(dir, preguntado) }
1247
- const nuevo = pedidoSinRespuesta?.version !== preguntado.version || pedidoSinRespuesta?.result !== preguntado.result
1248
- pedidoSinRespuesta = { ...preguntado, approvers: quienes }
1246
+ if (asked.result === 'pending') { asked = { ...asked, result: 'expired' }; writeAsked(dir, asked) }
1247
+ const newer = unansweredRequest?.version !== asked.version || unansweredRequest?.result !== asked.result
1248
+ unansweredRequest = { ...asked, approvers: whom }
1249
1249
  writeState()
1250
- if (nuevo) console.log(`[vault] version ${r.version} is out (this one is ${daemonVersion}) · approval for ${preguntado.version} was asked on ${new Date(preguntado.askedAt).toISOString()} and not given (${preguntado.result}) · not asking again until a newer version · install it with: dotrino-vault update`)
1250
+ if (newer) console.log(`[vault] version ${r.version} is out (this one is ${daemonVersion}) · approval for ${asked.version} was asked on ${new Date(asked.askedAt).toISOString()} and not given (${asked.result}) · not asking again until a newer version · install it with: dotrino-vault update`)
1251
1251
  return
1252
1252
  }
1253
1253
  const askedAt = Date.now()
1254
1254
  writeAsked(dir, { version: r.version, askedAt, result: 'pending' })
1255
- pedidoSinRespuesta = { version: r.version, askedAt, result: 'pending', approvers: quienes }
1255
+ unansweredRequest = { version: r.version, askedAt, result: 'pending', approvers: whom }
1256
1256
  writeState()
1257
- console.log(`[vault] version ${r.version} is out (this one is ${daemonVersion}) · asking ${quienAprueba.length} approver(s) across ${new Set(quienAprueba.map((a) => a.profileId)).size} profile(s), once · ${conAvisos} of them said notifications reach it`)
1257
+ console.log(`[vault] version ${r.version} is out (this one is ${daemonVersion}) · asking ${whoApproves.length} approver(s) across ${new Set(whoApproves.map((a) => a.profileId)).size} profile(s), once · ${withNotices} of them said notifications reach it`)
1258
1258
  // Un pedido por perfil que tenga quien apruebe, a la vez. El primer sí basta, y los
1259
1259
  // que queden vivos en los demás se retiran (`src/updateApproval.js`).
1260
- const conAprobador = new Set(quienAprueba.map((a) => a.profileId))
1261
- const si = await firstYes(enMarcha.filter((p) => conAprobador.has(p.id)).map((p) => p.vault.askUpdateApproval({ version: r.version })))
1260
+ const withApprover = new Set(whoApproves.map((a) => a.profileId))
1261
+ const si = await firstYes(inProgress.filter((p) => withApprover.has(p.id)).map((p) => p.vault.askUpdateApproval({ version: r.version })))
1262
1262
  if (!si) {
1263
1263
  const result = resultOfNo(askedAt, UPDATE_TTL_MS)
1264
1264
  writeAsked(dir, { version: r.version, askedAt, result })
1265
- pedidoSinRespuesta = { version: r.version, askedAt, result, approvers: quienes }
1265
+ unansweredRequest = { version: r.version, askedAt, result, approvers: whom }
1266
1266
  writeState()
1267
1267
  console.log(`[vault] update to ${r.version}: not approved (${result}) · it will not ask again for this version · install it with: dotrino-vault update`)
1268
1268
  return
1269
1269
  }
1270
- aprobada = r.version
1271
- } else if (quienAprueba.length) {
1270
+ approved = r.version
1271
+ } else if (whoApproves.length) {
1272
1272
  console.log(`[vault] version ${r.version} is out (this one is ${daemonVersion}) · already approved: installing`)
1273
- } else if (pedirPermiso) {
1273
+ } else if (askPermission) {
1274
1274
  console.log(`[vault] version ${r.version} is out (this one is ${daemonVersion}) · approval is on but no profile has an approver: updating on its own`)
1275
1275
  } else {
1276
1276
  console.log(`[vault] version ${r.version} is out (this one is ${daemonVersion}) · updating on its own`)
1277
1277
  }
1278
1278
  clearAsked(dir)
1279
- if (pedidoSinRespuesta) { pedidoSinRespuesta = null; writeState() }
1279
+ if (unansweredRequest) { unansweredRequest = null; writeState() }
1280
1280
  const res = await installRelease(r, { log: (m) => console.log(m), kind, pid: process.pid })
1281
1281
  if (!res.ok) {
1282
1282
  // Lo que NO cuadra no se instala, y se dice por qué: el archivo queda a mano.
@@ -1299,7 +1299,7 @@ export async function runDaemon () {
1299
1299
  if (res.then === 'exit') {
1300
1300
  console.log(`[vault] update: ${r.version} installed · leaving so the new one starts`)
1301
1301
  shutdown(`updated to ${r.version}`)
1302
- } else if (vigia) {
1302
+ } else if (watchdog) {
1303
1303
  console.log(`[vault] update: ${r.version} installed · restarting now to run it`)
1304
1304
  shutdown(`updated to ${r.version}`)
1305
1305
  } else {
@@ -1307,12 +1307,12 @@ export async function runDaemon () {
1307
1307
  }
1308
1308
  } catch (e) {
1309
1309
  console.log(`[vault] update to ${r.version} failed: ${e.message}`)
1310
- } finally { actualizando = false }
1310
+ } finally { updating = false }
1311
1311
  }
1312
- let actualizando = false
1313
- let avisadoOtra = null
1314
- let aprobada = null
1315
- let avisandoRoot = null
1312
+ let updating = false
1313
+ let warnedOther = null
1314
+ let approved = null
1315
+ let warningRoot = null
1316
1316
 
1317
1317
  /**
1318
1318
  * «ME ACTUALICÉ»: se lo cuenta a quien aprueba la versión NUEVA, ya corriendo (dueño,
@@ -1323,7 +1323,7 @@ export async function runDaemon () {
1323
1323
  * No se borra lo que no se pudo leer ni lo que no salió: se dice y se reintenta. Un
1324
1324
  * marcador de una versión ya superada sí se quita: esa noticia caducó.
1325
1325
  */
1326
- const anunciarActualizacion = () => {
1326
+ const announceUpdate = () => {
1327
1327
  if (!fs.existsSync(updatedFile)) return
1328
1328
  const m = ipcRead(updatedFile, null)
1329
1329
  if (!m || typeof m.to !== 'string') { console.log('[vault] update: updated.json exists but cannot be read · the approvers were not told'); return }
@@ -1331,8 +1331,8 @@ export async function runDaemon () {
1331
1331
  if (isNewer(daemonVersion, m.to)) rm(updatedFile)
1332
1332
  return // todavía no corre esa versión: se anuncia cuando arranque
1333
1333
  }
1334
- contarATodos({ version: m.to, from: typeof m.from === 'string' ? m.from : null }, ({ todos }) => {
1335
- if (todos) rm(updatedFile)
1334
+ tellEveryone({ version: m.to, from: typeof m.from === 'string' ? m.from : null }, ({ todos: all }) => {
1335
+ if (all) rm(updatedFile)
1336
1336
  else console.log('[vault] update: some approvers were not told · it will try again on the next start')
1337
1337
  })
1338
1338
  }
@@ -1342,30 +1342,30 @@ export async function runDaemon () {
1342
1342
  * en cuanto está identificado en el proxio: reintenta cada pocos segundos hasta que salió
1343
1343
  * en todos o se agotan los intentos. `alTerminar({ todos, alguno })`.
1344
1344
  */
1345
- function contarATodos (aviso, alTerminar) {
1346
- const hechos = new Set()
1347
- let intentos = 0
1348
- const intento = async () => {
1349
- intentos++
1350
- let falta = false
1351
- for (const p of perfilesEnMarcha()) {
1352
- if (hechos.has(p.id)) continue
1353
- if (!p.vault.isIdentified?.()) { falta = true; continue }
1354
- try { await p.vault.announceUpdate(aviso); hechos.add(p.id) } catch (e) {
1355
- falta = true
1356
- if (intentos === 1 || intentos === ANNOUNCE_TRIES) console.log(`[vault] update: profile ${p.name} could not tell its approvers yet: ${e?.message || e}`)
1345
+ function tellEveryone (notice, onFinish) {
1346
+ const completed = new Set()
1347
+ let attempts = 0
1348
+ const attempt = async () => {
1349
+ attempts++
1350
+ let missing = false
1351
+ for (const p of runningProfiles()) {
1352
+ if (completed.has(p.id)) continue
1353
+ if (!p.vault.isIdentified?.()) { missing = true; continue }
1354
+ try { await p.vault.announceUpdate(notice); completed.add(p.id) } catch (e) {
1355
+ missing = true
1356
+ if (attempts === 1 || attempts === ANNOUNCE_TRIES) console.log(`[vault] update: profile ${p.name} could not tell its approvers yet: ${e?.message || e}`)
1357
1357
  }
1358
1358
  }
1359
- if (!falta) return alTerminar({ todos: true, alguno: hechos.size > 0 })
1360
- if (intentos >= ANNOUNCE_TRIES) return alTerminar({ todos: false, alguno: hechos.size > 0 })
1361
- setTimeout(intento, ANNOUNCE_EVERY_MS).unref?.()
1359
+ if (!missing) return onFinish({ todos: true, alguno: completed.size > 0 })
1360
+ if (attempts >= ANNOUNCE_TRIES) return onFinish({ todos: false, alguno: completed.size > 0 })
1361
+ setTimeout(attempt, ANNOUNCE_EVERY_MS).unref?.()
1362
1362
  }
1363
- setTimeout(intento, ANNOUNCE_EVERY_MS).unref?.()
1363
+ setTimeout(attempt, ANNOUNCE_EVERY_MS).unref?.()
1364
1364
  }
1365
- anunciarActualizacion()
1366
- mirarRelease()
1367
- const relojRelease = setInterval(mirarRelease, CHECK_EVERY_MS)
1368
- relojRelease.unref?.()
1365
+ announceUpdate()
1366
+ checkRelease()
1367
+ const releaseClock = setInterval(checkRelease, CHECK_EVERY_MS)
1368
+ releaseClock.unref?.()
1369
1369
 
1370
1370
  console.log('[vault] servicio listo.')
1371
1371
  return mgr
package/src/keyowner.js CHANGED
@@ -59,9 +59,9 @@ export function keyOwnerOf (dir) {
59
59
  */
60
60
  export function assertKeyOwnsDir (dir, pub) {
61
61
  if (!pub) return null // sin llave todavía: no hay nada que comparar
62
- const previo = keyOwnerOf(dir)
62
+ const prior = keyOwnerOf(dir)
63
63
 
64
- if (previo && previo !== pub) {
64
+ if (prior && prior !== pub) {
65
65
  const e = new Error(
66
66
  'this data directory belongs to a DIFFERENT identity. Two vaults must never share one: ' +
67
67
  'each process needs its own directory, or one ends up running with the other\'s master key. ' +
@@ -71,7 +71,7 @@ export function assertKeyOwnsDir (dir, pub) {
71
71
  throw e
72
72
  }
73
73
 
74
- if (!previo) {
74
+ if (!prior) {
75
75
  try {
76
76
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
77
77
  fs.writeFileSync(path.join(dir, OWNER_FILE), JSON.stringify({ pub, at: Date.now() }, null, 2) + '\n', { mode: 0o600 })
package/src/manager.js CHANGED
@@ -102,8 +102,8 @@ export async function startVaultManager ({ root = dataDir(), proxyUrl, log = con
102
102
  // perfiles: se le pasan las tres cosas que necesita y nada más — con qué números
103
103
  // deriva el admin, cómo se abre con la derivada, y si hay contraseña de admin puesta.
104
104
  secondaryParams: () => profiles.secondaryParams(id),
105
- openWithSecondary: async (derivada) => {
106
- const r = await profiles.openWithSecondary(id, derivada)
105
+ openWithSecondary: async (derived) => {
106
+ const r = await profiles.openWithSecondary(id, derived)
107
107
  // Igual que `unlock`: abrir el perfil no basta, hay que traer la maestra a memoria.
108
108
  // Sin esto el candado diría «abierto» y todo lo que la necesita fallaría en otro
109
109
  // sitio y por otro motivo, que es el fallo que ya se pagó una vez.
@@ -215,14 +215,14 @@ export async function startVaultManager ({ root = dataDir(), proxyUrl, log = con
215
215
  let door
216
216
  try { door = profiles.addDoor(id, { prepared }) } catch (e) { if (fresh) profiles.dropFreshKey(id); throw e }
217
217
  if (fresh) {
218
- const maquina = new Uint8Array(kekFor(profiles.dirOf(id)))
218
+ const machine = new Uint8Array(kekFor(profiles.dirOf(id)))
219
219
  try {
220
- const r = await v.rekeySecrets?.(maquina, K)
220
+ const r = await v.rekeySecrets?.(machine, K)
221
221
  if (r?.rekeyed) log('[vault] secrets recovery copy moved from the machine key to the profile key')
222
222
  } catch (e) {
223
223
  // No se arrastra: abrir el perfil vuelve a intentarlo (`migrarRecuperacionALaFrase`).
224
224
  log('[vault] could not move the recovery copy to the profile key (it will be retried on unlock): %s', e.message)
225
- } finally { maquina.fill(0) }
225
+ } finally { machine.fill(0) }
226
226
  }
227
227
  return door
228
228
  }
package/src/platform.js CHANGED
@@ -35,31 +35,31 @@ import { VERSION } from './version.js'
35
35
  * usuario. No se alcanza desde otra máquina ni desde otro usuario, así que la promesa
36
36
  * del `docker-compose` —«la bóveda no escucha nada»— sigue siendo cierta donde importa.
37
37
  */
38
- function openLocalDesk ({ name, onMessage, channels: canales, maxBytes: MAX_REPLY_BYTES, log }) {
38
+ function openLocalDesk ({ name, onMessage, channels: channels, maxBytes: MAX_REPLY_BYTES, log }) {
39
39
  const socketPath = localSocketPath(name)
40
40
  let n = 0
41
41
  const server = net.createServer((sock) => {
42
42
  const id = 'local:' + (++n)
43
43
  let buf = ''
44
- const enviar = (obj) => { try { sock.write(JSON.stringify(obj) + '\n') } catch (_) {} }
45
- canales.set(id, enviar)
44
+ const send = (obj) => { try { sock.write(JSON.stringify(obj) + '\n') } catch (_) {} }
45
+ channels.set(id, send)
46
46
  sock.on('data', (chunk) => {
47
47
  buf += chunk
48
48
  // UN TOPE, y por lo mismo que en las respuestas: sin él, quien se conecte puede
49
49
  // hacer crecer este buffer hasta tumbar la bóveda mandando y sin saltos de línea.
50
- if (buf.length > MAX_REPLY_BYTES) { buf = ''; enviar({ type: MSG.ERROR, error: 'request too big' }); return }
50
+ if (buf.length > MAX_REPLY_BYTES) { buf = ''; send({ type: MSG.ERROR, error: 'request too big' }); return }
51
51
  let i
52
52
  while ((i = buf.indexOf('\n')) >= 0) {
53
- const linea = buf.slice(0, i); buf = buf.slice(i + 1)
54
- if (!linea.trim()) continue
53
+ const line = buf.slice(0, i); buf = buf.slice(i + 1)
54
+ if (!line.trim()) continue
55
55
  let p = null
56
- try { p = JSON.parse(linea) } catch (_) { enviar({ type: MSG.ERROR, error: 'malformed request' }); continue }
57
- onMessage(id, p).catch((e) => enviar({ type: MSG.ERROR, error: e.message }))
56
+ try { p = JSON.parse(line) } catch (_) { send({ type: MSG.ERROR, error: 'malformed request' }); continue }
57
+ onMessage(id, p).catch((e) => send({ type: MSG.ERROR, error: e.message }))
58
58
  }
59
59
  })
60
- const cerrar = () => canales.delete(id)
61
- sock.on('close', cerrar)
62
- sock.on('error', cerrar)
60
+ const close = () => channels.delete(id)
61
+ sock.on('close', close)
62
+ sock.on('error', close)
63
63
  })
64
64
  server.on('error', (e) => log('[vault] the local desk could not open (' + e.message + '): services will use the proxy'))
65
65
  // EL DIRECTORIO ES EL CONTROL, no el modo del socket.
@@ -77,10 +77,10 @@ function openLocalDesk ({ name, onMessage, channels: canales, maxBytes: MAX_REPL
77
77
  try { fs.mkdirSync(dir, { recursive: true, mode: 0o700 }) } catch (_) {}
78
78
  try {
79
79
  const st = fs.statSync(dir)
80
- const ajeno = typeof process.getuid === 'function' && st.uid !== process.getuid()
81
- const abierto = (st.mode & 0o077) !== 0
82
- if (ajeno || abierto) {
83
- return log(`[vault] the local desk stays closed: ${dir} is ${ajeno ? 'owned by another user' : 'writable by others'} ` +
80
+ const foreign = typeof process.getuid === 'function' && st.uid !== process.getuid()
81
+ const isOpen = (st.mode & 0o077) !== 0
82
+ if (foreign || isOpen) {
83
+ return log(`[vault] the local desk stays closed: ${dir} is ${foreign ? 'owned by another user' : 'writable by others'} ` +
84
84
  '— services on this machine will use the proxy instead')
85
85
  }
86
86
  } catch (e) {
@@ -116,7 +116,7 @@ export function nodePlatform (dir) {
116
116
  // antes de reemplazar); el resto lo hace su propio almacén al abrirse.
117
117
  try {
118
118
  const r = migrateFile(path.join(dir, 'identity.json'), kekFor(dir))
119
- if (r === 'migrado') log('[vault] identity encrypted at rest (bound to this machine)')
119
+ if (r === 'migrated') log('[vault] identity encrypted at rest (bound to this machine)')
120
120
  } catch (e) { log('[vault] could not encrypt the identity at rest:', e.message) }
121
121
  /**
122
122
  * EL CANDADO DE LA MAESTRA. La mitad privada se guarda sellada con la llave que sale de
@@ -125,7 +125,7 @@ export function nodePlatform (dir) {
125
125
  * `openKey`: se queda bajo la llave de máquina, y la consola lo dice en voz alta.
126
126
  */
127
127
  const keyLock = {
128
- seal: async (texto) => { const k = openKey?.(); return k ? encryptText(texto, k) : null },
128
+ seal: async (text) => { const k = openKey?.(); return k ? encryptText(text, k) : null },
129
129
  open: async (blob) => { const k = openKey?.(); if (!k) return null; try { return decryptText(blob, k) } catch (_) { return null } }
130
130
  }
131
131
  const identity = await Identity.connect({ dir, atRest: atRestFor(dir), keyLock })