@dotrino/identity 0.125.0 → 0.125.1
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 +1 -1
- package/vault/vendor/vault/VERSION.txt +1 -1
- package/vault/vendor/vault/core/gate.js +115 -0
- package/vault/vendor/vault/core/libVersion.js +1 -1
- package/vault/vendor/vault/core/transport.js +21 -1
- package/vault/vendor/vault/core/vault.js +40 -6
- package/vault/vendor/vault/enroll.js +20 -1
- package/vault/vendor/vault/passwordLogins.js +29 -3
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Copia vendorizada de @dotrino/vault@0.
|
|
1
|
+
Copia vendorizada de @dotrino/vault@0.98.0 (dotrino-vault/lib/src/{admin,b64,browser,core/approvals,core/backup,core/blocked,core/browserDisk,core/commKey,core/disk,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,115 @@
|
|
|
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
|
+
*
|
|
12
|
+
* Lo demás se descarta EN SILENCIO: sin respuesta, sin firma, sin línea en la bitácora y sin
|
|
13
|
+
* tocar el disco. Antes un desconocido conseguía que la bóveda le contestara con el acta
|
|
14
|
+
* entera, que la maestra le firmara cosas y que la bitácora rotara hasta perder lo viejo; todo
|
|
15
|
+
* eso pasaba ANTES de mirar quién preguntaba. Lo descartado se cuenta en memoria (`stats`),
|
|
16
|
+
* para que `status` lo pueda enseñar.
|
|
17
|
+
*
|
|
18
|
+
* La firma del miembro se comprueba aquí y otra vez en el manejador, que además mira el papel
|
|
19
|
+
* y los permisos: esta puerta no autoriza nada, solo decide si se escucha.
|
|
20
|
+
*/
|
|
21
|
+
import { verifyDeviceSig } from '@dotrino/identity/capabilities'
|
|
22
|
+
|
|
23
|
+
/** Freno por conexión y global, en memoria. Ventana fija: simple y suficiente. */
|
|
24
|
+
export function makeLimiter ({ perKey = 10, global = 120, windowMs = 60_000, maxKeys = 10_000, now = Date.now } = {}) {
|
|
25
|
+
let start = now()
|
|
26
|
+
let total = 0
|
|
27
|
+
let byKey = new Map()
|
|
28
|
+
return {
|
|
29
|
+
/** `true` si cabe; `false` si se pasó (de la conexión o del total). */
|
|
30
|
+
take (key) {
|
|
31
|
+
const t = now()
|
|
32
|
+
if (t - start >= windowMs) { start = t; total = 0; byKey = new Map() }
|
|
33
|
+
if (total >= global) return false
|
|
34
|
+
const n = byKey.get(key) || 0
|
|
35
|
+
if (n >= perKey) return false
|
|
36
|
+
// Un desconocido que abre miles de conexiones no puede llenar la memoria: al tope, ya
|
|
37
|
+
// no entra nadie nuevo hasta la siguiente ventana.
|
|
38
|
+
if (!byKey.has(key) && byKey.size >= maxKeys) return false
|
|
39
|
+
byKey.set(key, n + 1)
|
|
40
|
+
total++
|
|
41
|
+
return true
|
|
42
|
+
},
|
|
43
|
+
/** Cuánto falta para la siguiente ventana. */
|
|
44
|
+
waitMs: () => Math.max(0, windowMs - (now() - start))
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* QUIÉN DICE SER el que manda cada mensaje, y con qué lo prueba. `null` si el tipo no es de los
|
|
50
|
+
* que se atienden a un miembro. La llave tiene que estar en el acta y la firma ser suya.
|
|
51
|
+
*/
|
|
52
|
+
export function claimOf (MSG, p) {
|
|
53
|
+
switch (p?.type) {
|
|
54
|
+
case MSG.SIGN: case MSG.GET: case MSG.STORE: case MSG.CHECK: case MSG.DEVICES:
|
|
55
|
+
case MSG.RENEW: case MSG.SECRETS: case MSG.ADMIN: case MSG.INCIDENT:
|
|
56
|
+
return { pub: p.data?.publickey, data: p.data, signature: p.signature }
|
|
57
|
+
case MSG.REWRAP_OK:
|
|
58
|
+
return { pub: p.cert?.sub, data: p.data, signature: p.signature }
|
|
59
|
+
case MSG.REPLICA_ACK:
|
|
60
|
+
return { pub: p.body?.publickey, data: p.body, signature: p.signature }
|
|
61
|
+
// La renuncia la firma el propio miembro dentro del registro; la comprueba el manejador.
|
|
62
|
+
case MSG.RENOUNCE: {
|
|
63
|
+
const r = p.data?.record || p.record
|
|
64
|
+
return { pub: r?.member, data: null, signature: null }
|
|
65
|
+
}
|
|
66
|
+
// El aviso de otra bóveda no va firmado: lo que se autentica es el acta, sellada. Aquí se
|
|
67
|
+
// exige que la haya sellado un miembro de la nuestra; `adoptActa` comprueba el sello.
|
|
68
|
+
case MSG.ADMIN_EVENT:
|
|
69
|
+
return { pub: p.acta?.sealedBy, data: null, signature: null }
|
|
70
|
+
default:
|
|
71
|
+
return null
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* @param {object} o
|
|
77
|
+
* @param {object} o.MSG los tipos del protocolo
|
|
78
|
+
* @param {() => Promise<object|null>} o.acta el acta vigente de esta bóveda
|
|
79
|
+
* @param {(type: string, p: object, from: string) => boolean} o.pairing ¿es de un emparejamiento abierto?
|
|
80
|
+
* @param {ReturnType<typeof makeLimiter>} [o.limiter]
|
|
81
|
+
*/
|
|
82
|
+
export function createGate ({ MSG, acta, pairing, limiter = makeLimiter(), verify = verifyDeviceSig }) {
|
|
83
|
+
const LOGIN = new Set([MSG.LOGIN_START, MSG.LOGIN_FINISH, MSG.LOGIN_CLOSE])
|
|
84
|
+
const PAIRING = new Set([MSG.HELLO, MSG.ENROLL, MSG.ACTA_SEALED])
|
|
85
|
+
const stats = { dropped: 0, throttled: 0, since: Date.now() }
|
|
86
|
+
|
|
87
|
+
async function admit (from, p) {
|
|
88
|
+
const type = p?.type
|
|
89
|
+
if (LOGIN.has(type)) {
|
|
90
|
+
if (limiter.take(String(from))) return { ok: true }
|
|
91
|
+
stats.throttled++
|
|
92
|
+
return { ok: false, throttled: true, waitMs: limiter.waitMs() }
|
|
93
|
+
}
|
|
94
|
+
if (PAIRING.has(type)) {
|
|
95
|
+
if (pairing(type, p, from)) return { ok: true }
|
|
96
|
+
stats.dropped++
|
|
97
|
+
return { ok: false }
|
|
98
|
+
}
|
|
99
|
+
const claim = claimOf(MSG, p)
|
|
100
|
+
if (!claim || typeof claim.pub !== 'string' || !claim.pub) { stats.dropped++; return { ok: false } }
|
|
101
|
+
// NADA QUE DECIDIR SIN ACTA: se para (no hay a quién atender), no se deja pasar.
|
|
102
|
+
const record = await acta()
|
|
103
|
+
if (!record || !(record.members || []).some((m) => m?.pub === claim.pub)) { stats.dropped++; return { ok: false } }
|
|
104
|
+
if (claim.signature !== null) {
|
|
105
|
+
const ok = typeof claim.signature === 'string' && claim.data &&
|
|
106
|
+
await verify({ publickey: claim.pub, data: claim.data, signature: claim.signature }).catch(() => false)
|
|
107
|
+
if (!ok) { stats.dropped++; return { ok: false } }
|
|
108
|
+
}
|
|
109
|
+
return { ok: true }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
return { admit, stats: () => ({ ...stats }) }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export default { createGate, makeLimiter, claimOf }
|
|
@@ -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
|
}
|
|
@@ -46,6 +46,7 @@ import { openCommKey, COMM_CN, COMM_CAPS } from './commKey.js'
|
|
|
46
46
|
import { seal } from '../sealed.js'
|
|
47
47
|
import { MSG, SCOPE, secretsScope, isValidSecretsNs, VAULT_PROTOCOL, VAULT_SPEAKS } from '../protocol.js'
|
|
48
48
|
import { sha256Hex } from './sha256.js'
|
|
49
|
+
import { createGate } from './gate.js'
|
|
49
50
|
|
|
50
51
|
const b64ToBytes = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0))
|
|
51
52
|
const byteLength = (s) => new TextEncoder().encode(s).length
|
|
@@ -478,9 +479,17 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
478
479
|
const acta = info?.acta
|
|
479
480
|
if (!acta || isLocked() || identity.masterLocked) return false
|
|
480
481
|
const pub = await commKey.ensure()
|
|
481
|
-
|
|
482
|
+
const mine = (acta.members || []).find((m) => m?.pub === pub)
|
|
482
483
|
if (!info?.isMaster) return false
|
|
483
|
-
|
|
484
|
+
// DE QUÉ BÓVEDA ES (`vault`: esta maestra). Con dos bóvedas en la cuenta es lo único que
|
|
485
|
+
// deja a la consola escribirle a una sola. A la llave que entró antes del campo se le pone.
|
|
486
|
+
if (mine) {
|
|
487
|
+
if (mine.vault || !master) return false
|
|
488
|
+
await identity.setMemberVault({ pub, vault: master })
|
|
489
|
+
log('[vault] the record now says which vault this communication key speaks for')
|
|
490
|
+
return true
|
|
491
|
+
}
|
|
492
|
+
await identity.admitMember({ pub, label: 'esta bóveda', cn: COMM_CN, caps: [...COMM_CAPS], ...(master ? { vault: master } : {}) })
|
|
484
493
|
log('[vault] this vault is now a member of its own record: it talks with its own key, not the master one')
|
|
485
494
|
return true
|
|
486
495
|
} catch (e) {
|
|
@@ -488,12 +497,14 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
488
497
|
return false
|
|
489
498
|
}
|
|
490
499
|
}
|
|
491
|
-
|
|
500
|
+
// Lo que se selló aquí se anuncia cuando ya hay transporte (más abajo): sin el aviso, la otra
|
|
501
|
+
// bóveda de la cuenta no se entera y las dos acaban con actas distintas del mismo número.
|
|
502
|
+
const commSealedAtStart = await ensureCommKeyInActa()
|
|
492
503
|
|
|
493
504
|
// `announce`: el canal de ESTA cuenta, para que una máquina prestada —que no tiene
|
|
494
505
|
// ninguna llave y solo sabe la dirección `nombre@AB12-CD34-EF56`— pueda encontrar a quien
|
|
495
506
|
// la atiende. Lo construye la pieza compartida, porque quien lo busca es la extensión.
|
|
496
|
-
const { client, identify: reidentify, isIdentified } = await createTransport({
|
|
507
|
+
const { client, identify: reidentify, isIdentified, listen } = await createTransport({
|
|
497
508
|
identity, url: proxyUrl, commKey, log, announce: vaultChannel(fp), makeClient: platform.makeClient || null, wakeUrl: platform.wakeUrl || null
|
|
498
509
|
})
|
|
499
510
|
|
|
@@ -501,6 +512,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
501
512
|
// que le dicen a un tercero si esta cuenta sigue sellada por quien él cree. Ver
|
|
502
513
|
// `sealers.js` — es una comodidad para quien lee, nunca una dependencia de la bóveda.
|
|
503
514
|
startSealersPublisher({ identity, client, log })
|
|
515
|
+
if (commSealedAtStart) await notifyMembers('commkey')
|
|
504
516
|
|
|
505
517
|
async function revocationSet () {
|
|
506
518
|
const { revoked } = await identity.listDelegations()
|
|
@@ -2218,7 +2230,16 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2218
2230
|
reply(from, { type: MSG.INCIDENT_RESULT, id: pend.id, approvers, blocked: false })
|
|
2219
2231
|
}
|
|
2220
2232
|
|
|
2221
|
-
|
|
2233
|
+
// LA PUERTA (`gate.js`): solo el acta; entrar con contraseña con freno, y el alta solo
|
|
2234
|
+
// mientras hay un emparejamiento abierto. Lo demás se descarta sin contestar.
|
|
2235
|
+
const gate = createGate({
|
|
2236
|
+
MSG,
|
|
2237
|
+
acta: async () => (await identity.profileActa?.().catch(() => null))?.acta || null,
|
|
2238
|
+
pairing: (type, p) => desk.ownsPairing(type, p)
|
|
2239
|
+
})
|
|
2240
|
+
|
|
2241
|
+
// `listen` y no `client.on`: entrega también lo que llegó encolado antes de este punto.
|
|
2242
|
+
listen((from, payload) => {
|
|
2222
2243
|
// Quien monta la bóveda puede querer saber que hay trabajo (la Lambda se apaga cuando
|
|
2223
2244
|
// deja de haberlo). Es un aviso, no decide nada.
|
|
2224
2245
|
try { platform.onActivity?.() } catch (_) {}
|
|
@@ -2241,6 +2262,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2241
2262
|
|
|
2242
2263
|
async function onMessage (from, payload) {
|
|
2243
2264
|
if (!payload || typeof payload !== 'object') return
|
|
2265
|
+
const pass = await gate.admit(from, payload)
|
|
2266
|
+
if (!pass.ok) {
|
|
2267
|
+
// Al que entra con contraseña sí se le dice que espere: es la única puerta abierta a
|
|
2268
|
+
// desconocidos, y quien teclea su contraseña tiene que saber por qué no contesta.
|
|
2269
|
+
if (pass.throttled) reply(from, { type: MSG.ERROR, error: 'too many tries: wait before trying again', code: 'too-many-tries', waitMs: pass.waitMs })
|
|
2270
|
+
return
|
|
2271
|
+
}
|
|
2244
2272
|
try {
|
|
2245
2273
|
if (payload.type === MSG.HELLO) return desk.handleHello(from, payload)
|
|
2246
2274
|
if (payload.type === MSG.ENROLL) return await desk.handleEnroll(from, payload)
|
|
@@ -2606,6 +2634,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2606
2634
|
async function handleReplicaAck (from, p) {
|
|
2607
2635
|
const body = p?.body
|
|
2608
2636
|
if (!body || body.op !== 'replica.ack') return
|
|
2637
|
+
// Fresco, o un acuse capturado serviría para hacer empujar a la bóveda cuando quisiera.
|
|
2638
|
+
if (!isFresh(body)) return
|
|
2609
2639
|
const record = (await identity.profileActa?.().catch(() => null))?.acta || null
|
|
2610
2640
|
if (!record) return
|
|
2611
2641
|
// LA LLAVE VA DENTRO DEL MENSAJE FIRMADO, no se saca de `from`: `from` es el
|
|
@@ -4264,6 +4294,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
4264
4294
|
// Alcanzable ≠ corriendo: si el proxio rechazó el `identify` esta bóveda está viva y
|
|
4265
4295
|
// nadie puede hablarle. Lo mira `status` (ver `manager.js`, `summary`).
|
|
4266
4296
|
isIdentified,
|
|
4297
|
+
// Lo que la puerta descartó (`gate.js`): desconocidos y pedidos de entrar frenados.
|
|
4298
|
+
gateStats: () => gate.stats(),
|
|
4267
4299
|
// Se expone para poder PROBAR que una respuesta que no cabe no mata la conexión: es el
|
|
4268
4300
|
// único punto por el que sale todo, y el fallo que cierra vive justo ahí.
|
|
4269
4301
|
reply,
|
|
@@ -4293,7 +4325,9 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
4293
4325
|
// la bóveda seguía muda en el proxio con su llave ya admitida en el acta. Al dueño le
|
|
4294
4326
|
// pasó el 2026-09-05: hizo lo que el log pedía y la consola siguió sin contestar.
|
|
4295
4327
|
if (r?.locked === false) {
|
|
4296
|
-
try {
|
|
4328
|
+
try {
|
|
4329
|
+
if (await ensureCommKeyInActa()) { await reidentify?.(); await notifyMembers('commkey') }
|
|
4330
|
+
} catch (_) {}
|
|
4297
4331
|
}
|
|
4298
4332
|
// Y ABSORBER LO PENDIENTE. La subacta ya lo estaba honrando con el perfil cerrado —de
|
|
4299
4333
|
// 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
|
-
|
|
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
|
-
|
|
323
|
-
|
|
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
|
-
|
|
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
|
|