@dotrino/identity 0.125.0 → 0.126.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.125.0",
3
+ "version": "0.126.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
@@ -348,6 +348,8 @@ export class Identity {
348
348
  async myMembership () { return this._call('myMembership') }
349
349
  /** La cadena de actas desde `sinceSeq` (ver la nota en `node.js`). */
350
350
  async actaHistory (opts) { return this._call('actaHistory', opts || {}) }
351
+ /** Los que estuvieron en las actas de la ventana del historial y ya no están. */
352
+ async pastMembers () { return this._call('pastMembers', {}) }
351
353
 
352
354
  /** ¿Es ESTE dispositivo el master (el único que puede cambiar el acta)? */
353
355
  async isMaster () { return this._call('isMaster') }
package/vault/core.js CHANGED
@@ -2894,6 +2894,29 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
2894
2894
  return { chain: all.sort((a, b) => a.seq - b.seq), window: ACTA_WINDOW }
2895
2895
  },
2896
2896
 
2897
+ /**
2898
+ * LOS QUE ESTUVIERON Y YA NO ESTÁN: las llaves de las actas que guarda la ventana del
2899
+ * historial (`ACTA_WINDOW`) que el acta actual ya no nombra. La bóveda les contesta, solo
2900
+ * a ellos y solo con su aviso de expulsión, para que se borren aunque no les llegara.
2901
+ * Fuera de la ventana no se sabe nada, y no se inventa.
2902
+ */
2903
+ async pastMembers () {
2904
+ const cur = loadActa()
2905
+ if (!cur) return { members: [] }
2906
+ const now = new Set((cur.members || []).map((m) => m.pub))
2907
+ const seen = new Map()
2908
+ // SOLO LA VENTANA: el historial guarda además los eslabones de la cadena de selladores
2909
+ // (el génesis, para siempre), y esos no cuentan.
2910
+ const ventana = loadHistory().filter((a) => a?.seq !== cur.seq && a?.seq > cur.seq - ACTA_WINDOW)
2911
+ for (const a of ventana) {
2912
+ for (const m of (a?.members || [])) {
2913
+ if (!m?.pub || now.has(m.pub)) continue
2914
+ if (!seen.has(m.pub) || a.seq > seen.get(m.pub)) seen.set(m.pub, a.seq)
2915
+ }
2916
+ }
2917
+ return { members: [...seen].map(([pub, lastSeq]) => ({ pub, lastSeq })) }
2918
+ },
2919
+
2897
2920
  /**
2898
2921
  * MI tarjeta de perfil: lo mínimo que se le pasa a un contacto para que pueda cifrarme a
2899
2922
  * todos mis dispositivos (perfil, versión y llaves de cifrado). Sin etiquetas, sin
package/vault/facade.js CHANGED
@@ -106,6 +106,8 @@ export class IdentityFacade {
106
106
  * sincronizar su acta. Se quedaba con la copia del día que emparejó.
107
107
  */
108
108
  actaHistory (opts) { return this._h('actaHistory', opts || {}) }
109
+ /** Los que estuvieron en las actas de la ventana y el acta actual ya no nombra. */
110
+ pastMembers () { return this._h('pastMembers') }
109
111
  isMaster () { return this._h('isMaster') }
110
112
  admitMember (member) { return this._h('admitMember', member) }
111
113
  /** Registra la llave de cifrado de un miembro ya admitido (evita re-enrolarlo). */
