@dotrino/terminal-agent 0.5.1 → 0.7.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 +25 -5
- package/bin/cli.js +18 -35
- package/bin/terminal.js +260 -0
- package/consoles.js +23 -8
- package/index.js +100 -21
- package/link.js +59 -1
- package/local.js +126 -0
- package/package.json +6 -3
- package/title.js +50 -0
package/README.md
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
# @dotrino/terminal-agent
|
|
2
2
|
|
|
3
|
-
Agente de [Dotrino Terminal](https://terminal.dotrino.com)
|
|
4
|
-
|
|
3
|
+
Agente de [Dotrino Terminal](https://terminal.dotrino.com) y el cliente de sus ventanas. El
|
|
4
|
+
agente tiene las shells (PTY) de esta máquina; las abren las **ventanas locales**
|
|
5
|
+
(`dotrino-terminal`, por un socket) y los **aparatos de tu cuenta** (por el proxio,
|
|
6
|
+
cifrado). Una ventana abierta aquí se puede retomar desde el teléfono, y al revés. Lo común (enrolamiento, saludo contra
|
|
5
7
|
el acta, canal cifrado, revocación, renovación) es
|
|
6
8
|
[`@dotrino/remote-agent`](https://www.npmjs.com/package/@dotrino/remote-agent); esto
|
|
7
9
|
añade el PTY.
|
|
8
10
|
|
|
9
|
-
**Cómo se instala y se usa:** [wiki.dotrino.com/herramientas/terminal](https://wiki.dotrino.com/herramientas/terminal/).
|
|
11
|
+
**Cómo se instala y se usa:** [las ventanas y la app de escritorio](https://wiki.dotrino.com/herramientas/terminal-escritorio/) · [el acceso desde el navegador](https://wiki.dotrino.com/herramientas/terminal/).
|
|
10
12
|
|
|
11
13
|
```sh
|
|
12
14
|
npx @dotrino/terminal-agent # enlaza (si falta) y corre
|
|
@@ -17,6 +19,24 @@ npx @dotrino/terminal-agent info # qué aparato es: su ID, su bóved
|
|
|
17
19
|
# [--proxy wss://…] [--shell /bin/zsh] [--dir /ruta]
|
|
18
20
|
```
|
|
19
21
|
|
|
22
|
+
Las ventanas de esta máquina:
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
dotrino-terminal # abre una consola nueva en esta TTY (levanta el agente si hace falta)
|
|
26
|
+
dotrino-terminal --name casa # en el agente del perfil «casa»
|
|
27
|
+
dotrino-terminal ls # las consolas abiertas: id, origen, título, quién mira
|
|
28
|
+
dotrino-terminal attach <id> # retomar una
|
|
29
|
+
dotrino-terminal kill <id>
|
|
30
|
+
dotrino-terminal profiles [--json] # los perfiles (agentes con nombre) de esta máquina
|
|
31
|
+
dotrino-terminal link [--name <n>] # enlazar un perfil con tu bóveda
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Cerrar la ventana cierra su consola, como cualquier terminal; **Ctrl+] y luego d** la suelta
|
|
35
|
+
viva. Si un aparato remoto entra en una ventana local, esa ventana suena y lo dice en el
|
|
36
|
+
título. Sin enlace el agente atiende solo a las ventanas locales; al enlazarlo
|
|
37
|
+
(`dotrino-terminal link`) enciende la parte remota sin reiniciarse. La app de escritorio
|
|
38
|
+
(`desktop/` del repo) es una ventana nativa que corre este mismo cliente.
|
|
39
|
+
|
|
20
40
|
Enlazar pide una terminal interactiva: se pega la invitación de `dotrino-vault pair` y
|
|
21
41
|
se aprueba con `dotrino-vault approve <código>`. Después puede correr como servicio
|
|
22
42
|
(systemd, pm2). Una vez al día avisa si hay versión nueva; no se actualiza solo.
|
|
@@ -25,8 +45,8 @@ Como librería:
|
|
|
25
45
|
|
|
26
46
|
```js
|
|
27
47
|
import { startAgent } from '@dotrino/terminal-agent'
|
|
28
|
-
const agent = await startAgent({ /* dir, proxyUrl, shell, quiet, onRevoked */ })
|
|
29
|
-
// agent.
|
|
48
|
+
const agent = await startAgent({ /* dir, proxyUrl, shell, quiet, onRevoked, onLinked */ })
|
|
49
|
+
// agent.socket · agent.remote (null sin enlace) · agent.machineId · agent.consoles · agent.close()
|
|
30
50
|
```
|
|
31
51
|
|
|
32
52
|
Cada agente guarda su enlace en `~/.dotrino/agent/terminal-agent/<nombre>/`, el estándar de
|
package/bin/cli.js
CHANGED
|
@@ -7,16 +7,18 @@
|
|
|
7
7
|
* dotrino-terminal-agent list # los agentes enlazados en esta máquina
|
|
8
8
|
* dotrino-terminal-agent info [--name <n>] # qué aparato es: su ID, su bóveda, sus permisos
|
|
9
9
|
*
|
|
10
|
+
* Las ventanas de esta máquina se abren con `dotrino-terminal` (bin/terminal.js), que habla
|
|
11
|
+
* con este agente por un socket local y lo levanta si no está corriendo.
|
|
12
|
+
*
|
|
10
13
|
* Cada agente tiene su NOMBRE y su enlace (`@dotrino/remote-agent/instances`), como `dotrino-env`.
|
|
11
14
|
*
|
|
12
15
|
* El agente es un aparato más de tu cuenta: puede vivir en cualquier máquina. Con un
|
|
13
16
|
* solo comando queda enlazado y aparece solo en terminal.dotrino.com.
|
|
14
17
|
*/
|
|
15
|
-
import readline from 'node:readline'
|
|
16
18
|
import { createRequire } from 'node:module'
|
|
17
19
|
import { watchForUpdate } from '@dotrino/update'
|
|
18
20
|
import { startAgent } from '../index.js'
|
|
19
|
-
import {
|
|
21
|
+
import { linkInteractive, loadLink, dataDir, LABEL } from '../link.js'
|
|
20
22
|
import { listInstances, lockInstance, instancesRoot } from '@dotrino/remote-agent/instances'
|
|
21
23
|
import { deviceInfo, formatDeviceInfo } from '@dotrino/vault/device-info'
|
|
22
24
|
|
|
@@ -25,11 +27,6 @@ const args = process.argv.slice(2)
|
|
|
25
27
|
const cmd = args[0] && !args[0].startsWith('-') ? args[0] : 'run'
|
|
26
28
|
const opt = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined }
|
|
27
29
|
|
|
28
|
-
function ask (q) {
|
|
29
|
-
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
30
|
-
return new Promise((res) => rl.question(q, (a) => { rl.close(); res(a) }))
|
|
31
|
-
}
|
|
32
|
-
|
|
33
30
|
if (args.includes('-h') || args.includes('--help')) {
|
|
34
31
|
console.log(`uso:
|
|
35
32
|
dotrino-terminal-agent [--name <n>] enlaza este agente (si falta) y lo corre
|
|
@@ -38,6 +35,7 @@ if (args.includes('-h') || args.includes('--help')) {
|
|
|
38
35
|
dotrino-terminal-agent info [--name <n>] qué aparato es: su ID (el de «dotrino-vault members»),
|
|
39
36
|
su bóveda y sus permisos. Sin red. [--json]
|
|
40
37
|
opciones: [--name <n>] [--proxy <wss://…>] [--shell <bin>] [--dir <ruta>]
|
|
38
|
+
[--local] no enlazar ahora: atender solo a las ventanas de esta máquina
|
|
41
39
|
|
|
42
40
|
enlaces en ${instancesRoot(LABEL)}/<nombre> (override DOTRINO_AGENT_HOME;
|
|
43
41
|
--dir o DOTRINO_TERMINAL_DIR fuerzan una carpeta concreta)`)
|
|
@@ -64,46 +62,31 @@ if (cmd === 'info') {
|
|
|
64
62
|
process.exit(0)
|
|
65
63
|
}
|
|
66
64
|
|
|
67
|
-
async function doEnroll (dir) {
|
|
68
|
-
if (!process.stdin.isTTY) {
|
|
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.')
|
|
70
|
-
}
|
|
71
|
-
console.log('Enlazar esta máquina con tu bóveda.')
|
|
72
|
-
console.log('En el PC de tu bóveda corre `dotrino-vault pair` y copia la invitación.\n')
|
|
73
|
-
const qr = await parseQr(await ask('Pega la invitación y pulsa Enter:\n> '))
|
|
74
|
-
console.log('\nConectando…')
|
|
75
|
-
await enroll({
|
|
76
|
-
qr,
|
|
77
|
-
dir,
|
|
78
|
-
onChallenge: ({ deviceId, code }) => {
|
|
79
|
-
console.log('\n Escribe ESTE código en tu bóveda para aprobar esta máquina:')
|
|
80
|
-
console.log(` código: ${code}`)
|
|
81
|
-
console.log(` máquina: ${deviceId}`)
|
|
82
|
-
console.log(` (en el PC de la bóveda: dotrino-vault approve ${code})\n`)
|
|
83
|
-
console.log(' Esperando la aprobación…')
|
|
84
|
-
}
|
|
85
|
-
})
|
|
86
|
-
console.log('\n ✓ Máquina enlazada. Levantando el agente…\n')
|
|
87
|
-
}
|
|
88
|
-
|
|
89
65
|
try {
|
|
90
66
|
const dir = opt('--dir') || dataDir(opt('--name'))
|
|
91
67
|
// Antes de nada, también de enlazar: dos procesos con el mismo enlace son la misma llave.
|
|
92
68
|
process.on('exit', lockInstance(dir))
|
|
93
|
-
// Sin `enroll`, enlaza solo si aún no lo
|
|
94
|
-
//
|
|
95
|
-
|
|
69
|
+
// Sin `enroll`, enlaza solo si aún no lo está Y hay alguien delante (una TTY) que no pidió
|
|
70
|
+
// `--local`; `enroll` re-enlaza aunque ya lo esté. Sin enlace el agente atiende solo a las
|
|
71
|
+
// ventanas de esta máquina: así lo levanta `dotrino-terminal` cuando no hay ninguno.
|
|
72
|
+
const wantsLink = cmd === 'enroll' || (!loadLink(dir) && process.stdin.isTTY && !args.includes('--local'))
|
|
73
|
+
if (wantsLink) {
|
|
96
74
|
if (cmd === 'enroll' && loadLink(dir)) console.log('Re-enlazando esta máquina (sobrescribe el enlace actual).\n')
|
|
97
|
-
await
|
|
75
|
+
await linkInteractive(dir)
|
|
76
|
+
console.log(' Levantando el agente…\n')
|
|
98
77
|
}
|
|
99
78
|
|
|
100
79
|
const agent = await startAgent({
|
|
101
80
|
dir, proxyUrl: opt('--proxy'), shell: opt('--shell'),
|
|
102
|
-
onRevoked: () => { console.log(' Esta máquina se quitó de tu bóveda. Para volver a usarla, enlázala otra vez.\n'); process.exit(0) }
|
|
81
|
+
onRevoked: () => { console.log(' Esta máquina se quitó de tu bóveda. Para volver a usarla, enlázala otra vez.\n'); process.exit(0) },
|
|
82
|
+
onLinked: (r) => console.log(` enlazada: máquina ${r.machineId}. Tus otros aparatos ya pueden abrir estas consolas.\n`),
|
|
83
|
+
onLinkError: (e) => console.error('[terminal-agent] linked, but the remote side did not start:', e.message)
|
|
103
84
|
})
|
|
104
85
|
console.log('\n Dotrino Terminal — agente activo')
|
|
105
86
|
console.log(' versión:', VERSION)
|
|
106
|
-
console.log(' máquina:', agent.
|
|
87
|
+
console.log(' ventanas de esta máquina:', agent.socket)
|
|
88
|
+
if (agent.remote) console.log(' máquina:', agent.machineId, '(tus otros aparatos pueden abrir estas consolas)\n')
|
|
89
|
+
else console.log(' sin enlazar: solo ventanas de esta máquina. Para abrirlas desde otros aparatos: dotrino-terminal-agent enroll\n')
|
|
107
90
|
// §15: una vez al día mira si hay versión nueva y lo dice. Solo avisa: instalar lo decide una persona.
|
|
108
91
|
watchForUpdate({
|
|
109
92
|
current: VERSION, source: 'npm', pkg: '@dotrino/terminal-agent',
|
package/bin/terminal.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* dotrino-terminal — una ventana de Dotrino Terminal en ESTA terminal (TTY).
|
|
4
|
+
*
|
|
5
|
+
* dotrino-terminal [--name <n>] [--cwd <dir>] abre una consola nueva aquí (en la carpeta actual)
|
|
6
|
+
* dotrino-terminal attach <id> [--name <n>] se engancha a una consola que ya existe
|
|
7
|
+
* dotrino-terminal ls [--name <n>] [--json] las consolas abiertas en el agente
|
|
8
|
+
* dotrino-terminal kill <id> [--name <n>] cierra una consola
|
|
9
|
+
* dotrino-terminal profiles [--json] los perfiles de esta máquina (enlazados o no)
|
|
10
|
+
* dotrino-terminal link [--name <n>] enlaza un perfil con tu bóveda
|
|
11
|
+
*
|
|
12
|
+
* Un PERFIL es un agente con nombre (`~/.dotrino/agent/terminal-agent/<nombre>/`), enlazado a
|
|
13
|
+
* una bóveda o solo local. Cada consola vive en el agente de un perfil.
|
|
14
|
+
*
|
|
15
|
+
* La shell no vive aquí: vive en el agente (`dotrino-terminal-agent`), y esta ventana es un
|
|
16
|
+
* cliente más, igual que el navegador de otro aparato. Por eso lo que se abre aquí se puede
|
|
17
|
+
* abrir desde terminal.dotrino.com. Si el agente no está corriendo, se levanta solo.
|
|
18
|
+
*
|
|
19
|
+
* Cerrar la ventana mata la consola que abrió, como en cualquier terminal. Para dejarla viva
|
|
20
|
+
* y retomarla después: Ctrl+] y luego d.
|
|
21
|
+
*/
|
|
22
|
+
import fs from 'node:fs'
|
|
23
|
+
import path from 'node:path'
|
|
24
|
+
import { spawn } from 'node:child_process'
|
|
25
|
+
import { fileURLToPath } from 'node:url'
|
|
26
|
+
import { createRequire } from 'node:module'
|
|
27
|
+
import { StringDecoder } from 'node:string_decoder'
|
|
28
|
+
import { printUpdateNotice } from '@dotrino/update/notice'
|
|
29
|
+
import { dataDir, loadLink, listProfiles, linkInteractive, LABEL } from '../link.js'
|
|
30
|
+
import { resolveInstance, isValidName } from '@dotrino/remote-agent/instances'
|
|
31
|
+
import readline from 'node:readline'
|
|
32
|
+
import { connectLocal } from '../local.js'
|
|
33
|
+
import { titleFilter } from '../title.js'
|
|
34
|
+
|
|
35
|
+
const { version: VERSION } = createRequire(import.meta.url)('../package.json')
|
|
36
|
+
const args = process.argv.slice(2)
|
|
37
|
+
const cmd = args[0] && !args[0].startsWith('-') ? args[0] : 'open'
|
|
38
|
+
const opt = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined }
|
|
39
|
+
|
|
40
|
+
const es = /^es/i.test(process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || '')
|
|
41
|
+
const t = (esText, enText) => (es ? esText : enText)
|
|
42
|
+
|
|
43
|
+
const DETACH_PREFIX = '\x1d' // Ctrl+]
|
|
44
|
+
|
|
45
|
+
if (args.includes('-h') || args.includes('--help')) {
|
|
46
|
+
console.log(t(`uso:
|
|
47
|
+
dotrino-terminal [--name <n>] [--cwd <dir>] abre una consola nueva en esta ventana, en la carpeta actual
|
|
48
|
+
dotrino-terminal attach <id> [--name <n>] se engancha a una consola abierta
|
|
49
|
+
dotrino-terminal ls [--name <n>] [--json] las consolas abiertas
|
|
50
|
+
dotrino-terminal kill <id> [--name <n>] cierra una consola
|
|
51
|
+
dotrino-terminal profiles [--json] los perfiles de esta máquina
|
|
52
|
+
dotrino-terminal link [--name <n>] enlaza un perfil con tu bóveda
|
|
53
|
+
|
|
54
|
+
Dentro de una consola: Ctrl+] y luego d la suelta sin cerrarla.
|
|
55
|
+
Cerrar la ventana cierra la consola que abrió.`, `usage:
|
|
56
|
+
dotrino-terminal [--name <n>] [--cwd <dir>] open a new console in this window, in the current folder
|
|
57
|
+
dotrino-terminal attach <id> [--name <n>] attach to an open console
|
|
58
|
+
dotrino-terminal ls [--name <n>] [--json] list open consoles
|
|
59
|
+
dotrino-terminal kill <id> [--name <n>] close a console
|
|
60
|
+
dotrino-terminal profiles [--json] this machine's profiles
|
|
61
|
+
dotrino-terminal link [--name <n>] link a profile with your vault
|
|
62
|
+
|
|
63
|
+
Inside a console: Ctrl+] then d detaches without closing it.
|
|
64
|
+
Closing the window closes the console it opened.`))
|
|
65
|
+
process.exit(0)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Un error que termina el cliente. Dentro de la app de escritorio (`DOTRINO_TERMINAL_HOLD=1`)
|
|
70
|
+
* la ventana se cierra cuando el cliente sale, así que antes se espera una tecla: si no, el
|
|
71
|
+
* error desaparecería con la ventana sin que nadie lo leyera.
|
|
72
|
+
*/
|
|
73
|
+
const HOLD = Symbol('hold')
|
|
74
|
+
function die (msg) {
|
|
75
|
+
process.stderr.write(msg + '\n')
|
|
76
|
+
if (process.env.DOTRINO_TERMINAL_HOLD !== '1' || !process.stdin.isTTY) process.exit(1)
|
|
77
|
+
process.stderr.write(t('\nPulsa una tecla para cerrar.', '\nPress any key to close.'))
|
|
78
|
+
process.stdin.setRawMode(true)
|
|
79
|
+
process.stdin.resume()
|
|
80
|
+
process.stdin.once('data', () => process.exit(1))
|
|
81
|
+
throw HOLD // corta lo que venía detrás; el proceso sale con la tecla
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** El agente de esta máquina; si no hay ninguno escuchando, lo levanta y espera a que conteste. */
|
|
85
|
+
async function agent (dir) {
|
|
86
|
+
try { return await connectLocal(dir) } catch (e) { if (e.code !== 'ENOAGENT') throw e }
|
|
87
|
+
// Un agente vivo sin socket es uno anterior a las ventanas (< 0.6.0): no se levanta otro
|
|
88
|
+
// encima (tendrían la misma llave), se dice.
|
|
89
|
+
const pid = Number((() => { try { return fs.readFileSync(path.join(dir, 'agent.pid'), 'utf8') } catch (_) { return '' } })())
|
|
90
|
+
if (pid && alive(pid)) {
|
|
91
|
+
throw new Error(t(`hay un agente corriendo (pid ${pid}) que no acepta ventanas: es anterior a la 0.6.0. Reinícialo con la versión nueva.`,
|
|
92
|
+
`an agent is running (pid ${pid}) that does not accept windows: it predates 0.6.0. Restart it with the new version.`))
|
|
93
|
+
}
|
|
94
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
95
|
+
const log = path.join(dir, 'agent.log')
|
|
96
|
+
const fd = fs.openSync(log, 'a', 0o600)
|
|
97
|
+
const cli = fileURLToPath(new URL('./cli.js', import.meta.url))
|
|
98
|
+
const extra = opt('--name') ? ['--name', opt('--name')] : []
|
|
99
|
+
// Sin TTY: si la máquina no está enlazada, el agente atiende solo a las ventanas locales.
|
|
100
|
+
const child = spawn(process.execPath, [cli, ...extra], { detached: true, stdio: ['ignore', fd, fd], env: process.env })
|
|
101
|
+
child.unref()
|
|
102
|
+
fs.closeSync(fd)
|
|
103
|
+
const t0 = Date.now()
|
|
104
|
+
while (Date.now() - t0 < 10000) {
|
|
105
|
+
await new Promise((r) => setTimeout(r, 100))
|
|
106
|
+
try { return await connectLocal(dir) } catch (e) { if (e.code !== 'ENOAGENT') throw e }
|
|
107
|
+
}
|
|
108
|
+
throw new Error(t(`el agente no arrancó; mira ${log}`, `the agent did not start; see ${log}`))
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function alive (pid) {
|
|
112
|
+
try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function profiles () {
|
|
116
|
+
const list = await listProfiles()
|
|
117
|
+
if (args.includes('--json')) { console.log(JSON.stringify(list, null, 2)); return }
|
|
118
|
+
for (const p of list) {
|
|
119
|
+
const what = p.linked ? `${t('aparato', 'device')} ${p.id} · ${t('bóveda', 'vault')} ${p.vault}` : t('sin enlazar (solo esta máquina)', 'not linked (this machine only)')
|
|
120
|
+
console.log(` ${p.name.padEnd(16)} ${what}`)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Enlaza un perfil. Sin `--name`, lo pregunta. Uno ya enlazado no se pisa: eso es `enroll`. */
|
|
125
|
+
async function link () {
|
|
126
|
+
let name = opt('--name')
|
|
127
|
+
if (!name) {
|
|
128
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
129
|
+
const taken = (await listProfiles()).filter((p) => p.linked).map((p) => p.name)
|
|
130
|
+
const suggestion = taken.includes('default') ? '' : 'default'
|
|
131
|
+
name = await new Promise((resolve) => rl.question(t(`Nombre del perfil (a-z, 0-9, -)${suggestion ? ` [${suggestion}]` : ''}: `, `Profile name (a-z, 0-9, -)${suggestion ? ` [${suggestion}]` : ''}: `), (a) => { rl.close(); resolve(a.trim() || suggestion) }))
|
|
132
|
+
}
|
|
133
|
+
if (!isValidName(name)) die(t(`nombre no válido: «${name}» (usa a-z, 0-9 y -, hasta 32)`, `invalid name: "${name}" (use a-z, 0-9 and -, up to 32)`))
|
|
134
|
+
const { dir } = resolveInstance(LABEL, name)
|
|
135
|
+
if (loadLink(dir)) die(t(`el perfil «${name}» ya está enlazado. Para re-enlazarlo: dotrino-terminal-agent enroll --name ${name}`, `profile "${name}" is already linked. To re-link it: dotrino-terminal-agent enroll --name ${name}`))
|
|
136
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
137
|
+
await linkInteractive(dir)
|
|
138
|
+
console.log(t(`Perfil «${name}» enlazado.`, `Profile "${name}" linked.`))
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Una pregunta y su respuesta, para `ls` y `kill`. */
|
|
142
|
+
function request (conn, msg, type) {
|
|
143
|
+
return new Promise((resolve) => {
|
|
144
|
+
conn.on('message', (m) => { if (m.type === type || m.type === 'fail') resolve(m) })
|
|
145
|
+
conn.send(msg)
|
|
146
|
+
})
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const age = (ms) => {
|
|
150
|
+
const s = Math.round(ms / 1000)
|
|
151
|
+
return s < 60 ? `${s}s` : s < 3600 ? `${Math.round(s / 60)}m` : `${Math.round(s / 3600)}h`
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function list (conn) {
|
|
155
|
+
const { list } = await request(conn, { type: 'list' }, 'consoles')
|
|
156
|
+
if (args.includes('--json')) { console.log(JSON.stringify(list, null, 2)); return }
|
|
157
|
+
if (!list.length) { console.log(t('No hay consolas abiertas.', 'No open consoles.')); return }
|
|
158
|
+
for (const c of list) {
|
|
159
|
+
const remote = c.watchers.filter((w) => w.origin === 'remote').length
|
|
160
|
+
const who = `${c.viewers} ${t('mirando', 'watching')}${remote ? ` (${remote} ${t('desde otro aparato', 'from another device')})` : ''}`
|
|
161
|
+
console.log(` ${c.id} ${c.origin.padEnd(6)} ${age(Date.now() - c.createdAt).padStart(4)} ${who} ${c.title || ''}`)
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** La ventana: la TTY enganchada a una consola del agente. */
|
|
166
|
+
function interactive (conn, first) {
|
|
167
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) die(t('dotrino-terminal necesita una terminal (TTY).', 'dotrino-terminal needs a terminal (TTY).'))
|
|
168
|
+
const out = process.stdout
|
|
169
|
+
let consoleId = null
|
|
170
|
+
let shellTitle = ''
|
|
171
|
+
let remote = new Set()
|
|
172
|
+
let ending = false
|
|
173
|
+
|
|
174
|
+
const showTitle = () => {
|
|
175
|
+
const base = shellTitle || 'Dotrino Terminal'
|
|
176
|
+
const mark = remote.size ? ` ● ${t('abierta desde otro aparato', 'open on another device')}${remote.size > 1 ? ` ×${remote.size}` : ''}` : ''
|
|
177
|
+
out.write(`\x1b]2;${base}${mark}\x07`)
|
|
178
|
+
}
|
|
179
|
+
const onInfo = (info) => {
|
|
180
|
+
if (!info) return
|
|
181
|
+
shellTitle = info.title || ''
|
|
182
|
+
const now = new Set(info.watchers.filter((w) => w.origin === 'remote').map((w) => w.device || '?'))
|
|
183
|
+
const arrived = [...now].some((d) => !remote.has(d))
|
|
184
|
+
remote = now
|
|
185
|
+
if (arrived) out.write('\x07') // la campana: alguien entró desde fuera
|
|
186
|
+
showTitle()
|
|
187
|
+
}
|
|
188
|
+
const filter = titleFilter((title) => { shellTitle = title; showTitle() })
|
|
189
|
+
const size = () => ({ cols: out.columns || 80, rows: out.rows || 24 })
|
|
190
|
+
|
|
191
|
+
const finish = (code, note) => {
|
|
192
|
+
if (ending) return
|
|
193
|
+
ending = true
|
|
194
|
+
try { process.stdin.setRawMode(false) } catch (_) {}
|
|
195
|
+
out.write('\x1b]2;\x07')
|
|
196
|
+
if (note) process.stderr.write(`\r\n${note}\r\n`)
|
|
197
|
+
conn.close()
|
|
198
|
+
printUpdateNotice({ current: VERSION, source: 'npm', pkg: '@dotrino/terminal-agent', how: 'npx @dotrino/terminal-agent@latest' })
|
|
199
|
+
.finally(() => process.exit(code))
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
conn.on('message', (m) => {
|
|
203
|
+
if (m.type === 'out' || m.type === 'replay') { out.write(filter(m.data)); return }
|
|
204
|
+
if (m.type === 'attached') { consoleId = m.id; onInfo(m.console); return }
|
|
205
|
+
if (m.type === 'meta') { onInfo(m.console); return }
|
|
206
|
+
if (m.type === 'exit') { finish(m.code || 0); return }
|
|
207
|
+
if (m.type === 'fail') { finish(1, `dotrino-terminal: ${m.message} (${m.code})`) }
|
|
208
|
+
})
|
|
209
|
+
conn.on('close', () => finish(1, t('dotrino-terminal: el agente se detuvo.', 'dotrino-terminal: the agent stopped.')))
|
|
210
|
+
|
|
211
|
+
process.stdin.setRawMode(true)
|
|
212
|
+
process.stdin.resume()
|
|
213
|
+
const decoder = new StringDecoder('utf8')
|
|
214
|
+
let prefixed = false
|
|
215
|
+
process.stdin.on('data', (buf) => {
|
|
216
|
+
// Ctrl+] abre el atajo: «d» suelta la consola, otro Ctrl+] manda uno literal, y cualquier
|
|
217
|
+
// otra tecla pasa tal cual, con su Ctrl+] delante. Las dos teclas pueden llegar juntas.
|
|
218
|
+
let send = ''
|
|
219
|
+
for (const ch of decoder.write(buf)) {
|
|
220
|
+
if (prefixed) {
|
|
221
|
+
prefixed = false
|
|
222
|
+
if (ch === 'd') {
|
|
223
|
+
if (send) conn.send({ type: 'input', data: send })
|
|
224
|
+
conn.send({ type: 'detach' })
|
|
225
|
+
return finish(0, t(`Consola soltada. Para volver: dotrino-terminal attach ${consoleId}`, `Console detached. To return: dotrino-terminal attach ${consoleId}`))
|
|
226
|
+
}
|
|
227
|
+
send += ch === DETACH_PREFIX ? ch : DETACH_PREFIX + ch
|
|
228
|
+
} else if (ch === DETACH_PREFIX) prefixed = true
|
|
229
|
+
else send += ch
|
|
230
|
+
}
|
|
231
|
+
if (send) conn.send({ type: 'input', data: send })
|
|
232
|
+
})
|
|
233
|
+
out.on('resize', () => conn.send({ type: 'resize', ...size() }))
|
|
234
|
+
// La ventana se cerró: el agente ve caer la conexión y mata la consola que abrimos.
|
|
235
|
+
for (const sig of ['SIGHUP', 'SIGTERM']) process.on(sig, () => { conn.close(); process.exit(0) })
|
|
236
|
+
|
|
237
|
+
conn.send({ ...first, ...size() })
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
try {
|
|
241
|
+
if (cmd === 'profiles') { await profiles(); process.exit(0) }
|
|
242
|
+
if (cmd === 'link') { await link(); process.exit(0) }
|
|
243
|
+
const dir = opt('--dir') || dataDir(opt('--name'))
|
|
244
|
+
const conn = await agent(dir)
|
|
245
|
+
if (cmd === 'ls' || cmd === 'list') { await list(conn); conn.close() } else if (cmd === 'kill') {
|
|
246
|
+
if (!args[1]) die(t('falta el id: dotrino-terminal kill <id>', 'missing id: dotrino-terminal kill <id>'))
|
|
247
|
+
conn.send({ type: 'kill', id: args[1] })
|
|
248
|
+
const r = await Promise.race([request(conn, { type: 'list' }, 'consoles'), new Promise((resolve) => setTimeout(resolve, 1000))])
|
|
249
|
+
if (r?.type === 'fail') die(`dotrino-terminal: ${r.message} (${r.code})`)
|
|
250
|
+
conn.close()
|
|
251
|
+
} else if (cmd === 'attach') {
|
|
252
|
+
if (!args[1]) die(t('falta el id: dotrino-terminal attach <id> (mira «dotrino-terminal ls»)', 'missing id: dotrino-terminal attach <id> (see "dotrino-terminal ls")'))
|
|
253
|
+
interactive(conn, { type: 'attach', id: args[1] })
|
|
254
|
+
} else if (cmd === 'open') {
|
|
255
|
+
// Como cualquier terminal: la consola abre en la carpeta donde estás (o en `--cwd`).
|
|
256
|
+
interactive(conn, { type: 'open', cwd: path.resolve(opt('--cwd') || process.cwd()) })
|
|
257
|
+
} else die(t(`orden desconocida: ${cmd} (mira --help)`, `unknown command: ${cmd} (see --help)`))
|
|
258
|
+
} catch (e) {
|
|
259
|
+
if (e !== HOLD) { try { die(`dotrino-terminal: ${e.message}`) } catch (_) {} }
|
|
260
|
+
}
|
package/consoles.js
CHANGED
|
@@ -27,18 +27,27 @@ export const REPLAY_CHUNK = 64 * 1024
|
|
|
27
27
|
const randomId = () => [...crypto.getRandomValues(new Uint8Array(8))].map((x) => x.toString(16).padStart(2, '0')).join('')
|
|
28
28
|
|
|
29
29
|
class Console {
|
|
30
|
-
constructor ({ id, pty, cols, rows }) {
|
|
30
|
+
constructor ({ id, pty, cols, rows, origin }) {
|
|
31
31
|
this.id = id
|
|
32
32
|
this.pty = pty
|
|
33
|
+
this.origin = origin // 'local' (una ventana de esta máquina) | 'remote' (otro aparato)
|
|
34
|
+
this.title = '' // el que pone la shell (OSC 0/2), para reconocerla en la lista
|
|
33
35
|
this.cols = cols
|
|
34
36
|
this.rows = rows
|
|
35
37
|
this.createdAt = Date.now()
|
|
36
38
|
this.lastActive = Date.now()
|
|
37
|
-
this.viewers = new Set() // sesiones mirando: { onOut(data), onExit(code) }
|
|
39
|
+
this.viewers = new Set() // sesiones mirando: { onOut(data), onExit(code), onMeta?(info), origin, device? }
|
|
38
40
|
this.exited = false
|
|
39
41
|
this.screen = new Terminal({ cols, rows, scrollback: SCROLLBACK, allowProposedApi: true })
|
|
40
42
|
this.serializer = new SerializeAddon()
|
|
41
43
|
this.screen.loadAddon(this.serializer)
|
|
44
|
+
this.screen.onTitleChange((t) => { this.title = String(t).slice(0, 200); this._meta() })
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Avisa a todos los que miran de que cambió quién mira o el título. */
|
|
48
|
+
_meta () {
|
|
49
|
+
const info = this.info()
|
|
50
|
+
for (const v of this.viewers) v.onMeta?.(info)
|
|
42
51
|
}
|
|
43
52
|
|
|
44
53
|
/** Lo que sale de la shell: a la pantalla sin pantalla y a quien esté mirando. */
|
|
@@ -75,21 +84,27 @@ class Console {
|
|
|
75
84
|
this.viewers.delete(buffering)
|
|
76
85
|
this.viewers.add(viewer)
|
|
77
86
|
resolve(snapshot + pending.join(''))
|
|
87
|
+
this._meta()
|
|
78
88
|
})
|
|
79
89
|
})
|
|
80
90
|
}
|
|
81
91
|
|
|
82
|
-
detach (viewer) { this.viewers.delete(viewer) }
|
|
92
|
+
detach (viewer) { if (this.viewers.delete(viewer)) this._meta() }
|
|
83
93
|
|
|
94
|
+
/**
|
|
95
|
+
* `watchers` dice QUIÉN mira: una ventana de esta máquina o un aparato de la cuenta (con
|
|
96
|
+
* su pubkey). Es lo que deja a la ventana local avisar de que alguien entró desde fuera.
|
|
97
|
+
*/
|
|
84
98
|
info () {
|
|
85
|
-
|
|
99
|
+
const watchers = [...this.viewers].filter((v) => v.origin).map((v) => ({ origin: v.origin, device: v.device || null }))
|
|
100
|
+
return { id: this.id, origin: this.origin, title: this.title, cols: this.cols, rows: this.rows, createdAt: this.createdAt, lastActive: this.lastActive, viewers: this.viewers.size, watchers }
|
|
86
101
|
}
|
|
87
102
|
}
|
|
88
103
|
|
|
89
104
|
/** Las consolas de este agente. */
|
|
90
105
|
export class ConsoleHub {
|
|
91
106
|
/**
|
|
92
|
-
* @param {{ spawn:(opts:{cols:number,rows:number})=>any }} opts
|
|
107
|
+
* @param {{ spawn:(opts:{cols:number,rows:number,cwd:string|null})=>any }} opts
|
|
93
108
|
* `spawn` lanza la shell (un PTY con `onData`, `onExit`, `write`, `resize`, `kill`).
|
|
94
109
|
*/
|
|
95
110
|
constructor ({ spawn }) {
|
|
@@ -97,10 +112,10 @@ export class ConsoleHub {
|
|
|
97
112
|
this.consoles = new Map()
|
|
98
113
|
}
|
|
99
114
|
|
|
100
|
-
create ({ cols = 80, rows = 24 } = {}) {
|
|
115
|
+
create ({ cols = 80, rows = 24, origin = 'remote', cwd = null } = {}) {
|
|
101
116
|
const id = randomId()
|
|
102
|
-
const pty = this._spawn({ cols, rows })
|
|
103
|
-
const c = new Console({ id, pty, cols, rows })
|
|
117
|
+
const pty = this._spawn({ cols, rows, cwd })
|
|
118
|
+
const c = new Console({ id, pty, cols, rows, origin })
|
|
104
119
|
pty.onData((d) => c._out(d))
|
|
105
120
|
pty.onExit(({ exitCode }) => {
|
|
106
121
|
c.exited = true
|
package/index.js
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* el navegador solo las suelta, y cualquier aparato de la cuenta puede volver a ellas.
|
|
11
11
|
*
|
|
12
12
|
* Payloads de dominio (van cifrados dentro de la sesión, el proxio no los ve):
|
|
13
|
-
* cliente → agente: { type:'list' } · { type:'open', cols, rows } ·
|
|
13
|
+
* cliente → agente: { type:'list' } · { type:'open', cols, rows, cwd? } ·
|
|
14
14
|
* { type:'attach', id, cols, rows } · { type:'detach' } ·
|
|
15
15
|
* { type:'input', data } · { type:'resize', cols, rows } ·
|
|
16
16
|
* { type:'close' } (mata la consola enganchada) · { type:'kill', id }
|
|
@@ -18,16 +18,22 @@
|
|
|
18
18
|
* { type:'replay', id, data, last } · { type:'out', data } ·
|
|
19
19
|
* { type:'exit', code } · { type:'fail', code, message }
|
|
20
20
|
*/
|
|
21
|
+
import fs from 'node:fs'
|
|
21
22
|
import os from 'node:os'
|
|
23
|
+
import path from 'node:path'
|
|
22
24
|
import { createRequire } from 'node:module'
|
|
23
25
|
import { startRemoteAgent } from '@dotrino/remote-agent/agent'
|
|
24
|
-
import { dataDir, LABEL } from './link.js'
|
|
26
|
+
import { dataDir, loadLink, LABEL } from './link.js'
|
|
25
27
|
import { ConsoleHub, REPLAY_CHUNK } from './consoles.js'
|
|
28
|
+
import { listenLocal } from './local.js'
|
|
26
29
|
|
|
27
30
|
const require = createRequire(import.meta.url)
|
|
28
31
|
|
|
29
32
|
export { LABEL }
|
|
30
33
|
|
|
34
|
+
/** Cada cuánto mira un agente sin enlazar si ya lo enlazaron. */
|
|
35
|
+
export const LINK_POLL_MS = 2000
|
|
36
|
+
|
|
31
37
|
export function loadPty () {
|
|
32
38
|
// Binarios PREBUILT (Linux/macOS/Windows, sin toolchain), API idéntica a node-pty.
|
|
33
39
|
try { return require('@homebridge/node-pty-prebuilt-multiarch') } catch (e) {
|
|
@@ -35,30 +41,50 @@ export function loadPty () {
|
|
|
35
41
|
}
|
|
36
42
|
}
|
|
37
43
|
|
|
44
|
+
const isDir = (p) => {
|
|
45
|
+
try { return typeof p === 'string' && path.isAbsolute(p) && fs.statSync(p).isDirectory() } catch (_) { return false }
|
|
46
|
+
}
|
|
47
|
+
|
|
38
48
|
/** Las consolas de este agente, sobre el PTY. Exportada para las pruebas. */
|
|
39
49
|
export function makeHub (pty, opts = {}) {
|
|
40
50
|
const shell = opts.shell || process.env.SHELL || (process.platform === 'win32' ? 'powershell.exe' : 'bash')
|
|
41
51
|
return new ConsoleHub({
|
|
42
|
-
spawn: ({ cols, rows }) => pty.spawn(shell, [], {
|
|
52
|
+
spawn: ({ cols, rows, cwd }) => pty.spawn(shell, [], {
|
|
43
53
|
name: 'xterm-256color', cols, rows,
|
|
44
|
-
cwd: os.homedir(), env: { ...process.env, TERM: 'xterm-256color' }
|
|
54
|
+
cwd: cwd || os.homedir(), env: { ...process.env, TERM: 'xterm-256color' }
|
|
45
55
|
})
|
|
46
56
|
})
|
|
47
57
|
}
|
|
48
58
|
|
|
49
59
|
/**
|
|
50
|
-
* Atiende una sesión cifrada
|
|
51
|
-
*
|
|
60
|
+
* Atiende una sesión: la cifrada de un aparato remoto, o la de una ventana de esta máquina
|
|
61
|
+
* (`local.js`, por el socket). Una sesión mira UNA consola a la vez.
|
|
62
|
+
*
|
|
63
|
+
* Al irse la sesión, la consola se SUELTA — salvo que sea una ventana local que la abrió
|
|
64
|
+
* ella: cerrar la ventana mata su shell, como en cualquier terminal. Una ventana que solo
|
|
65
|
+
* se enganchó a una consola ajena, o que la soltó a propósito (`detach`), no mata nada.
|
|
66
|
+
*
|
|
67
|
+
* Tamaño con varios mirando: manda el último que se enganchó o escribió (como tmux).
|
|
52
68
|
* Exportada para las pruebas.
|
|
69
|
+
*
|
|
70
|
+
* @param {object} session
|
|
71
|
+
* @param {ConsoleHub} hub
|
|
72
|
+
* @param {{ origin?: 'local'|'remote' }} [opts]
|
|
53
73
|
*/
|
|
54
|
-
export function serveSession (session, hub) {
|
|
74
|
+
export function serveSession (session, hub, { origin = 'remote' } = {}) {
|
|
55
75
|
let current = null
|
|
76
|
+
let owned = null // la consola que esta ventana local abrió
|
|
77
|
+
let size = { cols: 80, rows: 24 }
|
|
56
78
|
const viewer = {
|
|
79
|
+
origin,
|
|
80
|
+
device: session.device || null,
|
|
57
81
|
onOut: (data) => { session.send({ type: 'out', data }) },
|
|
58
|
-
onExit: (code) => { current = null; session.send({ type: 'exit', code }) }
|
|
82
|
+
onExit: (code) => { current = null; owned = null; session.send({ type: 'exit', code }) },
|
|
83
|
+
onMeta: (info) => { session.send({ type: 'meta', console: info }) }
|
|
59
84
|
}
|
|
60
85
|
const release = () => { if (current) { current.detach(viewer); current = null } }
|
|
61
86
|
const fail = (code, message) => session.send({ type: 'fail', code, message })
|
|
87
|
+
const takeSize = (msg) => { if (msg.cols && msg.rows) size = { cols: msg.cols, rows: msg.rows } }
|
|
62
88
|
|
|
63
89
|
async function attachTo (c, { fresh }) {
|
|
64
90
|
release()
|
|
@@ -68,32 +94,55 @@ export function serveSession (session, hub) {
|
|
|
68
94
|
for (let i = 0; i < snapshot.length || i === 0; i += REPLAY_CHUNK) {
|
|
69
95
|
await session.send({ type: 'replay', id: c.id, data: snapshot.slice(i, i + REPLAY_CHUNK), last: i + REPLAY_CHUNK >= snapshot.length })
|
|
70
96
|
}
|
|
71
|
-
await session.send({ type: 'attached', id: c.id, fresh })
|
|
97
|
+
await session.send({ type: 'attached', id: c.id, fresh, console: c.info() })
|
|
72
98
|
}
|
|
73
99
|
|
|
74
100
|
session.on('message', (msg) => {
|
|
75
101
|
if (!msg || typeof msg !== 'object') return
|
|
76
102
|
if (msg.type === 'list') { session.send({ type: 'consoles', list: hub.list() }); return }
|
|
77
|
-
if (msg.type === 'open') {
|
|
103
|
+
if (msg.type === 'open') {
|
|
104
|
+
takeSize(msg)
|
|
105
|
+
// `cwd`: dónde abre la shell (la carpeta de la ventana que la pide). Si no existe, se
|
|
106
|
+
// dice: abrir en otra carpeta sin avisar haría que un comando corra donde no toca.
|
|
107
|
+
if (msg.cwd != null && !isDir(msg.cwd)) return fail('bad-cwd', `not a directory: ${msg.cwd}`)
|
|
108
|
+
const c = hub.create({ ...size, origin, cwd: msg.cwd || null })
|
|
109
|
+
if (origin === 'local') owned = c
|
|
110
|
+
attachTo(c, { fresh: true })
|
|
111
|
+
return
|
|
112
|
+
}
|
|
78
113
|
if (msg.type === 'attach') {
|
|
79
114
|
const c = hub.get(msg.id)
|
|
80
115
|
if (!c) return fail('no-console', 'that console no longer exists')
|
|
81
|
-
|
|
116
|
+
takeSize(msg)
|
|
117
|
+
c.resize(size.cols, size.rows)
|
|
82
118
|
attachTo(c, { fresh: false })
|
|
83
119
|
return
|
|
84
120
|
}
|
|
85
|
-
if (msg.type === 'detach') { release(); return }
|
|
86
|
-
if (msg.type === 'input') {
|
|
87
|
-
|
|
121
|
+
if (msg.type === 'detach') { owned = null; release(); return }
|
|
122
|
+
if (msg.type === 'input') {
|
|
123
|
+
if (!current) return
|
|
124
|
+
if (current.cols !== size.cols || current.rows !== size.rows) current.resize(size.cols, size.rows)
|
|
125
|
+
current.write(String(msg.data ?? ''))
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
if (msg.type === 'resize') { takeSize(msg); current?.resize(size.cols, size.rows); return }
|
|
88
129
|
if (msg.type === 'close') { if (current) hub.kill(current.id); return }
|
|
89
130
|
if (msg.type === 'kill') { if (!hub.kill(msg.id)) fail('no-console', 'that console no longer exists') }
|
|
90
131
|
})
|
|
91
|
-
session.on('close',
|
|
132
|
+
session.on('close', () => {
|
|
133
|
+
const mine = owned && owned === current ? owned : null
|
|
134
|
+
release()
|
|
135
|
+
if (mine) hub.kill(mine.id)
|
|
136
|
+
})
|
|
92
137
|
}
|
|
93
138
|
|
|
94
139
|
/**
|
|
95
|
-
* Arranca el agente
|
|
96
|
-
*
|
|
140
|
+
* Arranca el agente: las consolas, el socket de las ventanas de esta máquina y, si la
|
|
141
|
+
* máquina está enlazada con la bóveda, la parte remota (`startRemoteAgent`).
|
|
142
|
+
*
|
|
143
|
+
* Sin enlace el agente atiende SOLO a las ventanas locales: una terminal tiene que abrir
|
|
144
|
+
* aunque no haya bóveda (ninguna app puede exigirla). Lo que no hay es acceso desde otros
|
|
145
|
+
* aparatos, y se dice en `remote: null`.
|
|
97
146
|
*
|
|
98
147
|
* @param {object} [opts]
|
|
99
148
|
* @param {string} [opts.dir] dónde vive el enlace (default dataDir()).
|
|
@@ -101,19 +150,49 @@ export function serveSession (session, hub) {
|
|
|
101
150
|
* @param {string} [opts.shell] shell a lanzar (default $SHELL).
|
|
102
151
|
* @param {boolean} [opts.quiet]
|
|
103
152
|
* @param {()=>void} [opts.onRevoked]
|
|
153
|
+
* @param {(remote:object)=>void} [opts.onLinked] se enlazó mientras corría y ya atiende a otros aparatos.
|
|
154
|
+
* @param {(e:Error)=>void} [opts.onLinkError] se enlazó, pero la parte remota no arrancó.
|
|
155
|
+
* @returns {Promise<{ consoles: ConsoleHub, socket: string, remote: object|null, machineId: string|null, close: ()=>void }>}
|
|
104
156
|
*/
|
|
105
157
|
export async function startAgent (opts = {}) {
|
|
158
|
+
const dir = opts.dir || dataDir()
|
|
106
159
|
const hub = makeHub(loadPty(), opts)
|
|
107
|
-
const
|
|
160
|
+
const local = await listenLocal({ dir, serve: (session) => serveSession(session, hub, { origin: 'local' }) })
|
|
161
|
+
let remote = null
|
|
162
|
+
let stopped = false
|
|
163
|
+
const startRemote = () => startRemoteAgent({
|
|
108
164
|
label: LABEL,
|
|
109
|
-
dir
|
|
165
|
+
dir,
|
|
110
166
|
proxyUrl: opts.proxyUrl,
|
|
111
167
|
quiet: opts.quiet,
|
|
112
168
|
onRevoked: () => { hub.killAll(); opts.onRevoked?.() },
|
|
113
|
-
onSession: (session) => serveSession(session, hub)
|
|
169
|
+
onSession: (session) => serveSession(session, hub, { origin: 'remote' })
|
|
114
170
|
})
|
|
171
|
+
let watcher = null
|
|
172
|
+
if (loadLink(dir)) {
|
|
173
|
+
try { remote = await startRemote() } catch (e) { local.close(); throw e }
|
|
174
|
+
} else {
|
|
175
|
+
// Sin enlace: se mira cada poco si aparece (`dotrino-terminal link` desde una ventana).
|
|
176
|
+
// Al aparecer se enciende la parte remota SIN reiniciar, así las consolas abiertas siguen.
|
|
177
|
+
watcher = setInterval(() => {
|
|
178
|
+
if (!loadLink(dir)) return
|
|
179
|
+
clearInterval(watcher); watcher = null
|
|
180
|
+
startRemote().then((r) => {
|
|
181
|
+
if (stopped) { r.close(); return }
|
|
182
|
+
remote = r
|
|
183
|
+
opts.onLinked?.(r)
|
|
184
|
+
}).catch((e) => opts.onLinkError?.(e))
|
|
185
|
+
}, LINK_POLL_MS)
|
|
186
|
+
watcher.unref()
|
|
187
|
+
}
|
|
115
188
|
// Parar el agente sí mata las consolas: sin agente no hay quién las atienda.
|
|
116
|
-
return {
|
|
189
|
+
return {
|
|
190
|
+
consoles: hub,
|
|
191
|
+
socket: local.path,
|
|
192
|
+
get remote () { return remote },
|
|
193
|
+
get machineId () { return remote?.machineId || null },
|
|
194
|
+
close: () => { stopped = true; if (watcher) clearInterval(watcher); hub.killAll(); local.close(); remote?.close() }
|
|
195
|
+
}
|
|
117
196
|
}
|
|
118
197
|
|
|
119
198
|
export default { startAgent, LABEL }
|
package/link.js
CHANGED
|
@@ -4,8 +4,12 @@
|
|
|
4
4
|
* enrolamiento headless del ecosistema), y DÓNDE vive lo decide el estándar
|
|
5
5
|
* `@dotrino/remote-agent/instances`: `~/.dotrino/agent/terminal-agent/<nombre>/`.
|
|
6
6
|
*/
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
import readline from 'node:readline'
|
|
7
10
|
import { enroll as raEnroll, loadLink as raLoad, parseQr } from '@dotrino/remote-agent/link'
|
|
8
|
-
import { resolveInstance } from '@dotrino/remote-agent/instances'
|
|
11
|
+
import { resolveInstance, instancesRoot, isValidName, DEFAULT_NAME } from '@dotrino/remote-agent/instances'
|
|
12
|
+
import { deviceInfo } from '@dotrino/vault/device-info'
|
|
9
13
|
|
|
10
14
|
export { parseQr }
|
|
11
15
|
|
|
@@ -30,3 +34,57 @@ export const loadLink = (dir = dataDir()) => raLoad(dir)
|
|
|
30
34
|
export function enroll ({ qr, dir = dataDir(), label = LABEL, onChallenge }) {
|
|
31
35
|
return raEnroll({ qr, dir, label, onChallenge })
|
|
32
36
|
}
|
|
37
|
+
|
|
38
|
+
function ask (q) {
|
|
39
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
40
|
+
return new Promise((resolve) => rl.question(q, (a) => { rl.close(); resolve(a) }))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Enlaza la carpeta `dir` con la bóveda, preguntando en la terminal: la invitación de
|
|
45
|
+
* `dotrino-vault pair` y, mientras se espera, el código que hay que aprobar. Lo usan el
|
|
46
|
+
* agente (`dotrino-terminal-agent enroll`) y las ventanas (`dotrino-terminal link`).
|
|
47
|
+
*/
|
|
48
|
+
export async function linkInteractive (dir) {
|
|
49
|
+
if (!process.stdin.isTTY) {
|
|
50
|
+
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.')
|
|
51
|
+
}
|
|
52
|
+
console.log('Enlazar esta máquina con tu bóveda.')
|
|
53
|
+
console.log('En el PC de tu bóveda corre `dotrino-vault pair` y copia la invitación.\n')
|
|
54
|
+
const qr = await parseQr(await ask('Pega la invitación y pulsa Enter:\n> '))
|
|
55
|
+
console.log('\nConectando…')
|
|
56
|
+
await enroll({
|
|
57
|
+
qr,
|
|
58
|
+
dir,
|
|
59
|
+
onChallenge: ({ deviceId, code }) => {
|
|
60
|
+
console.log('\n Escribe ESTE código en tu bóveda para aprobar esta máquina:')
|
|
61
|
+
console.log(` código: ${code}`)
|
|
62
|
+
console.log(` máquina: ${deviceId}`)
|
|
63
|
+
console.log(` (en el PC de la bóveda: dotrino-vault approve ${code})\n`)
|
|
64
|
+
console.log(' Esperando la aprobación…')
|
|
65
|
+
}
|
|
66
|
+
})
|
|
67
|
+
console.log('\n ✓ Máquina enlazada.\n')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Los PERFILES de esta máquina: cada carpeta de agente de terminal, enlazada o no. Uno sin
|
|
72
|
+
* enlazar atiende solo a las ventanas locales. Si no hay ninguno, sale `default` sin enlazar,
|
|
73
|
+
* que es el que usa `dotrino-terminal` a secas.
|
|
74
|
+
*
|
|
75
|
+
* @returns {Promise<Array<{ name: string, dir: string, linked: boolean, id: string|null, vault: string|null, scope: string[] }>>}
|
|
76
|
+
*/
|
|
77
|
+
export async function listProfiles () {
|
|
78
|
+
const root = instancesRoot(LABEL)
|
|
79
|
+
let names = []
|
|
80
|
+
try { names = fs.readdirSync(root).filter((n) => isValidName(n) && fs.statSync(path.join(root, n)).isDirectory()) } catch (_) {}
|
|
81
|
+
if (!names.length) names = [DEFAULT_NAME]
|
|
82
|
+
const out = []
|
|
83
|
+
for (const name of names.sort()) {
|
|
84
|
+
const dir = path.join(root, name)
|
|
85
|
+
const link = raLoad(dir)
|
|
86
|
+
const info = link ? await deviceInfo(link) : null
|
|
87
|
+
out.push({ name, dir, linked: !!info, id: info?.id || null, vault: info?.vault || null, scope: info?.scope || [] })
|
|
88
|
+
}
|
|
89
|
+
return out
|
|
90
|
+
}
|
package/local.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* local.js — las ventanas de ESTA máquina hablan con el agente por un socket local.
|
|
3
|
+
*
|
|
4
|
+
* Es el primer escalón del transporte del ecosistema: si la otra punta está en la misma
|
|
5
|
+
* máquina, no se sale a la red. Por aquí no pasa ni el proxio ni el cifrado de sesión: el
|
|
6
|
+
* socket vive en la carpeta del enlace (`~/.dotrino/agent/terminal-agent/<nombre>/`, 0700)
|
|
7
|
+
* y solo lo abre el usuario dueño de esa carpeta — el mismo que ya puede leer el enlace.
|
|
8
|
+
*
|
|
9
|
+
* El protocolo es EL MISMO que el de las sesiones remotas (`serveSession`), en JSON por
|
|
10
|
+
* líneas: una ventana local y el navegador de otro aparato son dos clientes de las mismas
|
|
11
|
+
* consolas.
|
|
12
|
+
*/
|
|
13
|
+
import fs from 'node:fs'
|
|
14
|
+
import net from 'node:net'
|
|
15
|
+
import path from 'node:path'
|
|
16
|
+
|
|
17
|
+
export const SOCKET_NAME = 'terminal.sock'
|
|
18
|
+
export const socketPath = (dir) => path.join(dir, SOCKET_NAME)
|
|
19
|
+
/** Lo más largo que admite la ruta de un socket Unix (macOS: 104 bytes con el nulo; Linux: 108). */
|
|
20
|
+
export const MAX_SOCKET_PATH = 103
|
|
21
|
+
|
|
22
|
+
function checkLength (file) {
|
|
23
|
+
if (Buffer.byteLength(file) > MAX_SOCKET_PATH) {
|
|
24
|
+
throw Object.assign(new Error(`socket path too long (${Buffer.byteLength(file)} bytes, max ${MAX_SOCKET_PATH}): ${file}. Use a shorter DOTRINO_AGENT_HOME`), { code: 'ESOCKPATH' })
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Mensajes JSON por líneas sobre un socket. */
|
|
29
|
+
function framed (sock, onMessage) {
|
|
30
|
+
let buf = ''
|
|
31
|
+
sock.setEncoding('utf8')
|
|
32
|
+
sock.on('data', (chunk) => {
|
|
33
|
+
buf += chunk
|
|
34
|
+
let i
|
|
35
|
+
while ((i = buf.indexOf('\n')) >= 0) {
|
|
36
|
+
const line = buf.slice(0, i); buf = buf.slice(i + 1)
|
|
37
|
+
if (!line) continue
|
|
38
|
+
let msg
|
|
39
|
+
try { msg = JSON.parse(line) } catch { continue }
|
|
40
|
+
onMessage(msg)
|
|
41
|
+
}
|
|
42
|
+
})
|
|
43
|
+
return (obj) => { if (!sock.destroyed) sock.write(JSON.stringify(obj) + '\n') }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** ¿Contesta alguien en ese socket? */
|
|
47
|
+
function answers (file) {
|
|
48
|
+
return new Promise((resolve) => {
|
|
49
|
+
const s = net.connect(file)
|
|
50
|
+
s.once('connect', () => { s.destroy(); resolve(true) })
|
|
51
|
+
s.once('error', () => resolve(false))
|
|
52
|
+
})
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Escucha las ventanas locales. Cada conexión es una sesión con la misma forma que las de
|
|
57
|
+
* `@dotrino/remote-agent` (`send`, `on('message'|'close')`), así que `serve` es
|
|
58
|
+
* `serveSession` tal cual.
|
|
59
|
+
*
|
|
60
|
+
* @param {{ dir: string, serve: (session: object) => void }} opts
|
|
61
|
+
* @returns {Promise<{ path: string, close: () => void }>}
|
|
62
|
+
*/
|
|
63
|
+
export async function listenLocal ({ dir, serve }) {
|
|
64
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
65
|
+
fs.chmodSync(dir, 0o700)
|
|
66
|
+
const file = socketPath(dir)
|
|
67
|
+
checkLength(file)
|
|
68
|
+
if (fs.existsSync(file)) {
|
|
69
|
+
if (await answers(file)) throw Object.assign(new Error(`another agent is already listening on ${file}`), { code: 'EALREADY' })
|
|
70
|
+
fs.rmSync(file) // lo dejó un agente que murió sin limpiar
|
|
71
|
+
}
|
|
72
|
+
const socks = new Set()
|
|
73
|
+
const server = net.createServer((sock) => {
|
|
74
|
+
socks.add(sock)
|
|
75
|
+
sock.on('close', () => socks.delete(sock))
|
|
76
|
+
const h = { message: [], close: [] }
|
|
77
|
+
let closed = false
|
|
78
|
+
const session = {
|
|
79
|
+
device: null,
|
|
80
|
+
send: async (payload) => write(payload),
|
|
81
|
+
on (ev, cb) { h[ev]?.push(cb); return this }
|
|
82
|
+
}
|
|
83
|
+
const write = framed(sock, (msg) => { for (const cb of h.message) { try { cb(msg) } catch (_) {} } })
|
|
84
|
+
const bye = () => { if (closed) return; closed = true; for (const cb of h.close) { try { cb() } catch (_) {} } }
|
|
85
|
+
sock.on('close', bye)
|
|
86
|
+
sock.on('error', bye)
|
|
87
|
+
serve(session)
|
|
88
|
+
})
|
|
89
|
+
await new Promise((resolve, reject) => {
|
|
90
|
+
server.once('error', reject)
|
|
91
|
+
server.listen(file, () => { server.off('error', reject); resolve() })
|
|
92
|
+
})
|
|
93
|
+
fs.chmodSync(file, 0o600)
|
|
94
|
+
return {
|
|
95
|
+
path: file,
|
|
96
|
+
// Parar el agente cierra también las ventanas: sin agente no queda shell que mirar.
|
|
97
|
+
close: () => { server.close(); for (const s of socks) s.destroy(); try { fs.rmSync(file) } catch (_) {} }
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Se conecta al agente de esta máquina. Rechaza con `code: 'ENOAGENT'` si no hay ninguno
|
|
103
|
+
* escuchando en esa carpeta.
|
|
104
|
+
*
|
|
105
|
+
* @param {string} dir la carpeta del enlace del agente.
|
|
106
|
+
* @returns {Promise<{ send:(obj:object)=>void, on:(ev:'message'|'close', cb:Function)=>void, close:()=>void }>}
|
|
107
|
+
*/
|
|
108
|
+
export function connectLocal (dir) {
|
|
109
|
+
const file = socketPath(dir)
|
|
110
|
+
checkLength(file)
|
|
111
|
+
return new Promise((resolve, reject) => {
|
|
112
|
+
const sock = net.connect(file)
|
|
113
|
+
const h = { message: [], close: [] }
|
|
114
|
+
const send = framed(sock, (msg) => { for (const cb of h.message) cb(msg) })
|
|
115
|
+
let connected = false
|
|
116
|
+
sock.once('connect', () => {
|
|
117
|
+
connected = true
|
|
118
|
+
sock.on('close', () => { for (const cb of h.close) cb() })
|
|
119
|
+
resolve({ send, on: (ev, cb) => { h[ev]?.push(cb) }, close: () => sock.end() })
|
|
120
|
+
})
|
|
121
|
+
// Tras conectar, un error acaba en 'close', que ya se avisa arriba.
|
|
122
|
+
sock.on('error', (e) => {
|
|
123
|
+
if (!connected) reject(Object.assign(new Error(`no terminal agent is listening on ${file}`), { code: 'ENOAGENT', cause: e }))
|
|
124
|
+
})
|
|
125
|
+
})
|
|
126
|
+
}
|
package/package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/terminal-agent",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"description": "Dotrino Terminal: las ventanas de esta máquina (dotrino-terminal) y su agente, que deja abrir esas mismas consolas desde los otros aparatos de tu cuenta, cifrado punto a punto.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
|
-
"dotrino-terminal-agent": "bin/cli.js"
|
|
7
|
+
"dotrino-terminal-agent": "bin/cli.js",
|
|
8
|
+
"dotrino-terminal": "bin/terminal.js"
|
|
8
9
|
},
|
|
9
10
|
"exports": {
|
|
10
11
|
".": "./index.js"
|
|
@@ -13,6 +14,8 @@
|
|
|
13
14
|
"index.js",
|
|
14
15
|
"consoles.js",
|
|
15
16
|
"link.js",
|
|
17
|
+
"local.js",
|
|
18
|
+
"title.js",
|
|
16
19
|
"bin"
|
|
17
20
|
],
|
|
18
21
|
"scripts": {
|
package/title.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* title.js — separa el título que pone la shell (OSC 0/1/2) del resto de la salida.
|
|
3
|
+
*
|
|
4
|
+
* La ventana local compone su propio título: el de la shell y, si alguien la tiene abierta
|
|
5
|
+
* desde otro aparato, la marca que lo dice. Si el título de la shell llegara tal cual a la
|
|
6
|
+
* terminal, taparía esa marca al siguiente prompt — y es un aviso que no se puede perder.
|
|
7
|
+
*
|
|
8
|
+
* Las secuencias llegan partidas entre trozos, así que lo que queda a medias se guarda para
|
|
9
|
+
* el siguiente. Una secuencia sin terminar que crece más allá de `MAX_PENDING` no es un
|
|
10
|
+
* título: se suelta tal cual.
|
|
11
|
+
*/
|
|
12
|
+
const MAX_PENDING = 4096
|
|
13
|
+
const TITLE = /^([012]);([\s\S]*)$/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @param {(title: string) => void} onTitle
|
|
17
|
+
* @returns {(chunk: string) => string} lo que hay que escribir en la terminal
|
|
18
|
+
*/
|
|
19
|
+
export function titleFilter (onTitle) {
|
|
20
|
+
let carry = ''
|
|
21
|
+
return (chunk) => {
|
|
22
|
+
let data = carry + chunk
|
|
23
|
+
carry = ''
|
|
24
|
+
let out = ''
|
|
25
|
+
let pos = 0
|
|
26
|
+
while (pos < data.length) {
|
|
27
|
+
const start = data.indexOf('\x1b]', pos)
|
|
28
|
+
if (start < 0) {
|
|
29
|
+
// Un ESC al final puede ser el principio de una secuencia que sigue en el próximo trozo.
|
|
30
|
+
if (data.endsWith('\x1b')) { out += data.slice(pos, -1); carry = '\x1b' } else out += data.slice(pos)
|
|
31
|
+
break
|
|
32
|
+
}
|
|
33
|
+
out += data.slice(pos, start)
|
|
34
|
+
const bel = data.indexOf('\x07', start)
|
|
35
|
+
const st = data.indexOf('\x1b\\', start)
|
|
36
|
+
let end = -1; let len = 0
|
|
37
|
+
if (bel >= 0 && (st < 0 || bel < st)) { end = bel; len = 1 } else if (st >= 0) { end = st; len = 2 }
|
|
38
|
+
if (end < 0) {
|
|
39
|
+
const rest = data.slice(start)
|
|
40
|
+
if (rest.length > MAX_PENDING) out += rest; else carry = rest
|
|
41
|
+
break
|
|
42
|
+
}
|
|
43
|
+
const body = data.slice(start + 2, end)
|
|
44
|
+
const m = TITLE.exec(body)
|
|
45
|
+
if (m) onTitle(m[2]); else out += data.slice(start, end + len)
|
|
46
|
+
pos = end + len
|
|
47
|
+
}
|
|
48
|
+
return out
|
|
49
|
+
}
|
|
50
|
+
}
|