@dotrino/vaultd 0.169.0 → 0.170.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/lib/src/core/gate.js +115 -0
- package/lib/src/core/libVersion.js +1 -1
- package/lib/src/core/vault.js +20 -0
- package/lib/src/enroll.js +20 -1
- package/lib/src/passwordLogins.js +29 -3
- package/package.json +1 -1
|
@@ -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 }
|
package/lib/src/core/vault.js
CHANGED
|
@@ -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
|
|
@@ -2229,6 +2230,14 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2229
2230
|
reply(from, { type: MSG.INCIDENT_RESULT, id: pend.id, approvers, blocked: false })
|
|
2230
2231
|
}
|
|
2231
2232
|
|
|
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
|
+
|
|
2232
2241
|
// `listen` y no `client.on`: entrega también lo que llegó encolado antes de este punto.
|
|
2233
2242
|
listen((from, payload) => {
|
|
2234
2243
|
// Quien monta la bóveda puede querer saber que hay trabajo (la Lambda se apaga cuando
|
|
@@ -2253,6 +2262,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2253
2262
|
|
|
2254
2263
|
async function onMessage (from, payload) {
|
|
2255
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
|
+
}
|
|
2256
2272
|
try {
|
|
2257
2273
|
if (payload.type === MSG.HELLO) return desk.handleHello(from, payload)
|
|
2258
2274
|
if (payload.type === MSG.ENROLL) return await desk.handleEnroll(from, payload)
|
|
@@ -2618,6 +2634,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2618
2634
|
async function handleReplicaAck (from, p) {
|
|
2619
2635
|
const body = p?.body
|
|
2620
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
|
|
2621
2639
|
const record = (await identity.profileActa?.().catch(() => null))?.acta || null
|
|
2622
2640
|
if (!record) return
|
|
2623
2641
|
// LA LLAVE VA DENTRO DEL MENSAJE FIRMADO, no se saca de `from`: `from` es el
|
|
@@ -4276,6 +4294,8 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
4276
4294
|
// Alcanzable ≠ corriendo: si el proxio rechazó el `identify` esta bóveda está viva y
|
|
4277
4295
|
// nadie puede hablarle. Lo mira `status` (ver `manager.js`, `summary`).
|
|
4278
4296
|
isIdentified,
|
|
4297
|
+
// Lo que la puerta descartó (`gate.js`): desconocidos y pedidos de entrar frenados.
|
|
4298
|
+
gateStats: () => gate.stats(),
|
|
4279
4299
|
// Se expone para poder PROBAR que una respuesta que no cabe no mata la conexión: es el
|
|
4280
4300
|
// único punto por el que sale todo, y el fallo que cierra vive justo ahí.
|
|
4281
4301
|
reply,
|
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
|
-
|
|
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
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/vaultd",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.170.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": {
|