@@ -1,4 +1,4 @@
1
- Copia vendorizada de @dotrino/vault@0.96.0 (dotrino-vault/lib/src/{admin,b64,browser,core/approvals,core/backup,core/blocked,core/browserDisk,core/commKey,core/disk,core/libVersion,core/machines,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,loginClient,passwordLogins,procContext,protocol,revocation,sealed}.js).
1
+ Copia vendorizada de @dotrino/vault@0.99.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/machines,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,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,66 @@
1
+ /**
2
+ * exNotices.js — LOS AVISOS DE EXPULSIÓN YA FIRMADOS, uno por cada aparato que estuvo en las
3
+ * actas de la ventana del historial y ya no está (dueño, 2026-10-22).
4
+ *
5
+ * La bóveda solo atiende al acta (`gate.js`). A quien salió se le contesta UNA cosa —«¿sigo
6
+ * dentro?»— y la respuesta es su aviso, para que se borre aunque el que se le mandó al
7
+ * echarlo no le llegara (la cola del proxio dura 24 h). El aviso se firma una vez, con la
8
+ * bóveda abierta, y se guarda: contestar no firma nada, así que preguntar no sirve para que
9
+ * la maestra firme a pedido de nadie. Sin caducidad: tiene que valer el día que vuelva.
10
+ *
11
+ * Cifrado en reposo, como todo lo de la bóveda. Si no se puede leer, se para y se dice.
12
+ */
13
+ export const EX_NOTICES_FILE = 'exnotices.json'
14
+
15
+ const fail = (code, message) => Object.assign(new Error(message), { code })
16
+
17
+ export function openExNotices ({ disk }) {
18
+ const file = EX_NOTICES_FILE
19
+ const atRest = disk.atRest
20
+ /** pub → { body, signature } */
21
+ let items = load()
22
+
23
+ function load () {
24
+ let raw
25
+ try { raw = disk.read(file) } catch (e) {
26
+ throw fail('exnotices-unreadable', `cannot read ${EX_NOTICES_FILE}: ${e.message}`)
27
+ }
28
+ if (raw == null) return new Map()
29
+ let d
30
+ try { d = JSON.parse(atRest.decrypt(raw)) } catch (e) { throw fail('exnotices-unreadable', `${EX_NOTICES_FILE} cannot be opened: ${e.message}`) }
31
+ if (d?.v !== 1 || !d.items || typeof d.items !== 'object') throw fail('exnotices-unreadable', `${EX_NOTICES_FILE} has an unknown shape`)
32
+ return new Map(Object.entries(d.items))
33
+ }
34
+
35
+ function save () {
36
+ disk.write(file, atRest.encrypt(JSON.stringify({ v: 1, items: Object.fromEntries(items) })))
37
+ }
38
+
39
+ return {
40
+ has: (pub) => items.has(pub),
41
+ get: (pub) => items.get(pub) || null,
42
+ pubs: () => [...items.keys()],
43
+ /**
44
+ * Deja exactamente los avisos de `past` (los ex-miembros de la ventana): firma con `sign`
45
+ * los que falten y quita los de quien ya salió de la ventana. Devuelve cuántos firmó.
46
+ */
47
+ async sync (past, sign) {
48
+ const keep = new Set(past)
49
+ let changed = false
50
+ for (const pub of [...items.keys()]) if (!keep.has(pub)) { items.delete(pub); changed = true }
51
+ let signed = 0
52
+ for (const pub of keep) {
53
+ if (items.has(pub)) continue
54
+ // Sin `nonce` ni `exp`: habla del APARATO, no de un papel, y vale siempre.
55
+ const body = { op: 'revoke', sub: pub, iat: Date.now() }
56
+ items.set(pub, { body, signature: await sign(body) })
57
+ signed++
58
+ changed = true
59
+ }
60
+ if (changed) save()
61
+ return signed
62
+ }
63
+ }
64
+ }
65
+
66
+ export default { openExNotices, EX_NOTICES_FILE }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * gate.js — LA PUERTA DE LA BÓVEDA: solo atiende al acta (dueño, 2026-10-22).
3
+ *
4
+ * Una bóveda solo acepta mensajes de llaves que están en su acta. Hay dos excepciones, y
5
+ * ninguna más:
6
+ *
7
+ * · **Entrar con contraseña** (`LOGIN_*`): quien entra todavía no es nadie. Pasa solo eso,
8
+ * con freno por conexión y freno global, antes de cualquier trabajo.
9
+ * · **El alta de un aparato** (`HELLO`, `ENROLL`, `ACTA_SEALED`): solo mientras hay un
10
+ * emparejamiento abierto y el mensaje es de ESE emparejamiento. Fuera de eso, nada.
11
+ * · **Los que salieron** (`CHECK`): un aparato de las actas de la ventana que ya no está pasa
12
+ * solo a preguntar si sigue dentro, con su firma y con freno. Se le contesta con su aviso
13
+ * de expulsión ya firmado (`exNotices.js`), para que se borre.
14
+ *
15
+ * Lo demás se descarta EN SILENCIO: sin respuesta, sin firma, sin línea en la bitácora y sin
16
+ * tocar el disco. Antes un desconocido conseguía que la bóveda le contestara con el acta
17
+ * entera, que la maestra le firmara cosas y que la bitácora rotara hasta perder lo viejo; todo
18
+ * eso pasaba ANTES de mirar quién preguntaba. Lo descartado se cuenta en memoria (`stats`),
19
+ * para que `status` lo pueda enseñar.
20
+ *
21
+ * La firma del miembro se comprueba aquí y otra vez en el manejador, que además mira el papel
22
+ * y los permisos: esta puerta no autoriza nada, solo decide si se escucha.
23
+ */
24
+ import { verifyDeviceSig } from '@dotrino/identity/capabilities'
25
+
26
+ /** Freno por conexión y global, en memoria. Ventana fija: simple y suficiente. */
27
+ export function makeLimiter ({ perKey = 10, global = 120, windowMs = 60_000, maxKeys = 10_000, now = Date.now } = {}) {
28
+ let start = now()
29
+ let total = 0
30
+ let byKey = new Map()
31
+ return {
32
+ /** `true` si cabe; `false` si se pasó (de la conexión o del total). */
33
+ take (key) {
34
+ const t = now()
35
+ if (t - start >= windowMs) { start = t; total = 0; byKey = new Map() }
36
+ if (total >= global) return false
37
+ const n = byKey.get(key) || 0
38
+ if (n >= perKey) return false
39
+ // Un desconocido que abre miles de conexiones no puede llenar la memoria: al tope, ya
40
+ // no entra nadie nuevo hasta la siguiente ventana.
41
+ if (!byKey.has(key) && byKey.size >= maxKeys) return false
42
+ byKey.set(key, n + 1)
43
+ total++
44
+ return true
45
+ },
46
+ /** Cuánto falta para la siguiente ventana. */
47
+ waitMs: () => Math.max(0, windowMs - (now() - start))
48
+ }
49
+ }
50
+
51
+ /**
52
+ * QUIÉN DICE SER el que manda cada mensaje, y con qué lo prueba. `null` si el tipo no es de los
53
+ * que se atienden a un miembro. La llave tiene que estar en el acta y la firma ser suya.
54
+ */
55
+ export function claimOf (MSG, p) {
56
+ switch (p?.type) {
57
+ case MSG.SIGN: case MSG.GET: case MSG.STORE: case MSG.CHECK: case MSG.DEVICES:
58
+ case MSG.RENEW: case MSG.SECRETS: case MSG.ADMIN: case MSG.INCIDENT:
59
+ return { pub: p.data?.publickey, data: p.data, signature: p.signature }
60
+ case MSG.REWRAP_OK:
61
+ return { pub: p.cert?.sub, data: p.data, signature: p.signature }
62
+ case MSG.REPLICA_ACK:
63
+ return { pub: p.body?.publickey, data: p.body, signature: p.signature }
64
+ // La renuncia la firma el propio miembro dentro del registro; la comprueba el manejador.
65
+ case MSG.RENOUNCE: {
66
+ const r = p.data?.record || p.record
67
+ return { pub: r?.member, data: null, signature: null }
68
+ }
69
+ // El aviso de otra bóveda no va firmado: lo que se autentica es el acta, sellada. Aquí se
70
+ // exige que la haya sellado un miembro de la nuestra; `adoptActa` comprueba el sello.
71
+ case MSG.ADMIN_EVENT:
72
+ return { pub: p.acta?.sealedBy, data: null, signature: null }
73
+ default:
74
+ return null
75
+ }
76
+ }
77
+
78
+ /**
79
+ * @param {object} o
80
+ * @param {object} o.MSG los tipos del protocolo
81
+ * @param {() => Promise<object|null>} o.acta el acta vigente de esta bóveda
82
+ * @param {(type: string, p: object, from: string) => boolean} o.pairing ¿es de un emparejamiento abierto?
83
+ * @param {(pub: string) => boolean} [o.former] ¿estuvo en el acta (y tiene su aviso)?
84
+ * @param {ReturnType<typeof makeLimiter>} [o.limiter]
85
+ */
86
+ export function createGate ({ MSG, acta, pairing, former = () => false, limiter = makeLimiter(), verify = verifyDeviceSig }) {
87
+ const LOGIN = new Set([MSG.LOGIN_START, MSG.LOGIN_FINISH, MSG.LOGIN_CLOSE])
88
+ const PAIRING = new Set([MSG.HELLO, MSG.ENROLL, MSG.ACTA_SEALED])
89
+ const stats = { dropped: 0, throttled: 0, since: Date.now() }
90
+
91
+ async function admit (from, p) {
92
+ const type = p?.type
93
+ if (LOGIN.has(type)) {
94
+ if (limiter.take(String(from))) return { ok: true }
95
+ stats.throttled++
96
+ return { ok: false, throttled: true, waitMs: limiter.waitMs() }
97
+ }
98
+ if (PAIRING.has(type)) {
99
+ if (pairing(type, p, from)) return { ok: true }
100
+ stats.dropped++
101
+ return { ok: false }
102
+ }
103
+ const claim = claimOf(MSG, p)
104
+ if (!claim || typeof claim.pub !== 'string' || !claim.pub) { stats.dropped++; return { ok: false } }
105
+ // NADA QUE DECIDIR SIN ACTA: se para (no hay a quién atender), no se deja pasar.
106
+ const record = await acta()
107
+ if (!record) { stats.dropped++; return { ok: false } }
108
+ const member = (record.members || []).some((m) => m?.pub === claim.pub)
109
+ // Un ex-miembro, solo a preguntar si sigue dentro, y con freno.
110
+ const leaving = !member && type === MSG.CHECK && former(claim.pub)
111
+ if (!member && !leaving) { stats.dropped++; return { ok: false } }
112
+ if (leaving && !limiter.take('check:' + from)) { stats.throttled++; return { ok: false } }
113
+ if (claim.signature !== null) {
114
+ const ok = typeof claim.signature === 'string' && claim.data &&
115
+ await verify({ publickey: claim.pub, data: claim.data, signature: claim.signature }).catch(() => false)
116
+ if (!ok) { stats.dropped++; return { ok: false } }
117
+ }
118
+ return { ok: true }
119
+ }
120
+
121
+ return { admit, stats: () => ({ ...stats }) }
122
+ }
123
+
124
+ export default { createGate, makeLimiter, claimOf }
@@ -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.96.0'
8
+ export const LIB_VERSION = '0.99.0'
@@ -85,6 +85,21 @@ export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey
85
85
 
