@dotrino/remote-agent 0.31.0 → 0.32.2
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 +7 -4
- package/src/agent.js +113 -29
- package/src/catch-up.js +5 -0
- package/src/client.js +117 -26
- 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.32.2",
|
|
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",
|
|
@@ -49,12 +49,15 @@
|
|
|
49
49
|
],
|
|
50
50
|
"peerDependencies": {
|
|
51
51
|
"@dotrino/identity": ">=0.121.7",
|
|
52
|
-
"@dotrino/proxy-client": ">=0.
|
|
52
|
+
"@dotrino/proxy-client": ">=0.46.0",
|
|
53
53
|
"@dotrino/vault": ">=0.115.0"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@dotrino/identity": "0.135.0",
|
|
57
|
-
"@dotrino/proxy-client": "0.
|
|
58
|
-
"@dotrino/vault": "0.115.0"
|
|
57
|
+
"@dotrino/proxy-client": "0.46.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
|
@@ -37,6 +37,10 @@ const PKG_VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import
|
|
|
37
37
|
|
|
38
38
|
/** Sesión cifrada con un dispositivo cliente. La app recibe esto en `onSession`. */
|
|
39
39
|
export class AgentSession {
|
|
40
|
+
/**
|
|
41
|
+
* @param {{ sid: string, key: CryptoKey, from: string, device: string,
|
|
42
|
+
* send: (to: string, obj: object) => void, isDirect?: ((token: string) => boolean) | null }} o
|
|
43
|
+
*/
|
|
40
44
|
constructor ({ sid, key, from, device, send, isDirect = null }) {
|
|
41
45
|
this.sid = sid
|
|
42
46
|
this.key = key
|
|
@@ -44,11 +48,32 @@ export class AgentSession {
|
|
|
44
48
|
this.device = device // pubkey del dispositivo cliente
|
|
45
49
|
this._send = send // (to, obj) => void
|
|
46
50
|
this._isDirect = isDirect // (token) => boolean, o null si el transporte no lo sabe
|
|
51
|
+
/** @type {{ message: Array<(msg: any) => void>, close: Array<() => void> }} */
|
|
47
52
|
this._h = { message: [], close: [] }
|
|
48
53
|
this._closed = false
|
|
54
|
+
/** @type {Promise<void> | undefined} */
|
|
55
|
+
this._out = undefined
|
|
56
|
+
/** @type {Promise<void> | undefined} */
|
|
57
|
+
this._in = undefined
|
|
58
|
+
/** Cuándo caduca sin mensajes (ms epoch). Lo pone el agente. */
|
|
59
|
+
this._exp = 0
|
|
60
|
+
/**
|
|
61
|
+
* El nonce del papel del cliente, para cortarla si se revoca.
|
|
62
|
+
* @type {string | null}
|
|
63
|
+
*/
|
|
64
|
+
this._certNonce = null
|
|
65
|
+
/**
|
|
66
|
+
* El cliente se desconectó: se le espera hasta que salte.
|
|
67
|
+
* @type {ReturnType<typeof setTimeout> | null}
|
|
68
|
+
*/
|
|
69
|
+
this._gone = null
|
|
49
70
|
}
|
|
50
71
|
|
|
51
|
-
/**
|
|
72
|
+
/**
|
|
73
|
+
* Envía un payload de dominio cifrado al cliente.
|
|
74
|
+
* @param {unknown} payload
|
|
75
|
+
* @returns {Promise<void>}
|
|
76
|
+
*/
|
|
52
77
|
send (payload) {
|
|
53
78
|
if (this._closed) return Promise.resolve()
|
|
54
79
|
// SALEN EN EL ORDEN EN QUE SE PIDIERON. Cifrar tarda según el tamaño: sin esta cola, un
|
|
@@ -75,6 +100,7 @@ export class AgentSession {
|
|
|
75
100
|
* Espera a que abra el canal directo, como mucho `ms`. Resuelve `true` si abrió y `false`
|
|
76
101
|
* si se acabó el plazo o la sesión se cerró — en los dos casos se sigue, por donde haya.
|
|
77
102
|
*/
|
|
103
|
+
/** @param {number} [ms] @returns {Promise<boolean>} */
|
|
78
104
|
whenDirect (ms = 8000) {
|
|
79
105
|
return new Promise((resolve) => {
|
|
80
106
|
const until = Date.now() + ms
|
|
@@ -88,9 +114,15 @@ export class AgentSession {
|
|
|
88
114
|
})
|
|
89
115
|
}
|
|
90
116
|
|
|
117
|
+
/**
|
|
118
|
+
* @param {'message' | 'close'} ev `message` recibe lo que mandó el cliente, ya descifrado
|
|
119
|
+
* @param {(msg?: any) => void} cb
|
|
120
|
+
* @returns {this}
|
|
121
|
+
*/
|
|
91
122
|
on (ev, cb) { this._h[ev]?.push(cb); return this }
|
|
92
123
|
|
|
93
124
|
/** Lo que llega se entrega en el orden en que llegó, tarde lo que tarde en descifrarse cada uno. */
|
|
125
|
+
/** @param {{ iv: string, ct: string }} env */
|
|
94
126
|
_ingest (env) {
|
|
95
127
|
const opened = open(this.key, env).then((msg) => ({ msg }), () => null)
|
|
96
128
|
this._in = (this._in || Promise.resolve()).then(() => opened).then((r) => {
|
|
@@ -102,7 +134,7 @@ export class AgentSession {
|
|
|
102
134
|
close () {
|
|
103
135
|
if (this._closed) return
|
|
104
136
|
this._closed = true
|
|
105
|
-
clearTimeout(this._gone)
|
|
137
|
+
if (this._gone) clearTimeout(this._gone)
|
|
106
138
|
for (const h of this._h.close) { try { h() } catch (_) {} }
|
|
107
139
|
}
|
|
108
140
|
}
|
|
@@ -110,20 +142,20 @@ export class AgentSession {
|
|
|
110
142
|
/**
|
|
111
143
|
* Arranca el agente. Devuelve `{ machine, machineId, master, client, reportIncident, isBlocked, checkCap, record, close }`.
|
|
112
144
|
*
|
|
113
|
-
* @param {object} opts
|
|
145
|
+
* @param {object} [opts]
|
|
114
146
|
* @param {string} [opts.label] qué agente es (`terminal-agent`, `ia-agent`…): lo contesta el pong
|
|
115
147
|
* para que las apps lo encuentren (`probeAgents`). El nombre del acta es del dueño.
|
|
116
148
|
* @param {string} [opts.proxyUrl] default wss://proxy.dotrino.com.
|
|
117
149
|
* @param {string} [opts.dir] dir del enlace (default dataDir()).
|
|
118
|
-
* @param {
|
|
150
|
+
* @param {import('./link.js').AgentLink | null} [opts.link] enlace ya cargado (override de dir).
|
|
119
151
|
* @param {(session:AgentSession)=>void} [opts.onSession] cada handshake exitoso abre una sesión.
|
|
120
152
|
* @param {()=>void} [opts.onRevoked] se llamó al auto-borrarse por revocación.
|
|
121
|
-
* @param {()=>void} [opts.onReady] agente listo y escuchando.
|
|
153
|
+
* @param {(o: { machine: string, machineId: string, master: string }) => void} [opts.onReady] agente listo y escuchando.
|
|
122
154
|
* @param {boolean} [opts.quiet] sin logs.
|
|
123
155
|
* @param {number} [opts.sessionGoneMs] cuánto se espera a un cliente cuya conexión se fue (`SESSION_GONE_MS`).
|
|
124
156
|
* @param {number} [opts.sessionTtlMs] cuánto dura una sesión sin mensajes (`SESSION_TTL_MS`, 30 min).
|
|
125
157
|
* @param {number} [opts.netLogMs] cada cuánto van al log las estadísticas de red (5 min).
|
|
126
|
-
* @param {
|
|
158
|
+
* @param {import('@dotrino/proxy-client').WebSocketProxyClient} [opts.client] transporte ya conectado (SOLO pruebas).
|
|
127
159
|
* @param {string} [opts.product] qué producto es (`accounts`, `terminal-agent`…), para el anuncio a la bóveda.
|
|
128
160
|
* @param {string} [opts.version] su versión. Sin `product`/`version` se anuncia como `remote-agent`.
|
|
129
161
|
* @param {string[]} [opts.needs] los permisos del acta que necesita, además de `sign`, que lo
|
|
@@ -138,23 +170,25 @@ export class AgentSession {
|
|
|
138
170
|
*/
|
|
139
171
|
export async function startRemoteAgent (opts = {}) {
|
|
140
172
|
const dir = opts.dir || dataDir()
|
|
141
|
-
const
|
|
142
|
-
if (!
|
|
173
|
+
const loaded = opts.link || loadLink(dir)
|
|
174
|
+
if (!loaded?.device?.privateJwk || !loaded?.cert || !loaded?.iss) {
|
|
143
175
|
throw new Error('this machine is not linked: enroll your agent first')
|
|
144
176
|
}
|
|
177
|
+
const link = loaded
|
|
145
178
|
const MY_DECL = declare({
|
|
146
179
|
product: opts.product || 'remote-agent', version: opts.version || PKG_VERSION,
|
|
147
180
|
protocol: VAULT_PROTOCOL, speaks: VAULT_SPEAKS, needs: ['sign', ...(opts.needs || [])]
|
|
148
181
|
})
|
|
149
|
-
const master = link.iss
|
|
182
|
+
const master = /** @type {string} */ (link.iss) // comprobado arriba
|
|
150
183
|
const myPub = link.device.publickey
|
|
151
184
|
const myId = await keyLabel(myPub)
|
|
152
185
|
|
|
153
186
|
installNodeGlobals(dir)
|
|
154
187
|
|
|
155
188
|
// sid -> AgentSession
|
|
189
|
+
/** @type {Map<string, AgentSession>} */
|
|
156
190
|
const sessions = new Map()
|
|
157
|
-
const hasSessionFrom = (token) => { for (const s of sessions.values()) if (s.from === token) return true; return false }
|
|
191
|
+
const hasSessionFrom = (/** @type {string} */ token) => { for (const s of sessions.values()) if (s.from === token) return true; return false }
|
|
158
192
|
|
|
159
193
|
const proxyUrl = opts.proxyUrl || process.env.PROXY_URL || link.proxy || DEFAULT_PROXY
|
|
160
194
|
// `client` inyectado: solo para las pruebas (transporte de mentira). En producción se
|
|
@@ -178,7 +212,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
178
212
|
const identify = async () => {
|
|
179
213
|
if (!client.token) return
|
|
180
214
|
// 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 }) })
|
|
215
|
+
await client.identifyAs({ publickey: myPub, sign: (/** @type {object} */ d) => signWithDevice({ privateJwk: link.device.privateJwk, data: d }) })
|
|
182
216
|
}
|
|
183
217
|
await identify()
|
|
184
218
|
client.on('token', () => { identify().catch(() => {}) })
|
|
@@ -186,17 +220,21 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
186
220
|
// Bitácora persistente (sessions.log, JSONL): qué dispositivo abrió sesión y cuándo
|
|
187
221
|
// — auditoría local si un dispositivo tuyo cae en malas manos.
|
|
188
222
|
const sessionsLog = path.join(dir, 'sessions.log')
|
|
189
|
-
const audit = (op, info = {}) => {
|
|
223
|
+
const audit = (/** @type {string} */ op, /** @type {object} */ info = {}) => {
|
|
190
224
|
try { fs.appendFileSync(sessionsLog, JSON.stringify({ ts: Date.now(), op, ...info }) + '\n') } catch (_) {}
|
|
191
225
|
}
|
|
192
226
|
|
|
193
|
-
const send = (to, obj) => { try { client.send(to, obj) } catch (e) { if (!opts.quiet) console.error('[remote-agent] send:', e.message) } }
|
|
227
|
+
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
228
|
|
|
195
229
|
/**
|
|
196
230
|
* Petición firmada a la bóveda por el proxy, dirigida a su pubkey maestra. Es el
|
|
197
231
|
* mismo sobre para todo (`data` firmado con la D + el cert de esta máquina): lo
|
|
198
232
|
* comparten el refresco de revocaciones y la renovación del cert.
|
|
199
233
|
*/
|
|
234
|
+
/**
|
|
235
|
+
* @param {string} sendType @param {string} okType @param {object} payload @param {number} [timeoutMs]
|
|
236
|
+
* @returns {Promise<any>} la respuesta de la bóveda; cada llamador lee sus campos con guardas
|
|
237
|
+
*/
|
|
200
238
|
async function vaultRpc (sendType, okType, payload, timeoutMs = 15000) {
|
|
201
239
|
// QUÉ SOY Y QUÉ NECESITO DEL ACTA, dentro de lo firmado: la bóveda lo apunta y enseña lo que
|
|
202
240
|
// falta en la fila de este aparato (dueño, 2026-10-27). `accounts` se pasó días sin `sign`,
|
|
@@ -207,8 +245,8 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
207
245
|
// El temporizador se LIMPIA al contestar (y no retiene el bucle de eventos):
|
|
208
246
|
// sin eso, cada consulta al vault dejaba 15 s de espera pendiente y un proceso
|
|
209
247
|
// corto que solo quería preguntar algo se quedaba colgado hasta que vencía.
|
|
210
|
-
const done = (fn, v) => { off(); clearTimeout(timer); fn(v) }
|
|
211
|
-
const off = client.on('message', (_f, p) => {
|
|
248
|
+
const done = (/** @type {(v: any) => void} */ fn, /** @type {unknown} */ v) => { off(); clearTimeout(timer); fn(v) }
|
|
249
|
+
const off = client.on('message', (_f, /** @type {any} */ p) => {
|
|
212
250
|
if (p?.type === okType) done(resolve, p)
|
|
213
251
|
else if (p?.type === VMSG.ERROR) done(reject, new Error(p.error))
|
|
214
252
|
})
|
|
@@ -219,29 +257,32 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
219
257
|
}
|
|
220
258
|
|
|
221
259
|
// --- Revocación: refrescar la lista del vault por el proxy (best-effort) ---
|
|
260
|
+
/** @type {Set<string>} */
|
|
222
261
|
let revokedSet = new Set()
|
|
223
262
|
// LOS BLOQUEADOS (dueño, 2026-10-07): un aprobador bloqueó a ese aparato tras un incidente.
|
|
224
263
|
// No es una revocación —sigue en el acta, y se deshace en la bóveda—, así que va aparte y
|
|
225
264
|
// viaja con la lista de revocados. Se PERSISTE en el enlace: con la bóveda apagada, el
|
|
226
265
|
// agente tiene que seguir cerrándole la puerta a quien ya estaba bloqueado.
|
|
266
|
+
/** @type {Set<string>} */
|
|
227
267
|
let blockedSet = new Set(Array.isArray(link.blocked) ? link.blocked : [])
|
|
228
268
|
async function refreshRevocations () {
|
|
229
269
|
try {
|
|
230
270
|
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))
|
|
271
|
+
revokedSet = new Set((res.revoked || []).map((/** @type {any} */ r) => r.nonce || r))
|
|
232
272
|
if (Array.isArray(res.blocked)) takeBlocked(res.blocked)
|
|
233
273
|
// El acta viaja con la lista. Apuntar su `seq` es lo que dispara la renovación en el
|
|
234
274
|
// mismo tic si el dueño nos cambió los permisos.
|
|
235
275
|
await recordActa(res.acta)
|
|
236
276
|
evictOutsiders()
|
|
237
277
|
} catch (e) {
|
|
238
|
-
if (!opts.quiet) console.error('[remote-agent] could not refresh revocations (using cache):', e.message)
|
|
278
|
+
if (!opts.quiet) console.error('[remote-agent] could not refresh revocations (using cache):', /** @type {Error} */ (e).message)
|
|
239
279
|
}
|
|
240
280
|
}
|
|
241
281
|
|
|
242
282
|
/** La lista nueva de bloqueados: se guarda, y a quien acaba de entrar en ella se le cierra la sesión. */
|
|
283
|
+
/** @param {unknown[]} pubs */
|
|
243
284
|
function takeBlocked (pubs) {
|
|
244
|
-
const next = new Set(pubs.filter((p) => typeof p === 'string'))
|
|
285
|
+
const next = new Set(/** @type {string[]} */ (pubs.filter((p) => typeof p === 'string')))
|
|
245
286
|
const same = next.size === blockedSet.size && [...next].every((p) => blockedSet.has(p))
|
|
246
287
|
blockedSet = next
|
|
247
288
|
if (same) return
|
|
@@ -261,6 +302,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
261
302
|
* bóveda: `{ id, approvers, blocked }` (`id: null` si nadie aprueba o ya está bloqueado).
|
|
262
303
|
* No decide nada aquí: un incidente es información, y el freno local es cosa de la app.
|
|
263
304
|
*/
|
|
305
|
+
/** @param {{ kind: string, about: string, tries?: number | null }} o */
|
|
264
306
|
async function reportIncident ({ kind, about, tries = null }) {
|
|
265
307
|
if (typeof kind !== 'string' || !kind || typeof about !== 'string' || !about) throw new Error('reportIncident: kind and about are required')
|
|
266
308
|
audit('incident', { kind, device: (await pubkeyId(about).catch(() => '')).slice(0, 8).toUpperCase(), tries })
|
|
@@ -300,7 +342,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
300
342
|
// No es fatal: el papel de antes sigue sirviendo para todo lo que el acta le siga
|
|
301
343
|
// permitiendo, y el próximo tic reintenta. Se avisa igual: si esto falla, lo que el
|
|
302
344
|
// dueño acaba de conceder no llega.
|
|
303
|
-
if (!opts.quiet) console.error('[remote-agent] could not renew the cert:', e.message)
|
|
345
|
+
if (!opts.quiet) console.error('[remote-agent] could not renew the cert:', /** @type {Error} */ (e).message)
|
|
304
346
|
}
|
|
305
347
|
}
|
|
306
348
|
|
|
@@ -317,6 +359,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
317
359
|
* mandar un acta inventada y nombrarse miembro. Ahora el acta tiene que encadenar desde la
|
|
318
360
|
* que ya se dio por buena, o venir firmada por la bóveda con la que se enroló.
|
|
319
361
|
*/
|
|
362
|
+
/** @param {any} acta lo que llegó: se comprueba antes de adoptarlo @returns {Promise<boolean>} */
|
|
320
363
|
async function recordActa (acta) {
|
|
321
364
|
if (typeof acta?.seq !== 'number') return false
|
|
322
365
|
const r = await adoptRecord({ link, candidate: acta, me: myPub })
|
|
@@ -332,9 +375,41 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
332
375
|
link.actaTrusted = true
|
|
333
376
|
try { saveLink(dir, link) } catch (_) {}
|
|
334
377
|
evictOutsiders()
|
|
378
|
+
shareActa(acta)
|
|
335
379
|
return true
|
|
336
380
|
}
|
|
337
381
|
|
|
382
|
+
/**
|
|
383
|
+
* LA CACHÉ DE ACTAS DEL PROXIO (websocket-proxy ≥ 1.10.0). Quien adopta un acta nueva se la
|
|
384
|
+
* deja al proxio, así el siguiente aparato de la cuenta se entera sin despertar a la bóveda;
|
|
385
|
+
* y antes de preguntarle a la bóveda se mira ahí. Lo que llega del proxio pasa por
|
|
386
|
+
* `recordActa`, o sea que se adopta solo si encadena desde la de confianza: el proxio no
|
|
387
|
+
* puede colar nada, como mucho no tener la más nueva.
|
|
388
|
+
*/
|
|
389
|
+
const actaCacheProblems = new Set()
|
|
390
|
+
/** @param {string} what @param {any} e */
|
|
391
|
+
function noteActaCache (what, e) {
|
|
392
|
+
const code = e?.code || 'error'
|
|
393
|
+
if (actaCacheProblems.has(what + code)) return
|
|
394
|
+
actaCacheProblems.add(what + code)
|
|
395
|
+
if (!opts.quiet) console.error(`[remote-agent] record cache on the proxy (${what}): ${code} · ${e?.message || ''}`)
|
|
396
|
+
}
|
|
397
|
+
/** @param {DotrinoActa} acta */
|
|
398
|
+
function shareActa (acta) {
|
|
399
|
+
// Por detrás y sin tumbar a quien adopta: si falla, se dice una vez y sigue.
|
|
400
|
+
Promise.resolve().then(() => client.putActa(acta)).catch((e) => noteActaCache('put', e))
|
|
401
|
+
}
|
|
402
|
+
/** Adopta la más nueva del proxio que encadene. `true` si el acta avanzó. */
|
|
403
|
+
async function actaFromProxy () {
|
|
404
|
+
const profileId = trustedActa()?.profileId
|
|
405
|
+
if (!profileId) return false
|
|
406
|
+
/** @type {object[]} */
|
|
407
|
+
let list
|
|
408
|
+
try { list = await client.getActas(profileId, { sinceSeq: link.actaSeq ?? -1 }) } catch (e) { noteActaCache('get', e); return false }
|
|
409
|
+
for (const a of list) if (await recordActa(a)) return true
|
|
410
|
+
return false
|
|
411
|
+
}
|
|
412
|
+
|
|
338
413
|
/**
|
|
339
414
|
* CIERRA LAS SESIONES DE QUIEN YA NO PUEDE ESTAR: el acta de confianza ya no lo nombra (o
|
|
340
415
|
* le quitó `sign`), o su papel se retiró. Se juzgaba solo al saludar, así que un aparato
|
|
@@ -358,6 +433,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
358
433
|
* El acta con la que se juzga un papel. Sin ella no se atiende a nadie — y un acta que
|
|
359
434
|
* nunca se comprobó (la que guardó una versión anterior) cuenta como no tenerla.
|
|
360
435
|
*/
|
|
436
|
+
/** @returns {DotrinoActa | null} */
|
|
361
437
|
const trustedActa = () => (link.actaTrusted === true && link.acta ? link.acta : null)
|
|
362
438
|
const actaContext = () => {
|
|
363
439
|
const acta = trustedActa()
|
|
@@ -366,7 +442,8 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
366
442
|
|
|
367
443
|
const vaultTick = async () => { await refreshRevocations(); await renewCertIfNeeded() }
|
|
368
444
|
/** Trae el acta ahora (con freno) y dice si AVANZÓ: solo entonces merece juzgar otra vez. */
|
|
369
|
-
|
|
445
|
+
// Ponerse al día mira primero la caché del proxio y, si no trae nada que encadene, la bóveda.
|
|
446
|
+
const catchUp = makeCatchUp({ refresh: async () => { if (!await actaFromProxy()) await vaultTick() }, seq: () => link.actaSeq ?? null })
|
|
370
447
|
vaultTick()
|
|
371
448
|
const revTimer = setInterval(vaultTick, REVOKE_REFRESH_MS); revTimer.unref?.()
|
|
372
449
|
|
|
@@ -385,6 +462,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
385
462
|
}
|
|
386
463
|
}, Math.min(60 * 1000, ttlMs)); sweeper.unref?.()
|
|
387
464
|
|
|
465
|
+
/** @param {string} from @param {any} p el saludo tal como llegó: se comprueba campo a campo */
|
|
388
466
|
async function handleHandshake (from, p) {
|
|
389
467
|
const { data, signature, cert } = p
|
|
390
468
|
if (!data || !signature || !cert) return send(from, { type: ERROR, error: 'incomplete handshake' })
|
|
@@ -402,16 +480,17 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
402
480
|
// 2026-10-07). Ahora, ante un rechazo, se trae el acta EN EL MOMENTO y se juzga otra vez, una
|
|
403
481
|
// sola — y solo si el acta avanzó. Con freno (`catchUp`): cualquiera puede mandar saludos, y
|
|
404
482
|
// no por eso se le pregunta a la bóveda cada vez.
|
|
483
|
+
/** @returns {Promise<{ chk: { ok: boolean, device: string }, error?: undefined, code?: undefined, reason?: undefined } | { chk?: undefined, code: string, reason?: string, error: string }>} */
|
|
405
484
|
const judge = async () => {
|
|
406
485
|
const chk = await verifyChain({ data, signature, cert, expectedScope: SIGN_SCOPE, ...actaContext(), revoked: revokedSet })
|
|
407
486
|
if (!chk.ok) return { code: 'unauthorized', reason: chk.reason, error: 'unauthorized: ' + chk.reason }
|
|
408
|
-
return { chk }
|
|
487
|
+
return { chk: { ...chk, device: /** @type {string} */ (chk.device) } } // ok: verifyChain dice qué aparato firmó
|
|
409
488
|
}
|
|
410
489
|
let verdict = await judge()
|
|
411
|
-
const known = (v) => canGreet(trustedActa(), v.chk.device)
|
|
490
|
+
const known = (/** @type {Awaited<ReturnType<typeof judge>>} */ v) => !!v.chk && canGreet(trustedActa(), v.chk.device)
|
|
412
491
|
if ((verdict.error || !known(verdict)) && await catchUp()) verdict = await judge()
|
|
413
492
|
if (verdict.error) return send(from, { type: ERROR, code: verdict.code, reason: verdict.reason, error: verdict.error })
|
|
414
|
-
const chk = verdict.chk
|
|
493
|
+
const chk = /** @type {NonNullable<typeof verdict.chk>} */ (verdict.chk) // sin error hay chk
|
|
415
494
|
// CERT ∩ ACTA. `verifyChain` comprueba QUIÉN EMITIÓ el papel; que el APARATO siga siendo
|
|
416
495
|
// isMember y pueda firmar lo dice el acta, y hay que preguntárselo aparte. Sin esto, un
|
|
417
496
|
// papel bien firmado por una selladora abría sesión aunque el acta no nombrara a ese
|
|
@@ -447,7 +526,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
447
526
|
const ack = { op: ACK, sid, seph: eph.pub, ceph: data.eph, machine: myPub, publickey: myPub, ts: Date.now() }
|
|
448
527
|
const { signature: ackSig } = await signWithDevice({ privateJwk: link.device.privateJwk, data: ack })
|
|
449
528
|
|
|
450
|
-
const session = new AgentSession({ sid, key, from, device: chk.device, send, isDirect: typeof client.isWebRTCOpen === 'function' ? (t) => client.isWebRTCOpen(t) : null })
|
|
529
|
+
const session = new AgentSession({ sid, key, from, device: chk.device, send, isDirect: typeof client.isWebRTCOpen === 'function' ? (/** @type {string} */ t) => client.isWebRTCOpen(t) : null })
|
|
451
530
|
session._exp = Date.now() + ttlMs
|
|
452
531
|
// El papel con que entró: si después se retira (`revoked`), la sesión se cierra.
|
|
453
532
|
session._certNonce = cert.nonce || null
|
|
@@ -455,9 +534,10 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
455
534
|
audit('session-open', { sid: sid.slice(0, 8), device: (await pubkeyId(chk.device)).slice(0, 8).toUpperCase() })
|
|
456
535
|
send(from, { type: ACK, sid, ack, signature: ackSig, cert: link.cert })
|
|
457
536
|
if (!opts.quiet) console.log(`[remote-agent] session ${sid.slice(0, 8)} authorized (device ${chk.device?.slice?.(0, 8) || '?'})`)
|
|
458
|
-
if (opts.onSession) { try { opts.onSession(session) } catch (e) { if (!opts.quiet) console.error('[remote-agent] onSession:', e.message) } }
|
|
537
|
+
if (opts.onSession) { try { opts.onSession(session) } catch (e) { if (!opts.quiet) console.error('[remote-agent] onSession:', /** @type {Error} */ (e).message) } }
|
|
459
538
|
}
|
|
460
539
|
|
|
540
|
+
/** @param {string} from @param {any} p */
|
|
461
541
|
function handleData (from, p) {
|
|
462
542
|
const s = sessions.get(p.sid)
|
|
463
543
|
// Con `code` y el `sid`: así el cliente sabe que es SU sesión la que se perdió (el agente
|
|
@@ -476,14 +556,14 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
476
556
|
// Antes solo vencía por `SESSION_TTL_MS`: un teléfono que volvía del fondo abría sesión nueva
|
|
477
557
|
// y la vieja seguía enganchada a su consola (seis del mismo aparato en una, el 2026-10-09).
|
|
478
558
|
const goneMs = opts.sessionGoneMs ?? SESSION_GONE_MS
|
|
479
|
-
client.on('peer_disconnected', (token) => {
|
|
559
|
+
client.on('peer_disconnected', (/** @type {string} */ token) => {
|
|
480
560
|
for (const [sid, s] of sessions) {
|
|
481
561
|
if (s.from !== token || s._gone) continue
|
|
482
562
|
s._gone = setTimeout(() => {
|
|
483
563
|
s.close(); sessions.delete(sid)
|
|
484
564
|
audit('session-gone', { sid: sid.slice(0, 8) })
|
|
485
565
|
}, goneMs)
|
|
486
|
-
s._gone
|
|
566
|
+
s._gone?.unref?.()
|
|
487
567
|
}
|
|
488
568
|
})
|
|
489
569
|
|
|
@@ -508,6 +588,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
508
588
|
// firma valida y el body es para nuestra pubkey → un proxy/peer malicioso NO puede
|
|
509
589
|
// borrarnos con un mensaje falso (cierra el wipe-DoS). Borra el enlace (link.json) y
|
|
510
590
|
// detiene el agente.
|
|
591
|
+
/** @param {any} p el aviso de revocación: se comprueba su firma */
|
|
511
592
|
async function handleRevoked (p) {
|
|
512
593
|
const b = p?.body
|
|
513
594
|
if (!b || b.op !== 'revoke' || b.sub !== myPub) return
|
|
@@ -527,6 +608,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
527
608
|
* quitar un aparato le cierra la consola en el acto, sin esperar al tic de cinco minutos.
|
|
528
609
|
* Un bloqueo no cambia el acta: va en la lista, que sí se pide.
|
|
529
610
|
*/
|
|
611
|
+
/** @param {any} payload */
|
|
530
612
|
async function onAdminEvent (payload) {
|
|
531
613
|
const ev = payload.body?.ev
|
|
532
614
|
if (ev === 'blocked' || ev === 'unblocked') return refreshRevocations()
|
|
@@ -534,7 +616,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
534
616
|
if (typeof payload.acta?.seq === 'number' && payload.acta.seq > (link.actaSeq ?? -1)) await catchUp()
|
|
535
617
|
}
|
|
536
618
|
|
|
537
|
-
client.on('message', (from, payload) => {
|
|
619
|
+
client.on('message', (/** @type {string} */ from, /** @type {any} */ payload) => {
|
|
538
620
|
if (!payload || typeof payload !== 'object') return
|
|
539
621
|
if (payload.type === HS) handleHandshake(from, payload).catch((e) => send(from, { type: ERROR, error: e.message }))
|
|
540
622
|
else if (payload.type === DATA) handleData(from, payload)
|
|
@@ -562,8 +644,10 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
562
644
|
* Sin repliegue: sin acta no se sabe, y se dice con su código.
|
|
563
645
|
* @returns {Promise<{ ok: true, seq: number } | { ok: false, code: 'no-record'|'not-in-record'|'missing-cap' }>}
|
|
564
646
|
*/
|
|
647
|
+
/** @param {string} pub @param {string} cap */
|
|
565
648
|
async function checkCap (pub, cap) {
|
|
566
649
|
if (typeof pub !== 'string' || !pub || typeof cap !== 'string' || !cap) throw Object.assign(new Error('checkCap: pub and cap are required'), { code: 'bad-request' })
|
|
650
|
+
/** @returns {{ ok: true, seq: number } | { ok: false, code: 'no-record'|'not-in-record'|'missing-cap' }} */
|
|
567
651
|
const look = () => {
|
|
568
652
|
const acta = trustedActa()
|
|
569
653
|
if (!acta) return { ok: false, code: 'no-record' }
|
|
@@ -581,7 +665,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
581
665
|
}
|
|
582
666
|
if (opts.onReady) { try { opts.onReady({ machine: myPub, machineId: myId, master }) } catch (_) {} }
|
|
583
667
|
|
|
584
|
-
return { machine: myPub, machineId: myId, master, client, reportIncident, isBlocked: (pub) => blockedSet.has(pub), checkCap, record: trustedActa, close: stop }
|
|
668
|
+
return { machine: myPub, machineId: myId, master, client, reportIncident, isBlocked: (/** @type {string} */ pub) => blockedSet.has(pub), checkCap, record: trustedActa, close: stop }
|
|
585
669
|
}
|
|
586
670
|
|
|
587
671
|
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
|
@@ -21,20 +21,36 @@
|
|
|
21
21
|
* `on('message', cb)` recibe los payloads del agente, ya descifrados.
|
|
22
22
|
*/
|
|
23
23
|
import { verifyChain } from '@dotrino/identity/capabilities'
|
|
24
|
-
import { sealersOf, samePubkey } from '@dotrino/identity/acta'
|
|
24
|
+
import { sealersOf, samePubkey, canAdopt } from '@dotrino/identity/acta'
|
|
25
25
|
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,28 @@ 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
|
+
// @ts-expect-error proxy-client 0.46.0: su ProxyEvent no lista 'token_gone', que sí emite (src/client.js)
|
|
162
|
+
client.on('token_gone', (/** @type {string} */ token) => {
|
|
123
163
|
this._directPeers.delete(token)
|
|
124
164
|
if (token === this.agentToken) this.agentToken = null
|
|
125
165
|
})
|
|
126
166
|
|
|
127
|
-
|
|
167
|
+
client.on('message', (_from, p) => {
|
|
128
168
|
if (!p || typeof p !== 'object') return
|
|
129
|
-
if (p.type === DATA && p.sid === this.sid) {
|
|
169
|
+
if (p.type === DATA && p.sid === this.sid && this.key) {
|
|
130
170
|
// Se entregan en el orden en que llegaron: descifrar tarda según el tamaño, y sin
|
|
131
171
|
// esta cola un mensaje pequeño adelantaba a uno grande que llegó antes.
|
|
132
172
|
const opened = open(this.key, p.env).then((m) => ({ m }), () => null)
|
|
@@ -147,6 +187,7 @@ export class RemoteAgentClient {
|
|
|
147
187
|
* sale por `error`. Un `unknown-session` de un `sid` que ya no es el nuestro (llegó tarde,
|
|
148
188
|
* de antes de volver a saludar) no dice nada nuevo y se ignora.
|
|
149
189
|
*/
|
|
190
|
+
/** @param {{ code?: string, error?: string, reason?: string, sid?: string }} p */
|
|
150
191
|
_onAgentError (p) {
|
|
151
192
|
if (p.code !== 'unknown-session') { this._emit('error', Object.assign(new Error(p.error), { code: p.code, reason: p.reason })); return }
|
|
152
193
|
if (p.sid !== this.sid) return
|
|
@@ -154,6 +195,7 @@ export class RemoteAgentClient {
|
|
|
154
195
|
}
|
|
155
196
|
|
|
156
197
|
/** Vuelve a saludar, una sola vez aunque lleguen varios errores seguidos. */
|
|
198
|
+
/** @returns {Promise<void>} */
|
|
157
199
|
_resume () {
|
|
158
200
|
if (this._resuming) return this._resuming
|
|
159
201
|
this.key = null
|
|
@@ -180,8 +222,10 @@ export class RemoteAgentClient {
|
|
|
180
222
|
// El ACK se correlaciona por la clave efímera PROPIA (ceph === eph.pub): así
|
|
181
223
|
// varias sesiones simultáneas (varios RemoteAgentClient sobre la misma pubkey)
|
|
182
224
|
// no se roban el ACK de la otra.
|
|
225
|
+
const client = this._client()
|
|
226
|
+
/** @type {Promise<AgentAck>} */
|
|
183
227
|
const acked = new Promise((resolve, reject) => {
|
|
184
|
-
const off =
|
|
228
|
+
const off = client.on('message', (from, p) => {
|
|
185
229
|
if (!p || typeof p !== 'object') return
|
|
186
230
|
// El token se apunta AQUÍ, en el mismo tic: si el agente es quien abre el canal
|
|
187
231
|
// directo, su oferta llega justo detrás del ack y tiene que encontrarlo ya.
|
|
@@ -190,13 +234,17 @@ export class RemoteAgentClient {
|
|
|
190
234
|
})
|
|
191
235
|
setTimeout(() => { off(); reject(new Error('the agent did not reply (is it running there?)')) }, 20000)
|
|
192
236
|
})
|
|
193
|
-
|
|
237
|
+
client.sendByPubkey(/** @type {string} */ (this.agentPubkey), { type: HS, data, signature, cert })
|
|
194
238
|
const res = await acked
|
|
195
|
-
try { await this._checkAck(res, eph) } catch (e) { this._directPeers.delete(res.from); throw e }
|
|
239
|
+
try { await this._checkAck(res, eph) } catch (e) { if (res.from) this._directPeers.delete(res.from); throw e }
|
|
196
240
|
this.agentToken = res.from || null
|
|
197
241
|
}
|
|
198
242
|
|
|
199
|
-
/**
|
|
243
|
+
/**
|
|
244
|
+
* Comprueba el ack y deja `sid` y `key`.
|
|
245
|
+
* @param {AgentAck} res
|
|
246
|
+
* @param {{ privateKey: CryptoKey, pub: string }} eph
|
|
247
|
+
*/
|
|
200
248
|
async _checkAck (res, eph) {
|
|
201
249
|
// PRIMERO EL ACTA QUE YA SE TIENE (`trustedActa`), y la bóveda solo si con esa no pasa.
|
|
202
250
|
// Preguntarle en cada saludo hacía esperar a la ventana 4-17 s antes de pedir la clave de
|
|
@@ -206,12 +254,37 @@ export class RemoteAgentClient {
|
|
|
206
254
|
let local = null
|
|
207
255
|
try { local = this.trustedActa?.() || null } catch (_) {}
|
|
208
256
|
if (local) {
|
|
209
|
-
try { return await this._judgeAck(res, eph, local) } catch (e) { if (e.code !== 'unauthorized') throw e }
|
|
257
|
+
try { return await this._judgeAck(res, eph, local) } catch (e) { if (/** @type {{ code?: string }} */ (e).code !== 'unauthorized') throw e }
|
|
258
|
+
// Va atrás: antes que la bóveda, la caché de actas del proxio (websocket-proxy ≥ 1.10.0).
|
|
259
|
+
const newer = await this._actaFromProxy(local)
|
|
260
|
+
if (newer) {
|
|
261
|
+
try { return await this._judgeAck(res, eph, newer) } catch (e) { if (/** @type {{ code?: string }} */ (e).code !== 'unauthorized') throw e }
|
|
262
|
+
}
|
|
210
263
|
}
|
|
211
264
|
return this._judgeAck(res, eph, await this._acta())
|
|
212
265
|
}
|
|
213
266
|
|
|
214
|
-
/**
|
|
267
|
+
/**
|
|
268
|
+
* La más nueva de la caché del proxio que ENCADENE desde `trusted` (`canAdopt`), o `null`.
|
|
269
|
+
* El proxio no es de fiar: lo que no encadena se ignora. Si no se pudo preguntar, el motivo
|
|
270
|
+
* queda en `actaCacheError` y se sigue con la bóveda, que es quien manda.
|
|
271
|
+
*/
|
|
272
|
+
/** @param {DotrinoActa} trusted @returns {Promise<DotrinoActa | null>} */
|
|
273
|
+
async _actaFromProxy (trusted) {
|
|
274
|
+
if (!trusted?.profileId) return null
|
|
275
|
+
/** @type {DotrinoActa[]} */
|
|
276
|
+
let list
|
|
277
|
+
try { list = /** @type {DotrinoActa[]} */ (await this._client().getActas(trusted.profileId, { sinceSeq: trusted.seq })) } catch (e) { this.actaCacheError = e; return null }
|
|
278
|
+
for (const a of list) if ((await canAdopt({ candidate: a, current: trusted })).adopt) return a
|
|
279
|
+
return null
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Juzga el ack con `acta` y, si pasa, deja `sid` y `key`.
|
|
284
|
+
* @param {AgentAck} res
|
|
285
|
+
* @param {{ privateKey: CryptoKey, pub: string }} eph
|
|
286
|
+
* @param {DotrinoActa | null} acta
|
|
287
|
+
*/
|
|
215
288
|
async _judgeAck (res, eph, acta) {
|
|
216
289
|
|
|
217
290
|
// El ack debe: (1) encadenar a NUESTRA maestra, (2) estar firmado por el agente
|
|
@@ -247,10 +320,16 @@ export class RemoteAgentClient {
|
|
|
247
320
|
this.key = await deriveKey(eph.privateKey, res.ack.seph, res.sid)
|
|
248
321
|
}
|
|
249
322
|
|
|
250
|
-
/**
|
|
323
|
+
/**
|
|
324
|
+
* Envía un payload de dominio cifrado al agente (si se está volviendo a saludar, después).
|
|
325
|
+
* @param {unknown} payload
|
|
326
|
+
* @returns {Promise<void>}
|
|
327
|
+
*/
|
|
251
328
|
async send (payload) {
|
|
252
329
|
if (this._resuming) await this._resuming
|
|
253
330
|
if (!this.key) throw Object.assign(new Error('no session with the agent'), { code: 'no-session' })
|
|
331
|
+
const client = this._client()
|
|
332
|
+
const agentPubkey = /** @type {string} */ (this.agentPubkey) // `connect` la exigió
|
|
254
333
|
// Salen en el orden en que se pidieron, tarde lo que tarde en cifrarse cada uno.
|
|
255
334
|
const sid = this.sid
|
|
256
335
|
const sealed = seal(this.key, payload)
|
|
@@ -258,30 +337,42 @@ export class RemoteAgentClient {
|
|
|
258
337
|
const msg = { type: DATA, sid, env }
|
|
259
338
|
// Por token en cuanto se sabe: sube al canal directo, y si el token murió el pilar lo
|
|
260
339
|
// saca por la pubkey. Por pubkey solo mientras no hay token.
|
|
261
|
-
if (this.agentToken)
|
|
262
|
-
else
|
|
340
|
+
if (this.agentToken) client.sendToOrQueue(this.agentToken, msg, { peerPubkey: agentPubkey })
|
|
341
|
+
else client.sendByPubkey(agentPubkey, msg)
|
|
263
342
|
})
|
|
264
343
|
this._out = turn.catch(() => {})
|
|
265
344
|
return turn
|
|
266
345
|
}
|
|
267
346
|
|
|
268
|
-
/**
|
|
347
|
+
/**
|
|
348
|
+
* Sonda de presencia (liveness) sin abrir sesión. Devuelve true si responde.
|
|
349
|
+
* @param {{ timeoutMs?: number }} [o]
|
|
350
|
+
* @returns {Promise<boolean>}
|
|
351
|
+
*/
|
|
269
352
|
async ping ({ timeoutMs = 4000 } = {}) {
|
|
353
|
+
const client = this._client()
|
|
270
354
|
const n = crypto.getRandomValues(new Uint8Array(8)).join('')
|
|
355
|
+
/** @type {Promise<boolean>} */
|
|
271
356
|
const got = new Promise((resolve) => {
|
|
272
|
-
const off =
|
|
357
|
+
const off = client.on('message', (_f, p) => {
|
|
273
358
|
if (p?.type === PONG && p.n === n) { off(); resolve(true) }
|
|
274
359
|
})
|
|
275
360
|
setTimeout(() => { off(); resolve(false) }, timeoutMs)
|
|
276
361
|
})
|
|
277
362
|
// Efímero, como `probeAgents`: si no está, no se encola ni se le timbra.
|
|
278
|
-
|
|
363
|
+
client.sendByPubkey(/** @type {string} */ (this.agentPubkey), { type: PING, n }, { ephemeral: true })
|
|
279
364
|
return got
|
|
280
365
|
}
|
|
281
366
|
|
|
282
367
|
async close () {
|
|
283
368
|
try { this.client?.close() } catch {}
|
|
284
369
|
}
|
|
370
|
+
|
|
371
|
+
/** El transporte, que existe desde `connect`. Usarlo antes es un fallo de quien llama. */
|
|
372
|
+
_client () {
|
|
373
|
+
if (!this.client) throw Object.assign(new Error('not connected: call connect() first'), { code: 'not-connected' })
|
|
374
|
+
return this.client
|
|
375
|
+
}
|
|
285
376
|
}
|
|
286
377
|
|
|
287
378
|
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 }) {
|