@dotrino/terminal-agent 0.3.1 → 0.5.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
@@ -9,8 +9,10 @@ añade el PTY.
9
9
  **Cómo se instala y se usa:** [wiki.dotrino.com/herramientas/terminal](https://wiki.dotrino.com/herramientas/terminal/).
10
10
 
11
11
  ```sh
12
- npx @dotrino/terminal-agent # enlaza (si falta) y corre
13
- npx @dotrino/terminal-agent enroll # re-enlaza y corre
12
+ npx @dotrino/terminal-agent # enlaza (si falta) y corre
13
+ npx @dotrino/terminal-agent enroll # re-enlaza y corre
14
+ npx @dotrino/terminal-agent --name casa # otro agente en la misma máquina, con su enlace
15
+ npx @dotrino/terminal-agent list # los enlazados aquí
14
16
  # [--proxy wss://…] [--shell /bin/zsh] [--dir /ruta]
15
17
  ```
16
18
 
@@ -26,7 +28,9 @@ const agent = await startAgent({ /* dir, proxyUrl, shell, quiet, onRevoked */ })
26
28
  // agent.machine · agent.machineId · agent.close()
27
29
  ```
28
30
 
29
- Datos en `~/.local/share/dotrino-terminal-agent` (override `DOTRINO_TERMINAL_DIR`). El
30
- `link.json` guarda la llave privada de la máquina: trátalo como una llave SSH.
31
+ Cada agente guarda su enlace en `~/.dotrino/agent/terminal-agent/<nombre>/`, el estándar de
32
+ `@dotrino/remote-agent/instances` (como `dotrino-env` en `~/.dotrino/service/`). Sin
33
+ `--name` se usa el único que haya, o `default`. `DOTRINO_TERMINAL_DIR` o `--dir` fuerzan una
34
+ carpeta concreta. El `link.json` guarda la llave privada: trátalo como una llave SSH.
31
35
 
32
36
  MIT.
package/bin/cli.js CHANGED
@@ -2,8 +2,11 @@
2
2
  /**
3
3
  * dotrino-terminal-agent — agente de Dotrino Terminal.
4
4
  *
5
- * dotrino-terminal-agent # enlaza (si falta) y CORRE el agente
6
- * dotrino-terminal-agent enroll # re-enlaza (sobrescribe) y corre el agente
5
+ * dotrino-terminal-agent [--name <n>] # enlaza (si falta) y CORRE el agente
6
+ * dotrino-terminal-agent enroll [--name <n>] # re-enlaza (sobrescribe) y corre el agente
7
+ * dotrino-terminal-agent list # los agentes enlazados en esta máquina
8
+ *
9
+ * Cada agente tiene su NOMBRE y su enlace (`@dotrino/remote-agent/instances`), como `dotrino-env`.
7
10
  *
8
11
  * El agente es un aparato más de tu cuenta: puede vivir en cualquier máquina. Con un
9
12
  * solo comando queda enlazado y aparece solo en terminal.dotrino.com.
@@ -12,7 +15,8 @@ import readline from 'node:readline'
12
15
  import { createRequire } from 'node:module'
13
16
  import { watchForUpdate } from '@dotrino/update'
14
17
  import { startAgent } from '../index.js'
15
- import { enroll, parseQr, loadLink, dataDir } from '../link.js'
18
+ import { enroll, parseQr, loadLink, dataDir, LABEL } from '../link.js'
19
+ import { listInstances, lockInstance, instancesRoot } from '@dotrino/remote-agent/instances'
16
20
 
17
21
  const { version: VERSION } = createRequire(import.meta.url)('../package.json')
18
22
  const args = process.argv.slice(2)
@@ -26,11 +30,20 @@ function ask (q) {
26
30
 
27
31
  if (args.includes('-h') || args.includes('--help')) {
28
32
  console.log(`uso:
29
- dotrino-terminal-agent enlaza esta máquina (si falta) y corre el agente
30
- dotrino-terminal-agent enroll re-enlaza (sobrescribe el enlace) y corre el agente
31
- opciones: [--proxy <wss://…>] [--shell <bin>] [--dir <ruta>]
33
+ dotrino-terminal-agent [--name <n>] enlaza este agente (si falta) y lo corre
34
+ dotrino-terminal-agent enroll [--name <n>] re-enlaza (sobrescribe el enlace) y lo corre
35
+ dotrino-terminal-agent list los agentes enlazados en esta máquina
36
+ opciones: [--name <n>] [--proxy <wss://…>] [--shell <bin>] [--dir <ruta>]
37
+
38
+ enlaces en ${instancesRoot(LABEL)}/<nombre> (override DOTRINO_AGENT_HOME;
39
+ --dir o DOTRINO_TERMINAL_DIR fuerzan una carpeta concreta)`)
40
+ process.exit(0)
41
+ }
32
42
 
33
- datos en ${dataDir()} (override DOTRINO_TERMINAL_DIR)`)
43
+ if (cmd === 'list') {
44
+ const names = listInstances(LABEL)
45
+ if (!names.length) console.log('No hay ningún agente de terminal enlazado en esta máquina.')
46
+ for (const n of names) console.log(` ${n} ${instancesRoot(LABEL)}/${n}`)
34
47
  process.exit(0)
35
48
  }
36
49
 
@@ -57,7 +70,9 @@ async function doEnroll (dir) {
57
70
  }
58
71
 
59
72
  try {
60
- const dir = opt('--dir')
73
+ const dir = opt('--dir') || dataDir(opt('--name'))
74
+ // Antes de nada, también de enlazar: dos procesos con el mismo enlace son la misma llave.
75
+ process.on('exit', lockInstance(dir))
61
76
  // Sin `enroll`, enlaza solo si aún no lo está; `enroll` re-enlaza aunque ya lo esté.
62
77
  // En los dos casos sigue y LEVANTA el servicio.
63
78
  if (cmd === 'enroll' || !loadLink(dir)) {
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:'open', cols, rows } · { type:'input', data } ·
11
- * { type:'resize', cols, rows } · { type:'close' }
12
- * agente → cliente: { type:'out', data } · { type:'exit', code }
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
- /** Atiende una sesión cifrada: una shell por sesión. Exportada para las pruebas. */
31
- export function servePty (session, pty, opts) {
32
- let term = null
33
- const kill = () => { try { term?.kill() } catch (_) {} term = null }
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 === 'open') {
38
- if (term) return
39
- const shell = opts.shell || process.env.SHELL || (process.platform === 'win32' ? 'powershell.exe' : 'bash')
40
- term = pty.spawn(shell, [], {
41
- name: 'xterm-256color', cols: msg.cols || 80, rows: msg.rows || 24,
42
- cwd: os.homedir(), env: { ...process.env, TERM: 'xterm-256color' }
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 === 'input') { term?.write(String(msg.data ?? '')); return }
49
- if (msg.type === 'resize') { try { term?.resize(msg.cols, msg.rows) } catch (_) {} return }
50
- if (msg.type === 'close') { kill(); session.close() }
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
- // La sesión se cierra por inactividad o al parar el agente: la shell muere con ella.
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 pty = loadPty()
69
- return startRemoteAgent({
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) => servePty(session, pty, opts)
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/link.js CHANGED
@@ -1,22 +1,24 @@
1
1
  /**
2
2
  * link.js — el enlace de esta máquina con la bóveda. Todo lo hace
3
3
  * `@dotrino/remote-agent/link` (que a su vez usa `enrollWithVault`, el único
4
- * enrolamiento headless del ecosistema); aquí solo se decide DÓNDE vive el enlace.
4
+ * enrolamiento headless del ecosistema), y DÓNDE vive lo decide el estándar
5
+ * `@dotrino/remote-agent/instances`: `~/.dotrino/agent/terminal-agent/<nombre>/`.
5
6
  */
6
- import path from 'node:path'
7
- import os from 'node:os'
8
7
  import { enroll as raEnroll, loadLink as raLoad, parseQr } from '@dotrino/remote-agent/link'
8
+ import { resolveInstance } from '@dotrino/remote-agent/instances'
9
9
 
10
10
  export { parseQr }
11
11
 
12
- /** Label con el que se enrola y con el que la app encuentra las máquinas. */
12
+ /** El tipo de este agente: lo contesta al ping y da nombre a la carpeta de sus enlaces. */
13
13
  export const LABEL = 'terminal-agent'
14
14
 
15
- /** `~/.local/share/dotrino-terminal-agent` (override `DOTRINO_TERMINAL_DIR`). */
16
- export function dataDir () {
15
+ /**
16
+ * La carpeta del enlace. `DOTRINO_TERMINAL_DIR` fuerza una concreta (un contenedor); si no,
17
+ * la de la instancia `name` (sin nombre se busca y solo se exige con empate).
18
+ */
19
+ export function dataDir (name) {
17
20
  if (process.env.DOTRINO_TERMINAL_DIR) return process.env.DOTRINO_TERMINAL_DIR
18
- const base = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share')
19
- return path.join(base, 'dotrino-terminal-agent')
21
+ return resolveInstance(LABEL, name).dir
20
22
  }
21
23
 
22
24
  export const loadLink = (dir = dataDir()) => raLoad(dir)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/terminal-agent",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
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
  ],
@@ -22,10 +23,12 @@
22
23
  "dependencies": {
23
24
  "@dotrino/identity": "0.105.0",
24
25
  "@dotrino/proxy-client": "0.25.0",
25
- "@dotrino/remote-agent": "0.11.0",
26
+ "@dotrino/remote-agent": "0.12.0",
26
27
  "@dotrino/update": "0.2.2",
27
28
  "@dotrino/vault": "0.74.0",
28
- "@homebridge/node-pty-prebuilt-multiarch": "0.14.1-beta.2"
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"