@dotrino/vaultd 0.184.0 → 0.186.2

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.
@@ -61,8 +61,9 @@ export function claimOf (MSG, p) {
61
61
  return { pub: p.cert?.sub, data: p.data, signature: p.signature }
62
62
  case MSG.REPLICA_ACK:
63
63
  return { pub: p.body?.publickey, data: p.body, signature: p.signature }
64
- // Los cajones de una hermana: los firma su llave de comunicación (`body.by`), que es miembro.
65
- case MSG.SIBLING_DRAWERS:
64
+ // Los cajones de una hermana, y el respaldo de las apps: los firma su llave de comunicación
65
+ // (`body.by`), que es miembro.
66
+ case MSG.SIBLING_DRAWERS: case MSG.SIBLING_BACKUP:
66
67
  return { pub: p.body?.by, data: p.body, signature: p.signature }
67
68
  // La renuncia la firma el propio miembro dentro del registro; la comprueba el manejador.
68
69
  case MSG.RENOUNCE: {
@@ -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.111.0'
8
+ export const LIB_VERSION = '0.113.0'
@@ -0,0 +1,51 @@
1
+ /**
2
+ * LOS MIEMBROS DEL ACTA, EN TRES GRUPOS (dueño, 2026-10-26: «me confunde, no sé qué es
3
+ * dispositivo, qué es servicio, qué es bóveda, qué es llave de comunicación»). Una lista plana
4
+ * mezclaba cuatro cosas que no se administran igual:
5
+ *
6
+ * · BÓVEDAS: las que sellan el acta. Debajo de cada una, su llave de comunicación, que es parte
7
+ * de ella (habla por la red con el candado echado) y no un aparato.
8
+ * · APARATOS: teléfonos, navegadores, terminales, agentes.
9
+ * · SERVICIOS: los que solo leen su cajón de secretos (`cn` = su espacio).
10
+ *
11
+ * Una sola regla para la TUI y la consola (dueño, 2026-10-27: el administrador «organizado como
12
+ * está la TUI»): dos copias de esto acaban enseñando cosas distintas.
13
+ *
14
+ * Sin dependencias y sin red. Cada miembro trae `isMaster` (sella), `cn`, `vault` (en una llave
15
+ * de comunicación, la llave de su bóveda) e `isMe`; `keyOf` dice cuál es su llave (`sub` en la
16
+ * TUI, `pub` en la consola).
17
+ *
18
+ * @returns {{ group: 'vaults'|'devices'|'services', items: object[] }[]} solo los grupos con
19
+ * algo; en `vaults`, las llaves de comunicación van detrás de su bóveda con `child: true`.
20
+ */
21
+ export const isCommKey = (m) => m?.cn === 'vault'
22
+
23
+ export function groupMembers (members, { keyOf = (m) => m.pub } = {}) {
24
+ const list = members || []
25
+ const vaults = list.filter((m) => m.isMaster && !isCommKey(m))
26
+ const comms = list.filter(isCommKey)
27
+ const services = list.filter((m) => m.cn && !isCommKey(m) && !m.isMaster)
28
+ const devices = list.filter((m) => !m.isMaster && !m.cn)
29
+ // La de esta máquina primero: es la que se está administrando.
30
+ vaults.sort((a, b) => (b.isMe ? 1 : 0) - (a.isMe ? 1 : 0))
31
+ const placed = new Set()
32
+ const vaultBlock = []
33
+ for (const v of vaults) {
34
+ vaultBlock.push(v)
35
+ for (const c of comms) if (c.vault === keyOf(v)) { vaultBlock.push({ ...c, child: true }); placed.add(keyOf(c)) }
36
+ }
37
+ // Una llave de comunicación de antes de que el acta dijera de qué bóveda es: va con la bóveda
38
+ // de aquí, que es quien la acuñaba entonces.
39
+ const orphans = comms.filter((c) => !placed.has(keyOf(c))).map((c) => ({ ...c, child: true }))
40
+ const meAt = vaultBlock.findIndex((m) => m.isMe)
41
+ if (meAt >= 0) {
42
+ let at = meAt + 1
43
+ while (vaultBlock[at]?.child) at++
44
+ vaultBlock.splice(at, 0, ...orphans)
45
+ } else vaultBlock.push(...orphans)
46
+ return [
47
+ { group: 'vaults', items: vaultBlock },
48
+ { group: 'devices', items: devices },
49
+ { group: 'services', items: services }
50
+ ].filter((g) => g.items.length)
51
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * EL RESPALDO DE LAS APPS SE COPIA ENTRE LAS BÓVEDAS DE LA CUENTA, solo (dueño, 2026-10-28:
3
+ * «las bóvedas siempre se sincronizan automáticamente»). Antes cada navegador respaldaba en la
4
+ * bóveda que le dio su papel y nada más: si el disco del PC se perdía, se perdía el respaldo.
5
+ *
6
+ * Mismo camino que los cajones: mensajes sellados a la hermana y CALLADOS, que no despiertan a
7
+ * la Nube (cada despertar cuesta). Los recibe cuando despierta, y al arrancar anuncia lo suyo.
8
+ *
9
+ * Por partes, porque son hasta 25 MB y el proxio corta en 1 MB. Cuatro mensajes:
10
+ *
11
+ * state huella por hilo y suelos → la otra, si difiere, manda su índice
12
+ * index ids y ts de los hilos que difieren → la otra manda lo que le falta a esta y pide lo suyo
13
+ * want ids que me faltan → la otra los manda
14
+ * entries entradas, lápidas, dueños y suelos → se mezclan con las reglas de @dotrino/store/core
15
+ *
16
+ * Termina solo: cuando las huellas coinciden nadie manda nada. Y el tope es determinista, así
17
+ * que dos bóvedas con lo mismo borran lo mismo y no se persiguen la cola.
18
+ */
19
+ import * as core from '@dotrino/store/core'
20
+
21
+ const ANNOUNCE_DEBOUNCE_MS = 2 * 60_000
22
+
23
+ /** Qué mandar y qué pedir de un hilo, comparando mi índice con el de la otra. */
24
+ export function planSibling (mine, theirs) {
25
+ const M = new Map((mine?.items || []).map(([id, ts]) => [String(id), ts]))
26
+ const T = new Map((theirs?.items || []).map(([id, ts]) => [String(id), ts]))
27
+ const send = []; const want = []
28
+ for (const [id, ts] of M) { const t = T.get(id); if (t === undefined || ts > t) send.push(id) }
29
+ for (const [id, ts] of T) { const m = M.get(id); if (m === undefined || ts > m) want.push(id) }
30
+ return { send, want }
31
+ }
32
+
33
+ /**
34
+ * @param {{
35
+ * threads: { methods: object, raw: () => object },
36
+ * siblings: () => Promise<string[]>, // llaves de comunicación de las hermanas
37
+ * send: (to: string, body: object) => Promise<void>,
38
+ * onChange?: () => void, // lo mezclado cambió lo guardado
39
+ * log: (msg: string) => void
40
+ * }} o
41
+ */
42
+ export function createSiblingBackup ({ threads, siblings, send, onChange = () => {}, log }) {
43
+ const partial = new Map() // quién → { indexes } mientras llegan las páginas de su índice
44
+ let timer = null
45
+
46
+ async function announce (reason) {
47
+ const to = await siblings()
48
+ if (!to.length) return
49
+ const { digests, floors } = await threads.methods.getBackupState()
50
+ let n = 0
51
+ for (const pub of to) {
52
+ try { await send(pub, { op: 'state', digests, floors }); n++ }
53
+ catch (e) { log(`[vault] could not send the app backup state to a sibling vault (${e.code || 'error'}): ${e.message}`) }
54
+ }
55
+ if (n) log(`[vault] sent the app backup state to ${n} sibling vault(s) on ${reason}`)
56
+ }
57
+
58
+ function schedule () {
59
+ if (timer) return
60
+ timer = setTimeout(() => { timer = null; announce('change').catch((e) => log('[vault] could not announce the app backup: ' + e.message)) }, ANNOUNCE_DEBOUNCE_MS)
61
+ timer.unref?.()
62
+ }
63
+
64
+ async function sendIndex (to, keys) {
65
+ const data = threads.raw()
66
+ const { floors } = await threads.methods.getBackupState()
67
+ let cursor = null
68
+ do {
69
+ const page = core.indexPage(data.threads, data.tombs, keys, cursor, core.PAGE_BYTES)
70
+ cursor = page.next
71
+ await send(to, { op: 'index', keys, indexes: page.indexes, floors, last: !cursor })
72
+ } while (cursor)
73
+ }
74
+
75
+ async function sendEntries (to, refs, keys) {
76
+ const data = threads.raw()
77
+ const { floors } = await threads.methods.getBackupState()
78
+ const tombs = core.pickTombs(data.tombs, refs, keys)
79
+ let rest = refs
80
+ let first = true
81
+ while (rest || first) {
82
+ const page = threads.methods.getEntries({ refs: rest || {}, maxBytes: core.PAGE_BYTES })
83
+ await send(to, { op: 'entries', threads: page.threads, owners: page.owners, tombs: first ? tombs : {}, floors })
84
+ rest = page.rest
85
+ first = false
86
+ }
87
+ }
88
+
89
+ async function merge (body) {
90
+ const r = threads.methods.importThreads({ threads: body.threads || {}, tombs: body.tombs || {}, owners: body.owners || {}, floors: body.floors || {}, mode: 'merge' })
91
+ if (r.changed.length) { onChange(); schedule() }
92
+ return r
93
+ }
94
+
95
+ /** Un mensaje de una hermana ya comprobada (sellado, del acta, para mí). */
96
+ async function handle (from, body) {
97
+ if (body.op === 'state') {
98
+ if (body.floors) await merge({ floors: body.floors })
99
+ const mine = await threads.methods.getBackupState()
100
+ const theirs = body.digests || {}
101
+ const keys = [...new Set([...Object.keys(mine.digests), ...Object.keys(theirs)])]
102
+ .filter((k) => mine.digests[k]?.digest !== theirs[k]?.digest)
103
+ if (keys.length) await sendIndex(from, keys)
104
+ return
105
+ }
106
+ if (body.op === 'index') {
107
+ const acc = partial.get(from) || { indexes: {} }
108
+ for (const [k, idx] of Object.entries(body.indexes || {})) {
109
+ const a = acc.indexes[k] || (acc.indexes[k] = { items: [], tombs: [] })
110
+ a.items.push(...(idx.items || [])); a.tombs.push(...(idx.tombs || []))
111
+ }
112
+ partial.set(from, acc)
113
+ if (!body.last) return
114
+ partial.delete(from)
115
+ const keys = Array.isArray(body.keys) ? body.keys.filter(core.validKey) : []
116
+ // Sus lápidas y sus suelos primero: lo borrado allí no se manda de vuelta.
117
+ const tombs = Object.fromEntries(Object.entries(acc.indexes).map(([k, idx]) => [k, idx.tombs]))
118
+ await merge({ tombs, floors: body.floors })
119
+ const data = threads.raw()
120
+ const mine = core.indexPage(data.threads, data.tombs, keys, null, Infinity).indexes
121
+ const send_ = {}; const want = {}
122
+ for (const k of keys) {
123
+ const p = planSibling(mine[k], acc.indexes[k])
124
+ if (p.send.length) send_[k] = p.send
125
+ if (p.want.length) want[k] = p.want
126
+ }
127
+ if (Object.keys(send_).length) await sendEntries(from, send_, keys)
128
+ if (Object.keys(want).length) await send(from, { op: 'want', refs: want })
129
+ return
130
+ }
131
+ if (body.op === 'want') return sendEntries(from, body.refs || {}, Object.keys(body.refs || {}))
132
+ if (body.op === 'entries') {
133
+ const r = await merge(body)
134
+ if (r.changed.length || r.evicted) log(`[vault] merged the app backup of a sibling vault: ${r.changed.length} thread(s) changed${r.evicted ? `, ${r.evicted} old entr${r.evicted === 1 ? 'y' : 'ies'} out by the 25 MB cap` : ''}`)
135
+ }
136
+ }
137
+
138
+ return { announce, schedule, handle }
139
+ }
@@ -44,7 +44,22 @@ export function openThreadStore (disk) {
44
44
  // primer aparato que todavía tenga la entrada.
45
45
  if (!data.tombs) data.tombs = {}
46
46
  core.pruneTombs(data.tombs, Date.now())
47
+ // EL TOPE DEL RESPALDO (dueño, 2026-10-28): 25 MB por cuenta. `owners` dice de qué app es
48
+ // cada hilo (lo anota el almacén del navegador) y `floors`, por hilo, hasta qué `ts` se borró
49
+ // por el tope: eso sale solo de aquí, el aparato lo conserva y deja de subirlo.
50
+ if (!data.owners) data.owners = {}
51
+ if (!data.floors) data.floors = {}
47
52
  const save = () => writeJson(disk, file, data)
53
+ const takeOwners = (incoming) => {
54
+ let changed = false
55
+ for (const [k, app] of Object.entries(needMap(incoming, 'owners'))) {
56
+ if (!core.validKey(k) || typeof app !== 'string' || !app || data.owners[k] === app) continue
57
+ data.owners[k] = app
58
+ changed = true
59
+ }
60
+ return changed
61
+ }
62
+ const fit = () => core.enforceQuota(data.threads, data.owners, data.floors)
48
63
  save() // reescribe al abrir: cifra lo que venía en claro
49
64
  const budget = (n) => Math.min(Math.max(Number(n) || core.PAGE_BYTES, 1024), core.PAGE_BYTES)
50
65
  const needKeys = (keys) => {
@@ -60,6 +75,7 @@ export function openThreadStore (disk) {
60
75
  const methods = {
61
76
  appendMessage ({ threadKey, entry }) {
62
77
  core.writeEntry(data.threads, data.tombs, threadKey, entry, { max: MAX_PER_THREAD, now: Date.now(), newId: () => crypto.randomUUID() })
78
+ fit()
63
79
  save(); return entry
64
80
  },
65
81
  listThread ({ threadKey, limit, before }) {
@@ -109,22 +125,34 @@ export function openThreadStore (disk) {
109
125
  getThreadDigests ({ keys } = {}) {
110
126
  return core.digestsOf(data.threads, keys == null ? undefined : needKeys(keys))
111
127
  },
128
+ /** Las huellas y los suelos: el aparato calcula las suyas sin lo que aquí ya no se guarda. */
129
+ async getBackupState () {
130
+ return { digests: await core.digestsOf(data.threads), floors: { ...data.floors }, quota: core.VAULT_QUOTA_BYTES }
131
+ },
112
132
  getThreadIndexes ({ keys, cursor, maxBytes }) {
113
133
  return core.indexPage(data.threads, data.tombs, needKeys(keys), cursor || null, budget(maxBytes))
114
134
  },
115
135
  getEntries ({ refs, maxBytes }) {
116
- return core.entriesPage(data.threads, needMap(refs, 'refs'), budget(maxBytes))
136
+ const page = core.entriesPage(data.threads, needMap(refs, 'refs'), budget(maxBytes))
137
+ const owners = Object.fromEntries(Object.keys(page.threads).filter((k) => Object.hasOwn(data.owners, k)).map((k) => [k, data.owners[k]]))
138
+ return { ...page, owners }
117
139
  },
118
- importThreads ({ threads, tombs, mode = 'merge' }) {
140
+ importThreads ({ threads, tombs, owners, floors, mode = 'merge' }) {
119
141
  if (!threads || typeof threads !== 'object') throw new Error('threads required')
120
142
  if (mode === 'replace') { data.threads = threads; save(); return { mode, count: Object.keys(threads).length } }
121
143
  if (mode !== 'merge' && mode !== 'upsert') throw new Error(`unknown import mode: ${mode}`)
122
144
  const now = Date.now()
145
+ const ownersChanged = takeOwners(owners)
146
+ // Los suelos de otra bóveda (la copia entre hermanas): el mayor de cada hilo.
147
+ const floorsChanged = core.mergeFloors(data.floors, needMap(floors, 'floors'))
148
+ const lowered = floorsChanged ? core.applyFloors(data.threads, data.floors) : new Set()
123
149
  const buried = core.applyTombs(data.threads, data.tombs, needMap(tombs, 'tombs'), now)
124
- const merged = core.mergeEntries(data.threads, data.tombs, threads, { mode, max: MAX_PER_THREAD })
150
+ const merged = core.mergeEntries(data.threads, data.tombs, threads, { mode, max: MAX_PER_THREAD, floors: data.floors })
125
151
  core.pruneTombs(data.tombs, now)
126
- if (buried.tombsChanged || buried.changed.size || merged.size) save()
127
- return { mode, count: Object.keys(data.threads).length, changed: [...new Set([...buried.changed, ...merged])] }
152
+ const fitted = fit()
153
+ const changed = new Set([...lowered, ...buried.changed, ...merged, ...fitted.changed])
154
+ if (ownersChanged || floorsChanged || buried.tombsChanged || changed.size || fitted.evicted) save()
155
+ return { mode, count: Object.keys(data.threads).length, changed: [...changed], evicted: fitted.evicted }
128
156
  },
129
157
  // ----- PERFIL del usuario (me): el vault es la copia AUTORITATIVA -----
130
158
  // Cada dispositivo emparejado lo empuja al editarlo y lo jala al arrancar →
@@ -262,7 +290,7 @@ export function openThreadStore (disk) {
262
290
  */
263
291
  export const STORE_READ_METHODS = new Set([
264
292
  'listThread', 'listThreadKeys', 'getThreadSummaries', 'getOpens', 'exportThreads', 'getStats', 'profileGet',
265
- 'getThreadDigests', 'getThreadIndexes', 'getEntries'
293
+ 'getThreadDigests', 'getThreadIndexes', 'getEntries', 'getBackupState'
266
294
  ])
267
295
 
268
296
  /**
@@ -22,6 +22,7 @@ import { createTransport, masterPubkeyOf } from './transport.js'
22
22
  import { startSealersPublisher } from './sealers.js'
23
23
  import { openStore } from './store.js'
24
24
  import { openThreadStore, STORE_READ_METHODS, PROFILE_EDIT_METHODS } from './threadStore.js'
25
+ import { createSiblingBackup } from './siblingBackup.js'
25
26
  import { openSecretsStore, assertVar, RECOVERY as RECOVERY_WRAP, PROFILE_OWNER } from './secretsStore.js'
26
27
  import { openSubacta } from './subacta.js'
27
28
  import { openBlocked } from './blocked.js'
@@ -161,6 +162,23 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
161
162
 
162
163
  const store = openStore(disk)
163
164
  const threads = openThreadStore(disk)
165
+ const siblingBackup = createSiblingBackup({
166
+ threads,
167
+ siblings: async () => {
168
+ const acta = (await identity.profileActa?.().catch(() => null))?.acta || null
169
+ const mine = await commKey.ensure().catch(() => null)
170
+ if (!acta || !mine) return []
171
+ return (acta.members || []).filter((m) => m.cn === COMM_CN && m.vault && m.vault !== master && m.pub !== mine).map((m) => m.pub)
172
+ },
173
+ send: async (to, part) => {
174
+ const mine = await commKey.ensure()
175
+ const body = { ...part, by: mine, to, ts: Date.now() }
176
+ const signature = await commKey.sign(body)
177
+ if (!signature) throw new Error('the communication key could not sign')
178
+ await client.sendSealed([to], { type: MSG.SIBLING_BACKUP, body, signature }, { quiet: true, app: 'vault' })
179
+ },
180
+ log
181
+ })
164
182
  /**
165
183
  * LO QUE SIRVE LA BÓVEDA VA CON LA LLAVE VIGENTE (dueño, 2026-09-30). Tras una rotación
166
184
  * de la llave de la cuenta, los sobres (`t: 'dotrino-cek'`) de generaciones anteriores
@@ -609,6 +627,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
609
627
  // POR DETRÁS: sellar a la hermana exige averiguar su llave en el proxio, y si no la ha
610
628
  // anunciado esa pregunta tarda. El arranque no espera a eso.
611
629
  pushDrawersToSiblings('start').catch(() => {})
630
+ // Y EL RESPALDO DE LAS APPS: una que estuvo apagada días se pone al día sola.
631
+ siblingBackup.announce('start').catch((e) => log('[vault] could not announce the app backup: ' + e.message))
612
632
  await syncExNotices()
613
633
 
614
634
  async function revocationSet () {
@@ -1314,6 +1334,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
1314
1334
  // de seguridad, no una copia de lo que guardas).
1315
1335
  if (!STORE_READ_METHODS.has(d.method)) {
1316
1336
  audit('store', { device: await deviceIdOf(chk.device), method: d.method })
1337
+ siblingBackup.schedule()
1317
1338
  }
1318
1339
  const enc = await identity.sealContent(JSON.stringify(result ?? null))
1319
1340
  reply(from, { type: MSG.STORE_RESULT, method: d.method, result: { __enc: enc } })
@@ -1537,7 +1558,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
1537
1558
  // LA SUBACTA VIAJA CON EL ACTA. Es la mitad de «se comparte entre todos los
1538
1559
  // dispositivos»: sin esto, una renuncia sin sellar solo la respeta esta máquina.
1539
1560
  // Cada entrada va firmada por su sujeto, así que quien la recibe la verifica sola.
1540
- reply(from, fitChain({ type: MSG.DEVICES_RESULT, devices, revoked, blocked: blocked.pubs(), acta: record, chain, sealerChain: await sealerChainOf(), vault: MI_VERSION, subacta: subacta.entries() }))
1561
+ reply(from, fitChain({ type: MSG.DEVICES_RESULT, devices, siblingCerts: await siblingCertsFor(record), revoked, blocked: blocked.pubs(), acta: record, chain, sealerChain: await sealerChainOf(), vault: MI_VERSION, subacta: subacta.entries() }))
1541
1562
  }
1542
1563
 
1543
1564
  /**
@@ -2499,6 +2520,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2499
2520
  if (payload.type === MSG.RENOUNCE) return await handleRenounce(from, payload)
2500
2521
  if (payload.type === MSG.ADMIN_EVENT) return await handleAdminEvent(payload)
2501
2522
  if (payload.type === MSG.SIBLING_DRAWERS) return await handleSiblingDrawers(payload, meta)
2523
+ if (payload.type === MSG.SIBLING_BACKUP) return await handleSiblingBackup(payload, meta)
2502
2524
  if (payload.type === MSG.INCIDENT) return await handleIncident(from, payload)
2503
2525
  if (payload.type === MSG.REPLICA_ACK) return await handleReplicaAck(from, payload)
2504
2526
  if (payload.type === MSG.LOGIN_START) return await handleLoginStart(from, payload)
@@ -2856,9 +2878,14 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2856
2878
  const mine = await commKey.ensure().catch(() => null)
2857
2879
  if (!mine) return
2858
2880
  const siblings = (acta.members || []).filter((m) => m.cn === COMM_CN && m.vault && m.vault !== master && m.pub !== mine)
2881
+ // Y LOS PAPELES QUE EMITIÓ ESTA (2026-10-27): cada bóveda solo conoce los suyos, y la
2882
+ // otra decía «sin acceso» de un aparato que entraba con el de esta. Solo lo que hace falta
2883
+ // para decirlo (de quién, desde cuándo, con qué acta); nada con lo que entrar.
2884
+ const certs = ((await identity.listDelegations().catch(() => null))?.issued || [])
2885
+ .filter((d) => d.sub).map((d) => ({ nonce: d.nonce, sub: d.sub, iat: d.iat || null, seq: d.seq ?? null }))
2859
2886
  let n = 0
2860
2887
  for (const m of siblings) {
2861
- const body = { op: 'drawers', by: mine, to: m.pub, seq: acta.seq, state, ts: Date.now() }
2888
+ const body = { op: 'drawers', by: mine, to: m.pub, seq: acta.seq, state, certs, ts: Date.now() }
2862
2889
  const signature = await commKey.sign(body)
2863
2890
  if (!signature) continue
2864
2891
  // SELLADO POR EL PILAR a la llave de cifrado del transporte de la hermana, que ella
@@ -2871,6 +2898,37 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2871
2898
  } catch (e) { log('[vault] could not send the drawers to the sibling vaults: ' + e.message) }
2872
2899
  }
2873
2900
 
2901
+ /**
2902
+ * LOS PAPELES DE LAS HERMANAS, por bóveda (su llave). Se guardan en los ajustes para que una
2903
+ * bóveda que duerme (la Lambda) los tenga al despertar, y se enseñan aparte de los propios:
2904
+ * la lista de dispositivos de una bóveda dice lo SUYO, y lo de la otra va marcado como suyo.
2905
+ */
2906
+ const SIBLING_CERTS = 'sibling-certs'
2907
+ function loadSiblingCerts () {
2908
+ const raw = store.getSetting?.(SIBLING_CERTS)
2909
+ if (!raw) return {}
2910
+ try { return JSON.parse(raw) || {} } catch (e) { log('[vault] the certificates of the sibling vaults could not be read: ' + e.message); return {} }
2911
+ }
2912
+ function saveSiblingCerts (vaultPub, certs) {
2913
+ const all = loadSiblingCerts()
2914
+ all[vaultPub] = { at: Date.now(), certs: certs.filter((c) => c && typeof c.sub === 'string').slice(0, 500) }
2915
+ store.setSetting?.(SIBLING_CERTS, JSON.stringify(all))
2916
+ }
2917
+ async function siblingCertsFor (record) {
2918
+ const all = loadSiblingCerts()
2919
+ const out = []
2920
+ for (const [vaultPub, v] of Object.entries(all)) {
2921
+ // Solo de una bóveda que sigue sellando esta cuenta: la que salió no avala a nadie.
2922
+ if (!record || !Acta.memberCan(record, vaultPub, 'sealer')) continue
2923
+ const vaultId = await deviceIdOf(vaultPub).catch(() => null)
2924
+ for (const c of v.certs || []) {
2925
+ if (!(record.members || []).some((m) => m.pub === c.sub)) continue
2926
+ out.push({ sub: c.sub, deviceId: await deviceIdOf(c.sub).catch(() => null), nonce: c.nonce, iat: c.iat, seq: c.seq, by: vaultPub, byId: vaultId, at: v.at })
2927
+ }
2928
+ }
2929
+ return out
2930
+ }
2931
+
2874
2932
  /**
2875
2933
  * LOS CAJONES DE UNA HERMANA. La puerta ya comprobó que `body.by` es miembro y que la
2876
2934
  * firma es suya; aquí se mira que sea la llave de comunicación de OTRA bóveda que sella y
@@ -2886,6 +2944,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2886
2944
  const who = (acta?.members || []).find((m) => m.pub === body.by)
2887
2945
  const okSibling = acta && who && who.cn === COMM_CN && who.vault && who.vault !== master && Acta.memberCan(acta, who.vault, 'sealer')
2888
2946
  if (!okSibling || body.to !== mine) return log('[vault] drawers from someone who is not a sibling vault, or not for us: ignored')
2947
+ if (Array.isArray(body.certs)) saveSiblingCerts(who.vault, body.certs)
2889
2948
  try {
2890
2949
  const r = await secrets.mergeState(body.state)
2891
2950
  log(`[vault] merged the drawers of a sibling vault (record #${body.seq}): ${r.changed} change(s)`)
@@ -2895,6 +2954,19 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2895
2954
  } catch (e) { log('[vault] could not merge the drawers of a sibling vault: ' + e.message) }
2896
2955
  }
2897
2956
 
2957
+ async function handleSiblingBackup (payload, meta) {
2958
+ const body = payload?.body
2959
+ if (!body || typeof body.op !== 'string') return
2960
+ // NADA EN CLARO: es lo que guardan las apps del usuario.
2961
+ if (!meta?.sealed) return log('[vault] app backup from a sibling arrived UNSEALED: ignored')
2962
+ const acta = (await identity.profileActa?.().catch(() => null))?.acta || null
2963
+ const mine = await commKey.ensure().catch(() => null)
2964
+ const who = (acta?.members || []).find((m) => m.pub === body.by)
2965
+ const okSibling = acta && who && who.cn === COMM_CN && who.vault && who.vault !== master && Acta.memberCan(acta, who.vault, 'sealer')
2966
+ if (!okSibling || body.to !== mine) return log('[vault] app backup from someone who is not a sibling vault, or not for us: ignored')
2967
+ try { await siblingBackup.handle(body.by, body) } catch (e) { log(`[vault] could not handle the app backup of a sibling vault (${body.op}): ${e.message}`) }
2968
+ }
2969
+
2898
2970
  async function notifyMembers (ev, info = {}) {
2899
2971
  // El acta pudo cambiar (alguien salió): su aviso tiene que estar listo para cuando pregunte.
2900
2972
  await syncExNotices()
@@ -3621,8 +3693,15 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
3621
3693
  if (!record) return []
3622
3694
  // Sin `encPub` no hay a dónde envolver: se queda en deuda y se ve como `sinLlave`,
3623
3695
  // igual que cualquier otro miembro incompleto.
3624
- return (record.members || []).filter((m) =>
3696
+ const others = (record.members || []).filter((m) =>
3625
3697
  m.pub !== master && m.encPub && Acta.memberCan(record, m.pub, 'sealer'))
3698
+ if (!others.length) return []
3699
+ // Y ESTA MISMA, si hay otras (2026-10-27). Aquí se lee con la copia maestra y no necesita su
3700
+ // sobre, pero lo que se sincroniza es el estado entero, y la hermana veía a esta bóveda sin
3701
+ // sobre en sus cajones: «sin llave todavía 3B48-962A» en la Nube, que no se iba nunca porque
3702
+ // esta no se lo ponía. Un sobre de más para una llave que ya los abre no da nada nuevo.
3703
+ const me = (record.members || []).find((m) => m.pub === master && m.encPub)
3704
+ return me ? [...others, me] : others
3626
3705
  }
3627
3706
 
3628
3707
  /** Sin duplicar: un cosellador puede ser además el dueño del cajón. */
@@ -4100,6 +4179,9 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
4100
4179
  }
4101
4180
  const r = await resealAll(k).catch((e) => { log(`[vault] ${reason}: could not rebuild the keyring: ${e.message}`); return null })
4102
4181
  if (r?.wrapped) log(`[vault] ${reason}: keyring rebuilt (${r.wrapped} wrap(s) in ${r.drawers} drawer(s))`)
4182
+ // Lo rehecho, a las hermanas: si no, su copia sigue con los sobres de antes hasta el próximo
4183
+ // cambio, y su pantalla dice que faltan.
4184
+ if (r?.wrapped || r?.dropped) scheduleDrawerPush()
4103
4185
  // LOS SOBRES CADUCOS SE DICEN. Son envolturas de quien ya no debería poder abrir ese
4104
4186
  // cajón: retirarlas en silencio esconde que alguien las tuvo de más.
4105
4187
  if (r?.dropped) log(`[vault] ${reason}: ${r.dropped} stale wrap(s) dropped (they belonged to members the record no longer names)`)
@@ -88,6 +88,8 @@ export const MSG = Object.freeze({
88
88
  // bóveda → sus hermanas: los cajones (sellados a la llave de cifrado de la hermana) y las
89
89
  // lápidas, firmados por la llave de comunicación de quien manda (`docs/replicas.md` §11.4).
90
90
  SIBLING_DRAWERS: 'vault.sibling.drawers',
91
+ // bóveda → sus hermanas: el respaldo de las apps, por partes (`core/siblingBackup.js`).
92
+ SIBLING_BACKUP: 'vault.sibling.backup',
91
93
  ADMIN_EVENT: 'vault.admin.event', // vault → todos: { body:{ev,deviceId,by,ts}, acta } (pedidos: + seal)
92
94
  // RÉPLICAS: la principal empuja lo que hay que servir (el acta y los sobres, que van
93
95
  // firmados de antes y no se pueden falsificar) y la réplica acusa hasta qué `seq` tiene.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/vaultd",
3
- "version": "0.184.0",
3
+ "version": "0.186.2",
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": {
@@ -13,7 +13,7 @@
13
13
  "start": "node bin/dotrino-vaultd.js",
14
14
  "pair": "node bin/dotrino-vaultd.js --pair",
15
15
  "tui": "node bin/dotrino-vault-tui.js",
16
- "test": "node --test test/*.test.mjs",
16
+ "test": "node --test --require ./test/fixtures/hang-watchdog.cjs test/*.test.mjs",
17
17
  "type-check": "tsc --noEmit",
18
18
  "release:env": "node packaging/release-env.mjs"
19
19
  },
@@ -22,12 +22,12 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@dotrino/compat": "0.5.0",
25
- "@dotrino/identity": "0.132.0",
25
+ "@dotrino/identity": "0.134.0",
26
26
  "@dotrino/opaque": "0.1.0",
27
27
  "@dotrino/passmanager": "0.18.6",
28
- "@dotrino/proxy-client": "^0.45.0",
28
+ "@dotrino/proxy-client": "^0.45.3",
29
29
  "@dotrino/roadmap": "0.4.63",
30
- "@dotrino/store": "0.12.3",
30
+ "@dotrino/store": "0.13.0",
31
31
  "@dotrino/update": "0.9.0",
32
32
  "sigstore": "5.0.0",
33
33
  "ws": "^8.18.0"
package/src/ctl.js CHANGED
@@ -613,21 +613,12 @@ async function cmdMembers () {
613
613
  assertOpen(record)
614
614
  if (!record.members?.length) { console.log('Este perfil todavía no tiene acta.'); return }
615
615
 
616
- // `sealer` y `passwords` faltaban y salían crudos, en inglés, entre los demás en
617
- // español. Se resaltan como `admin` y `approve`: los cuatro cambian lo que ese aparato
618
- // puede hacerle a la cuenta, y eso se lee de un vistazo o no se lee.
619
- const CAP = {
620
- sign: 'firma', store: 'guarda', read: 'lee',
621
- admin: `${B}administra el perfil${Z}`, approve: `${B}aprueba pedidos${Z}`,
622
- sealer: `${B}sella el acta${Z}`, passwords: `${B}pide contraseñas${Z}`,
623
- // Resaltado como los otros cuatro: dice si esa máquina se lleva tus claves privadas
624
- // sola o si te lo pregunta. Sin traducción salía el identificador en crudo
625
- // (`unattended`) en una lista que lee un humano.
626
- unattended: `${B}recibe claves sin aprobación${Z}`,
627
- // Y el que reparte cuando esta bóveda no está. Se resalta como los demás que cambian
628
- // lo que ese aparato puede hacerle a la cuenta.
629
- replica: `${B}entrega tus claves con la bóveda apagada${Z}`
630
- }
616
+ // LOS PERMISOS POR SU NOMBRE, el mismo que se teclea en `caps` (dueño, 2026-10-27: «solo en
617
+ // inglés»). Antes salía una descripción en español («sella el acta», «aprueba pedidos») y había
618
+ // que traducirla para poder tocar el permiso. Se resaltan los que cambian lo que ese aparato
619
+ // puede hacerle a la cuenta: se leen de un vistazo o no se leen.
620
+ const STRONG = new Set(['admin', 'approve', 'sealer', 'passwords', 'unattended', 'replica'])
621
+ const CAP = Object.fromEntries(CAP_WORDS.map((w) => [w, STRONG.has(w) ? `${B}${w}${Z}` : w]))
631
622
  // El nombre del perfil es una pubkey JWK. Recortarla no la hace legible: la deja
632
623
  // pareciendo un error (`{"key_ops":["verify"],"e…`). Se muestra su huella corta, la
633
624
  // misma que se enseña al emparejar y en la lista de miembros.
@@ -1682,7 +1673,7 @@ const LOGINS_USAGE = `uso: dotrino-vault logins <orden>
1682
1673
  logins [ls] los aparatos que se abren con usuario y contraseña
1683
1674
  logins add <usuario> [nombre del equipo] [±permiso …]
1684
1675
  permisos como en «caps» (+approve, -store, +unattended…).
1685
- Sin decir nada: firma, lee y guarda
1676
+ Sin decir nada: sign, read y store
1686
1677
  logins passwd <usuario> cambia la contraseña (cierra lo que estuviera abierto)
1687
1678
  logins close <usuario> [sid] cierra una sesión abierta (sin sid, todas)
1688
1679
  logins unblock <usuario> quita la espera de los intentos fallidos
@@ -1717,7 +1708,7 @@ async function cmdLogins (rest) {
1717
1708
  case 'add': {
1718
1709
  needUser()
1719
1710
  // `±permiso` se lee con las MISMAS palabras que `caps <ID> ±permiso`, sobre los de
1720
- // siempre (firma, lee, guarda); lo demás es el nombre del equipo. Antes el texto de
1711
+ // siempre (sign, read, store); lo demás es el nombre del equipo. Antes el texto de
1721
1712
  // ayuda lo anunciaba y aquí se juntaba todo como nombre.
1722
1713
  const caps = new Set(['sign', 'read', 'store'])
1723
1714
  const name = []
@@ -2559,8 +2550,8 @@ function help () {
2559
2550
  El QR no lleva nada: el permiso se aplica al aprobar el código aquí
2560
2551
  pair --quiet escupe SOLO la invitación (una línea) y termina: sin QR y sin
2561
2552
  esperar. Para desplegar (un contenedor no mira un QR en pantalla)
2562
- pair --scope <lista> los PERMISOS con los que entra, cualquiera de los de caps (firma,lee,guarda,administra,
2563
- aprueba,contrasenas,sella,desatendido,replica) y secrets:<ns>. Sin esto: firma,lee,guarda.
2553
+ pair --scope <lista> los PERMISOS con los que entra, cualquiera de los de caps (sign,read,store,admin,
2554
+ approve,passwords,sealer,unattended,replica) y secrets:<ns>. Sin esto: sign,read,store.
2564
2555
  Entra al acta ya con ellos. Se combina con --service: --service eco --scope sign
2565
2556
  secret set <ns> <CLAVE> <valor> variable del scope <ns>: la comparten TODOS los
2566
2557
  aparatos del perfil que sirven ese namespace
@@ -2634,7 +2625,7 @@ function help () {
2634
2625
  prestado, donde no puedes emparejar nada)
2635
2626
  logins add <usuario> [nombre del equipo] [±permiso …]
2636
2627
  permisos como en «caps» (+approve, -store, +unattended…).
2637
- Sin decir nada: firma, lee y guarda
2628
+ Sin decir nada: sign, read y store
2638
2629
  crea uno. La contraseña se teclea aquí y no sale de esta terminal:
2639
2630
  la bóveda guarda un paquete de llaves que solo ella abre
2640
2631
  logins passwd <usuario> cambia la contraseña (cierra lo que estuviera abierto)
package/src/tui/app.js CHANGED
@@ -46,6 +46,7 @@ import * as service from '../service.js'
46
46
  import { startDaemonService, restartDaemonService } from '../service.js'
47
47
  import { DEVICE_CAPS } from '@dotrino/identity/acta'
48
48
  import { machineLine } from '@dotrino/identity/machine'
49
+ import { groupMembers, isCommKey } from '../../lib/src/core/memberGroups.js'
49
50
 
50
51
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
51
52
 
@@ -506,40 +507,11 @@ function deviceRows (st, t) {
506
507
  if (draft.length) {
507
508
  rows.unshift({ text: t.bold(' ' + i.devicesDraft(draft.length)), sel: false }, { text: '', sel: false })
508
509
  }
509
- // EN TRES GRUPOS (dueño, 2026-10-26: «me confunde, no sé qué es dispositivo, qué es servicio,
510
- // qué es bóveda, qué es llave de comunicación»). La lista plana mezclaba cuatro cosas que no
511
- // se administran igual:
512
- // · BÓVEDAS: las que sellan el acta. Debajo de cada una, su llave de comunicación, que es
513
- // parte de ella (habla por la red con el candado echado) y no un aparato.
514
- // · APARATOS: teléfonos, navegadores, terminales, agentes.
515
- // · SERVICIOS: los que solo leen su cajón de secretos (`cn` = su espacio).
516
- const isComm = (d) => d.cn === 'vault'
517
- const vaults = devices.filter((d) => d.isMaster && !isComm(d))
518
- const comms = devices.filter(isComm)
519
- const services = devices.filter((d) => d.cn && !isComm(d) && !d.isMaster)
520
- const others = devices.filter((d) => !d.isMaster && !d.cn)
521
- // La de esta máquina primero: es la que se está administrando.
522
- vaults.sort((a, b) => (b.isMe ? 1 : 0) - (a.isMe ? 1 : 0))
523
- const ordered = []
524
- const section = (title, list) => { if (list.length) ordered.push({ title }, ...list) }
525
- const placed = new Set()
526
- const vaultBlock = []
527
- for (const v of vaults) {
528
- vaultBlock.push(v)
529
- for (const c of comms) if (c.vault === v.sub) { vaultBlock.push({ ...c, child: true }); placed.add(c.sub) }
530
- }
531
- // Una llave de comunicación de antes de que el acta dijera de qué bóveda es: va con la bóveda
532
- // de aquí, que es quien la acuñaba entonces.
533
- const orphanComms = comms.filter((c) => !placed.has(c.sub)).map((c) => ({ ...c, child: true }))
534
- const meAt = vaultBlock.findIndex((d) => d.isMe)
535
- if (meAt >= 0) {
536
- let at = meAt + 1
537
- while (vaultBlock[at]?.child) at++
538
- vaultBlock.splice(at, 0, ...orphanComms)
539
- } else vaultBlock.push(...orphanComms)
540
- section(i.groupVaults, vaultBlock)
541
- section(i.groupDevices, others)
542
- section(i.groupServices, services)
510
+ // EN TRES GRUPOS: bóvedas (con su llave de comunicación debajo), aparatos y servicios. La regla
511
+ // vive en `lib/src/core/memberGroups.js`, la misma que usa la consola.
512
+ const isComm = isCommKey
513
+ const GROUP_TITLE = { vaults: i.groupVaults, devices: i.groupDevices, services: i.groupServices }
514
+ const ordered = groupMembers(devices, { keyOf: (d) => d.sub }).flatMap((g) => [{ title: GROUP_TITLE[g.group] }, ...g.items])
543
515
  for (const d of ordered) {
544
516
  if (d.title) {
545
517
  if (rows.length && rows[rows.length - 1].text !== '') rows.push({ text: '', sel: false })