@dotrino/vaultd 0.189.1 → 0.191.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
@@ -50,6 +50,11 @@ export const ADMIN_OPS = Object.freeze([
50
50
  // Los BLOQUEADOS por un aprobador (`src/blocked.js`): verlos y desbloquearlos. Bloquear a
51
51
  // distancia también, por si el administrador llega antes que el teléfono. No toca el acta.
52
52
  'blocked', 'block', 'unblock',
53
+ // LAS CONCESIONES (un pedido aprobado deja pasar ese comando una hora que se renueva con
54
+ // cada uso): verlas y cortarlas. Las mismas que el aprobador ve en /approvals; aquí las ve
55
+ // quien administra, igual que la TUI del binario. Cortar no sella nada: la lista es de la
56
+ // bóveda, no del acta.
57
+ 'grants', 'grant-revoke',
53
58
  // Variables de entorno: verlas (nombres siempre; valor solo de las públicas) y
54
59
  // ponerles valor (de las dos). Borrar NO está, y es a propósito: un aparato robado
55
60
  // no debe poder dejar sin configuración a los servicios.
@@ -99,8 +104,8 @@ export const ADMIN_OPS = Object.freeze([
99
104
  */
100
105
  export const ADMIN_OPS_WHILE_LOCKED = Object.freeze([
101
106
  'audit', 'vars', 'var.set', 'var.setMany', 'var.recipients', 'var.reveal.begin', 'var.reveal',
102
- // Bloquear no sella nada: la lista es de la bóveda, no del acta.
103
- 'blocked', 'block', 'unblock',
107
+ // Bloquear no sella nada: la lista es de la bóveda, no del acta. Las concesiones, igual.
108
+ 'blocked', 'block', 'unblock', 'grants', 'grant-revoke',
104
109
  // Las dos de abrir, obviamente: son las únicas que solo tienen sentido con el candado
105
110
  // echado. Que estén aquí NO las deja pasar sin más — siguen exigiendo cert, acta, nonce
106
111
  // y frescura como todas, y además la contraseña dentro del sobre.
@@ -154,6 +159,9 @@ export function createAdminDesk ({
154
159
  unlockDesk = null,
155
160
  // La lista de bloqueados, inyectada como `vars`: `{ list(), set(pub, on, { by }) }`.
156
161
  blocked = null,
162
+ // Las CONCESIONES, inyectadas igual: `{ list(device), revoke(id, { by }) }`. `list` recibe
163
+ // a quien pregunta porque el comando de cada una va sellado a su llave de cifrado.
164
+ grants = null,
157
165
  now = () => Date.now()
158
166
  }) {
159
167
  const ops = new Set(ADMIN_OPS)
@@ -352,6 +360,13 @@ export function createAdminDesk ({
352
360
  // usarlo para quitar dejaba un miembro sin certificados al que la bóveda ya nunca le
353
361
  // mandaba el aviso de expulsión (mientras siga en el acta, un papel retirado
354
362
  // significa «renueva»). Ese era el dispositivo fantasma.
363
+ if (data.op === 'grants' || data.op === 'grant-revoke') {
364
+ if (!grants) return { ok: false, error: 'admin: this vault has no grants' }
365
+ if (data.op === 'grants') return { ok: true, result: await grants.list(chk.device) }
366
+ if (typeof data.id !== 'string' || !data.id) return { ok: false, error: 'admin: grant-revoke needs the grant id' }
367
+ const ok = await grants.revoke(data.id, { by })
368
+ return { ok: true, result: { id: data.id, ok } }
369
+ }
355
370
  if (data.op === 'blocked' || data.op === 'block' || data.op === 'unblock') {
356
371
  if (!blocked) return { ok: false, error: 'admin: this vault cannot block devices' }
357
372
  if (data.op === 'blocked') return { ok: true, result: { items: blocked.list() } }
@@ -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.117.0'
8
+ export const LIB_VERSION = '0.119.0'
@@ -22,7 +22,14 @@ export const NOTICE_TTL_MS = 24 * 60 * 60 * 1000
22
22
  * (`docs/pairing-protocol.md` §1.7). No pide nada: no hay a quién bloquear, porque ninguno
23
23
  * entró. Lo cuenta, con el ID y la máquina de los dos.
24
24
  */
25
- export const NOTICE_EVS = ['updated', 'update-needs-root', 'pairing-contested', 'log-anchor']
25
+ export const NOTICE_EVS = ['updated', 'update-needs-root', 'pairing-contested', 'log-anchor', 'delivered']
26
+ /**
27
+ * `delivered`: un aparato con `unattended` se llevó claves de un cajón (`kind: 'secrets'`) o
28
+ * una contraseña (`kind: 'passwords'`) sin que nadie aprobara, porque no le hacía falta (dueño,
29
+ * 2026-11-04: «equipos unattended no deben pedir aprobación, quizás sí notificar que han
30
+ * entregado contraseñas»). No pide nada: lo cuenta. Lleva `ns`, `deviceId` y `label`.
31
+ */
32
+ const DELIVERED_KINDS = ['secrets', 'passwords']
26
33
 
27
34
  const newId = () => [...crypto.getRandomValues(new Uint8Array(8))].map((b) => b.toString(16).padStart(2, '0')).join('')
28
35
 
@@ -58,8 +65,17 @@ export function openNotices ({ disk, now = Date.now }) {
58
65
  * administrador). `product`: qué (`@dotrino/vaultd` es la propia bóveda);
59
66
  * `deviceId`/`label`: el aparato, si fue uno.
60
67
  */
61
- add (ev, { version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null, devices = null, logSeq = null, head = null, tsa = null }) {
68
+ add (ev, { version, from = null, product = '@dotrino/vaultd', deviceId = null, label = null, devices = null, logSeq = null, head = null, tsa = null, ns = null, kind = null }) {
62
69
  if (!NOTICE_EVS.includes(ev)) throw fail('bad-notice', `unknown notice: ${ev}`)
70
+ if (ev === 'delivered') {
71
+ if (!DELIVERED_KINDS.includes(kind)) throw fail('bad-notice', `${ev}: kind must be one of ${DELIVERED_KINDS.join(', ')}`)
72
+ if (typeof ns !== 'string' || !ns) throw fail('bad-notice', `${ev}: the drawer (ns) is required`)
73
+ if (typeof deviceId !== 'string' || !deviceId) throw fail('bad-notice', `${ev}: the device is required`)
74
+ const n = { id: newId(), ev, kind, ns, deviceId, label: typeof label === 'string' ? label : '', ts: now() }
75
+ items = [...items.filter(alive), n]
76
+ save()
77
+ return n
78
+ }
63
79
  // EL ANCLA DE LA BITÁCORA (`logAnchor.js`): la cabeza sellada por el signer, para que el
64
80
  // aprobador la guarde. Solo se queda la última: la anterior ya no dice nada que esta no diga.
65
81
  if (ev === 'log-anchor') {
@@ -36,6 +36,7 @@ export const PASSWORDS_CAP = 'passwords'
36
36
  * `encPubOf(pubkey)` su llave de cifrado, para sellarle la respuesta
37
37
  * `needsApproval(pubkey)` (async) si ese aparato tiene que pedir aprobación (`unattended`)
38
38
  * `approve({ pubkey, op })` pide el visto bueno (el teléfono) y espera
39
+ * `onDelivered(pubkey)` se sirvió una lectura (`pm2.get`) a ese aparato
39
40
  * `audit(op, info)` la bitácora del vault
40
41
  */
41
42
  export function createPasswordDesk (opts = {}) {
@@ -48,6 +49,7 @@ export function createPasswordDesk (opts = {}) {
48
49
  encPubOf = () => null,
49
50
  needsApproval = () => true,
50
51
  approve = async () => false,
52
+ onDelivered = () => {},
51
53
  audit = () => {},
52
54
  log = () => {},
53
55
  } = opts
@@ -73,6 +75,8 @@ export function createPasswordDesk (opts = {}) {
73
75
  // La bitácora NO lleva qué credencial se pidió: eso es contenido del usuario.
74
76
  audit('passwords', { op: r.op, outcome: r.outcome, device: (r.from || '').slice(0, 24) })
75
77
  if (r.outcome !== 'ok') log(`[vault] passwords: ${r.op} ${r.outcome}`)
78
+ // Una LECTURA servida: quien llama decide si hay que contarla (`unattended`, ver vault.js).
79
+ else if (r.op === 'pm2.get' && r.from) onDelivered(r.from)
76
80
  },
77
81
  })
78
82
 
@@ -2036,6 +2036,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2036
2036
  }
2037
2037
  audit('secrets', { device: await deviceIdOf(chk.device), ns, ...(publicOnly ? { publicOnly: true } : {}) })
2038
2038
  reply(from, { type: MSG.SECRETS_RESULT, ...res })
2039
+ if (!publicOnly) announceDelivered({ device: chk.device, ns, kind: 'secrets' })
2039
2040
  }
2040
2041
 
2041
2042
  /** El bundle de `ns` para `devicePub`, sellado a su `ek` y firmado por la llave de sellado. */
@@ -2139,12 +2140,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2139
2140
  if (op === 'blocked') return answer({ op: 'blocked', items: blocked.list() })
2140
2141
  if (op === 'grant-revoke') {
2141
2142
  const gid = typeof p.data?.id === 'string' ? p.data.id : ''
2142
- const ok = gid ? grants.revoke(gid) : false
2143
- if (ok) {
2144
- audit('secrets.grant.revoked', { id: gid, by })
2145
- log(`[vault] grant ${gid} revoked by ${by} — that command will ring again`)
2146
- }
2147
- return answer({ op: 'grant-revoke.result', id: gid, ok })
2143
+ return answer({ op: 'grant-revoke.result', id: gid, ok: revokeGrantBy(gid, by) })
2148
2144
  }
2149
2145
  const id = typeof p.data?.id === 'string' ? p.data.id : ''
2150
2146
  const pend = approvals.take(id)
@@ -2249,6 +2245,52 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2249
2245
  * en vez de mandárselo en claro «para que al menos lo vea»: eso sería cambiar la promesa
2250
2246
  * por comodidad, y encima sin avisar a nadie.
2251
2247
  */
2248
+ /** Un objeto pequeño sellado a un `encPub` del acta: `{ wrap, envelope }`, lo abre `openSealed`. */
2249
+ async function sealTo (encPub, obj) {
2250
+ const cek = await makeContentKey()
2251
+ const envelope = await encryptWithCek({ cek, gen: 0, plaintext: JSON.stringify(obj) })
2252
+ const wrap = await wrapForMember({ cek, memberEncPub: encPub })
2253
+ return { wrap, envelope }
2254
+ }
2255
+
2256
+ /**
2257
+ * EL ASUNTO DEL TIMBRE, SELLADO AL TELÉFONO (dueño, 2026-11-04: «que las notificaciones a
2258
+ * móviles no sean del todo anónimas sino que al menos tengan asunto, para ver quién solicita
2259
+ * qué»). El timbre que sale por FCM/APNs lo leen Google y Apple, así que el proxio lo manda
2260
+ * vacío. Lo que va aquí viaja dentro del mensaje como `ring` y el proxio lo pega al timbre
2261
+ * TAL CUAL: va cifrado a la `encPub` del aprobador, y solo su teléfono lo abre, sin red.
2262
+ *
2263
+ * Es solo el asunto. Quien aprueba sigue decidiendo con la lista (`op: 'approvals'`), que
2264
+ * es la que va firmada: un asunto falso no aprueba nada.
2265
+ *
2266
+ * Sin `encPub` en el acta no hay asunto (y el teléfono enseña el genérico): mandarlo en claro
2267
+ * sería cambiar la promesa sin avisar.
2268
+ */
2269
+ const RING_CTX_KEYS = ['op', 'fields', 'product', 'version', 'from', 'reporterLabel', 'kind']
2270
+ async function ringFor (pub, record, hint) {
2271
+ const encPub = (record?.members || []).find((m) => m.pub === pub)?.encPub || null
2272
+ if (!encPub) return null
2273
+ let ctx = null
2274
+ if (hint.ctx && typeof hint.ctx === 'object') {
2275
+ ctx = {}
2276
+ for (const k of RING_CTX_KEYS) if (hint.ctx[k] != null) ctx[k] = hint.ctx[k]
2277
+ }
2278
+ try { return await sealTo(encPub, { ...hint, ctx }) } catch (e) {
2279
+ log(`[vault] could not seal the subject of the ring for ${pub.slice(0, 24)}…: ${e.message}`)
2280
+ return null
2281
+ }
2282
+ }
2283
+
2284
+ /** Corta una concesión (desde /approvals o desde la consola de administración). */
2285
+ function revokeGrantBy (gid, by) {
2286
+ const ok = gid ? grants.revoke(gid) : false
2287
+ if (ok) {
2288
+ audit('secrets.grant.revoked', { id: gid, by })
2289
+ log(`[vault] grant ${gid} revoked by ${by} — that command will ring again`)
2290
+ }
2291
+ return ok
2292
+ }
2293
+
2252
2294
  async function withSealedContext (items, approver, record) {
2253
2295
  const encPub = (record?.members || []).find((m) => m.pub === approver)?.encPub || null
2254
2296
  const output = []
@@ -2257,9 +2299,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2257
2299
  if (!ctx) { output.push({ ...rest, ctx: null }); continue }
2258
2300
  if (!encPub) { output.push({ ...rest, ctx: null, ctxSealed: false, ctxReason: 'no-enc-key' }); continue }
2259
2301
  try {
2260
- const cek = await makeContentKey()
2261
- const envelope = await encryptWithCek({ cek, gen: 0, plaintext: JSON.stringify(ctx) })
2262
- const wrap = await wrapForMember({ cek, memberEncPub: encPub })
2302
+ const { wrap, envelope } = await sealTo(encPub, ctx)
2263
2303
  output.push({ ...rest, ctx: null, ctxSealed: true, ctxWrap: wrap, ctxEnvelope: envelope })
2264
2304
  } catch (e) {
2265
2305
  // NO SE TRAGA: sin esto, un fallo al sellar se vería en el teléfono igual que un
@@ -2300,7 +2340,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2300
2340
  for (const pub of who) {
2301
2341
  // A la app que APRUEBA (`vault`): en un teléfono la llave es de todas sus apps, y sin
2302
2342
  // decirlo el pedido timbraba a messenger (websocket-proxy ≥ 1.4.0).
2303
- try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal }, { app: 'vault' }) }
2343
+ const ring = await ringFor(pub, record, { ...body, ctx: pend.ctx || null })
2344
+ try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal, ...(ring ? { ring } : {}) }, { app: 'vault' }) }
2304
2345
  catch (e) { log(`[vault] could not ring ${pub.slice(0, 24)}… about ${pend.ns}: ${e.message}`) }
2305
2346
  }
2306
2347
  log(`[vault] ${pend.ns}: rang ${who.length} approver(s) for ${pend.id}`)
@@ -2331,9 +2372,12 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2331
2372
  const { id, ev, ts, ...rest } = notice
2332
2373
  const body = { ev, id, ...rest, ts }
2333
2374
  const seal = await sealOrFail(body)
2375
+ // Lo que calla no timbra: no lleva asunto. Lo que suena, sí (ver `ringFor`).
2376
+ const record = quiet ? null : await refreshActa()
2334
2377
  let sent = 0
2335
2378
  for (const pub of who) {
2336
- try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal }, { app: 'vault', ...(quiet ? { quiet: true } : {}) }); sent++ }
2379
+ const ring = quiet ? null : await ringFor(pub, record, { ev, id, ts, kind: rest.kind || null, ns: rest.ns || null, deviceId: rest.deviceId || null, label: rest.label || null, product: rest.product || null, version: rest.version || null, from: rest.from || null })
2380
+ try { client.sendByPubkey(pub, { type: MSG.ADMIN_EVENT, body, seal, ...(ring ? { ring } : {}) }, { app: 'vault', ...(quiet ? { quiet: true } : {}) }); sent++ }
2337
2381
  catch (e) { log(`[vault] could not tell ${pub.slice(0, 24)}… about ${what}: ${e.message}`) }
2338
2382
  }
2339
2383
  return sent
@@ -2402,6 +2446,39 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2402
2446
  return { approvers: who.length, sent, notice }
2403
2447
  }
2404
2448
 
2449
+ /**
2450
+ * «SE LLEVÓ CLAVES SIN PEDIR», a quien aprueba (dueño, 2026-11-04). Un aparato con
2451
+ * `unattended` no pide aprobación —para eso se le dio—, pero que lo haga en silencio deja al
2452
+ * dueño sin saber qué máquina se llevó qué. Se cuenta como aviso (`delivered`), no como pedido.
2453
+ *
2454
+ * UNO POR APARATO, CAJÓN Y HORA: un servicio pide su cajón en cada arranque y el gestor una
2455
+ * contraseña en cada relleno; timbrar cada vez enseña a ignorar el timbre. Solo cuando de
2456
+ * verdad no se pidió por `unattended`: sin aprobadores no hay a quién contar, y lo aprobado
2457
+ * ya lo vio quien aprobó.
2458
+ */
2459
+ const DELIVERED_EVERY_MS = 60 * 60 * 1000
2460
+ const deliveredAt = new Map()
2461
+ async function announceDelivered ({ device, ns, kind }) {
2462
+ try {
2463
+ const record = await refreshActa()
2464
+ if (!record || !Acta.memberCan(record, device, 'unattended')) return
2465
+ const who = (record.members || []).filter((m) => Acta.memberCan(record, m.pub, 'approve')).map((m) => m.pub)
2466
+ if (!who.length) return
2467
+ const key = `${device}|${kind}|${ns}`
2468
+ const now = Date.now()
2469
+ if (now - (deliveredAt.get(key) || 0) < DELIVERED_EVERY_MS) return
2470
+ deliveredAt.set(key, now)
2471
+ for (const [k, t] of deliveredAt) if (now - t >= DELIVERED_EVERY_MS) deliveredAt.delete(k)
2472
+ const deviceId = await deviceIdOf(device).catch(() => null)
2473
+ if (!deviceId) return log(`[vault] delivered: could not name the device that took ${kind} of ${ns}, so nobody is told`)
2474
+ const label = (record.members || []).find((m) => m.pub === device)?.label || ''
2475
+ const notice = notices.add('delivered', { kind, ns, deviceId, label })
2476
+ const sent = await sendNotice(notice, who, `the delivery of ${kind} of ${ns} to ${deviceId}`)
2477
+ audit('delivered.announced', { device: deviceId, ns, kind, approvers: who.length, sent })
2478
+ log(`[vault] delivered: told ${sent} of ${who.length} approver(s) that ${deviceId} took ${kind} of ${ns} without approval (unattended)`)
2479
+ } catch (e) { log(`[vault] delivered: could not tell the approvers (${e.code || 'error'}: ${e.message})`) }
2480
+ }
2481
+
2405
2482
  /**
2406
2483
  * UN INCIDENTE: un agente de la cuenta dice que OTRO aparato de la cuenta se equivocó de
2407
2484
  * clave tres veces seguidas (la terminal, `dotrino-terminal lock`). No se decide aquí
@@ -2676,6 +2753,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2676
2753
  // el permiso se seguía sirviendo solo.
2677
2754
  needsApproval: passwordsNeedApproval,
2678
2755
  approve: approvePasswordRequest,
2756
+ onDelivered: (pub) => announceDelivered({ device: pub, ns: 'passwords', kind: 'passwords' }),
2679
2757
  audit,
2680
2758
  log,
2681
2759
  }).start()
@@ -3448,6 +3526,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
3448
3526
  deviceIdOf,
3449
3527
  audit,
3450
3528
  blocked: { list: () => blocked.list(), set: setBlocked },
3529
+ grants: {
3530
+ list: async (device) => {
3531
+ const record = (await identity.profileActa?.().catch(() => null))?.acta
3532
+ return { items: await withSealedContext(grants.list(), device, record), ttlMs: GRANT_TTL_MS }
3533
+ },
3534
+ revoke: async (id, { by }) => revokeGrantBy(id, by)
3535
+ },
3451
3536
  // Abrir a distancia. Va inyectado porque `admin.js` es puro y esto necesita cripto y
3452
3537
  // disco; `null` si este perfil no lo soporta, y entonces la operación contesta que no.
3453
3538
  unlockDesk,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/vaultd",
3
- "version": "0.189.1",
3
+ "version": "0.191.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": {