@dotrino/terminal-agent 0.4.0 → 0.5.1
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 +1 -0
- package/bin/cli.js +17 -0
- package/consoles.js +128 -0
- package/index.js +65 -25
- package/package.json +6 -3
package/README.md
CHANGED
|
@@ -13,6 +13,7 @@ npx @dotrino/terminal-agent # enlaza (si falta) y corre
|
|
|
13
13
|
npx @dotrino/terminal-agent enroll # re-enlaza y corre
|
|
14
14
|
npx @dotrino/terminal-agent --name casa # otro agente en la misma máquina, con su enlace
|
|
15
15
|
npx @dotrino/terminal-agent list # los enlazados aquí
|
|
16
|
+
npx @dotrino/terminal-agent info # qué aparato es: su ID, su bóveda, sus permisos
|
|
16
17
|
# [--proxy wss://…] [--shell /bin/zsh] [--dir /ruta]
|
|
17
18
|
```
|
|
18
19
|
|
package/bin/cli.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* dotrino-terminal-agent [--name <n>] # enlaza (si falta) y CORRE el agente
|
|
6
6
|
* dotrino-terminal-agent enroll [--name <n>] # re-enlaza (sobrescribe) y corre el agente
|
|
7
7
|
* dotrino-terminal-agent list # los agentes enlazados en esta máquina
|
|
8
|
+
* dotrino-terminal-agent info [--name <n>] # qué aparato es: su ID, su bóveda, sus permisos
|
|
8
9
|
*
|
|
9
10
|
* Cada agente tiene su NOMBRE y su enlace (`@dotrino/remote-agent/instances`), como `dotrino-env`.
|
|
10
11
|
*
|
|
@@ -17,6 +18,7 @@ import { watchForUpdate } from '@dotrino/update'
|
|
|
17
18
|
import { startAgent } from '../index.js'
|
|
18
19
|
import { enroll, parseQr, loadLink, dataDir, LABEL } from '../link.js'
|
|
19
20
|
import { listInstances, lockInstance, instancesRoot } from '@dotrino/remote-agent/instances'
|
|
21
|
+
import { deviceInfo, formatDeviceInfo } from '@dotrino/vault/device-info'
|
|
20
22
|
|
|
21
23
|
const { version: VERSION } = createRequire(import.meta.url)('../package.json')
|
|
22
24
|
const args = process.argv.slice(2)
|
|
@@ -33,6 +35,8 @@ if (args.includes('-h') || args.includes('--help')) {
|
|
|
33
35
|
dotrino-terminal-agent [--name <n>] enlaza este agente (si falta) y lo corre
|
|
34
36
|
dotrino-terminal-agent enroll [--name <n>] re-enlaza (sobrescribe el enlace) y lo corre
|
|
35
37
|
dotrino-terminal-agent list los agentes enlazados en esta máquina
|
|
38
|
+
dotrino-terminal-agent info [--name <n>] qué aparato es: su ID (el de «dotrino-vault members»),
|
|
39
|
+
su bóveda y sus permisos. Sin red. [--json]
|
|
36
40
|
opciones: [--name <n>] [--proxy <wss://…>] [--shell <bin>] [--dir <ruta>]
|
|
37
41
|
|
|
38
42
|
enlaces en ${instancesRoot(LABEL)}/<nombre> (override DOTRINO_AGENT_HOME;
|
|
@@ -47,6 +51,19 @@ if (cmd === 'list') {
|
|
|
47
51
|
process.exit(0)
|
|
48
52
|
}
|
|
49
53
|
|
|
54
|
+
// `info`: la pieza común del ecosistema (`@dotrino/vault/device-info`). Lo que se viene a
|
|
55
|
+
// mirar es el ID, para buscarlo en el acta.
|
|
56
|
+
if (cmd === 'info') {
|
|
57
|
+
try {
|
|
58
|
+
const dir = opt('--dir') || dataDir(opt('--name'))
|
|
59
|
+
const link = loadLink(dir)
|
|
60
|
+
if (!link) { console.error(`Este agente no está enlazado (${dir}). Enlázalo con: dotrino-terminal-agent`); process.exit(1) }
|
|
61
|
+
const info = await deviceInfo(link, { kind: LABEL, name: opt('--dir') ? null : dir.split(/[\\/]/).pop(), version: VERSION, dir })
|
|
62
|
+
console.log(args.includes('--json') ? JSON.stringify(info, null, 2) : formatDeviceInfo(info))
|
|
63
|
+
} catch (e) { console.error('error:', e.message); process.exit(1) }
|
|
64
|
+
process.exit(0)
|
|
65
|
+
}
|
|
66
|
+
|
|
50
67
|
async function doEnroll (dir) {
|
|
51
68
|
if (!process.stdin.isTTY) {
|
|
52
69
|
throw new Error('this machine is not linked, and linking needs an interactive terminal. Run it once in a terminal, then start it as a service.')
|
package/consoles.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* consoles.js — las shells del agente, SEPARADAS de las conexiones.
|
|
3
|
+
*
|
|
4
|
+
* Antes una shell vivía lo que su sesión cifrada: cerrar o recargar el navegador la
|
|
5
|
+
* dejaba huérfana y a los 30 min moría. Ahora cada shell es una CONSOLA con id, que sigue
|
|
6
|
+
* viva aunque no haya nadie mirando, y a la que cualquier aparato de la cuenta puede
|
|
7
|
+
* volver (`attach`) y ver la pantalla tal como estaba.
|
|
8
|
+
*
|
|
9
|
+
* La pantalla se reconstruye con una terminal SIN PANTALLA (`@xterm/headless`) que recibe
|
|
10
|
+
* lo mismo que el navegador: al volver se manda su estado serializado (pantalla + historial),
|
|
11
|
+
* no los últimos bytes sueltos, que cortarían secuencias de escape a la mitad.
|
|
12
|
+
*
|
|
13
|
+
* Todo en MEMORIA: nada de lo que sale por una shell se escribe al disco. Si el agente se
|
|
14
|
+
* reinicia, las consolas se pierden (y se dice: la app ve que ya no están).
|
|
15
|
+
*/
|
|
16
|
+
import { createRequire } from 'node:module'
|
|
17
|
+
|
|
18
|
+
const require = createRequire(import.meta.url)
|
|
19
|
+
const { Terminal } = require('@xterm/headless')
|
|
20
|
+
const { SerializeAddon } = require('@xterm/addon-serialize')
|
|
21
|
+
|
|
22
|
+
/** Líneas de historial que se guardan y se devuelven al volver. */
|
|
23
|
+
export const SCROLLBACK = 1000
|
|
24
|
+
/** Tamaño máximo de cada trozo de la repetición: el proxio corta los mensajes a 1 MB. */
|
|
25
|
+
export const REPLAY_CHUNK = 64 * 1024
|
|
26
|
+
|
|
27
|
+
const randomId = () => [...crypto.getRandomValues(new Uint8Array(8))].map((x) => x.toString(16).padStart(2, '0')).join('')
|
|
28
|
+
|
|
29
|
+
class Console {
|
|
30
|
+
constructor ({ id, pty, cols, rows }) {
|
|
31
|
+
this.id = id
|
|
32
|
+
this.pty = pty
|
|
33
|
+
this.cols = cols
|
|
34
|
+
this.rows = rows
|
|
35
|
+
this.createdAt = Date.now()
|
|
36
|
+
this.lastActive = Date.now()
|
|
37
|
+
this.viewers = new Set() // sesiones mirando: { onOut(data), onExit(code) }
|
|
38
|
+
this.exited = false
|
|
39
|
+
this.screen = new Terminal({ cols, rows, scrollback: SCROLLBACK, allowProposedApi: true })
|
|
40
|
+
this.serializer = new SerializeAddon()
|
|
41
|
+
this.screen.loadAddon(this.serializer)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Lo que sale de la shell: a la pantalla sin pantalla y a quien esté mirando. */
|
|
45
|
+
_out (data) {
|
|
46
|
+
this.lastActive = Date.now()
|
|
47
|
+
this.screen.write(data)
|
|
48
|
+
for (const v of this.viewers) v.onOut(data)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
write (data) { this.lastActive = Date.now(); this.pty.write(data) }
|
|
52
|
+
|
|
53
|
+
resize (cols, rows) {
|
|
54
|
+
if (!cols || !rows) return
|
|
55
|
+
this.cols = cols; this.rows = rows
|
|
56
|
+
try { this.pty.resize(cols, rows) } catch (_) {}
|
|
57
|
+
try { this.screen.resize(cols, rows) } catch (_) {}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Engancha a `viewer` y le devuelve la pantalla actual. EXACTO, sin huecos ni repetidos:
|
|
62
|
+
* lo que ya se escribió va en la foto, y lo que llega mientras se hace la foto se guarda
|
|
63
|
+
* aparte y se le da después. El `write('', cb)` hace de marca: xterm procesa en orden y
|
|
64
|
+
* llama al callback justo tras esa marca, así que la foto tiene todo lo anterior y nada
|
|
65
|
+
* de lo posterior.
|
|
66
|
+
* @returns {Promise<string>} la pantalla serializada
|
|
67
|
+
*/
|
|
68
|
+
attach (viewer) {
|
|
69
|
+
const pending = []
|
|
70
|
+
const buffering = { onOut: (d) => pending.push(d), onExit: viewer.onExit }
|
|
71
|
+
this.viewers.add(buffering)
|
|
72
|
+
return new Promise((resolve) => {
|
|
73
|
+
this.screen.write('', () => {
|
|
74
|
+
const snapshot = this.serializer.serialize()
|
|
75
|
+
this.viewers.delete(buffering)
|
|
76
|
+
this.viewers.add(viewer)
|
|
77
|
+
resolve(snapshot + pending.join(''))
|
|
78
|
+
})
|
|
79
|
+
})
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
detach (viewer) { this.viewers.delete(viewer) }
|
|
83
|
+
|
|
84
|
+
info () {
|
|
85
|
+
return { id: this.id, cols: this.cols, rows: this.rows, createdAt: this.createdAt, lastActive: this.lastActive, viewers: this.viewers.size }
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Las consolas de este agente. */
|
|
90
|
+
export class ConsoleHub {
|
|
91
|
+
/**
|
|
92
|
+
* @param {{ spawn:(opts:{cols:number,rows:number})=>any }} opts
|
|
93
|
+
* `spawn` lanza la shell (un PTY con `onData`, `onExit`, `write`, `resize`, `kill`).
|
|
94
|
+
*/
|
|
95
|
+
constructor ({ spawn }) {
|
|
96
|
+
this._spawn = spawn
|
|
97
|
+
this.consoles = new Map()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
create ({ cols = 80, rows = 24 } = {}) {
|
|
101
|
+
const id = randomId()
|
|
102
|
+
const pty = this._spawn({ cols, rows })
|
|
103
|
+
const c = new Console({ id, pty, cols, rows })
|
|
104
|
+
pty.onData((d) => c._out(d))
|
|
105
|
+
pty.onExit(({ exitCode }) => {
|
|
106
|
+
c.exited = true
|
|
107
|
+
this.consoles.delete(id)
|
|
108
|
+
for (const v of c.viewers) v.onExit(exitCode)
|
|
109
|
+
c.viewers.clear()
|
|
110
|
+
try { c.screen.dispose() } catch (_) {}
|
|
111
|
+
})
|
|
112
|
+
this.consoles.set(id, c)
|
|
113
|
+
return c
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
get (id) { return this.consoles.get(id) || null }
|
|
117
|
+
|
|
118
|
+
list () { return [...this.consoles.values()].map((c) => c.info()) }
|
|
119
|
+
|
|
120
|
+
kill (id) {
|
|
121
|
+
const c = this.consoles.get(id)
|
|
122
|
+
if (!c) return false
|
|
123
|
+
try { c.pty.kill() } catch (_) {}
|
|
124
|
+
return true
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
killAll () { for (const id of [...this.consoles.keys()]) this.kill(id) }
|
|
128
|
+
}
|
package/index.js
CHANGED
|
@@ -6,15 +6,23 @@
|
|
|
6
6
|
* paquete solo sabe de PTY. Antes lo hacía todo a mano (su propio enrolamiento, su propio
|
|
7
7
|
* cifrado) y por eso se quedó atrás: con la bóveda actual no podía ni emparejarse.
|
|
8
8
|
*
|
|
9
|
+
* Las shells son CONSOLAS que viven aparte de las sesiones (consoles.js): cerrar o recargar
|
|
10
|
+
* el navegador solo las suelta, y cualquier aparato de la cuenta puede volver a ellas.
|
|
11
|
+
*
|
|
9
12
|
* Payloads de dominio (van cifrados dentro de la sesión, el proxio no los ve):
|
|
10
|
-
* cliente → agente: { type:'
|
|
11
|
-
* { type:'
|
|
12
|
-
*
|
|
13
|
+
* cliente → agente: { type:'list' } · { type:'open', cols, rows } ·
|
|
14
|
+
* { type:'attach', id, cols, rows } · { type:'detach' } ·
|
|
15
|
+
* { type:'input', data } · { type:'resize', cols, rows } ·
|
|
16
|
+
* { type:'close' } (mata la consola enganchada) · { type:'kill', id }
|
|
17
|
+
* agente → cliente: { type:'consoles', list } · { type:'attached', id, fresh } ·
|
|
18
|
+
* { type:'replay', id, data, last } · { type:'out', data } ·
|
|
19
|
+
* { type:'exit', code } · { type:'fail', code, message }
|
|
13
20
|
*/
|
|
14
21
|
import os from 'node:os'
|
|
15
22
|
import { createRequire } from 'node:module'
|
|
16
23
|
import { startRemoteAgent } from '@dotrino/remote-agent/agent'
|
|
17
24
|
import { dataDir, LABEL } from './link.js'
|
|
25
|
+
import { ConsoleHub, REPLAY_CHUNK } from './consoles.js'
|
|
18
26
|
|
|
19
27
|
const require = createRequire(import.meta.url)
|
|
20
28
|
|
|
@@ -27,30 +35,60 @@ export function loadPty () {
|
|
|
27
35
|
}
|
|
28
36
|
}
|
|
29
37
|
|
|
30
|
-
/**
|
|
31
|
-
export function
|
|
32
|
-
|
|
33
|
-
|
|
38
|
+
/** Las consolas de este agente, sobre el PTY. Exportada para las pruebas. */
|
|
39
|
+
export function makeHub (pty, opts = {}) {
|
|
40
|
+
const shell = opts.shell || process.env.SHELL || (process.platform === 'win32' ? 'powershell.exe' : 'bash')
|
|
41
|
+
return new ConsoleHub({
|
|
42
|
+
spawn: ({ cols, rows }) => pty.spawn(shell, [], {
|
|
43
|
+
name: 'xterm-256color', cols, rows,
|
|
44
|
+
cwd: os.homedir(), env: { ...process.env, TERM: 'xterm-256color' }
|
|
45
|
+
})
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Atiende una sesión cifrada. Una sesión mira UNA consola a la vez (una pestaña). Si la
|
|
51
|
+
* sesión se cierra (el navegador se fue, inactividad), la consola se SUELTA, no se mata.
|
|
52
|
+
* Exportada para las pruebas.
|
|
53
|
+
*/
|
|
54
|
+
export function serveSession (session, hub) {
|
|
55
|
+
let current = null
|
|
56
|
+
const viewer = {
|
|
57
|
+
onOut: (data) => { session.send({ type: 'out', data }) },
|
|
58
|
+
onExit: (code) => { current = null; session.send({ type: 'exit', code }) }
|
|
59
|
+
}
|
|
60
|
+
const release = () => { if (current) { current.detach(viewer); current = null } }
|
|
61
|
+
const fail = (code, message) => session.send({ type: 'fail', code, message })
|
|
62
|
+
|
|
63
|
+
async function attachTo (c, { fresh }) {
|
|
64
|
+
release()
|
|
65
|
+
current = c
|
|
66
|
+
const snapshot = await c.attach(viewer)
|
|
67
|
+
// La pantalla va en trozos: el proxio corta los mensajes a 1 MB.
|
|
68
|
+
for (let i = 0; i < snapshot.length || i === 0; i += REPLAY_CHUNK) {
|
|
69
|
+
await session.send({ type: 'replay', id: c.id, data: snapshot.slice(i, i + REPLAY_CHUNK), last: i + REPLAY_CHUNK >= snapshot.length })
|
|
70
|
+
}
|
|
71
|
+
await session.send({ type: 'attached', id: c.id, fresh })
|
|
72
|
+
}
|
|
34
73
|
|
|
35
74
|
session.on('message', (msg) => {
|
|
36
75
|
if (!msg || typeof msg !== 'object') return
|
|
37
|
-
if (msg.type === '
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
})
|
|
44
|
-
term.onData((data) => { session.send({ type: 'out', data }) })
|
|
45
|
-
term.onExit(({ exitCode }) => { session.send({ type: 'exit', code: exitCode }); term = null })
|
|
76
|
+
if (msg.type === 'list') { session.send({ type: 'consoles', list: hub.list() }); return }
|
|
77
|
+
if (msg.type === 'open') { attachTo(hub.create({ cols: msg.cols || 80, rows: msg.rows || 24 }), { fresh: true }); return }
|
|
78
|
+
if (msg.type === 'attach') {
|
|
79
|
+
const c = hub.get(msg.id)
|
|
80
|
+
if (!c) return fail('no-console', 'that console no longer exists')
|
|
81
|
+
c.resize(msg.cols, msg.rows)
|
|
82
|
+
attachTo(c, { fresh: false })
|
|
46
83
|
return
|
|
47
84
|
}
|
|
48
|
-
if (msg.type === '
|
|
49
|
-
if (msg.type === '
|
|
50
|
-
if (msg.type === '
|
|
85
|
+
if (msg.type === 'detach') { release(); return }
|
|
86
|
+
if (msg.type === 'input') { current?.write(String(msg.data ?? '')); return }
|
|
87
|
+
if (msg.type === 'resize') { current?.resize(msg.cols, msg.rows); return }
|
|
88
|
+
if (msg.type === 'close') { if (current) hub.kill(current.id); return }
|
|
89
|
+
if (msg.type === 'kill') { if (!hub.kill(msg.id)) fail('no-console', 'that console no longer exists') }
|
|
51
90
|
})
|
|
52
|
-
|
|
53
|
-
session.on('close', kill)
|
|
91
|
+
session.on('close', release)
|
|
54
92
|
}
|
|
55
93
|
|
|
56
94
|
/**
|
|
@@ -65,15 +103,17 @@ export function servePty (session, pty, opts) {
|
|
|
65
103
|
* @param {()=>void} [opts.onRevoked]
|
|
66
104
|
*/
|
|
67
105
|
export async function startAgent (opts = {}) {
|
|
68
|
-
const
|
|
69
|
-
|
|
106
|
+
const hub = makeHub(loadPty(), opts)
|
|
107
|
+
const ra = await startRemoteAgent({
|
|
70
108
|
label: LABEL,
|
|
71
109
|
dir: opts.dir || dataDir(),
|
|
72
110
|
proxyUrl: opts.proxyUrl,
|
|
73
111
|
quiet: opts.quiet,
|
|
74
|
-
onRevoked: opts.onRevoked,
|
|
75
|
-
onSession: (session) =>
|
|
112
|
+
onRevoked: () => { hub.killAll(); opts.onRevoked?.() },
|
|
113
|
+
onSession: (session) => serveSession(session, hub)
|
|
76
114
|
})
|
|
115
|
+
// Parar el agente sí mata las consolas: sin agente no hay quién las atienda.
|
|
116
|
+
return { ...ra, consoles: hub, close: () => { hub.killAll(); ra.close() } }
|
|
77
117
|
}
|
|
78
118
|
|
|
79
119
|
export default { startAgent, LABEL }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/terminal-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "Agente de Dotrino Terminal: abre una shell (PTY) en esta máquina solo para los aparatos de tu cuenta, cifrada punto a punto, vía @dotrino/remote-agent.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
},
|
|
12
12
|
"files": [
|
|
13
13
|
"index.js",
|
|
14
|
+
"consoles.js",
|
|
14
15
|
"link.js",
|
|
15
16
|
"bin"
|
|
16
17
|
],
|
|
@@ -24,8 +25,10 @@
|
|
|
24
25
|
"@dotrino/proxy-client": "0.25.0",
|
|
25
26
|
"@dotrino/remote-agent": "0.12.0",
|
|
26
27
|
"@dotrino/update": "0.2.2",
|
|
27
|
-
"@dotrino/vault": "0.
|
|
28
|
-
"@homebridge/node-pty-prebuilt-multiarch": "0.14.1-beta.2"
|
|
28
|
+
"@dotrino/vault": "0.75.0",
|
|
29
|
+
"@homebridge/node-pty-prebuilt-multiarch": "0.14.1-beta.2",
|
|
30
|
+
"@xterm/addon-serialize": "0.13.0",
|
|
31
|
+
"@xterm/headless": "5.5.0"
|
|
29
32
|
},
|
|
30
33
|
"engines": {
|
|
31
34
|
"node": ">=20"
|