@dotrino/remote-agent 0.9.2 → 0.11.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
@@ -34,7 +34,7 @@ Provee lo común — y **solo** eso:
34
34
  | `@dotrino/remote-agent/agent` | Node | `startRemoteAgent(opts)` |
35
35
  | `@dotrino/remote-agent/client` | navegador | `RemoteAgentClient` |
36
36
  | `@dotrino/remote-agent/link` | Node | `enroll`, `loadLink`, `saveLink`, `dataDir`, `parseQr`, `identityFromLink`, `clientLink`, `renewLink` |
37
- | `@dotrino/remote-agent/discover` | navegador | `listAgentsByLabel` |
37
+ | `@dotrino/remote-agent/discover` | navegador | `listAgentsByLabel`, `probeAgents` |
38
38
 
39
39
  ## Uso
40
40
 
@@ -123,6 +123,20 @@ chat.send({ type: 'msg', text: 'arreglá el bug en auth.js' })
123
123
  const online = await chat.ping() // liveness sin abrir sesión
124
124
  ```
125
125
 
126
+ **Encontrar los agentes de UN tipo: pregúntaselo a ellos, no al nombre del acta.** El label
127
+ del acta lo pone el dueño al emparejar («TerminalLocal»), así que filtrar por él no encuentra
128
+ nada. El pong de cada agente dice qué es (el `label` con que arrancó `startRemoteAgent`):
129
+
130
+ ```js
131
+ import { listAgentsByLabel, probeAgents } from '@dotrino/remote-agent/discover'
132
+ const miembros = await listAgentsByLabel(id) // todos, sin filtrar
133
+ const vivos = await probeAgents(proxyClient, miembros.map((m) => m.sub))
134
+ const terminales = miembros.filter((m) => vivos.get(m.sub)?.kind === 'terminal-agent')
135
+ ```
136
+
137
+ Un agente apagado no contesta y no sale: sin preguntarle no se sabe qué es. El pong con
138
+ `kind` existe desde 0.11.0; uno más viejo contesta con `kind: null`.
139
+
126
140
  ### `link` (la PWA lo obtiene del vault)
127
141
 
128
142
  Ver `dotrino-terminal/src/vault.js` (`getLink` / `getSelfLink`) como referencia: es
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/remote-agent",
3
- "version": "0.9.2",
3
+ "version": "0.11.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",
@@ -45,13 +45,13 @@
45
45
  "p2p"
46
46
  ],
47
47
  "peerDependencies": {
48
- "@dotrino/identity": ">=0.73.1",
48
+ "@dotrino/identity": ">=0.92.0",
49
49
  "@dotrino/proxy-client": ">=0.18.2",
50
- "@dotrino/vault": ">=0.30.0"
50
+ "@dotrino/vault": ">=0.64.0"
51
51
  },
52
52
  "devDependencies": {
53
- "@dotrino/identity": "0.73.0",
53
+ "@dotrino/identity": "0.92.0",
54
54
  "@dotrino/proxy-client": "0.18.2",
55
- "@dotrino/vault": "0.35.0"
55
+ "@dotrino/vault": "0.64.0"
56
56
  }
57
57
  }
package/src/agent.js CHANGED
@@ -21,8 +21,8 @@
21
21
  */
22
22
  import fs from 'node:fs'
23
23
  import path from 'node:path'
24
- import { verifyChain, signWithDevice, verifyDeviceSig, verifyDelegation, pubkeyId } from '@dotrino/identity/capabilities'
25
- import { sealersOf, memberCan } from '@dotrino/identity/acta'
24
+ import { verifyChain, signWithDevice, verifyDeviceSig, pubkeyId } from '@dotrino/identity/capabilities'
25
+ import { sealersOf, memberCan, checkVaultReply } from '@dotrino/identity/acta'
26
26
  import { installNodeGlobals } from '../node-globals.js'
27
27
  import { makeEphemeral, deriveKey, seal, open } from '../e2e.js'
28
28
  import { HS, ACK, DATA, PING, PONG, ERROR, VMSG, SIGN_SCOPE, SESSION_TTL_MS, REVOKE_REFRESH_MS } from '../protocol.js'
@@ -66,7 +66,8 @@ class AgentSession {
66
66
  * Arranca el agente. Devuelve `{ machine, machineId, master, close }`.
67
67
  *
68
68
  * @param {object} opts
69
- * @param {string} [opts.label] label del dispositivo (para logging; el real vive en link.json).
69
+ * @param {string} [opts.label] qué agente es (`terminal-agent`, `ia-agent`…): lo contesta el pong
70
+ * para que las apps lo encuentren (`probeAgents`). El nombre del acta es del dueño.
70
71
  * @param {string} [opts.proxyUrl] default wss://proxy.dotrino.com.
71
72
  * @param {string} [opts.dir] dir del enlace (default dataDir()).
72
73
  * @param {object} [opts.link] enlace ya cargado (override de dir).
@@ -191,14 +192,10 @@ export async function startRemoteAgent (opts = {}) {
191
192
  const res = await vaultRpc(VMSG.RENEW, VMSG.RENEWED, { op: 'renew', publickey: myPub, ts: Date.now() })
192
193
  const cert = res?.cert
193
194
  const acta = res?.acta
194
- if (!cert || cert.sub !== myPub) throw new Error('the vault returned a cert that is not for this machine')
195
- if (!acta) throw new Error('the vault did not send its record: cannot check who signed this cert')
196
- if (acta.profileId !== master) throw new Error('the record is from a profile other than the pinned one')
197
- const v = await verifyDelegation({
198
- cert, expectedSub: myPub, expectedScope: SIGN_SCOPE,
199
- actaSeq: acta.seq, sealers: sealersOf(acta)
200
- })
201
- if (!v.ok) throw new Error(v.reason)
195
+ // La regla del pilar, contra la bóveda a la que se le pidió (`master`). Aquí se exigía
196
+ // `acta.profileId === master`, que con una segunda bóveda nunca es verdad.
197
+ const chk = await checkVaultReply({ acta, cert, vault: master, sub: myPub, scope: SIGN_SCOPE })
198
+ if (!chk.ok) throw new Error('invalid renewed cert: ' + chk.reason)
202
199
  link.cert = cert
203
200
  link.actaSeq = acta.seq
204
201
  saveLink(dir, link)
@@ -333,7 +330,9 @@ export async function startRemoteAgent (opts = {}) {
333
330
  else if (payload.type === DATA) handleData(from, payload)
334
331
  // Sonda de presencia (liveness): el cliente hace ping y respondemos pong con el
335
332
  // mismo nonce → así la app sabe que el agente está online (sin abrir sesión).
336
- else if (payload.type === PING) send(from, { type: PONG, n: payload.n })
333
+ // El pong dice además QUÉ agente es (`kind`, el label con que arrancó): el nombre que
334
+ // tiene en el acta lo pone el dueño al emparejar y no sirve para saber qué atiende.
335
+ else if (payload.type === PING) send(from, { type: PONG, n: payload.n, kind: opts.label || null })
337
336
  else if (payload.type === VMSG.REVOKED) handleRevoked(payload).catch(() => {})
338
337
  })
339
338
 
package/src/discover.js CHANGED
@@ -21,6 +21,8 @@
21
21
  * después son sus miembros.
22
22
  */
23
23
 
24
+ import { PING, PONG } from '../protocol.js'
25
+
24
26
  /**
25
27
  * @param {object} id instancia de Identity (del vault) ya conectada.
26
28
  * @param {string} [label] filtrar por servicio/label exacto (p. ej. `'content'`,
@@ -44,4 +46,37 @@ export async function listAgentsByLabel (id, label) {
44
46
  .map((m) => ({ sub: m.pub, label: m.label || m.cn || '', cn: m.cn || null }))
45
47
  }
46
48
 
47
- export default { listAgentsByLabel }
49
+ /**
50
+ * QUÉ AGENTE ES CADA UNO, preguntándoselo. Manda un `ra.ping` a cada pubkey por el
51
+ * transporte que se le pase y devuelve los que contestan, con el `kind` que declara el
52
+ * agente al arrancar (`startRemoteAgent({ label })`).
53
+ *
54
+ * Existe porque buscar por el label del ACTA no sirve: ese nombre lo pone el dueño al
55
+ * emparejar («TerminalLocal», «el PC de la oficina»), así que una app que buscaba
56
+ * `terminal-agent` no encontraba nada. Lo que un agente atiende lo sabe el agente.
57
+ *
58
+ * Un agente apagado no contesta y no sale: no se puede saber qué es sin preguntarle.
59
+ *
60
+ * @param {{ on:Function, sendByPubkey:Function }} client un WebSocketProxyClient conectado.
61
+ * @param {string[]} subs pubkeys a preguntar (p. ej. las de `listAgentsByLabel(id)`).
62
+ * @param {{ timeoutMs?: number }} [opts]
63
+ * @returns {Promise<Map<string, { kind: string|null }>>} sub → lo que contestó.
64
+ */
65
+ export function probeAgents (client, subs, { timeoutMs = 3000 } = {}) {
66
+ return new Promise((resolve) => {
67
+ const found = new Map()
68
+ if (!client || !subs?.length) return resolve(found)
69
+ const bySub = new Map()
70
+ const off = client.on('message', (_from, p) => {
71
+ if (p?.type === PONG && bySub.has(p.n)) found.set(bySub.get(p.n), { kind: p.kind ?? null })
72
+ })
73
+ for (const sub of subs) {
74
+ const n = [...crypto.getRandomValues(new Uint8Array(8))].map((x) => x.toString(16).padStart(2, '0')).join('')
75
+ bySub.set(n, sub)
76
+ try { client.sendByPubkey(sub, { type: PING, n }) } catch (_) {}
77
+ }
78
+ setTimeout(() => { try { off() } catch (_) {} resolve(found) }, timeoutMs)
79
+ })
80
+ }
81
+
82
+ export default { listAgentsByLabel, probeAgents }
package/src/link.js CHANGED
@@ -16,8 +16,7 @@
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, verifyDelegation } from '@dotrino/identity/capabilities'
20
- import { sealersOf } from '@dotrino/identity/acta'
19
+ import { signWithDevice, pubkeyId } from '@dotrino/identity/capabilities'
21
20
  import { requestDevices, requestRenew } from '@dotrino/identity/vault/remote.js'
22
21
  import { installNodeGlobals } from '../node-globals.js'
23
22
 
@@ -169,17 +168,11 @@ export async function renewLink (link, { dir = dataDir(), force = false } = {})
169
168
  if (!force && !legado && !atrasado) return { renewed: false, seq: link.cert.seq, reason: 'not due' }
170
169
  installNodeGlobals(dir)
171
170
  try {
172
- const res = await requestRenew({ master: link.iss, proxy: link.proxy || 'wss://proxy.dotrino.com', device: link.device, cert: link.cert })
173
- const cert = res?.cert
174
- const acta = res?.acta
175
- if (!cert || cert.sub !== link.device.publickey) throw new Error('the vault returned a cert that is not for this machine')
176
- // El acta viaja con el papel y hace falta para juzgarlo: quien lo firmó tiene que ser
177
- // SELLADORA de este perfil. Ya no se compara `cert.iss` con una llave fija — con varias
178
- // bóvedas el emisor puede ser otra del mismo perfil; lo que se fija es el PERFIL.
179
- if (!acta) throw new Error('the vault did not send its record: cannot check who signed this cert')
180
- if (acta.profileId !== link.iss) throw new Error('the record is from a profile other than the pinned one')
181
- const v = await verifyDelegation({ cert, expectedSub: link.device.publickey, actaSeq: acta.seq, sealers: sealersOf(acta) })
182
- if (!v.ok) throw new Error(v.reason)
171
+ // `requestRenew` ya JUZGA lo que devuelve (`checkVaultReply` del pilar: acta bien
172
+ // firmada, esta bóveda puede sellarla, el papel lo firmó ella y es para esta llave) y
173
+ // lanza si no cuadra. Aquí se comparaba `acta.profileId` con `link.iss`, que solo vale
174
+ // en una cuenta que nació en esa bóveda: con una segunda bóveda no renovaba nunca.
175
+ const { cert, acta } = await requestRenew({ master: link.iss, proxy: link.proxy || 'wss://proxy.dotrino.com', device: link.device, cert: link.cert })
183
176
  // SE GUARDA ANTES DE DAR NADA POR BUENO. Emitir un papel RETIRA el anterior, así que si
184
177
  // esto no se persiste la máquina se queda usando uno revocado y fuera para siempre. Le
185
178
  // pasó al registro de selladores en la migración, y por eso está dicho aquí.