@dotrino/remote-agent 0.36.0 → 0.37.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 +21 -0
- package/package.json +5 -1
- package/src/service.js +442 -0
- package/types/src/service.d.ts +170 -0
package/README.md
CHANGED
|
@@ -42,6 +42,7 @@ Provee lo común — y **solo** eso:
|
|
|
42
42
|
| `@dotrino/remote-agent/discover` | navegador | `listAgentsByLabel`, `probeAgents` |
|
|
43
43
|
| `@dotrino/remote-agent/update` | Node | `startSelfUpdate`, `vaultHooks`: el agente se actualiza solo (CONVENCIONES §15) y se reinicia cuando está libre (0.36.0; necesita `@dotrino/update`) |
|
|
44
44
|
| `@dotrino/remote-agent/instances` | Node | `resolveInstance`, `listInstances`, `lockInstance`, `instancesRoot` |
|
|
45
|
+
| `@dotrino/remote-agent/service` | Node | `makeService`: el agente como servicio del usuario (systemd de usuario o inicio automático del escritorio en Linux, LaunchAgent en macOS, `HKCU\…\Run` + supervisor en Windows). Sin `sudo` (0.37.0) |
|
|
45
46
|
|
|
46
47
|
## Uso
|
|
47
48
|
|
|
@@ -150,6 +151,26 @@ Sin nombre: si no hay ninguno enlazado es `default`; si hay uno, ese; si hay var
|
|
|
150
151
|
para y dice cuáles hay (la misma regla que `dotrino-env`). La raíz común se cambia con
|
|
151
152
|
`DOTRINO_AGENT_HOME`.
|
|
152
153
|
|
|
154
|
+
### Como servicio del usuario (`/service`, 0.37.0)
|
|
155
|
+
|
|
156
|
+
```js
|
|
157
|
+
import { makeService } from '@dotrino/remote-agent/service'
|
|
158
|
+
const svc = makeService({
|
|
159
|
+
id: 'remote-desktop-agent', // dotrino-<id>-<perfil>.service / .desktop, com.dotrino.<id>.<perfil>
|
|
160
|
+
title: 'Dotrino Remote Desktop agent',
|
|
161
|
+
runPrefix: 'DotrinoRemoteDesktopAgent', // el valor de HKCU\…\Run
|
|
162
|
+
agentArgs: (name) => ['--name', name], // cómo se corre el agente sin TTY
|
|
163
|
+
linux: 'autostart' // o 'systemd' (por defecto)
|
|
164
|
+
})
|
|
165
|
+
svc.installService({ name, cli, dir }) // también uninstallService, serviceStatus, startService
|
|
166
|
+
// y en el CLI: `supervise --name <n>` → svc.superviseCommand({ name, dir, cli })
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
`linux: 'systemd'` arranca al encender (con *linger*), sin sesión gráfica: vale para un agente
|
|
170
|
+
que solo necesita una shell (Terminal). `linux: 'autostart'` arranca con la sesión gráfica, que
|
|
171
|
+
es lo que necesita un agente que mira el escritorio. Los dos casos con supervisor (Windows y
|
|
172
|
+
`autostart`) le ponen `DOTRINO_SUPERVISED=1` al agente, así que `/update` puede reiniciarlo.
|
|
173
|
+
|
|
153
174
|
### Un agente como CLIENTE de otro agente (Node)
|
|
154
175
|
|
|
155
176
|
Un agente Node también puede hablar con otro agente —un bot que guarda en el node de
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/remote-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.37.0",
|
|
4
4
|
"description": "Middleware compartido del ecosistema Dotrino para apps de agente remoto cifrado punto a punto (handshake E2E, emparejamiento SAS con vault, revocación, descubrimiento). Lo consumen dotrino-terminal (PTY) y dotrino-ia (chat con IA).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
@@ -41,6 +41,10 @@
|
|
|
41
41
|
"./update": {
|
|
42
42
|
"types": "./types/src/update.d.ts",
|
|
43
43
|
"import": "./src/update.js"
|
|
44
|
+
},
|
|
45
|
+
"./service": {
|
|
46
|
+
"types": "./types/src/service.d.ts",
|
|
47
|
+
"import": "./src/service.js"
|
|
44
48
|
}
|
|
45
49
|
},
|
|
46
50
|
"files": [
|
package/src/service.js
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* service.js — un agente como SERVICIO del usuario: arranca solo con la máquina o con la sesión.
|
|
3
|
+
*
|
|
4
|
+
* Venía de `dotrino-terminal/agent/service.js` y ahora es común (CLAUDE.md: reusar es la norma):
|
|
5
|
+
* lo usan el agente de Terminal y el del escritorio remoto. Cada uno lo configura con
|
|
6
|
+
* `makeService({ id, title, runPrefix, agentArgs, linux })` y recibe las órdenes de siempre.
|
|
7
|
+
*
|
|
8
|
+
* · Linux, `linux: 'systemd'` — una unidad de systemd DEL USUARIO (`~/.config/systemd/user`),
|
|
9
|
+
* sin `sudo`. Con «linger» arranca al encender, antes de que nadie inicie sesión.
|
|
10
|
+
* · Linux, `linux: 'autostart'` — el inicio automático del escritorio
|
|
11
|
+
* (`~/.config/autostart/*.desktop`, XDG) lanza un SUPERVISOR que levanta el agente cada vez
|
|
12
|
+
* que sale. Para un agente que necesita la SESIÓN GRÁFICA (el escritorio remoto: `DISPLAY`,
|
|
13
|
+
* el bus de sesión, la accesibilidad): una unidad que arranca al encender no tiene nada de
|
|
14
|
+
* eso, y `graphical-session.target` no lo activan todos los escritorios (XFCE no siempre).
|
|
15
|
+
* · macOS — un LaunchAgent (`~/Library/LaunchAgents`): arranca al iniciar sesión.
|
|
16
|
+
* · Windows — una entrada en `HKCU\…\Run` que lanza el mismo supervisor sin ventana. No es el
|
|
17
|
+
* Programador de tareas ni un servicio de Windows: los dos piden derechos de administrador.
|
|
18
|
+
*
|
|
19
|
+
* Es de usuario a propósito (CONVENCIONES §15): así el agente se sigue actualizando solo, y con
|
|
20
|
+
* alguien que lo levante (`DOTRINO_SUPERVISED`) ya puede reiniciarse para estrenar la versión.
|
|
21
|
+
*
|
|
22
|
+
* Una unidad por PERFIL: cada perfil es un agente con su enlace.
|
|
23
|
+
*/
|
|
24
|
+
import fs from 'node:fs'
|
|
25
|
+
import os from 'node:os'
|
|
26
|
+
import path from 'node:path'
|
|
27
|
+
import { execFileSync, spawn as childSpawn } from 'node:child_process'
|
|
28
|
+
|
|
29
|
+
/** @typedef {Error & { code?: string, stderr?: string | Buffer }} Thrown */
|
|
30
|
+
|
|
31
|
+
/** @type {(code: string, message: string) => Error & { code: string }} */
|
|
32
|
+
const fail = (code, message) => Object.assign(new Error(message), { code })
|
|
33
|
+
|
|
34
|
+
/** Correr una orden del sistema (`execFileSync`, o su doble en las pruebas). */
|
|
35
|
+
/** @typedef {(cmd: string, args: string[], opts?: import('node:child_process').ExecFileSyncOptions) => unknown} RunFn */
|
|
36
|
+
/** Lanzar un proceso (`spawn`, o su doble en las pruebas). */
|
|
37
|
+
/** @typedef {typeof childSpawn} SpawnFn */
|
|
38
|
+
/** Lo que comparten las órdenes de servicio: el perfil, y Node y el CLI con que se lanza. */
|
|
39
|
+
/** @typedef {{ name: string, node: string, cli: string }} Launch */
|
|
40
|
+
/** @typedef {'systemd' | 'autostart' | 'launchd' | 'run-key'} ServiceKind */
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Qué agente es.
|
|
44
|
+
* @typedef {object} Product
|
|
45
|
+
* @property {string} id `terminal-agent` → `dotrino-terminal-agent-<perfil>.service`, `com.dotrino.terminal-agent.<perfil>`
|
|
46
|
+
* @property {string} title para la descripción de la unidad: `Dotrino Terminal agent`
|
|
47
|
+
* @property {string} runPrefix el valor de `HKCU\…\Run`: `DotrinoTerminalAgent` → `DotrinoTerminalAgent-<perfil>`
|
|
48
|
+
* @property {(name: string) => string[]} agentArgs con qué argumentos se corre el agente sin TTY
|
|
49
|
+
* @property {'systemd' | 'autostart'} [linux] cómo se pone en Linux (por defecto, systemd)
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/** Windows: la clave de lo que arranca al iniciar sesión. */
|
|
53
|
+
export const RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
|
|
54
|
+
/** Cuánto espera el supervisor antes de volver a levantar el agente (como `RestartSec`). */
|
|
55
|
+
export const RESTART_MS = 3000
|
|
56
|
+
/** @param {string} dir */
|
|
57
|
+
export const supervisorPidFile = (dir) => path.join(dir, 'supervisor.pid')
|
|
58
|
+
|
|
59
|
+
/** systemd parte `ExecStart` por espacios: lo que los lleve va entre comillas. */
|
|
60
|
+
/** @param {string} s */
|
|
61
|
+
const unitArg = (s) => (/[\s"'\\$%]/.test(s) ? `"${s.replace(/[\\"]/g, '\\$&').replace(/%/g, '%%').replace(/\$/g, '$$$$')}"` : s)
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Un argumento de `Exec=` de un `.desktop` (especificación XDG): entre comillas dobles si lleva
|
|
65
|
+
* algo reservado, con `"`, `` ` ``, `$` y `\` escapados, y el `%` doblado (son los códigos de campo).
|
|
66
|
+
* La barra va cuádruple: primero se aplica el escape de las cadenas y después el de las comillas.
|
|
67
|
+
* @param {string} s
|
|
68
|
+
*/
|
|
69
|
+
export const desktopArg = (s) => {
|
|
70
|
+
const v = s.replace(/%/g, '%%')
|
|
71
|
+
if (!/[\s"'\\$`<>~|&;*?#()]/.test(v)) return v
|
|
72
|
+
return `"${v.replace(/\\/g, '\\\\\\\\').replace(/["`$]/g, '\\$&')}"`
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** @param {unknown} s */
|
|
76
|
+
const xml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* @param {RunFn} run
|
|
80
|
+
* @param {string} cmd
|
|
81
|
+
* @param {string[]} args
|
|
82
|
+
* @returns {{ ok: true } | { ok: false, reason: string | undefined }}
|
|
83
|
+
*/
|
|
84
|
+
function quiet (run, cmd, args) {
|
|
85
|
+
try { run(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' }); return { ok: true } } catch (e) {
|
|
86
|
+
return { ok: false, reason: String(/** @type {Thrown} */ (e).stderr || /** @type {Thrown} */ (e).message).trim().split('\n').pop() }
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* @param {RunFn} run
|
|
92
|
+
* @param {string} cmd
|
|
93
|
+
* @param {string[]} args
|
|
94
|
+
*/
|
|
95
|
+
function must (run, cmd, args) {
|
|
96
|
+
const r = quiet(run, cmd, args)
|
|
97
|
+
if (!r.ok) throw fail('service-command-failed', `${cmd} ${args.join(' ')}: ${r.reason}`)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const LINGER_DIR = '/var/lib/systemd/linger'
|
|
101
|
+
/** ¿Ya arrancan los servicios de ese usuario al encender? systemd lo apunta con un archivo. */
|
|
102
|
+
/** @type {(user: string, root?: string) => boolean} */
|
|
103
|
+
const lingers = (user, root = LINGER_DIR) => fs.existsSync(path.join(root, user))
|
|
104
|
+
|
|
105
|
+
/** @type {(file: string) => number} */
|
|
106
|
+
const readPid = (file) => { try { return Number(fs.readFileSync(file, 'utf8')) || 0 } catch (e) { if (/** @type {Thrown} */ (e).code === 'ENOENT') return 0; throw e } }
|
|
107
|
+
/** @type {(pid: number) => boolean} */
|
|
108
|
+
const alive = (pid) => { try { process.kill(pid, 0); return true } catch (e) { return /** @type {Thrown} */ (e).code === 'EPERM' } }
|
|
109
|
+
|
|
110
|
+
/** PowerShell: una cadena entre comillas simples. */
|
|
111
|
+
/** @param {string} s */
|
|
112
|
+
const psQuote = (s) => `'${String(s).replace(/'/g, "''")}'`
|
|
113
|
+
|
|
114
|
+
/** ¿Hay sesión gráfica en este entorno? Sin ella, un agente de `autostart` no puede arrancar ahora. */
|
|
115
|
+
/** @param {NodeJS.ProcessEnv} env */
|
|
116
|
+
const graphical = (env) => !!(env.DISPLAY || env.WAYLAND_DISPLAY)
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* El supervisor: levanta el agente del perfil y lo vuelve a levantar cada vez que sale (también
|
|
120
|
+
* cuando se reinicia para estrenar una versión: §15, `DOTRINO_SUPERVISED`). Uno por perfil: si
|
|
121
|
+
* ya hay otro vivo, lanza `already-supervised`.
|
|
122
|
+
* @param {{ name: string, dir: string, node?: string, cli: string, args: string[], spawn?: SpawnFn }} o
|
|
123
|
+
*/
|
|
124
|
+
export function supervise ({ name, dir, node = process.execPath, cli, args, spawn = childSpawn }) {
|
|
125
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
126
|
+
const pidFile = supervisorPidFile(dir)
|
|
127
|
+
const other = readPid(pidFile)
|
|
128
|
+
if (other && other !== process.pid && alive(other)) throw fail('already-supervised', `profile ${name} already has a supervisor (pid ${other})`)
|
|
129
|
+
fs.writeFileSync(pidFile, String(process.pid))
|
|
130
|
+
let stopped = false
|
|
131
|
+
/** @type {import('node:child_process').ChildProcess | null} */
|
|
132
|
+
let child = null
|
|
133
|
+
const start = () => {
|
|
134
|
+
const fd = fs.openSync(path.join(dir, 'agent.log'), 'a', 0o600)
|
|
135
|
+
child = spawn(node, [cli, ...args], { windowsHide: true, stdio: ['ignore', fd, fd], env: { ...process.env, DOTRINO_SUPERVISED: '1' } })
|
|
136
|
+
fs.closeSync(fd)
|
|
137
|
+
child.on('exit', () => { child = null; if (!stopped) setTimeout(start, RESTART_MS) })
|
|
138
|
+
}
|
|
139
|
+
start()
|
|
140
|
+
return {
|
|
141
|
+
stop: () => {
|
|
142
|
+
stopped = true
|
|
143
|
+
try { child?.kill() } catch (_) {}
|
|
144
|
+
try { if (readPid(pidFile) === process.pid) fs.rmSync(pidFile) } catch (_) {}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Para el supervisor y después el agente. En Windows matar el supervisor no se lleva al hijo
|
|
151
|
+
* (no hay señales: `agent.pid`, si el agente lo escribe); en Linux el supervisor para a su hijo
|
|
152
|
+
* al recibir SIGTERM.
|
|
153
|
+
* @param {string} dir
|
|
154
|
+
*/
|
|
155
|
+
function stopSupervised (dir) {
|
|
156
|
+
for (const file of [supervisorPidFile(dir), path.join(dir, 'agent.pid')]) {
|
|
157
|
+
const pid = readPid(file)
|
|
158
|
+
if (pid && alive(pid)) process.kill(pid)
|
|
159
|
+
}
|
|
160
|
+
fs.rmSync(supervisorPidFile(dir), { force: true })
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Las órdenes de servicio de un agente.
|
|
165
|
+
* @param {Product} product
|
|
166
|
+
*/
|
|
167
|
+
export function makeService ({ id, title, runPrefix, agentArgs, linux = 'systemd' }) {
|
|
168
|
+
/** @param {string} name */
|
|
169
|
+
const unitName = (name) => `dotrino-${id}-${name}.service`
|
|
170
|
+
/** @param {string} name */
|
|
171
|
+
const plistLabel = (name) => `com.dotrino.${id}.${name}`
|
|
172
|
+
/** @param {string} name */
|
|
173
|
+
const runValue = (name) => `${runPrefix}-${name}`
|
|
174
|
+
/** @param {string} name @param {string} [home] */
|
|
175
|
+
const unitPath = (name, home = os.homedir()) => path.join(home, '.config', 'systemd', 'user', unitName(name))
|
|
176
|
+
/** @param {string} name @param {string} [home] */
|
|
177
|
+
const plistPath = (name, home = os.homedir()) => path.join(home, 'Library', 'LaunchAgents', `${plistLabel(name)}.plist`)
|
|
178
|
+
/** @param {string} name @param {string} [home] */
|
|
179
|
+
const autostartPath = (name, home = os.homedir()) => path.join(home, '.config', 'autostart', `dotrino-${id}-${name}.desktop`)
|
|
180
|
+
/** Lo que se apunta en la clave de Windows: Node, el CLI y el supervisor del perfil. */
|
|
181
|
+
/** @param {Launch} o */
|
|
182
|
+
const runCommand = ({ name, node, cli }) => `"${node}" "${cli}" supervise --name ${name}`
|
|
183
|
+
/** @param {string} name */
|
|
184
|
+
const runKeyFile = (name) => `${RUN_KEY}\\${runValue(name)}`
|
|
185
|
+
/** @type {(name: string, run: RunFn) => boolean} */
|
|
186
|
+
const hasRunKey = (name, run) => quiet(run, 'reg', ['query', RUN_KEY, '/v', runValue(name)]).ok
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* La unidad de systemd. El PATH es el de quien instala: el de un servicio de usuario es mínimo
|
|
190
|
+
* y no trae el Node de nvm ni las herramientas que el agente espera encontrar.
|
|
191
|
+
* @param {Launch & { pathEnv: string }} o
|
|
192
|
+
*/
|
|
193
|
+
function unitText ({ name, node, cli, pathEnv }) {
|
|
194
|
+
return `[Unit]
|
|
195
|
+
Description=${title} (${name})
|
|
196
|
+
After=network-online.target
|
|
197
|
+
Wants=network-online.target
|
|
198
|
+
|
|
199
|
+
[Service]
|
|
200
|
+
ExecStart=${[node, cli, ...agentArgs(name)].map(unitArg).join(' ')}
|
|
201
|
+
Environment=${unitArg(`PATH=${pathEnv}`)}
|
|
202
|
+
Restart=always
|
|
203
|
+
RestartSec=3
|
|
204
|
+
|
|
205
|
+
[Install]
|
|
206
|
+
WantedBy=default.target
|
|
207
|
+
`
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* La entrada del inicio automático del escritorio: lanza el supervisor del perfil. El entorno
|
|
212
|
+
* (PATH, DISPLAY, el bus de sesión) es el de la sesión, que es justo lo que hace falta.
|
|
213
|
+
* @param {Launch} o
|
|
214
|
+
*/
|
|
215
|
+
function autostartText ({ name, node, cli }) {
|
|
216
|
+
return `[Desktop Entry]
|
|
217
|
+
Type=Application
|
|
218
|
+
Name=${title} (${name})
|
|
219
|
+
Exec=${[node, cli, 'supervise', '--name', name].map(desktopArg).join(' ')}
|
|
220
|
+
Terminal=false
|
|
221
|
+
NoDisplay=true
|
|
222
|
+
X-GNOME-Autostart-enabled=true
|
|
223
|
+
`
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* El LaunchAgent de macOS. `DOTRINO_SUPERVISED`: launchd lo levanta si sale (§15).
|
|
228
|
+
* @param {Launch & { pathEnv: string, log: string }} o
|
|
229
|
+
*/
|
|
230
|
+
function plistText ({ name, node, cli, pathEnv, log }) {
|
|
231
|
+
const args = [node, cli, ...agentArgs(name)].map((a) => ` <string>${xml(a)}</string>`).join('\n')
|
|
232
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
233
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
234
|
+
<plist version="1.0"><dict>
|
|
235
|
+
<key>Label</key><string>${xml(plistLabel(name))}</string>
|
|
236
|
+
<key>ProgramArguments</key>
|
|
237
|
+
<array>
|
|
238
|
+
${args}
|
|
239
|
+
</array>
|
|
240
|
+
<key>EnvironmentVariables</key>
|
|
241
|
+
<dict>
|
|
242
|
+
<key>PATH</key><string>${xml(pathEnv)}</string>
|
|
243
|
+
<key>DOTRINO_SUPERVISED</key><string>1</string>
|
|
244
|
+
</dict>
|
|
245
|
+
<key>RunAtLoad</key><true/>
|
|
246
|
+
<key>KeepAlive</key><true/>
|
|
247
|
+
<key>StandardOutPath</key><string>${xml(log)}</string>
|
|
248
|
+
<key>StandardErrorPath</key><string>${xml(log)}</string>
|
|
249
|
+
</dict></plist>
|
|
250
|
+
`
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* ¿Deja este sistema instalar el servicio? Lanza con el motivo si no.
|
|
255
|
+
* @param {{ platform: string, run: RunFn }} o
|
|
256
|
+
* @returns {ServiceKind}
|
|
257
|
+
*/
|
|
258
|
+
function platformOf ({ platform, run }) {
|
|
259
|
+
if (platform === 'darwin') return 'launchd'
|
|
260
|
+
if (platform === 'win32') return 'run-key'
|
|
261
|
+
if (platform !== 'linux') throw fail('unsupported-platform', `there is no service support for ${platform}`)
|
|
262
|
+
if (linux === 'autostart') return 'autostart'
|
|
263
|
+
// Sin systemd de usuario (un contenedor, WSL sin systemd, otra init) no hay dónde ponerlo.
|
|
264
|
+
if (!quiet(run, 'systemctl', ['--user', 'show-environment']).ok) throw fail('no-user-systemd', 'this session has no systemd user manager')
|
|
265
|
+
return 'systemd'
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Lanza el supervisor del perfil, ya suelto (sin ventana en Windows, en su propia sesión en Linux).
|
|
270
|
+
*
|
|
271
|
+
* Windows desde SSH no vale un proceso aparte: sshd mete la sesión en un objeto de trabajo y al
|
|
272
|
+
* cerrarla mata todo lo que lanzó. Ahí lo crea WMI (`Win32_Process.Create`) con la misma línea
|
|
273
|
+
* que queda en `HKCU\…\Run`; una cuenta sin administrador no puede, y se devuelve el motivo.
|
|
274
|
+
*
|
|
275
|
+
* Linux (`autostart`) sin sesión gráfica en este entorno (por SSH): el agente no arrancaría.
|
|
276
|
+
* No se lanza nada y se dice; el inicio automático lo arranca al iniciar sesión.
|
|
277
|
+
*
|
|
278
|
+
* @param {Launch & { platform: string, spawn: SpawnFn, run: RunFn, env: NodeJS.ProcessEnv }} o
|
|
279
|
+
* @returns {{ ok: true } | { ok: false, reason: string }}
|
|
280
|
+
*/
|
|
281
|
+
function spawnSupervisor ({ name, node, cli, platform, spawn, run, env }) {
|
|
282
|
+
if (platform === 'win32' && (env.SSH_CONNECTION || env.SSH_CLIENT)) {
|
|
283
|
+
const script = `$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = ${psQuote(runCommand({ name, node, cli }))} }; if ($r.ReturnValue -ne 0) { throw "Win32_Process.Create returned $($r.ReturnValue)" }`
|
|
284
|
+
const r = quiet(run, 'powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script])
|
|
285
|
+
return r.ok ? { ok: true } : { ok: false, reason: 'Windows (WMI) does not let this account start it from SSH' }
|
|
286
|
+
}
|
|
287
|
+
if (platform === 'linux' && !graphical(env)) return { ok: false, reason: 'there is no graphical session here (DISPLAY / WAYLAND_DISPLAY)' }
|
|
288
|
+
const child = spawn(node, [cli, 'supervise', '--name', name], { detached: true, windowsHide: true, stdio: 'ignore', env: { ...env, DOTRINO_SUPERVISOR: '1' } })
|
|
289
|
+
child.unref()
|
|
290
|
+
return { ok: true }
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* La orden `supervise` del CLI del agente. La lanza el sistema (la entrada de `Run`, el inicio
|
|
295
|
+
* automático del escritorio): primero se vuelve a lanzar suelto y sale (en Windows se abre CON
|
|
296
|
+
* ventana), y ese segundo proceso es el supervisor. Para con SIGINT/SIGTERM y se lleva al agente.
|
|
297
|
+
* @param {{ name: string, dir: string, cli: string, node?: string, spawn?: SpawnFn, env?: NodeJS.ProcessEnv }} o
|
|
298
|
+
*/
|
|
299
|
+
function superviseCommand ({ name, dir, cli, node = process.execPath, spawn = childSpawn, env = process.env }) {
|
|
300
|
+
if (!env.DOTRINO_SUPERVISOR) {
|
|
301
|
+
spawn(node, [cli, 'supervise', '--name', name], { detached: true, windowsHide: true, stdio: 'ignore', env: { ...env, DOTRINO_SUPERVISOR: '1' } }).unref()
|
|
302
|
+
return { relaunched: true }
|
|
303
|
+
}
|
|
304
|
+
const s = supervise({ name, dir, node, cli, args: agentArgs(name), spawn })
|
|
305
|
+
const bye = () => { s.stop(); process.exit(0) }
|
|
306
|
+
process.on('SIGINT', bye); process.on('SIGTERM', bye)
|
|
307
|
+
return { relaunched: false, stop: s.stop }
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Instala y enciende el servicio del perfil `name`.
|
|
312
|
+
*
|
|
313
|
+
* `running`: ya hay un agente de ese perfil corriendo por su cuenta. Dos agentes con el mismo
|
|
314
|
+
* enlace son la misma llave: el servicio queda puesto y toma el relevo cuando ese termine o al
|
|
315
|
+
* próximo arranque.
|
|
316
|
+
*
|
|
317
|
+
* @param {{ name: string, node?: string, cli: string, dir: string, running?: boolean, pathEnv?: string, platform?: string, home?: string,
|
|
318
|
+
* user?: string, uid?: number, run?: RunFn, spawn?: SpawnFn, env?: NodeJS.ProcessEnv }} o
|
|
319
|
+
* @returns {{ kind: ServiceKind, file: string, started: boolean, boot?: boolean, lingerReason?: string, startReason?: string }}
|
|
320
|
+
*/
|
|
321
|
+
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, env = process.env }) {
|
|
322
|
+
const kind = platformOf({ platform, run })
|
|
323
|
+
if (kind === 'run-key' || kind === 'autostart') {
|
|
324
|
+
let file
|
|
325
|
+
if (kind === 'run-key') {
|
|
326
|
+
must(run, 'reg', ['add', RUN_KEY, '/v', runValue(name), '/t', 'REG_SZ', '/d', runCommand({ name, node, cli }), '/f'])
|
|
327
|
+
file = runKeyFile(name)
|
|
328
|
+
} else {
|
|
329
|
+
file = autostartPath(name, home)
|
|
330
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
331
|
+
fs.writeFileSync(file, autostartText({ name, node, cli }), { mode: 0o644 })
|
|
332
|
+
}
|
|
333
|
+
if (running) return { kind, file, started: false }
|
|
334
|
+
const pid = readPid(supervisorPidFile(dir))
|
|
335
|
+
if (pid && alive(pid)) return { kind, file, started: true }
|
|
336
|
+
const s = spawnSupervisor({ name, node, cli, platform, spawn, run, env })
|
|
337
|
+
return { kind, file, started: s.ok, ...(s.ok ? {} : { startReason: s.reason }) }
|
|
338
|
+
}
|
|
339
|
+
if (kind === 'launchd') {
|
|
340
|
+
const file = plistPath(name, home)
|
|
341
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
342
|
+
fs.writeFileSync(file, plistText({ name, node, cli, pathEnv, log: path.join(dir, 'agent.log') }), { mode: 0o644 })
|
|
343
|
+
if (running) return { kind, file, started: false }
|
|
344
|
+
// Si ya estaba cargado (una instalación anterior), se recarga con el archivo nuevo.
|
|
345
|
+
quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
346
|
+
must(run, 'launchctl', ['bootstrap', `gui/${uid}`, file])
|
|
347
|
+
return { kind, file, started: true }
|
|
348
|
+
}
|
|
349
|
+
const file = unitPath(name, home)
|
|
350
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
351
|
+
fs.writeFileSync(file, unitText({ name, node, cli, pathEnv }), { mode: 0o644 })
|
|
352
|
+
must(run, 'systemctl', ['--user', 'daemon-reload'])
|
|
353
|
+
must(run, 'systemctl', ['--user', 'enable', unitName(name)])
|
|
354
|
+
if (!running) must(run, 'systemctl', ['--user', 'restart', unitName(name)])
|
|
355
|
+
// Arrancar al ENCENDER, sin que nadie inicie sesión. Si el sistema no lo deja sin
|
|
356
|
+
// administrador, el servicio arranca al iniciar sesión, y se dice.
|
|
357
|
+
if (lingers(user)) return { kind, file, started: !running, boot: true }
|
|
358
|
+
const linger = quiet(run, 'loginctl', ['enable-linger', user])
|
|
359
|
+
return { kind, file, started: !running, boot: linger.ok, ...(linger.ok ? {} : { lingerReason: linger.reason }) }
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Arranca el servicio ya instalado de ese perfil. `false` si el perfil no tiene servicio (o no
|
|
364
|
+
* se puede dejar corriendo desde aquí): entonces quien llama levanta el agente él mismo.
|
|
365
|
+
* @param {{ name: string, dir: string, node?: string, cli: string, platform?: string, home?: string, uid?: number,
|
|
366
|
+
* run?: RunFn, spawn?: SpawnFn, env?: NodeJS.ProcessEnv }} o
|
|
367
|
+
* @returns {boolean}
|
|
368
|
+
*/
|
|
369
|
+
function startService ({ name, dir, node = process.execPath, cli, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync, spawn = childSpawn, env = process.env }) {
|
|
370
|
+
if (platform === 'win32' || (platform === 'linux' && linux === 'autostart')) {
|
|
371
|
+
if (platform === 'win32' ? !hasRunKey(name, run) : !fs.existsSync(autostartPath(name, home))) return false
|
|
372
|
+
const pid = readPid(supervisorPidFile(dir))
|
|
373
|
+
if (pid && alive(pid)) return true
|
|
374
|
+
return spawnSupervisor({ name, node, cli, platform, spawn, run, env }).ok
|
|
375
|
+
}
|
|
376
|
+
if (platform === 'darwin') {
|
|
377
|
+
const file = plistPath(name, home)
|
|
378
|
+
if (!fs.existsSync(file)) return false
|
|
379
|
+
// Cargado y parado no puede estar (KeepAlive): si no corre, es que no está cargado.
|
|
380
|
+
quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
381
|
+
must(run, 'launchctl', ['bootstrap', `gui/${uid}`, file])
|
|
382
|
+
return true
|
|
383
|
+
}
|
|
384
|
+
if (platform !== 'linux' || !fs.existsSync(unitPath(name, home))) return false
|
|
385
|
+
must(run, 'systemctl', ['--user', 'start', unitName(name)])
|
|
386
|
+
return true
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Para el servicio y lo quita. El enlace y los ajustes del perfil no se tocan.
|
|
391
|
+
* @param {{ name: string, dir: string, platform?: string, home?: string, uid?: number, run?: RunFn }} o
|
|
392
|
+
* @returns {{ kind: ServiceKind, file: string, removed: boolean }}
|
|
393
|
+
*/
|
|
394
|
+
function uninstallService ({ name, dir, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
|
|
395
|
+
const kind = platformOf({ platform, run })
|
|
396
|
+
if (kind === 'run-key') {
|
|
397
|
+
if (!hasRunKey(name, run)) return { kind, file: runKeyFile(name), removed: false }
|
|
398
|
+
stopSupervised(dir)
|
|
399
|
+
must(run, 'reg', ['delete', RUN_KEY, '/v', runValue(name), '/f'])
|
|
400
|
+
return { kind, file: runKeyFile(name), removed: true }
|
|
401
|
+
}
|
|
402
|
+
if (kind === 'autostart') {
|
|
403
|
+
const file = autostartPath(name, home)
|
|
404
|
+
if (!fs.existsSync(file)) return { kind, file, removed: false }
|
|
405
|
+
stopSupervised(dir)
|
|
406
|
+
fs.rmSync(file)
|
|
407
|
+
return { kind, file, removed: true }
|
|
408
|
+
}
|
|
409
|
+
const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
|
|
410
|
+
if (!fs.existsSync(file)) return { kind, file, removed: false }
|
|
411
|
+
if (kind === 'launchd') quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
412
|
+
else must(run, 'systemctl', ['--user', 'disable', '--now', unitName(name)])
|
|
413
|
+
fs.rmSync(file)
|
|
414
|
+
if (kind === 'systemd') must(run, 'systemctl', ['--user', 'daemon-reload'])
|
|
415
|
+
return { kind, file, removed: true }
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* ¿Está puesto, y está corriendo ahora bajo el sistema?
|
|
420
|
+
* @param {{ name: string, dir: string, platform?: string, home?: string, uid?: number, run?: RunFn }} o
|
|
421
|
+
* @returns {{ kind: ServiceKind, file: string, installed: boolean, active: boolean }}
|
|
422
|
+
*/
|
|
423
|
+
function serviceStatus ({ name, dir, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
|
|
424
|
+
const kind = platformOf({ platform, run })
|
|
425
|
+
if (kind === 'run-key' || kind === 'autostart') {
|
|
426
|
+
const installed = kind === 'run-key' ? hasRunKey(name, run) : fs.existsSync(autostartPath(name, home))
|
|
427
|
+
const pid = installed ? readPid(supervisorPidFile(dir)) : 0
|
|
428
|
+
return { kind, file: kind === 'run-key' ? runKeyFile(name) : autostartPath(name, home), installed, active: !!pid && alive(pid) }
|
|
429
|
+
}
|
|
430
|
+
const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
|
|
431
|
+
const installed = fs.existsSync(file)
|
|
432
|
+
const active = installed && (kind === 'launchd'
|
|
433
|
+
? quiet(run, 'launchctl', ['print', `gui/${uid}/${plistLabel(name)}`]).ok
|
|
434
|
+
: quiet(run, 'systemctl', ['--user', 'is-active', '--quiet', unitName(name)]).ok)
|
|
435
|
+
return { kind, file, installed, active }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
return {
|
|
439
|
+
installService, uninstallService, serviceStatus, startService, superviseCommand,
|
|
440
|
+
unitText, autostartText, plistText, unitName, unitPath, plistLabel, plistPath, autostartPath, runValue, runCommand
|
|
441
|
+
}
|
|
442
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* El supervisor: levanta el agente del perfil y lo vuelve a levantar cada vez que sale (también
|
|
3
|
+
* cuando se reinicia para estrenar una versión: §15, `DOTRINO_SUPERVISED`). Uno por perfil: si
|
|
4
|
+
* ya hay otro vivo, lanza `already-supervised`.
|
|
5
|
+
* @param {{ name: string, dir: string, node?: string, cli: string, args: string[], spawn?: SpawnFn }} o
|
|
6
|
+
*/
|
|
7
|
+
export function supervise({ name, dir, node, cli, args, spawn }: {
|
|
8
|
+
name: string;
|
|
9
|
+
dir: string;
|
|
10
|
+
node?: string;
|
|
11
|
+
cli: string;
|
|
12
|
+
args: string[];
|
|
13
|
+
spawn?: SpawnFn;
|
|
14
|
+
}): {
|
|
15
|
+
stop: () => void;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Las órdenes de servicio de un agente.
|
|
19
|
+
* @param {Product} product
|
|
20
|
+
*/
|
|
21
|
+
export function makeService({ id, title, runPrefix, agentArgs, linux }: Product): {
|
|
22
|
+
installService: ({ name, node, cli, dir, running, pathEnv, platform, home, user, uid, run, spawn, env }: {
|
|
23
|
+
name: string;
|
|
24
|
+
node?: string;
|
|
25
|
+
cli: string;
|
|
26
|
+
dir: string;
|
|
27
|
+
running?: boolean;
|
|
28
|
+
pathEnv?: string;
|
|
29
|
+
platform?: string;
|
|
30
|
+
home?: string;
|
|
31
|
+
user?: string;
|
|
32
|
+
uid?: number;
|
|
33
|
+
run?: RunFn;
|
|
34
|
+
spawn?: SpawnFn;
|
|
35
|
+
env?: NodeJS.ProcessEnv;
|
|
36
|
+
}) => {
|
|
37
|
+
kind: ServiceKind;
|
|
38
|
+
file: string;
|
|
39
|
+
started: boolean;
|
|
40
|
+
boot?: boolean;
|
|
41
|
+
lingerReason?: string;
|
|
42
|
+
startReason?: string;
|
|
43
|
+
};
|
|
44
|
+
uninstallService: ({ name, dir, platform, home, uid, run }: {
|
|
45
|
+
name: string;
|
|
46
|
+
dir: string;
|
|
47
|
+
platform?: string;
|
|
48
|
+
home?: string;
|
|
49
|
+
uid?: number;
|
|
50
|
+
run?: RunFn;
|
|
51
|
+
}) => {
|
|
52
|
+
kind: ServiceKind;
|
|
53
|
+
file: string;
|
|
54
|
+
removed: boolean;
|
|
55
|
+
};
|
|
56
|
+
serviceStatus: ({ name, dir, platform, home, uid, run }: {
|
|
57
|
+
name: string;
|
|
58
|
+
dir: string;
|
|
59
|
+
platform?: string;
|
|
60
|
+
home?: string;
|
|
61
|
+
uid?: number;
|
|
62
|
+
run?: RunFn;
|
|
63
|
+
}) => {
|
|
64
|
+
kind: ServiceKind;
|
|
65
|
+
file: string;
|
|
66
|
+
installed: boolean;
|
|
67
|
+
active: boolean;
|
|
68
|
+
};
|
|
69
|
+
startService: ({ name, dir, node, cli, platform, home, uid, run, spawn, env }: {
|
|
70
|
+
name: string;
|
|
71
|
+
dir: string;
|
|
72
|
+
node?: string;
|
|
73
|
+
cli: string;
|
|
74
|
+
platform?: string;
|
|
75
|
+
home?: string;
|
|
76
|
+
uid?: number;
|
|
77
|
+
run?: RunFn;
|
|
78
|
+
spawn?: SpawnFn;
|
|
79
|
+
env?: NodeJS.ProcessEnv;
|
|
80
|
+
}) => boolean;
|
|
81
|
+
superviseCommand: ({ name, dir, cli, node, spawn, env }: {
|
|
82
|
+
name: string;
|
|
83
|
+
dir: string;
|
|
84
|
+
cli: string;
|
|
85
|
+
node?: string;
|
|
86
|
+
spawn?: SpawnFn;
|
|
87
|
+
env?: NodeJS.ProcessEnv;
|
|
88
|
+
}) => {
|
|
89
|
+
relaunched: boolean;
|
|
90
|
+
stop?: undefined;
|
|
91
|
+
} | {
|
|
92
|
+
relaunched: boolean;
|
|
93
|
+
stop: () => void;
|
|
94
|
+
};
|
|
95
|
+
unitText: ({ name, node, cli, pathEnv }: Launch & {
|
|
96
|
+
pathEnv: string;
|
|
97
|
+
}) => string;
|
|
98
|
+
autostartText: ({ name, node, cli }: Launch) => string;
|
|
99
|
+
plistText: ({ name, node, cli, pathEnv, log }: Launch & {
|
|
100
|
+
pathEnv: string;
|
|
101
|
+
log: string;
|
|
102
|
+
}) => string;
|
|
103
|
+
unitName: (name: string) => string;
|
|
104
|
+
unitPath: (name: string, home?: string) => string;
|
|
105
|
+
plistLabel: (name: string) => string;
|
|
106
|
+
plistPath: (name: string, home?: string) => string;
|
|
107
|
+
autostartPath: (name: string, home?: string) => string;
|
|
108
|
+
runValue: (name: string) => string;
|
|
109
|
+
runCommand: ({ name, node, cli }: Launch) => string;
|
|
110
|
+
};
|
|
111
|
+
/** Correr una orden del sistema (`execFileSync`, o su doble en las pruebas). */
|
|
112
|
+
/** @typedef {(cmd: string, args: string[], opts?: import('node:child_process').ExecFileSyncOptions) => unknown} RunFn */
|
|
113
|
+
/** Lanzar un proceso (`spawn`, o su doble en las pruebas). */
|
|
114
|
+
/** @typedef {typeof childSpawn} SpawnFn */
|
|
115
|
+
/** Lo que comparten las órdenes de servicio: el perfil, y Node y el CLI con que se lanza. */
|
|
116
|
+
/** @typedef {{ name: string, node: string, cli: string }} Launch */
|
|
117
|
+
/** @typedef {'systemd' | 'autostart' | 'launchd' | 'run-key'} ServiceKind */
|
|
118
|
+
/**
|
|
119
|
+
* Qué agente es.
|
|
120
|
+
* @typedef {object} Product
|
|
121
|
+
* @property {string} id `terminal-agent` → `dotrino-terminal-agent-<perfil>.service`, `com.dotrino.terminal-agent.<perfil>`
|
|
122
|
+
* @property {string} title para la descripción de la unidad: `Dotrino Terminal agent`
|
|
123
|
+
* @property {string} runPrefix el valor de `HKCU\…\Run`: `DotrinoTerminalAgent` → `DotrinoTerminalAgent-<perfil>`
|
|
124
|
+
* @property {(name: string) => string[]} agentArgs con qué argumentos se corre el agente sin TTY
|
|
125
|
+
* @property {'systemd' | 'autostart'} [linux] cómo se pone en Linux (por defecto, systemd)
|
|
126
|
+
*/
|
|
127
|
+
/** Windows: la clave de lo que arranca al iniciar sesión. */
|
|
128
|
+
export const RUN_KEY: "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
|
|
129
|
+
/** Cuánto espera el supervisor antes de volver a levantar el agente (como `RestartSec`). */
|
|
130
|
+
export const RESTART_MS: 3000;
|
|
131
|
+
export function supervisorPidFile(dir: string): string;
|
|
132
|
+
export function desktopArg(s: string): string;
|
|
133
|
+
export type Thrown = Error & {
|
|
134
|
+
code?: string;
|
|
135
|
+
stderr?: string | Buffer;
|
|
136
|
+
};
|
|
137
|
+
export type RunFn = (cmd: string, args: string[], opts?: import("node:child_process").ExecFileSyncOptions) => unknown;
|
|
138
|
+
export type SpawnFn = typeof childSpawn;
|
|
139
|
+
export type Launch = {
|
|
140
|
+
name: string;
|
|
141
|
+
node: string;
|
|
142
|
+
cli: string;
|
|
143
|
+
};
|
|
144
|
+
export type ServiceKind = "systemd" | "autostart" | "launchd" | "run-key";
|
|
145
|
+
/**
|
|
146
|
+
* Qué agente es.
|
|
147
|
+
*/
|
|
148
|
+
export type Product = {
|
|
149
|
+
/**
|
|
150
|
+
* `terminal-agent` → `dotrino-terminal-agent-<perfil>.service`, `com.dotrino.terminal-agent.<perfil>`
|
|
151
|
+
*/
|
|
152
|
+
id: string;
|
|
153
|
+
/**
|
|
154
|
+
* para la descripción de la unidad: `Dotrino Terminal agent`
|
|
155
|
+
*/
|
|
156
|
+
title: string;
|
|
157
|
+
/**
|
|
158
|
+
* el valor de `HKCU\…\Run`: `DotrinoTerminalAgent` → `DotrinoTerminalAgent-<perfil>`
|
|
159
|
+
*/
|
|
160
|
+
runPrefix: string;
|
|
161
|
+
/**
|
|
162
|
+
* con qué argumentos se corre el agente sin TTY
|
|
163
|
+
*/
|
|
164
|
+
agentArgs: (name: string) => string[];
|
|
165
|
+
/**
|
|
166
|
+
* cómo se pone en Linux (por defecto, systemd)
|
|
167
|
+
*/
|
|
168
|
+
linux?: "systemd" | "autostart" | undefined;
|
|
169
|
+
};
|
|
170
|
+
import { spawn as childSpawn } from 'node:child_process';
|