@dotrino/identity 0.135.1 → 0.136.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/package.json +16 -3
- package/src/index.d.ts +86 -3
- package/types/acta.d.ts +652 -0
- package/types/assertion.d.ts +208 -0
- package/types/avatar.d.ts +11 -0
- package/types/capabilities.d.ts +188 -0
- package/types/content.d.ts +191 -0
- package/types/core.d.ts +1168 -0
- package/types/keyid.d.ts +12 -0
- package/types/machine.d.ts +54 -0
- package/types/peerSync.d.ts +33 -0
- package/types/remote.d.ts +181 -0
- package/types/session.d.ts +163 -0
- package/types/sessionFlow.d.ts +86 -0
- package/types/vaultSeal.d.ts +58 -0
- package/vault/acta.js +2 -2
- package/vault/core.js +22 -16
- package/vault/remote.js +54 -29
- package/vault/vaultSeal.js +126 -0
package/vault/core.js
CHANGED
|
@@ -803,7 +803,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
803
803
|
if (!v?.cert) throw Object.assign(new Error('that profile is not paired with a vault'), { code: 'not-paired' })
|
|
804
804
|
if (!(v.cert.scope || []).includes('vault:approve')) throw Object.assign(new Error('that profile does not approve requests'), { code: 'no-approve' })
|
|
805
805
|
const device = await signerForProfile(pid)
|
|
806
|
-
const r = await remoteApproval({ master: v.master, proxy: v.proxy, device, cert: v.cert, op, id })
|
|
806
|
+
const r = await remoteApproval({ acta: actaOfProfile(pid), master: v.master, proxy: v.proxy, device, cert: v.cert, op, id })
|
|
807
807
|
// Y EL COMANDO SE ABRE TAMBIÉN AQUÍ, con la llave de ESA cuenta. Sin esto los pedidos de
|
|
808
808
|
// las demás cuentas se veían sin comando —el dato por el que se mira la pantalla— y el
|
|
809
809
|
// fallo era mudo: llegaban con su sobre cerrado y nadie lo abría.
|
|
@@ -909,6 +909,11 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
909
909
|
const grantedTo = (key) => (loadGrants()[key]?.scopes) || []
|
|
910
910
|
|
|
911
911
|
const loadActa = () => { try { return JSON.parse(kv.getItem(ACTA_STORAGE) || 'null') } catch (_) { return null } }
|
|
912
|
+
/** El acta guardada de OTRO perfil de este aparato (la del activo es `loadActa`). Dice a qué bóvedas sellarle. */
|
|
913
|
+
const actaOfProfile = (pid) => {
|
|
914
|
+
if (pid === currentPid) return loadActa()
|
|
915
|
+
try { return JSON.parse(rawKv.getItem(`dotrino.identity.p.${pid}.acta`) || 'null') } catch (_) { return null }
|
|
916
|
+
}
|
|
912
917
|
const saveActa = (a) => kv.setItem(ACTA_STORAGE, JSON.stringify(a))
|
|
913
918
|
// VENTANA DE RETENCIÓN (§1.3): el master conserva las últimas actas para que un miembro
|
|
914
919
|
// que estuvo apagado pueda comprobar el encadenamiento al volver. Un tercero no las
|
|
@@ -1635,7 +1640,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
1635
1640
|
const v = loadVaultCert(); const device = loadVaultDevice()
|
|
1636
1641
|
if (!v?.cert || !device) return null
|
|
1637
1642
|
renewLastTry = Date.now()
|
|
1638
|
-
const { cert } = await remoteRenew({ master: v.master, proxy: v.proxy, device, cert: v.cert, onRevoked: wipeVaultLink })
|
|
1643
|
+
const { cert } = await remoteRenew({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert, onRevoked: wipeVaultLink })
|
|
1639
1644
|
kv.setItem(VAULT_CERT_STORAGE, JSON.stringify({ ...v, cert, renewedAt: Date.now() }))
|
|
1640
1645
|
emitVault({ phase: 'renewed', seq: cert.seq })
|
|
1641
1646
|
return cert
|
|
@@ -1877,7 +1882,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
1877
1882
|
let destinatarios = null
|
|
1878
1883
|
if (privados.length) {
|
|
1879
1884
|
destinatarios = await remoteStore({
|
|
1880
|
-
master: v.master, proxy: v.proxy, device, cert: v.cert,
|
|
1885
|
+
acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert,
|
|
1881
1886
|
method: 'profileRecipients', args: {}, onRevoked: wipeVaultLink
|
|
1882
1887
|
})
|
|
1883
1888
|
if (!destinatarios?.recoveryPub) {
|
|
@@ -1900,7 +1905,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
1900
1905
|
}
|
|
1901
1906
|
args.sobre = { e, wraps }
|
|
1902
1907
|
}
|
|
1903
|
-
await remoteStore({ master: v.master, proxy: v.proxy, device, cert: v.cert, method: 'profilePut', args, onRevoked: wipeVaultLink })
|
|
1908
|
+
await remoteStore({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert, method: 'profilePut', args, onRevoked: wipeVaultLink })
|
|
1904
1909
|
lastPushedFields[c.key] = c.cls + '\u0000' + c.value
|
|
1905
1910
|
}
|
|
1906
1911
|
}
|
|
@@ -1962,6 +1967,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
1962
1967
|
const v = loadVaultCert()
|
|
1963
1968
|
if (v?.cert && loadVaultDevice()) return // con papel, ya lo comprueba el camino normal
|
|
1964
1969
|
const r = await remoteCheck({
|
|
1970
|
+
acta,
|
|
1965
1971
|
master: Acta.sealersOf(acta)[0] || null,
|
|
1966
1972
|
proxy: v?.proxy || 'wss://proxy.dotrino.com',
|
|
1967
1973
|
device: { publickey: publickeyJwkStr, privateKey: masterKey() },
|
|
@@ -2025,7 +2031,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
2025
2031
|
if (!v?.cert || !device) return
|
|
2026
2032
|
// EL PAQUETE LO ARMA ESTE APARATO (dueño, 2026-09-03). La bóveda entrega los sobres
|
|
2027
2033
|
// que tiene; aquí se abren los que nos tocan y se compone el perfil.
|
|
2028
|
-
const b = await remoteStore({ master: v.master, proxy: v.proxy, device, cert: v.cert, method: 'profileBundle', args: {}, onRevoked: wipeVaultLink })
|
|
2034
|
+
const b = await remoteStore({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert, method: 'profileBundle', args: {}, onRevoked: wipeVaultLink })
|
|
2029
2035
|
const entries = b?.entries || {}
|
|
2030
2036
|
if (!Object.keys(entries).length) {
|
|
2031
2037
|
// La bóveda aún no tiene perfil: sembrar con el local (si tiene contenido).
|
|
@@ -2391,7 +2397,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
2391
2397
|
}
|
|
2392
2398
|
maybeRenewVaultCert()
|
|
2393
2399
|
try {
|
|
2394
|
-
const firmado = await remoteSign({ master: v.master, proxy: v.proxy, device, cert: v.cert, payload: data, onRevoked: wipeVaultLink })
|
|
2400
|
+
const firmado = await remoteSign({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert, payload: data, onRevoked: wipeVaultLink })
|
|
2395
2401
|
// A NOMBRE DE QUIÉN, TAMBIÉN CUANDO FIRMA LA BÓVEDA. La respuesta del daemon trae
|
|
2396
2402
|
// `signature` y `publickey` y nada más, así que por este camino la firma salía sin
|
|
2397
2403
|
// identidad ni cadena: quien la recibía no podía ni verificarla (le falta el acta que
|
|
@@ -3003,7 +3009,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
3003
3009
|
// la próxima vez que se renuncie.
|
|
3004
3010
|
const v = loadVaultCert(); const dev = loadVaultDevice()
|
|
3005
3011
|
if (v?.cert && dev) {
|
|
3006
|
-
remoteRenounce({ master: v.master, proxy: v.proxy, device: dev, cert: v.cert, record })
|
|
3012
|
+
remoteRenounce({ acta: loadActa(), master: v.master, proxy: v.proxy, device: dev, cert: v.cert, record })
|
|
3007
3013
|
.catch(() => {})
|
|
3008
3014
|
}
|
|
3009
3015
|
// Si además soy el master, la absorbo ya en el acta.
|
|
@@ -3364,7 +3370,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
3364
3370
|
const v = loadVaultCert(); const device = loadVaultDevice()
|
|
3365
3371
|
if (!v?.cert || !device) throw new Error('this device is not paired with a vault')
|
|
3366
3372
|
maybeRenewVaultCert()
|
|
3367
|
-
try { return await remoteSign({ master: v.master, proxy: v.proxy, device, cert: v.cert, payload, onRevoked: wipeVaultLink }) }
|
|
3373
|
+
try { return await remoteSign({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert, payload, onRevoked: wipeVaultLink }) }
|
|
3368
3374
|
catch (e) { return handleVaultError(e) }
|
|
3369
3375
|
},
|
|
3370
3376
|
|
|
@@ -3391,7 +3397,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
3391
3397
|
try {
|
|
3392
3398
|
// `wake: false` (lo decide el almacén, dueño 2026-10-28): no despierta a la Nube por cada
|
|
3393
3399
|
// mensaje; solo si lleva más de 24 h sin respaldar, o con el botón de sincronizar.
|
|
3394
|
-
const res = await remoteStore({ master: v.master, proxy: v.proxy, device, cert: v.cert, method, enc, wake, onRevoked: wipeVaultLink })
|
|
3400
|
+
const res = await remoteStore({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert, method, enc, wake, onRevoked: wipeVaultLink })
|
|
3395
3401
|
if (!res || typeof res !== 'object' || !res.__enc) {
|
|
3396
3402
|
throw Object.assign(new Error('the vault replied to the store without encrypting it'), { code: 'vault-reply-unsealed' })
|
|
3397
3403
|
}
|
|
@@ -3439,9 +3445,9 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
3439
3445
|
// LAS CONCESIONES (`grants`) traen el comando sellado a este aparato, como los pedidos:
|
|
3440
3446
|
// se abre aquí, donde está la llave. Lo que no trae nada sellado pasa tal cual.
|
|
3441
3447
|
const opened = async (r) => (Array.isArray(r?.items) ? { ...r, items: await abrirContextos(r.items, currentPid) } : r)
|
|
3442
|
-
if (link.self) return opened(await remoteAdmin({ master: v.master, proxy: v.proxy, device, cert: v.cert, op, ...rest }))
|
|
3448
|
+
if (link.self) return opened(await remoteAdmin({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert, op, ...rest }))
|
|
3443
3449
|
maybeRenewVaultCert()
|
|
3444
|
-
try { return await opened(await remoteAdmin({ master: v.master, proxy: v.proxy, device, cert: v.cert, op, ...rest, onRevoked: wipeVaultLink })) }
|
|
3450
|
+
try { return await opened(await remoteAdmin({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert, op, ...rest, onRevoked: wipeVaultLink })) }
|
|
3445
3451
|
catch (e) { return handleVaultError(e) }
|
|
3446
3452
|
},
|
|
3447
3453
|
|
|
@@ -3459,12 +3465,12 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
3459
3465
|
if (!link) throw new Error('this device is not paired with a vault')
|
|
3460
3466
|
const { v, device } = link
|
|
3461
3467
|
if (link.self) {
|
|
3462
|
-
const r = await remoteApproval({ master: v.master, proxy: v.proxy, device, cert: v.cert, op, id, notify })
|
|
3468
|
+
const r = await remoteApproval({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert, op, id, notify })
|
|
3463
3469
|
if (Array.isArray(r?.items)) return { ...r, items: await abrirContextos(r.items, currentPid) }
|
|
3464
3470
|
return r
|
|
3465
3471
|
}
|
|
3466
3472
|
maybeRenewVaultCert()
|
|
3467
|
-
const ask = (cert) => remoteApproval({ master: v.master, proxy: v.proxy, device, cert, op, id, notify, onRevoked: wipeVaultLink })
|
|
3473
|
+
const ask = (cert) => remoteApproval({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert, op, id, notify, onRevoked: wipeVaultLink })
|
|
3468
3474
|
try {
|
|
3469
3475
|
let r
|
|
3470
3476
|
try { r = await ask(v.cert) } catch (e) {
|
|
@@ -3525,7 +3531,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
3525
3531
|
try {
|
|
3526
3532
|
// `notify` habla de la cuenta ACTIVA: los avisos se suscriben bajo SU llave. De las
|
|
3527
3533
|
// demás no se dice nada, que no es lo mismo que decir que no.
|
|
3528
|
-
const r = await remoteApproval({ master: v.master, proxy: v.proxy, device, cert: v.cert, op: 'approvals', ...(p.id === currentPid ? { notify } : {}) })
|
|
3534
|
+
const r = await remoteApproval({ acta: actaOfProfile(p.id), master: v.master, proxy: v.proxy, device, cert: v.cert, op: 'approvals', ...(p.id === currentPid ? { notify } : {}) })
|
|
3529
3535
|
const items = Array.isArray(r?.items) ? await abrirContextos(r.items, p.id) : []
|
|
3530
3536
|
return { ...base, items }
|
|
3531
3537
|
} catch (e) {
|
|
@@ -3599,7 +3605,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
3599
3605
|
// El acta es la nuestra: no hay nada que adoptar.
|
|
3600
3606
|
if ((!v?.cert || !device) && adminLink()?.self) {
|
|
3601
3607
|
const self = adminLink()
|
|
3602
|
-
const res = await remoteDevices({ master: self.v.master, proxy: self.v.proxy, device: self.device, cert: self.v.cert, sinceSeq: loadActa()?.seq ?? 0, ...target })
|
|
3608
|
+
const res = await remoteDevices({ acta: loadActa(), master: self.v.master, proxy: self.v.proxy, device: self.device, cert: self.v.cert, sinceSeq: loadActa()?.seq ?? 0, ...target })
|
|
3603
3609
|
return { ...res, acta: loadActa() }
|
|
3604
3610
|
}
|
|
3605
3611
|
if (!v?.cert || !device) {
|
|
@@ -3617,7 +3623,7 @@ export async function createIdentityCore ({ kv: hostKv, peers, makeSync = null,
|
|
|
3617
3623
|
}
|
|
3618
3624
|
maybeRenewVaultCert()
|
|
3619
3625
|
try {
|
|
3620
|
-
const res = await remoteDevices({ master: v.master, proxy: v.proxy, device, cert: v.cert, sinceSeq: loadActa()?.seq ?? 0, onRevoked: wipeVaultLink, ...target })
|
|
3626
|
+
const res = await remoteDevices({ acta: loadActa(), master: v.master, proxy: v.proxy, device, cert: v.cert, sinceSeq: loadActa()?.seq ?? 0, onRevoked: wipeVaultLink, ...target })
|
|
3621
3627
|
// El acta viaja con la lista: así los cambios de política llegan sin canal aparte.
|
|
3622
3628
|
// Si estuve apagado, viene la CADENA y se adopta eslabón a eslabón (§1.3).
|
|
3623
3629
|
// Y si no encaja, SE DICE (2026-10-27): callado, el navegador de Seyacat se quedó en la #74
|
package/vault/remote.js
CHANGED
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
import { makeDeviceKey, signWithDevice, verifyDeviceSig, makePairingCode, commitCode, keyLabel } from './capabilities.js'
|
|
17
17
|
import { checkVaultReply, accountMismatch } from './acta.js'
|
|
18
18
|
import { cleanMachine, browserMachine } from './machine.js'
|
|
19
|
+
import { sendToVault, acceptReply } from './vaultSeal.js'
|
|
19
20
|
|
|
20
21
|
const MSG = {
|
|
21
22
|
HELLO: 'vault.hello',
|
|
@@ -282,8 +283,9 @@ export async function enrollDevice ({ qr, device, onChallenge, label = '', conti
|
|
|
282
283
|
* firma. Requiere que el vault esté online.
|
|
283
284
|
* @returns {Promise<{ signature:string, publickey:string }>} publickey = la maestra.
|
|
284
285
|
*/
|
|
285
|
-
export async function requestSign ({ master, proxy, device, cert, payload, onRevoked, timeoutMs = 15000 } = {}) {
|
|
286
|
+
export async function requestSign ({ master, proxy, device, cert, acta = null, payload, onRevoked, timeoutMs = 15000 } = {}) {
|
|
286
287
|
const res = await vaultRpc({
|
|
288
|
+
acta,
|
|
287
289
|
master, proxy, device, cert, onRevoked, timeoutMs,
|
|
288
290
|
sendType: 'vault.sign', okType: 'vault.signed', data: { op: 'sign', payload }
|
|
289
291
|
})
|
|
@@ -342,12 +344,15 @@ function localClient (open) {
|
|
|
342
344
|
const handlers = new Set()
|
|
343
345
|
const chan = open((reply) => { for (const h of [...handlers]) { try { h('local', reply) } catch (_) {} } })
|
|
344
346
|
return {
|
|
347
|
+
// El socket de esta máquina: no toca la red, así que no hay nada que sellar (`vaultSeal.js`).
|
|
348
|
+
local: true,
|
|
345
349
|
connect: async () => {},
|
|
346
350
|
identifyAs: async () => {},
|
|
347
351
|
on (ev, fn) {
|
|
348
352
|
if (ev !== 'message') return () => {}
|
|
349
|
-
|
|
350
|
-
|
|
353
|
+
const h = (from, payload) => fn(from, payload, { local: true })
|
|
354
|
+
handlers.add(h)
|
|
355
|
+
return () => handlers.delete(h)
|
|
351
356
|
},
|
|
352
357
|
sendByPubkey (_to, payload) { chan.send(payload) },
|
|
353
358
|
close () { handlers.clear(); chan.close() }
|
|
@@ -355,28 +360,43 @@ function localClient (open) {
|
|
|
355
360
|
}
|
|
356
361
|
|
|
357
362
|
/** El cliente para hablar con `master`: el local si esa bóveda corre aquí, y si no el del proxio. */
|
|
358
|
-
async function clientFor (proxy, master) {
|
|
363
|
+
async function clientFor (proxy, master, { myEncPrivateKey = null } = {}) {
|
|
359
364
|
const open = master ? localVaults.get(master) : null
|
|
360
365
|
if (open) return localClient(open)
|
|
361
366
|
const { WebSocketProxyClient } = await import('@dotrino/proxy-client')
|
|
362
|
-
|
|
367
|
+
// `myEncPrivateKey` SIN `myEncPub`: abre la respuesta sellada a la llave de un solo uso de
|
|
368
|
+
// esta llamada, y no anuncia nada — anunciarla pisaría la llave de cifrado del aparato.
|
|
369
|
+
const client = new WebSocketProxyClient({ url: proxy, enableWebRTC: false, autoReconnect: false, ...(myEncPrivateKey ? { myEncPrivateKey } : {}) })
|
|
363
370
|
await client.connect()
|
|
364
371
|
return client
|
|
365
372
|
}
|
|
366
373
|
|
|
374
|
+
/** La llave de un solo uso con la que vuelve sellada la respuesta (`vaultSeal.js`). */
|
|
375
|
+
async function makeReplyKey () {
|
|
376
|
+
const { makeEncKeypair } = await import('@dotrino/proxy-client')
|
|
377
|
+
return makeEncKeypair()
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const warnOnce = (() => {
|
|
381
|
+
const told = new Set()
|
|
382
|
+
return (line) => { if (told.has(line)) return; told.add(line); try { console.warn(line) } catch (_) {} }
|
|
383
|
+
})()
|
|
384
|
+
|
|
367
385
|
async function vaultRpc ({ master, to = null, proxy, device, cert, acta = null, sendType, okType, data, onRevoked, timeoutMs = 15000, quiet = false }) {
|
|
368
386
|
// `to`: a qué llave se escribe, si no es la maestra. Con dos bóvedas en la cuenta, la
|
|
369
387
|
// maestra del perfil las alcanza a todas; la llave de comunicación de una, solo a ella.
|
|
370
388
|
const dest = to || master
|
|
371
389
|
if (!master || !proxy || !(device?.privateJwk || device?.privateKey || typeof device?.sign === 'function') || !cert) throw new Error('missing pairing data')
|
|
372
|
-
|
|
390
|
+
// LA RESPUESTA VUELVE SELLADA a esta llave, que va dentro de lo firmado (`vaultSeal.js`).
|
|
391
|
+
const rk = await makeReplyKey()
|
|
392
|
+
const client = await clientFor(proxy, dest, { myEncPrivateKey: rk.privateKey })
|
|
373
393
|
try {
|
|
374
394
|
try { await identifyAsDevice(client, device, { cert, acta }) } catch (_) { /* sin identify seguimos: solo perdemos la cola */ }
|
|
375
|
-
const signed = { ...data, publickey: device.publickey, ts: Date.now(), ...(cleanMachine(device.machine) ? { machine: cleanMachine(device.machine) } : {}) }
|
|
395
|
+
const signed = { ...data, rek: rk.encPub, publickey: device.publickey, ts: Date.now(), ...(cleanMachine(device.machine) ? { machine: cleanMachine(device.machine) } : {}) }
|
|
376
396
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, privateKey: device.privateKey, publickey: device.publickey, sign: device.sign, data: signed })
|
|
377
397
|
const pending = new Promise((resolve, reject) => {
|
|
378
398
|
let graceTimer = null
|
|
379
|
-
const off = client.on('message', (_f, p) => {
|
|
399
|
+
const off = client.on('message', (_f, p, meta) => {
|
|
380
400
|
if (!p || typeof p !== 'object') return
|
|
381
401
|
if (p.type === MSG.REVOKED) {
|
|
382
402
|
isAuthenticRevoke({ body: p.body, signature: p.signature, master, devicePubkey: device.publickey, currentNonce: cert?.nonce || null })
|
|
@@ -384,8 +404,10 @@ async function vaultRpc ({ master, to = null, proxy, device, cert, acta = null,
|
|
|
384
404
|
.catch(() => {})
|
|
385
405
|
return
|
|
386
406
|
}
|
|
387
|
-
if (p.type === okType) {
|
|
388
|
-
|
|
407
|
+
if (p.type === okType) {
|
|
408
|
+
if (!acceptReply({ meta, local: !!client.local, type: okType, warn: warnOnce })) return
|
|
409
|
+
cleanup(); resolve(p)
|
|
410
|
+
} else if (p.type === 'vault.error') {
|
|
389
411
|
// «Te echaron» llega en DOS mensajes: este error (que no va firmado, así que no
|
|
390
412
|
// puede borrar nada — wipe-DoS) y el `vault.revoked` FIRMADO, que es el único que
|
|
391
413
|
// sí. Cerrar el socket al recibir el primero era llegar a cerrar la puerta justo
|
|
@@ -402,7 +424,8 @@ async function vaultRpc ({ master, to = null, proxy, device, cert, acta = null,
|
|
|
402
424
|
const cleanup = () => { off(); clearTimeout(t); clearTimeout(graceTimer) }
|
|
403
425
|
})
|
|
404
426
|
// `quiet`: no despierta a una bóveda dormida (la Nube); si duerme, lo recibe al despertar.
|
|
405
|
-
|
|
427
|
+
// SELLADA a cada bóveda de la cuenta: fuera del sobre solo queda a quién va.
|
|
428
|
+
await sendToVault(client, { dest, to, acta, payload: { type: sendType, data: signed, signature, cert }, quiet, warn: warnOnce })
|
|
406
429
|
return await pending
|
|
407
430
|
} finally { try { client.close() } catch (_) {} }
|
|
408
431
|
}
|
|
@@ -419,19 +442,20 @@ async function vaultRpc ({ master, to = null, proxy, device, cert, acta = null,
|
|
|
419
442
|
* expulsión, ESE es el que borra la cuenta aquí (`onRevoked`); el «no» pelado no borra
|
|
420
443
|
* nada, como cualquier otro mensaje sin firma.
|
|
421
444
|
*/
|
|
422
|
-
export async function checkMembership ({ master, proxy, device, onRevoked, timeoutMs = 12000 } = {}) {
|
|
445
|
+
export async function checkMembership ({ master, proxy, device, acta = null, onRevoked, timeoutMs = 12000 } = {}) {
|
|
423
446
|
if (!master || !proxy || !(device?.privateJwk || device?.privateKey || typeof device?.sign === 'function')) throw new Error('missing device data')
|
|
424
|
-
const
|
|
447
|
+
const rk = await makeReplyKey()
|
|
448
|
+
const client = await clientFor(proxy, master, { myEncPrivateKey: rk.privateKey })
|
|
425
449
|
try {
|
|
426
450
|
// Identificarse hace además que el proxy entregue lo ENCOLADO (un aviso de cuando
|
|
427
451
|
// estaba apagado, si todavía está dentro de las 24 h).
|
|
428
452
|
try { await identifyAsDevice(client, device) } catch (_) {}
|
|
429
|
-
const data = { op: 'check', publickey: device.publickey, ts: Date.now(), ...(cleanMachine(device.machine) ? { machine: cleanMachine(device.machine) } : {}) }
|
|
453
|
+
const data = { op: 'check', rek: rk.encPub, publickey: device.publickey, ts: Date.now(), ...(cleanMachine(device.machine) ? { machine: cleanMachine(device.machine) } : {}) }
|
|
430
454
|
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, privateKey: device.privateKey, publickey: device.publickey, sign: device.sign, data })
|
|
431
455
|
const res = await new Promise((resolve) => {
|
|
432
456
|
let settled = false
|
|
433
457
|
const done = (v) => { if (!settled) { settled = true; cleanup(); resolve(v) } }
|
|
434
|
-
const off = client.on('message', (_f, p) => {
|
|
458
|
+
const off = client.on('message', (_f, p, meta) => {
|
|
435
459
|
if (!p || typeof p !== 'object') return
|
|
436
460
|
if (p.type === MSG.REVOKED) {
|
|
437
461
|
isAuthenticRevoke({ body: p.body, signature: p.signature, master, devicePubkey: device.publickey, currentNonce: null })
|
|
@@ -439,29 +463,30 @@ export async function checkMembership ({ master, proxy, device, onRevoked, timeo
|
|
|
439
463
|
.catch(() => {})
|
|
440
464
|
return
|
|
441
465
|
}
|
|
442
|
-
if (p.type === MSG.CHECKED) done({ in: !!p.in })
|
|
466
|
+
if (p.type === MSG.CHECKED) { if (acceptReply({ meta, local: !!client.local, type: MSG.CHECKED, warn: warnOnce })) done({ in: !!p.in }) }
|
|
443
467
|
else if (p.type === MSG.ERROR) done({ error: p.error })
|
|
444
468
|
})
|
|
445
469
|
const t = setTimeout(() => done({ error: 'the vault did not reply' }), timeoutMs)
|
|
446
470
|
const cleanup = () => { off(); clearTimeout(t) }
|
|
447
|
-
client
|
|
471
|
+
sendToVault(client, { dest: master, acta, payload: { type: MSG.CHECK, data, signature }, warn: warnOnce })
|
|
472
|
+
.catch((e) => done({ error: e.message, code: e.code }))
|
|
448
473
|
})
|
|
449
474
|
return res
|
|
450
475
|
} finally { try { client.close() } catch (_) {} }
|
|
451
476
|
}
|
|
452
477
|
|
|
453
478
|
/** Lee/escribe el store de hilos+aperturas EN el vault (con el cert del dispositivo). */
|
|
454
|
-
export async function requestStore ({ master, proxy, device, cert, method, args, enc, onRevoked, wake = true } = {}) {
|
|
479
|
+
export async function requestStore ({ master, proxy, device, cert, acta = null, method, args, enc, onRevoked, wake = true } = {}) {
|
|
455
480
|
// `enc`: argumentos cifrados con la clave de contenido del perfil (el proxy no los ve).
|
|
456
481
|
const data = enc ? { op: 'store', method, enc } : { op: 'store', method, args: args || {} }
|
|
457
|
-
const res = await vaultRpc({ master, proxy, device, cert, onRevoked, quiet: !wake, sendType: 'vault.store', okType: 'vault.store.result', data })
|
|
482
|
+
const res = await vaultRpc({ master, proxy, device, cert, acta, onRevoked, quiet: !wake, sendType: 'vault.store', okType: 'vault.store.result', data })
|
|
458
483
|
return res.result
|
|
459
484
|
}
|
|
460
485
|
|
|
461
486
|
/** Lista (solo lectura) los dispositivos enrolados en tu vault. */
|
|
462
|
-
export async function requestDevices ({ master, to = null, timeoutMs, proxy, device, cert, sinceSeq, onRevoked } = {}) {
|
|
487
|
+
export async function requestDevices ({ master, to = null, timeoutMs, proxy, device, cert, acta = null, sinceSeq, onRevoked } = {}) {
|
|
463
488
|
const data = typeof sinceSeq === 'number' ? { op: 'devices', sinceSeq } : { op: 'devices' }
|
|
464
|
-
const res = await vaultRpc({ master, to, proxy, device, cert, onRevoked, ...(timeoutMs ? { timeoutMs } : {}), sendType: 'vault.devices', okType: 'vault.devices.result', data })
|
|
489
|
+
const res = await vaultRpc({ master, to, proxy, device, cert, acta, onRevoked, ...(timeoutMs ? { timeoutMs } : {}), sendType: 'vault.devices', okType: 'vault.devices.result', data })
|
|
465
490
|
// `sealerChain`: [génesis, …cambios de sellador…, actual], lo que una firma de este aparato
|
|
466
491
|
// tiene que llevar para que `verifySignedFor` la ate a la cuenta (vaultd ≥ 0.154.0).
|
|
467
492
|
// `siblingCerts`: los papeles que emitieron las OTRAS bóvedas de la cuenta (vaultd ≥ 0.185.0).
|
|
@@ -473,8 +498,8 @@ export async function requestDevices ({ master, to = null, timeoutMs, proxy, dev
|
|
|
473
498
|
* el vault firma uno fresco para la misma sub-clave y scope, sin QR ni aprobación.
|
|
474
499
|
* @returns {Promise<{ cert: object }>}
|
|
475
500
|
*/
|
|
476
|
-
export async function requestRenew ({ master, proxy, device, cert, onRevoked } = {}) {
|
|
477
|
-
const res = await vaultRpc({ master, proxy, device, cert, onRevoked, sendType: 'vault.renew', okType: 'vault.renewed', data: { op: 'renew' } })
|
|
501
|
+
export async function requestRenew ({ master, proxy, device, cert, acta = null, onRevoked } = {}) {
|
|
502
|
+
const res = await vaultRpc({ master, proxy, device, cert, acta, onRevoked, sendType: 'vault.renew', okType: 'vault.renewed', data: { op: 'renew' } })
|
|
478
503
|
// EL ACTA VIAJA CON EL PAPEL y hay que dejarla pasar: quien lo recibe la necesita para
|
|
479
504
|
// comprobar que lo firmó una SELLADORA de este perfil. Aquí se comparaba `cert.iss` con
|
|
480
505
|
// la maestra y se tiraba el acta, así que arriba no había con qué juzgar y la renovación
|
|
@@ -500,9 +525,9 @@ export async function requestRenew ({ master, proxy, device, cert, onRevoked } =
|
|
|
500
525
|
* El `record` va FIRMADO por el propio miembro y solo puede QUITAR, así que la bóveda no
|
|
501
526
|
* necesita comprobar ningún certificado para honrarlo: le basta la firma.
|
|
502
527
|
*/
|
|
503
|
-
export async function requestRenounce ({ master, proxy, device, cert, record, onRevoked } = {}) {
|
|
528
|
+
export async function requestRenounce ({ master, proxy, device, cert, acta = null, record, onRevoked } = {}) {
|
|
504
529
|
const res = await vaultRpc({
|
|
505
|
-
master, proxy, device, cert, onRevoked,
|
|
530
|
+
master, proxy, device, cert, acta, onRevoked,
|
|
506
531
|
sendType: MSG.RENOUNCE, okType: MSG.RENOUNCE_RESULT, data: { op: 'renounce', record }
|
|
507
532
|
})
|
|
508
533
|
return { ok: !!res.ok, seq: res.seq ?? null }
|
|
@@ -520,7 +545,7 @@ export async function requestRenounce ({ master, proxy, device, cert, record, on
|
|
|
520
545
|
* El `nonce` de un solo uso va en cada petición porque `approve` y `revoke` cambian
|
|
521
546
|
* estado, y para eso la ventana de frescura de ±5 min no alcanza.
|
|
522
547
|
*/
|
|
523
|
-
export async function requestAdmin ({ master, to = null, timeoutMs, proxy, device, cert, op, onRevoked, nonce: dado, ...rest } = {}) {
|
|
548
|
+
export async function requestAdmin ({ master, to = null, timeoutMs, proxy, device, cert, acta = null, op, onRevoked, nonce: dado, ...rest } = {}) {
|
|
524
549
|
// EL NONCE SE PUEDE DAR, y hace falta para abrir la bóveda a distancia: ahí va también
|
|
525
550
|
// DENTRO del sobre sellado, y quien lo sella tiene que conocerlo antes de llamar. Si se
|
|
526
551
|
// generara siempre aquí, el de fuera y el de dentro no podrían coincidir — y el de
|
|
@@ -530,7 +555,7 @@ export async function requestAdmin ({ master, to = null, timeoutMs, proxy, devic
|
|
|
530
555
|
: [...crypto.getRandomValues(new Uint8Array(16))]
|
|
531
556
|
.map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
532
557
|
const res = await vaultRpc({
|
|
533
|
-
master, to, proxy, device, cert, onRevoked, ...(timeoutMs ? { timeoutMs } : {}),
|
|
558
|
+
master, to, proxy, device, cert, acta, onRevoked, ...(timeoutMs ? { timeoutMs } : {}),
|
|
534
559
|
sendType: MSG.ADMIN, okType: MSG.ADMIN_RESULT,
|
|
535
560
|
data: { op, ...rest, nonce }
|
|
536
561
|
})
|
|
@@ -543,14 +568,14 @@ export async function requestAdmin ({ master, to = null, timeoutMs, proxy, devic
|
|
|
543
568
|
* `vault:approve` — que, como `admin`, no se recibe al emparejar: se concede a mano.
|
|
544
569
|
* La bóveda contesta un cuerpo firmado por la maestra (`{ op, items | ok }`).
|
|
545
570
|
*/
|
|
546
|
-
export async function requestApproval ({ master, proxy, device, cert, op, id, notify, onRevoked } = {}) {
|
|
571
|
+
export async function requestApproval ({ master, proxy, device, cert, acta = null, op, id, notify, onRevoked } = {}) {
|
|
547
572
|
// `notify`: al pedir la lista, este aparato dice si le llegan los avisos. La bóveda lo
|
|
548
573
|
// apunta y es lo que mira para saber si hay a quién pedirle permiso antes de actualizarse.
|
|
549
574
|
// Solo va si quien llama lo SABE (true o false): no decir nada no cambia lo ya dicho.
|
|
550
575
|
const data = id ? { op, id } : { op }
|
|
551
576
|
if (op === 'approvals' && typeof notify === 'boolean') data.notify = notify
|
|
552
577
|
const res = await vaultRpc({
|
|
553
|
-
master, proxy, device, cert, onRevoked,
|
|
578
|
+
master, proxy, device, cert, acta, onRevoked,
|
|
554
579
|
sendType: MSG.SECRETS, okType: MSG.SECRETS_RESULT,
|
|
555
580
|
data
|
|
556
581
|
})
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* LO QUE UN APARATO LE PIDE A SU BÓVEDA VA SELLADO, Y LO QUE ELLA CONTESTA TAMBIÉN.
|
|
3
|
+
*
|
|
4
|
+
* El proxio no cifra (CONVENCIONES §4.1): una petición firmada pero sin sellar llevaba en
|
|
5
|
+
* claro el `machine` del aparato, el cajón que pedía, el método del almacén o el id del
|
|
6
|
+
* pedido que se aprobaba — todo legible para quien opere el proxio (regla `encrypted` de la
|
|
7
|
+
* auditoría, dueño 2026-10-26: *nada viaja en claro por la red*).
|
|
8
|
+
*
|
|
9
|
+
* El diseño, sin cripto nueva — es el sellado del pilar (`sendSealed` de
|
|
10
|
+
* `@dotrino/proxy-client`, que es `wrapForMember` de `./content.js`):
|
|
11
|
+
*
|
|
12
|
+
* · **La petición ENTERA** (`{ type, data, signature, cert }`) se sella a la llave de
|
|
13
|
+
* cifrado del transporte de cada bóveda de la cuenta. Esas bóvedas son los miembros del
|
|
14
|
+
* acta con `cn: 'vault'` (sus llaves de comunicación), y su llave de cifrado la anuncia
|
|
15
|
+
* cada una firmada al identificarse; el pilar la averigua y verifica la firma. Fuera
|
|
16
|
+
* del sobre queda solo lo que el proxio necesita para enrutar: a quién va
|
|
17
|
+
* (`to_publickey`, la cuenta) y si timbra (`quiet`).
|
|
18
|
+
* · **Se enruta a la cuenta** (`dest`), no a cada bóveda: así sigue despertando a la que
|
|
19
|
+
* duerme (la de la Nube) y llega a todas, como antes. Va un sobre por bóveda y cada una
|
|
20
|
+
* abre solo el suyo.
|
|
21
|
+
* · **La respuesta vuelve sellada a una llave de un solo uso** (`rek`), que va DENTRO de lo
|
|
22
|
+
* firmado: solo quien abrió la petición la conoce, así que una respuesta sellada a ella
|
|
23
|
+
* solo pudo armarla la bóveda. La privada no sale del cliente de esta llamada.
|
|
24
|
+
*
|
|
25
|
+
* MIGRACIÓN — CADUCA EL 2026-12-15 (`PLAIN_UNTIL`). Hasta esa fecha, si no hay a quién
|
|
26
|
+
* sellarle (acta sin la llave de comunicación de la bóveda, o una bóveda que todavía no
|
|
27
|
+
* anuncia su llave de cifrado), la petición sale en claro **y se dice**; y una respuesta
|
|
28
|
+
* sin sellar de una bóveda vieja se acepta **y se dice**. Desde esa fecha, ninguna de las
|
|
29
|
+
* dos cosas: se para con `vault-unsealable` / `vault-reply-unsealed`. Lo cubre
|
|
30
|
+
* `test/vault-seal.test.mjs`. Quitar este bloque en cuanto pase la fecha.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import { VAULT_CN, canAdopt } from './acta.js'
|
|
34
|
+
export { VAULT_CN }
|
|
35
|
+
|
|
36
|
+
/** MIGRACIÓN: hasta cuándo se tolera hablar en claro con una bóveda vieja (2026-12-15 UTC). */
|
|
37
|
+
export const PLAIN_UNTIL = Date.UTC(2026, 11, 15)
|
|
38
|
+
export const PLAIN_UNTIL_TEXT = '2026-12-15'
|
|
39
|
+
|
|
40
|
+
/** ¿Todavía se tolera el claro de la migración? */
|
|
41
|
+
export function plainAllowed (now = Date.now()) { return now < PLAIN_UNTIL }
|
|
42
|
+
|
|
43
|
+
const withCode = (message, code) => Object.assign(new Error(message), { code })
|
|
44
|
+
|
|
45
|
+
/** Las llaves de comunicación de las bóvedas de la cuenta, según el acta. */
|
|
46
|
+
export function vaultKeysOf (acta) {
|
|
47
|
+
return [...new Set((acta?.members || [])
|
|
48
|
+
.filter((m) => m && m.cn === VAULT_CN && typeof m.pub === 'string' && m.pub)
|
|
49
|
+
.map((m) => m.pub))]
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* EL ACTA MÁS NUEVA QUE ENCADENA CON LA MÍA, de la copia que guarda el proxio
|
|
54
|
+
* (`getActas`, websocket-proxy ≥ 1.10.0). Sin esto, un aparato con el acta atrasada le
|
|
55
|
+
* sellaría a una llave de comunicación que la bóveda ya cambió, y la petición se perdería
|
|
56
|
+
* en silencio: la bóveda no puede abrirla y no sabe de quién era.
|
|
57
|
+
*
|
|
58
|
+
* No se fía del proxio: cada acta tiene que verificarse y encadenar con la anterior aceptada
|
|
59
|
+
* (`canAdopt`, la regla de siempre). Un proxio que no guarda actas (`no-acta-cache`) no es un
|
|
60
|
+
* fallo: se sigue con la que ya se tenía, que es la verificada. Cualquier otro error se dice.
|
|
61
|
+
*/
|
|
62
|
+
export async function latestActa (client, acta) {
|
|
63
|
+
if (!acta?.profileId || typeof acta.seq !== 'number' || typeof client?.getActas !== 'function') return acta
|
|
64
|
+
let newer
|
|
65
|
+
try { newer = await client.getActas(acta.profileId, { sinceSeq: acta.seq }) } catch (e) {
|
|
66
|
+
if (e?.code === 'no-acta-cache') return acta
|
|
67
|
+
throw e
|
|
68
|
+
}
|
|
69
|
+
let current = acta
|
|
70
|
+
for (const candidate of [...(newer || [])].filter((a) => typeof a?.seq === 'number' && a.seq > acta.seq).sort((a, b) => a.seq - b.seq)) {
|
|
71
|
+
if ((await canAdopt({ candidate, current })).adopt) current = candidate
|
|
72
|
+
}
|
|
73
|
+
return current
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Manda `payload` a la bóveda SELLADO.
|
|
78
|
+
*
|
|
79
|
+
* @param {any} client un cliente de `@dotrino/proxy-client` (o el local, `client.local`)
|
|
80
|
+
* @param {object} o
|
|
81
|
+
* @param {string} o.dest a qué llave se enruta (la cuenta, o `to`)
|
|
82
|
+
* @param {string|null} [o.to] una bóveda concreta (su llave de comunicación): solo a ella
|
|
83
|
+
* @param {object|null} [o.acta] el acta de la cuenta que este aparato ya aceptó: de ella (o de una
|
|
84
|
+
* más nueva que encadene con ella, `latestActa`) salen las bóvedas
|
|
85
|
+
* @param {object} o.payload `{ type, data, signature, cert }`
|
|
86
|
+
* @param {boolean} [o.quiet] no timbra a una bóveda dormida
|
|
87
|
+
* @param {(line:string)=>void} [o.warn] dónde se dice que salió en claro (migración)
|
|
88
|
+
* @param {number} [o.now]
|
|
89
|
+
* @returns {Promise<{ sealed:number, why?:string }>}
|
|
90
|
+
*/
|
|
91
|
+
export async function sendToVault (client, { dest, to = null, acta = null, payload, quiet = false, warn = null, now = Date.now() }) {
|
|
92
|
+
const opts = quiet ? { quiet: true } : {}
|
|
93
|
+
// EL SOCKET DE ESTA MÁQUINA no toca la red (escalón 1 del transporte): no hay a quién
|
|
94
|
+
// esconderle nada, y ahí la bóveda no tiene llave de cifrado que anunciar.
|
|
95
|
+
if (client?.local) { client.sendByPubkey(dest, payload, opts); return { sealed: 0, why: 'local' } }
|
|
96
|
+
const keys = to ? [to] : vaultKeysOf(await latestActa(client, acta))
|
|
97
|
+
const encPubs = []
|
|
98
|
+
let lastError = null
|
|
99
|
+
for (const k of keys) {
|
|
100
|
+
try { encPubs.push(await client.encPubOf(k)) } catch (e) { lastError = e }
|
|
101
|
+
}
|
|
102
|
+
if (encPubs.length) {
|
|
103
|
+
for (const peerEncPub of encPubs) await client.sendSealed([dest], payload, { peerEncPub, ...opts })
|
|
104
|
+
return { sealed: encPubs.length }
|
|
105
|
+
}
|
|
106
|
+
const why = keys.length ? (lastError?.code || 'no-encpub') : 'no-vault-key'
|
|
107
|
+
if (!plainAllowed(now)) {
|
|
108
|
+
throw withCode(`cannot seal the request to the vault (${why}): update the vault, or let this device see the current record`, 'vault-unsealable')
|
|
109
|
+
}
|
|
110
|
+
// MIGRACIÓN (caduca 2026-12-15): ver la cabecera.
|
|
111
|
+
try { warn?.(`[vault] request ${payload?.type || ''} sent UNSEALED (${why}): tolerated only until ${PLAIN_UNTIL_TEXT} — update the vault`) } catch (_) {}
|
|
112
|
+
client.sendByPubkey(dest, payload, opts)
|
|
113
|
+
return { sealed: 0, why }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* ¿Se acepta esta respuesta? Sellada, siempre. Por el socket local, siempre. En claro, solo
|
|
118
|
+
* durante la migración, y se dice. Devuelve `false` para ignorarla.
|
|
119
|
+
*/
|
|
120
|
+
export function acceptReply ({ meta, local = false, type = '', warn = null, now = Date.now() }) {
|
|
121
|
+
if (local || meta?.sealed) return true
|
|
122
|
+
if (!plainAllowed(now)) return false
|
|
123
|
+
// MIGRACIÓN (caduca 2026-12-15): una bóveda vieja todavía no sella lo que contesta.
|
|
124
|
+
try { warn?.(`[vault] reply ${type} arrived UNSEALED from an old vault: tolerated only until ${PLAIN_UNTIL_TEXT} — update the vault`) } catch (_) {}
|
|
125
|
+
return true
|
|
126
|
+
}
|