@dotrino/vaultd 0.169.0 → 0.171.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.
@@ -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.97.0'
8
+ export const LIB_VERSION = '0.99.0'
@@ -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,6 +475,19 @@ 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?.()
@@ -512,6 +528,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
512
528
  // `sealers.js` — es una comodidad para quien lee, nunca una dependencia de la bóveda.
513
529
  startSealersPublisher({ identity, client, log })
514
530
  if (commSealedAtStart) await notifyMembers('commkey')
531
+ await syncExNotices()
515
532
 
516
533
  async function revocationSet () {
517
534
  const { revoked } = await identity.listDelegations()
@@ -1320,9 +1337,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
1320
1337
  }
1321
1338
  const record = (await identity.profileActa?.().catch(() => null))?.acta || null
1322
1339
  const inside = (record?.members || []).some((m) => m?.pub === pub)
1323
- 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 })
1324
1342
  if (inside) return reply(from, { type: MSG.CHECKED, in: true })
1325
- 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 })
1326
1347
  reply(from, { type: MSG.CHECKED, in: false })
1327
1348
  }
1328
1349
 
@@ -2229,6 +2250,15 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2229
2250
  reply(from, { type: MSG.INCIDENT_RESULT, id: pend.id, approvers, blocked: false })
2230
2251
  }
2231
2252
 
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
+
2232
2262
  // `listen` y no `client.on`: entrega también lo que llegó encolado antes de este punto.
2233
2263
  listen((from, payload) => {
2234
2264
  // Quien monta la bóveda puede querer saber que hay trabajo (la Lambda se apaga cuando
@@ -2253,6 +2283,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2253
2283
 
2254
2284
  async function onMessage (from, payload) {
2255
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
+ }
2256
2293
  try {
2257
2294
  if (payload.type === MSG.HELLO) return desk.handleHello(from, payload)
2258
2295
  if (payload.type === MSG.ENROLL) return await desk.handleEnroll(from, payload)
@@ -2548,6 +2585,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2548
2585
  * `sendByPubkey`, así que al que está apagado le llega cuando encienda (cola 24 h).
2549
2586
  */
2550
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()
2551
2590
  try {
2552
2591
  // SIN FIRMA, y no falta nada: quien lo usa es el ACTA que viaja al lado, que se
2553
2592
  // autentica sola (otra bóveda la adopta por `canAdopt`; el teléfono solo refresca y
@@ -2618,6 +2657,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
2618
2657
  async function handleReplicaAck (from, p) {
2619
2658
  const body = p?.body
2620
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
2621
2662
  const record = (await identity.profileActa?.().catch(() => null))?.acta || null
2622
2663
  if (!record) return
2623
2664
  // LA LLAVE VA DENTRO DEL MENSAJE FIRMADO, no se saca de `from`: `from` es el
@@ -4276,6 +4317,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
4276
4317
  // Alcanzable ≠ corriendo: si el proxio rechazó el `identify` esta bóveda está viva y
4277
4318
  // nadie puede hablarle. Lo mira `status` (ver `manager.js`, `summary`).
4278
4319
  isIdentified,
4320
+ // Lo que la puerta descartó (`gate.js`): desconocidos y pedidos de entrar frenados.
4321
+ gateStats: () => gate.stats(),
4279
4322
  // Se expone para poder PROBAR que una respuesta que no cabe no mata la conexión: es el
4280
4323
  // único punto por el que sale todo, y el fallo que cierra vive justo ahí.
4281
4324
  reply,
@@ -4308,6 +4351,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
4308
4351
  try {
4309
4352
  if (await ensureCommKeyInActa()) { await reidentify?.(); await notifyMembers('commkey') }
4310
4353
  } catch (_) {}
4354
+ await syncExNotices()
4311
4355
  }
4312
4356
  // Y ABSORBER LO PENDIENTE. La subacta ya lo estaba honrando con el perfil cerrado —de
4313
4357
  // eso vive—, pero mientras siga ahí solo lo sabe esta máquina: al sellarlo, entra en
package/lib/src/enroll.js CHANGED
@@ -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
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/vaultd",
3
- "version": "0.169.0",
3
+ "version": "0.171.0",
4
4
  "type": "module",
5
5
  "description": "Certificador personal de Dotrino: daemon headless que custodia la clave maestra y delega capacidades a tus dispositivos por el proxy. Tu CA propia.",
6
6
  "bin": {
@@ -22,7 +22,7 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@dotrino/compat": "0.4.0",
25
- "@dotrino/identity": "0.125.0",
25
+ "@dotrino/identity": "0.126.0",
26
26
  "@dotrino/opaque": "0.1.0",
27
27
  "@dotrino/passmanager": "0.18.4",
28
28
  "@dotrino/proxy-client": "0.39.0",