@dotrino/identity 0.133.0 → 0.134.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/identity",
3
- "version": "0.133.0",
3
+ "version": "0.134.0",
4
4
  "description": "Identidad y rating de usuarios compartidos entre apps de Dotrino (vault iframe + postMessage)",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/index.js CHANGED
@@ -464,8 +464,8 @@ export class Identity {
464
464
  * listThread, recordOpen, getOpens, getStats, …) EN tu vault, usando el cert de
465
465
  * este dispositivo. Reusa el mismo emparejamiento. Requiere el vault encendido.
466
466
  */
467
- async vaultStore (method, args) {
468
- return this._call('vaultStore', { method, args }, 20000)
467
+ async vaultStore (method, args, { wake = true } = {}) {
468
+ return this._call('vaultStore', { method, args, wake }, 20000)
469
469
  }
470
470
 
471
471
  /**
package/vault/core.js CHANGED
@@ -3360,7 +3360,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3360
3360
  * perfil desde un aparato que ya la tenga — y se ve, en vez de viajar a la vista.
3361
3361
  * Por lo mismo, una respuesta sin cifrar tampoco se acepta.
3362
3362
  */
3363
- async vaultStore ({ method, args }) {
3363
+ async vaultStore ({ method, args, wake = true }) {
3364
3364
  const v = loadVaultCert(); const device = loadVaultDevice()
3365
3365
  if (!v?.cert || !device) throw Object.assign(new Error('this device is not paired with a vault'), { code: 'not-paired' })
3366
3366
  maybeRenewVaultCert()
@@ -3368,10 +3368,25 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
3368
3368
  if (!mine) throw Object.assign(new Error('this device does not hold the profile content key yet'), { code: 'no-content-key' })
3369
3369
  const enc = await Content.encryptWithCek({ cek: mine.cek, gen: mine.gen, plaintext: JSON.stringify(args ?? {}) })
3370
3370
  try {
3371
- const res = await remoteStore({ master: v.master, proxy: v.proxy, device, cert: v.cert, method, enc, onRevoked: wipeVaultLink })
3371
+ // `wake: false` (lo decide el almacén, dueño 2026-10-28): no despierta a la Nube por cada
3372
+ // mensaje; solo si lleva más de 24 h sin respaldar, o con el botón de sincronizar.
3373
+ const res = await remoteStore({ master: v.master, proxy: v.proxy, device, cert: v.cert, method, enc, wake, onRevoked: wipeVaultLink })
3372
3374
  if (!res || typeof res !== 'object' || !res.__enc) {
3373
3375
  throw Object.assign(new Error('the vault replied to the store without encrypting it'), { code: 'vault-reply-unsealed' })
3374
3376
  }
3377
+ // LA BÓVEDA CONTESTA CON SU GENERACIÓN, que puede ser más nueva que mi acta (2026-10-27:
3378
+ // el navegador del messenger en un acta anterior a la #74 y la bóveda cerrando con la
3379
+ // generación 11, que nació en la #74). Solo la página /vault ponía al día el acta, así
3380
+ // que fuera de ella el almacén fallaba para siempre. Me pongo al día por el camino de
3381
+ // siempre (la lista trae el acta y la cadena de selladoras) y la abro con la que llegue.
3382
+ const hasGen = () => (loadActa()?.keyring || []).some((g) => g.gen === res.__enc?.gen && g.wraps?.[publickeyJwkStr])
3383
+ if (!hasGen()) {
3384
+ const antes = loadActa()?.seq ?? null
3385
+ await handlers.listVaultDevices()
3386
+ if (!hasGen()) {
3387
+ throw Object.assign(new Error(`the vault replied with content key generation ${res.__enc?.gen} and this device, on record #${loadActa()?.seq ?? antes}, does not hold it`), { code: 'content-gen-ahead' })
3388
+ }
3389
+ }
3375
3390
  return JSON.parse(await Content.decryptWithKeyring({
3376
3391
  envelope: res.__enc, keyring: loadActa()?.keyring, myPub: publickeyJwkStr, myEncPrivateKey: encKeypair.privateKey
3377
3392
  }))
package/vault/facade.js CHANGED
@@ -154,7 +154,7 @@ export class IdentityFacade {
154
154
  vaultStatus () { return this._h('vaultStatus') }
155
155
  unpairDevice () { return this._h('vaultUnpair') }
156
156
  vaultSign (payload) { return this._h('vaultSign', { payload }) }
157
- vaultStore (method, args) { return this._h('vaultStore', { method, args }) }
157
+ vaultStore (method, args, { wake = true } = {}) { return this._h('vaultStore', { method, args, wake }) }
158
158
  listVaultDevices (opts) { return this._h('listVaultDevices', opts || {}) }
159
159
  getVaultCert () { return this._h('getVaultCert') }
160
160
  vaultApprovals (op, args) { return this._h('vaultApprovals', { op, ...(args || {}) }) }
package/vault/remote.js CHANGED
@@ -364,7 +364,7 @@ async function clientFor (proxy, master) {
364
364
  return client
365
365
  }
366
366
 
367
- async function vaultRpc ({ master, to = null, proxy, device, cert, acta = null, sendType, okType, data, onRevoked, timeoutMs = 15000 }) {
367
+ async function vaultRpc ({ master, to = null, proxy, device, cert, acta = null, sendType, okType, data, onRevoked, timeoutMs = 15000, quiet = false }) {
368
368
  // `to`: a qué llave se escribe, si no es la maestra. Con dos bóvedas en la cuenta, la
369
369
  // maestra del perfil las alcanza a todas; la llave de comunicación de una, solo a ella.
370
370
  const dest = to || master
@@ -401,7 +401,8 @@ async function vaultRpc ({ master, to = null, proxy, device, cert, acta = null,
401
401
  const t = setTimeout(() => { cleanup(); reject(Object.assign(new Error('the vault did not reply (is it running?)'), { code: 'vault-no-reply' })) }, timeoutMs)
402
402
  const cleanup = () => { off(); clearTimeout(t); clearTimeout(graceTimer) }
403
403
  })
404
- client.sendByPubkey(dest, { type: sendType, data: signed, signature, cert })
404
+ // `quiet`: no despierta a una bóveda dormida (la Nube); si duerme, lo recibe al despertar.
405
+ client.sendByPubkey(dest, { type: sendType, data: signed, signature, cert }, quiet ? { quiet: true } : {})
405
406
  return await pending
406
407
  } finally { try { client.close() } catch (_) {} }
407
408
  }
@@ -450,10 +451,10 @@ export async function checkMembership ({ master, proxy, device, onRevoked, timeo
450
451
  }
451
452
 
452
453
  /** Lee/escribe el store de hilos+aperturas EN el vault (con el cert del dispositivo). */
453
- export async function requestStore ({ master, proxy, device, cert, method, args, enc, onRevoked } = {}) {
454
+ export async function requestStore ({ master, proxy, device, cert, method, args, enc, onRevoked, wake = true } = {}) {
454
455
  // `enc`: argumentos cifrados con la clave de contenido del perfil (el proxy no los ve).
455
456
  const data = enc ? { op: 'store', method, enc } : { op: 'store', method, args: args || {} }
456
- const res = await vaultRpc({ master, proxy, device, cert, onRevoked, sendType: 'vault.store', okType: 'vault.store.result', data })
457
+ const res = await vaultRpc({ master, proxy, device, cert, onRevoked, quiet: !wake, sendType: 'vault.store', okType: 'vault.store.result', data })
457
458
  return res.result
458
459
  }
459
460
 
@@ -1,3 +1,3 @@
1
- Copia vendorizada de @dotrino/roadmap@0.4.83 (dotrino-roadmap/src/{index,manifests}.js).
1
+ Copia vendorizada de @dotrino/roadmap@0.4.84 (dotrino-roadmap/src/{index,manifests}.js).
2
2
  NO se edita a mano: la escribe `node vendor.mjs` y la vigila test/vendor-up-to-date.test.mjs.
3
3
  El registro de versiones rotas que viaja con cada versión. Importa @dotrino/compat/ranges.
@@ -31,7 +31,7 @@ export const MANIFESTS = Object.freeze({
31
31
  "identity": {
32
32
  "repo": "imdotrino/dotrino-identity",
33
33
  "npm": "@dotrino/identity",
34
- "current": "0.132.0",
34
+ "current": "0.133.1",
35
35
  "protocol": 1,
36
36
  "requires": {
37
37
  "proxy-client": ">=0.13.1"
@@ -271,12 +271,12 @@ export const MANIFESTS = Object.freeze({
271
271
  "vault": {
272
272
  "repo": "imdotrino/dotrino-vault",
273
273
  "npm": "@dotrino/vault",
274
- "current": "0.111.0",
274
+ "current": "0.112.0",
275
275
  "protocol": 1,
276
276
  "requires": {
277
277
  "vaultd": ">=0.105.0",
278
278
  "proxy-client": ">=0.44.1",
279
- "identity": ">=0.132.0",
279
+ "identity": ">=0.133.1",
280
280
  "opaque": ">=0.1.0",
281
281
  "compat": ">=0.5.0",
282
282
  "roadmap": ">=0.4.26",
@@ -287,10 +287,10 @@ export const MANIFESTS = Object.freeze({
287
287
  "vaultd": {
288
288
  "repo": "imdotrino/dotrino-vault",
289
289
  "npm": "@dotrino/vaultd",
290
- "current": "0.184.0",
290
+ "current": "0.185.0",
291
291
  "protocol": 1,
292
292
  "requires": {
293
- "identity": ">=0.132.0",
293
+ "identity": ">=0.133.1",
294
294
  "proxy-client": ">=0.44.1",
295
295
  "store": ">=0.11.0",
296
296
  "passmanager": ">=0.18.6",
@@ -1,3 +1,3 @@
1
- Copia vendorizada de @dotrino/store/core@0.12.4 (dotrino-store/store/{core}.js).
1
+ Copia vendorizada de @dotrino/store/core@0.13.0 (dotrino-store/store/{core}.js).
2
2
  NO se edita a mano: la escribe `node vendor.mjs` y la vigila test/vendor-up-to-date.test.mjs.
3
3
  Las reglas del almacén (lápidas, páginas): las mismas en el store y en la bóveda.
@@ -31,6 +31,17 @@ export const TOMB_TTL_MS = 180 * 24 * 60 * 60 * 1000
31
31
  */
32
32
  export const PAGE_BYTES = 400_000
33
33
 
34
+ /**
35
+ * TOPE DEL RESPALDO EN UNA BÓVEDA, por cuenta (dueño, 2026-10-28). Al pasarlo se borra lo más
36
+ * viejo de la app que más ocupa: los adjuntos del messenger no se llevan las facturas. Lo
37
+ * grande va a un content server, no aquí. Borrar por tope NO es una lápida: la entrada sale
38
+ * de la bóveda y nada más, el aparato la conserva y deja de subirla (el SUELO del hilo).
39
+ */
40
+ export const VAULT_QUOTA_BYTES = 25 * 1024 * 1024
41
+
42
+ /** La app de un hilo que nadie anotó (escrito antes de que el almacén lo anotara). */
43
+ export const UNKNOWN_APP = '?'
44
+
34
45
  const encoder = new TextEncoder()
35
46
  export const byteLength = (value) => encoder.encode(typeof value === 'string' ? value : JSON.stringify(value)).length
36
47
 
@@ -62,18 +73,102 @@ export async function threadDigest (entries) {
62
73
  return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('')
63
74
  }
64
75
 
65
- /** Huella de cada hilo con entradas (o solo de `keys`, si se pasan). */
66
- export async function digestsOf (threads, keys) {
76
+ /**
77
+ * Huella de cada hilo con entradas (o solo de `keys`, si se pasan). Con `floors`, solo cuenta
78
+ * lo que está por encima del suelo de cada hilo: así el aparato compara con la bóveda lo que
79
+ * ella todavía guarda, y lo que borró por el tope no se vuelve a subir.
80
+ */
81
+ export async function digestsOf (threads, keys, floors = null) {
67
82
  const out = {}
68
83
  const list = Array.isArray(keys) ? keys.filter((k) => validKey(k) && has(threads, k)) : Object.keys(threads)
69
84
  for (const k of list) {
70
- const arr = threads[k]
71
- if (!Array.isArray(arr) || arr.length === 0) continue
85
+ const all = threads[k]
86
+ if (!Array.isArray(all)) continue
87
+ const arr = floors ? all.filter((e) => aboveFloor(floors, k, e)) : all
88
+ if (arr.length === 0) continue
72
89
  out[k] = { count: arr.length, digest: await threadDigest(arr) }
73
90
  }
74
91
  return out
75
92
  }
76
93
 
94
+ // ----- tope del respaldo -----
95
+
96
+ /** ¿Está la entrada por encima del suelo de su hilo? (`floors`: { [threadKey]: ts }) */
97
+ export function aboveFloor (floors, k, entry) {
98
+ return !has(floors, k) || (Number(entry?.ts) || 0) > floors[k]
99
+ }
100
+
101
+ /** La app que escribió un hilo (`owners`: { [threadKey]: 'messenger.dotrino.com' }). */
102
+ export function appOf (owners, k) {
103
+ return has(owners, k) && typeof owners[k] === 'string' && owners[k] ? owners[k] : UNKNOWN_APP
104
+ }
105
+
106
+ /** Sube los suelos de `floors` a los de `incoming` (el mayor de cada hilo). Devuelve si cambió algo. */
107
+ export function mergeFloors (floors, incoming) {
108
+ let changed = false
109
+ for (const [k, ts] of Object.entries(incoming || {})) {
110
+ if (!validKey(k) || typeof ts !== 'number') continue
111
+ if (has(floors, k) && floors[k] >= ts) continue
112
+ floors[k] = ts
113
+ changed = true
114
+ }
115
+ return changed
116
+ }
117
+
118
+ /** Quita lo que está en o por debajo del suelo. Devuelve los hilos que cambiaron. */
119
+ export function applyFloors (threads, floors) {
120
+ const changed = new Set()
121
+ for (const k of Object.keys(floors)) {
122
+ if (!has(threads, k)) continue
123
+ const kept = threads[k].filter((e) => aboveFloor(floors, k, e))
124
+ if (kept.length === threads[k].length) continue
125
+ if (kept.length) threads[k] = kept; else delete threads[k]
126
+ changed.add(k)
127
+ }
128
+ return changed
129
+ }
130
+
131
+ /**
132
+ * HACE CABER EL RESPALDO EN `maxBytes`: mientras se pase, sale la entrada más vieja de la app
133
+ * que más ocupa, y el suelo de su hilo sube a su `ts`. Es determinista: dos bóvedas con lo
134
+ * mismo borran lo mismo, y así la copia entre ellas no se persigue la cola.
135
+ *
136
+ * @returns {{ changed: Set<string>, evicted: number, bytes: number }}
137
+ */
138
+ export function enforceQuota (threads, owners, floors, { maxBytes = VAULT_QUOTA_BYTES } = {}) {
139
+ const apps = new Map()
140
+ let total = 0
141
+ for (const [k, arr] of Object.entries(threads)) {
142
+ const app = appOf(owners, k)
143
+ let a = apps.get(app)
144
+ if (!a) apps.set(app, (a = { bytes: 0, list: [], i: 0 }))
145
+ for (const e of arr) {
146
+ const size = byteLength(e)
147
+ a.bytes += size
148
+ a.list.push({ k, ts: Number(e?.ts) || 0, size })
149
+ total += size
150
+ }
151
+ }
152
+ if (total <= maxBytes) return { changed: new Set(), evicted: 0, bytes: total }
153
+ for (const a of apps.values()) a.list.sort((x, y) => x.ts - y.ts || (x.k < y.k ? -1 : x.k > y.k ? 1 : 0))
154
+ let evicted = 0
155
+ while (total > maxBytes) {
156
+ let big = null
157
+ for (const a of apps.values()) if (a.i < a.list.length && (!big || a.bytes > big.bytes)) big = a
158
+ if (!big) break
159
+ const { k, ts, size } = big.list[big.i++]
160
+ big.bytes -= size
161
+ total -= size
162
+ evicted++
163
+ if (!has(floors, k) || floors[k] < ts) floors[k] = ts
164
+ }
165
+ const changed = applyFloors(threads, floors)
166
+ // Lo que salió de más por empatar en `ts` con lo último que salió.
167
+ total = 0
168
+ for (const arr of Object.values(threads)) for (const e of arr) total += byteLength(e)
169
+ return { changed, evicted, bytes: total }
170
+ }
171
+
77
172
  // ----- lápidas -----
78
173
 
79
174
  export function tombOf (tombs, k, id) {
@@ -149,7 +244,7 @@ export function applyTombs (threads, tombs, incoming, now) {
149
244
  * gana la que llega (es una escritura de su dueño, no una copia vieja). Lo enterrado no
150
245
  * entra. Devuelve los hilos que cambiaron.
151
246
  */
152
- export function mergeEntries (threads, tombs, incoming, { mode = 'merge', max = MAX_PER_THREAD_LIMIT } = {}) {
247
+ export function mergeEntries (threads, tombs, incoming, { mode = 'merge', max = MAX_PER_THREAD_LIMIT, floors = null } = {}) {
153
248
  const changed = new Set()
154
249
  for (const [k, arr] of Object.entries(incoming || {})) {
155
250
  if (!validKey(k) || !Array.isArray(arr) || arr.length === 0) continue
@@ -160,6 +255,7 @@ export function mergeEntries (threads, tombs, incoming, { mode = 'merge', max =
160
255
  for (const e of arr) {
161
256
  if (!e || typeof e !== 'object' || e.id == null) continue
162
257
  if (isBuried(tombs, k, e)) continue
258
+ if (floors && !aboveFloor(floors, k, e)) continue
163
259
  const prev = byId.get(idOf(e))
164
260
  const ts = Number(e.ts) || 0
165
261
  const prevTs = Number(prev?.ts) || 0
@@ -1,4 +1,4 @@
1
- Copia vendorizada de @dotrino/vault@0.112.0 (dotrino-vault/lib/src/{admin,b64,browser,core/approvals,core/backup,core/blocked,core/browserDisk,core/commKey,core/disk,core/exNotices,core/gate,core/libVersion,core/logAnchor,core/machines,core/memberGroups,core/notices,core/notifiable,core/passwords,core/sealKey,core/sealer,core/sealers,core/secretsStore,core/sha256,core/store,core/subacta,core/threadStore,core/transport,core/vault,enroll,index,invite,loginClient,passwordLogins,procContext,protocol,revocation,sealed}.js).
1
+ Copia vendorizada de @dotrino/vault@0.113.0 (dotrino-vault/lib/src/{admin,b64,browser,core/approvals,core/backup,core/blocked,core/browserDisk,core/commKey,core/disk,core/exNotices,core/gate,core/libVersion,core/logAnchor,core/machines,core/memberGroups,core/notices,core/notifiable,core/passwords,core/sealKey,core/sealer,core/sealers,core/secretsStore,core/sha256,core/siblingBackup,core/store,core/subacta,core/threadStore,core/transport,core/vault,enroll,index,invite,loginClient,passwordLogins,procContext,protocol,revocation,sealed}.js).
2
2
  NO se edita a mano: la escribe `node vendor.mjs` y la vigila test/vendor-up-to-date.test.mjs.
3
3
  browser.js es la bóveda de esta pestaña: el MISMO núcleo que el binario (core/), con
4
4
  el disco en IndexedDB. Importa @dotrino/{compat,roadmap,passmanager,store/core} y
@@ -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.