@dotrino/remote-agent 0.32.1 → 0.33.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/node-globals.js +11 -5
- package/package.json +8 -5
- package/src/agent.js +112 -40
- package/src/catch-up.js +5 -0
- package/src/client.js +99 -27
- package/src/discover.js +10 -6
- package/src/instances.js +13 -3
- package/src/link.js +81 -20
- package/src/membership.js +5 -1
- package/src/record.js +1 -1
package/node-globals.js
CHANGED
|
@@ -13,7 +13,12 @@ import path from 'node:path'
|
|
|
13
13
|
import WebSocket from 'ws'
|
|
14
14
|
|
|
15
15
|
/** localStorage síncrono respaldado por un archivo JSON (solo lo que usan los paquetes). */
|
|
16
|
+
/**
|
|
17
|
+
* @param {string} filePath
|
|
18
|
+
* @returns {Storage}
|
|
19
|
+
*/
|
|
16
20
|
export function fileLocalStorage (filePath) {
|
|
21
|
+
/** @type {Record<string, string>} */
|
|
17
22
|
let data = {}
|
|
18
23
|
try { if (fs.existsSync(filePath)) data = JSON.parse(fs.readFileSync(filePath, 'utf8')) || {} } catch (_) {}
|
|
19
24
|
const flush = () => {
|
|
@@ -21,19 +26,20 @@ export function fileLocalStorage (filePath) {
|
|
|
21
26
|
fs.writeFileSync(filePath, JSON.stringify(data), { mode: 0o600 })
|
|
22
27
|
}
|
|
23
28
|
return {
|
|
24
|
-
getItem: (k) => (k in data ? data[k] : null),
|
|
25
|
-
setItem: (k, v) => { data[k] = String(v); flush() },
|
|
26
|
-
removeItem: (k) => { delete data[k]; flush() },
|
|
29
|
+
getItem: (/** @type {string} */ k) => (k in data ? data[k] : null),
|
|
30
|
+
setItem: (/** @type {string} */ k, /** @type {unknown} */ v) => { data[k] = String(v); flush() },
|
|
31
|
+
removeItem: (/** @type {string} */ k) => { delete data[k]; flush() },
|
|
27
32
|
clear: () => { data = {}; flush() },
|
|
28
|
-
key: (i) => Object.keys(data)[i] ?? null,
|
|
33
|
+
key: (/** @type {number} */ i) => Object.keys(data)[i] ?? null,
|
|
29
34
|
get length () { return Object.keys(data).length }
|
|
30
35
|
}
|
|
31
36
|
}
|
|
32
37
|
|
|
33
38
|
let _installed = false
|
|
39
|
+
/** @param {string} dir dónde vive `transport.json` (la llave de transporte del proxy-client) */
|
|
34
40
|
export function installNodeGlobals (dir) {
|
|
35
41
|
if (_installed) return
|
|
36
|
-
if (typeof globalThis.WebSocket === 'undefined') globalThis.WebSocket = WebSocket
|
|
42
|
+
if (typeof globalThis.WebSocket === 'undefined') globalThis.WebSocket = /** @type {typeof globalThis.WebSocket} */ (/** @type {unknown} */ (WebSocket)) // `ws` cumple la API que usa el proxy-client
|
|
37
43
|
|
|
38
44
|
// Node ≥22 expone un `localStorage` NO funcional sin `--localstorage-file`, así
|
|
39
45
|
// que aquí se pone el shim de archivo igual. Pero se pone con `defineProperty` y
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/remote-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.33.0",
|
|
4
4
|
"description": "Middleware compartido del ecosistema Dotrino para apps de agente remoto cifrado punto a punto (handshake E2E, emparejamiento SAS con vault, revocación, descubrimiento). Lo consumen dotrino-terminal (PTY) y dotrino-ia (chat con IA).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
@@ -48,13 +48,16 @@
|
|
|
48
48
|
"p2p"
|
|
49
49
|
],
|
|
50
50
|
"peerDependencies": {
|
|
51
|
-
"@dotrino/identity": ">=0.
|
|
51
|
+
"@dotrino/identity": ">=0.136.0",
|
|
52
52
|
"@dotrino/proxy-client": ">=0.46.0",
|
|
53
53
|
"@dotrino/vault": ">=0.115.0"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
|
-
"@dotrino/identity": "0.
|
|
57
|
-
"@dotrino/proxy-client": "0.
|
|
58
|
-
"@dotrino/vault": "0.115.0"
|
|
56
|
+
"@dotrino/identity": "0.136.0",
|
|
57
|
+
"@dotrino/proxy-client": "0.47.0",
|
|
58
|
+
"@dotrino/vault": "0.115.0",
|
|
59
|
+
"@types/node": "22.20.1",
|
|
60
|
+
"@types/ws": "8.18.1",
|
|
61
|
+
"typescript": "5.9.3"
|
|
59
62
|
}
|
|
60
63
|
}
|
package/src/agent.js
CHANGED
|
@@ -23,6 +23,7 @@ import fs from 'node:fs'
|
|
|
23
23
|
import path from 'node:path'
|
|
24
24
|
import { verifyChain, signWithDevice, verifyDeviceSig, pubkeyId, keyLabel } from '@dotrino/identity/capabilities'
|
|
25
25
|
import { sealersOf, memberCan, checkVaultReply } from '@dotrino/identity/acta'
|
|
26
|
+
import { sendToVault, acceptReply } from '@dotrino/identity/vault-seal'
|
|
26
27
|
import { adoptRecord } from './record.js'
|
|
27
28
|
import { canGreet } from './membership.js'
|
|
28
29
|
import { installNodeGlobals } from '../node-globals.js'
|
|
@@ -37,6 +38,10 @@ const PKG_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import
|
|
|
37
38
|
|
|
38
39
|
/** Sesión cifrada con un dispositivo cliente. La app recibe esto en `onSession`. */
|
|
39
40
|
export class AgentSession {
|
|
41
|
+
/**
|
|
42
|
+
* @param {{ sid: string, key: CryptoKey, from: string, device: string,
|
|
43
|
+
* send: (to: string, obj: object) => void, isDirect?: ((token: string) => boolean) | null }} o
|
|
44
|
+
*/
|
|
40
45
|
constructor ({ sid, key, from, device, send, isDirect = null }) {
|
|
41
46
|
this.sid = sid
|
|
42
47
|
this.key = key
|
|
@@ -44,11 +49,32 @@ export class AgentSession {
|
|
|
44
49
|
this.device = device // pubkey del dispositivo cliente
|
|
45
50
|
this._send = send // (to, obj) => void
|
|
46
51
|
this._isDirect = isDirect // (token) => boolean, o null si el transporte no lo sabe
|
|
52
|
+
/** @type {{ message: Array<(msg: any) => void>, close: Array<() => void> }} */
|
|
47
53
|
this._h = { message: [], close: [] }
|
|
48
54
|
this._closed = false
|
|
55
|
+
/** @type {Promise<void> | undefined} */
|
|
56
|
+
this._out = undefined
|
|
57
|
+
/** @type {Promise<void> | undefined} */
|
|
58
|
+
this._in = undefined
|
|
59
|
+
/** Cuándo caduca sin mensajes (ms epoch). Lo pone el agente. */
|
|
60
|
+
this._exp = 0
|
|
61
|
+
/**
|
|
62
|
+
* El nonce del papel del cliente, para cortarla si se revoca.
|
|
63
|
+
* @type {string | null}
|
|
64
|
+
*/
|
|
65
|
+
this._certNonce = null
|
|
66
|
+
/**
|
|
67
|
+
* El cliente se desconectó: se le espera hasta que salte.
|
|
68
|
+
* @type {ReturnType<typeof setTimeout> | null}
|
|
69
|
+
*/
|
|
70
|
+
this._gone = null
|
|
49
71
|
}
|
|
50
72
|
|
|
51
|
-
/**
|
|
73
|
+
/**
|
|
74
|
+
* Envía un payload de dominio cifrado al cliente.
|
|
75
|
+
* @param {unknown} payload
|
|
76
|
+
* @returns {Promise<void>}
|
|
77
|
+
*/
|
|
52
78
|
send (payload) {
|
|
53
79
|
if (this._closed) return Promise.resolve()
|
|
54
80
|
// SALEN EN EL ORDEN EN QUE SE PIDIERON. Cifrar tarda según el tamaño: sin esta cola, un
|
|
@@ -75,6 +101,7 @@ export class AgentSession {
|
|
|
75
101
|
* Espera a que abra el canal directo, como mucho `ms`. Resuelve `true` si abrió y `false`
|
|
76
102
|
* si se acabó el plazo o la sesión se cerró — en los dos casos se sigue, por donde haya.
|
|
77
103
|
*/
|
|
104
|
+
/** @param {number} [ms] @returns {Promise<boolean>} */
|
|
78
105
|
whenDirect (ms = 8000) {
|
|
79
106
|
return new Promise((resolve) => {
|
|
80
107
|
const until = Date.now() + ms
|
|
@@ -88,9 +115,15 @@ export class AgentSession {
|
|
|
88
115
|
})
|
|
89
116
|
}
|
|
90
117
|
|
|
118
|
+
/**
|
|
119
|
+
* @param {'message' | 'close'} ev `message` recibe lo que mandó el cliente, ya descifrado
|
|
120
|
+
* @param {(msg?: any) => void} cb
|
|
121
|
+
* @returns {this}
|
|
122
|
+
*/
|
|
91
123
|
on (ev, cb) { this._h[ev]?.push(cb); return this }
|
|
92
124
|
|
|
93
125
|
/** Lo que llega se entrega en el orden en que llegó, tarde lo que tarde en descifrarse cada uno. */
|
|
126
|
+
/** @param {{ iv: string, ct: string }} env */
|
|
94
127
|
_ingest (env) {
|
|
95
128
|
const opened = open(this.key, env).then((msg) => ({ msg }), () => null)
|
|
96
129
|
this._in = (this._in || Promise.resolve()).then(() => opened).then((r) => {
|
|
@@ -102,7 +135,7 @@ export class AgentSession {
|
|
|
102
135
|
close () {
|
|
103
136
|
if (this._closed) return
|
|
104
137
|
this._closed = true
|
|
105
|
-
clearTimeout(this._gone)
|
|
138
|
+
if (this._gone) clearTimeout(this._gone)
|
|
106
139
|
for (const h of this._h.close) { try { h() } catch (_) {} }
|
|
107
140
|
}
|
|
108
141
|
}
|
|
@@ -110,20 +143,20 @@ export class AgentSession {
|
|
|
110
143
|
/**
|
|
111
144
|
* Arranca el agente. Devuelve `{ machine, machineId, master, client, reportIncident, isBlocked, checkCap, record, close }`.
|
|
112
145
|
*
|
|
113
|
-
* @param {object} opts
|
|
146
|
+
* @param {object} [opts]
|
|
114
147
|
* @param {string} [opts.label] qué agente es (`terminal-agent`, `ia-agent`…): lo contesta el pong
|
|
115
148
|
* para que las apps lo encuentren (`probeAgents`). El nombre del acta es del dueño.
|
|
116
149
|
* @param {string} [opts.proxyUrl] default wss://proxy.dotrino.com.
|
|
117
150
|
* @param {string} [opts.dir] dir del enlace (default dataDir()).
|
|
118
|
-
* @param {
|
|
151
|
+
* @param {import('./link.js').AgentLink | null} [opts.link] enlace ya cargado (override de dir).
|
|
119
152
|
* @param {(session:AgentSession)=>void} [opts.onSession] cada handshake exitoso abre una sesión.
|
|
120
153
|
* @param {()=>void} [opts.onRevoked] se llamó al auto-borrarse por revocación.
|
|
121
|
-
* @param {()=>void} [opts.onReady] agente listo y escuchando.
|
|
154
|
+
* @param {(o: { machine: string, machineId: string, master: string }) => void} [opts.onReady] agente listo y escuchando.
|
|
122
155
|
* @param {boolean} [opts.quiet] sin logs.
|
|
123
156
|
* @param {number} [opts.sessionGoneMs] cuánto se espera a un cliente cuya conexión se fue (`SESSION_GONE_MS`).
|
|
124
157
|
* @param {number} [opts.sessionTtlMs] cuánto dura una sesión sin mensajes (`SESSION_TTL_MS`, 30 min).
|
|
125
158
|
* @param {number} [opts.netLogMs] cada cuánto van al log las estadísticas de red (5 min).
|
|
126
|
-
* @param {
|
|
159
|
+
* @param {import('@dotrino/proxy-client').WebSocketProxyClient} [opts.client] transporte ya conectado (SOLO pruebas).
|
|
127
160
|
* @param {string} [opts.product] qué producto es (`accounts`, `terminal-agent`…), para el anuncio a la bóveda.
|
|
128
161
|
* @param {string} [opts.version] su versión. Sin `product`/`version` se anuncia como `remote-agent`.
|
|
129
162
|
* @param {string[]} [opts.needs] los permisos del acta que necesita, además de `sign`, que lo
|
|
@@ -138,23 +171,25 @@ export class AgentSession {
|
|
|
138
171
|
*/
|
|
139
172
|
export async function startRemoteAgent (opts = {}) {
|
|
140
173
|
const dir = opts.dir || dataDir()
|
|
141
|
-
const
|
|
142
|
-
if (!
|
|
174
|
+
const loaded = opts.link || loadLink(dir)
|
|
175
|
+
if (!loaded?.device?.privateJwk || !loaded?.cert || !loaded?.iss) {
|
|
143
176
|
throw new Error('this machine is not linked: enroll your agent first')
|
|
144
177
|
}
|
|
178
|
+
const link = loaded
|
|
145
179
|
const MY_DECL = declare({
|
|
146
180
|
product: opts.product || 'remote-agent', version: opts.version || PKG_VERSION,
|
|
147
181
|
protocol: VAULT_PROTOCOL, speaks: VAULT_SPEAKS, needs: ['sign', ...(opts.needs || [])]
|
|
148
182
|
})
|
|
149
|
-
const master = link.iss
|
|
183
|
+
const master = /** @type {string} */ (link.iss) // comprobado arriba
|
|
150
184
|
const myPub = link.device.publickey
|
|
151
185
|
const myId = await keyLabel(myPub)
|
|
152
186
|
|
|
153
187
|
installNodeGlobals(dir)
|
|
154
188
|
|
|
155
189
|
// sid -> AgentSession
|
|
190
|
+
/** @type {Map<string, AgentSession>} */
|
|
156
191
|
const sessions = new Map()
|
|
157
|
-
const hasSessionFrom = (token) => { for (const s of sessions.values()) if (s.from === token) return true; return false }
|
|
192
|
+
const hasSessionFrom = (/** @type {string} */ token) => { for (const s of sessions.values()) if (s.from === token) return true; return false }
|
|
158
193
|
|
|
159
194
|
const proxyUrl = opts.proxyUrl || process.env.PROXY_URL || link.proxy || DEFAULT_PROXY
|
|
160
195
|
// `client` inyectado: solo para las pruebas (transporte de mentira). En producción se
|
|
@@ -178,7 +213,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
178
213
|
const identify = async () => {
|
|
179
214
|
if (!client.token) return
|
|
180
215
|
// El sobre lo arma el pilar (`identifyAs`), que le pone el destinatario.
|
|
181
|
-
await client.identifyAs({ publickey: myPub, sign: (d) => signWithDevice({ privateJwk: link.device.privateJwk, data: d }) })
|
|
216
|
+
await client.identifyAs({ publickey: myPub, sign: (/** @type {object} */ d) => signWithDevice({ privateJwk: link.device.privateJwk, data: d }) })
|
|
182
217
|
}
|
|
183
218
|
await identify()
|
|
184
219
|
client.on('token', () => { identify().catch(() => {}) })
|
|
@@ -186,62 +221,86 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
186
221
|
// Bitácora persistente (sessions.log, JSONL): qué dispositivo abrió sesión y cuándo
|
|
187
222
|
// — auditoría local si un dispositivo tuyo cae en malas manos.
|
|
188
223
|
const sessionsLog = path.join(dir, 'sessions.log')
|
|
189
|
-
const audit = (op, info = {}) => {
|
|
224
|
+
const audit = (/** @type {string} */ op, /** @type {object} */ info = {}) => {
|
|
190
225
|
try { fs.appendFileSync(sessionsLog, JSON.stringify({ ts: Date.now(), op, ...info }) + '\n') } catch (_) {}
|
|
191
226
|
}
|
|
192
227
|
|
|
193
|
-
const send = (to, obj) => { try { client.send(to, obj) } catch (e) { if (!opts.quiet) console.error('[remote-agent] send:', e.message) } }
|
|
228
|
+
const send = (/** @type {string} */ to, /** @type {object} */ obj) => { try { client.send(to, obj) } catch (e) { if (!opts.quiet) console.error('[remote-agent] send:', /** @type {Error} */ (e).message) } }
|
|
194
229
|
|
|
195
230
|
/**
|
|
196
231
|
* Petición firmada a la bóveda por el proxy, dirigida a su pubkey maestra. Es el
|
|
197
232
|
* mismo sobre para todo (`data` firmado con la D + el cert de esta máquina): lo
|
|
198
233
|
* comparten el refresco de revocaciones y la renovación del cert.
|
|
199
234
|
*/
|
|
235
|
+
/**
|
|
236
|
+
* @param {string} sendType @param {string} okType @param {object} payload @param {number} [timeoutMs]
|
|
237
|
+
* @returns {Promise<any>} la respuesta de la bóveda; cada llamador lee sus campos con guardas
|
|
238
|
+
*/
|
|
200
239
|
async function vaultRpc (sendType, okType, payload, timeoutMs = 15000) {
|
|
240
|
+
// SELLADA (`dotrino-vault/docs/sealed-requests.md`): la petición entera a las bóvedas del
|
|
241
|
+
// acta, y la respuesta a una llave de un solo uso (`rek`) que va dentro de lo firmado. Por
|
|
242
|
+
// eso va por una conexión PROPIA y corta: el cliente compartido no puede abrir lo sellado a
|
|
243
|
+
// una llave que no es la suya. Con `opts.client` (solo pruebas, una bóveda de mentira) va
|
|
244
|
+
// por ese transporte tal cual.
|
|
245
|
+
const { makeEncKeypair, WebSocketProxyClient } = await import('@dotrino/proxy-client')
|
|
246
|
+
const rk = opts.client ? null : await makeEncKeypair()
|
|
201
247
|
// QUÉ SOY Y QUÉ NECESITO DEL ACTA, dentro de lo firmado: la bóveda lo apunta y enseña lo que
|
|
202
248
|
// falta en la fila de este aparato (dueño, 2026-10-27). `accounts` se pasó días sin `sign`,
|
|
203
249
|
// renovando un papel que no le servía, sin que ninguna pantalla lo dijera.
|
|
204
|
-
const data = { ...payload, v: MY_DECL }
|
|
250
|
+
const data = { ...payload, ...(rk ? { rek: rk.encPub } : {}), v: MY_DECL }
|
|
205
251
|
const { signature } = await signWithDevice({ privateJwk: link.device.privateJwk, data })
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
252
|
+
const message = { type: sendType, data, signature, cert: link.cert }
|
|
253
|
+
/** @type {any} */
|
|
254
|
+
const via = opts.client || new WebSocketProxyClient({ url: proxyUrl, autoReconnect: false, myEncPrivateKey: rk?.privateKey })
|
|
255
|
+
const warn = (/** @type {string} */ line) => { if (!opts.quiet) console.error('[remote-agent] ' + line) }
|
|
256
|
+
try {
|
|
257
|
+
if (!opts.client) await via.connect()
|
|
258
|
+
return await new Promise((resolve, reject) => {
|
|
259
|
+
// El temporizador se LIMPIA al contestar (y no retiene el bucle de eventos):
|
|
260
|
+
// sin eso, cada consulta al vault dejaba 15 s de espera pendiente y un proceso
|
|
261
|
+
// corto que solo quería preguntar algo se quedaba colgado hasta que vencía.
|
|
262
|
+
const done = (/** @type {(v: any) => void} */ fn, /** @type {unknown} */ v) => { off(); clearTimeout(timer); fn(v) }
|
|
263
|
+
const off = via.on('message', (/** @type {any} */ _f, /** @type {any} */ p, /** @type {any} */ meta) => {
|
|
264
|
+
if (p?.type === okType) {
|
|
265
|
+
if (!opts.client && !acceptReply({ meta, type: okType, warn })) return
|
|
266
|
+
done(resolve, p)
|
|
267
|
+
} else if (p?.type === VMSG.ERROR) done(reject, new Error(p.error))
|
|
268
|
+
})
|
|
269
|
+
const timer = setTimeout(() => done(reject, new Error('timeout')), timeoutMs)
|
|
270
|
+
timer.unref?.()
|
|
271
|
+
if (opts.client) via.sendByPubkey(master, message)
|
|
272
|
+
else sendToVault(via, { dest: master, acta: link.acta || null, payload: message, warn }).catch((e) => done(reject, e))
|
|
214
273
|
})
|
|
215
|
-
|
|
216
|
-
timer.unref?.()
|
|
217
|
-
client.sendByPubkey(master, { type: sendType, data, signature, cert: link.cert })
|
|
218
|
-
})
|
|
274
|
+
} finally { if (!opts.client) { try { via.close() } catch (_) {} } }
|
|
219
275
|
}
|
|
220
276
|
|
|
221
277
|
// --- Revocación: refrescar la lista del vault por el proxy (best-effort) ---
|
|
278
|
+
/** @type {Set<string>} */
|
|
222
279
|
let revokedSet = new Set()
|
|
223
280
|
// LOS BLOQUEADOS (dueño, 2026-10-07): un aprobador bloqueó a ese aparato tras un incidente.
|
|
224
281
|
// No es una revocación —sigue en el acta, y se deshace en la bóveda—, así que va aparte y
|
|
225
282
|
// viaja con la lista de revocados. Se PERSISTE en el enlace: con la bóveda apagada, el
|
|
226
283
|
// agente tiene que seguir cerrándole la puerta a quien ya estaba bloqueado.
|
|
284
|
+
/** @type {Set<string>} */
|
|
227
285
|
let blockedSet = new Set(Array.isArray(link.blocked) ? link.blocked : [])
|
|
228
286
|
async function refreshRevocations () {
|
|
229
287
|
try {
|
|
230
288
|
const res = await vaultRpc(VMSG.DEVICES, VMSG.DEVICES_RESULT, { op: 'devices', publickey: myPub, ts: Date.now() })
|
|
231
|
-
revokedSet = new Set((res.revoked || []).map((r) => r.nonce || r))
|
|
289
|
+
revokedSet = new Set((res.revoked || []).map((/** @type {any} */ r) => r.nonce || r))
|
|
232
290
|
if (Array.isArray(res.blocked)) takeBlocked(res.blocked)
|
|
233
291
|
// El acta viaja con la lista. Apuntar su `seq` es lo que dispara la renovación en el
|
|
234
292
|
// mismo tic si el dueño nos cambió los permisos.
|
|
235
293
|
await recordActa(res.acta)
|
|
236
294
|
evictOutsiders()
|
|
237
295
|
} catch (e) {
|
|
238
|
-
if (!opts.quiet) console.error('[remote-agent] could not refresh revocations (using cache):', e.message)
|
|
296
|
+
if (!opts.quiet) console.error('[remote-agent] could not refresh revocations (using cache):', /** @type {Error} */ (e).message)
|
|
239
297
|
}
|
|
240
298
|
}
|
|
241
299
|
|
|
242
300
|
/** La lista nueva de bloqueados: se guarda, y a quien acaba de entrar en ella se le cierra la sesión. */
|
|
301
|
+
/** @param {unknown[]} pubs */
|
|
243
302
|
function takeBlocked (pubs) {
|
|
244
|
-
const next = new Set(pubs.filter((p) => typeof p === 'string'))
|
|
303
|
+
const next = new Set(/** @type {string[]} */ (pubs.filter((p) => typeof p === 'string')))
|
|
245
304
|
const same = next.size === blockedSet.size && [...next].every((p) => blockedSet.has(p))
|
|
246
305
|
blockedSet = next
|
|
247
306
|
if (same) return
|
|
@@ -261,6 +320,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
261
320
|
* bóveda: `{ id, approvers, blocked }` (`id: null` si nadie aprueba o ya está bloqueado).
|
|
262
321
|
* No decide nada aquí: un incidente es información, y el freno local es cosa de la app.
|
|
263
322
|
*/
|
|
323
|
+
/** @param {{ kind: string, about: string, tries?: number | null }} o */
|
|
264
324
|
async function reportIncident ({ kind, about, tries = null }) {
|
|
265
325
|
if (typeof kind !== 'string' || !kind || typeof about !== 'string' || !about) throw new Error('reportIncident: kind and about are required')
|
|
266
326
|
audit('incident', { kind, device: (await pubkeyId(about).catch(() => '')).slice(0, 8).toUpperCase(), tries })
|
|
@@ -300,7 +360,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
300
360
|
// No es fatal: el papel de antes sigue sirviendo para todo lo que el acta le siga
|
|
301
361
|
// permitiendo, y el próximo tic reintenta. Se avisa igual: si esto falla, lo que el
|
|
302
362
|
// dueño acaba de conceder no llega.
|
|
303
|
-
if (!opts.quiet) console.error('[remote-agent] could not renew the cert:', e.message)
|
|
363
|
+
if (!opts.quiet) console.error('[remote-agent] could not renew the cert:', /** @type {Error} */ (e).message)
|
|
304
364
|
}
|
|
305
365
|
}
|
|
306
366
|
|
|
@@ -317,6 +377,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
317
377
|
* mandar un acta inventada y nombrarse miembro. Ahora el acta tiene que encadenar desde la
|
|
318
378
|
* que ya se dio por buena, o venir firmada por la bóveda con la que se enroló.
|
|
319
379
|
*/
|
|
380
|
+
/** @param {any} acta lo que llegó: se comprueba antes de adoptarlo @returns {Promise<boolean>} */
|
|
320
381
|
async function recordActa (acta) {
|
|
321
382
|
if (typeof acta?.seq !== 'number') return false
|
|
322
383
|
const r = await adoptRecord({ link, candidate: acta, me: myPub })
|
|
@@ -344,12 +405,14 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
344
405
|
* puede colar nada, como mucho no tener la más nueva.
|
|
345
406
|
*/
|
|
346
407
|
const actaCacheProblems = new Set()
|
|
408
|
+
/** @param {string} what @param {any} e */
|
|
347
409
|
function noteActaCache (what, e) {
|
|
348
410
|
const code = e?.code || 'error'
|
|
349
411
|
if (actaCacheProblems.has(what + code)) return
|
|
350
412
|
actaCacheProblems.add(what + code)
|
|
351
413
|
if (!opts.quiet) console.error(`[remote-agent] record cache on the proxy (${what}): ${code} · ${e?.message || ''}`)
|
|
352
414
|
}
|
|
415
|
+
/** @param {DotrinoActa} acta */
|
|
353
416
|
function shareActa (acta) {
|
|
354
417
|
// Por detrás y sin tumbar a quien adopta: si falla, se dice una vez y sigue.
|
|
355
418
|
Promise.resolve().then(() => client.putActa(acta)).catch((e) => noteActaCache('put', e))
|
|
@@ -358,6 +421,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
358
421
|
async function actaFromProxy () {
|
|
359
422
|
const profileId = trustedActa()?.profileId
|
|
360
423
|
if (!profileId) return false
|
|
424
|
+
/** @type {object[]} */
|
|
361
425
|
let list
|
|
362
426
|
try { list = await client.getActas(profileId, { sinceSeq: link.actaSeq ?? -1 }) } catch (e) { noteActaCache('get', e); return false }
|
|
363
427
|
for (const a of list) if (await recordActa(a)) return true
|
|
@@ -387,6 +451,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
387
451
|
* El acta con la que se juzga un papel. Sin ella no se atiende a nadie — y un acta que
|
|
388
452
|
* nunca se comprobó (la que guardó una versión anterior) cuenta como no tenerla.
|
|
389
453
|
*/
|
|
454
|
+
/** @returns {DotrinoActa | null} */
|
|
390
455
|
const trustedActa = () => (link.actaTrusted === true && link.acta ? link.acta : null)
|
|
391
456
|
const actaContext = () => {
|
|
392
457
|
const acta = trustedActa()
|
|
@@ -396,7 +461,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
396
461
|
const vaultTick = async () => { await refreshRevocations(); await renewCertIfNeeded() }
|
|
397
462
|
/** Trae el acta ahora (con freno) y dice si AVANZÓ: solo entonces merece juzgar otra vez. */
|
|
398
463
|
// Ponerse al día mira primero la caché del proxio y, si no trae nada que encadene, la bóveda.
|
|
399
|
-
const catchUp = makeCatchUp({ refresh: async () => { if (!await actaFromProxy()) await vaultTick() }, seq: () => link.actaSeq })
|
|
464
|
+
const catchUp = makeCatchUp({ refresh: async () => { if (!await actaFromProxy()) await vaultTick() }, seq: () => link.actaSeq ?? null })
|
|
400
465
|
vaultTick()
|
|
401
466
|
const revTimer = setInterval(vaultTick, REVOKE_REFRESH_MS); revTimer.unref?.()
|
|
402
467
|
|
|
@@ -415,6 +480,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
415
480
|
}
|
|
416
481
|
}, Math.min(60 * 1000, ttlMs)); sweeper.unref?.()
|
|
417
482
|
|
|
483
|
+
/** @param {string} from @param {any} p el saludo tal como llegó: se comprueba campo a campo */
|
|
418
484
|
async function handleHandshake (from, p) {
|
|
419
485
|
const { data, signature, cert } = p
|
|
420
486
|
if (!data || !signature || !cert) return send(from, { type: ERROR, error: 'incomplete handshake' })
|
|
@@ -432,16 +498,17 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
432
498
|
// 2026-10-07). Ahora, ante un rechazo, se trae el acta EN EL MOMENTO y se juzga otra vez, una
|
|
433
499
|
// sola — y solo si el acta avanzó. Con freno (`catchUp`): cualquiera puede mandar saludos, y
|
|
434
500
|
// no por eso se le pregunta a la bóveda cada vez.
|
|
501
|
+
/** @returns {Promise<{ chk: { ok: boolean, device: string }, error?: undefined, code?: undefined, reason?: undefined } | { chk?: undefined, code: string, reason?: string, error: string }>} */
|
|
435
502
|
const judge = async () => {
|
|
436
503
|
const chk = await verifyChain({ data, signature, cert, expectedScope: SIGN_SCOPE, ...actaContext(), revoked: revokedSet })
|
|
437
504
|
if (!chk.ok) return { code: 'unauthorized', reason: chk.reason, error: 'unauthorized: ' + chk.reason }
|
|
438
|
-
return { chk }
|
|
505
|
+
return { chk: { ...chk, device: /** @type {string} */ (chk.device) } } // ok: verifyChain dice qué aparato firmó
|
|
439
506
|
}
|
|
440
507
|
let verdict = await judge()
|
|
441
|
-
const known = (v) => canGreet(trustedActa(), v.chk.device)
|
|
508
|
+
const known = (/** @type {Awaited<ReturnType<typeof judge>>} */ v) => !!v.chk && canGreet(trustedActa(), v.chk.device)
|
|
442
509
|
if ((verdict.error || !known(verdict)) && await catchUp()) verdict = await judge()
|
|
443
510
|
if (verdict.error) return send(from, { type: ERROR, code: verdict.code, reason: verdict.reason, error: verdict.error })
|
|
444
|
-
const chk = verdict.chk
|
|
511
|
+
const chk = /** @type {NonNullable<typeof verdict.chk>} */ (verdict.chk) // sin error hay chk
|
|
445
512
|
// CERT ∩ ACTA. `verifyChain` comprueba QUIÉN EMITIÓ el papel; que el APARATO siga siendo
|
|
446
513
|
// isMember y pueda firmar lo dice el acta, y hay que preguntárselo aparte. Sin esto, un
|
|
447
514
|
// papel bien firmado por una selladora abría sesión aunque el acta no nombrara a ese
|
|
@@ -477,7 +544,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
477
544
|
const ack = { op: ACK, sid, seph: eph.pub, ceph: data.eph, machine: myPub, publickey: myPub, ts: Date.now() }
|
|
478
545
|
const { signature: ackSig } = await signWithDevice({ privateJwk: link.device.privateJwk, data: ack })
|
|
479
546
|
|
|
480
|
-
const session = new AgentSession({ sid, key, from, device: chk.device, send, isDirect: typeof client.isWebRTCOpen === 'function' ? (t) => client.isWebRTCOpen(t) : null })
|
|
547
|
+
const session = new AgentSession({ sid, key, from, device: chk.device, send, isDirect: typeof client.isWebRTCOpen === 'function' ? (/** @type {string} */ t) => client.isWebRTCOpen(t) : null })
|
|
481
548
|
session._exp = Date.now() + ttlMs
|
|
482
549
|
// El papel con que entró: si después se retira (`revoked`), la sesión se cierra.
|
|
483
550
|
session._certNonce = cert.nonce || null
|
|
@@ -485,9 +552,10 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
485
552
|
audit('session-open', { sid: sid.slice(0, 8), device: (await pubkeyId(chk.device)).slice(0, 8).toUpperCase() })
|
|
486
553
|
send(from, { type: ACK, sid, ack, signature: ackSig, cert: link.cert })
|
|
487
554
|
if (!opts.quiet) console.log(`[remote-agent] session ${sid.slice(0, 8)} authorized (device ${chk.device?.slice?.(0, 8) || '?'})`)
|
|
488
|
-
if (opts.onSession) { try { opts.onSession(session) } catch (e) { if (!opts.quiet) console.error('[remote-agent] onSession:', e.message) } }
|
|
555
|
+
if (opts.onSession) { try { opts.onSession(session) } catch (e) { if (!opts.quiet) console.error('[remote-agent] onSession:', /** @type {Error} */ (e).message) } }
|
|
489
556
|
}
|
|
490
557
|
|
|
558
|
+
/** @param {string} from @param {any} p */
|
|
491
559
|
function handleData (from, p) {
|
|
492
560
|
const s = sessions.get(p.sid)
|
|
493
561
|
// Con `code` y el `sid`: así el cliente sabe que es SU sesión la que se perdió (el agente
|
|
@@ -506,14 +574,14 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
506
574
|
// Antes solo vencía por `SESSION_TTL_MS`: un teléfono que volvía del fondo abría sesión nueva
|
|
507
575
|
// y la vieja seguía enganchada a su consola (seis del mismo aparato en una, el 2026-10-09).
|
|
508
576
|
const goneMs = opts.sessionGoneMs ?? SESSION_GONE_MS
|
|
509
|
-
client.on('peer_disconnected', (token) => {
|
|
577
|
+
client.on('peer_disconnected', (/** @type {string} */ token) => {
|
|
510
578
|
for (const [sid, s] of sessions) {
|
|
511
579
|
if (s.from !== token || s._gone) continue
|
|
512
580
|
s._gone = setTimeout(() => {
|
|
513
581
|
s.close(); sessions.delete(sid)
|
|
514
582
|
audit('session-gone', { sid: sid.slice(0, 8) })
|
|
515
583
|
}, goneMs)
|
|
516
|
-
s._gone
|
|
584
|
+
s._gone?.unref?.()
|
|
517
585
|
}
|
|
518
586
|
})
|
|
519
587
|
|
|
@@ -538,6 +606,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
538
606
|
// firma valida y el body es para nuestra pubkey → un proxy/peer malicioso NO puede
|
|
539
607
|
// borrarnos con un mensaje falso (cierra el wipe-DoS). Borra el enlace (link.json) y
|
|
540
608
|
// detiene el agente.
|
|
609
|
+
/** @param {any} p el aviso de revocación: se comprueba su firma */
|
|
541
610
|
async function handleRevoked (p) {
|
|
542
611
|
const b = p?.body
|
|
543
612
|
if (!b || b.op !== 'revoke' || b.sub !== myPub) return
|
|
@@ -557,6 +626,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
557
626
|
* quitar un aparato le cierra la consola en el acto, sin esperar al tic de cinco minutos.
|
|
558
627
|
* Un bloqueo no cambia el acta: va en la lista, que sí se pide.
|
|
559
628
|
*/
|
|
629
|
+
/** @param {any} payload */
|
|
560
630
|
async function onAdminEvent (payload) {
|
|
561
631
|
const ev = payload.body?.ev
|
|
562
632
|
if (ev === 'blocked' || ev === 'unblocked') return refreshRevocations()
|
|
@@ -564,7 +634,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
564
634
|
if (typeof payload.acta?.seq === 'number' && payload.acta.seq > (link.actaSeq ?? -1)) await catchUp()
|
|
565
635
|
}
|
|
566
636
|
|
|
567
|
-
client.on('message', (from, payload) => {
|
|
637
|
+
client.on('message', (/** @type {string} */ from, /** @type {any} */ payload) => {
|
|
568
638
|
if (!payload || typeof payload !== 'object') return
|
|
569
639
|
if (payload.type === HS) handleHandshake(from, payload).catch((e) => send(from, { type: ERROR, error: e.message }))
|
|
570
640
|
else if (payload.type === DATA) handleData(from, payload)
|
|
@@ -592,8 +662,10 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
592
662
|
* Sin repliegue: sin acta no se sabe, y se dice con su código.
|
|
593
663
|
* @returns {Promise<{ ok: true, seq: number } | { ok: false, code: 'no-record'|'not-in-record'|'missing-cap' }>}
|
|
594
664
|
*/
|
|
665
|
+
/** @param {string} pub @param {string} cap */
|
|
595
666
|
async function checkCap (pub, cap) {
|
|
596
667
|
if (typeof pub !== 'string' || !pub || typeof cap !== 'string' || !cap) throw Object.assign(new Error('checkCap: pub and cap are required'), { code: 'bad-request' })
|
|
668
|
+
/** @returns {{ ok: true, seq: number } | { ok: false, code: 'no-record'|'not-in-record'|'missing-cap' }} */
|
|
597
669
|
const look = () => {
|
|
598
670
|
const acta = trustedActa()
|
|
599
671
|
if (!acta) return { ok: false, code: 'no-record' }
|
|
@@ -611,7 +683,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
611
683
|
}
|
|
612
684
|
if (opts.onReady) { try { opts.onReady({ machine: myPub, machineId: myId, master }) } catch (_) {} }
|
|
613
685
|
|
|
614
|
-
return { machine: myPub, machineId: myId, master, client, reportIncident, isBlocked: (pub) => blockedSet.has(pub), checkCap, record: trustedActa, close: stop }
|
|
686
|
+
return { machine: myPub, machineId: myId, master, client, reportIncident, isBlocked: (/** @type {string} */ pub) => blockedSet.has(pub), checkCap, record: trustedActa, close: stop }
|
|
615
687
|
}
|
|
616
688
|
|
|
617
689
|
export default { startRemoteAgent }
|
package/src/catch-up.js
CHANGED
|
@@ -11,8 +11,13 @@
|
|
|
11
11
|
*/
|
|
12
12
|
export const CATCH_UP_GAP_MS = 10_000
|
|
13
13
|
|
|
14
|
+
/**
|
|
15
|
+
* @param {{ refresh: () => Promise<unknown>, seq: () => number | null, minGapMs?: number, now?: () => number }} o
|
|
16
|
+
* @returns {() => Promise<boolean>}
|
|
17
|
+
*/
|
|
14
18
|
export function makeCatchUp ({ refresh, seq, minGapMs = CATCH_UP_GAP_MS, now = Date.now }) {
|
|
15
19
|
let last = -Infinity
|
|
20
|
+
/** @type {Promise<boolean> | null} */
|
|
16
21
|
let running = null
|
|
17
22
|
return async () => {
|
|
18
23
|
// Uno a la vez: los saludos que lleguen mientras tanto esperan a ese mismo y usan su resultado.
|
package/src/client.js
CHANGED
|
@@ -26,15 +26,31 @@ import { makeEphemeral, deriveKey, seal, open } from '../e2e.js'
|
|
|
26
26
|
import { canGreet } from './membership.js'
|
|
27
27
|
import { HS, ACK, DATA, PING, PONG, ERROR, DEFAULT_PROXY } from '../protocol.js'
|
|
28
28
|
|
|
29
|
+
/**
|
|
30
|
+
* El enlace con que se habla a un agente: el de una pestaña (identidad del vault) o el de
|
|
31
|
+
* otro agente (`clientLink`).
|
|
32
|
+
* @typedef {object} ClientLink
|
|
33
|
+
* @property {AgentIdentity} id
|
|
34
|
+
* @property {unknown} cert
|
|
35
|
+
* @property {string} [iss]
|
|
36
|
+
* @property {string} [proxy]
|
|
37
|
+
* @property {string} [mode] 'self': el dispositivo es su propio vault
|
|
38
|
+
* @property {DotrinoActa} [acta] un acta ya comprobada, si la trae
|
|
39
|
+
* @property {() => Promise<unknown>} [getSelfCert] modo self: refresca el self-cert
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
/** Un ack del agente tal como llega (se comprueba en `_judgeAck`). */
|
|
43
|
+
/** @typedef {{ type: string, ack: any, signature: string, cert: unknown, sid: string, from?: string }} AgentAck */
|
|
44
|
+
|
|
29
45
|
export class RemoteAgentClient {
|
|
30
46
|
/**
|
|
31
|
-
* @param {
|
|
47
|
+
* @param {ClientLink} link
|
|
32
48
|
* enlace del vault (modo vault) o de @dotrino/vault (modo self: el dispositivo
|
|
33
49
|
* es su propio vault; `cert` es el self-cert `P ← P` e `iss` es la propia P).
|
|
34
|
-
* @param {object} opts
|
|
35
|
-
* @param {string} opts.agentPubkey dirección (pubkey) del agente destino.
|
|
50
|
+
* @param {object} [opts] `agentPubkey` es obligatoria: `connect` la comprueba.
|
|
51
|
+
* @param {string} [opts.agentPubkey] dirección (pubkey) del agente destino.
|
|
36
52
|
* @param {string} [opts.proxyUrl] override del proxy del enlace.
|
|
37
|
-
* @param {() =>
|
|
53
|
+
* @param {(() => DotrinoActa | null) | null} [opts.trustedActa] un acta ya COMPROBADA y que alguien mantiene
|
|
38
54
|
* al día (un agente de Node: la de su enlace, que refresca cada 5 min y con los avisos de la
|
|
39
55
|
* bóveda). Con ella el saludo no espera a la bóveda; si no pasa, se le pregunta y se juzga
|
|
40
56
|
* otra vez. Sin ella, la bóveda en cada saludo, como siempre.
|
|
@@ -44,24 +60,43 @@ export class RemoteAgentClient {
|
|
|
44
60
|
this.trustedActa = trustedActa
|
|
45
61
|
this.agentPubkey = agentPubkey // pubkey del agente destino
|
|
46
62
|
this.proxyUrl = proxyUrl || link.proxy || DEFAULT_PROXY
|
|
63
|
+
/** @type {import('@dotrino/proxy-client').WebSocketProxyClient | null} */
|
|
47
64
|
this.client = null
|
|
65
|
+
/** @type {CryptoKey | null} */
|
|
48
66
|
this.key = null
|
|
67
|
+
/** @type {string | null} */
|
|
49
68
|
this.sid = null
|
|
69
|
+
/** @type {Record<string, Array<(...args: any[]) => void>>} */
|
|
50
70
|
this._h = { message: [], error: [], resumed: [] }
|
|
71
|
+
/** @type {Promise<void> | null} */
|
|
51
72
|
this._resuming = null
|
|
73
|
+
/** @type {Promise<void> | undefined} */
|
|
74
|
+
this._in = undefined
|
|
75
|
+
/** @type {Promise<void> | undefined} */
|
|
76
|
+
this._out = undefined
|
|
77
|
+
/** @type {unknown} */
|
|
78
|
+
this.actaCacheError = undefined
|
|
52
79
|
// El token del agente: una vez que contesta el saludo se le habla POR TOKEN, que es lo
|
|
53
80
|
// único que sube a WebRTC. `null` es «todavía no lo sé» y se va por su pubkey.
|
|
81
|
+
/** @type {string | null} */
|
|
54
82
|
this.agentToken = null
|
|
83
|
+
/** @type {Set<string>} */
|
|
55
84
|
this._directPeers = new Set()
|
|
56
85
|
}
|
|
57
86
|
|
|
58
|
-
/**
|
|
87
|
+
/**
|
|
88
|
+
* Suscribe a eventos. Devuelve un `off()` para desuscribir. Eventos: message, error, resumed.
|
|
89
|
+
* @param {'message' | 'error' | 'resumed'} ev
|
|
90
|
+
* @param {(...args: any[]) => void} cb
|
|
91
|
+
* @returns {() => void}
|
|
92
|
+
*/
|
|
59
93
|
on (ev, cb) {
|
|
60
94
|
if (!this._h[ev]) this._h[ev] = []
|
|
61
95
|
this._h[ev].push(cb)
|
|
62
96
|
return () => { this._h[ev] = this._h[ev].filter((f) => f !== cb) }
|
|
63
97
|
}
|
|
64
98
|
|
|
99
|
+
/** @param {string} ev @param {...unknown} args */
|
|
65
100
|
_emit (ev, ...args) { for (const h of (this._h[ev] || [])) { try { h(...args) } catch (_) {} } }
|
|
66
101
|
|
|
67
102
|
/**
|
|
@@ -75,9 +110,11 @@ export class RemoteAgentClient {
|
|
|
75
110
|
* Si no hay ninguna, `null` y se corta con `no-record`: sin acta no hay con qué decidir, y
|
|
76
111
|
* no decidir es que no.
|
|
77
112
|
*/
|
|
113
|
+
/** @returns {Promise<DotrinoActa | null>} */
|
|
78
114
|
async _acta () {
|
|
79
115
|
if (this.link.acta) return this.link.acta
|
|
80
116
|
const id = this.link.id
|
|
117
|
+
/** @type {DotrinoActa | null} */
|
|
81
118
|
let acta = null
|
|
82
119
|
try { acta = (await id?.listVaultDevices?.())?.acta || null } catch (_) {}
|
|
83
120
|
if (!acta) { try { acta = (await id?.profileActa?.())?.acta || null } catch (_) {} }
|
|
@@ -90,14 +127,15 @@ export class RemoteAgentClient {
|
|
|
90
127
|
// mensajes dirigidos a P (que atiende el listener de enrolamiento). La
|
|
91
128
|
// autorización la da el vault/self-cert que va firmado en el handshake.
|
|
92
129
|
if (this.link.mode === 'self') return
|
|
93
|
-
|
|
130
|
+
const client = this._client()
|
|
131
|
+
if (!client.token) return
|
|
94
132
|
// Patrón estándar del ecosistema (messenger): identify firmado por id.signData
|
|
95
133
|
// + cert del vault → el proxy enruta también lo dirigido a la maestra.
|
|
96
134
|
const { id, cert } = this.link
|
|
97
135
|
const publickey = id.me?.publickey
|
|
98
136
|
if (!publickey) return
|
|
99
137
|
// El sobre lo arma el pilar (`identifyAs`), que le pone el destinatario.
|
|
100
|
-
await
|
|
138
|
+
await client.identifyAs({ publickey, sign: (d) => id.signData(d), cert })
|
|
101
139
|
}
|
|
102
140
|
|
|
103
141
|
async connect () {
|
|
@@ -107,26 +145,27 @@ export class RemoteAgentClient {
|
|
|
107
145
|
// porque entonces Node no tenía con qué; se quedó así cuando ya lo tuvo, y dos equipos
|
|
108
146
|
// en la misma red se hablaban dando la vuelta por el proxio.
|
|
109
147
|
// Solo negocia canal directo quien contestó NUESTRO saludo.
|
|
110
|
-
|
|
148
|
+
const client = new WebSocketProxyClient({
|
|
111
149
|
url: this.proxyUrl, autoReconnect: true,
|
|
112
150
|
acceptDirectFrom: (token) => this._directPeers.has(token)
|
|
113
151
|
})
|
|
114
|
-
|
|
152
|
+
this.client = client
|
|
153
|
+
await client.connect()
|
|
115
154
|
await this._identify()
|
|
116
155
|
if (this.link.mode !== 'self') {
|
|
117
|
-
|
|
156
|
+
client.on('token', () => { this._identify().catch(() => {}) })
|
|
118
157
|
}
|
|
119
158
|
|
|
120
159
|
// El agente se reinició: su token ya no existe. El pilar ya mandó ese mensaje por su
|
|
121
160
|
// pubkey; aquí solo se deja de usar el token hasta el próximo saludo.
|
|
122
|
-
|
|
161
|
+
client.on('token_gone', (/** @type {string} */ token) => {
|
|
123
162
|
this._directPeers.delete(token)
|
|
124
163
|
if (token === this.agentToken) this.agentToken = null
|
|
125
164
|
})
|
|
126
165
|
|
|
127
|
-
|
|
166
|
+
client.on('message', (_from, p) => {
|
|
128
167
|
if (!p || typeof p !== 'object') return
|
|
129
|
-
if (p.type === DATA && p.sid === this.sid) {
|
|
168
|
+
if (p.type === DATA && p.sid === this.sid && this.key) {
|
|
130
169
|
// Se entregan en el orden en que llegaron: descifrar tarda según el tamaño, y sin
|
|
131
170
|
// esta cola un mensaje pequeño adelantaba a uno grande que llegó antes.
|
|
132
171
|
const opened = open(this.key, p.env).then((m) => ({ m }), () => null)
|
|
@@ -147,6 +186,7 @@ export class RemoteAgentClient {
|
|
|
147
186
|
* sale por `error`. Un `unknown-session` de un `sid` que ya no es el nuestro (llegó tarde,
|
|
148
187
|
* de antes de volver a saludar) no dice nada nuevo y se ignora.
|
|
149
188
|
*/
|
|
189
|
+
/** @param {{ code?: string, error?: string, reason?: string, sid?: string }} p */
|
|
150
190
|
_onAgentError (p) {
|
|
151
191
|
if (p.code !== 'unknown-session') { this._emit('error', Object.assign(new Error(p.error), { code: p.code, reason: p.reason })); return }
|
|
152
192
|
if (p.sid !== this.sid) return
|
|
@@ -154,6 +194,7 @@ export class RemoteAgentClient {
|
|
|
154
194
|
}
|
|
155
195
|
|
|
156
196
|
/** Vuelve a saludar, una sola vez aunque lleguen varios errores seguidos. */
|
|
197
|
+
/** @returns {Promise<void>} */
|
|
157
198
|
_resume () {
|
|
158
199
|
if (this._resuming) return this._resuming
|
|
159
200
|
this.key = null
|
|
@@ -180,8 +221,10 @@ export class RemoteAgentClient {
|
|
|
180
221
|
// El ACK se correlaciona por la clave efímera PROPIA (ceph === eph.pub): así
|
|
181
222
|
// varias sesiones simultáneas (varios RemoteAgentClient sobre la misma pubkey)
|
|
182
223
|
// no se roban el ACK de la otra.
|
|
224
|
+
const client = this._client()
|
|
225
|
+
/** @type {Promise<AgentAck>} */
|
|
183
226
|
const acked = new Promise((resolve, reject) => {
|
|
184
|
-
const off =
|
|
227
|
+
const off = client.on('message', (from, p) => {
|
|
185
228
|
if (!p || typeof p !== 'object') return
|
|
186
229
|
// El token se apunta AQUÍ, en el mismo tic: si el agente es quien abre el canal
|
|
187
230
|
// directo, su oferta llega justo detrás del ack y tiene que encontrarlo ya.
|
|
@@ -190,13 +233,17 @@ export class RemoteAgentClient {
|
|
|
190
233
|
})
|
|
191
234
|
setTimeout(() => { off(); reject(new Error('the agent did not reply (is it running there?)')) }, 20000)
|
|
192
235
|
})
|
|
193
|
-
|
|
236
|
+
client.sendByPubkey(/** @type {string} */ (this.agentPubkey), { type: HS, data, signature, cert })
|
|
194
237
|
const res = await acked
|
|
195
|
-
try { await this._checkAck(res, eph) } catch (e) { this._directPeers.delete(res.from); throw e }
|
|
238
|
+
try { await this._checkAck(res, eph) } catch (e) { if (res.from) this._directPeers.delete(res.from); throw e }
|
|
196
239
|
this.agentToken = res.from || null
|
|
197
240
|
}
|
|
198
241
|
|
|
199
|
-
/**
|
|
242
|
+
/**
|
|
243
|
+
* Comprueba el ack y deja `sid` y `key`.
|
|
244
|
+
* @param {AgentAck} res
|
|
245
|
+
* @param {{ privateKey: CryptoKey, pub: string }} eph
|
|
246
|
+
*/
|
|
200
247
|
async _checkAck (res, eph) {
|
|
201
248
|
// PRIMERO EL ACTA QUE YA SE TIENE (`trustedActa`), y la bóveda solo si con esa no pasa.
|
|
202
249
|
// Preguntarle en cada saludo hacía esperar a la ventana 4-17 s antes de pedir la clave de
|
|
@@ -206,11 +253,11 @@ export class RemoteAgentClient {
|
|
|
206
253
|
let local = null
|
|
207
254
|
try { local = this.trustedActa?.() || null } catch (_) {}
|
|
208
255
|
if (local) {
|
|
209
|
-
try { return await this._judgeAck(res, eph, local) } catch (e) { if (e.code !== 'unauthorized') throw e }
|
|
256
|
+
try { return await this._judgeAck(res, eph, local) } catch (e) { if (/** @type {{ code?: string }} */ (e).code !== 'unauthorized') throw e }
|
|
210
257
|
// Va atrás: antes que la bóveda, la caché de actas del proxio (websocket-proxy ≥ 1.10.0).
|
|
211
258
|
const newer = await this._actaFromProxy(local)
|
|
212
259
|
if (newer) {
|
|
213
|
-
try { return await this._judgeAck(res, eph, newer) } catch (e) { if (e.code !== 'unauthorized') throw e }
|
|
260
|
+
try { return await this._judgeAck(res, eph, newer) } catch (e) { if (/** @type {{ code?: string }} */ (e).code !== 'unauthorized') throw e }
|
|
214
261
|
}
|
|
215
262
|
}
|
|
216
263
|
return this._judgeAck(res, eph, await this._acta())
|
|
@@ -221,15 +268,22 @@ export class RemoteAgentClient {
|
|
|
221
268
|
* El proxio no es de fiar: lo que no encadena se ignora. Si no se pudo preguntar, el motivo
|
|
222
269
|
* queda en `actaCacheError` y se sigue con la bóveda, que es quien manda.
|
|
223
270
|
*/
|
|
271
|
+
/** @param {DotrinoActa} trusted @returns {Promise<DotrinoActa | null>} */
|
|
224
272
|
async _actaFromProxy (trusted) {
|
|
225
273
|
if (!trusted?.profileId) return null
|
|
274
|
+
/** @type {DotrinoActa[]} */
|
|
226
275
|
let list
|
|
227
|
-
try { list = await this.
|
|
276
|
+
try { list = /** @type {DotrinoActa[]} */ (await this._client().getActas(trusted.profileId, { sinceSeq: trusted.seq })) } catch (e) { this.actaCacheError = e; return null }
|
|
228
277
|
for (const a of list) if ((await canAdopt({ candidate: a, current: trusted })).adopt) return a
|
|
229
278
|
return null
|
|
230
279
|
}
|
|
231
280
|
|
|
232
|
-
/**
|
|
281
|
+
/**
|
|
282
|
+
* Juzga el ack con `acta` y, si pasa, deja `sid` y `key`.
|
|
283
|
+
* @param {AgentAck} res
|
|
284
|
+
* @param {{ privateKey: CryptoKey, pub: string }} eph
|
|
285
|
+
* @param {DotrinoActa | null} acta
|
|
286
|
+
*/
|
|
233
287
|
async _judgeAck (res, eph, acta) {
|
|
234
288
|
|
|
235
289
|
// El ack debe: (1) encadenar a NUESTRA maestra, (2) estar firmado por el agente
|
|
@@ -265,10 +319,16 @@ export class RemoteAgentClient {
|
|
|
265
319
|
this.key = await deriveKey(eph.privateKey, res.ack.seph, res.sid)
|
|
266
320
|
}
|
|
267
321
|
|
|
268
|
-
/**
|
|
322
|
+
/**
|
|
323
|
+
* Envía un payload de dominio cifrado al agente (si se está volviendo a saludar, después).
|
|
324
|
+
* @param {unknown} payload
|
|
325
|
+
* @returns {Promise<void>}
|
|
326
|
+
*/
|
|
269
327
|
async send (payload) {
|
|
270
328
|
if (this._resuming) await this._resuming
|
|
271
329
|
if (!this.key) throw Object.assign(new Error('no session with the agent'), { code: 'no-session' })
|
|
330
|
+
const client = this._client()
|
|
331
|
+
const agentPubkey = /** @type {string} */ (this.agentPubkey) // `connect` la exigió
|
|
272
332
|
// Salen en el orden en que se pidieron, tarde lo que tarde en cifrarse cada uno.
|
|
273
333
|
const sid = this.sid
|
|
274
334
|
const sealed = seal(this.key, payload)
|
|
@@ -276,30 +336,42 @@ export class RemoteAgentClient {
|
|
|
276
336
|
const msg = { type: DATA, sid, env }
|
|
277
337
|
// Por token en cuanto se sabe: sube al canal directo, y si el token murió el pilar lo
|
|
278
338
|
// saca por la pubkey. Por pubkey solo mientras no hay token.
|
|
279
|
-
if (this.agentToken)
|
|
280
|
-
else
|
|
339
|
+
if (this.agentToken) client.sendToOrQueue(this.agentToken, msg, { peerPubkey: agentPubkey })
|
|
340
|
+
else client.sendByPubkey(agentPubkey, msg)
|
|
281
341
|
})
|
|
282
342
|
this._out = turn.catch(() => {})
|
|
283
343
|
return turn
|
|
284
344
|
}
|
|
285
345
|
|
|
286
|
-
/**
|
|
346
|
+
/**
|
|
347
|
+
* Sonda de presencia (liveness) sin abrir sesión. Devuelve true si responde.
|
|
348
|
+
* @param {{ timeoutMs?: number }} [o]
|
|
349
|
+
* @returns {Promise<boolean>}
|
|
350
|
+
*/
|
|
287
351
|
async ping ({ timeoutMs = 4000 } = {}) {
|
|
352
|
+
const client = this._client()
|
|
288
353
|
const n = crypto.getRandomValues(new Uint8Array(8)).join('')
|
|
354
|
+
/** @type {Promise<boolean>} */
|
|
289
355
|
const got = new Promise((resolve) => {
|
|
290
|
-
const off =
|
|
356
|
+
const off = client.on('message', (_f, p) => {
|
|
291
357
|
if (p?.type === PONG && p.n === n) { off(); resolve(true) }
|
|
292
358
|
})
|
|
293
359
|
setTimeout(() => { off(); resolve(false) }, timeoutMs)
|
|
294
360
|
})
|
|
295
361
|
// Efímero, como `probeAgents`: si no está, no se encola ni se le timbra.
|
|
296
|
-
|
|
362
|
+
client.sendByPubkey(/** @type {string} */ (this.agentPubkey), { type: PING, n }, { ephemeral: true })
|
|
297
363
|
return got
|
|
298
364
|
}
|
|
299
365
|
|
|
300
366
|
async close () {
|
|
301
367
|
try { this.client?.close() } catch {}
|
|
302
368
|
}
|
|
369
|
+
|
|
370
|
+
/** El transporte, que existe desde `connect`. Usarlo antes es un fallo de quien llama. */
|
|
371
|
+
_client () {
|
|
372
|
+
if (!this.client) throw Object.assign(new Error('not connected: call connect() first'), { code: 'not-connected' })
|
|
373
|
+
return this.client
|
|
374
|
+
}
|
|
303
375
|
}
|
|
304
376
|
|
|
305
377
|
export default { RemoteAgentClient }
|
package/src/discover.js
CHANGED
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
import { PING, PONG } from '../protocol.js'
|
|
25
25
|
|
|
26
26
|
/**
|
|
27
|
-
* @param {
|
|
27
|
+
* @param {AgentIdentity} id instancia de Identity (del vault) ya conectada.
|
|
28
28
|
* @param {string} [label] filtrar por servicio/label exacto (p. ej. `'content'`,
|
|
29
29
|
* `'ia-agent'`). Omitir = todos los que tengan nameOf y no sean `'cli'` (un navegador
|
|
30
30
|
* enrolado queda como `cli` y no atiende a nadie).
|
|
@@ -41,12 +41,14 @@ export async function listAgentsByLabel (id, label, { fresh = true } = {}) {
|
|
|
41
41
|
// vuelve a mirar cada pocos segundos: el panel de máquinas del agente lo hacía cada 30 s, y
|
|
42
42
|
// cada vez era un `vault.devices` a la cuenta que despertaba a la bóveda de Lambda y no la
|
|
43
43
|
// dejaba dormirse (2026-10-25). El agente ya refresca su acta solo (`REVOKE_REFRESH_MS`).
|
|
44
|
+
/** @type {DotrinoActa | null} */
|
|
44
45
|
let acta = null
|
|
46
|
+
/** @type {Error | null} */
|
|
45
47
|
let why = null
|
|
46
48
|
if (!fresh) acta = (await id.profileActa?.().catch(() => null))?.acta || null
|
|
47
|
-
if (!acta) { try { acta = (await id.listVaultDevices())?.acta || null } catch (e) { why = e } }
|
|
49
|
+
if (!acta) { try { acta = (await id.listVaultDevices())?.acta || null } catch (e) { why = /** @type {Error} */ (e) } }
|
|
48
50
|
// La bóveda no contestó: vale el acta que ya se tiene guardada.
|
|
49
|
-
if (!acta) acta = (await id.profileActa?.().catch((e) => { why = why || e; return null }))?.acta || null
|
|
51
|
+
if (!acta) acta = (await id.profileActa?.().catch((/** @type {Error} */ e) => { why = why || e; return null }))?.acta || null
|
|
50
52
|
// SIN ACTA NO SE SABE quién es de la cuenta, y eso no es «no hay nadie». Devolver una lista
|
|
51
53
|
// vacía aquí hacía que una máquina con la bóveda inalcanzable dijera «no tienes otras
|
|
52
54
|
// máquinas» con toda tranquilidad. Se para y se dice.
|
|
@@ -55,12 +57,13 @@ export async function listAgentsByLabel (id, label, { fresh = true } = {}) {
|
|
|
55
57
|
}
|
|
56
58
|
|
|
57
59
|
const mine = id.me?.publickey
|
|
58
|
-
|
|
60
|
+
/** @typedef {NonNullable<DotrinoActa['members']>[number]} Member */
|
|
61
|
+
const nameOf = (/** @type {Member} */ m) => m.cn || m.label || null
|
|
59
62
|
// LAS BÓVEDAS NO SON AGENTES: su llave de comunicación (`cn: 'vault'`), la que sella
|
|
60
63
|
// (`sealer`) y la réplica (`replica`). Preguntarles qué agente son no sirve de nada, y a una
|
|
61
64
|
// bóveda que duerme (la de Lambda) el sondeo de Terminal cada 30 s la tenía despierta
|
|
62
65
|
// (2026-10-25). Quien busca una bóveda por su nombre (`label`) la sigue encontrando.
|
|
63
|
-
const isVault = (m) => m.cn === 'vault' || (Array.isArray(m.caps) && (m.caps.includes('sealer') || m.caps.includes('replica')))
|
|
66
|
+
const isVault = (/** @type {Member} */ m) => m.cn === 'vault' || (Array.isArray(m.caps) && (m.caps.includes('sealer') || m.caps.includes('replica')))
|
|
64
67
|
return (acta.members || [])
|
|
65
68
|
.filter((m) => m?.pub && m.pub !== mine)
|
|
66
69
|
.filter((m) => (label ? nameOf(m) === label : (nameOf(m) && nameOf(m) !== 'cli' && !isVault(m))))
|
|
@@ -78,7 +81,8 @@ export async function listAgentsByLabel (id, label, { fresh = true } = {}) {
|
|
|
78
81
|
*
|
|
79
82
|
* Un agente apagado no contesta y no sale: no se puede saber qué es sin preguntarle.
|
|
80
83
|
*
|
|
81
|
-
* @param {{ on:
|
|
84
|
+
* @param {{ on: (ev: 'message', fn: (from: string, p: any) => void) => () => void, sendByPubkey: (to: string, payload: object, opts?: { ephemeral?: boolean }) => unknown } | null} client
|
|
85
|
+
* un WebSocketProxyClient conectado. `p` es lo que llega: se mira su `type` antes de usarlo.
|
|
82
86
|
* @param {string[]} subs pubkeys a preguntar (p. ej. las de `listAgentsByLabel(id)`).
|
|
83
87
|
* @param {{ timeoutMs?: number }} [opts]
|
|
84
88
|
* @returns {Promise<Map<string, { kind: string|null }>>} sub → lo que contestó.
|
package/src/instances.js
CHANGED
|
@@ -20,6 +20,7 @@ import os from 'node:os'
|
|
|
20
20
|
import path from 'node:path'
|
|
21
21
|
|
|
22
22
|
export const DEFAULT_NAME = 'default'
|
|
23
|
+
/** @param {unknown} n @returns {n is string} */
|
|
23
24
|
export const isValidName = (n) => typeof n === 'string' && /^[a-z0-9-]{1,32}$/.test(n)
|
|
24
25
|
|
|
25
26
|
/**
|
|
@@ -33,9 +34,14 @@ export function instancesRoot (kind) {
|
|
|
33
34
|
return path.join(home, kind)
|
|
34
35
|
}
|
|
35
36
|
|
|
36
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
* Nombres de las instancias enlazadas (las que tienen `link.json`).
|
|
39
|
+
* @param {string} kind
|
|
40
|
+
* @returns {string[]}
|
|
41
|
+
*/
|
|
37
42
|
export function listInstances (kind) {
|
|
38
43
|
const root = instancesRoot(kind)
|
|
44
|
+
/** @type {string[]} */
|
|
39
45
|
let names = []
|
|
40
46
|
try { names = fs.readdirSync(root) } catch (_) { return [] }
|
|
41
47
|
return names.filter((n) => isValidName(n) && fs.existsSync(path.join(root, n, 'link.json'))).sort()
|
|
@@ -47,6 +53,8 @@ export function listInstances (kind) {
|
|
|
47
53
|
* · sin nombre y ninguna enlazada: `default`;
|
|
48
54
|
* · sin nombre y UNA enlazada: esa;
|
|
49
55
|
* · sin nombre y VARIAS: se para y se dice cuáles hay. Elegir por el usuario sería adivinar.
|
|
56
|
+
* @param {string} kind
|
|
57
|
+
* @param {string | null} [name]
|
|
50
58
|
* @returns {{ name: string, dir: string }}
|
|
51
59
|
*/
|
|
52
60
|
export function resolveInstance (kind, name) {
|
|
@@ -64,6 +72,7 @@ export function resolveInstance (kind, name) {
|
|
|
64
72
|
* Candado de la instancia: dos procesos con el MISMO enlace son la misma llave y se
|
|
65
73
|
* estorban. Si ya corre uno vivo, se para y se dice. Devuelve `release()`.
|
|
66
74
|
*/
|
|
75
|
+
/** @param {string} dir @returns {() => void} suelta el candado */
|
|
67
76
|
export function lockInstance (dir) {
|
|
68
77
|
const file = path.join(dir, 'agent.pid')
|
|
69
78
|
try {
|
|
@@ -71,12 +80,13 @@ export function lockInstance (dir) {
|
|
|
71
80
|
if (pid && pid !== process.pid && isAlive(pid)) {
|
|
72
81
|
throw Object.assign(new Error(`this agent is already running (pid ${pid}). To run another one at the same time, give it its own --name`), { code: 'EALREADY' })
|
|
73
82
|
}
|
|
74
|
-
} catch (e) { if (e.code === 'EALREADY') throw e }
|
|
83
|
+
} catch (e) { if (/** @type {{ code?: string }} */ (e).code === 'EALREADY') throw e }
|
|
75
84
|
fs.mkdirSync(dir, { recursive: true })
|
|
76
85
|
fs.writeFileSync(file, String(process.pid), { mode: 0o600 })
|
|
77
86
|
return () => { try { if (Number(fs.readFileSync(file, 'utf8')) === process.pid) fs.rmSync(file) } catch (_) {} }
|
|
78
87
|
}
|
|
79
88
|
|
|
89
|
+
/** @param {number} pid */
|
|
80
90
|
function isAlive (pid) {
|
|
81
|
-
try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' }
|
|
91
|
+
try { process.kill(pid, 0); return true } catch (e) { return /** @type {{ code?: string }} */ (e).code === 'EPERM' }
|
|
82
92
|
}
|
package/src/link.js
CHANGED
|
@@ -26,13 +26,40 @@ import { DEFAULT_PROXY, RENEW_BEFORE_MS } from '../protocol.js'
|
|
|
26
26
|
// @dotrino/vault >= 0.115.0 (la primera que exporta `atrest`).
|
|
27
27
|
import { atRestFor, isEncrypted } from '@dotrino/vault/atrest'
|
|
28
28
|
|
|
29
|
+
/**
|
|
30
|
+
* El papel de un aparato: lo firma la bóveda. `seq` es el del acta con que se emitió; `exp`
|
|
31
|
+
* solo lo lleva el modelo viejo (por fecha).
|
|
32
|
+
* @typedef {{ seq?: number, exp?: number } & Record<string, unknown>} AgentCert
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* El enlace de esta máquina con su cuenta (`link.json`). Con bóveda: `device`, `enc`, `cert`,
|
|
37
|
+
* `iss`, `proxy`. Propio (`self: true`): `device`, `enc` y su génesis en `sealerChain`.
|
|
38
|
+
* @typedef {object} AgentLink
|
|
39
|
+
* @property {{ publickey: string, privateJwk: JsonWebKey }} device
|
|
40
|
+
* @property {{ publickey?: string, privateJwk?: JsonWebKey } & Record<string, unknown>} [enc]
|
|
41
|
+
* @property {AgentCert} [cert]
|
|
42
|
+
* @property {string} [iss] la bóveda con que se enroló
|
|
43
|
+
* @property {string} [proxy]
|
|
44
|
+
* @property {string} [label]
|
|
45
|
+
* @property {string} [ns]
|
|
46
|
+
* @property {number} [at]
|
|
47
|
+
* @property {boolean} [self]
|
|
48
|
+
* @property {DotrinoActa[]} [sealerChain]
|
|
49
|
+
* @property {DotrinoActa} [acta] el acta de confianza (solo si `actaTrusted`)
|
|
50
|
+
* @property {boolean} [actaTrusted]
|
|
51
|
+
* @property {number} [actaSeq] la `seq` del acta más nueva que se ha visto
|
|
52
|
+
* @property {string[]} [blocked] aparatos bloqueados por la bóveda (pubkeys)
|
|
53
|
+
*/
|
|
54
|
+
|
|
55
|
+
/** @param {string} [name] @returns {string} */
|
|
29
56
|
export function dataDir (name = 'dotrino-remote-agent') {
|
|
30
57
|
if (process.env.DOTRINO_REMOTE_AGENT_DIR) return process.env.DOTRINO_REMOTE_AGENT_DIR
|
|
31
58
|
const base = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share')
|
|
32
59
|
return path.join(base, name)
|
|
33
60
|
}
|
|
34
61
|
|
|
35
|
-
const linkPath = (dir) => path.join(dir, 'link.json')
|
|
62
|
+
const linkPath = (/** @type {string} */ dir) => path.join(dir, 'link.json')
|
|
36
63
|
|
|
37
64
|
/*
|
|
38
65
|
* EL ENLACE VA CIFRADO EN REPOSO (0.30.0). Lleva la llave privada del aparato, y hasta aquí
|
|
@@ -53,11 +80,13 @@ const linkPath = (dir) => path.join(dir, 'link.json')
|
|
|
53
80
|
*/
|
|
54
81
|
export function loadLink (dir = dataDir()) {
|
|
55
82
|
let text
|
|
56
|
-
try { text = fs.readFileSync(linkPath(dir), 'utf8') } catch (
|
|
83
|
+
try { text = fs.readFileSync(linkPath(dir), 'utf8') } catch (err) {
|
|
84
|
+
const e = /** @type {NodeJS.ErrnoException} */ (err)
|
|
57
85
|
if (e?.code === 'ENOENT') return null
|
|
58
86
|
throw Object.assign(new Error(`cannot read the link (${linkPath(dir)}): ${e.message}`), { code: 'link-unreadable' })
|
|
59
87
|
}
|
|
60
88
|
const box = atRestFor(dir)
|
|
89
|
+
/** @type {AgentLink} */
|
|
61
90
|
let link
|
|
62
91
|
try { link = JSON.parse(box.decrypt(text)) } catch (e) {
|
|
63
92
|
throw Object.assign(new Error(`cannot open the link (${linkPath(dir)}): it was encrypted on another machine, or the file is damaged. Enroll this device again.`), { code: 'link-unreadable', cause: e })
|
|
@@ -66,6 +95,11 @@ export function loadLink (dir = dataDir()) {
|
|
|
66
95
|
return link
|
|
67
96
|
}
|
|
68
97
|
|
|
98
|
+
/**
|
|
99
|
+
* @param {string} dir
|
|
100
|
+
* @param {ReturnType<typeof atRestFor>} box
|
|
101
|
+
* @param {AgentLink} link
|
|
102
|
+
*/
|
|
69
103
|
function writeEncrypted (dir, box, link) {
|
|
70
104
|
const json = JSON.stringify(link, null, 2)
|
|
71
105
|
const blob = box.encrypt(json)
|
|
@@ -77,6 +111,7 @@ function writeEncrypted (dir, box, link) {
|
|
|
77
111
|
}
|
|
78
112
|
|
|
79
113
|
/** Persiste el enlace, cifrado (0600). Exportada porque la RENOVACIÓN del cert lo reescribe. */
|
|
114
|
+
/** @param {string} dir @param {AgentLink} link */
|
|
80
115
|
export function saveLink (dir, link) {
|
|
81
116
|
writeEncrypted(dir, atRestFor(dir), link)
|
|
82
117
|
}
|
|
@@ -86,6 +121,7 @@ export function saveLink (dir, link) {
|
|
|
86
121
|
* `dotrino-vault pair` (URL del QR, código compacto, JSON, base64url): es el mismo
|
|
87
122
|
* `parseInvite` del ecosistema. `enroll` ya lo hace solo; esto es para quien quiera
|
|
88
123
|
* mirar la invitación antes (qué bóveda, qué proxy) sin enrolar.
|
|
124
|
+
* @param {string} text
|
|
89
125
|
*/
|
|
90
126
|
export async function parseQr (text) {
|
|
91
127
|
const { parseInvite } = await import('@dotrino/vault/invite')
|
|
@@ -95,6 +131,7 @@ export async function parseQr (text) {
|
|
|
95
131
|
}
|
|
96
132
|
|
|
97
133
|
/** base64url → utf8 (lo usan los tests y algún QR viejo). */
|
|
134
|
+
/** @param {string} s @returns {string} */
|
|
98
135
|
export function b64urlDecode (s) {
|
|
99
136
|
const b64 = String(s).replace(/-/g, '+').replace(/_/g, '/')
|
|
100
137
|
return Buffer.from(b64, 'base64').toString('utf8')
|
|
@@ -118,12 +155,13 @@ export function b64urlDecode (s) {
|
|
|
118
155
|
* @param {object|string} args.qr La invitación, en cualquiera de sus formas.
|
|
119
156
|
* @param {string} [args.label='remote-agent'] label del dispositivo (lo filtra el cliente).
|
|
120
157
|
* @param {string} [args.dir=dataDir()] dónde persistir el enlace.
|
|
121
|
-
* @param {string} [args.ns]
|
|
158
|
+
* @param {string | null} [args.ns] cajón de secretos que lee este agente (si lo hay).
|
|
122
159
|
* @param {(c:{deviceId:string,code:string})=>void} [args.onChallenge] mostrar el CÓDIGO para
|
|
123
160
|
* que un humano lo TIPEE en la bóveda al aprobar (el código NO viaja de aquí).
|
|
124
161
|
* @param {number} [args.timeoutMs=180000]
|
|
162
|
+
* @returns {Promise<AgentLink>}
|
|
125
163
|
*/
|
|
126
|
-
export async function enroll ({ qr, label = 'remote-agent', dir = dataDir(), ns = null, onChallenge, timeoutMs = 180000 } = {}) {
|
|
164
|
+
export async function enroll ({ qr, label = 'remote-agent', dir = dataDir(), ns = null, onChallenge, timeoutMs = 180000 } = /** @type {{ qr: string }} */ ({ qr: '' })) {
|
|
127
165
|
installNodeGlobals(dir)
|
|
128
166
|
const { enrollWithVault } = await import('@dotrino/vault/service')
|
|
129
167
|
const res = await enrollWithVault({
|
|
@@ -133,6 +171,7 @@ export async function enroll ({ qr, label = 'remote-agent', dir = dataDir(), ns
|
|
|
133
171
|
onCode: onChallenge,
|
|
134
172
|
approveTimeoutMs: timeoutMs
|
|
135
173
|
})
|
|
174
|
+
/** @type {AgentLink} */
|
|
136
175
|
const link = { device: res.device, enc: res.enc, cert: res.cert, iss: res.iss, proxy: res.proxy, label, ...(ns ? { ns } : {}), at: Date.now() }
|
|
137
176
|
saveLink(dir, link)
|
|
138
177
|
return link
|
|
@@ -153,6 +192,7 @@ export async function enroll ({ qr, label = 'remote-agent', dir = dataDir(), ns
|
|
|
153
192
|
* misma, seguiría siendo la raíz de su génesis y podría entrar igual a otras bóvedas.
|
|
154
193
|
*
|
|
155
194
|
* @param {{ label?: string, dir?: string }} [args]
|
|
195
|
+
* @returns {Promise<AgentLink>}
|
|
156
196
|
*/
|
|
157
197
|
export async function selfLink ({ label = 'remote-agent', dir = dataDir() } = {}) {
|
|
158
198
|
installNodeGlobals(dir)
|
|
@@ -162,6 +202,7 @@ export async function selfLink ({ label = 'remote-agent', dir = dataDir() } = {}
|
|
|
162
202
|
acta: genesisActa({ pub: d.publickey, encPub: e.encPublickey, label }),
|
|
163
203
|
privateJwk: d.privateJwk
|
|
164
204
|
})
|
|
205
|
+
/** @type {AgentLink} */
|
|
165
206
|
const link = {
|
|
166
207
|
device: { publickey: d.publickey, privateJwk: d.privateJwk },
|
|
167
208
|
enc: { publickey: e.encPublickey, privateJwk: e.encPrivateJwk },
|
|
@@ -172,7 +213,7 @@ export async function selfLink ({ label = 'remote-agent', dir = dataDir() } = {}
|
|
|
172
213
|
}
|
|
173
214
|
|
|
174
215
|
/** ¿Es una identidad propia (sin bóveda)? */
|
|
175
|
-
export const isSelfLink = (link) => link?.self === true
|
|
216
|
+
export const isSelfLink = (/** @type {AgentLink | null | undefined} */ link) => link?.self === true
|
|
176
217
|
|
|
177
218
|
/**
|
|
178
219
|
* La IDENTIDAD de un agente a partir de su enlace: lo que un cliente del ecosistema
|
|
@@ -182,8 +223,9 @@ export const isSelfLink = (link) => link?.self === true
|
|
|
182
223
|
* Node puede ser CLIENTE de otro agente (un bot que guarda en el node de contenido)
|
|
183
224
|
* con el mismo código que usa una app.
|
|
184
225
|
*
|
|
185
|
-
* @param {
|
|
226
|
+
* @param {AgentLink} link el enlace (`loadLink(dir)`).
|
|
186
227
|
* @param {{ dir?: string }} [opts] dir para los globals de Node (localStorage del proxy-client).
|
|
228
|
+
* @returns {AgentIdentity}
|
|
187
229
|
*/
|
|
188
230
|
export function identityFromLink (link, { dir = dataDir() } = {}) {
|
|
189
231
|
if (isSelfLink(link)) return selfIdentity(link, dir)
|
|
@@ -191,8 +233,10 @@ export function identityFromLink (link, { dir = dataDir() } = {}) {
|
|
|
191
233
|
installNodeGlobals(dir)
|
|
192
234
|
const device = link.device
|
|
193
235
|
const proxy = link.proxy || DEFAULT_PROXY
|
|
236
|
+
const iss = link.iss // comprobado arriba
|
|
194
237
|
return {
|
|
195
238
|
me: { publickey: device.publickey },
|
|
239
|
+
/** @param {object} data */
|
|
196
240
|
async signData (data) {
|
|
197
241
|
const signed = await signWithDevice({ privateJwk: device.privateJwk, publickey: device.publickey, data })
|
|
198
242
|
// A NOMBRE DE QUIÉN VA, igual que en el navegador: el `profileId` y la cadena de
|
|
@@ -206,7 +250,7 @@ export function identityFromLink (link, { dir = dataDir() } = {}) {
|
|
|
206
250
|
// `seq` es lo que describe un papel ahora; `exp` solo lo llevan los del modelo viejo
|
|
207
251
|
// y se sigue dando mientras existan, para que quien mire sepa que le falta migrar.
|
|
208
252
|
return {
|
|
209
|
-
paired: true, master:
|
|
253
|
+
paired: true, master: iss, proxy, deviceId: await pubkeyId(device.publickey),
|
|
210
254
|
seq: link.cert?.seq ?? null,
|
|
211
255
|
...(typeof link.cert?.exp === 'number' ? { exp: link.cert.exp, legacy: true } : {})
|
|
212
256
|
}
|
|
@@ -218,7 +262,7 @@ export function identityFromLink (link, { dir = dataDir() } = {}) {
|
|
|
218
262
|
// actual de un salto («sin-acta-previa»), de modo que la cadena no iba a usarse jamás.
|
|
219
263
|
// Costó tenerlo así: la respuesta llegó a 1,03 MB, el proxio corta el frame a 1 MB y
|
|
220
264
|
// la bóveda se quedaba muda para todo el ecosistema (2026-08-24).
|
|
221
|
-
const res = await requestDevices({ master:
|
|
265
|
+
const res = await requestDevices({ master: iss, proxy, device, cert: link.cert })
|
|
222
266
|
// EL ACTA QUE SE DEVUELVE ES UNA COMPROBADA, nunca la que llegó por la red: la respuesta
|
|
223
267
|
// no trae remitente comprobable, y con ella se decide quién es de la cuenta (a quién
|
|
224
268
|
// se le abre una consola). Vale la que encadena desde la de confianza del enlace (o la
|
|
@@ -237,6 +281,7 @@ export function identityFromLink (link, { dir = dataDir() } = {}) {
|
|
|
237
281
|
* La identidad de un enlace propio: firma con su llave y prueba con su génesis. Lo que
|
|
238
282
|
* pregunta a una bóveda no existe aquí, y se dice (`no-vault`) en vez de inventarse.
|
|
239
283
|
*/
|
|
284
|
+
/** @param {AgentLink} link @param {string} dir @returns {AgentIdentity} */
|
|
240
285
|
function selfIdentity (link, dir) {
|
|
241
286
|
const chain = link.sealerChain
|
|
242
287
|
if (!link?.device?.privateJwk || !Array.isArray(chain) || chain.length !== 1) throw new Error('invalid self link: device and its genesis required')
|
|
@@ -245,6 +290,7 @@ function selfIdentity (link, dir) {
|
|
|
245
290
|
const noVault = () => Promise.reject(Object.assign(new Error('this device has its own identity and is not paired with a vault'), { code: 'no-vault' }))
|
|
246
291
|
return {
|
|
247
292
|
me: { publickey: device.publickey },
|
|
293
|
+
/** @param {object} data */
|
|
248
294
|
async signData (data) {
|
|
249
295
|
const signed = await signWithDevice({ privateJwk: device.privateJwk, publickey: device.publickey, data })
|
|
250
296
|
return { ...signed, profileId: chain[0].profileId, chain }
|
|
@@ -258,9 +304,15 @@ function selfIdentity (link, dir) {
|
|
|
258
304
|
}
|
|
259
305
|
}
|
|
260
306
|
|
|
261
|
-
const trustedActaOf = (link) => (link?.actaTrusted === true && link.acta ? link.acta : null)
|
|
307
|
+
const trustedActaOf = (/** @type {AgentLink} */ link) => (link?.actaTrusted === true && link.acta ? link.acta : null)
|
|
262
308
|
|
|
263
|
-
/**
|
|
309
|
+
/**
|
|
310
|
+
* El acta que `listVaultDevices` puede dar por buena. Exportada para las pruebas.
|
|
311
|
+
* @param {AgentLink} link
|
|
312
|
+
* @param {DotrinoActa | null | undefined} candidate la que llegó por la red
|
|
313
|
+
* @param {string} me
|
|
314
|
+
* @returns {Promise<DotrinoActa | null>}
|
|
315
|
+
*/
|
|
264
316
|
export async function checkedActa (link, candidate, me) {
|
|
265
317
|
if (candidate && typeof candidate.seq === 'number') {
|
|
266
318
|
const r = await adoptRecord({ link, candidate, me })
|
|
@@ -280,7 +332,7 @@ export { RENEW_BEFORE_MS }
|
|
|
280
332
|
* · `'behind'`: el acta que hemos visto va por delante del papel (el dueño cambió permisos).
|
|
281
333
|
* Nunca por calendario: el papel no vence.
|
|
282
334
|
*
|
|
283
|
-
* @param {
|
|
335
|
+
* @param {AgentLink} link
|
|
284
336
|
* @returns {'legacy'|'behind'|null}
|
|
285
337
|
*/
|
|
286
338
|
export function renewalReason (link) {
|
|
@@ -297,6 +349,7 @@ export function renewalReason (link) {
|
|
|
297
349
|
* El acta que viaja con el papel se adopta SOLO si se puede comprobar (`record.js`): es la que
|
|
298
350
|
* decide quién abre sesión con este agente. El papel sí se guarda siempre.
|
|
299
351
|
*/
|
|
352
|
+
/** @param {{ dir: string, link: AgentLink, cert: AgentCert, acta: DotrinoActa }} o */
|
|
300
353
|
export async function storeRenewedCert ({ dir, link, cert, acta }) {
|
|
301
354
|
link.cert = cert
|
|
302
355
|
link.actaSeq = acta.seq
|
|
@@ -316,9 +369,9 @@ export async function storeRenewedCert ({ dir, link, cert, acta }) {
|
|
|
316
369
|
* El cert nuevo se VERIFICA antes de guardarlo (misma maestra, misma llave, más vida).
|
|
317
370
|
* Un cert ya vencido no se renueva: ahí toca re-emparejar. No lanza: devuelve qué pasó.
|
|
318
371
|
*
|
|
319
|
-
* @param {
|
|
372
|
+
* @param {AgentLink} link el enlace (se muta con el cert nuevo).
|
|
320
373
|
* @param {{ dir?: string, force?: boolean }} [opts]
|
|
321
|
-
* @returns {Promise<{ renewed: boolean,
|
|
374
|
+
* @returns {Promise<{ renewed: boolean, seq?: number | null, reason?: string }>} `seq`: la del papel que queda
|
|
322
375
|
*/
|
|
323
376
|
export async function renewLink (link, { dir = dataDir(), force = false } = {}) {
|
|
324
377
|
if (!link?.cert) return { renewed: false, seq: null, reason: 'no cert' }
|
|
@@ -336,14 +389,14 @@ export async function renewLink (link, { dir = dataDir(), force = false } = {})
|
|
|
336
389
|
// firmada, esta bóveda puede sellarla, el papel lo firmó ella y es para esta llave) y
|
|
337
390
|
// lanza si no cuadra. Aquí se comparaba `acta.profileId` con `link.iss`, que solo vale
|
|
338
391
|
// en una cuenta que nació en esa bóveda: con una segunda bóveda no renovaba nunca.
|
|
339
|
-
const { cert, acta } = await requestRenew({ master: link.iss, proxy: link.proxy || DEFAULT_PROXY, device: link.device, cert: link.cert })
|
|
392
|
+
const { cert, acta } = await requestRenew({ master: /** @type {string} */ (link.iss), proxy: link.proxy || DEFAULT_PROXY, device: link.device, cert: link.cert })
|
|
340
393
|
// SE GUARDA ANTES DE DAR NADA POR BUENO. Emitir un papel RETIRA el anterior, así que si
|
|
341
394
|
// esto no se persiste la máquina se queda usando uno revocado y fuera para siempre. Le
|
|
342
395
|
// pasó al registro de selladores en la migración, y por eso está dicho aquí.
|
|
343
396
|
await storeRenewedCert({ dir, link, cert, acta })
|
|
344
397
|
return { renewed: true, seq: cert.seq }
|
|
345
398
|
} catch (e) {
|
|
346
|
-
return { renewed: false, seq: link.cert.seq ?? null, reason: e.message }
|
|
399
|
+
return { renewed: false, seq: link.cert.seq ?? null, reason: /** @type {Error} */ (e).message }
|
|
347
400
|
}
|
|
348
401
|
}
|
|
349
402
|
|
|
@@ -354,7 +407,9 @@ export async function renewLink (link, { dir = dataDir(), force = false } = {})
|
|
|
354
407
|
* de otra cuenta no entra. Un agente que firma de cara a terceros la pide al arrancar y la
|
|
355
408
|
* refresca de vez en cuando. No lanza: devuelve qué pasó.
|
|
356
409
|
*
|
|
357
|
-
* @
|
|
410
|
+
* @param {AgentLink} link
|
|
411
|
+
* @param {{ dir?: string }} [opts]
|
|
412
|
+
* @returns {Promise<{ ok: boolean, seq?: number, reason?: string, self?: boolean }>}
|
|
358
413
|
*/
|
|
359
414
|
export async function refreshChain (link, { dir = dataDir() } = {}) {
|
|
360
415
|
// Una identidad propia es su propia cadena: no hay a quién preguntar ni nada que caduque.
|
|
@@ -363,25 +418,31 @@ export async function refreshChain (link, { dir = dataDir() } = {}) {
|
|
|
363
418
|
installNodeGlobals(dir)
|
|
364
419
|
try {
|
|
365
420
|
const res = await requestDevices({ master: link.iss, proxy: link.proxy || DEFAULT_PROXY, device: link.device, cert: link.cert })
|
|
366
|
-
const chain = res.sealerChain
|
|
421
|
+
const chain = /** @type {DotrinoActa[] | undefined} */ (res.sealerChain)
|
|
367
422
|
if (!Array.isArray(chain) || !chain.length) return { ok: false, reason: 'the vault sent no sealer chain (vaultd < 0.154.0?)' }
|
|
368
423
|
const expected = link.sealerChain?.[0]?.profileId ?? link.acta?.profileId ?? null
|
|
369
424
|
const v = await verifySealerChain(chain, { expectedProfileId: expected })
|
|
370
425
|
if (!v.ok) return { ok: false, reason: 'bad sealer chain: ' + v.reason }
|
|
371
426
|
const head = chain[chain.length - 1]
|
|
372
|
-
|
|
427
|
+
const stored = link.sealerChain?.[link.sealerChain.length - 1]
|
|
428
|
+
if (typeof stored?.seq === 'number' && head.seq < stored.seq) {
|
|
373
429
|
return { ok: false, reason: 'older than the chain already stored' }
|
|
374
430
|
}
|
|
375
431
|
link.sealerChain = chain
|
|
376
432
|
saveLink(dir, link)
|
|
377
433
|
return { ok: true, seq: head.seq }
|
|
378
|
-
} catch (
|
|
434
|
+
} catch (err) {
|
|
435
|
+
const e = /** @type {Error & { code?: string } | undefined} */ (err)
|
|
379
436
|
// Un fallo de red llega a veces sin frase: se dice el código, o al menos que no se alcanzó.
|
|
380
437
|
return { ok: false, reason: e?.message || e?.code || 'unreachable' }
|
|
381
438
|
}
|
|
382
439
|
}
|
|
383
440
|
|
|
384
|
-
/**
|
|
441
|
+
/**
|
|
442
|
+
* El enlace como lo esperan `ContentClient.connect({ link })` y `RemoteAgentClient`.
|
|
443
|
+
* @param {AgentLink} link
|
|
444
|
+
* @param {{ dir?: string }} [opts]
|
|
445
|
+
*/
|
|
385
446
|
export function clientLink (link, opts) {
|
|
386
447
|
return { id: identityFromLink(link, opts), cert: link.cert, iss: link.iss, proxy: link.proxy || DEFAULT_PROXY }
|
|
387
448
|
}
|
package/src/membership.js
CHANGED
|
@@ -14,7 +14,11 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import { memberCan, samePubkey } from '@dotrino/identity/acta'
|
|
16
16
|
|
|
17
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* @param {DotrinoActa | null | undefined} acta
|
|
19
|
+
* @param {unknown} pub
|
|
20
|
+
* @returns {boolean}
|
|
21
|
+
*/
|
|
18
22
|
export function canGreet (acta, pub) {
|
|
19
23
|
if (!acta || typeof pub !== 'string' || !pub) return false
|
|
20
24
|
return (acta.members || []).some((m) => samePubkey(m?.pub, pub)) && memberCan(acta, pub, 'sign')
|
package/src/record.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
import { canAdopt, verifyActa, samePubkey } from '@dotrino/identity/acta'
|
|
19
19
|
|
|
20
20
|
/**
|
|
21
|
-
* @param {{ link:
|
|
21
|
+
* @param {{ link: import('./link.js').AgentLink, candidate: DotrinoActa | null | undefined, me: string }} args `me` = la llave pública de esta máquina.
|
|
22
22
|
* @returns {Promise<{ adopt: boolean, reason: string }>}
|
|
23
23
|
*/
|
|
24
24
|
export async function adoptRecord ({ link, candidate, me }) {
|