@dotrino/remote-agent 0.26.0 → 0.28.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/README.md CHANGED
@@ -33,7 +33,7 @@ Provee lo común — y **solo** eso:
33
33
  | `@dotrino/remote-agent` | isomórfico | `e2e` (`makeEphemeral`/`deriveKey`/`seal`/`open`) + constantes de protocolo |
34
34
  | `@dotrino/remote-agent/agent` | Node | `startRemoteAgent(opts)` |
35
35
  | `@dotrino/remote-agent/client` | navegador | `RemoteAgentClient` |
36
- | `@dotrino/remote-agent/link` | Node | `enroll`, `loadLink`, `saveLink`, `dataDir`, `parseQr`, `identityFromLink`, `clientLink`, `renewLink` |
36
+ | `@dotrino/remote-agent/link` | Node | `enroll`, `selfLink`, `isSelfLink`, `loadLink`, `saveLink`, `dataDir`, `parseQr`, `identityFromLink`, `clientLink`, `renewLink` |
37
37
  | `@dotrino/remote-agent/discover` | navegador | `listAgentsByLabel`, `probeAgents` |
38
38
  | `@dotrino/remote-agent/instances` | Node | `resolveInstance`, `listInstances`, `lockInstance`, `instancesRoot` |
39
39
 
@@ -107,6 +107,18 @@ parámetros (`{ ns, proxyUrl: link.proxy, masterPubkey: link.iss, device, cert,
107
107
  Un agente que corre UNA vez (un bot por cron) no tiene el tic de renovación de
108
108
  `startRemoteAgent`: que llame a `renewLink(link)` en cada corrida, o su cert muere a los 30 días.
109
109
 
110
+ ### Sin bóveda: identidad propia (`selfLink`)
111
+
112
+ Un agente no tiene por qué exigir una bóveda. `selfLink({ label, dir })` crea las llaves
113
+ del aparato (firma y cifrado) y un acta de génesis autofirmada donde él es el único
114
+ miembro: una cuenta de un solo aparato, la misma forma que «este dispositivo es bóveda»
115
+ en el navegador. `identityFromLink` la sirve igual (`signData` lleva la cadena `[génesis]`
116
+ y `verifySignedFor` la acepta); lo que pregunta a una bóveda lanza `no-vault`.
117
+
118
+ Para pasarlo después a una cuenta **con la misma llave**: `enroll({ qr, label, dir, keep:
119
+ link })`. Necesita `@dotrino/vault` ≥ 0.115.0; con una más vieja se para con
120
+ `key-not-kept` en vez de cambiar de llave en silencio.
121
+
110
122
  ### Dónde vive el enlace: `~/.dotrino/agent/<tipo>/<nombre>/` (el estándar)
111
123
 
112
124
  Todo agente guarda su enlace ahí, igual que `dotrino-env` guarda el suyo en
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/remote-agent",
3
- "version": "0.26.0",
3
+ "version": "0.28.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",
package/src/agent.js CHANGED
@@ -121,6 +121,7 @@ export class AgentSession {
121
121
  * @param {()=>void} [opts.onReady] agente listo y escuchando.
122
122
  * @param {boolean} [opts.quiet] sin logs.
123
123
  * @param {number} [opts.sessionGoneMs] cuánto se espera a un cliente cuya conexión se fue (`SESSION_GONE_MS`).
124
+ * @param {number} [opts.sessionTtlMs] cuánto dura una sesión sin mensajes (`SESSION_TTL_MS`, 30 min).
124
125
  * @param {number} [opts.netLogMs] cada cuánto van al log las estadísticas de red (5 min).
125
126
  * @param {object} [opts.client] transporte ya conectado (SOLO pruebas).
126
127
  * @param {string} [opts.product] qué producto es (`accounts`, `terminal-agent`…), para el anuncio a la bóveda.
@@ -369,12 +370,20 @@ export async function startRemoteAgent (opts = {}) {
369
370
  vaultTick()
370
371
  const revTimer = setInterval(vaultTick, REVOKE_REFRESH_MS); revTimer.unref?.()
371
372
 
373
+ const ttlMs = opts.sessionTtlMs ?? SESSION_TTL_MS
374
+ // UNA SESIÓN QUE VENCE SE LE DICE AL CLIENTE en ese momento, con el mismo `unknown-session`
375
+ // que recibiría al mandar algo. Antes vencía callada: la ventana de una consola quieta seguía
376
+ // pareciendo abierta y solo se enteraba al teclear, con la consola ya perdida (2026-11-04).
377
+ // Así el cliente vuelve a saludar enseguida y la app decide qué enseña.
372
378
  const sweeper = setInterval(() => {
373
379
  const now = Date.now()
374
380
  for (const [sid, s] of sessions) {
375
- if (now > s._exp) { s.close(); sessions.delete(sid); audit('session-expire', { sid: sid.slice(0, 8) }) }
381
+ if (now > s._exp) {
382
+ s.close(); sessions.delete(sid); audit('session-expire', { sid: sid.slice(0, 8) })
383
+ if (!s._gone) send(s.from, { type: ERROR, code: 'unknown-session', sid, error: 'unknown or expired session' })
384
+ }
376
385
  }
377
- }, 60 * 1000); sweeper.unref?.()
386
+ }, Math.min(60 * 1000, ttlMs)); sweeper.unref?.()
378
387
 
379
388
  async function handleHandshake (from, p) {
380
389
  const { data, signature, cert } = p
@@ -439,7 +448,7 @@ export async function startRemoteAgent (opts = {}) {
439
448
  const { signature: ackSig } = await signWithDevice({ privateJwk: link.device.privateJwk, data: ack })
440
449
 
441
450
  const session = new AgentSession({ sid, key, from, device: chk.device, send, isDirect: typeof client.isWebRTCOpen === 'function' ? (t) => client.isWebRTCOpen(t) : null })
442
- session._exp = Date.now() + SESSION_TTL_MS
451
+ session._exp = Date.now() + ttlMs
443
452
  // El papel con que entró: si después se retira (`revoked`), la sesión se cierra.
444
453
  session._certNonce = cert.nonce || null
445
454
  sessions.set(sid, session)
@@ -455,7 +464,7 @@ export async function startRemoteAgent (opts = {}) {
455
464
  // se reinició, o venció) y vuelve a saludar solo, en vez de quedarse con un error. Se
456
465
  // comprueba por el código, no por la frase.
457
466
  if (!s) return send(from, { type: ERROR, code: 'unknown-session', sid: p.sid, error: 'unknown or expired session' })
458
- s._exp = Date.now() + SESSION_TTL_MS
467
+ s._exp = Date.now() + ttlMs
459
468
  s.from = from
460
469
  if (s._gone) { clearTimeout(s._gone); s._gone = null }
461
470
  s._ingest(p.env).catch(() => send(from, { type: ERROR, error: 'invalid envelope' }))
package/src/link.js CHANGED
@@ -16,11 +16,11 @@
16
16
  import fs from 'node:fs'
17
17
  import path from 'node:path'
18
18
  import os from 'node:os'
19
- import { signWithDevice, pubkeyId } from '@dotrino/identity/capabilities'
19
+ import { signWithDevice, pubkeyId, makeDeviceKey, makeDeviceEncKey } from '@dotrino/identity/capabilities'
20
20
  import { requestDevices, requestRenew } from '@dotrino/identity/vault/remote.js'
21
21
  import { installNodeGlobals } from '../node-globals.js'
22
22
  import { adoptRecord } from './record.js'
23
- import { verifySealerChain } from '@dotrino/identity/acta'
23
+ import { verifySealerChain, genesisActa, sealActa } from '@dotrino/identity/acta'
24
24
  import { DEFAULT_PROXY, RENEW_BEFORE_MS } from '../protocol.js'
25
25
 
26
26
  export function dataDir (name = 'dotrino-remote-agent') {
@@ -84,7 +84,7 @@ export function b64urlDecode (s) {
84
84
  * que un humano lo TIPEE en la bóveda al aprobar (el código NO viaja de aquí).
85
85
  * @param {number} [args.timeoutMs=180000]
86
86
  */
87
- export async function enroll ({ qr, label = 'remote-agent', dir = dataDir(), ns = null, onChallenge, timeoutMs = 180000 } = {}) {
87
+ export async function enroll ({ qr, label = 'remote-agent', dir = dataDir(), ns = null, onChallenge, timeoutMs = 180000, keep = null } = {}) {
88
88
  installNodeGlobals(dir)
89
89
  const { enrollWithVault } = await import('@dotrino/vault/service')
90
90
  const res = await enrollWithVault({
@@ -92,13 +92,52 @@ export async function enroll ({ qr, label = 'remote-agent', dir = dataDir(), ns
92
92
  label,
93
93
  expectedScope: ns ? 'vault:secrets:' + ns : null,
94
94
  onCode: onChallenge,
95
- approveTimeoutMs: timeoutMs
95
+ approveTimeoutMs: timeoutMs,
96
+ ...(keep ? { device: keep.device, enc: keep.enc || null } : {})
96
97
  })
98
+ // Conservar la llave era lo pedido: una bóveda vieja (`@dotrino/vault` < 0.115.0) ignora
99
+ // `device` y crea otra, y entonces la dirección que sale de la llave cambiaría sin avisar.
100
+ if (keep && res.device?.publickey !== keep.device.publickey) {
101
+ throw Object.assign(new Error('the vault library created a new key instead of keeping this one: install @dotrino/vault >= 0.115.0'), { code: 'key-not-kept' })
102
+ }
97
103
  const link = { device: res.device, enc: res.enc, cert: res.cert, iss: res.iss, proxy: res.proxy, label, ...(ns ? { ns } : {}), at: Date.now() }
98
104
  saveLink(dir, link)
99
105
  return link
100
106
  }
101
107
 
108
+ /**
109
+ * UNA IDENTIDAD PROPIA, SIN BÓVEDA. El aparato cumple el rol cuando no hay pieza dedicada:
110
+ * crea sus llaves (firma y cifrado) y un acta de génesis autofirmada donde él es el único
111
+ * miembro. Es una cuenta de un solo aparato, igual que «este dispositivo es bóveda» en el
112
+ * navegador: `verifySignedFor` la acepta sin saber nada más, porque la raíz de toda cuenta
113
+ * es un acta autofirmada.
114
+ *
115
+ * El enlace queda `{ device, enc, label, self: true, sealerChain: [génesis], at }`, sin
116
+ * `cert` ni `iss`. Emparejarlo después con una bóveda (`enroll({ keep: link })`) mete ESTAS
117
+ * llaves en el acta de la cuenta: el aparato sigue siendo el mismo.
118
+ *
119
+ * @param {{ label?: string, dir?: string }} [args]
120
+ */
121
+ export async function selfLink ({ label = 'remote-agent', dir = dataDir() } = {}) {
122
+ installNodeGlobals(dir)
123
+ const d = await makeDeviceKey({ label })
124
+ const e = await makeDeviceEncKey()
125
+ const genesis = await sealActa({
126
+ acta: genesisActa({ pub: d.publickey, encPub: e.encPublickey, label }),
127
+ privateJwk: d.privateJwk
128
+ })
129
+ const link = {
130
+ device: { publickey: d.publickey, privateJwk: d.privateJwk },
131
+ enc: { publickey: e.encPublickey, privateJwk: e.encPrivateJwk },
132
+ label, self: true, sealerChain: [genesis], at: Date.now()
133
+ }
134
+ saveLink(dir, link)
135
+ return link
136
+ }
137
+
138
+ /** ¿Es una identidad propia (sin bóveda)? */
139
+ export const isSelfLink = (link) => link?.self === true
140
+
102
141
  /**
103
142
  * La IDENTIDAD de un agente a partir de su enlace: lo que un cliente del ecosistema
104
143
  * espera como `link.id` (`RemoteAgentClient`, `ContentClient`, `listAgentsByLabel`) —
@@ -111,6 +150,7 @@ export async function enroll ({ qr, label = 'remote-agent', dir = dataDir(), ns
111
150
  * @param {{ dir?: string }} [opts] dir para los globals de Node (localStorage del proxy-client).
112
151
  */
113
152
  export function identityFromLink (link, { dir = dataDir() } = {}) {
153
+ if (isSelfLink(link)) return selfIdentity(link, dir)
114
154
  if (!link?.device?.privateJwk || !link?.cert || !link?.iss) throw new Error('invalid link: device/cert/iss required')
115
155
  installNodeGlobals(dir)
116
156
  const device = link.device
@@ -157,6 +197,31 @@ export function identityFromLink (link, { dir = dataDir() } = {}) {
157
197
  }
158
198
  }
159
199
 
200
+ /**
201
+ * La identidad de un enlace propio: firma con su llave y prueba con su génesis. Lo que
202
+ * pregunta a una bóveda no existe aquí, y se dice (`no-vault`) en vez de inventarse.
203
+ */
204
+ function selfIdentity (link, dir) {
205
+ const chain = link.sealerChain
206
+ if (!link?.device?.privateJwk || !Array.isArray(chain) || chain.length !== 1) throw new Error('invalid self link: device and its genesis required')
207
+ installNodeGlobals(dir)
208
+ const device = link.device
209
+ const noVault = () => Promise.reject(Object.assign(new Error('this device has its own identity and is not paired with a vault'), { code: 'no-vault' }))
210
+ return {
211
+ me: { publickey: device.publickey },
212
+ async signData (data) {
213
+ const signed = await signWithDevice({ privateJwk: device.privateJwk, publickey: device.publickey, data })
214
+ return { ...signed, profileId: chain[0].profileId, chain }
215
+ },
216
+ getVaultCert: noVault,
217
+ async vaultStatus () {
218
+ return { paired: false, self: true, master: null, proxy: link.proxy || DEFAULT_PROXY, deviceId: await pubkeyId(device.publickey), seq: chain[0].seq }
219
+ },
220
+ listVaultDevices: noVault,
221
+ async profileActa () { return { acta: chain[0] } }
222
+ }
223
+ }
224
+
160
225
  const trustedActaOf = (link) => (link?.actaTrusted === true && link.acta ? link.acta : null)
161
226
 
162
227
  /** El acta que `listVaultDevices` puede dar por buena. Exportada para las pruebas. */
@@ -256,6 +321,8 @@ export async function renewLink (link, { dir = dataDir(), force = false } = {})
256
321
  * @returns {Promise<{ ok: boolean, seq?: number, reason?: string }>}
257
322
  */
258
323
  export async function refreshChain (link, { dir = dataDir() } = {}) {
324
+ // Una identidad propia es su propia cadena: no hay a quién preguntar ni nada que caduque.
325
+ if (isSelfLink(link)) return { ok: true, seq: link.sealerChain?.[0]?.seq ?? 1, self: true }
259
326
  if (!link?.device?.privateJwk || !link?.cert || !link?.iss) return { ok: false, reason: 'invalid link' }
260
327
  installNodeGlobals(dir)
261
328
  try {
@@ -283,4 +350,4 @@ export function clientLink (link, opts) {
283
350
  return { id: identityFromLink(link, opts), cert: link.cert, iss: link.iss, proxy: link.proxy || DEFAULT_PROXY }
284
351
  }
285
352
 
286
- export default { dataDir, loadLink, saveLink, parseQr, enroll, identityFromLink, clientLink, renewLink, renewalReason, storeRenewedCert, refreshChain }
353
+ export default { dataDir, loadLink, saveLink, parseQr, enroll, selfLink, isSelfLink, identityFromLink, clientLink, renewLink, renewalReason, storeRenewedCert, refreshChain }