@dotrino/identity 0.124.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/src/index.js +4 -1
- package/vault/acta.js +23 -1
- package/vault/core.js +25 -3
- package/vault/facade.js +2 -0
- package/vault/originPolicy.js +1 -1
- package/vault/remote.js +8 -5
- package/vault/vendor/roadmap/VERSION.txt +1 -1
- package/vault/vendor/roadmap/manifests.js +15 -8
- 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
package/src/index.js
CHANGED
|
@@ -474,9 +474,12 @@ export class Identity {
|
|
|
474
474
|
* Requiere que el cert de este aparato lleve `vault:admin`, que **no se recibe al
|
|
475
475
|
* emparejar**: se concede a mano en la bóveda. Cambiar permisos y traspasar el mando
|
|
476
476
|
* NO se administran a distancia — siguen siendo del master, en su máquina.
|
|
477
|
+
*
|
|
478
|
+
* `args.to`: la llave de comunicación de UNA bóveda de la cuenta (`vault` en el acta), para
|
|
479
|
+
* hablarle a esa y no a la que conteste primero. Espera más: una alojada dormida tarda.
|
|
477
480
|
*/
|
|
478
481
|
async vaultAdmin (op, args) {
|
|
479
|
-
return this._call('vaultAdmin', { op, ...(args || {}) }, 20000)
|
|
482
|
+
return this._call('vaultAdmin', { op, ...(args || {}) }, args?.to ? 50000 : 20000)
|
|
480
483
|
}
|
|
481
484
|
|
|
482
485
|
/**
|
package/vault/acta.js
CHANGED
|
@@ -215,6 +215,12 @@ export const CAP_SCOPE = Object.freeze({ sign: 'vault:sign', store: 'vault:store
|
|
|
215
215
|
const enc = (s) => new TextEncoder().encode(s)
|
|
216
216
|
const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
217
217
|
const isPub = (v) => typeof v === 'string' && v.length > 0
|
|
218
|
+
/** La maestra de la que es una llave de comunicación; solo la del `cn` de la bóveda la lleva. */
|
|
219
|
+
const vaultOfComm = (cn, vault) => {
|
|
220
|
+
if (cn !== VAULT_CN) throw new Error('vault: only the vault communication key says which vault it is')
|
|
221
|
+
if (!isPub(vault)) throw new Error('vault: missing the vault master pubkey')
|
|
222
|
+
return vault
|
|
223
|
+
}
|
|
218
224
|
|
|
219
225
|
/**
|
|
220
226
|
* La llave de CIFRADO de un miembro (`encPub`): JWK público de una ECDH P-256.
|
|
@@ -517,6 +523,9 @@ export function checkShape (acta) {
|
|
|
517
523
|
// arrancar en vez de avisar. Primero los servicios registran su llave (op
|
|
518
524
|
// `encpub`), y cuando no quede ninguno sin ella se aprieta aquí.
|
|
519
525
|
if (m.encPub != null && !isEncPub(m.encPub)) return 'invalid-encpub'
|
|
526
|
+
// DE QUÉ BÓVEDA ES una llave de comunicación (`vault`: la maestra por la que habla). Solo
|
|
527
|
+
// la lleva un miembro con el `cn` de la bóveda: en cualquier otro no significa nada.
|
|
528
|
+
if (m.vault != null && (!isPub(m.vault) || m.cn !== VAULT_CN)) return 'invalid-vault'
|
|
520
529
|
}
|
|
521
530
|
// LA LLAVE DE SELLADO Y SU REGISTRO. `sealPub` puede no estar (un perfil que no sella
|
|
522
531
|
// secretos), pero si está tiene que decir DESDE QUÉ acta manda: sin `sealSince` no se
|
|
@@ -834,10 +843,23 @@ export async function applyChanges (acta, changes, { by, now = Date.now(), sealP
|
|
|
834
843
|
// Puente con la identidad que este miembro traía de antes (ver makeContinuity).
|
|
835
844
|
...(m.continuity ? { continuity: m.continuity } : {}),
|
|
836
845
|
// DÓNDE CORRE (`machine.js`): lo que dijo al emparejar, para reconocerlo en la lista.
|
|
837
|
-
...(cleanMachine(m.machine) ? { machine: cleanMachine(m.machine) } : {})
|
|
846
|
+
...(cleanMachine(m.machine) ? { machine: cleanMachine(m.machine) } : {}),
|
|
847
|
+
// DE QUÉ BÓVEDA ES, si es la llave de comunicación de una (ver op `vault`).
|
|
848
|
+
...(m.vault != null ? { vault: vaultOfComm(cn, m.vault) } : {})
|
|
838
849
|
})
|
|
839
850
|
break
|
|
840
851
|
}
|
|
852
|
+
// DE QUÉ BÓVEDA ES UNA LLAVE DE COMUNICACIÓN. Con dos bóvedas en la cuenta hay dos llaves
|
|
853
|
+
// `cn: 'vault'`, y sin esto nadie sabe a cuál escribirle para hablar con UNA de ellas: la
|
|
854
|
+
// consola elige bóveda y le escribe a su llave, que es la única que la alcanza sin pasar
|
|
855
|
+
// por las demás. La pone la propia bóveda al admitir su llave, o después, a una que entró
|
|
856
|
+
// antes de existir el campo.
|
|
857
|
+
case 'vault': {
|
|
858
|
+
const m = find(ch.pub)
|
|
859
|
+
if (!m) throw new Error('vault: that member is not in the record')
|
|
860
|
+
m.vault = vaultOfComm(m.cn, ch.vault)
|
|
861
|
+
break
|
|
862
|
+
}
|
|
841
863
|
// Registra (o reemplaza) la llave de CIFRADO de un miembro que YA está admitido.
|
|
842
864
|
//
|
|
843
865
|
// Existe para no tener que expulsar y volver a admitir a un servicio solo porque
|
package/vault/core.js
CHANGED
|
@@ -804,6 +804,8 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
804
804
|
* Lo pone quien levanta la bóveda (`setSelfVault`) y lo quita al pararla.
|
|
805
805
|
*/
|
|
806
806
|
let selfLink = null
|
|
807
|
+
/** Lo que se espera a una bóveda elegida: una alojada dormida arranca antes de contestar. */
|
|
808
|
+
const VAULT_WAKE_MS = 45000
|
|
807
809
|
let selfLinkOff = null
|
|
808
810
|
/** El enlace con el que administrar: el emparejamiento si lo hay, y si no, la bóveda local. */
|
|
809
811
|
const adminLink = () => {
|
|
@@ -2598,6 +2600,8 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
2598
2600
|
addedAt: m.addedAt || null,
|
|
2599
2601
|
// Dónde corre, según dijo al emparejarse (`machine.js`). `null` si entró antes.
|
|
2600
2602
|
machine: m.machine || null,
|
|
2603
|
+
// Si es la llave de comunicación de una bóveda, la maestra de ESA bóveda.
|
|
2604
|
+
vault: m.vault || null,
|
|
2601
2605
|
isMe: m.pub === publickeyJwkStr,
|
|
2602
2606
|
isMaster: Acta.canSeal(acta, m.pub),
|
|
2603
2607
|
// La llave de CIFRADO del miembro y, derivado, si se le puede envolver algo.
|
|
@@ -2643,7 +2647,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
2643
2647
|
* Admite un miembro (solo el master). El cert lo emite quien llama, antes o después.
|
|
2644
2648
|
* `continuity`: si esa identidad ya existía por su cuenta, su puente firmado (F3).
|
|
2645
2649
|
*/
|
|
2646
|
-
async admitMember ({ pub, encPub = null, label = '', cn = null, caps = null, cert = null, continuity = null, machine = null } = {}) {
|
|
2650
|
+
async admitMember ({ pub, encPub = null, label = '', cn = null, caps = null, cert = null, continuity = null, machine = null, vault = null } = {}) {
|
|
2647
2651
|
// `cn`: si viene, este miembro es un SERVICIO: abre el cajón de secretos de ESE nombre
|
|
2648
2652
|
// por llevarlo, sin permiso aparte, y no ve nada más del usuario. Sin `cn` es un dispositivo.
|
|
2649
2653
|
const finales = caps || (cn ? [] : ['store', 'read'])
|
|
@@ -2660,10 +2664,20 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
2660
2664
|
const mine = encPub ? await myCek() : null
|
|
2661
2665
|
if (mine) wrap = { op: 'wrap', gen: mine.gen, pub, wrap: await Content.wrapForMember({ cek: mine.cek, memberEncPub: encPub }) }
|
|
2662
2666
|
} catch (_) { wrap = null }
|
|
2663
|
-
const acta = await sealChanges([{ op: 'admit', member: { pub, encPub, label, cn, caps: finales, cert, continuity, machine } }, ...(wrap ? [wrap] : [])])
|
|
2667
|
+
const acta = await sealChanges([{ op: 'admit', member: { pub, encPub, label, cn, caps: finales, cert, continuity, machine, ...(vault ? { vault } : {}) } }, ...(wrap ? [wrap] : [])])
|
|
2664
2668
|
return { ok: true, seq: acta.seq, wrapped: !!wrap }
|
|
2665
2669
|
},
|
|
2666
2670
|
|
|
2671
|
+
/**
|
|
2672
|
+
* DE QUÉ BÓVEDA ES una llave de comunicación (`vault`: su maestra). La pone la propia
|
|
2673
|
+
* bóveda a la llave que entró antes de existir el campo; sin él, con dos bóvedas en la
|
|
2674
|
+
* cuenta no hay forma de escribirle a una sola.
|
|
2675
|
+
*/
|
|
2676
|
+
async setMemberVault ({ pub, vault } = {}) {
|
|
2677
|
+
const acta = await sealChanges([{ op: 'vault', pub, vault }])
|
|
2678
|
+
return { ok: true, seq: acta.seq }
|
|
2679
|
+
},
|
|
2680
|
+
|
|
2667
2681
|
async setCaps ({ pub, caps } = {}) {
|
|
2668
2682
|
const acta = await sealChanges([{ op: 'caps', pub, caps }])
|
|
2669
2683
|
return { ok: true, seq: acta.seq }
|
|
@@ -3123,10 +3137,18 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
3123
3137
|
* permisos y traspasar el mando NO están, y no es un olvido: eso sigue siendo del
|
|
3124
3138
|
* master, en su máquina.
|
|
3125
3139
|
*/
|
|
3126
|
-
async vaultAdmin ({ op, ...rest } = {}) {
|
|
3140
|
+
async vaultAdmin ({ op, to = null, ...rest } = {}) {
|
|
3127
3141
|
const link = adminLink()
|
|
3128
3142
|
if (!link) throw new Error('this device is not paired with a vault')
|
|
3129
3143
|
const { v, device } = link
|
|
3144
|
+
// A UNA BÓVEDA CONCRETA de la cuenta: `to` es su llave de comunicación (`vault` en el
|
|
3145
|
+
// acta). La alojada puede estar dormida y tarda en despertar, así que se le da más tiempo.
|
|
3146
|
+
if (to) {
|
|
3147
|
+
if (!(loadActa()?.members || []).some((m) => m.pub === to && m.vault)) {
|
|
3148
|
+
throw Object.assign(new Error('vaultAdmin: that key is not a vault of this account'), { code: 'not-a-vault' })
|
|
3149
|
+
}
|
|
3150
|
+
rest = { ...rest, to, timeoutMs: VAULT_WAKE_MS }
|
|
3151
|
+
}
|
|
3130
3152
|
if (link.self) return remoteAdmin({ master: v.master, proxy: v.proxy, device, cert: v.cert, op, ...rest })
|
|
3131
3153
|
maybeRenewVaultCert()
|
|
3132
3154
|
try { return await remoteAdmin({ master: v.master, proxy: v.proxy, device, cert: v.cert, op, ...rest, onRevoked: wipeVaultLink }) }
|
package/vault/facade.js
CHANGED
|
@@ -110,6 +110,8 @@ export class IdentityFacade {
|
|
|
110
110
|
admitMember (member) { return this._h('admitMember', member) }
|
|
111
111
|
/** Registra la llave de cifrado de un miembro ya admitido (evita re-enrolarlo). */
|
|
112
112
|
setMemberEncPub (args) { return this._h('setMemberEncPub', args) }
|
|
113
|
+
/** Dice de qué bóveda es una llave de comunicación ya admitida. */
|
|
114
|
+
setMemberVault (args) { return this._h('setMemberVault', args) }
|
|
113
115
|
setCaps (pub, caps) { return this._h('setCaps', { pub, caps }) }
|
|
114
116
|
setCapsMany (changes) { return this._h('setCapsMany', { changes }) }
|
|
115
117
|
setLabel (pub, label) { return this._h('setLabel', { pub, label }) }
|
package/vault/originPolicy.js
CHANGED
|
@@ -21,7 +21,7 @@ const CONSOLE = /^https:\/\/(vault|profile)\.dotrino\.com$/
|
|
|
21
21
|
* sus respaldos) y la contraseña del perfil.
|
|
22
22
|
*/
|
|
23
23
|
export const CONSOLE_ONLY = Object.freeze([
|
|
24
|
-
'admitMember', 'removeMember', 'setCaps', 'setCapsMany', 'setLabel', 'setMemberEncPub', 'handoverMaster',
|
|
24
|
+
'admitMember', 'removeMember', 'setCaps', 'setCapsMany', 'setLabel', 'setMemberEncPub', 'setMemberVault', 'handoverMaster',
|
|
25
25
|
'renounceCaps', 'absorbRenounce', 'adoptActa', 'adoptActaChain', 'joinProfile', 'rotateSealKey', 'setSealKeyProvider',
|
|
26
26
|
'revokeDevice', 'vaultPair', 'vaultAdopt', 'vaultUnpair', 'prepareForAdoption', 'setSelfVault',
|
|
27
27
|
'exportIdentity', 'importIdentity', 'deleteProfile', 'setProfilePassword', 'removeProfilePassword',
|
package/vault/remote.js
CHANGED
|
@@ -348,9 +348,12 @@ async function clientFor (proxy, master) {
|
|
|
348
348
|
return client
|
|
349
349
|
}
|
|
350
350
|
|
|
351
|
-
async function vaultRpc ({ master, proxy, device, cert, acta = null, sendType, okType, data, onRevoked, timeoutMs = 15000 }) {
|
|
351
|
+
async function vaultRpc ({ master, to = null, proxy, device, cert, acta = null, sendType, okType, data, onRevoked, timeoutMs = 15000 }) {
|
|
352
|
+
// `to`: a qué llave se escribe, si no es la maestra. Con dos bóvedas en la cuenta, la
|
|
353
|
+
// maestra del perfil las alcanza a todas; la llave de comunicación de una, solo a ella.
|
|
354
|
+
const dest = to || master
|
|
352
355
|
if (!master || !proxy || !(device?.privateJwk || device?.privateKey || typeof device?.sign === 'function') || !cert) throw new Error('missing pairing data')
|
|
353
|
-
const client = await clientFor(proxy,
|
|
356
|
+
const client = await clientFor(proxy, dest)
|
|
354
357
|
try {
|
|
355
358
|
try { await identifyAsDevice(client, device, { cert, acta }) } catch (_) { /* sin identify seguimos: solo perdemos la cola */ }
|
|
356
359
|
const signed = { ...data, publickey: device.publickey, ts: Date.now(), ...(cleanMachine(device.machine) ? { machine: cleanMachine(device.machine) } : {}) }
|
|
@@ -382,7 +385,7 @@ async function vaultRpc ({ master, proxy, device, cert, acta = null, sendType, o
|
|
|
382
385
|
const t = setTimeout(() => { cleanup(); reject(Object.assign(new Error('the vault did not reply (is it running?)'), { code: 'vault-no-reply' })) }, timeoutMs)
|
|
383
386
|
const cleanup = () => { off(); clearTimeout(t); clearTimeout(graceTimer) }
|
|
384
387
|
})
|
|
385
|
-
client.sendByPubkey(
|
|
388
|
+
client.sendByPubkey(dest, { type: sendType, data: signed, signature, cert })
|
|
386
389
|
return await pending
|
|
387
390
|
} finally { try { client.close() } catch (_) {} }
|
|
388
391
|
}
|
|
@@ -499,7 +502,7 @@ export async function requestRenounce ({ master, proxy, device, cert, record, on
|
|
|
499
502
|
* El `nonce` de un solo uso va en cada petición porque `approve` y `revoke` cambian
|
|
500
503
|
* estado, y para eso la ventana de frescura de ±5 min no alcanza.
|
|
501
504
|
*/
|
|
502
|
-
export async function requestAdmin ({ master, proxy, device, cert, op, onRevoked, nonce: dado, ...rest } = {}) {
|
|
505
|
+
export async function requestAdmin ({ master, to = null, timeoutMs, proxy, device, cert, op, onRevoked, nonce: dado, ...rest } = {}) {
|
|
503
506
|
// EL NONCE SE PUEDE DAR, y hace falta para abrir la bóveda a distancia: ahí va también
|
|
504
507
|
// DENTRO del sobre sellado, y quien lo sella tiene que conocerlo antes de llamar. Si se
|
|
505
508
|
// generara siempre aquí, el de fuera y el de dentro no podrían coincidir — y el de
|
|
@@ -509,7 +512,7 @@ export async function requestAdmin ({ master, proxy, device, cert, op, onRevoked
|
|
|
509
512
|
: [...crypto.getRandomValues(new Uint8Array(16))]
|
|
510
513
|
.map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
511
514
|
const res = await vaultRpc({
|
|
512
|
-
master, proxy, device, cert, onRevoked,
|
|
515
|
+
master, to, proxy, device, cert, onRevoked, ...(timeoutMs ? { timeoutMs } : {}),
|
|
513
516
|
sendType: MSG.ADMIN, okType: MSG.ADMIN_RESULT,
|
|
514
517
|
data: { op, ...rest, nonce }
|
|
515
518
|
})
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
Copia vendorizada de @dotrino/roadmap@0.4.
|
|
1
|
+
Copia vendorizada de @dotrino/roadmap@0.4.51 (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.
|
|
34
|
+
"current": "0.124.0",
|
|
35
35
|
"protocol": 1,
|
|
36
36
|
"requires": {
|
|
37
37
|
"proxy-client": ">=0.13.1"
|
|
@@ -253,12 +253,12 @@ export const MANIFESTS = Object.freeze({
|
|
|
253
253
|
"vault": {
|
|
254
254
|
"repo": "imdotrino/dotrino-vault",
|
|
255
255
|
"npm": "@dotrino/vault",
|
|
256
|
-
"current": "0.
|
|
256
|
+
"current": "0.96.0",
|
|
257
257
|
"protocol": 1,
|
|
258
258
|
"requires": {
|
|
259
259
|
"vaultd": ">=0.105.0",
|
|
260
260
|
"proxy-client": ">=0.39.0",
|
|
261
|
-
"identity": ">=0.
|
|
261
|
+
"identity": ">=0.124.0",
|
|
262
262
|
"opaque": ">=0.1.0",
|
|
263
263
|
"compat": ">=0.4.0",
|
|
264
264
|
"roadmap": ">=0.4.26",
|
|
@@ -269,10 +269,10 @@ export const MANIFESTS = Object.freeze({
|
|
|
269
269
|
"vaultd": {
|
|
270
270
|
"repo": "imdotrino/dotrino-vault",
|
|
271
271
|
"npm": "@dotrino/vaultd",
|
|
272
|
-
"current": "0.
|
|
272
|
+
"current": "0.168.0",
|
|
273
273
|
"protocol": 1,
|
|
274
274
|
"requires": {
|
|
275
|
-
"identity": ">=0.
|
|
275
|
+
"identity": ">=0.124.0",
|
|
276
276
|
"proxy-client": ">=0.39.0",
|
|
277
277
|
"store": ">=0.11.0",
|
|
278
278
|
"passmanager": ">=0.18.4",
|
|
@@ -364,14 +364,14 @@ export const MANIFESTS = Object.freeze({
|
|
|
364
364
|
"accounts": {
|
|
365
365
|
"repo": "imdotrino/dotrino-accounts",
|
|
366
366
|
"npm": null,
|
|
367
|
-
"current": "0.
|
|
367
|
+
"current": "0.6.0",
|
|
368
368
|
"protocol": 1,
|
|
369
369
|
"requires": {
|
|
370
370
|
"identity": ">=0.116.0",
|
|
371
371
|
"remote-agent": ">=0.23.1",
|
|
372
|
-
"vault": ">=0.
|
|
372
|
+
"vault": ">=0.96.0",
|
|
373
373
|
"pay": ">=0.2.0",
|
|
374
|
-
"vaultd": ">=0.
|
|
374
|
+
"vaultd": ">=0.168.0"
|
|
375
375
|
}
|
|
376
376
|
},
|
|
377
377
|
"ai": {
|
|
@@ -381,6 +381,13 @@ export const MANIFESTS = Object.freeze({
|
|
|
381
381
|
"protocol": 1,
|
|
382
382
|
"requires": {}
|
|
383
383
|
},
|
|
384
|
+
"dictation": {
|
|
385
|
+
"repo": "imdotrino/dotrino-dictation",
|
|
386
|
+
"npm": "@dotrino/dictation",
|
|
387
|
+
"current": "0.1.1",
|
|
388
|
+
"protocol": 1,
|
|
389
|
+
"requires": {}
|
|
390
|
+
},
|
|
384
391
|
"pay": {
|
|
385
392
|
"repo": "imdotrino/dotrino-pay",
|
|
386
393
|
"npm": "@dotrino/pay",
|
|
@@ -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
|
|