@dotrino/terminal-agent 0.54.1 → 0.55.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/bin/cli.js +2 -9
- package/package.json +6 -6
- package/service.js +18 -349
package/bin/cli.js
CHANGED
|
@@ -75,21 +75,14 @@ if (cmd === 'update') {
|
|
|
75
75
|
// `supervise` (Windows): lo lanza la entrada de `HKCU\…\Run` que pone `dotrino-terminal service
|
|
76
76
|
// install`. Al iniciar sesión Windows lo abre CON ventana: se vuelve a lanzar sin ella y sale.
|
|
77
77
|
if (cmd === 'supervise') {
|
|
78
|
-
const {
|
|
78
|
+
const { superviseCommand } = await import('../service.js')
|
|
79
79
|
const { realpathSync } = await import('node:fs')
|
|
80
80
|
const { fileURLToPath } = await import('node:url')
|
|
81
81
|
const name = opt('--name')
|
|
82
82
|
if (!name) { console.error('uso: dotrino-terminal-agent supervise --name <n>'); process.exit(2) }
|
|
83
83
|
const cli = realpathSync(fileURLToPath(import.meta.url))
|
|
84
|
-
if (!process.env.DOTRINO_SUPERVISOR) {
|
|
85
|
-
const { spawn } = await import('node:child_process')
|
|
86
|
-
spawn(process.execPath, [cli, 'supervise', '--name', name], { detached: true, windowsHide: true, stdio: 'ignore', env: { ...process.env, DOTRINO_SUPERVISOR: '1' } }).unref()
|
|
87
|
-
process.exit(0)
|
|
88
|
-
}
|
|
89
84
|
try {
|
|
90
|
-
|
|
91
|
-
const bye = () => { s.stop(); process.exit(0) }
|
|
92
|
-
process.on('SIGINT', bye); process.on('SIGTERM', bye)
|
|
85
|
+
if (superviseCommand({ name, dir: dataDir(name), cli }).relaunched) process.exit(0)
|
|
93
86
|
} catch (e) { console.error('error:', /** @type {Thrown} */ (e).message); process.exit(1) }
|
|
94
87
|
}
|
|
95
88
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/terminal-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.55.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": {
|
|
@@ -37,11 +37,11 @@
|
|
|
37
37
|
"type-check": "tsc --noEmit"
|
|
38
38
|
},
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@dotrino/identity": "0.
|
|
41
|
-
"@dotrino/proxy-client": "0.
|
|
42
|
-
"@dotrino/remote-agent": "0.
|
|
43
|
-
"@dotrino/update": "0.9.
|
|
44
|
-
"@dotrino/vault": "0.
|
|
40
|
+
"@dotrino/identity": "0.138.0",
|
|
41
|
+
"@dotrino/proxy-client": "0.49.1",
|
|
42
|
+
"@dotrino/remote-agent": "0.37.0",
|
|
43
|
+
"@dotrino/update": "0.9.4",
|
|
44
|
+
"@dotrino/vault": "0.121.2",
|
|
45
45
|
"@xterm/addon-serialize": "0.13.0",
|
|
46
46
|
"@xterm/headless": "5.5.0",
|
|
47
47
|
"jsonc-parser": "3.3.1",
|
package/service.js
CHANGED
|
@@ -2,363 +2,32 @@
|
|
|
2
2
|
* service.js — el agente como SERVICIO del usuario: arranca solo con la máquina.
|
|
3
3
|
*
|
|
4
4
|
* Sin esto el agente lo levanta la primera ventana que se abre (`dotrino-terminal`), así que
|
|
5
|
-
* tras encender la máquina nadie puede abrir sus consolas desde otro aparato hasta que
|
|
6
|
-
*
|
|
5
|
+
* tras encender la máquina nadie puede abrir sus consolas desde otro aparato hasta que alguien
|
|
6
|
+
* se siente delante. `dotrino-terminal service install` lo deja a cargo del sistema.
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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.
|
|
16
|
-
*
|
|
17
|
-
* Es de usuario a propósito (CONVENCIONES §15): así el agente se sigue actualizando solo, y
|
|
18
|
-
* con alguien que lo levante ya puede reiniciarse para estrenar la versión nueva.
|
|
19
|
-
*
|
|
20
|
-
* Una unidad por PERFIL: cada perfil es un agente con su enlace.
|
|
21
|
-
*/
|
|
22
|
-
import fs from 'node:fs'
|
|
23
|
-
import os from 'node:os'
|
|
24
|
-
import path from 'node:path'
|
|
25
|
-
import { execFileSync, spawn as childSpawn } from 'node:child_process'
|
|
26
|
-
|
|
27
|
-
/** @type {(code: string, message: string) => Error & { code: string }} */
|
|
28
|
-
const fail = (code, message) => Object.assign(new Error(message), { code })
|
|
29
|
-
|
|
30
|
-
/** Correr una orden del sistema (`execFileSync`, o su doble en las pruebas). */
|
|
31
|
-
/** @typedef {(cmd: string, args: string[], opts?: import('node:child_process').ExecFileSyncOptions) => unknown} RunFn */
|
|
32
|
-
/** Lanzar un proceso (`spawn`, o su doble en las pruebas). */
|
|
33
|
-
/** @typedef {typeof childSpawn} SpawnFn */
|
|
34
|
-
/** Lo que comparten las órdenes de servicio: el perfil, y Node y el CLI con que se lanza. */
|
|
35
|
-
/** @typedef {{ name: string, node: string, cli: string }} Launch */
|
|
36
|
-
|
|
37
|
-
/** @param {string} name */
|
|
38
|
-
export const unitName = (name) => `dotrino-terminal-agent-${name}.service`
|
|
39
|
-
/** @param {string} name */
|
|
40
|
-
export const plistLabel = (name) => `com.dotrino.terminal-agent.${name}`
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* @param {string} name
|
|
44
|
-
* @param {string} [home]
|
|
45
|
-
*/
|
|
46
|
-
export function unitPath (name, home = os.homedir()) {
|
|
47
|
-
return path.join(home, '.config', 'systemd', 'user', unitName(name))
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/**
|
|
51
|
-
* @param {string} name
|
|
52
|
-
* @param {string} [home]
|
|
53
|
-
*/
|
|
54
|
-
export function plistPath (name, home = os.homedir()) {
|
|
55
|
-
return path.join(home, 'Library', 'LaunchAgents', `${plistLabel(name)}.plist`)
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
/** Windows: la clave de lo que arranca al iniciar sesión, y el nombre del valor de cada perfil. */
|
|
59
|
-
export const RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
|
|
60
|
-
/** @param {string} name */
|
|
61
|
-
export const runValue = (name) => `DotrinoTerminalAgent-${name}`
|
|
62
|
-
/** Lo que se apunta en la clave: Node, el CLI y el supervisor del perfil. */
|
|
63
|
-
/** @param {Launch} o */
|
|
64
|
-
export const runCommand = ({ name, node, cli }) => `"${node}" "${cli}" supervise --name ${name}`
|
|
65
|
-
/** @param {string} dir */
|
|
66
|
-
export const supervisorPidFile = (dir) => path.join(dir, 'supervisor.pid')
|
|
67
|
-
/** Cuánto espera el supervisor antes de volver a levantar el agente (como `RestartSec`). */
|
|
68
|
-
export const RESTART_MS = 3000
|
|
69
|
-
|
|
70
|
-
/** systemd parte `ExecStart` por espacios: lo que los lleve va entre comillas. */
|
|
71
|
-
/** @param {string} s */
|
|
72
|
-
const unitArg = (s) => (/[\s"'\\$%]/.test(s) ? `"${s.replace(/[\\"]/g, '\\$&').replace(/%/g, '%%').replace(/\$/g, '$$$$')}"` : s)
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
* La unidad de systemd. `--local`: sin TTY el agente nunca pregunta; si el perfil no está
|
|
76
|
-
* enlazado atiende solo a las ventanas de esta máquina, igual que cuando lo levanta una ventana.
|
|
77
|
-
*
|
|
78
|
-
* El PATH es el de quien instala: el de un servicio de usuario es mínimo y no trae el Node
|
|
79
|
-
* de nvm ni las herramientas que las consolas esperan encontrar.
|
|
80
|
-
* @param {Launch & { pathEnv: string }} o
|
|
81
|
-
*/
|
|
82
|
-
export function unitText ({ name, node, cli, pathEnv }) {
|
|
83
|
-
return `[Unit]
|
|
84
|
-
Description=Dotrino Terminal agent (${name})
|
|
85
|
-
After=network-online.target
|
|
86
|
-
Wants=network-online.target
|
|
87
|
-
|
|
88
|
-
[Service]
|
|
89
|
-
ExecStart=${unitArg(node)} ${unitArg(cli)} --name ${name} --local
|
|
90
|
-
Environment=${unitArg(`PATH=${pathEnv}`)}
|
|
91
|
-
Restart=always
|
|
92
|
-
RestartSec=3
|
|
93
|
-
|
|
94
|
-
[Install]
|
|
95
|
-
WantedBy=default.target
|
|
96
|
-
`
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/** @param {unknown} s */
|
|
100
|
-
const xml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
101
|
-
|
|
102
|
-
/**
|
|
103
|
-
* El LaunchAgent de macOS. `DOTRINO_SUPERVISED`: launchd lo levanta si sale (§15).
|
|
104
|
-
* @param {Launch & { pathEnv: string, log: string }} o
|
|
105
|
-
*/
|
|
106
|
-
export function plistText ({ name, node, cli, pathEnv, log }) {
|
|
107
|
-
const args = [node, cli, '--name', name, '--local'].map((a) => ` <string>${xml(a)}</string>`).join('\n')
|
|
108
|
-
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
109
|
-
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
110
|
-
<plist version="1.0"><dict>
|
|
111
|
-
<key>Label</key><string>${xml(plistLabel(name))}</string>
|
|
112
|
-
<key>ProgramArguments</key>
|
|
113
|
-
<array>
|
|
114
|
-
${args}
|
|
115
|
-
</array>
|
|
116
|
-
<key>EnvironmentVariables</key>
|
|
117
|
-
<dict>
|
|
118
|
-
<key>PATH</key><string>${xml(pathEnv)}</string>
|
|
119
|
-
<key>DOTRINO_SUPERVISED</key><string>1</string>
|
|
120
|
-
</dict>
|
|
121
|
-
<key>RunAtLoad</key><true/>
|
|
122
|
-
<key>KeepAlive</key><true/>
|
|
123
|
-
<key>StandardOutPath</key><string>${xml(log)}</string>
|
|
124
|
-
<key>StandardErrorPath</key><string>${xml(log)}</string>
|
|
125
|
-
</dict></plist>
|
|
126
|
-
`
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
/**
|
|
130
|
-
* @param {RunFn} run
|
|
131
|
-
* @param {string} cmd
|
|
132
|
-
* @param {string[]} args
|
|
133
|
-
* @returns {{ ok: true } | { ok: false, reason: string | undefined }}
|
|
8
|
+
* La pieza es común (`@dotrino/remote-agent/service`, la usa también el escritorio remoto);
|
|
9
|
+
* aquí solo va qué agente es. En Linux, systemd de usuario: este agente no necesita la sesión
|
|
10
|
+
* gráfica, así que con «linger» arranca al encender, antes de que nadie inicie sesión. Los
|
|
11
|
+
* nombres (unidad, LaunchAgent, entrada de `Run`) son los de siempre: un servicio ya instalado
|
|
12
|
+
* sigue siendo el mismo.
|
|
134
13
|
*/
|
|
135
|
-
|
|
136
|
-
try { run(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' }); return { ok: true } } catch (e) {
|
|
137
|
-
return { ok: false, reason: String(/** @type {Thrown} */ (e).stderr || /** @type {Thrown} */ (e).message).trim().split('\n').pop() }
|
|
138
|
-
}
|
|
139
|
-
}
|
|
14
|
+
import { makeService, supervise as superviseAgent, RUN_KEY, RESTART_MS, supervisorPidFile } from '@dotrino/remote-agent/service'
|
|
140
15
|
|
|
141
|
-
/**
|
|
142
|
-
* @param {RunFn} run
|
|
143
|
-
* @param {string} cmd
|
|
144
|
-
* @param {string[]} args
|
|
145
|
-
*/
|
|
146
|
-
function must (run, cmd, args) {
|
|
147
|
-
const r = quiet(run, cmd, args)
|
|
148
|
-
if (!r.ok) throw fail('service-command-failed', `${cmd} ${args.join(' ')}: ${r.reason}`)
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/** ¿Ya arrancan los servicios de ese usuario al encender? systemd lo apunta con un archivo. */
|
|
152
|
-
/** @type {(user: string, root?: string) => boolean} */
|
|
153
|
-
const lingers = (user, root = LINGER_DIR) => fs.existsSync(path.join(root, user))
|
|
154
|
-
const LINGER_DIR = '/var/lib/systemd/linger'
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* ¿Deja este sistema instalar el servicio? Lanza con el motivo si no.
|
|
158
|
-
* @param {{ platform: string, run: RunFn }} o
|
|
159
|
-
* @returns {'launchd' | 'run-key' | 'systemd'}
|
|
160
|
-
*/
|
|
161
|
-
function platformOf ({ platform, run }) {
|
|
162
|
-
if (platform === 'darwin') return 'launchd'
|
|
163
|
-
if (platform === 'win32') return 'run-key'
|
|
164
|
-
if (platform !== 'linux') throw fail('unsupported-platform', `there is no service support for ${platform}`)
|
|
165
|
-
// Sin systemd de usuario (un contenedor, WSL sin systemd, otra init) no hay dónde ponerlo.
|
|
166
|
-
if (!quiet(run, 'systemctl', ['--user', 'show-environment']).ok) throw fail('no-user-systemd', 'this session has no systemd user manager')
|
|
167
|
-
return 'systemd'
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/** @type {(file: string) => number} */
|
|
171
|
-
const readPid = (file) => { try { return Number(fs.readFileSync(file, 'utf8')) || 0 } catch (e) { if (/** @type {Thrown} */ (e).code === 'ENOENT') return 0; throw e } }
|
|
172
|
-
/** @type {(pid: number) => boolean} */
|
|
173
|
-
const alive = (pid) => { try { process.kill(pid, 0); return true } catch (e) { return /** @type {Thrown} */ (e).code === 'EPERM' } }
|
|
174
16
|
/** @param {string} name */
|
|
175
|
-
const
|
|
176
|
-
/** @type {(name: string, run: RunFn) => boolean} */
|
|
177
|
-
const hasRunKey = (name, run) => quiet(run, 'reg', ['query', RUN_KEY, '/v', runValue(name)]).ok
|
|
17
|
+
const agentArgs = (name) => ['--name', name, '--local']
|
|
178
18
|
|
|
179
|
-
|
|
180
|
-
/** @param {string} s */
|
|
181
|
-
const psQuote = (s) => `'${String(s).replace(/'/g, "''")}'`
|
|
19
|
+
const svc = makeService({ id: 'terminal-agent', title: 'Dotrino Terminal agent', runPrefix: 'DotrinoTerminalAgent', agentArgs })
|
|
182
20
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
* (`Win32_Process.Create`), que lo lanza fuera de la sesión, y con la misma línea que queda en
|
|
189
|
-
* `HKCU\…\Run`: así se prueba también la que correrá al iniciar sesión.
|
|
190
|
-
*
|
|
191
|
-
* Una cuenta sin administrador no puede pedirle eso a WMI desde SSH. Entonces no queda nada
|
|
192
|
-
* corriendo ahora (lo que se lanzara moriría al cerrar la sesión) y se devuelve el motivo: la
|
|
193
|
-
* entrada de `Run` ya está puesta y lo arranca al iniciar sesión.
|
|
194
|
-
*
|
|
195
|
-
* @param {Launch & { spawn: SpawnFn, run: RunFn, env: NodeJS.ProcessEnv }} o
|
|
196
|
-
* @returns {{ ok: true } | { ok: false, reason: string }}
|
|
197
|
-
*/
|
|
198
|
-
function spawnSupervisor ({ name, node, cli, spawn, run, env }) {
|
|
199
|
-
if (env.SSH_CONNECTION || env.SSH_CLIENT) {
|
|
200
|
-
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)" }`
|
|
201
|
-
const r = quiet(run, 'powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script])
|
|
202
|
-
return r.ok ? { ok: true } : { ok: false, reason: 'Windows (WMI) does not let this account start it from SSH' }
|
|
203
|
-
}
|
|
204
|
-
const child = spawn(node, [cli, 'supervise', '--name', name], { detached: true, windowsHide: true, stdio: 'ignore', env: { ...env, DOTRINO_SUPERVISOR: '1' } })
|
|
205
|
-
child.unref()
|
|
206
|
-
return { ok: true }
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
/**
|
|
210
|
-
* El supervisor de Windows: levanta el agente del perfil y lo vuelve a levantar cada vez que
|
|
211
|
-
* sale (también cuando se reinicia para estrenar una versión: §15, `DOTRINO_SUPERVISED`).
|
|
212
|
-
* Uno por perfil: si ya hay otro vivo, lanza `already-supervised`.
|
|
213
|
-
* @param {{ name: string, dir: string, node?: string, cli: string, spawn?: SpawnFn }} o
|
|
214
|
-
*/
|
|
215
|
-
export function supervise ({ name, dir, node = process.execPath, cli, spawn = childSpawn }) {
|
|
216
|
-
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
217
|
-
const pidFile = supervisorPidFile(dir)
|
|
218
|
-
const other = readPid(pidFile)
|
|
219
|
-
if (other && other !== process.pid && alive(other)) throw fail('already-supervised', `profile ${name} already has a supervisor (pid ${other})`)
|
|
220
|
-
fs.writeFileSync(pidFile, String(process.pid))
|
|
221
|
-
let stopped = false
|
|
222
|
-
/** @type {import('node:child_process').ChildProcess | null} */
|
|
223
|
-
let child = null
|
|
224
|
-
const start = () => {
|
|
225
|
-
const fd = fs.openSync(path.join(dir, 'agent.log'), 'a', 0o600)
|
|
226
|
-
child = spawn(node, [cli, '--name', name, '--local'], { windowsHide: true, stdio: ['ignore', fd, fd], env: { ...process.env, DOTRINO_SUPERVISED: '1' } })
|
|
227
|
-
fs.closeSync(fd)
|
|
228
|
-
child.on('exit', () => { child = null; if (!stopped) setTimeout(start, RESTART_MS) })
|
|
229
|
-
}
|
|
230
|
-
start()
|
|
231
|
-
return {
|
|
232
|
-
stop: () => {
|
|
233
|
-
stopped = true
|
|
234
|
-
try { child?.kill() } catch (_) {}
|
|
235
|
-
try { if (readPid(pidFile) === process.pid) fs.rmSync(pidFile) } catch (_) {}
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/**
|
|
241
|
-
* Windows: para el supervisor y después el agente (matar el supervisor no se lleva al hijo).
|
|
242
|
-
* @param {string} dir
|
|
243
|
-
*/
|
|
244
|
-
function stopSupervised (dir) {
|
|
245
|
-
for (const file of [supervisorPidFile(dir), path.join(dir, 'agent.pid')]) {
|
|
246
|
-
const pid = readPid(file)
|
|
247
|
-
if (pid && alive(pid)) process.kill(pid)
|
|
248
|
-
}
|
|
249
|
-
fs.rmSync(supervisorPidFile(dir), { force: true })
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
/**
|
|
253
|
-
* Instala y enciende el servicio del perfil `name`.
|
|
254
|
-
*
|
|
255
|
-
* `running`: ya hay un agente de ese perfil corriendo por su cuenta (lo levantó una ventana).
|
|
256
|
-
* Dos agentes con el mismo enlace son la misma llave, y parar ese cerraría sus consolas: el
|
|
257
|
-
* servicio queda puesto y toma el relevo cuando ese agente termine o al próximo arranque.
|
|
258
|
-
*
|
|
259
|
-
* @param {{ name: string, node?: string, cli: string, dir: string, running?: boolean, pathEnv?: string, platform?: string, home?: string,
|
|
260
|
-
* user?: string, uid?: number, run?: RunFn, spawn?: SpawnFn, env?: NodeJS.ProcessEnv }} o
|
|
261
|
-
* @returns {{ kind:'systemd'|'launchd'|'run-key', file:string, started:boolean, boot?:boolean, lingerReason?:string, startReason?:string }}
|
|
262
|
-
*/
|
|
263
|
-
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, env = process.env }) {
|
|
264
|
-
const kind = platformOf({ platform, run })
|
|
265
|
-
if (kind === 'run-key') {
|
|
266
|
-
must(run, 'reg', ['add', RUN_KEY, '/v', runValue(name), '/t', 'REG_SZ', '/d', runCommand({ name, node, cli }), '/f'])
|
|
267
|
-
if (running) return { kind, file: runKeyFile(name), started: false }
|
|
268
|
-
const s = spawnSupervisor({ name, node, cli, spawn, run, env })
|
|
269
|
-
return { kind, file: runKeyFile(name), started: s.ok, ...(s.ok ? {} : { startReason: s.reason }) }
|
|
270
|
-
}
|
|
271
|
-
if (kind === 'launchd') {
|
|
272
|
-
const file = plistPath(name, home)
|
|
273
|
-
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
274
|
-
fs.writeFileSync(file, plistText({ name, node, cli, pathEnv, log: path.join(dir, 'agent.log') }), { mode: 0o644 })
|
|
275
|
-
if (running) return { kind, file, started: false }
|
|
276
|
-
// Si ya estaba cargado (una instalación anterior), se recarga con el archivo nuevo.
|
|
277
|
-
quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
278
|
-
must(run, 'launchctl', ['bootstrap', `gui/${uid}`, file])
|
|
279
|
-
return { kind, file, started: true }
|
|
280
|
-
}
|
|
281
|
-
const file = unitPath(name, home)
|
|
282
|
-
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
283
|
-
fs.writeFileSync(file, unitText({ name, node, cli, pathEnv }), { mode: 0o644 })
|
|
284
|
-
must(run, 'systemctl', ['--user', 'daemon-reload'])
|
|
285
|
-
must(run, 'systemctl', ['--user', 'enable', unitName(name)])
|
|
286
|
-
if (!running) must(run, 'systemctl', ['--user', 'restart', unitName(name)])
|
|
287
|
-
// Arrancar al ENCENDER, sin que nadie inicie sesión. Si el sistema no lo deja sin
|
|
288
|
-
// administrador, el servicio arranca al iniciar sesión, y se dice.
|
|
289
|
-
if (lingers(user)) return { kind, file, started: !running, boot: true }
|
|
290
|
-
const linger = quiet(run, 'loginctl', ['enable-linger', user])
|
|
291
|
-
return { kind, file, started: !running, boot: linger.ok, ...(linger.ok ? {} : { lingerReason: linger.reason }) }
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
/**
|
|
295
|
-
* Arranca el servicio ya instalado de ese perfil. `false` si el perfil no tiene servicio (o
|
|
296
|
-
* este sistema no los tiene): entonces el agente lo levanta la ventana, como siempre. Lo usa
|
|
297
|
-
* `dotrino-terminal` cuando no encuentra agente, para no levantar uno propio al lado de un
|
|
298
|
-
* servicio que el sistema arrancaría después con la misma llave.
|
|
299
|
-
* @param {{ name: string, dir: string, node?: string, cli: string, platform?: string, home?: string, uid?: number,
|
|
300
|
-
* run?: RunFn, spawn?: SpawnFn, env?: NodeJS.ProcessEnv }} o
|
|
301
|
-
* @returns {boolean}
|
|
302
|
-
*/
|
|
303
|
-
export function startService ({ name, dir, node = process.execPath, cli, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync, spawn = childSpawn, env = process.env }) {
|
|
304
|
-
if (platform === 'win32') {
|
|
305
|
-
if (!hasRunKey(name, run)) return false
|
|
306
|
-
const pid = readPid(supervisorPidFile(dir))
|
|
307
|
-
if (pid && alive(pid)) return true
|
|
308
|
-
// Sin poder dejarlo corriendo (cuenta normal por SSH), lo levanta la ventana, como sin servicio.
|
|
309
|
-
return spawnSupervisor({ name, node, cli, spawn, run, env }).ok
|
|
310
|
-
}
|
|
311
|
-
if (platform === 'darwin') {
|
|
312
|
-
const file = plistPath(name, home)
|
|
313
|
-
if (!fs.existsSync(file)) return false
|
|
314
|
-
// Cargado y parado no puede estar (KeepAlive): si no corre, es que no está cargado.
|
|
315
|
-
quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
316
|
-
must(run, 'launchctl', ['bootstrap', `gui/${uid}`, file])
|
|
317
|
-
return true
|
|
318
|
-
}
|
|
319
|
-
if (platform !== 'linux' || !fs.existsSync(unitPath(name, home))) return false
|
|
320
|
-
must(run, 'systemctl', ['--user', 'start', unitName(name)])
|
|
321
|
-
return true
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
/**
|
|
325
|
-
* Para el servicio y lo quita. El enlace y los ajustes del perfil no se tocan.
|
|
326
|
-
* @param {{ name: string, dir: string, platform?: string, home?: string, uid?: number, run?: RunFn }} o
|
|
327
|
-
*/
|
|
328
|
-
export function uninstallService ({ name, dir, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
|
|
329
|
-
const kind = platformOf({ platform, run })
|
|
330
|
-
if (kind === 'run-key') {
|
|
331
|
-
if (!hasRunKey(name, run)) return { kind, file: runKeyFile(name), removed: false }
|
|
332
|
-
stopSupervised(dir)
|
|
333
|
-
must(run, 'reg', ['delete', RUN_KEY, '/v', runValue(name), '/f'])
|
|
334
|
-
return { kind, file: runKeyFile(name), removed: true }
|
|
335
|
-
}
|
|
336
|
-
const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
|
|
337
|
-
if (!fs.existsSync(file)) return { kind, file, removed: false }
|
|
338
|
-
if (kind === 'launchd') quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
339
|
-
else must(run, 'systemctl', ['--user', 'disable', '--now', unitName(name)])
|
|
340
|
-
fs.rmSync(file)
|
|
341
|
-
if (kind === 'systemd') must(run, 'systemctl', ['--user', 'daemon-reload'])
|
|
342
|
-
return { kind, file, removed: true }
|
|
343
|
-
}
|
|
21
|
+
export const {
|
|
22
|
+
installService, uninstallService, serviceStatus, startService, superviseCommand,
|
|
23
|
+
unitText, plistText, unitName, unitPath, plistLabel, plistPath, runValue, runCommand
|
|
24
|
+
} = svc
|
|
25
|
+
export { RUN_KEY, RESTART_MS, supervisorPidFile }
|
|
344
26
|
|
|
345
27
|
/**
|
|
346
|
-
*
|
|
347
|
-
* @param {{ name: string, dir: string,
|
|
28
|
+
* El supervisor (Windows): levanta el agente del perfil y lo vuelve a levantar cada vez que sale.
|
|
29
|
+
* @param {{ name: string, dir: string, node?: string, cli: string, spawn?: typeof import('node:child_process').spawn }} o
|
|
348
30
|
*/
|
|
349
|
-
export
|
|
350
|
-
const kind = platformOf({ platform, run })
|
|
351
|
-
if (kind === 'run-key') {
|
|
352
|
-
const installed = hasRunKey(name, run)
|
|
353
|
-
const pid = installed ? readPid(supervisorPidFile(dir)) : 0
|
|
354
|
-
return { kind, file: runKeyFile(name), installed, active: !!pid && alive(pid) }
|
|
355
|
-
}
|
|
356
|
-
const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
|
|
357
|
-
const installed = fs.existsSync(file)
|
|
358
|
-
const active = installed && (kind === 'launchd'
|
|
359
|
-
? quiet(run, 'launchctl', ['print', `gui/${uid}/${plistLabel(name)}`]).ok
|
|
360
|
-
: quiet(run, 'systemctl', ['--user', 'is-active', '--quiet', unitName(name)]).ok)
|
|
361
|
-
return { kind, file, installed, active }
|
|
362
|
-
}
|
|
31
|
+
export const supervise = (o) => superviseAgent({ ...o, args: agentArgs(o.name) })
|
|
363
32
|
|
|
364
33
|
export default { supervise, runCommand, runValue, RUN_KEY, startService, installService, uninstallService, serviceStatus, unitText, plistText, unitName, unitPath, plistLabel, plistPath }
|