@dotrino/terminal-agent 0.46.4 → 0.47.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 +17 -3
- package/bin/cli.js +24 -1
- package/bin/terminal.js +15 -12
- package/consoles.js +43 -2
- package/editors.js +3 -1
- package/index.js +12 -8
- package/local.js +94 -24
- package/package.json +1 -1
- package/service.js +94 -7
package/README.md
CHANGED
|
@@ -77,7 +77,7 @@ La clave de una máquina se recuerda solo en memoria, cuando una ventana la escr
|
|
|
77
77
|
Solo esta máquina necesita la 0.38: las otras atienden como a cualquier aparato.
|
|
78
78
|
|
|
79
79
|
`dotrino-terminal vscode` escribe el perfil de terminal «Dotrino» en el `settings.json` de VS Code,
|
|
80
|
-
VS Code Insiders, VSCodium y Cursor (los que haya, Linux y
|
|
80
|
+
VS Code Insiders, VSCodium y Cursor (los que haya, Linux, macOS y Windows) y lo deja por defecto; conserva
|
|
81
81
|
los comentarios y el resto del archivo (`editors.js`, con `jsonc-parser`). El perfil apunta a Node
|
|
82
82
|
y al script por su ruta, porque un editor lanzado desde el escritorio no hereda el PATH de la shell:
|
|
83
83
|
al cambiar de Node se vuelve a correr. En esa terminal (`TERM_PROGRAM=vscode`, sin `--tag`) cerrar
|
|
@@ -179,9 +179,23 @@ En la app de escritorio: menú **Perfil → Poner o cambiar la clave… / Quitar
|
|
|
179
179
|
`dotrino-terminal service install [--name <n>]` escribe una unidad de systemd **del usuario**
|
|
180
180
|
(`~/.config/systemd/user/dotrino-terminal-agent-<perfil>.service`, `Restart=always`, con el `PATH`
|
|
181
181
|
de quien instala) y pide `loginctl enable-linger` para que arranque sin sesión; en macOS, un
|
|
182
|
-
LaunchAgent (`~/Library/LaunchAgents/com.dotrino.terminal-agent.<perfil>.plist`)
|
|
182
|
+
LaunchAgent (`~/Library/LaunchAgents/com.dotrino.terminal-agent.<perfil>.plist`); en Windows, el valor
|
|
183
|
+
`DotrinoTerminalAgent-<perfil>` en `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`, que al iniciar
|
|
184
|
+
sesión corre `dotrino-terminal-agent supervise`: se vuelve a lanzar sin ventana y levanta el agente cada
|
|
185
|
+
vez que sale (`supervisor.pid` en la carpeta del perfil). Ni el Programador de tareas ni un servicio de
|
|
186
|
+
Windows: los dos piden derechos que una cuenta normal no tiene. Es de usuario
|
|
183
187
|
para que el agente se siga actualizando solo (§15): con quien lo levante ya puede reiniciarse.
|
|
184
188
|
Un agente que ya corre por su cuenta no se para (cerraría sus consolas): el servicio queda
|
|
185
189
|
habilitado, y `dotrino-terminal`, cuando no encuentra agente, arranca el servicio en vez de
|
|
186
190
|
levantar uno propio. Código en `service.js`; probado con systemd en un contenedor de Fedora,
|
|
187
|
-
macOS solo con
|
|
191
|
+
Windows de punta a punta en el runner `windows-latest` (`test/windows.test.mjs`), macOS solo con
|
|
192
|
+
pruebas unitarias.
|
|
193
|
+
|
|
194
|
+
## Windows
|
|
195
|
+
|
|
196
|
+
El agente corre en Windows (≥ 0.47.0) y abre **PowerShell** (`powershell.exe`; otra con `--shell`).
|
|
197
|
+
Las ventanas locales no van por un socket Unix sino por una **tubería con nombre**: su nombre es
|
|
198
|
+
aleatorio y, junto con una llave, queda en `terminal.pipe` dentro de la carpeta del perfil. La ventana
|
|
199
|
+
manda la llave en su primera línea (`{ type:'local-auth', key }`) y sin ella el agente corta sin
|
|
200
|
+
contestar: la lista de tuberías la ve cualquier usuario de la máquina, la carpeta del perfil no.
|
|
201
|
+
La app de escritorio (`desktop/`) todavía no tiene versión para Windows.
|
package/bin/cli.js
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* dotrino-terminal-agent info [--name <n>] # qué aparato es: su ID, su bóveda, sus permisos
|
|
9
9
|
* dotrino-terminal-agent update [--name <n>] [--approval on|off] [--notify on|off]
|
|
10
10
|
* # cómo se actualiza este agente (CONVENCIONES §15)
|
|
11
|
+
* dotrino-terminal-agent supervise --name <n> # Windows: lo lanza el servicio al iniciar sesión
|
|
11
12
|
*
|
|
12
13
|
* Las ventanas de esta máquina se abren con `dotrino-terminal` (bin/terminal.js), que habla
|
|
13
14
|
* con este agente por un socket local y lo levanta si no está corriendo.
|
|
@@ -69,6 +70,27 @@ if (cmd === 'update') {
|
|
|
69
70
|
process.exit(r.ok ? 0 : 2)
|
|
70
71
|
}
|
|
71
72
|
|
|
73
|
+
// `supervise` (Windows): lo lanza la entrada de `HKCU\…\Run` que pone `dotrino-terminal service
|
|
74
|
+
// install`. Al iniciar sesión Windows lo abre CON ventana: se vuelve a lanzar sin ella y sale.
|
|
75
|
+
if (cmd === 'supervise') {
|
|
76
|
+
const { supervise } = await import('../service.js')
|
|
77
|
+
const { realpathSync } = await import('node:fs')
|
|
78
|
+
const { fileURLToPath } = await import('node:url')
|
|
79
|
+
const name = opt('--name')
|
|
80
|
+
if (!name) { console.error('uso: dotrino-terminal-agent supervise --name <n>'); process.exit(2) }
|
|
81
|
+
const cli = realpathSync(fileURLToPath(import.meta.url))
|
|
82
|
+
if (!process.env.DOTRINO_SUPERVISOR) {
|
|
83
|
+
const { spawn } = await import('node:child_process')
|
|
84
|
+
spawn(process.execPath, [cli, 'supervise', '--name', name], { detached: true, windowsHide: true, stdio: 'ignore', env: { ...process.env, DOTRINO_SUPERVISOR: '1' } }).unref()
|
|
85
|
+
process.exit(0)
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
const s = supervise({ name, dir: dataDir(name), cli })
|
|
89
|
+
const bye = () => { s.stop(); process.exit(0) }
|
|
90
|
+
process.on('SIGINT', bye); process.on('SIGTERM', bye)
|
|
91
|
+
} catch (e) { console.error('error:', e.message); process.exit(1) }
|
|
92
|
+
}
|
|
93
|
+
|
|
72
94
|
// `info`: la pieza común del ecosistema (`@dotrino/vault/device-info`). Lo que se viene a
|
|
73
95
|
// mirar es el ID, para buscarlo en el acta.
|
|
74
96
|
if (cmd === 'info') {
|
|
@@ -86,7 +108,8 @@ if (cmd === 'info') {
|
|
|
86
108
|
process.exit(0)
|
|
87
109
|
}
|
|
88
110
|
|
|
89
|
-
|
|
111
|
+
// El supervisor de arriba sigue vivo con su hijo: aquí no se corre otro agente.
|
|
112
|
+
if (cmd !== 'supervise') try {
|
|
90
113
|
const dir = opt('--dir') || dataDir(opt('--name'))
|
|
91
114
|
// Antes de nada, también de enlazar: dos procesos con el mismo enlace son la misma llave.
|
|
92
115
|
process.on('exit', lockInstance(dir))
|
package/bin/terminal.js
CHANGED
|
@@ -218,12 +218,13 @@ async function agent (dir) {
|
|
|
218
218
|
// Si este perfil tiene servicio (`dotrino-terminal service install`), el agente es el del
|
|
219
219
|
// sistema: se arranca ese, no uno propio al lado. `--dir` fuerza una carpeta sin perfil.
|
|
220
220
|
const { startService } = await import('../service.js')
|
|
221
|
-
|
|
221
|
+
const cli = fs.realpathSync(fileURLToPath(new URL('./cli.js', import.meta.url)))
|
|
222
|
+
if (!(!opt('--dir') && !process.env.DOTRINO_TERMINAL_DIR && startService({ name: path.basename(dir), dir, cli }))) {
|
|
222
223
|
const fd = fs.openSync(log, 'a', 0o600)
|
|
223
|
-
const cli = fileURLToPath(new URL('./cli.js', import.meta.url))
|
|
224
224
|
const extra = opt('--name') ? ['--name', opt('--name')] : []
|
|
225
225
|
// Sin TTY: si la máquina no está enlazada, el agente atiende solo a las ventanas locales.
|
|
226
|
-
|
|
226
|
+
// `windowsHide`: en Windows un proceso aparte abre su propia ventana de consola.
|
|
227
|
+
const child = spawn(process.execPath, [cli, ...extra], { detached: true, windowsHide: true, stdio: ['ignore', fd, fd], env: process.env })
|
|
227
228
|
child.unref()
|
|
228
229
|
fs.closeSync(fd)
|
|
229
230
|
}
|
|
@@ -261,7 +262,7 @@ function vscode () {
|
|
|
261
262
|
try { done = configureEditors({ profile }) } catch (e) {
|
|
262
263
|
if (e.code === 'no-editor') die(t('no encontré VS Code, VS Code Insiders, VSCodium ni Cursor en esta cuenta.', 'could not find VS Code, VS Code Insiders, VSCodium or Cursor in this account.'))
|
|
263
264
|
if (e.code === 'bad-settings') die(t(`no se pudo leer la configuración y no se tocó nada: ${e.message}`, `could not read the settings and nothing was changed: ${e.message}`))
|
|
264
|
-
if (e.code === 'unsupported-platform') die(t('esto solo está para Linux y
|
|
265
|
+
if (e.code === 'unsupported-platform') die(t('esto solo está para Linux, macOS y Windows.', 'this is only available on Linux, macOS and Windows.'))
|
|
265
266
|
throw e
|
|
266
267
|
}
|
|
267
268
|
for (const d of done) {
|
|
@@ -447,7 +448,7 @@ async function restart () {
|
|
|
447
448
|
}
|
|
448
449
|
if (inside && !args.includes('--detached-step')) {
|
|
449
450
|
const self = fileURLToPath(import.meta.url)
|
|
450
|
-
spawn(process.execPath, [self, ...args.filter((a) => a !== '--yes'), '--yes', '--detached-step'], { detached: true, stdio: 'ignore', env: process.env }).unref()
|
|
451
|
+
spawn(process.execPath, [self, ...args.filter((a) => a !== '--yes'), '--yes', '--detached-step'], { detached: true, windowsHide: true, stdio: 'ignore', env: process.env }).unref()
|
|
451
452
|
console.log(t('Reiniciando. Esta consola se va a cerrar.', 'Restarting. This console is about to close.'))
|
|
452
453
|
return
|
|
453
454
|
}
|
|
@@ -462,7 +463,7 @@ async function restart () {
|
|
|
462
463
|
await new Promise((r) => setTimeout(r, 100))
|
|
463
464
|
}
|
|
464
465
|
let service = false
|
|
465
|
-
try { service = serviceStatus({ name: a.name }).installed } catch (e) { if (e.code !== 'no-user-systemd' && e.code !== 'unsupported-platform') throw e }
|
|
466
|
+
try { service = serviceStatus({ name: a.name, dir }).installed } catch (e) { if (e.code !== 'no-user-systemd' && e.code !== 'unsupported-platform') throw e }
|
|
466
467
|
console.log(service
|
|
467
468
|
? t(`«${a.name}»: agente detenido (${a.consoles} consola(s) cerradas). Su servicio lo vuelve a levantar con la ${VERSION}.`, `"${a.name}": agent stopped (${a.consoles} console(s) closed). Its service starts it again with ${VERSION}.`)
|
|
468
469
|
: t(`«${a.name}»: agente detenido (${a.consoles} consola(s) cerradas). Arranca con la ${VERSION} al abrir una ventana.`, `"${a.name}": agent stopped (${a.consoles} console(s) closed). It starts with ${VERSION} when you open a window.`))
|
|
@@ -494,7 +495,7 @@ async function network () {
|
|
|
494
495
|
console.log(t('\nBytes del contenido, sin las cabeceras de la red. Acumulados desde que arrancó el agente.', '\nContent bytes, without network headers. Accumulated since the agent started.'))
|
|
495
496
|
}
|
|
496
497
|
|
|
497
|
-
/** El agente como servicio del usuario (systemd en Linux, launchd en macOS). */
|
|
498
|
+
/** El agente como servicio del usuario (systemd en Linux, launchd en macOS, `HKCU\…\Run` en Windows). */
|
|
498
499
|
async function service () {
|
|
499
500
|
const action = args[1]
|
|
500
501
|
if (!['install', 'uninstall', 'status'].includes(action)) die(t('uso: dotrino-terminal service install|uninstall|status [--name <perfil>]', 'usage: dotrino-terminal service install|uninstall|status [--name <profile>]'))
|
|
@@ -505,11 +506,11 @@ async function service () {
|
|
|
505
506
|
const { installService, uninstallService, serviceStatus } = await import('../service.js')
|
|
506
507
|
const explain = (e) => {
|
|
507
508
|
if (e.code === 'no-user-systemd') die(t('esta sesión no tiene systemd de usuario, que es donde se pone el servicio. No se instaló nada.', 'this session has no systemd user manager, which is where the service goes. Nothing was installed.'))
|
|
508
|
-
if (e.code === 'unsupported-platform') die(t('esto solo está para Linux y
|
|
509
|
+
if (e.code === 'unsupported-platform') die(t('esto solo está para Linux, macOS y Windows.', 'this is only available on Linux, macOS and Windows.'))
|
|
509
510
|
throw e
|
|
510
511
|
}
|
|
511
512
|
let st
|
|
512
|
-
try { st = serviceStatus({ name }) } catch (e) { explain(e) }
|
|
513
|
+
try { st = serviceStatus({ name, dir }) } catch (e) { explain(e) }
|
|
513
514
|
const pid = Number((() => { try { return fs.readFileSync(path.join(dir, 'agent.pid'), 'utf8') } catch (_) { return '' } })())
|
|
514
515
|
const running = !!pid && alive(pid)
|
|
515
516
|
|
|
@@ -517,6 +518,7 @@ async function service () {
|
|
|
517
518
|
if (!st.installed) console.log(t(`El perfil «${name}» no tiene servicio: su agente arranca cuando abres una ventana. Para ponerlo: dotrino-terminal service install --name ${name}`, `Profile "${name}" has no service: its agent starts when you open a window. To add it: dotrino-terminal service install --name ${name}`))
|
|
518
519
|
else if (st.active) console.log(t(`Servicio puesto y corriendo (${st.file}).`, `Service installed and running (${st.file}).`))
|
|
519
520
|
else if (running) console.log(t(`Servicio puesto (${st.file}). Ahora corre un agente que levantó una ventana; el servicio toma el relevo cuando ese termine o al próximo arranque.`, `Service installed (${st.file}). Right now an agent started by a window is running; the service takes over when it ends or at the next start.`))
|
|
521
|
+
else if (st.kind === 'run-key') console.log(t(`Servicio puesto pero parado (${st.file}). Arranca al abrir una ventana o al iniciar sesión; si falló, mira por qué en ${path.join(dir, 'agent.log')}`, `Service installed but stopped (${st.file}). It starts when you open a window or log in; if it failed, see why in ${path.join(dir, 'agent.log')}`))
|
|
520
522
|
else console.log(t(`Servicio puesto pero parado (${st.file}). Arranca al abrir una ventana; si falló, mira por qué: journalctl --user -u dotrino-terminal-agent-${name}`, `Service installed but stopped (${st.file}). It starts when you open a window; if it failed, see why: journalctl --user -u dotrino-terminal-agent-${name}`))
|
|
521
523
|
return
|
|
522
524
|
}
|
|
@@ -532,6 +534,7 @@ async function service () {
|
|
|
532
534
|
if (r.started) console.log(t('El agente ya corre como servicio.', 'The agent now runs as a service.'))
|
|
533
535
|
else console.log(t('Ahora mismo corre un agente que levantó una ventana, y no se toca para no cerrar sus consolas. El servicio toma el relevo cuando ese termine o al próximo arranque.', 'Right now an agent started by a window is running, and it is left alone so its consoles stay open. The service takes over when it ends or at the next start.'))
|
|
534
536
|
if (r.kind === 'launchd') console.log(t('Arranca solo cuando inicias sesión en esta Mac.', 'It starts by itself when you log in to this Mac.'))
|
|
537
|
+
else if (r.kind === 'run-key') console.log(t('Arranca solo cuando inicias sesión en Windows.', 'It starts by itself when you log in to Windows.'))
|
|
535
538
|
else if (r.boot) console.log(t('Arranca solo al encender la máquina, sin que nadie inicie sesión.', 'It starts by itself when the machine boots, with nobody logged in.'))
|
|
536
539
|
else console.log(t(`Arranca solo cuando inicias sesión. Para que arranque al encender, sin iniciar sesión: sudo loginctl enable-linger ${os.userInfo().username}`, `It starts by itself when you log in. To start at boot, with nobody logged in: sudo loginctl enable-linger ${os.userInfo().username}`))
|
|
537
540
|
if (!loadLink(dir)) console.log(t(`Este perfil no está enlazado: el servicio atiende solo a las ventanas de esta máquina. Para abrir sus consolas desde otros aparatos: dotrino-terminal link --name ${name}`, `This profile is not linked: the service only serves this machine's windows. To open its consoles from other devices: dotrino-terminal link --name ${name}`))
|
|
@@ -551,7 +554,7 @@ async function service () {
|
|
|
551
554
|
}
|
|
552
555
|
}
|
|
553
556
|
let r
|
|
554
|
-
try { r = uninstallService({ name }) } catch (e) { explain(e) }
|
|
557
|
+
try { r = uninstallService({ name, dir }) } catch (e) { explain(e) }
|
|
555
558
|
console.log(t(`Servicio del perfil «${name}» quitado (${r.file}). El perfil y su enlace siguen igual: el agente vuelve a arrancar cuando abras una ventana.`, `Service for profile "${name}" removed (${r.file}). The profile and its link are untouched: the agent starts again when you open a window.`))
|
|
556
559
|
}
|
|
557
560
|
|
|
@@ -675,7 +678,7 @@ async function rename () {
|
|
|
675
678
|
}
|
|
676
679
|
if (running && inside && !args.includes('--detached-step')) {
|
|
677
680
|
const self = fileURLToPath(import.meta.url)
|
|
678
|
-
spawn(process.execPath, [self, 'rename', from, to, '--yes', '--detached-step'], { detached: true, stdio: 'ignore', env: process.env }).unref()
|
|
681
|
+
spawn(process.execPath, [self, 'rename', from, to, '--yes', '--detached-step'], { detached: true, windowsHide: true, stdio: 'ignore', env: process.env }).unref()
|
|
679
682
|
console.log(t(`Renombrando «${from}» → «${to}». Esta consola es de ese perfil y se va a cerrar; la ventana sigue en «${to}».`,
|
|
680
683
|
`Renaming "${from}" → "${to}". This console belongs to that profile and is about to close; the window continues in "${to}".`))
|
|
681
684
|
return
|
|
@@ -707,7 +710,7 @@ function samePath (a, b) {
|
|
|
707
710
|
|
|
708
711
|
/** La preferencia de la app de escritorio: el último perfil elegido en su menú. */
|
|
709
712
|
function lastProfileFile () {
|
|
710
|
-
const base = process.env.XDG_CONFIG_HOME || path.join(
|
|
713
|
+
const base = process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config')
|
|
711
714
|
return path.join(base, 'dotrino-terminal', 'last-profile')
|
|
712
715
|
}
|
|
713
716
|
|
package/consoles.js
CHANGED
|
@@ -23,8 +23,49 @@ const { SerializeAddon } = require('@xterm/addon-serialize')
|
|
|
23
23
|
|
|
24
24
|
/** Líneas de historial que se guardan y se devuelven al volver. */
|
|
25
25
|
export const SCROLLBACK = 1000
|
|
26
|
-
/**
|
|
27
|
-
|
|
26
|
+
/**
|
|
27
|
+
* Lo más que puede medir, EN JSON, lo que va en un mensaje al aparato. El tope de verdad es el
|
|
28
|
+
* del canal directo: werift (el agente) y libwebrtc (Android, iOS, Chrome) se quedan en 64 KiB
|
|
29
|
+
* por mensaje cuando el otro no dice más, y uno mayor NO sale por ahí: el pilar lo manda por el
|
|
30
|
+
* proxio, que da la vuelta por internet, y llega DESPUÉS del mensaje pequeño que sí fue directo.
|
|
31
|
+
* Con trozos de 64 KB (122 KB sellados) el historial llegaba desordenado: la pantalla quedaba a
|
|
32
|
+
* medio historial, o con la pantalla pintada dos veces (2026-10-15, la tablet). Lo sellado es el
|
|
33
|
+
* JSON en base64 (×1,34) más el sobre: 40 KB de JSON son unos 55 KB por el canal.
|
|
34
|
+
*/
|
|
35
|
+
export const PIECE_JSON_MAX = 40 * 1024
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Corta `data` en trozos que, puestos en JSON, no pasen de `max` bytes. Mide lo que cuesta cada
|
|
39
|
+
* carácter al serializarlo (un ESC son 6, una comilla 2, un acento 2 o 3) en vez de contar
|
|
40
|
+
* caracteres: una pantalla llena de colores es casi todo escapes. No parte un par sustituto.
|
|
41
|
+
* Devuelve al menos un trozo (vacío si `data` está vacío).
|
|
42
|
+
* @param {string} data
|
|
43
|
+
* @param {number} [max]
|
|
44
|
+
* @returns {string[]}
|
|
45
|
+
*/
|
|
46
|
+
export function pieces (data, max = PIECE_JSON_MAX) {
|
|
47
|
+
const out = []
|
|
48
|
+
let start = 0; let cost = 0
|
|
49
|
+
for (let i = 0; i < data.length; i++) {
|
|
50
|
+
const c = data.charCodeAt(i)
|
|
51
|
+
let w
|
|
52
|
+
if (c < 0x20) w = (c === 8 || c === 9 || c === 10 || c === 12 || c === 13) ? 2 : 6
|
|
53
|
+
else if (c === 0x22 || c === 0x5c) w = 2
|
|
54
|
+
else if (c < 0x80) w = 1
|
|
55
|
+
else if (c < 0x800) w = 2
|
|
56
|
+
else if (c >= 0xd800 && c <= 0xdfff) w = 2 // cada mitad del par: 4 bytes entre las dos
|
|
57
|
+
else w = 3
|
|
58
|
+
if (cost + w > max && i > start) {
|
|
59
|
+
// No partir un par sustituto: si lo anterior es la mitad alta, se queda con la baja.
|
|
60
|
+
const prev = data.charCodeAt(i - 1)
|
|
61
|
+
const cut = (prev >= 0xd800 && prev <= 0xdbff) ? i - 1 : i
|
|
62
|
+
if (cut > start) { out.push(data.slice(start, cut)); start = cut; cost = 0; i = cut - 1; continue }
|
|
63
|
+
}
|
|
64
|
+
cost += w
|
|
65
|
+
}
|
|
66
|
+
out.push(data.slice(start))
|
|
67
|
+
return out
|
|
68
|
+
}
|
|
28
69
|
|
|
29
70
|
// ¿ESTÁ TRABAJANDO? Lo que el panel enseña con un color por consola. UNA regla, sin leer lo que
|
|
30
71
|
// dice la pantalla ni el título (dueño, 2026-10-06): si el TÍTULO o el CONTENIDO cambian de
|
package/editors.js
CHANGED
|
@@ -30,16 +30,18 @@ export const EDITORS = [
|
|
|
30
30
|
/** Un error con `code`: quien lo recibe decide por el código, no por la frase. */
|
|
31
31
|
const fail = (code, message) => Object.assign(new Error(message), { code })
|
|
32
32
|
|
|
33
|
-
/** `linux`
|
|
33
|
+
/** `linux`, `osx` o `windows`: el sufijo de las claves de terminal de VS Code. Otro sistema no se atiende. */
|
|
34
34
|
export function platformKey (platform = process.platform) {
|
|
35
35
|
if (platform === 'linux') return 'linux'
|
|
36
36
|
if (platform === 'darwin') return 'osx'
|
|
37
|
+
if (platform === 'win32') return 'windows'
|
|
37
38
|
throw fail('unsupported-platform', `unsupported platform: ${platform}`)
|
|
38
39
|
}
|
|
39
40
|
|
|
40
41
|
/** Donde los editores guardan lo del usuario. */
|
|
41
42
|
export function configBase ({ platform = process.platform, home = os.homedir(), env = process.env } = {}) {
|
|
42
43
|
if (platform === 'darwin') return path.join(home, 'Library', 'Application Support')
|
|
44
|
+
if (platform === 'win32') return env.APPDATA || path.join(home, 'AppData', 'Roaming')
|
|
43
45
|
return env.XDG_CONFIG_HOME || path.join(home, '.config')
|
|
44
46
|
}
|
|
45
47
|
|
package/index.js
CHANGED
|
@@ -40,7 +40,7 @@ import { startRemoteAgent } from '@dotrino/remote-agent/agent'
|
|
|
40
40
|
import { dataDir, loadLink, LABEL } from './link.js'
|
|
41
41
|
import { listTransports, netReport } from '@dotrino/proxy-client'
|
|
42
42
|
import { shortId } from './far.js'
|
|
43
|
-
import { ConsoleHub,
|
|
43
|
+
import { ConsoleHub, pieces, isTyped } from './consoles.js'
|
|
44
44
|
import { listenLocal } from './local.js'
|
|
45
45
|
import { makeGate } from './access.js'
|
|
46
46
|
import { makeFar } from './far.js'
|
|
@@ -117,7 +117,8 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
|
|
|
117
117
|
origin,
|
|
118
118
|
device: session.device || null,
|
|
119
119
|
// Con el `id` de la consola: lo que llega tarde de una consola que ya se dejó, el cliente lo tira.
|
|
120
|
-
|
|
120
|
+
// En trozos que quepan en el canal directo (`pieces`): un `cat` largo llega de golpe en 64 KB.
|
|
121
|
+
onOut: (data) => { const id = current ? current.id : null; for (const d of pieces(data)) session.send({ type: 'out', id, data: d }) },
|
|
121
122
|
// `closedBy: 'other'`: la cerró otra pantalla (no esta, ni la shell por su cuenta).
|
|
122
123
|
onExit: (code, why) => { current = null; session.send({ type: 'exit', code, ...(why?.byOther ? { closedBy: 'other' } : {}) }) },
|
|
123
124
|
onMeta: (info) => { session.send({ type: 'meta', console: info }) }
|
|
@@ -155,11 +156,13 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
|
|
|
155
156
|
// Volver a engancharse tras una reconexión (`keep`) no es abrir ni cambiarse: no toca el tamaño.
|
|
156
157
|
// Pero si el tamaño era de esta misma pantalla, lo sigue siendo (y se le sigue el teclado, el giro).
|
|
157
158
|
if (!keep) c.take(viewer); else c.resume(viewer)
|
|
158
|
-
// La pantalla va en trozos
|
|
159
|
-
//
|
|
160
|
-
|
|
159
|
+
// La pantalla va en trozos que quepan en el canal directo (`pieces`: lo que no cabe da la
|
|
160
|
+
// vuelta por el proxio y llega tarde). Si entre trozo y trozo la sesión pidió otra consola,
|
|
161
|
+
// esta ya no es la suya: lo que falta no se manda.
|
|
162
|
+
const parts = pieces(snapshot)
|
|
163
|
+
for (let i = 0; i < parts.length; i++) {
|
|
161
164
|
if (current !== c) return
|
|
162
|
-
await session.send({ type: 'replay', id: c.id, data:
|
|
165
|
+
await session.send({ type: 'replay', id: c.id, data: parts[i], last: i === parts.length - 1 })
|
|
163
166
|
}
|
|
164
167
|
if (current !== c) return
|
|
165
168
|
await session.send({ type: 'attached', id: c.id, fresh, console: c.info() })
|
|
@@ -178,9 +181,10 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
|
|
|
178
181
|
if (full == null || current !== c) return
|
|
179
182
|
// Cada trozo vuelve a mirar: el historial de A seguía saliendo entero después de cambiarse a
|
|
180
183
|
// B, y como empieza por un reinicio de la terminal, A tapaba a B en la pantalla (2026-10-14).
|
|
181
|
-
|
|
184
|
+
const parts = pieces(full)
|
|
185
|
+
for (let i = 0; i < parts.length; i++) {
|
|
182
186
|
if (current !== c) return
|
|
183
|
-
await session.send({ type: 'replay', id: c.id, data:
|
|
187
|
+
await session.send({ type: 'replay', id: c.id, data: parts[i], last: i === parts.length - 1 })
|
|
184
188
|
}
|
|
185
189
|
}
|
|
186
190
|
|
package/local.js
CHANGED
|
@@ -9,13 +9,28 @@
|
|
|
9
9
|
* El protocolo es EL MISMO que el de las sesiones remotas (`serveSession`), en JSON por
|
|
10
10
|
* líneas: una ventana local y el navegador de otro aparato son dos clientes de las mismas
|
|
11
11
|
* consolas.
|
|
12
|
+
*
|
|
13
|
+
* En Windows no hay sockets Unix: es una TUBERÍA CON NOMBRE (`\\.\pipe\…`). Esas viven en un
|
|
14
|
+
* espacio de nombres de toda la máquina, no en la carpeta, así que el permiso de la carpeta no
|
|
15
|
+
* las protege. Dos cosas lo suplen, y las dos salen de un archivo que solo lee el usuario
|
|
16
|
+
* (`terminal.pipe`, en la carpeta del enlace):
|
|
17
|
+
*
|
|
18
|
+
* · el NOMBRE de la tubería es aleatorio: nadie puede crearla antes que el agente para
|
|
19
|
+
* hacerse pasar por él, porque no sabe cómo se va a llamar;
|
|
20
|
+
* · una LLAVE que la ventana manda en su primera línea. La lista de tuberías la ve cualquiera,
|
|
21
|
+
* y sin la llave el agente corta la conexión sin atender nada.
|
|
12
22
|
*/
|
|
13
23
|
import fs from 'node:fs'
|
|
14
24
|
import net from 'node:net'
|
|
15
25
|
import path from 'node:path'
|
|
26
|
+
import crypto from 'node:crypto'
|
|
16
27
|
|
|
17
28
|
export const SOCKET_NAME = 'terminal.sock'
|
|
18
29
|
export const socketPath = (dir) => path.join(dir, SOCKET_NAME)
|
|
30
|
+
/** Windows: el archivo que dice cómo se llama la tubería del agente y con qué llave se entra. */
|
|
31
|
+
export const PIPE_FILE = 'terminal.pipe'
|
|
32
|
+
export const pipeFile = (dir) => path.join(dir, PIPE_FILE)
|
|
33
|
+
const isWindows = (platform) => platform === 'win32'
|
|
19
34
|
/** Lo más largo que admite la ruta de un socket Unix (macOS: 104 bytes con el nulo; Linux: 108). */
|
|
20
35
|
export const MAX_SOCKET_PATH = 103
|
|
21
36
|
|
|
@@ -52,49 +67,95 @@ function answers (file) {
|
|
|
52
67
|
})
|
|
53
68
|
}
|
|
54
69
|
|
|
70
|
+
/** Windows: lo apuntado por el agente que escucha (o escuchó) en esa carpeta. `null` si no hay. */
|
|
71
|
+
function readPipe (dir) {
|
|
72
|
+
let text
|
|
73
|
+
try { text = fs.readFileSync(pipeFile(dir), 'utf8') } catch (e) { if (e.code === 'ENOENT') return null; throw e }
|
|
74
|
+
const rec = JSON.parse(text)
|
|
75
|
+
if (typeof rec?.pipe !== 'string' || typeof rec?.key !== 'string') throw Object.assign(new Error(`${pipeFile(dir)} is malformed`), { code: 'EBADPIPE' })
|
|
76
|
+
return rec
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** La sesión de una conexión: misma forma que las de `@dotrino/remote-agent`. */
|
|
80
|
+
function sessionOf (sock, serve, key) {
|
|
81
|
+
const h = { message: [], close: [] }
|
|
82
|
+
let closed = false
|
|
83
|
+
let allowed = !key
|
|
84
|
+
const session = {
|
|
85
|
+
device: null,
|
|
86
|
+
send: async (payload) => { if (allowed) write(payload) },
|
|
87
|
+
on (ev, cb) { h[ev]?.push(cb); return this }
|
|
88
|
+
}
|
|
89
|
+
const write = framed(sock, (msg) => {
|
|
90
|
+
// Windows: la primera línea es la llave. Cualquier otra cosa corta, sin contestar.
|
|
91
|
+
if (!allowed) {
|
|
92
|
+
const got = Buffer.from(String(msg?.type === 'local-auth' ? msg.key : ''))
|
|
93
|
+
const want = Buffer.from(key)
|
|
94
|
+
if (got.length !== want.length || !crypto.timingSafeEqual(got, want)) { sock.destroy(); return }
|
|
95
|
+
allowed = true
|
|
96
|
+
serve(session)
|
|
97
|
+
return
|
|
98
|
+
}
|
|
99
|
+
for (const cb of h.message) { try { cb(msg) } catch (_) {} }
|
|
100
|
+
})
|
|
101
|
+
const bye = () => { if (closed) return; closed = true; if (allowed) for (const cb of h.close) { try { cb() } catch (_) {} } }
|
|
102
|
+
sock.on('close', bye)
|
|
103
|
+
sock.on('error', bye)
|
|
104
|
+
if (allowed) serve(session)
|
|
105
|
+
}
|
|
106
|
+
|
|
55
107
|
/**
|
|
56
108
|
* Escucha las ventanas locales. Cada conexión es una sesión con la misma forma que las de
|
|
57
109
|
* `@dotrino/remote-agent` (`send`, `on('message'|'close')`), así que `serve` es
|
|
58
110
|
* `serveSession` tal cual.
|
|
59
111
|
*
|
|
60
|
-
* @param {{ dir: string, serve: (session: object) => void }} opts
|
|
112
|
+
* @param {{ dir: string, serve: (session: object) => void, platform?: string }} opts
|
|
61
113
|
* @returns {Promise<{ path: string, close: () => void }>}
|
|
62
114
|
*/
|
|
63
|
-
export async function listenLocal ({ dir, serve }) {
|
|
115
|
+
export async function listenLocal ({ dir, serve, platform = process.platform }) {
|
|
64
116
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
65
117
|
fs.chmodSync(dir, 0o700)
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
if (await answers(
|
|
70
|
-
|
|
118
|
+
let file, key = null
|
|
119
|
+
if (isWindows(platform)) {
|
|
120
|
+
const old = readPipe(dir)
|
|
121
|
+
if (old && await answers(old.pipe)) throw Object.assign(new Error(`another agent is already listening on ${old.pipe}`), { code: 'EALREADY' })
|
|
122
|
+
file = `\\\\.\\pipe\\dotrino-terminal-${crypto.randomBytes(16).toString('hex')}`
|
|
123
|
+
key = crypto.randomBytes(32).toString('hex')
|
|
124
|
+
} else {
|
|
125
|
+
file = socketPath(dir)
|
|
126
|
+
checkLength(file)
|
|
127
|
+
if (fs.existsSync(file)) {
|
|
128
|
+
if (await answers(file)) throw Object.assign(new Error(`another agent is already listening on ${file}`), { code: 'EALREADY' })
|
|
129
|
+
fs.rmSync(file) // lo dejó un agente que murió sin limpiar
|
|
130
|
+
}
|
|
71
131
|
}
|
|
72
132
|
const socks = new Set()
|
|
73
133
|
const server = net.createServer((sock) => {
|
|
74
134
|
socks.add(sock)
|
|
75
135
|
sock.on('close', () => socks.delete(sock))
|
|
76
|
-
|
|
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)
|
|
136
|
+
sessionOf(sock, serve, key)
|
|
88
137
|
})
|
|
89
138
|
await new Promise((resolve, reject) => {
|
|
90
139
|
server.once('error', reject)
|
|
91
140
|
server.listen(file, () => { server.off('error', reject); resolve() })
|
|
92
141
|
})
|
|
93
|
-
|
|
142
|
+
if (key) {
|
|
143
|
+
// Se apunta DESPUÉS de escuchar: quien lo lea encuentra la tubería ya abierta.
|
|
144
|
+
const tmp = pipeFile(dir) + '.tmp'
|
|
145
|
+
fs.writeFileSync(tmp, JSON.stringify({ pipe: file, key }), { mode: 0o600 })
|
|
146
|
+
fs.renameSync(tmp, pipeFile(dir))
|
|
147
|
+
} else {
|
|
148
|
+
fs.chmodSync(file, 0o600)
|
|
149
|
+
}
|
|
150
|
+
const forget = () => {
|
|
151
|
+
if (!key) { try { fs.rmSync(file) } catch (_) {} return }
|
|
152
|
+
// Solo si sigue siendo el nuestro: otro agente pudo tomar la carpeta después.
|
|
153
|
+
try { if (readPipe(dir)?.pipe === file) fs.rmSync(pipeFile(dir)) } catch (_) {}
|
|
154
|
+
}
|
|
94
155
|
return {
|
|
95
156
|
path: file,
|
|
96
157
|
// 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();
|
|
158
|
+
close: () => { server.close(); for (const s of socks) s.destroy(); forget() }
|
|
98
159
|
}
|
|
99
160
|
}
|
|
100
161
|
|
|
@@ -103,11 +164,19 @@ export async function listenLocal ({ dir, serve }) {
|
|
|
103
164
|
* escuchando en esa carpeta.
|
|
104
165
|
*
|
|
105
166
|
* @param {string} dir la carpeta del enlace del agente.
|
|
167
|
+
* @param {{ platform?: string }} [opts]
|
|
106
168
|
* @returns {Promise<{ send:(obj:object)=>void, on:(ev:'message'|'close', cb:Function)=>void, close:()=>void }>}
|
|
107
169
|
*/
|
|
108
|
-
export function connectLocal (dir) {
|
|
109
|
-
|
|
110
|
-
|
|
170
|
+
export function connectLocal (dir, { platform = process.platform } = {}) {
|
|
171
|
+
let file, key = null
|
|
172
|
+
if (isWindows(platform)) {
|
|
173
|
+
const rec = readPipe(dir)
|
|
174
|
+
if (!rec) return Promise.reject(Object.assign(new Error(`no terminal agent is listening in ${dir}`), { code: 'ENOAGENT' }))
|
|
175
|
+
file = rec.pipe; key = rec.key
|
|
176
|
+
} else {
|
|
177
|
+
file = socketPath(dir)
|
|
178
|
+
checkLength(file)
|
|
179
|
+
}
|
|
111
180
|
return new Promise((resolve, reject) => {
|
|
112
181
|
const sock = net.connect(file)
|
|
113
182
|
const h = { message: [], close: [] }
|
|
@@ -115,6 +184,7 @@ export function connectLocal (dir) {
|
|
|
115
184
|
let connected = false
|
|
116
185
|
sock.once('connect', () => {
|
|
117
186
|
connected = true
|
|
187
|
+
if (key) send({ type: 'local-auth', key })
|
|
118
188
|
sock.on('close', () => { for (const cb of h.close) cb() })
|
|
119
189
|
resolve({ send, on: (ev, cb) => { h[ev]?.push(cb) }, close: () => sock.end() })
|
|
120
190
|
})
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/terminal-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.47.0",
|
|
4
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": {
|
package/service.js
CHANGED
|
@@ -8,6 +8,11 @@
|
|
|
8
8
|
* · Linux — una unidad de systemd DEL USUARIO (`~/.config/systemd/user`), sin `sudo`. Con
|
|
9
9
|
* «linger» arranca al encender, antes de que nadie inicie sesión; sin él, al iniciarla.
|
|
10
10
|
* · macOS — un LaunchAgent (`~/Library/LaunchAgents`): arranca al iniciar sesión.
|
|
11
|
+
* · Windows — una entrada en `HKCU\…\Run`: arranca al iniciar sesión, sin administrador.
|
|
12
|
+
* Lanza un SUPERVISOR (`dotrino-terminal-agent supervise`) que se vuelve a abrir sin
|
|
13
|
+
* ventana y levanta el agente cada vez que sale, como `Restart=always`. No es el
|
|
14
|
+
* Programador de tareas porque crear una tarea al iniciar sesión pide derechos que una
|
|
15
|
+
* cuenta normal no tiene, y no es un servicio de Windows porque ese pide administrador.
|
|
11
16
|
*
|
|
12
17
|
* Es de usuario a propósito (CONVENCIONES §15): así el agente se sigue actualizando solo, y
|
|
13
18
|
* con alguien que lo levante ya puede reiniciarse para estrenar la versión nueva.
|
|
@@ -17,7 +22,7 @@
|
|
|
17
22
|
import fs from 'node:fs'
|
|
18
23
|
import os from 'node:os'
|
|
19
24
|
import path from 'node:path'
|
|
20
|
-
import { execFileSync } from 'node:child_process'
|
|
25
|
+
import { execFileSync, spawn as childSpawn } from 'node:child_process'
|
|
21
26
|
|
|
22
27
|
const fail = (code, message) => Object.assign(new Error(message), { code })
|
|
23
28
|
|
|
@@ -32,6 +37,15 @@ export function plistPath (name, home = os.homedir()) {
|
|
|
32
37
|
return path.join(home, 'Library', 'LaunchAgents', `${plistLabel(name)}.plist`)
|
|
33
38
|
}
|
|
34
39
|
|
|
40
|
+
/** Windows: la clave de lo que arranca al iniciar sesión, y el nombre del valor de cada perfil. */
|
|
41
|
+
export const RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
|
|
42
|
+
export const runValue = (name) => `DotrinoTerminalAgent-${name}`
|
|
43
|
+
/** Lo que se apunta en la clave: Node, el CLI y el supervisor del perfil. */
|
|
44
|
+
export const runCommand = ({ name, node, cli }) => `"${node}" "${cli}" supervise --name ${name}`
|
|
45
|
+
export const supervisorPidFile = (dir) => path.join(dir, 'supervisor.pid')
|
|
46
|
+
/** Cuánto espera el supervisor antes de volver a levantar el agente (como `RestartSec`). */
|
|
47
|
+
export const RESTART_MS = 3000
|
|
48
|
+
|
|
35
49
|
/** systemd parte `ExecStart` por espacios: lo que los lleve va entre comillas. */
|
|
36
50
|
const unitArg = (s) => (/[\s"'\\$%]/.test(s) ? `"${s.replace(/[\\"]/g, '\\$&').replace(/%/g, '%%').replace(/\$/g, '$$$$')}"` : s)
|
|
37
51
|
|
|
@@ -103,12 +117,62 @@ const LINGER_DIR = '/var/lib/systemd/linger'
|
|
|
103
117
|
/** ¿Deja este sistema instalar el servicio? Lanza con el motivo si no. */
|
|
104
118
|
function platformOf ({ platform, run }) {
|
|
105
119
|
if (platform === 'darwin') return 'launchd'
|
|
120
|
+
if (platform === 'win32') return 'run-key'
|
|
106
121
|
if (platform !== 'linux') throw fail('unsupported-platform', `there is no service support for ${platform}`)
|
|
107
122
|
// Sin systemd de usuario (un contenedor, WSL sin systemd, otra init) no hay dónde ponerlo.
|
|
108
123
|
if (!quiet(run, 'systemctl', ['--user', 'show-environment']).ok) throw fail('no-user-systemd', 'this session has no systemd user manager')
|
|
109
124
|
return 'systemd'
|
|
110
125
|
}
|
|
111
126
|
|
|
127
|
+
const readPid = (file) => { try { return Number(fs.readFileSync(file, 'utf8')) || 0 } catch (e) { if (e.code === 'ENOENT') return 0; throw e } }
|
|
128
|
+
const alive = (pid) => { try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' } }
|
|
129
|
+
const runKeyFile = (name) => `${RUN_KEY}\\${runValue(name)}`
|
|
130
|
+
const hasRunKey = (name, run) => quiet(run, 'reg', ['query', RUN_KEY, '/v', runValue(name)]).ok
|
|
131
|
+
|
|
132
|
+
/** Windows: lanza el supervisor del perfil, ya sin ventana. */
|
|
133
|
+
function spawnSupervisor ({ name, node, cli, spawn }) {
|
|
134
|
+
const child = spawn(node, [cli, 'supervise', '--name', name], { detached: true, windowsHide: true, stdio: 'ignore', env: { ...process.env, DOTRINO_SUPERVISOR: '1' } })
|
|
135
|
+
child.unref()
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* El supervisor de Windows: levanta el agente del perfil y lo vuelve a levantar cada vez que
|
|
140
|
+
* sale (también cuando se reinicia para estrenar una versión: §15, `DOTRINO_SUPERVISED`).
|
|
141
|
+
* Uno por perfil: si ya hay otro vivo, lanza `already-supervised`.
|
|
142
|
+
*/
|
|
143
|
+
export function supervise ({ name, dir, node = process.execPath, cli, spawn = childSpawn }) {
|
|
144
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
145
|
+
const pidFile = supervisorPidFile(dir)
|
|
146
|
+
const other = readPid(pidFile)
|
|
147
|
+
if (other && other !== process.pid && alive(other)) throw fail('already-supervised', `profile ${name} already has a supervisor (pid ${other})`)
|
|
148
|
+
fs.writeFileSync(pidFile, String(process.pid))
|
|
149
|
+
let stopped = false
|
|
150
|
+
let child = null
|
|
151
|
+
const start = () => {
|
|
152
|
+
const fd = fs.openSync(path.join(dir, 'agent.log'), 'a', 0o600)
|
|
153
|
+
child = spawn(node, [cli, '--name', name, '--local'], { windowsHide: true, stdio: ['ignore', fd, fd], env: { ...process.env, DOTRINO_SUPERVISED: '1' } })
|
|
154
|
+
fs.closeSync(fd)
|
|
155
|
+
child.on('exit', () => { child = null; if (!stopped) setTimeout(start, RESTART_MS) })
|
|
156
|
+
}
|
|
157
|
+
start()
|
|
158
|
+
return {
|
|
159
|
+
stop: () => {
|
|
160
|
+
stopped = true
|
|
161
|
+
try { child?.kill() } catch (_) {}
|
|
162
|
+
try { if (readPid(pidFile) === process.pid) fs.rmSync(pidFile) } catch (_) {}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Windows: para el supervisor y después el agente (matar el supervisor no se lleva al hijo). */
|
|
168
|
+
function stopSupervised (dir) {
|
|
169
|
+
for (const file of [supervisorPidFile(dir), path.join(dir, 'agent.pid')]) {
|
|
170
|
+
const pid = readPid(file)
|
|
171
|
+
if (pid && alive(pid)) process.kill(pid)
|
|
172
|
+
}
|
|
173
|
+
fs.rmSync(supervisorPidFile(dir), { force: true })
|
|
174
|
+
}
|
|
175
|
+
|
|
112
176
|
/**
|
|
113
177
|
* Instala y enciende el servicio del perfil `name`.
|
|
114
178
|
*
|
|
@@ -116,10 +180,16 @@ function platformOf ({ platform, run }) {
|
|
|
116
180
|
* Dos agentes con el mismo enlace son la misma llave, y parar ese cerraría sus consolas: el
|
|
117
181
|
* servicio queda puesto y toma el relevo cuando ese agente termine o al próximo arranque.
|
|
118
182
|
*
|
|
119
|
-
* @returns {{ kind:'systemd'|'launchd', file:string, started:boolean, boot?:boolean, lingerReason?:string }}
|
|
183
|
+
* @returns {{ kind:'systemd'|'launchd'|'run-key', file:string, started:boolean, boot?:boolean, lingerReason?:string }}
|
|
120
184
|
*/
|
|
121
|
-
export function installService ({ name, node = process.execPath, cli, dir, running = false, pathEnv = process.env.PATH || '', platform = process.platform, home = os.homedir(), user = os.userInfo().username, uid = process.getuid?.(), run = execFileSync }) {
|
|
185
|
+
export function installService ({ name, node = process.execPath, cli, dir, running = false, pathEnv = process.env.PATH || '', platform = process.platform, home = os.homedir(), user = os.userInfo().username, uid = process.getuid?.(), run = execFileSync, spawn = childSpawn }) {
|
|
122
186
|
const kind = platformOf({ platform, run })
|
|
187
|
+
if (kind === 'run-key') {
|
|
188
|
+
must(run, 'reg', ['add', RUN_KEY, '/v', runValue(name), '/t', 'REG_SZ', '/d', runCommand({ name, node, cli }), '/f'])
|
|
189
|
+
if (running) return { kind, file: runKeyFile(name), started: false }
|
|
190
|
+
spawnSupervisor({ name, node, cli, spawn })
|
|
191
|
+
return { kind, file: runKeyFile(name), started: true }
|
|
192
|
+
}
|
|
123
193
|
if (kind === 'launchd') {
|
|
124
194
|
const file = plistPath(name, home)
|
|
125
195
|
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
@@ -149,7 +219,13 @@ export function installService ({ name, node = process.execPath, cli, dir, runni
|
|
|
149
219
|
* `dotrino-terminal` cuando no encuentra agente, para no levantar uno propio al lado de un
|
|
150
220
|
* servicio que el sistema arrancaría después con la misma llave.
|
|
151
221
|
*/
|
|
152
|
-
export function startService ({ name, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
|
|
222
|
+
export function startService ({ name, dir, node = process.execPath, cli, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync, spawn = childSpawn }) {
|
|
223
|
+
if (platform === 'win32') {
|
|
224
|
+
if (!hasRunKey(name, run)) return false
|
|
225
|
+
const pid = readPid(supervisorPidFile(dir))
|
|
226
|
+
if (!(pid && alive(pid))) spawnSupervisor({ name, node, cli, spawn })
|
|
227
|
+
return true
|
|
228
|
+
}
|
|
153
229
|
if (platform === 'darwin') {
|
|
154
230
|
const file = plistPath(name, home)
|
|
155
231
|
if (!fs.existsSync(file)) return false
|
|
@@ -164,8 +240,14 @@ export function startService ({ name, platform = process.platform, home = os.hom
|
|
|
164
240
|
}
|
|
165
241
|
|
|
166
242
|
/** Para el servicio y lo quita. El enlace y los ajustes del perfil no se tocan. */
|
|
167
|
-
export function uninstallService ({ name, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
|
|
243
|
+
export function uninstallService ({ name, dir, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
|
|
168
244
|
const kind = platformOf({ platform, run })
|
|
245
|
+
if (kind === 'run-key') {
|
|
246
|
+
if (!hasRunKey(name, run)) return { kind, file: runKeyFile(name), removed: false }
|
|
247
|
+
stopSupervised(dir)
|
|
248
|
+
must(run, 'reg', ['delete', RUN_KEY, '/v', runValue(name), '/f'])
|
|
249
|
+
return { kind, file: runKeyFile(name), removed: true }
|
|
250
|
+
}
|
|
169
251
|
const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
|
|
170
252
|
if (!fs.existsSync(file)) return { kind, file, removed: false }
|
|
171
253
|
if (kind === 'launchd') quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
@@ -176,8 +258,13 @@ export function uninstallService ({ name, platform = process.platform, home = os
|
|
|
176
258
|
}
|
|
177
259
|
|
|
178
260
|
/** ¿Está puesto, y está corriendo ahora bajo el sistema? */
|
|
179
|
-
export function serviceStatus ({ name, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
|
|
261
|
+
export function serviceStatus ({ name, dir, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
|
|
180
262
|
const kind = platformOf({ platform, run })
|
|
263
|
+
if (kind === 'run-key') {
|
|
264
|
+
const installed = hasRunKey(name, run)
|
|
265
|
+
const pid = installed ? readPid(supervisorPidFile(dir)) : 0
|
|
266
|
+
return { kind, file: runKeyFile(name), installed, active: !!pid && alive(pid) }
|
|
267
|
+
}
|
|
181
268
|
const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
|
|
182
269
|
const installed = fs.existsSync(file)
|
|
183
270
|
const active = installed && (kind === 'launchd'
|
|
@@ -186,4 +273,4 @@ export function serviceStatus ({ name, platform = process.platform, home = os.ho
|
|
|
186
273
|
return { kind, file, installed, active }
|
|
187
274
|
}
|
|
188
275
|
|
|
189
|
-
export default { startService, installService, uninstallService, serviceStatus, unitText, plistText, unitName, unitPath, plistLabel, plistPath }
|
|
276
|
+
export default { supervise, runCommand, runValue, RUN_KEY, startService, installService, uninstallService, serviceStatus, unitText, plistText, unitName, unitPath, plistLabel, plistPath }
|