86
86
  await client.connect()
87
87
 
88
+ // LO ENCOLADO LLEGA AL IDENTIFICARSE, y quien monta la bóveda todavía no escucha: pone su
89
+ // oyente cuando ya tiene todo listo, bastante después. Sin esto, lo que el proxio guardaba
90
+ // para una bóveda dormida —el acta nueva que sacó la otra bóveda, un pedido— se entregaba
91
+ // a nadie y se perdía. Se guarda aquí hasta que llegue el oyente (`listen`).
92
+ let early = []
93
+ const offEarly = client.on('message', (from, payload) => { early?.push([from, payload]) })
94
+ const listen = (fn) => {
95
+ const off = client.on('message', fn)
96
+ const pending = early || []
97
+ early = null
98
+ try { offEarly?.() } catch (_) {}
99
+ for (const [from, payload] of pending) { try { fn(from, payload) } catch (_) {} }
100
+ return off
101
+ }
102
+
88
103
  const identify = async () => {
89
104
  identified = false
90
105
  if (!client.token) return
@@ -195,6 +210,11 @@ export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey
195
210
  if (!comm || !seenActa) { log('[vault] cannot register the wake URL: no communication key in the record yet'); return }
196
211
  try {
197
212
  await client.registerWake({ publicKey: comm, sign: (d) => commKey.sign(d), url: wakeUrl, acta: seenActa, channel: announce || undefined })
213
+ // Y POR SU PROPIA LLAVE. Lo dirigido a la cuenta solo la despierta si no hay nadie más
214
+ // de la cuenta conectado; con otra bóveda encendida, nunca. La consola que elige ESTA
215
+ // bóveda le escribe a su llave de comunicación (`vault` en el acta), y es por ella
216
+ // por donde tiene que despertarse.
217
+ await client.registerWake({ publicKey: comm, sign: (d) => commKey.sign(d), url: wakeUrl, acta: seenActa, self: true })
198
218
  log('[vault] wake URL registered on the proxy')
199
219
  } catch (e) {
200
220
  log(`[vault] could not register the wake URL (${e.code || ''} ${e.message}) — the proxy will not wake this vault`)
@@ -286,5 +306,5 @@ export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey
286
306
  }, RECHECK_MS)
