@dotrino/terminal-agent 0.2.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 ADDED
@@ -0,0 +1,46 @@
1
+ # @dotrino/terminal-agent
2
+
3
+ Agente de **Dotrino Terminal**: abre una shell real (PTY) **solo** para
4
+ dispositivos enlazados al mismo vault. Contraparte de la PWA
5
+ `terminal.dotrino.com`.
6
+
7
+ Puede correr en **cualquier máquina** (un servidor, un contenedor, otra PC): se
8
+ enrola con el vault como un dispositivo más, así que **no necesita la maestra** —
9
+ solo su propia sub-clave `D` + `cert` y la pública maestra pineada.
10
+
11
+ - **Autorización = el vault**: cliente y agente son peers certificados por el mismo
12
+ vault; cada uno verifica que el `cert` del otro encadena a la maestra
13
+ (`@dotrino/identity` `verifyChain`). Revocable desde el vault (el agente refresca
14
+ la lista con `vault.devices` por el proxy).
15
+ - **Transporte = el proxy** (`@dotrino/proxy-client`): el agente se identifica bajo
16
+ SU pubkey; el cliente lo direcciona por ella.
17
+ - **Cifrado E2E**: ECDH → AES-GCM por sesión; el proxy solo ve texto cifrado.
18
+
19
+ ## Requisitos
20
+
21
+ - Que el vault esté accesible **al enrolar** (para el pairing). Después, las
22
+ sesiones no necesitan el vault online (la confianza está pineada a la pública
23
+ maestra; el TTL del cert acota el riesgo si no puede refrescar revocaciones).
24
+ - Toolchain de C++ para compilar `node-pty` (`build-essential`, `python3`).
25
+
26
+ ## Uso
27
+
28
+ ```sh
29
+ npm install
30
+ dotrino-terminal-agent enroll # enlazar esta máquina (una vez)
31
+ dotrino-terminal-agent # correr; imprime su "dirección de máquina"
32
+ # [--proxy wss://…] [--shell /bin/zsh] [--dir /ruta]
33
+ ```
34
+
35
+ Como librería:
36
+
37
+ ```js
38
+ import { startAgent } from '@dotrino/terminal-agent'
39
+ const agent = await startAgent({ /* dir, proxyUrl, shell, quiet */ })
40
+ // agent.machine → pubkey de esta máquina (la "dirección")
41
+ // agent.machineId → id corto legible
42
+ // agent.close()
43
+ ```
44
+
45
+ Datos en `~/.local/share/dotrino-terminal-agent` (override `DOTRINO_TERMINAL_DIR`).
46
+ MIT.
package/bin/cli.js ADDED
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dotrino-terminal-agent — agente de Dotrino Terminal.
4
+ *
5
+ * dotrino-terminal-agent enroll # enlaza ESTA máquina con tu vault (una vez)
6
+ * dotrino-terminal-agent # corre el agente (abre shells para tus dispositivos)
7
+ *
8
+ * El agente es un dispositivo enrolado del vault: puede vivir en cualquier
9
+ * máquina. Imprime la "dirección de máquina" (su pubkey) que pegas en el cliente
10
+ * terminal.dotrino.com para conectarte a ESTA máquina.
11
+ */
12
+ import readline from 'node:readline'
13
+ import { startAgent } from '../index.js'
14
+ import { enroll, parseQr, loadLink, dataDir } from '../link.js'
15
+
16
+ const args = process.argv.slice(2)
17
+ const cmd = args[0] && !args[0].startsWith('-') ? args[0] : 'run'
18
+ const opt = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined }
19
+
20
+ function ask (q) {
21
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
22
+ return new Promise((res) => rl.question(q, (a) => { rl.close(); res(a) }))
23
+ }
24
+
25
+ if (args.includes('-h') || args.includes('--help')) {
26
+ console.log(`uso:
27
+ dotrino-terminal-agent enroll [--label <nombre>] enlaza esta máquina con el vault
28
+ dotrino-terminal-agent [--proxy <wss://…>] [--shell <bin>] [--dir <ruta>] corre el agente
29
+
30
+ datos en ${dataDir()} (override DOTRINO_TERMINAL_DIR)`)
31
+ process.exit(0)
32
+ }
33
+
34
+ try {
35
+ if (cmd === 'enroll') {
36
+ console.log('Enlazar esta máquina con tu vault.')
37
+ console.log('En la máquina del vault: `dotrino-vault pair` y copia el QR/JSON.\n')
38
+ const text = await ask('Pega el QR/JSON del vault y Enter:\n> ')
39
+ const qr = parseQr(text)
40
+ console.log('\nConectando al vault…')
41
+ const link = await enroll({
42
+ qr,
43
+ dir: opt('--dir'),
44
+ label: opt('--label') || 'terminal-agent',
45
+ onChallenge: ({ deviceId, sas }) => {
46
+ console.log('\n Compara que este código coincida y apruébalo EN EL VAULT:')
47
+ console.log(` código: ${sas}`)
48
+ console.log(` máquina ${deviceId}`)
49
+ console.log(` en el PC del vault: dotrino-vault approve ${sas}\n`)
50
+ console.log(' Esperando aprobación…')
51
+ }
52
+ })
53
+ console.log('\n ✓ Máquina enlazada. Dirección de máquina (aparecerá sola en la app; también puedes pegarla):\n')
54
+ console.log(' ', link.device.publickey, '\n')
55
+ console.log(' Ahora ejecuta: dotrino-terminal-agent\n')
56
+ process.exit(0)
57
+ }
58
+
59
+ if (!loadLink(opt('--dir'))) {
60
+ console.error('esta máquina no está enlazada. Ejecuta primero: dotrino-terminal-agent enroll')
61
+ process.exit(1)
62
+ }
63
+ const agent = await startAgent({
64
+ dir: opt('--dir'), proxyUrl: opt('--proxy'), shell: opt('--shell')
65
+ })
66
+ console.log('\n Dotrino Terminal — agente activo')
67
+ console.log(' máquina:', agent.machineId)
68
+ console.log(' dirección (pegar en la app):')
69
+ console.log(' ', agent.machine, '\n')
70
+ const bye = () => { agent.close(); process.exit(0) }
71
+ process.on('SIGINT', bye); process.on('SIGTERM', bye)
72
+ } catch (e) {
73
+ console.error('error:', e.message)
74
+ process.exit(1)
75
+ }
package/e2e.js ADDED
@@ -0,0 +1,75 @@
1
+ // COPIA de ../shared/e2e.js (fuente única en shared/). No editar aquí: tras cambiar
2
+ // shared/e2e.js, volver a copiarlo (el paquete npm no incluye ../shared).
3
+ /**
4
+ * e2e.js — canal cifrado punto a punto entre el dispositivo enlazado y el agente
5
+ * de la máquina del vault. Isomórfico: usa WebCrypto (`globalThis.crypto.subtle`),
6
+ * disponible tanto en el navegador (PWA) como en Node ≥ 18.
7
+ *
8
+ * NO reimplementa la identidad ni la firma del ecosistema: la AUTORIZACIÓN la da
9
+ * el vault (cert de dispositivo verificado con `@dotrino/identity/capabilities`
10
+ * → cadena hasta la maestra). Este módulo solo levanta un secreto de sesión
11
+ * efímero (ECDH P-256 → HKDF → AES-256-GCM) para que el relay del túnel
12
+ * (`r.dotrino.com`) vea únicamente texto cifrado. La identidad de las dos puntas
13
+ * ya la garantizan las firmas del vault que envuelven las claves efímeras.
14
+ *
15
+ * El mismo archivo se copia a `agent/` y a `web/src/` (fuente única en `shared/`).
16
+ */
17
+
18
+ const subtle = () => globalThis.crypto.subtle
19
+
20
+ const b64 = {
21
+ enc (buf) {
22
+ const b = new Uint8Array(buf)
23
+ let s = ''
24
+ for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i])
25
+ return btoa(s)
26
+ },
27
+ dec (str) {
28
+ const bin = atob(str)
29
+ const out = new Uint8Array(bin.length)
30
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
31
+ return out
32
+ }
33
+ }
34
+
35
+ /** Genera un par ECDH P-256 efímero. Devuelve la pub en raw (base64) + privada. */
36
+ export async function makeEphemeral () {
37
+ const kp = await subtle().generateKey({ name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits'])
38
+ const raw = await subtle().exportKey('raw', kp.publicKey)
39
+ return { privateKey: kp.privateKey, pub: b64.enc(raw) }
40
+ }
41
+
42
+ /**
43
+ * Deriva la clave AES-256-GCM de la sesión a partir de la privada propia y la
44
+ * pub efímera (base64 raw) del otro extremo. `salt` liga la clave a la sesión.
45
+ */
46
+ export async function deriveKey (privateKey, otherPubB64, salt) {
47
+ const otherPub = await subtle().importKey(
48
+ 'raw', b64.dec(otherPubB64), { name: 'ECDH', namedCurve: 'P-256' }, false, []
49
+ )
50
+ const bits = await subtle().deriveBits({ name: 'ECDH', public: otherPub }, privateKey, 256)
51
+ const hkdfKey = await subtle().importKey('raw', bits, 'HKDF', false, ['deriveKey'])
52
+ return subtle().deriveKey(
53
+ { name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode(salt), info: new TextEncoder().encode('dotrino-terminal-e2e') },
54
+ hkdfKey,
55
+ { name: 'AES-GCM', length: 256 },
56
+ false,
57
+ ['encrypt', 'decrypt']
58
+ )
59
+ }
60
+
61
+ /** Cifra un objeto JSON → sobre { iv, ct } (ambos base64). */
62
+ export async function seal (key, obj) {
63
+ const iv = globalThis.crypto.getRandomValues(new Uint8Array(12))
64
+ const pt = new TextEncoder().encode(JSON.stringify(obj))
65
+ const ct = await subtle().encrypt({ name: 'AES-GCM', iv }, key, pt)
66
+ return { iv: b64.enc(iv), ct: b64.enc(ct) }
67
+ }
68
+
69
+ /** Descifra un sobre { iv, ct } → objeto JSON. Lanza si el tag GCM no valida. */
70
+ export async function open (key, env) {
71
+ const pt = await subtle().decrypt({ name: 'AES-GCM', iv: b64.dec(env.iv) }, key, b64.dec(env.ct))
72
+ return JSON.parse(new TextDecoder().decode(pt))
73
+ }
74
+
75
+ export { b64 }
package/index.js ADDED
@@ -0,0 +1,170 @@
1
+ /**
2
+ * @dotrino/terminal-agent — abre una shell real (PTY) SOLO para dispositivos
3
+ * enlazados al mismo vault. Puede correr en CUALQUIER máquina: se enrola con el
4
+ * vault como un dispositivo más (ver link.js), así que NO necesita la maestra —
5
+ * solo su propia sub-clave `D` + `cert` y la pública maestra pineada (`iss`).
6
+ *
7
+ * Autorización = el vault. Cada `terminal.hs` llega firmado por la `D` del cliente
8
+ * con su `cert`; el agente verifica la cadena `D_cliente ← maestra` (misma maestra
9
+ * que la suya) con `verifyChain`. Ambas puntas son peers certificados por el mismo
10
+ * vault; ninguna tiene la clave maestra. El ack lo firma el agente con SU `D` y
11
+ * adjunta su `cert`, para que el cliente compruebe que habla con una máquina que
12
+ * el vault certificó (anti-MITM del relay).
13
+ *
14
+ * Transporte = el proxy (`@dotrino/proxy-client`): el agente se identifica bajo
15
+ * SU pubkey y el cliente lo direcciona por ella. Revocación: refresca la lista del
16
+ * vault (`vault.devices`) por el proxy; si el vault está offline, usa la última
17
+ * cacheada + el TTL del cert acota el riesgo. I/O cifrado E2E (../shared/e2e.js).
18
+ */
19
+ import os from 'node:os'
20
+ import { createRequire } from 'node:module'
21
+ import { verifyChain, signWithDevice, pubkeyId } from '@dotrino/identity/capabilities'
22
+ import { installNodeGlobals } from './node-globals.js'
23
+ import { makeEphemeral, deriveKey, seal, open } from './e2e.js'
24
+ import { loadLink, dataDir } from './link.js'
25
+
26
+ const require = createRequire(import.meta.url)
27
+
28
+ const T = {
29
+ HS: 'terminal.hs', ACK: 'terminal.hs.ack', CMD: 'terminal.cmd', OUT: 'terminal.out', ERROR: 'terminal.error'
30
+ }
31
+ const VMSG = { DEVICES: 'vault.devices', DEVICES_RESULT: 'vault.devices.result' }
32
+ const SIGN_SCOPE = 'vault:sign'
33
+ const SESSION_TTL_MS = 30 * 60 * 1000
34
+ const REVOKE_REFRESH_MS = 5 * 60 * 1000
35
+
36
+ export async function startAgent (opts = {}) {
37
+ const dir = opts.dir || dataDir()
38
+ const link = opts.link || loadLink(dir)
39
+ if (!link?.device?.privateJwk || !link?.cert || !link?.iss) {
40
+ throw new Error('esta máquina no está enlazada. Ejecuta primero: `dotrino-terminal-agent enroll`.')
41
+ }
42
+ const master = link.iss
43
+ const myPub = link.device.publickey
44
+ const myId = (await pubkeyId(myPub)).slice(0, 8).toUpperCase().replace(/(.{4})(.{4})/, '$1-$2')
45
+
46
+ installNodeGlobals(dir)
47
+
48
+ let pty
49
+ try { pty = require('node-pty') } catch {
50
+ throw new Error('falta node-pty. En agent/: `npm install`.')
51
+ }
52
+
53
+ const { getWebSocketProxyClient } = await import('@dotrino/proxy-client')
54
+ const proxyUrl = opts.proxyUrl || process.env.PROXY_URL || link.proxy || 'wss://proxy.dotrino.com'
55
+ const client = getWebSocketProxyClient({
56
+ url: proxyUrl, enableWebRTC: false, autoReconnect: true,
57
+ maxReconnectAttempts: 100000, reconnectDelay: 4000
58
+ })
59
+ await client.connect()
60
+
61
+ // Identificarse bajo la pubkey de ESTA máquina (firmado con su D).
62
+ const identify = async () => {
63
+ if (!client.token) return
64
+ const data = { op: 'identify', publickey: myPub, token: client.token, ts: Date.now() }
65
+ const { signature } = await signWithDevice({ privateJwk: link.device.privateJwk, data })
66
+ await client.identify({ data, signature })
67
+ }
68
+ await identify()
69
+ client.on('token', () => { identify().catch(() => {}) })
70
+
71
+ const send = (to, obj) => { try { client.send(to, obj) } catch (e) { if (!opts.quiet) console.error('[terminal] send:', e.message) } }
72
+
73
+ // --- Revocación: refrescar la lista del vault por el proxy (best-effort) ---
74
+ let revokedSet = new Set()
75
+ async function refreshRevocations () {
76
+ try {
77
+ const data = { op: 'devices', publickey: myPub, ts: Date.now() }
78
+ const { signature } = await signWithDevice({ privateJwk: link.device.privateJwk, data })
79
+ const res = await new Promise((resolve, reject) => {
80
+ const off = client.on('message', (_f, p) => {
81
+ if (p?.type === VMSG.DEVICES_RESULT) { off(); resolve(p) }
82
+ else if (p?.type === 'vault.error') { off(); reject(new Error(p.error)) }
83
+ })
84
+ setTimeout(() => { off(); reject(new Error('timeout')) }, 15000)
85
+ client.sendByPubkey(master, { type: VMSG.DEVICES, data, signature, cert: link.cert })
86
+ })
87
+ revokedSet = new Set((res.revoked || []).map((r) => r.nonce || r))
88
+ } catch (e) {
89
+ if (!opts.quiet) console.error('[terminal] no pude refrescar revocaciones (uso la cache):', e.message)
90
+ }
91
+ }
92
+ refreshRevocations()
93
+ const revTimer = setInterval(refreshRevocations, REVOKE_REFRESH_MS); revTimer.unref?.()
94
+
95
+ // sid -> { key, term, from, exp }
96
+ const sessions = new Map()
97
+ const sweeper = setInterval(() => {
98
+ const now = Date.now()
99
+ for (const [sid, s] of sessions) if (now > s.exp) { try { s.term?.kill() } catch {}; sessions.delete(sid) }
100
+ }, 60 * 1000); sweeper.unref?.()
101
+
102
+ async function pushOut (s, data) {
103
+ if (!s.from) return
104
+ const env = await seal(s.key, { type: 'out', data }).catch(() => null)
105
+ if (env) send(s.from, { type: T.OUT, sid: s.sid, env })
106
+ }
107
+
108
+ async function handleHandshake (from, p) {
109
+ const { data, signature, cert } = p
110
+ if (!data || !signature || !cert) return send(from, { type: T.ERROR, error: 'handshake incompleto' })
111
+ const chk = await verifyChain({ data, signature, cert, expectedScope: SIGN_SCOPE, trustedIssuer: master, revoked: revokedSet })
112
+ if (!chk.ok) return send(from, { type: T.ERROR, error: 'no autorizado: ' + chk.reason })
113
+ if (data.op !== 'terminal.hs' || typeof data.eph !== 'string') return send(from, { type: T.ERROR, error: 'handshake inválido' })
114
+
115
+ const eph = await makeEphemeral()
116
+ const sid = [...crypto.getRandomValues(new Uint8Array(16))].map((x) => x.toString(16).padStart(2, '0')).join('')
117
+ const key = await deriveKey(eph.privateKey, data.eph, sid)
118
+ // Ack firmado con la D de ESTA máquina + su cert: el cliente verifica la
119
+ // cadena a la maestra y que la pub efímera viene de una máquina certificada.
120
+ // `publickey` va DENTRO del dato firmado (verifyChain lo exige: firma contra
121
+ // data.publickey y cert.sub === data.publickey).
122
+ const ack = { op: 'terminal.hs.ack', sid, seph: eph.pub, ceph: data.eph, machine: myPub, publickey: myPub, ts: Date.now() }
123
+ const { signature: ackSig } = await signWithDevice({ privateJwk: link.device.privateJwk, data: ack })
124
+
125
+ sessions.set(sid, { sid, key, term: null, from, exp: Date.now() + SESSION_TTL_MS })
126
+ send(from, { type: T.ACK, sid, ack, signature: ackSig, cert: link.cert })
127
+ if (!opts.quiet) console.log(`[terminal] sesión ${sid.slice(0, 8)} autorizada (device ${chk.device?.slice?.(0, 8) || '?'})`)
128
+ }
129
+
130
+ async function handleCmd (from, p) {
131
+ const s = sessions.get(p.sid)
132
+ if (!s) return send(from, { type: T.ERROR, error: 'sesión desconocida o expirada' })
133
+ s.exp = Date.now() + SESSION_TTL_MS
134
+ s.from = from
135
+ let msg
136
+ try { msg = await open(s.key, p.env) } catch { return send(from, { type: T.ERROR, error: 'sobre inválido' }) }
137
+
138
+ if (msg.type === 'open') {
139
+ if (s.term) return
140
+ const shell = opts.shell || process.env.SHELL || (process.platform === 'win32' ? 'powershell.exe' : 'bash')
141
+ s.term = pty.spawn(shell, [], {
142
+ name: 'xterm-256color', cols: msg.cols || 80, rows: msg.rows || 24,
143
+ cwd: os.homedir(), env: { ...process.env, TERM: 'xterm-256color' }
144
+ })
145
+ s.term.onData((d) => pushOut(s, d))
146
+ s.term.onExit(({ exitCode }) => { pushOut(s, `\r\n[proceso terminado (${exitCode})]\r\n`); s.term = null })
147
+ return
148
+ }
149
+ if (msg.type === 'input') return void s.term?.write(msg.data)
150
+ if (msg.type === 'resize') { try { s.term?.resize(msg.cols, msg.rows) } catch {}; return }
151
+ if (msg.type === 'close') { try { s.term?.kill() } catch {}; sessions.delete(p.sid); return }
152
+ }
153
+
154
+ client.on('message', (from, payload) => {
155
+ if (!payload || typeof payload !== 'object') return
156
+ if (payload.type === T.HS) handleHandshake(from, payload).catch((e) => send(from, { type: T.ERROR, error: e.message }))
157
+ else if (payload.type === T.CMD) handleCmd(from, payload).catch((e) => send(from, { type: T.ERROR, error: e.message }))
158
+ })
159
+
160
+ if (!opts.quiet) {
161
+ console.log(`[terminal] agente activo · máquina ${myId} · vault ${(await pubkeyId(master)).slice(0, 16)} · proxy ${proxyUrl}`)
162
+ }
163
+
164
+ return {
165
+ machine: myPub, machineId: myId, master,
166
+ close () { clearInterval(revTimer); clearInterval(sweeper); for (const s of sessions.values()) { try { s.term?.kill() } catch {} } try { client.close() } catch {} }
167
+ }
168
+ }
169
+
170
+ export default { startAgent }
package/link.js ADDED
@@ -0,0 +1,93 @@
1
+ /**
2
+ * link.js — enrola ESTA máquina como un dispositivo del vault (mismo flujo
3
+ * endurecido que usa el navegador / `dotrino-vault/src/client.js#enroll`). Es lo
4
+ * que vuelve al agente INDEPENDIENTE de la máquina del vault: guarda su propia
5
+ * sub-clave `D` + `cert` (cadena `D ← maestra`); la maestra NUNCA vive aquí, solo
6
+ * su pública pineada (`iss`).
7
+ *
8
+ * Persistencia en un directorio propio (por defecto
9
+ * `~/.local/share/dotrino-terminal-agent`, override `DOTRINO_TERMINAL_DIR`): NO
10
+ * comparte carpeta con el vault, así el agente puede correr en otro host.
11
+ */
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+ import os from 'node:os'
15
+ import {
16
+ makeDeviceKey, signWithDevice, verifyDelegation, deriveSAS, pubkeyId
17
+ } from '@dotrino/identity/capabilities'
18
+ import { installNodeGlobals } from './node-globals.js'
19
+
20
+ const MSG = {
21
+ ENROLL: 'vault.enroll',
22
+ ENROLL_CHALLENGE: 'vault.enroll.challenge',
23
+ ENROLLED: 'vault.enrolled',
24
+ ERROR: 'vault.error'
25
+ }
26
+
27
+ export function dataDir () {
28
+ if (process.env.DOTRINO_TERMINAL_DIR) return process.env.DOTRINO_TERMINAL_DIR
29
+ const base = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share')
30
+ return path.join(base, 'dotrino-terminal-agent')
31
+ }
32
+
33
+ const linkPath = (dir) => path.join(dir, 'link.json')
34
+
35
+ export function loadLink (dir = dataDir()) {
36
+ try { return JSON.parse(fs.readFileSync(linkPath(dir), 'utf8')) } catch { return null }
37
+ }
38
+
39
+ function saveLink (dir, link) {
40
+ fs.mkdirSync(dir, { recursive: true })
41
+ fs.writeFileSync(linkPath(dir), JSON.stringify(link, null, 2), { mode: 0o600 })
42
+ }
43
+
44
+ export function parseQr (text) {
45
+ const qr = JSON.parse(String(text).trim())
46
+ if (!qr?.iss || !qr?.proxy || !qr?.token || !qr?.sn) throw new Error('QR inválido (v2): faltan iss/proxy/token/sn')
47
+ return qr
48
+ }
49
+
50
+ async function freshClient (proxyUrl, dir) {
51
+ installNodeGlobals(dir)
52
+ const { WebSocketProxyClient } = await import('@dotrino/proxy-client')
53
+ const client = new WebSocketProxyClient({ url: proxyUrl, enableWebRTC: false, autoReconnect: false })
54
+ await client.connect()
55
+ return client
56
+ }
57
+
58
+ /**
59
+ * Enrola esta máquina contra el vault del QR. Devuelve y persiste
60
+ * `{ device, cert, iss, proxy, label }`.
61
+ * @param {(c:{deviceId:string,sas:string})=>void} onChallenge mostrar el SAS a comparar/aprobar en el vault
62
+ */
63
+ export async function enroll ({ qr, label = 'terminal-agent', dir = dataDir(), onChallenge, timeoutMs = 180000 } = {}) {
64
+ const client = await freshClient(qr.proxy, dir)
65
+ try {
66
+ const device = await makeDeviceKey({ label })
67
+ const deviceId = (await pubkeyId(device.publickey)).slice(0, 8).toUpperCase().replace(/(.{4})(.{4})/, '$1-$2')
68
+ const sas = await deriveSAS(qr.iss, device.publickey, qr.sn)
69
+ const data = { op: 'enroll', dpub: device.publickey, token: qr.token, sn: qr.sn, label, ts: Date.now() }
70
+ const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
71
+
72
+ const done = new Promise((resolve, reject) => {
73
+ const off = client.on('message', (_from, p) => {
74
+ if (!p || typeof p !== 'object') return
75
+ if (p.type === MSG.ENROLL_CHALLENGE) onChallenge?.({ deviceId, sas })
76
+ else if (p.type === MSG.ENROLLED) { cleanup(); resolve(p) }
77
+ else if (p.type === MSG.ERROR) { cleanup(); reject(new Error(p.error)) }
78
+ })
79
+ const t = setTimeout(() => { cleanup(); reject(new Error('timeout esperando la aprobación en el vault')) }, timeoutMs)
80
+ const cleanup = () => { off(); clearTimeout(t) }
81
+ })
82
+ client.sendByPubkey(qr.iss, { type: MSG.ENROLL, data, signature })
83
+ const res = await done
84
+
85
+ const v = await verifyDelegation({ cert: res.cert, expectedSub: device.publickey })
86
+ if (!v.ok) throw new Error('cert inválido: ' + v.reason)
87
+ if (res.cert.iss !== qr.iss) throw new Error('cert firmado por otra maestra (posible proxy malicioso)')
88
+
89
+ const link = { device, cert: res.cert, iss: qr.iss, proxy: qr.proxy, label, at: Date.now() }
90
+ saveLink(dir, link)
91
+ return link
92
+ } finally { client.close() }
93
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Instala los globals del navegador que los paquetes del ecosistema esperan
3
+ * cuando corren headless en Node: `WebSocket` (paquete `ws`) y un `localStorage`
4
+ * respaldado en archivo (lo usa `@dotrino/proxy-client` para su keypair de
5
+ * transporte estable). Mismo patrón que `dotrino-bots/src/core/node-globals.js`
6
+ * — NO se reimplementa nada, solo se inyecta el entorno.
7
+ */
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+ import WebSocket from 'ws'
11
+
12
+ /** localStorage síncrono respaldado por un archivo JSON (solo lo que usan los paquetes). */
13
+ export function fileLocalStorage (filePath) {
14
+ let data = {}
15
+ try { if (fs.existsSync(filePath)) data = JSON.parse(fs.readFileSync(filePath, 'utf8')) || {} } catch (_) {}
16
+ const flush = () => {
17
+ fs.mkdirSync(path.dirname(filePath), { recursive: true })
18
+ fs.writeFileSync(filePath, JSON.stringify(data), { mode: 0o600 })
19
+ }
20
+ return {
21
+ getItem: (k) => (k in data ? data[k] : null),
22
+ setItem: (k, v) => { data[k] = String(v); flush() },
23
+ removeItem: (k) => { delete data[k]; flush() },
24
+ clear: () => { data = {}; flush() },
25
+ key: (i) => Object.keys(data)[i] ?? null,
26
+ get length () { return Object.keys(data).length }
27
+ }
28
+ }
29
+
30
+ let _installed = false
31
+ export function installNodeGlobals (dir) {
32
+ if (_installed) return
33
+ if (typeof globalThis.WebSocket === 'undefined') globalThis.WebSocket = WebSocket
34
+ // Node ≥22 expone un `localStorage` no funcional sin flag → forzamos el shim.
35
+ globalThis.localStorage = fileLocalStorage(path.join(dir, 'transport.json'))
36
+ _installed = true
37
+ }
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@dotrino/terminal-agent",
3
+ "version": "0.2.0",
4
+ "description": "Agente de Dotrino Terminal: abre una shell (PTY) en la máquina del vault solo para el dispositivo enlazado, vía @dotrino/tunnel y cifrado E2E.",
5
+ "type": "module",
6
+ "bin": {
7
+ "dotrino-terminal-agent": "bin/cli.js"
8
+ },
9
+ "exports": {
10
+ ".": "./index.js"
11
+ },
12
+ "scripts": {
13
+ "start": "node bin/cli.js"
14
+ },
15
+ "dependencies": {
16
+ "@dotrino/identity": "0.17.0",
17
+ "@dotrino/proxy-client": "0.6.4",
18
+ "node-pty": "1.1.0"
19
+ },
20
+ "license": "MIT"
21
+ }