@dotrino/vaultd 0.190.1 → 0.192.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/admin.js +17 -2
- package/lib/src/core/libVersion.js +1 -1
- package/lib/src/core/transport.js +15 -3
- package/lib/src/core/vault.js +89 -7
- package/lib/src/protocol.js +25 -0
- package/lib/src/service.js +71 -35
- package/package.json +3 -3
- package/src/client.js +29 -17
- package/src/replica.js +42 -10
package/lib/src/admin.js
CHANGED
|
@@ -50,6 +50,11 @@ export const ADMIN_OPS = Object.freeze([
|
|
|
50
50
|
// Los BLOQUEADOS por un aprobador (`src/blocked.js`): verlos y desbloquearlos. Bloquear a
|
|
51
51
|
// distancia también, por si el administrador llega antes que el teléfono. No toca el acta.
|
|
52
52
|
'blocked', 'block', 'unblock',
|
|
53
|
+
// LAS CONCESIONES (un pedido aprobado deja pasar ese comando una hora que se renueva con
|
|
54
|
+
// cada uso): verlas y cortarlas. Las mismas que el aprobador ve en /approvals; aquí las ve
|
|
55
|
+
// quien administra, igual que la TUI del binario. Cortar no sella nada: la lista es de la
|
|
56
|
+
// bóveda, no del acta.
|
|
57
|
+
'grants', 'grant-revoke',
|
|
53
58
|
// Variables de entorno: verlas (nombres siempre; valor solo de las públicas) y
|
|
54
59
|
// ponerles valor (de las dos). Borrar NO está, y es a propósito: un aparato robado
|
|
55
60
|
// no debe poder dejar sin configuración a los servicios.
|
|
@@ -99,8 +104,8 @@ export const ADMIN_OPS = Object.freeze([
|
|
|
99
104
|
*/
|
|
100
105
|
export const ADMIN_OPS_WHILE_LOCKED = Object.freeze([
|
|
101
106
|
'audit', 'vars', 'var.set', 'var.setMany', 'var.recipients', 'var.reveal.begin', 'var.reveal',
|
|
102
|
-
// Bloquear no sella nada: la lista es de la bóveda, no del acta.
|
|
103
|
-
'blocked', 'block', 'unblock',
|
|
107
|
+
// Bloquear no sella nada: la lista es de la bóveda, no del acta. Las concesiones, igual.
|
|
108
|
+
'blocked', 'block', 'unblock', 'grants', 'grant-revoke',
|
|
104
109
|
// Las dos de abrir, obviamente: son las únicas que solo tienen sentido con el candado
|
|
105
110
|
// echado. Que estén aquí NO las deja pasar sin más — siguen exigiendo cert, acta, nonce
|
|
106
111
|
// y frescura como todas, y además la contraseña dentro del sobre.
|
|
@@ -154,6 +159,9 @@ export function createAdminDesk ({
|
|
|
154
159
|
unlockDesk = null,
|
|
155
160
|
// La lista de bloqueados, inyectada como `vars`: `{ list(), set(pub, on, { by }) }`.
|
|
156
161
|
blocked = null,
|
|
162
|
+
// Las CONCESIONES, inyectadas igual: `{ list(device), revoke(id, { by }) }`. `list` recibe
|
|
163
|
+
// a quien pregunta porque el comando de cada una va sellado a su llave de cifrado.
|
|
164
|
+
grants = null,
|
|
157
165
|
now = () => Date.now()
|
|
158
166
|
}) {
|
|
159
167
|
const ops = new Set(ADMIN_OPS)
|
|
@@ -352,6 +360,13 @@ export function createAdminDesk ({
|
|
|
352
360
|
// usarlo para quitar dejaba un miembro sin certificados al que la bóveda ya nunca le
|
|
353
361
|
// mandaba el aviso de expulsión (mientras siga en el acta, un papel retirado
|
|
354
362
|
// significa «renueva»). Ese era el dispositivo fantasma.
|
|
363
|
+
if (data.op === 'grants' || data.op === 'grant-revoke') {
|
|
364
|
+
if (!grants) return { ok: false, error: 'admin: this vault has no grants' }
|
|
365
|
+
if (data.op === 'grants') return { ok: true, result: await grants.list(chk.device) }
|
|
366
|
+
if (typeof data.id !== 'string' || !data.id) return { ok: false, error: 'admin: grant-revoke needs the grant id' }
|
|
367
|
+
const ok = await grants.revoke(data.id, { by })
|
|
368
|
+
return { ok: true, result: { id: data.id, ok } }
|
|
369
|
+
}
|
|
355
370
|
if (data.op === 'blocked' || data.op === 'block' || data.op === 'unblock') {
|
|
356
371
|
if (!blocked) return { ok: false, error: 'admin: this vault cannot block devices' }
|
|
357
372
|
if (data.op === 'blocked') return { ok: true, result: { items: blocked.list() } }
|
|
@@ -81,12 +81,16 @@ export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey
|
|
|
81
81
|
// CON QUÉ SE ABRE LO QUE NOS SELLAN (`commKey.encKeypair`): sin esto la bóveda no podía
|
|
82
82
|
// recibir nada sellado, y una hermana cerrada no habría podido abrir los cajones que le
|
|
83
83
|
// manda la otra. El pilar anuncia la pública al identificarse con la llave de comunicación.
|
|
84
|
-
|
|
84
|
+
let enc = commKey?.pub?.() && typeof commKey.encKeypair === 'function'
|
|
85
85
|
? await commKey.encKeypair().catch((e) => { log('[vault] no transport encryption key: ' + e.message); return null })
|
|
86
86
|
: null
|
|
87
|
-
|
|
87
|
+
// Y A QUIEN CREA EL CLIENTE TAMBIÉN se le pasa (la extensión, la pestaña): sin esto una bóveda
|
|
88
|
+
// de navegador no anunciaba llave de cifrado, y lo que sus aparatos le sellan
|
|
89
|
+
// (`docs/sealed-requests.md`) no tenía con qué abrirse.
|
|
90
|
+
const encOpts = enc ? { myEncPub: enc.encPub, myEncPrivateKey: enc.privateKey } : {}
|
|
91
|
+
const client = makeClient ? makeClient({ url, acceptDirectFrom: inActa, ...encOpts }) : new WebSocketProxyClient({
|
|
88
92
|
url, enableWebRTC: true, acceptDirectFrom: inActa, autoReconnect: true,
|
|
89
|
-
...
|
|
93
|
+
...encOpts,
|
|
90
94
|
maxReconnectAttempts: 100000, reconnectDelay: 4000,
|
|
91
95
|
// EL BLUETOOTH (proxy-client docs/bluetooth.md) lo decide la plataforma: el binario en
|
|
92
96
|
// Linux sí; la pestaña y la extensión no pueden. Misma puerta que WebRTC (`inActa`).
|
|
@@ -118,6 +122,14 @@ export async function createTransport ({ identity, url = DEFAULT_PROXY, commKey
|
|
|
118
122
|
const record = (await identity.profileActa?.().catch(() => null))?.acta || null
|
|
119
123
|
seenActa = record // la copia que mira la puerta del canal directo
|
|
120
124
|
const comm = commKey?.pub?.() || null
|
|
125
|
+
// LA LLAVE DE CIFRADO TAMBIÉN SI LA DE COMUNICACIÓN SE ESTRENÓ DESPUÉS de crear el cliente
|
|
126
|
+
// (un perfil con contraseña la estrena al abrirse). Sin esto la bóveda volvía a la red con
|
|
127
|
+
// su llave nueva pero sin anunciar con qué se le sella, y lo que sus aparatos le mandan
|
|
128
|
+
// sellado (`docs/sealed-requests.md`) no tenía con qué abrirse.
|
|
129
|
+
if (comm && !enc && typeof commKey.encKeypair === 'function') {
|
|
130
|
+
enc = await commKey.encKeypair().catch((e) => { log('[vault] no transport encryption key: ' + e.message); return null })
|
|
131
|
+
if (enc) client.updateConfig?.({ myEncPub: enc.encPub, myEncPrivateKey: enc.privateKey })
|
|
132
|
+
}
|
|
121
133
|
// ¿Nos nombra el acta? Con `cn` o sin él, lo que el proxio mira es la pertenencia.
|
|
122
134
|
const isMember = comm && (record?.members || []).some((m) => m?.pub === comm)
|
|
123
135
|
|
package/lib/src/core/vault.js
CHANGED
|
@@ -46,7 +46,7 @@ import { BACKUP_VERSION, PASSWORDS_DRAWER, wants, assertSelected, planImport, re
|
|
|
46
46
|
import { openSealKeys } from './sealKey.js'
|
|
47
47
|
import { openCommKey, COMM_CN, COMM_CAPS } from './commKey.js'
|
|
48
48
|
import { seal } from '../sealed.js'
|
|
49
|
-
import { MSG, SCOPE, secretsScope, isValidSecretsNs, VAULT_PROTOCOL, VAULT_SPEAKS } from '../protocol.js'
|
|
49
|
+
import { MSG, SCOPE, secretsScope, isValidSecretsNs, VAULT_PROTOCOL, VAULT_SPEAKS, SEALED_REQUEST_TYPES, unsealedRequestsAllowed, UNSEALED_REQUESTS_UNTIL_TEXT } from '../protocol.js'
|
|
50
50
|
import { sha256Hex } from './sha256.js'
|
|
51
51
|
import { sealHead, ANCHOR_EVERY_MS, ANCHOR_FIRST_MS } from './logAnchor.js'
|
|
52
52
|
import { createGate } from './gate.js'
|
|
@@ -656,6 +656,63 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
656
656
|
*/
|
|
657
657
|
const channels = new Map()
|
|
658
658
|
|
|
659
|
+
/**
|
|
660
|
+
* LA RESPUESTA A UNA PETICIÓN SELLADA VUELVE SELLADA (`docs/sealed-requests.md`).
|
|
661
|
+
*
|
|
662
|
+
* El aparato mete en lo firmado una llave de un solo uso (`data.rek`), y a esa llave se le
|
|
663
|
+
* sella todo lo que se le conteste a ESA petición. Se hace con un canal más de `channels`
|
|
664
|
+
* —como el socket local—, así que ningún mostrador tiene que saber nada: contesta a `from`
|
|
665
|
+
* como siempre y el canal sella. El canal es por conexión Y llave: dos peticiones por la
|
|
666
|
+
* misma conexión con llaves distintas no se pisan, y un tercero que escriba «desde» ese
|
|
667
|
+
* token con otra llave se lleva su propio canal, no el del aparato.
|
|
668
|
+
*
|
|
669
|
+
* Viven lo que puede tardar la respuesta más lenta (un pedido que espera al teléfono) y se
|
|
670
|
+
* podan por antigüedad; si ya no está, la respuesta a un pedido aprobado sale por la cola
|
|
671
|
+
* del aparato, como antes.
|
|
672
|
+
*/
|
|
673
|
+
const SEALED_CHANNEL_TTL_MS = 24 * 60 * 60 * 1000
|
|
674
|
+
const SEALED_CHANNELS_MAX = 5000
|
|
675
|
+
const sealedChannelAt = new Map()
|
|
676
|
+
function sealedChannel (token, rek) {
|
|
677
|
+
const id = `sealed:${token}:${sha256Hex(rek).slice(0, 16)}`
|
|
678
|
+
const now = Date.now()
|
|
679
|
+
if (!channels.has(id)) {
|
|
680
|
+
for (const [k, t] of sealedChannelAt) {
|
|
681
|
+
if (now - t < SEALED_CHANNEL_TTL_MS && sealedChannelAt.size < SEALED_CHANNELS_MAX) break
|
|
682
|
+
sealedChannelAt.delete(k); channels.delete(k)
|
|
683
|
+
}
|
|
684
|
+
// EN ORDEN: sellar es asíncrono, y dos respuestas seguidas podían adelantarse una a la
|
|
685
|
+
// otra. El orden importa (el aviso firmado de expulsión va ANTES del «no», porque el
|
|
686
|
+
// aparato deja de escuchar al recibir el «no»), así que salen en fila.
|
|
687
|
+
let tail = Promise.resolve()
|
|
688
|
+
channels.set(id, (obj) => {
|
|
689
|
+
tail = tail.then(() => client.sendSealedTo(token, obj, { peerEncPub: rek, pilar: true }))
|
|
690
|
+
.catch((e) => log(`[vault] could not send a sealed reply (${e.code || 'error'}): ${e.message}`))
|
|
691
|
+
})
|
|
692
|
+
}
|
|
693
|
+
sealedChannelAt.delete(id)
|
|
694
|
+
sealedChannelAt.set(id, now)
|
|
695
|
+
return id
|
|
696
|
+
}
|
|
697
|
+
const unsealedTold = new Map()
|
|
698
|
+
/** MIGRACIÓN (caduca 2026-12-15): una petición en claro de un cliente viejo. */
|
|
699
|
+
function unsealedRequest (from, payload) {
|
|
700
|
+
const type = String(payload.type)
|
|
701
|
+
if (!unsealedRequestsAllowed()) {
|
|
702
|
+
audit('rejected', { what: type, reason: 'unsealed' })
|
|
703
|
+
reply(from, { type: MSG.ERROR, error: `${type}: requests must be sealed to this vault — update the client`, code: 'request-unsealed' })
|
|
704
|
+
return false
|
|
705
|
+
}
|
|
706
|
+
const t = Date.now()
|
|
707
|
+
if (t - (unsealedTold.get(type) || 0) > 60 * 60 * 1000) {
|
|
708
|
+
unsealedTold.set(type, t)
|
|
709
|
+
log(`[vault] ${type} arrived UNSEALED from an old client: served until ${UNSEALED_REQUESTS_UNTIL_TEXT} (migration), then refused — update it`)
|
|
710
|
+
}
|
|
711
|
+
return true
|
|
712
|
+
}
|
|
713
|
+
const SEALED_TYPES = new Set(SEALED_REQUEST_TYPES)
|
|
714
|
+
|
|
715
|
+
|
|
659
716
|
/**
|
|
660
717
|
* QUÉ SOMOS, Y QUÉ CORRE CADA APARATO (CONVENCIONES §14, `@dotrino/compat`).
|
|
661
718
|
*
|
|
@@ -2140,12 +2197,7 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2140
2197
|
if (op === 'blocked') return answer({ op: 'blocked', items: blocked.list() })
|
|
2141
2198
|
if (op === 'grant-revoke') {
|
|
2142
2199
|
const gid = typeof p.data?.id === 'string' ? p.data.id : ''
|
|
2143
|
-
|
|
2144
|
-
if (ok) {
|
|
2145
|
-
audit('secrets.grant.revoked', { id: gid, by })
|
|
2146
|
-
log(`[vault] grant ${gid} revoked by ${by} — that command will ring again`)
|
|
2147
|
-
}
|
|
2148
|
-
return answer({ op: 'grant-revoke.result', id: gid, ok })
|
|
2200
|
+
return answer({ op: 'grant-revoke.result', id: gid, ok: revokeGrantBy(gid, by) })
|
|
2149
2201
|
}
|
|
2150
2202
|
const id = typeof p.data?.id === 'string' ? p.data.id : ''
|
|
2151
2203
|
const pend = approvals.take(id)
|
|
@@ -2286,6 +2338,16 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2286
2338
|
}
|
|
2287
2339
|
}
|
|
2288
2340
|
|
|
2341
|
+
/** Corta una concesión (desde /approvals o desde la consola de administración). */
|
|
2342
|
+
function revokeGrantBy (gid, by) {
|
|
2343
|
+
const ok = gid ? grants.revoke(gid) : false
|
|
2344
|
+
if (ok) {
|
|
2345
|
+
audit('secrets.grant.revoked', { id: gid, by })
|
|
2346
|
+
log(`[vault] grant ${gid} revoked by ${by} — that command will ring again`)
|
|
2347
|
+
}
|
|
2348
|
+
return ok
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2289
2351
|
async function withSealedContext (items, approver, record) {
|
|
2290
2352
|
const encPub = (record?.members || []).find((m) => m.pub === approver)?.encPub || null
|
|
2291
2353
|
const output = []
|
|
@@ -2570,6 +2632,19 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
2570
2632
|
if (pass.throttled) reply(from, { type: MSG.ERROR, error: 'too many tries: wait before trying again', code: 'too-many-tries', waitMs: pass.waitMs })
|
|
2571
2633
|
return
|
|
2572
2634
|
}
|
|
2635
|
+
// ¿SELLADA? Por el socket local (`channels`) no hace falta: no toca la red. Por el proxio,
|
|
2636
|
+
// lo que pide un aparato tiene que venir sellado, y su respuesta vuelve sellada a `rek`.
|
|
2637
|
+
if (SEALED_TYPES.has(payload.type) && !channels.has(from)) {
|
|
2638
|
+
if (meta?.sealed) {
|
|
2639
|
+
const rek = payload?.data?.rek
|
|
2640
|
+
if (!ActaPilar.isEncPub(rek)) {
|
|
2641
|
+
// Sellada pero sin a dónde sellar la respuesta: contestar en claro sería deshacer el
|
|
2642
|
+
// sobre de la petición. Se dice, en claro y sin nada del aparato dentro.
|
|
2643
|
+
return reply(from, { type: MSG.ERROR, error: `${payload.type}: a sealed request needs data.rek to seal the reply to`, code: 'no-reply-key' })
|
|
2644
|
+
}
|
|
2645
|
+
from = sealedChannel(from, rek)
|
|
2646
|
+
} else if (!unsealedRequest(from, payload)) return
|
|
2647
|
+
}
|
|
2573
2648
|
try {
|
|
2574
2649
|
if (payload.type === MSG.HELLO) return desk.handleHello(from, payload)
|
|
2575
2650
|
if (payload.type === MSG.ENROLL) return await desk.handleEnroll(from, payload)
|
|
@@ -3521,6 +3596,13 @@ export async function startVault ({ platform, proxyUrl, log = console.log, onEnr
|
|
|
3521
3596
|
deviceIdOf,
|
|
3522
3597
|
audit,
|
|
3523
3598
|
blocked: { list: () => blocked.list(), set: setBlocked },
|
|
3599
|
+
grants: {
|
|
3600
|
+
list: async (device) => {
|
|
3601
|
+
const record = (await identity.profileActa?.().catch(() => null))?.acta
|
|
3602
|
+
return { items: await withSealedContext(grants.list(), device, record), ttlMs: GRANT_TTL_MS }
|
|
3603
|
+
},
|
|
3604
|
+
revoke: async (id, { by }) => revokeGrantBy(id, by)
|
|
3605
|
+
},
|
|
3524
3606
|
// Abrir a distancia. Va inyectado porque `admin.js` es puro y esto necesita cripto y
|
|
3525
3607
|
// disco; `null` si este perfil no lo soporta, y entonces la operación contesta que no.
|
|
3526
3608
|
unlockDesk,
|
package/lib/src/protocol.js
CHANGED
|
@@ -168,3 +168,28 @@ export const VAULT_PROTOCOL = 1
|
|
|
168
168
|
|
|
169
169
|
/** Los protocolos que esta build entiende. Al añadir el 2, aquí van `[1, 2]`. */
|
|
170
170
|
export const VAULT_SPEAKS = [1]
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* LAS PETICIONES DE UN APARATO A SU BÓVEDA VAN SELLADAS (regla `encrypted`, dueño 2026-10-26:
|
|
174
|
+
* nada viaja en claro por la red). El aparato sella la petición ENTERA a la llave de cifrado
|
|
175
|
+
* del transporte de la bóveda (`sendSealed` del pilar, `@dotrino/identity/vault-seal`) y mete
|
|
176
|
+
* dentro de lo firmado la llave de un solo uso a la que se le sella la respuesta (`data.rek`).
|
|
177
|
+
* Diseño: `docs/sealed-requests.md`.
|
|
178
|
+
*
|
|
179
|
+
* Estos son los tipos que lo exigen: lo que pide un aparato con su firma. El emparejamiento,
|
|
180
|
+
* la entrada con contraseña y lo que se cruzan las bóvedas siguen su propio camino.
|
|
181
|
+
*/
|
|
182
|
+
export const SEALED_REQUEST_TYPES = Object.freeze([
|
|
183
|
+
MSG.SIGN, MSG.GET, MSG.STORE, MSG.CHECK, MSG.DEVICES, MSG.RENEW, MSG.SECRETS,
|
|
184
|
+
MSG.ADMIN, MSG.RENOUNCE, MSG.INCIDENT, MSG.REWRAP_OK
|
|
185
|
+
])
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* MIGRACIÓN — CADUCA EL 2026-12-15. Hasta esa fecha una petición de esos tipos que llega en
|
|
189
|
+
* claro (un cliente viejo) se atiende y se apunta en el log; desde esa fecha se rechaza con
|
|
190
|
+
* `request-unsealed`. Lo cubre `test/sealed-requests.test.mjs`. Quitar en cuanto pase.
|
|
191
|
+
*/
|
|
192
|
+
export const UNSEALED_REQUESTS_UNTIL = Date.UTC(2026, 11, 15)
|
|
193
|
+
export const UNSEALED_REQUESTS_UNTIL_TEXT = '2026-12-15'
|
|
194
|
+
/** ¿Todavía se atiende una petición en claro? (migración, ver arriba) */
|
|
195
|
+
export const unsealedRequestsAllowed = (now = Date.now()) => now < UNSEALED_REQUESTS_UNTIL
|
package/lib/src/service.js
CHANGED
|
@@ -27,6 +27,7 @@ import {
|
|
|
27
27
|
verifyDeviceSig, makePairingCode, commitCode, pubkeyId, keyLabel } from '@dotrino/identity/capabilities'
|
|
28
28
|
import { openWrap, wrapForMember, decryptWithCek } from '@dotrino/identity/content'
|
|
29
29
|
import { verifyActa, sealKeyAt, sealersOf, memberCan, checkVaultReply, accountMismatch, verifySealerChain, actaHash } from '@dotrino/identity/acta'
|
|
30
|
+
import { sendToVault, acceptReply } from '@dotrino/identity/vault-seal'
|
|
30
31
|
import { MSG, secretsScope, isValidSecretsNs, VAULT_PROTOCOL, VAULT_SPEAKS } from './protocol.js'
|
|
31
32
|
import { PKG_VERSION } from './version.js'
|
|
32
33
|
import { makeEphemeralKey, openSealed } from './sealed.js'
|
|
@@ -189,7 +190,13 @@ async function freshClient (proxyUrl, connectTimeoutMs = 20000, master = null) {
|
|
|
189
190
|
// preferir. Se mira si está, en vez de apagarlo a mano para siempre: el día que este
|
|
190
191
|
// código corra en un navegador —o que Node lo traiga— se enciende solo.
|
|
191
192
|
const hasWebRTC = typeof globalThis.RTCPeerConnection === 'function'
|
|
192
|
-
|
|
193
|
+
// LA LLAVE DE UN SOLO USO de esta conexión (`docs/sealed-requests.md`): va dentro de cada
|
|
194
|
+
// petición firmada (`rek`) y la bóveda le sella la respuesta. Sin `myEncPub`, para no
|
|
195
|
+
// anunciarla: no es la llave de cifrado del servicio.
|
|
196
|
+
const { makeEncKeypair } = await import('@dotrino/proxy-client')
|
|
197
|
+
const replyKey = await makeEncKeypair()
|
|
198
|
+
const client = new WebSocketProxyClient({ url: proxyUrl, enableWebRTC: hasWebRTC, autoReconnect: false, myEncPrivateKey: replyKey.privateKey })
|
|
199
|
+
client.replyKey = replyKey.encPub
|
|
193
200
|
// connect() del cliente solo se resuelve con 'connected' y solo rechaza en el
|
|
194
201
|
// evento 'error' de transporte: si el socket cierra LIMPIO antes de 'connected'
|
|
195
202
|
// (p.ej. el proxy banea la IP y envía close 1008), la promesa quedaría colgada
|
|
@@ -218,6 +225,22 @@ async function identifyAsService (client, device) {
|
|
|
218
225
|
await client.identifyAs({ publickey: device.publickey, sign: (d) => signWithDevice({ privateJwk: device.privateJwk, data: d }) })
|
|
219
226
|
}
|
|
220
227
|
|
|
228
|
+
/** `rek` dentro de lo firmado: a esa llave se sella la respuesta. El socket local no la lleva. */
|
|
229
|
+
const rekOf = (client) => (client?.replyKey ? { rek: client.replyKey } : {})
|
|
230
|
+
|
|
231
|
+
const toldOnce = new Set()
|
|
232
|
+
const warnOnce = (line) => { if (toldOnce.has(line)) return; toldOnce.add(line); console.error(line) }
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* MANDA UNA PETICIÓN A LA BÓVEDA, SELLADA (`@dotrino/identity/vault-seal`): entera, a la llave
|
|
236
|
+
* de transporte de cada bóveda de la cuenta (las de `acta`, la última que este servicio
|
|
237
|
+
* verificó, o una más nueva que encadene con ella), y enrutada a `dest`. A un replicador
|
|
238
|
+
* (`to`), solo a él.
|
|
239
|
+
*/
|
|
240
|
+
function sendVault (client, dest, payload, { acta = null, to = null } = {}) {
|
|
241
|
+
return sendToVault(client, { dest, to, acta, payload, warn: warnOnce })
|
|
242
|
+
}
|
|
243
|
+
|
|
221
244
|
/** Cuánto espera un agente a que alguien apruebe (el pedido vive 5 min en la bóveda). */
|
|
222
245
|
export const APPROVAL_TIMEOUT_MS = 5 * 60 * 1000 + 10 * 1000
|
|
223
246
|
|
|
@@ -232,8 +255,11 @@ export const APPROVAL_TIMEOUT_MS = 5 * 60 * 1000 + 10 * 1000
|
|
|
232
255
|
function waitForMsg (client, predicate, timeoutMs = 30000, guard = null) {
|
|
233
256
|
return new Promise((resolve, reject) => {
|
|
234
257
|
let unverified = null
|
|
235
|
-
const off = client.on('message', async (_from, payload) => {
|
|
258
|
+
const off = client.on('message', async (_from, payload, meta) => {
|
|
236
259
|
if (!payload || typeof payload !== 'object' || !predicate(payload)) return
|
|
260
|
+
// Lo que no es un error tiene que volver SELLADO (salvo por el socket local, y durante la
|
|
261
|
+
// migración, que se dice). Un error sin firma no decide nada de todos modos.
|
|
262
|
+
if (payload.type !== MSG.ERROR && !acceptReply({ meta, local: !!client.local, type: payload.type, warn: warnOnce })) return
|
|
237
263
|
if (guard && payload.type === MSG.ERROR && !await isMyVaultError(payload, guard)) { unverified = payload; return }
|
|
238
264
|
cleanup(); resolve(payload)
|
|
239
265
|
})
|
|
@@ -475,7 +501,7 @@ export async function enrollWithVault ({ qr, label = 'agent', expectedScope = nu
|
|
|
475
501
|
})
|
|
476
502
|
if (!chk.ok) throw new Error('the vault reply does not check out: ' + chk.reason)
|
|
477
503
|
|
|
478
|
-
return { device, enc: enc ? { publickey: enc.encPublickey, privateJwk: enc.encPrivateJwk } : null, cert: res.cert, iss: qr.iss, proxy: qr.proxy || 'wss://proxy.dotrino.com' }
|
|
504
|
+
return { device, enc: enc ? { publickey: enc.encPublickey, privateJwk: enc.encPrivateJwk } : null, cert: res.cert, iss: qr.iss, proxy: qr.proxy || 'wss://proxy.dotrino.com', acta: res.acta || null }
|
|
479
505
|
} finally { client.close() }
|
|
480
506
|
}
|
|
481
507
|
|
|
@@ -528,10 +554,11 @@ export async function enrollService ({ qr, ns, dir, label, onCode, onReplace, ap
|
|
|
528
554
|
try { onReplace?.(replaced) } catch (_) {}
|
|
529
555
|
}
|
|
530
556
|
|
|
531
|
-
const { device, enc, cert, iss, proxy } = await enrollWithVault({ qr, label, expectedScope: secretsScope(ns), onCode, approveTimeoutMs })
|
|
557
|
+
const { device, enc, cert, iss, proxy, acta } = await enrollWithVault({ qr, label, expectedScope: secretsScope(ns), onCode, approveTimeoutMs })
|
|
532
558
|
// v2: suma `enc`. El `device` (la llave de FIRMA) no se toca — de él sale el
|
|
533
|
-
// id de nodo del proxio y la fila del acta.
|
|
534
|
-
|
|
559
|
+
// id de nodo del proxio y la fila del acta. `acta` (ya verificada aquí dentro): a qué
|
|
560
|
+
// bóvedas se le sella lo que pide; se pone al día con cada respuesta.
|
|
561
|
+
writeServiceIdentity(dir, { v: 2, ns, iss, proxy, device, enc, cert, acta, enrolledAt: Date.now() })
|
|
535
562
|
return { device, enc, cert, iss, replaced }
|
|
536
563
|
}
|
|
537
564
|
|
|
@@ -565,13 +592,13 @@ export async function registerEncKey ({ dir, ns, proxyUrl, masterPubkey, device,
|
|
|
565
592
|
if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
|
|
566
593
|
|
|
567
594
|
const client = await freshClient(proxyUrl, 20000, masterPubkey)
|
|
568
|
-
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
|
|
595
|
+
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
|
|
569
596
|
try {
|
|
570
597
|
await identifyAsService(client, device)
|
|
571
|
-
const data = { op: 'enckey', ns, encPub, publickey: device.publickey, ts: Date.now() }
|
|
598
|
+
const data = { op: 'enckey', ns, encPub, ...rekOf(client), publickey: device.publickey, ts: Date.now() }
|
|
572
599
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
573
600
|
const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
|
|
574
|
-
client
|
|
601
|
+
await sendVault(client, masterPubkey, { type: MSG.SECRETS, data, signature, cert }, { acta: saved?.acta })
|
|
575
602
|
const res = await pending
|
|
576
603
|
if (res.type === MSG.ERROR) throw vaultError(res)
|
|
577
604
|
return { encPub, created, ok: true }
|
|
@@ -617,14 +644,14 @@ export async function storeVars ({ dir, ns, proxyUrl, masterPubkey, device, cert
|
|
|
617
644
|
}
|
|
618
645
|
|
|
619
646
|
const client = await freshClient(proxyUrl, 20000, masterPubkey)
|
|
620
|
-
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
|
|
647
|
+
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
|
|
621
648
|
try {
|
|
622
649
|
await identifyAsService(client, device)
|
|
623
650
|
const ask = async (data) => {
|
|
624
|
-
const signed = { ...data, ns, publickey: device.publickey, ts: Date.now() }
|
|
651
|
+
const signed = { ...data, ns, ...rekOf(client), publickey: device.publickey, ts: Date.now() }
|
|
625
652
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data: signed })
|
|
626
653
|
const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
|
|
627
|
-
client
|
|
654
|
+
await sendVault(client, masterPubkey, { type: MSG.SECRETS, data: signed, signature, cert }, { acta: saved?.acta })
|
|
628
655
|
const res = await pending
|
|
629
656
|
if (res.type === MSG.ERROR) throw vaultError(res)
|
|
630
657
|
await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
|
|
@@ -673,13 +700,13 @@ export async function fetchDigest ({ dir, ns, proxyUrl, masterPubkey, device, ce
|
|
|
673
700
|
if (!isValidSecretsNs(ns)) throw new Error('invalid ns')
|
|
674
701
|
if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
|
|
675
702
|
const client = await freshClient(proxyUrl, 20000, masterPubkey)
|
|
676
|
-
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
|
|
703
|
+
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
|
|
677
704
|
try {
|
|
678
705
|
await identifyAsService(client, device)
|
|
679
|
-
const data = { op: 'digest', ns, publickey: device.publickey, ts: Date.now() }
|
|
706
|
+
const data = { op: 'digest', ns, ...rekOf(client), publickey: device.publickey, ts: Date.now() }
|
|
680
707
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
681
708
|
const pending = waitForMsg(client, (p) => p.type === MSG.ERROR || (p.type === MSG.SECRETS_RESULT && p.body?.op === 'secrets.digest'), timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
|
|
682
|
-
client
|
|
709
|
+
await sendVault(client, masterPubkey, { type: MSG.SECRETS, data, signature, cert }, { acta: saved?.acta })
|
|
683
710
|
const res = await pending
|
|
684
711
|
if (res.type === MSG.ERROR) throw vaultError(res)
|
|
685
712
|
await verifyResponder({ body: res.body, seal: res.seal, acta: res.acta, masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
|
|
@@ -726,10 +753,10 @@ export async function askUpdateApproval ({ product, version, from = null, dir, p
|
|
|
726
753
|
if (typeof product !== 'string' || !product || typeof version !== 'string' || !version) throw new Error('askUpdateApproval: needs product and version')
|
|
727
754
|
if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
|
|
728
755
|
const client = await freshClient(proxyUrl, 20000, masterPubkey)
|
|
729
|
-
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
|
|
756
|
+
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
|
|
730
757
|
try {
|
|
731
758
|
await identifyAsService(client, device)
|
|
732
|
-
const data = { op: 'update-ask', product, version, ...(typeof from === 'string' && from ? { from } : {}), publickey: device.publickey, ts: Date.now() }
|
|
759
|
+
const data = { op: 'update-ask', product, version, ...(typeof from === 'string' && from ? { from } : {}), ...rekOf(client), publickey: device.publickey, ts: Date.now() }
|
|
733
760
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
734
761
|
const mine = (p) => p.type === MSG.ERROR || (p.type === MSG.SECRETS_RESULT && p.body?.op === 'update-ask' && p.body.product === product && p.body.version === version)
|
|
735
762
|
const check = async (res) => {
|
|
@@ -743,7 +770,11 @@ export async function askUpdateApproval ({ product, version, from = null, dir, p
|
|
|
743
770
|
// día por algo que ya se contestó).
|
|
744
771
|
const queue = []
|
|
745
772
|
let wake = null
|
|
746
|
-
const off = client.on('message', (_from, p) => {
|
|
773
|
+
const off = client.on('message', (_from, p, meta) => {
|
|
774
|
+
if (!p || typeof p !== 'object' || !mine(p)) return
|
|
775
|
+
if (p.type !== MSG.ERROR && !acceptReply({ meta, local: !!client.local, type: p.type, warn: warnOnce })) return
|
|
776
|
+
queue.push(p); wake?.()
|
|
777
|
+
})
|
|
747
778
|
const next = (ms, code, message) => new Promise((resolve, reject) => {
|
|
748
779
|
if (queue.length) return resolve(queue.shift())
|
|
749
780
|
const t = setTimeout(() => { wake = null; reject(Object.assign(new Error(message), { code })) }, ms)
|
|
@@ -751,7 +782,7 @@ export async function askUpdateApproval ({ product, version, from = null, dir, p
|
|
|
751
782
|
})
|
|
752
783
|
let body
|
|
753
784
|
try {
|
|
754
|
-
client
|
|
785
|
+
await sendVault(client, masterPubkey, { type: MSG.SECRETS, data, signature, cert }, { acta: saved?.acta })
|
|
755
786
|
body = await check(await next(timeoutMs, 'vault-no-reply', 'update-ask: the vault did not answer'))
|
|
756
787
|
if (body.pending === true) {
|
|
757
788
|
try { onPending?.({ id: body.id, exp: body.exp }) } catch (_) {}
|
|
@@ -840,13 +871,13 @@ async function reportToVault (op, { product, version, from = null, dir, proxyUrl
|
|
|
840
871
|
if (typeof product !== 'string' || !product || typeof version !== 'string' || !version) throw new Error(`${op}: needs product and version`)
|
|
841
872
|
if (!proxyUrl || !masterPubkey || !device || !cert) throw new Error('service not enrolled')
|
|
842
873
|
const client = await freshClient(proxyUrl, 20000, masterPubkey)
|
|
843
|
-
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
|
|
874
|
+
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
|
|
844
875
|
try {
|
|
845
876
|
await identifyAsService(client, device)
|
|
846
|
-
const data = { op, product, version, ...(typeof from === 'string' && from ? { from } : {}), publickey: device.publickey, ts: Date.now() }
|
|
877
|
+
const data = { op, product, version, ...(typeof from === 'string' && from ? { from } : {}), ...rekOf(client), publickey: device.publickey, ts: Date.now() }
|
|
847
878
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
848
879
|
const pending = waitForMsg(client, (p) => p.type === MSG.ERROR || (p.type === MSG.SECRETS_RESULT && p.body?.op === op && p.body.product === product && p.body.version === version), timeoutMs, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
|
|
849
|
-
client
|
|
880
|
+
await sendVault(client, masterPubkey, { type: MSG.SECRETS, data, signature, cert }, { acta: saved?.acta })
|
|
850
881
|
const res = await pending.catch((e) => {
|
|
851
882
|
if (/timeout/.test(e.message)) throw Object.assign(new Error(`${op}: the vault did not answer`), { code: 'vault-no-reply' })
|
|
852
883
|
throw e
|
|
@@ -882,7 +913,7 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
|
|
|
882
913
|
}
|
|
883
914
|
|
|
884
915
|
const client = await freshClient(proxyUrl, 20000, masterPubkey)
|
|
885
|
-
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert })
|
|
916
|
+
const askSealerChain = sealerChainAsker({ client, masterPubkey, device, cert, acta: saved?.acta })
|
|
886
917
|
try {
|
|
887
918
|
await identifyAsService(client, device)
|
|
888
919
|
|
|
@@ -918,12 +949,15 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
|
|
|
918
949
|
// aunque la selle otra bóveda de la cuenta (`verifyResponder`). La primera vez se guarda
|
|
919
950
|
// también con el mismo `seq`, porque un agente de antes no lo tenía.
|
|
920
951
|
if (typeof saved?.actaSeq === 'number' && acta.seq === saved.actaSeq && !Array.isArray(saved.sealers)) remember({ sealers: sealersOf(acta) })
|
|
952
|
+
// A QUIÉN SE SELLA (`docs/sealed-requests.md`): las bóvedas de la cuenta salen de esta acta,
|
|
953
|
+
// que ya se aceptó. Un agente de antes no la tenía guardada: se apunta también con el mismo `seq`.
|
|
954
|
+
if (!saved?.acta || (typeof saved.acta.seq === 'number' && acta.seq > saved.acta.seq)) remember({ acta })
|
|
921
955
|
if (typeof saved?.actaSeq === 'number' && acta.seq <= saved.actaSeq) return
|
|
922
956
|
// Y QUIÉNES REPARTEN. Sale del acta, que llega firmada en cada respuesta, así que no
|
|
923
957
|
// hay una lista que mantener a mano ni un `.env` que se olvide: darle `replica` a un
|
|
924
958
|
// aparato basta para que sus servicios sepan preguntarle cuando la bóveda no esté.
|
|
925
959
|
const replicas = (acta.members || []).filter((m) => memberCan(acta, m.pub, 'replica')).map((m) => m.pub)
|
|
926
|
-
remember({ actaSeq: acta.seq, replicas, sealers: sealersOf(acta) })
|
|
960
|
+
remember({ actaSeq: acta.seq, replicas, sealers: sealersOf(acta), acta })
|
|
927
961
|
}
|
|
928
962
|
|
|
929
963
|
// DOS MOTIVOS PARA PEDIR PAPEL NUEVO:
|
|
@@ -942,10 +976,10 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
|
|
|
942
976
|
// insiste: si falla, se sigue con el papel que hay — que probablemente valga.
|
|
943
977
|
const renewCert = async () => {
|
|
944
978
|
try {
|
|
945
|
-
const data = { op: 'renew', publickey: device.publickey, ts: Date.now() }
|
|
979
|
+
const data = { op: 'renew', ...rekOf(client), publickey: device.publickey, ts: Date.now() }
|
|
946
980
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
947
981
|
const pending = waitForMsg(client, (p) => p.type === MSG.RENEWED || p.type === MSG.ERROR, 15000)
|
|
948
|
-
client
|
|
982
|
+
await sendVault(client, masterPubkey, { type: MSG.RENEW, data, signature, cert }, { acta: saved?.acta })
|
|
949
983
|
const res = await pending
|
|
950
984
|
// SE VERIFICA ANTES DE GUARDARLO. Aquí solo se miraba que fuera para esta llave: un
|
|
951
985
|
// papel cualquiera, sin firma que valga, sustituía al bueno y el servicio se quedaba
|
|
@@ -987,7 +1021,7 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
|
|
|
987
1021
|
const ctx = client.local ? selfContext() : null
|
|
988
1022
|
// `publicOnly` VIAJA FIRMADO (va dentro de `data`), así que nadie lo puede quitar ni
|
|
989
1023
|
// poner por el camino. Quien decide qué se manda es la bóveda; esto solo es la petición.
|
|
990
|
-
data = { op: 'secrets', ns, ek: eph.ek, publickey: device.publickey, ts: Date.now(), v: declarationOf({ product, version, needs }), machine: selfMachine(), ...(ctx ? { ctx } : {}), ...(publicOnly ? { publicOnly: true } : {}) }
|
|
1024
|
+
data = { op: 'secrets', ns, ek: eph.ek, ...rekOf(client), publickey: device.publickey, ts: Date.now(), v: declarationOf({ product, version, needs }), machine: selfMachine(), ...(ctx ? { ctx } : {}), ...(publicOnly ? { publicOnly: true } : {}) }
|
|
991
1025
|
;({ signature } = await signWithDevice({ privateJwk: device.privateJwk, data }))
|
|
992
1026
|
// A QUIÉN SE LE PREGUNTA: primero a la bóveda, y si no contesta, a los REPLICADORES
|
|
993
1027
|
// que el acta nombraba la última vez que la vimos (`docs/replicas.md` §8: «el servicio
|
|
@@ -1007,8 +1041,10 @@ export async function fetchSecrets ({ dir, ns, proxyUrl, masterPubkey, device, c
|
|
|
1007
1041
|
let last = null
|
|
1008
1042
|
for (const target of targets) {
|
|
1009
1043
|
const pending = waitForMsg(client, (p) => p.type === MSG.SECRETS_RESULT || p.type === MSG.ERROR, byTarget, { re: requestRef(signature), masterPubkey, knownSeq: saved?.actaSeq ?? null, knownSealers: saved?.sealers ?? null, askSealerChain })
|
|
1010
|
-
|
|
1011
|
-
|
|
1044
|
+
try {
|
|
1045
|
+
await sendVault(client, target, { type: MSG.SECRETS, data, signature, cert }, target === masterPubkey ? { acta: saved?.acta } : { to: target })
|
|
1046
|
+
res = await pending; break
|
|
1047
|
+
} catch (e) { last = e }
|
|
1012
1048
|
}
|
|
1013
1049
|
if (!res) throw last || new Error('nobody answered: neither the vault nor any replica')
|
|
1014
1050
|
}
|
|
@@ -1252,14 +1288,14 @@ export async function sealedByChain ({ chain, acta, masterPubkey }) {
|
|
|
1252
1288
|
* Pide la cadena de selladoras a la bóveda (`vault.devices`: la manda también a un servicio
|
|
1253
1289
|
* sin `lee`). Una vez por operación: la segunda llamada reusa la primera respuesta.
|
|
1254
1290
|
*/
|
|
1255
|
-
export function sealerChainAsker ({ client, masterPubkey, device, cert, timeoutMs = 15000 }) {
|
|
1291
|
+
export function sealerChainAsker ({ client, masterPubkey, device, cert, acta = null, timeoutMs = 15000 }) {
|
|
1256
1292
|
let pending = null
|
|
1257
1293
|
return () => {
|
|
1258
1294
|
pending = pending || (async () => {
|
|
1259
|
-
const data = { op: 'devices', publickey: device.publickey, ts: Date.now() }
|
|
1295
|
+
const data = { op: 'devices', ...rekOf(client), publickey: device.publickey, ts: Date.now() }
|
|
1260
1296
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
1261
1297
|
const wait = waitForMsg(client, (p) => p.type === MSG.DEVICES_RESULT || (p.type === MSG.ERROR && !p.signed), timeoutMs)
|
|
1262
|
-
client
|
|
1298
|
+
await sendVault(client, masterPubkey, { type: MSG.DEVICES, data, signature, cert }, { acta })
|
|
1263
1299
|
const res = await wait
|
|
1264
1300
|
if (res.type === MSG.ERROR) throw new Error('the vault refused: ' + res.error)
|
|
1265
1301
|
if (!Array.isArray(res.sealerChain) || !res.sealerChain.length) throw new Error('the vault sent no sealer chain')
|
|
@@ -1453,7 +1489,7 @@ export async function watchSecretsChanges ({
|
|
|
1453
1489
|
let client = null
|
|
1454
1490
|
// La cadena de selladoras, pedida por la conexión viva. Una por aviso: se rehace cada vez
|
|
1455
1491
|
// porque la conexión cambia al reconectar.
|
|
1456
|
-
const watchChainAsker = () => sealerChainAsker({ client, masterPubkey: master, device: saved.device, cert: readServiceIdentity(dir)?.cert || saved.cert })
|
|
1492
|
+
const watchChainAsker = () => sealerChainAsker({ client, masterPubkey: master, device: saved.device, cert: readServiceIdentity(dir)?.cert || saved.cert, acta: readServiceIdentity(dir)?.acta || saved.acta })
|
|
1457
1493
|
let retryTimer = null
|
|
1458
1494
|
// Huella de la configuración EN USO. Comparar huellas y no valores es lo que permite
|
|
1459
1495
|
// decir «esto no es lo que está corriendo» sin volver a manejar los secretos.
|
|
@@ -1531,9 +1567,9 @@ export async function watchSecretsChanges ({
|
|
|
1531
1567
|
if (!ident?.enc?.privateJwk) return log('[vault] rewrap: this agent has no encryption key')
|
|
1532
1568
|
const cek = await openWrap({ wrap: body.wrap, myEncPrivateKey: await importDeviceEncKey(ident.enc.privateJwk) })
|
|
1533
1569
|
const wrap = await wrapForMember({ cek, memberEncPub: target.encPub })
|
|
1534
|
-
const data = { op: 'rewrap.ok', owner: body.owner, gen: body.gen, target: body.target, wrap, ts: Date.now() }
|
|
1570
|
+
const data = { op: 'rewrap.ok', owner: body.owner, gen: body.gen, target: body.target, wrap, ...rekOf(client), ts: Date.now() }
|
|
1535
1571
|
const { signature } = await signWithDevice({ privateJwk: saved.device.privateJwk, data })
|
|
1536
|
-
client
|
|
1572
|
+
await sendVault(client, master, { type: MSG.REWRAP_OK, data, signature, cert: saved.cert }, { acta: readServiceIdentity(dir)?.acta || saved.acta })
|
|
1537
1573
|
log(`[vault] key handed to ${String(body.target).slice(0, 12)}… for ${body.owner} (gen ${body.gen})`)
|
|
1538
1574
|
} catch (e) {
|
|
1539
1575
|
log('[vault] rewrap failed: ' + e.message)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/vaultd",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.192.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,10 +22,10 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@dotrino/compat": "0.5.0",
|
|
25
|
-
"@dotrino/identity": "0.
|
|
25
|
+
"@dotrino/identity": "0.136.0",
|
|
26
26
|
"@dotrino/opaque": "0.1.0",
|
|
27
27
|
"@dotrino/passmanager": "0.18.6",
|
|
28
|
-
"@dotrino/proxy-client": "^0.
|
|
28
|
+
"@dotrino/proxy-client": "^0.47.0",
|
|
29
29
|
"@dotrino/roadmap": "0.4.63",
|
|
30
30
|
"@dotrino/store": "0.13.0",
|
|
31
31
|
"@dotrino/update": "0.9.0",
|
package/src/client.js
CHANGED
|
@@ -17,6 +17,8 @@ import { myContentKey, encryptWithCek, decryptWithKeyring } from '@dotrino/ident
|
|
|
17
17
|
import { checkVaultReply } from '@dotrino/identity/acta'
|
|
18
18
|
import { installNodeGlobals } from './node-globals.js'
|
|
19
19
|
import { MSG } from './protocol.js'
|
|
20
|
+
// SELLADO (`docs/sealed-requests.md`): la petición entera a las bóvedas del acta, la respuesta a `rek`.
|
|
21
|
+
import { sendToVault, acceptReply } from '@dotrino/identity/vault-seal'
|
|
20
22
|
|
|
21
23
|
async function freshClient ({ proxyUrl, dir = '.dotrino-vault-device' }) {
|
|
22
24
|
installNodeGlobals(dir)
|
|
@@ -24,11 +26,19 @@ async function freshClient ({ proxyUrl, dir = '.dotrino-vault-device' }) {
|
|
|
24
26
|
// WEBRTC SOLO DONDE EXISTE (ver `lib/src/service.js`): en Node no hay
|
|
25
27
|
// `RTCPeerConnection` y encenderlo reventaría al negociar; en un navegador es nativo y es
|
|
26
28
|
// el camino directo que hay que preferir. Se mira, en vez de apagarlo para siempre.
|
|
27
|
-
|
|
29
|
+
// La llave de un solo uso de la respuesta (`rek`): abre lo que la bóveda le sella, y no se anuncia.
|
|
30
|
+
const { makeEncKeypair } = await import('@dotrino/proxy-client')
|
|
31
|
+
const replyKey = await makeEncKeypair()
|
|
32
|
+
const client = new WebSocketProxyClient({ url: proxyUrl, enableWebRTC: typeof globalThis.RTCPeerConnection === 'function', autoReconnect: false, myEncPrivateKey: replyKey.privateKey })
|
|
33
|
+
client.replyKey = replyKey.encPub
|
|
28
34
|
await client.connect()
|
|
29
35
|
return client
|
|
30
36
|
}
|
|
31
37
|
|
|
38
|
+
const warn = (line) => console.error(line)
|
|
39
|
+
/** Manda a la bóveda SELLADO a las bóvedas que nombra `acta`. */
|
|
40
|
+
const toVault = (client, masterPubkey, acta, payload) => sendToVault(client, { dest: masterPubkey, acta, payload, warn })
|
|
41
|
+
|
|
32
42
|
/** Identifica la conexión bajo la pubkey de dispositivo D (para ser direccionable). */
|
|
33
43
|
async function identifyAsDevice (client, device) {
|
|
34
44
|
if (!client.token) return
|
|
@@ -38,8 +48,10 @@ async function identifyAsDevice (client, device) {
|
|
|
38
48
|
|
|
39
49
|
function waitFor (client, predicate, timeoutMs = 30000) {
|
|
40
50
|
return new Promise((resolve, reject) => {
|
|
41
|
-
const off = client.on('message', (_from, payload) => {
|
|
42
|
-
if (payload
|
|
51
|
+
const off = client.on('message', (_from, payload, meta) => {
|
|
52
|
+
if (!payload || typeof payload !== 'object' || !predicate(payload)) return
|
|
53
|
+
if (payload.type !== MSG.ERROR && !acceptReply({ meta, type: payload.type, warn })) return
|
|
54
|
+
cleanup(); resolve(payload)
|
|
43
55
|
})
|
|
44
56
|
const t = setTimeout(() => { cleanup(); reject(new Error('timeout waiting for the vault response')) }, timeoutMs)
|
|
45
57
|
const cleanup = () => { off(); clearTimeout(t) }
|
|
@@ -115,13 +127,13 @@ export async function verifyRevoke ({ body, signature, master, devicePubkey }) {
|
|
|
115
127
|
}
|
|
116
128
|
|
|
117
129
|
/** Pide a la maestra que firme `payload` (scope vault:sign). */
|
|
118
|
-
export async function requestSign ({ masterPubkey, proxyUrl, device, cert, payload, dir } = {}) {
|
|
130
|
+
export async function requestSign ({ masterPubkey, proxyUrl, device, cert, acta = null, payload, dir } = {}) {
|
|
119
131
|
const client = await freshClient({ proxyUrl, dir })
|
|
120
132
|
try {
|
|
121
|
-
const data = { op: 'sign', payload, publickey: device.publickey, ts: Date.now() }
|
|
133
|
+
const data = { op: 'sign', payload, rek: client.replyKey, publickey: device.publickey, ts: Date.now() }
|
|
122
134
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
123
135
|
const pending = waitFor(client, (p) => p.type === MSG.SIGNED || p.type === MSG.ERROR)
|
|
124
|
-
client
|
|
136
|
+
await toVault(client, masterPubkey, acta, { type: MSG.SIGN, data, signature, cert })
|
|
125
137
|
const res = await pending
|
|
126
138
|
if (res.type === MSG.ERROR) throw new Error(res.error)
|
|
127
139
|
return { signature: res.signature, publickey: res.publickey }
|
|
@@ -129,13 +141,13 @@ export async function requestSign ({ masterPubkey, proxyUrl, device, cert, paylo
|
|
|
129
141
|
}
|
|
130
142
|
|
|
131
143
|
/** Lee un nodo del árbol del vault (scope vault:read). */
|
|
132
|
-
export async function requestGet ({ masterPubkey, proxyUrl, device, cert, id = 'root', dir } = {}) {
|
|
144
|
+
export async function requestGet ({ masterPubkey, proxyUrl, device, cert, acta = null, id = 'root', dir } = {}) {
|
|
133
145
|
const client = await freshClient({ proxyUrl, dir })
|
|
134
146
|
try {
|
|
135
|
-
const data = { op: 'get', id, publickey: device.publickey, ts: Date.now() }
|
|
147
|
+
const data = { op: 'get', id, rek: client.replyKey, publickey: device.publickey, ts: Date.now() }
|
|
136
148
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
137
149
|
const pending = waitFor(client, (p) => p.type === MSG.DATA || p.type === MSG.ERROR)
|
|
138
|
-
client
|
|
150
|
+
await toVault(client, masterPubkey, acta, { type: MSG.GET, data, signature, cert })
|
|
139
151
|
const res = await pending
|
|
140
152
|
if (res.type === MSG.ERROR) throw new Error(res.error)
|
|
141
153
|
return { id: res.id, node: res.node }
|
|
@@ -150,13 +162,13 @@ export async function requestGet ({ masterPubkey, proxyUrl, device, cert, id = '
|
|
|
150
162
|
* después de emparejarlo —y como se le cae uno que le quitaron—. Un cert vencido o
|
|
151
163
|
* revocado no se renueva: ahí toca volver a emparejar.
|
|
152
164
|
*/
|
|
153
|
-
export async function requestRenew ({ masterPubkey, proxyUrl, device, cert, dir } = {}) {
|
|
165
|
+
export async function requestRenew ({ masterPubkey, proxyUrl, device, cert, acta = null, dir } = {}) {
|
|
154
166
|
const client = await freshClient({ proxyUrl, dir })
|
|
155
167
|
try {
|
|
156
|
-
const data = { op: 'renew', publickey: device.publickey, ts: Date.now() }
|
|
168
|
+
const data = { op: 'renew', rek: client.replyKey, publickey: device.publickey, ts: Date.now() }
|
|
157
169
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
158
170
|
const pending = waitFor(client, (p) => p.type === MSG.RENEWED || p.type === MSG.ERROR)
|
|
159
|
-
client
|
|
171
|
+
await toVault(client, masterPubkey, acta, { type: MSG.RENEW, data, signature, cert })
|
|
160
172
|
const res = await pending
|
|
161
173
|
if (res.type === MSG.ERROR) throw new Error(res.error)
|
|
162
174
|
// Se valida antes de devolverlo, igual que en el enrolamiento: un cert que no firmó la
|
|
@@ -181,10 +193,10 @@ export async function requestStore ({ masterPubkey, proxyUrl, device, cert, acta
|
|
|
181
193
|
const enc = await encryptWithCek({ cek: mine.cek, gen: mine.gen, plaintext: JSON.stringify(args ?? {}) })
|
|
182
194
|
const client = await freshClient({ proxyUrl, dir })
|
|
183
195
|
try {
|
|
184
|
-
const data = { op: 'store', method, enc, publickey: device.publickey, ts: Date.now() }
|
|
196
|
+
const data = { op: 'store', method, enc, rek: client.replyKey, publickey: device.publickey, ts: Date.now() }
|
|
185
197
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
186
198
|
const pending = waitFor(client, (p) => p.type === MSG.STORE_RESULT || p.type === MSG.ERROR)
|
|
187
|
-
client
|
|
199
|
+
await toVault(client, masterPubkey, acta, { type: MSG.STORE, data, signature, cert })
|
|
188
200
|
const res = await pending
|
|
189
201
|
if (res.type === MSG.ERROR) throw Object.assign(new Error(res.error), res.code ? { code: res.code } : {})
|
|
190
202
|
if (!res.result?.__enc) throw Object.assign(new Error('the vault replied to the store without encrypting it'), { code: 'vault-reply-unsealed' })
|
|
@@ -200,7 +212,7 @@ export async function requestStore ({ masterPubkey, proxyUrl, device, cert, acta
|
|
|
200
212
|
* El `nonce` de un solo uso NO es decorativo: `approve` y `revoke` cambian estado, así
|
|
201
213
|
* que la ventana de frescura de ±5 min no basta para descartar un replay.
|
|
202
214
|
*/
|
|
203
|
-
export async function requestAdmin ({ masterPubkey, proxyUrl, device, cert, op, dir, nonce: dado, ...rest } = {}) {
|
|
215
|
+
export async function requestAdmin ({ masterPubkey, proxyUrl, device, cert, acta = null, op, dir, nonce: dado, ...rest } = {}) {
|
|
204
216
|
const client = await freshClient({ proxyUrl, dir })
|
|
205
217
|
try {
|
|
206
218
|
// EL NONCE SE PUEDE DAR. Abrir la bóveda a distancia lo mete TAMBIÉN dentro del sobre
|
|
@@ -209,10 +221,10 @@ export async function requestAdmin ({ masterPubkey, proxyUrl, device, cert, op,
|
|
|
209
221
|
const nonce = typeof dado === 'string' && dado.length >= 16
|
|
210
222
|
? dado
|
|
211
223
|
: [...crypto.getRandomValues(new Uint8Array(16))].map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
212
|
-
const data = { op, ...rest, publickey: device.publickey, ts: Date.now(), nonce }
|
|
224
|
+
const data = { op, ...rest, rek: client.replyKey, publickey: device.publickey, ts: Date.now(), nonce }
|
|
213
225
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
214
226
|
const pending = waitFor(client, (p) => p.type === MSG.ADMIN_RESULT || p.type === MSG.ERROR)
|
|
215
|
-
client
|
|
227
|
+
await toVault(client, masterPubkey, acta, { type: MSG.ADMIN, data, signature, cert })
|
|
216
228
|
const res = await pending
|
|
217
229
|
if (res.type === MSG.ERROR) {
|
|
218
230
|
// CON LO QUE TRAE: el `code` y —al abrir— el freno. Emparejar por el TEXTO es lo que
|
package/src/replica.js
CHANGED
|
@@ -23,10 +23,10 @@
|
|
|
23
23
|
import fs from 'node:fs'
|
|
24
24
|
import path from 'node:path'
|
|
25
25
|
import os from 'node:os'
|
|
26
|
-
import { WebSocketProxyClient } from '@dotrino/proxy-client'
|
|
26
|
+
import { WebSocketProxyClient, makeEncKeypair, exportEncPrivate, importEncPrivate, isEncPub } from '@dotrino/proxy-client'
|
|
27
27
|
import { signWithDevice, verifyDeviceSig, verifyChain, pubkeyId, keyLabel } from '@dotrino/identity/capabilities'
|
|
28
28
|
import { verifyActa, memberCan, memberCanReadSecrets, sealKeyAt, sealersOf } from '@dotrino/identity/acta'
|
|
29
|
-
import { MSG, secretsScope, isValidSecretsNs } from '../lib/src/protocol.js'
|
|
29
|
+
import { MSG, secretsScope, isValidSecretsNs, unsealedRequestsAllowed, UNSEALED_REQUESTS_UNTIL_TEXT } from '../lib/src/protocol.js'
|
|
30
30
|
import { FRESH_WINDOW_MS } from '../lib/src/enroll.js'
|
|
31
31
|
import { seal } from '../lib/src/sealed.js'
|
|
32
32
|
import { atRestFor } from './atrest.js'
|
|
@@ -165,7 +165,19 @@ export async function runReplica ({ dir = replicaDir(), proxyUrl, wakeUrl = null
|
|
|
165
165
|
// Por llave solo se habla con la BÓVEDA (`link.iss`), que es a quien queremos alcanzar
|
|
166
166
|
// aunque no esté conectada ahora mismo.
|
|
167
167
|
|
|
168
|
-
|
|
168
|
+
/**
|
|
169
|
+
* LA LLAVE DE TRANSPORTE (`docs/sealed-requests.md`): con ella abre lo que los servicios le
|
|
170
|
+
* sellan —qué cajón piden, desde qué máquina— y nada más. No es una llave del acta: el acta
|
|
171
|
+
* sigue sin nombrarle llave de cifrado, así que ningún sobre de secretos puede ir a ella.
|
|
172
|
+
* Se estrena una vez y se guarda con el enlace (cifrado en reposo); su pública la anuncia el
|
|
173
|
+
* pilar, firmada por la llave del aparato, al identificarse.
|
|
174
|
+
*/
|
|
175
|
+
if (!link.transport?.priv || !isEncPub(link.transport?.encPub)) {
|
|
176
|
+
const kp = await makeEncKeypair()
|
|
177
|
+
store.setLink({ ...link, transport: { encPub: kp.encPub, priv: await exportEncPrivate(kp.privateKey) } })
|
|
178
|
+
}
|
|
179
|
+
const transport = store.link.transport
|
|
180
|
+
const client = new WebSocketProxyClient({ url, myEncPub: transport.encPub, myEncPrivateKey: await importEncPrivate(transport.priv) })
|
|
169
181
|
await client.connect()
|
|
170
182
|
// El sobre lo arma el pilar (`identifyAs`), que le pone el destinatario.
|
|
171
183
|
await client.identifyAs({ publickey: link.device.publickey, sign: (d) => sign(d) })
|
|
@@ -246,12 +258,31 @@ export async function runReplica ({ dir = replicaDir(), proxyUrl, wakeUrl = null
|
|
|
246
258
|
* y no hace falta: quitar un aparato es sacarlo del acta (`docs/acta-de-perfil.md`), y de
|
|
247
259
|
* eso se ocupa `memberCanReadSecrets` con el acta de abajo.
|
|
248
260
|
*/
|
|
249
|
-
async function onSecrets (from, p) {
|
|
261
|
+
async function onSecrets (from, p, meta) {
|
|
250
262
|
const ns = p?.data?.ns
|
|
251
263
|
const ek = p?.data?.ek
|
|
252
264
|
if (!isValidSecretsNs(ns) || typeof ek !== 'string') return
|
|
253
|
-
|
|
254
|
-
|
|
265
|
+
// LO QUE SE CONTESTA VUELVE SELLADO a la llave de un solo uso de la petición (`data.rek`)
|
|
266
|
+
// cuando la petición vino sellada. En claro solo durante la migración (caduca 2026-12-15).
|
|
267
|
+
const rek = p?.data?.rek
|
|
268
|
+
const send = (obj) => {
|
|
269
|
+
if (meta?.sealed && isEncPub(rek)) {
|
|
270
|
+
return client.sendSealedTo(from, obj, { peerEncPub: rek, pilar: true })
|
|
271
|
+
.catch((e) => log(`[replica] could not send a sealed reply (${e.code || 'error'}): ${e.message}`))
|
|
272
|
+
}
|
|
273
|
+
client.send(from, obj)
|
|
274
|
+
}
|
|
275
|
+
if (!meta?.sealed) {
|
|
276
|
+
if (!unsealedRequestsAllowed()) {
|
|
277
|
+
log('[replica] a secrets request arrived UNSEALED: refused (the migration window is over)')
|
|
278
|
+
return client.send(from, { type: MSG.ERROR, error: 'replica: requests must be sealed — update the client', code: 'request-unsealed' })
|
|
279
|
+
}
|
|
280
|
+
if (!unsealedTold) { unsealedTold = true; log(`[replica] a secrets request arrived UNSEALED from an old client: served until ${UNSEALED_REQUESTS_UNTIL_TEXT} (migration), then refused`) }
|
|
281
|
+
} else if (!isEncPub(rek)) {
|
|
282
|
+
return client.send(from, { type: MSG.ERROR, error: 'replica: a sealed request needs data.rek to seal the reply to', code: 'no-reply-key' })
|
|
283
|
+
}
|
|
284
|
+
if (!store.acta) return send({ type: MSG.ERROR, error: 'replica: no record yet' })
|
|
285
|
+
const no = (error) => send({ type: MSG.ERROR, error })
|
|
255
286
|
const acta = store.acta
|
|
256
287
|
|
|
257
288
|
if (typeof p?.data?.ts !== 'number' || Math.abs(Date.now() - p.data.ts) > FRESH_WINDOW_MS) {
|
|
@@ -280,7 +311,7 @@ export async function runReplica ({ dir = replicaDir(), proxyUrl, wakeUrl = null
|
|
|
280
311
|
const b = store.bundleFor(ns, who)
|
|
281
312
|
if (!b) {
|
|
282
313
|
log(`[replica] asked for "${ns}" and has nothing stored for that device`)
|
|
283
|
-
return
|
|
314
|
+
return send({
|
|
284
315
|
type: MSG.ERROR,
|
|
285
316
|
error: `replica: nothing stored for "${ns}" and this device — ask the vault once while it is up`
|
|
286
317
|
})
|
|
@@ -290,18 +321,19 @@ export async function runReplica ({ dir = replicaDir(), proxyUrl, wakeUrl = null
|
|
|
290
321
|
// `by` y no `seq`: no tenemos la llave de sellado y no debemos tenerla. Quien recibe
|
|
291
322
|
// mira el acta, ve que a esta llave le reconoce `replica`, y acepta.
|
|
292
323
|
const { signature } = await sign(body)
|
|
293
|
-
|
|
324
|
+
send({ type: MSG.SECRETS_RESULT, body, seal: { by: link.device.publickey, sig: signature } })
|
|
294
325
|
log(`[replica] served "${ns}" from record #${store.seq}`)
|
|
295
326
|
}
|
|
296
327
|
|
|
297
328
|
/** Todo lo que DECIDE algo se contesta que no, y se dice por qué. */
|
|
298
329
|
const NO_DECIDE = new Set([MSG.ENROLL, MSG.ADMIN, MSG.RENEW, MSG.RENOUNCE, MSG.SIGN, MSG.ACTA_SEALED])
|
|
299
330
|
|
|
300
|
-
|
|
331
|
+
let unsealedTold = false
|
|
332
|
+
client.on('message', (from, p, meta) => {
|
|
301
333
|
onActivity?.()
|
|
302
334
|
const t = p?.type
|
|
303
335
|
if (t === MSG.REPLICA_PUSH) return onPush(from, p).catch((e) => log('[replica] push: ' + e.message))
|
|
304
|
-
if (t === MSG.SECRETS) return onSecrets(from, p).catch((e) => log('[replica] secrets: ' + e.message))
|
|
336
|
+
if (t === MSG.SECRETS) return onSecrets(from, p, meta).catch((e) => log('[replica] secrets: ' + e.message))
|
|
305
337
|
if (NO_DECIDE.has(t)) {
|
|
306
338
|
log(`[replica] refused "${t}": a replica hands things out, it does not decide`)
|
|
307
339
|
return client.send(from, {
|