287
307
  watchdog.unref?.()
288
308
 
289
- return { client, token: client.token, identify: identifyWithRetry, isIdentified: () => identified }
309
+ return { client, token: client.token, identify: identifyWithRetry, isIdentified: () => identified, listen }
290
310
  }
@@ -25,6 +25,7 @@ import { openThreadStore, STORE_READ_METHODS, PROFILE_EDIT_METHODS } from './thr
25
25
  import { openSecretsStore, assertVar, RECOVERY as RECOVERY_WRAP, PROFILE_OWNER } from './secretsStore.js'
26
26
  import { openSubacta } from './subacta.js'
27
27
  import { openBlocked } from './blocked.js'
28
+ import { openExNotices } from './exNotices.js'
28
29
  import { openNotifiable } from './notifiable.js'
29
30
  import { openMachines } from './machines.js'
30
31
  import { machineLine } from '@dotrino/identity/machine'
@@ -46,6 +47,7 @@ import { openCommKey, COMM_CN, COMM_CAPS } from './commKey.js'
46
47
  import { seal } from '../sealed.js'
47
48
  import { MSG, SCOPE, secretsScope, isValidSecretsNs, VAULT_PROTOCOL, VAULT_SPEAKS } from '../protocol.js'
48
49
  import { sha256Hex } from './sha256.js'
