@dotrino/vaultd 0.185.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.112.0'
8
+ export const LIB_VERSION = '0.113.0'
@@ -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 } })
@@ -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)
@@ -2932,6 +2954,19 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2932
2954
  } catch (e) { log('[vault] could not merge the drawers of a sibling vault: ' + e.message) }
2933
2955
  }
2934
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
+
2935
2970
  async function notifyMembers (ev, info = {}) {
2936
2971
  // El acta pudo cambiar (alguien salió): su aviso tiene que estar listo para cuando pregunte.
2937
2972
  await syncExNotices()
@@ -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.185.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.133.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"