50
+ import { createGate } from './gate.js'
49
51
 
50
52
  const b64ToBytes = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0))
51
53
  const byteLength = (s) => new TextEncoder().encode(s).length
@@ -264,6 +266,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
264
266
  const passwordsAtRest = disk.atRest
265
267
  // Los aparatos BLOQUEADOS por un aprobador (`src/blocked.js`). Cifrado en reposo como lo demás.
266
268
  const blocked = openBlocked({ disk })
269
+ const exNotices = openExNotices({ disk })
267
270
  // Qué aprobadores dijeron que pueden recibir avisos (`src/notifiable.js`). No decide nada: se enseña.
268
271
  const notifiable = openNotifiable({ disk })
269
272
  // Dónde corre cada aparato, según lo último que dijo firmado (`src/machines.js`). Se enseña.
@@ -472,15 +475,36 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
472
475
  * maestra o quedándose mudos. Se vio el 2026-09-02: de dos perfiles, el que tenía
473
476
  * contraseña era el que no tenía `commkey.json`.
474
477
  */
478
+ /**
479
+ * LOS AVISOS DE LOS QUE SALIERON (`exNotices.js`): uno firmado por cada aparato de las actas
480
+ * de la ventana que ya no está. Solo con la bóveda ABIERTA y si esta sella: cerrada no firma.
481
+ */
482
+ async function syncExNotices () {
483
+ try {
484
+ if (isLocked() || identity.masterLocked || !(await identity.isMaster?.())) return
485
+ const past = ((await identity.pastMembers()).members || []).map((m) => m.pub)
486
+ const n = await exNotices.sync(past, async (body) => (await identity.signData(body)).signature)
487
+ if (n) log(`[vault] signed the leaving notice of ${n} former member(s): they get it when they ask`)
488
+ } catch (e) { log('[vault] could not prepare the notices for former members:', e.message) }
489
+ }
490
+
475
491
  async function ensureCommKeyInActa () {
476
492
  try {
477
493
  const info = await identity.profileActa?.()
478
494
  const acta = info?.acta
479
495
  if (!acta || isLocked() || identity.masterLocked) return false
480
496
  const pub = await commKey.ensure()
481
- if ((acta.members || []).some((m) => m?.pub === pub)) return false
497
+ const mine = (acta.members || []).find((m) => m?.pub === pub)
482
498
  if (!info?.isMaster) return false
483
- await identity.admitMember({ pub, label: 'esta bóveda', cn: COMM_CN, caps: [...COMM_CAPS] })
499
+ // DE QUÉ BÓVEDA ES (`vault`: esta maestra). Con dos bóvedas en la cuenta es lo único que
500
+ // deja a la consola escribirle a una sola. A la llave que entró antes del campo se le pone.
501
+ if (mine) {
502
+ if (mine.vault || !master) return false
503
+ await identity.setMemberVault({ pub, vault: master })
504
+ log('[vault] the record now says which vault this communication key speaks for')
505
+ return true
506
+ }
507
+ await identity.admitMember({ pub, label: 'esta bóveda', cn: COMM_CN, caps: [...COMM_CAPS], ...(master ? { vault: master } : {}) })
484
508
  log('[vault] this vault is now a member of its own record: it talks with its own key, not the master one')
485
509
  return true
486
510
  } catch (e) {
@@ -488,12 +512,14 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
488
512
  return false
489
513
  }
490
514
  }
491
- await ensureCommKeyInActa()
515
+ // Lo que se selló aquí se anuncia cuando ya hay transporte (más abajo): sin el aviso, la otra
516
+ // bóveda de la cuenta no se entera y las dos acaban con actas distintas del mismo número.
517
+ const commSealedAtStart = await ensureCommKeyInActa()
492
518
 
493
519
  // `announce`: el canal de ESTA cuenta, para que una máquina prestada —que no tiene
494
520
  // ninguna llave y solo sabe la dirección `nombre@AB12-CD34-EF56`— pueda encontrar a quien
495
521
  // la atiende. Lo construye la pieza compartida, porque quien lo busca es la extensión.
496
- const { client, identify: reidentify, isIdentified } = await createTransport({
522
+ const { client, identify: reidentify, isIdentified, listen } = await createTransport({
497
523
  identity, url: proxyUrl, commKey, log, announce: vaultChannel(fp), makeClient: platform.makeClient || null, wakeUrl: platform.wakeUrl || null
498
524
  })
499
525
 
@@ -501,6 +527,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
501
527
  // que le dicen a un tercero si esta cuenta sigue sellada por quien él cree. Ver
502
528
  // `sealers.js` — es una comodidad para quien lee, nunca una dependencia de la bóveda.
503
529
  startSealersPublisher({ identity, client, log })
530
+ if (commSealedAtStart) await notifyMembers('commkey')
531
+ await syncExNotices()
504
532
 
505
533
  async function revocationSet () {
506
534
  const { revoked } = await identity.listDelegations()
@@ -1309,9 +1337,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
1309
1337
  }
1310
1338
  const record = (await identity.profileActa?.().catch(() => null))?.acta || null
1311
1339
  const inside = (record?.members || []).some((m) => m?.pub === pub)
1312
- audit('check', { device: await deviceIdOf(pub).catch(() => null), in: inside })
1340
+ // Solo de los de dentro: un ex-miembro pregunta con freno y no escribe en la bitácora.
1341
+ if (inside) audit('check', { device: await deviceIdOf(pub).catch(() => null), in: true })
1313
1342
  if (inside) return reply(from, { type: MSG.CHECKED, in: true })
1314
- await notifyIfRevoked(pub, null, null, 'revoked')
1343
+ // UN EX-MIEMBRO: su aviso, el que se firmó una vez (`exNotices`). Primero el aviso y luego
1344
+ // el «no»: el aparato deja de escuchar al recibir el «no». Aquí no se firma nada.
1345
+ const notice = exNotices.get(pub)
1346
+ if (notice) reply(from, { type: MSG.REVOKED, body: notice.body, signature: notice.signature })
1315
1347
  reply(from, { type: MSG.CHECKED, in: false })
1316
1348
  }
1317
1349
 
@@ -2218,7 +2250,17 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2218
2250
  reply(from, { type: MSG.INCIDENT_RESULT, id: pend.id, approvers, blocked: false })
2219
2251
  }
2220
2252
 
2221
- client.on('message', (from, payload) => {
2253
+ // LA PUERTA (`gate.js`): solo el acta; entrar con contraseña con freno, y el alta solo
2254
+ // mientras hay un emparejamiento abierto. Lo demás se descarta sin contestar.
2255
+ const gate = createGate({
2256
+ MSG,
2257
+ acta: async () => (await identity.profileActa?.().catch(() => null))?.acta || null,
2258
+ pairing: (type, p) => desk.ownsPairing(type, p),
2259
+ former: (pub) => exNotices.has(pub)
2260
+ })
2261
+
2262
+ // `listen` y no `client.on`: entrega también lo que llegó encolado antes de este punto.
2263
+ listen((from, payload) => {
2222
2264
  // Quien monta la bóveda puede querer saber que hay trabajo (la Lambda se apaga cuando
2223
2265
  // deja de haberlo). Es un aviso, no decide nada.
2224
2266
  try { platform.onActivity?.() } catch (_) {}
@@ -2241,6 +2283,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2241
2283
 
2242
2284
  async function onMessage (from, payload) {
2243
2285
  if (!payload || typeof payload !== 'object') return
2286
+ const pass = await gate.admit(from, payload)
2287
+ if (!pass.ok) {
2288
+ // Al que entra con contraseña sí se le dice que espere: es la única puerta abierta a
2289
+ // desconocidos, y quien teclea su contraseña tiene que saber por qué no contesta.
2290
+ if (pass.throttled) reply(from, { type: MSG.ERROR, error: 'too many tries: wait before trying again', code: 'too-many-tries', waitMs: pass.waitMs })
2291
+ return
2292
+ }
2244
2293
  try {
2245
2294
  if (payload.type === MSG.HELLO) return desk.handleHello(from, payload)
2246
2295
  if (payload.type === MSG.ENROLL) return await desk.handleEnroll(from, payload)
@@ -2536,6 +2585,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2536
2585
  * `sendByPubkey`, así que al que está apagado le llega cuando encienda (cola 24 h).
2537
2586
  */
2538
2587
  async function notifyMembers (ev, info = {}) {
2588
+ // El acta pudo cambiar (alguien salió): su aviso tiene que estar listo para cuando pregunte.
2589
+ await syncExNotices()
2539
2590
  try {
2540
2591
  // SIN FIRMA, y no falta nada: quien lo usa es el ACTA que viaja al lado, que se
2541
2592
  // autentica sola (otra bóveda la adopta por `canAdopt`; el teléfono solo refresca y
@@ -2606,6 +2657,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2606
2657
  async function handleReplicaAck (from, p) {
2607
2658
  const body = p?.body
2608
2659
  if (!body || body.op !== 'replica.ack') return
2660
+ // Fresco, o un acuse capturado serviría para hacer empujar a la bóveda cuando quisiera.
2661
+ if (!isFresh(body)) return
2609
2662
  const record = (await identity.profileActa?.().catch(() => null))?.acta || null
2610
2663
  if (!record) return
2611
2664
  // LA LLAVE VA DENTRO DEL MENSAJE FIRMADO, no se saca de `from`: `from` es el
@@ -4264,6 +4317,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
4264
4317
  // Alcanzable ≠ corriendo: si el proxio rechazó el `identify` esta bóveda está viva y
4265
4318
  // nadie puede hablarle. Lo mira `status` (ver `manager.js`, `summary`).
4266
4319
  isIdentified,
4320
+ // Lo que la puerta descartó (`gate.js`): desconocidos y pedidos de entrar frenados.
4321
+ gateStats: () => gate.stats(),
4267
4322
  // Se expone para poder PROBAR que una respuesta que no cabe no mata la conexión: es el
4268
4323
  // único punto por el que sale todo, y el fallo que cierra vive justo ahí.
4269
4324
  reply,
@@ -4293,7 +4348,10 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
4293
4348
  // la bóveda seguía muda en el proxio con su llave ya admitida en el acta. Al dueño le
4294
4349
  // pasó el 2026-09-05: hizo lo que el log pedía y la consola siguió sin contestar.
4295
4350
  if (r?.locked === false) {
4296
- try { if (await ensureCommKeyInActa()) await reidentify?.() } catch (_) {}
4351
+ try {
4352
+ if (await ensureCommKeyInActa()) { await reidentify?.(); await notifyMembers('commkey') }
4353
+ } catch (_) {}
4354
+ await syncExNotices()
4297
4355
  }
4298
4356
  // Y ABSORBER LO PENDIENTE. La subacta ya lo estaba honrando con el perfil cerrado —de
4299
4357
  // eso vive—, pero mientras siga ahí solo lo sabe esta máquina: al sellarlo, entra en
@@ -504,7 +504,10 @@ export function createEnrollDesk ({
504
504
  */
505
505
  async function handleActaSealed (from, p) {
506
506
  const record = p?.acta
507
- const pend = [...pending.values()].find((x) => x.state === 'AWAITING_ACTA' && (x.from === from || x.dpub))
507
+ // LA SESIÓN ES LA DEL APARATO QUE SELLÓ EL ACTA. Esto buscaba «la del mismo token o
508
+ // cualquiera con `dpub`», o sea la primera que esperara un acta, viniera de quien viniera.
509
+ // Quien sella es lo que identifica al emparejamiento (el token cambia si reconecta).
510
+ const pend = [...pending.values()].find((x) => x.state === 'AWAITING_ACTA' && x.dpub && x.dpub === record?.sealedBy)
508
511
  if (!pend) return fail(from, 'no adoption awaiting a record', pend?.sn)
509
512
  if (!record || typeof record !== 'object') return fail(from, 'record missing or unreadable', pend?.sn)
510
513
  // Ya no hay campo `sealer`: se le pregunta al PERMISO. Es la misma comprobación —«¿me
@@ -604,7 +607,23 @@ export function createEnrollDesk ({
604
607
  return res
605
608
  }
606
609
 
610
+ /**
611
+ * ¿Es este mensaje de un emparejamiento que ESTA bóveda tiene abierto (o acaba de cerrar)?
612
+ * Es la puerta del alta (`core/gate.js`): fuera de un emparejamiento, el alta no existe y lo
613
+ * que llegue se descarta sin contestar.
614
+ */
615
+ function ownsPairing (type, p) {
616
+ if (type === MSG_HELLO) { const sn = String(p?.sn || ''); return !!sn && (pending.has(sn) || gone.has(sn)) }
617
+ if (type === MSG_ENROLL) { const tk = String(p?.data?.token || ''); return !!tk && (pending.has(tk) || gone.has(tk)) }
618
+ if (type === MSG_ACTA_SEALED) {
619
+ const by = p?.acta?.sealedBy
620
+ return !!by && [...pending.values()].some((x) => x.state === 'AWAITING_ACTA' && x.dpub === by)
621
+ }
622
+ return false
623
+ }
624
+
607
625
  return {
626
+ ownsPairing,
608
627
  startPairing, stopPairing, handleEnroll, handleActaSealed, handleHello, approve, reject,
609
628
  listPending, findPending, emitRevoke, revoke, revokeDevice,
610
629
  get pendingCount () { return pending.size }
@@ -202,6 +202,14 @@ export function createLoginDesk ({ load, save, now = () => Date.now(), opaque =
202
202
 
203
203
  /** Intercambios a medias: viven en memoria, y por eso un reinicio los tira. */
204
204
  const exchanges = new Map()
205
+ /** Tope de intercambios a medias: un desconocido no puede llenar la memoria abriéndolos. */
206
+ const MAX_EXCHANGES = 1000
207
+ /**
208
+ * EL FRENO DE LOS USUARIOS QUE NO EXISTEN, en memoria. Sin él, tras cinco intentos solo los
209
+ * usuarios reales contestaban «espera», y eso decía cuáles existen. Así frenan igual.
210
+ */
211
+ const ghosts = new Map()
212
+ const MAX_GHOSTS = 5000
205
213
 
206
214
  const read = () => {
207
215
  const s = load()
@@ -319,8 +327,14 @@ export function createLoginDesk ({ load, save, now = () => Date.now(), opaque =
319
327
  if (typeof request !== 'string' || !request) throw err('bad-input', 'request required')
320
328
  const u = isValidUser(user) ? state.users[user] || null : null
321
329
  const t = now()
322
- if (u?.nextTryAt && u.nextTryAt > t) {
323
- throw Object.assign(err('too-many-tries', 'too many tries: wait before trying again'), { waitMs: u.nextTryAt - t })
330
+ const ghostKey = String(user || '').slice(0, 64)
331
+ let ghost = u ? null : ghosts.get(ghostKey) || null
332
+ const next = u ? u.nextTryAt : ghost?.nextTryAt
333
+ if (next && next > t) {
334
+ throw Object.assign(err('too-many-tries', 'too many tries: wait before trying again'), { waitMs: next - t })
335
+ }
336
+ if (exchanges.size >= MAX_EXCHANGES) {
337
+ throw Object.assign(err('too-many-tries', 'too many logins in progress: wait before trying again'), { waitMs: EXCHANGE_TTL_MS })
324
338
  }
325
339
  // EL INTENTO SE CUENTA AQUÍ. Ver el comentario del freno: quien prueba una contraseña
326
340
  // puede no mandar nunca el último mensaje, así que si se contara al final no se
@@ -328,7 +342,16 @@ export function createLoginDesk ({ load, save, now = () => Date.now(), opaque =
328
342
  if (u) {
329
343
  u.fails = (u.fails || 0) + 1
330
344
  u.nextTryAt = t + backoffFor(u.fails)
345
+ } else {
346
+ if (!ghost) {
347
+ if (ghosts.size >= MAX_GHOSTS) ghosts.delete(ghosts.keys().next().value)
348
+ ghost = { fails: 0, nextTryAt: 0 }
349
+ ghosts.set(ghostKey, ghost)
350
+ }
351
+ ghost.fails++
352
+ ghost.nextTryAt = t + backoffFor(ghost.fails)
331
353
  }
354
+ const freshSetup = !state.setup
332
355
  const setup = await setupOf(state)
333
356
  const { state: serverState, response } = await opaque.loginStart({
334
357
  setup,
@@ -339,7 +362,10 @@ export function createLoginDesk ({ load, save, now = () => Date.now(), opaque =
339
362
  })
340
363
  const lid = crypto.randomUUID()
341
364
  exchanges.set(lid, { user: String(user || ''), known: !!u, state: serverState, at: t })
342
- save(state)
365
+ // Solo se escribe el disco por un usuario que existe (su freno tiene que sobrevivir a un
366
+ // reinicio) o la primera vez, cuando nace la configuración. Por uno inventado no: si no,
367
+ // cada intento de un desconocido reescribía el archivo.
368
+ if (u || freshSetup) save(state)
343
369
  return { lid, response }
344
370
  },
345
371