@dotrino/terminal-agent 0.39.0 → 0.40.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 +13 -0
- package/bin/terminal.js +95 -7
- package/desktop.js +10 -2
- package/package.json +2 -1
- package/service.js +189 -0
package/README.md
CHANGED
|
@@ -51,6 +51,7 @@ dotrino-terminal link [--name <n>] # enlazar un perfil con tu bóveda
|
|
|
51
51
|
dotrino-terminal rename <perfil> [nuevo] # renombrarlo (mueve su carpeta y para su agente; mismo aparato)
|
|
52
52
|
dotrino-terminal vscode [--name <n>] # la terminal embebida de VS Code abre consolas de aquí (--off lo deshace)
|
|
53
53
|
dotrino-terminal desktop update [--check] # actualiza la app de escritorio: baja, verifica la firma e instala
|
|
54
|
+
dotrino-terminal service install|uninstall|status [--name <n>] # el agente como servicio del usuario
|
|
54
55
|
```
|
|
55
56
|
|
|
56
57
|
Cerrar la ventana no cierra la consola: sigue viva en el agente y se retoma después (se cierra
|
|
@@ -149,3 +150,15 @@ En la app de escritorio: menú **Perfil → Poner o cambiar la clave… / Quitar
|
|
|
149
150
|
nunca la clave. Viaja dentro de la sesión cifrada: el proxio no la ve.
|
|
150
151
|
- Hace falta agente ≥ 0.19.0, y web ≥ 0.8.9 o las apps ≥ 0.8.9 para poder escribirla. Un
|
|
151
152
|
cliente más viejo ve el error `locked` y no entra.
|
|
153
|
+
|
|
154
|
+
## Como servicio (arrancar al encender)
|
|
155
|
+
|
|
156
|
+
`dotrino-terminal service install [--name <n>]` escribe una unidad de systemd **del usuario**
|
|
157
|
+
(`~/.config/systemd/user/dotrino-terminal-agent-<perfil>.service`, `Restart=always`, con el `PATH`
|
|
158
|
+
de quien instala) y pide `loginctl enable-linger` para que arranque sin sesión; en macOS, un
|
|
159
|
+
LaunchAgent (`~/Library/LaunchAgents/com.dotrino.terminal-agent.<perfil>.plist`). Es de usuario
|
|
160
|
+
para que el agente se siga actualizando solo (§15): con quien lo levante ya puede reiniciarse.
|
|
161
|
+
Un agente que ya corre por su cuenta no se para (cerraría sus consolas): el servicio queda
|
|
162
|
+
habilitado, y `dotrino-terminal`, cuando no encuentra agente, arranca el servicio en vez de
|
|
163
|
+
levantar uno propio. Código en `service.js`; probado con systemd en un contenedor de Fedora,
|
|
164
|
+
macOS solo con pruebas unitarias.
|
package/bin/terminal.js
CHANGED
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
* dotrino-terminal vscode [--name <n>] la terminal embebida de VS Code abre consolas de aquí
|
|
18
18
|
* dotrino-terminal vscode --off lo deshace
|
|
19
19
|
* dotrino-terminal desktop update [--check] actualiza la app de escritorio (la ventana)
|
|
20
|
+
* dotrino-terminal service install|uninstall|status [--name <n>]
|
|
21
|
+
* el agente como servicio: arranca solo con la máquina
|
|
20
22
|
*
|
|
21
23
|
* Un PERFIL es un agente con nombre (`~/.dotrino/agent/terminal-agent/<nombre>/`), enlazado a
|
|
22
24
|
* una bóveda o solo local. Cada consola vive en el agente de un perfil.
|
|
@@ -29,6 +31,7 @@
|
|
|
29
31
|
* cierra saliendo de su shell (`exit`) o desde el panel.
|
|
30
32
|
*/
|
|
31
33
|
import fs from 'node:fs'
|
|
34
|
+
import os from 'node:os'
|
|
32
35
|
import path from 'node:path'
|
|
33
36
|
import { spawn } from 'node:child_process'
|
|
34
37
|
import { fileURLToPath } from 'node:url'
|
|
@@ -82,6 +85,10 @@ if (args.includes('-h') || args.includes('--help')) {
|
|
|
82
85
|
dotrino-terminal desktop update actualiza la app de escritorio (la ventana): baja la
|
|
83
86
|
versión nueva, comprueba su firma y la instala
|
|
84
87
|
(--check solo mira si hay una)
|
|
88
|
+
dotrino-terminal service install [--name <n>] deja el agente como servicio de tu usuario: arranca
|
|
89
|
+
solo al encender la máquina, sin abrir ninguna ventana
|
|
90
|
+
dotrino-terminal service uninstall [--name <n>] lo quita (para el agente: cierra sus consolas)
|
|
91
|
+
dotrino-terminal service status [--name <n>] dice si está puesto y si está corriendo
|
|
85
92
|
|
|
86
93
|
Dentro de una consola: Ctrl+] y luego d la suelta sin cerrarla; Ctrl+] n abre otra
|
|
87
94
|
(y suelta la actual); Ctrl+] a <id> Enter pasa a esa consola; Ctrl+] p fija el tamaño de la
|
|
@@ -114,6 +121,10 @@ Cerrar la ventana no cierra la consola: sigue abierta y se retoma después.`, `u
|
|
|
114
121
|
dotrino-terminal desktop update update the desktop app (the window): downloads the
|
|
115
122
|
new version, checks its signature and installs it
|
|
116
123
|
(--check only looks for one)
|
|
124
|
+
dotrino-terminal service install [--name <n>] run the agent as a service of your user: it starts
|
|
125
|
+
by itself when the machine boots, with no window open
|
|
126
|
+
dotrino-terminal service uninstall [--name <n>] remove it (stops the agent: closes its consoles)
|
|
127
|
+
dotrino-terminal service status [--name <n>] say whether it is installed and running
|
|
117
128
|
|
|
118
129
|
Inside a console: Ctrl+] then d detaches without closing it; Ctrl+] n opens another
|
|
119
130
|
(detaching the current one); Ctrl+] a <id> Enter switches to that console; Ctrl+] p pins the
|
|
@@ -169,13 +180,18 @@ async function agent (dir) {
|
|
|
169
180
|
}
|
|
170
181
|
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
171
182
|
const log = path.join(dir, 'agent.log')
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
183
|
+
// Si este perfil tiene servicio (`dotrino-terminal service install`), el agente es el del
|
|
184
|
+
// sistema: se arranca ese, no uno propio al lado. `--dir` fuerza una carpeta sin perfil.
|
|
185
|
+
const { startService } = await import('../service.js')
|
|
186
|
+
if (!(!opt('--dir') && !process.env.DOTRINO_TERMINAL_DIR && startService({ name: path.basename(dir) }))) {
|
|
187
|
+
const fd = fs.openSync(log, 'a', 0o600)
|
|
188
|
+
const cli = fileURLToPath(new URL('./cli.js', import.meta.url))
|
|
189
|
+
const extra = opt('--name') ? ['--name', opt('--name')] : []
|
|
190
|
+
// Sin TTY: si la máquina no está enlazada, el agente atiende solo a las ventanas locales.
|
|
191
|
+
const child = spawn(process.execPath, [cli, ...extra], { detached: true, stdio: ['ignore', fd, fd], env: process.env })
|
|
192
|
+
child.unref()
|
|
193
|
+
fs.closeSync(fd)
|
|
194
|
+
}
|
|
179
195
|
const t0 = Date.now()
|
|
180
196
|
while (Date.now() - t0 < 10000) {
|
|
181
197
|
await new Promise((r) => setTimeout(r, 100))
|
|
@@ -265,6 +281,77 @@ async function desktop () {
|
|
|
265
281
|
else console.log(t(`La app está al día (${current}).`, `The app is up to date (${current}).`))
|
|
266
282
|
}
|
|
267
283
|
|
|
284
|
+
/** Cuántas consolas tiene abiertas el agente de esa carpeta (0 si no hay agente). */
|
|
285
|
+
async function openConsoles (dir) {
|
|
286
|
+
let conn
|
|
287
|
+
try { conn = await connectLocal(dir) } catch (e) { if (e.code === 'ENOAGENT') return 0; throw e }
|
|
288
|
+
const r = await request(conn, { type: 'list' }, 'consoles')
|
|
289
|
+
conn.close()
|
|
290
|
+
if (r.type === 'fail') throw new Error(`${r.message} (${r.code})`)
|
|
291
|
+
return r.list.length
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** El agente como servicio del usuario (systemd en Linux, launchd en macOS). */
|
|
295
|
+
async function service () {
|
|
296
|
+
const action = args[1]
|
|
297
|
+
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>]'))
|
|
298
|
+
const asked = opt('--name')
|
|
299
|
+
if (asked !== undefined && !isValidName(asked)) die(t(`nombre de perfil no válido: ${asked}`, `invalid profile name: ${asked}`))
|
|
300
|
+
const { dir } = resolveInstance(LABEL, asked)
|
|
301
|
+
const name = path.basename(dir)
|
|
302
|
+
const { installService, uninstallService, serviceStatus } = await import('../service.js')
|
|
303
|
+
const explain = (e) => {
|
|
304
|
+
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.'))
|
|
305
|
+
if (e.code === 'unsupported-platform') die(t('esto solo está para Linux y macOS.', 'this is only available on Linux and macOS.'))
|
|
306
|
+
throw e
|
|
307
|
+
}
|
|
308
|
+
let st
|
|
309
|
+
try { st = serviceStatus({ name }) } catch (e) { explain(e) }
|
|
310
|
+
const pid = Number((() => { try { return fs.readFileSync(path.join(dir, 'agent.pid'), 'utf8') } catch (_) { return '' } })())
|
|
311
|
+
const running = !!pid && alive(pid)
|
|
312
|
+
|
|
313
|
+
if (action === 'status') {
|
|
314
|
+
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}`))
|
|
315
|
+
else if (st.active) console.log(t(`Servicio puesto y corriendo (${st.file}).`, `Service installed and running (${st.file}).`))
|
|
316
|
+
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.`))
|
|
317
|
+
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}`))
|
|
318
|
+
return
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
if (action === 'install') {
|
|
322
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
323
|
+
const cli = fs.realpathSync(fileURLToPath(new URL('./cli.js', import.meta.url)))
|
|
324
|
+
// Un agente que corre por su cuenta no se para: cerraría sus consolas.
|
|
325
|
+
const own = running && !st.active
|
|
326
|
+
let r
|
|
327
|
+
try { r = installService({ name, cli, dir, running: own }) } catch (e) { explain(e) }
|
|
328
|
+
console.log(t(`Servicio del perfil «${name}» puesto: ${r.file}`, `Service for profile "${name}" installed: ${r.file}`))
|
|
329
|
+
if (r.started) console.log(t('El agente ya corre como servicio.', 'The agent now runs as a service.'))
|
|
330
|
+
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.'))
|
|
331
|
+
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.'))
|
|
332
|
+
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.'))
|
|
333
|
+
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}`))
|
|
334
|
+
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}`))
|
|
335
|
+
console.log(t('Si cambias de versión de Node, vuelve a correr esta orden.', 'If you switch Node versions, run this command again.'))
|
|
336
|
+
return
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (!st.installed) { console.log(t(`El perfil «${name}» no tiene servicio.`, `Profile "${name}" has no service.`)); return }
|
|
340
|
+
// Quitarlo para el agente que corre bajo el servicio, y con él sus consolas.
|
|
341
|
+
if (st.active && !args.includes('--yes')) {
|
|
342
|
+
const inside = !!process.env.DOTRINO_TERMINAL_PROFILE_DIR && samePath(process.env.DOTRINO_TERMINAL_PROFILE_DIR, dir)
|
|
343
|
+
if (inside) die(t('esta consola es de ese mismo servicio: quitarlo la cerraría a mitad de la orden. Hazlo desde una terminal normal, o con --yes si eso es lo que quieres.', 'this console belongs to that very service: removing it would close it mid-command. Do it from a plain terminal, or with --yes if that is what you want.'))
|
|
344
|
+
const open = await openConsoles(dir)
|
|
345
|
+
if (open > 0) {
|
|
346
|
+
const ok = await ask(t(`El perfil «${name}» tiene ${open} consola(s) abierta(s); quitar el servicio las cierra. ¿Seguir? [s/N] `, `Profile "${name}" has ${open} open console(s); removing the service closes them. Continue? [y/N] `))
|
|
347
|
+
if (!/^[sy]/i.test(ok)) die(t('No se quitó.', 'Not removed.'))
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
let r
|
|
351
|
+
try { r = uninstallService({ name }) } catch (e) { explain(e) }
|
|
352
|
+
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.`))
|
|
353
|
+
}
|
|
354
|
+
|
|
268
355
|
/** Enlaza un perfil. Sin `--name`, lo pregunta. Uno ya enlazado no se pisa: eso es `enroll`. */
|
|
269
356
|
async function link () {
|
|
270
357
|
let name = opt('--name')
|
|
@@ -740,6 +827,7 @@ try {
|
|
|
740
827
|
if (cmd === 'lock') { await lock(); process.exit(0) }
|
|
741
828
|
if (cmd === 'vscode') { vscode(); process.exit(0) }
|
|
742
829
|
if (cmd === 'desktop') { await desktop(); process.exit(0) }
|
|
830
|
+
if (cmd === 'service') { await service(); process.exit(0) }
|
|
743
831
|
if (cmd === 'note') { await note(); process.exit(0) }
|
|
744
832
|
const dir = opt('--dir') || dataDir(opt('--name'))
|
|
745
833
|
if (cmd === 'open' || cmd === 'attach') captureEarly()
|
package/desktop.js
CHANGED
|
@@ -29,6 +29,7 @@ export const DESKTOP_TAG = 'desktop-v'
|
|
|
29
29
|
export const BINARY = 'dotrino-terminal-desktop'
|
|
30
30
|
const PRODUCT = 'dotrino-terminal-desktop'
|
|
31
31
|
|
|
32
|
+
/** @returns {any} */
|
|
32
33
|
const fail = (code, reason, extra = {}) => ({ ok: false, code, reason, ...extra })
|
|
33
34
|
|
|
34
35
|
/** La última release del escritorio. `{ ok:false }` si no se pudo mirar, que NO es «al día». */
|
|
@@ -40,7 +41,8 @@ export const latestDesktop = (opts = {}) =>
|
|
|
40
41
|
* y cómo se pone. Se le pregunta al gestor de paquetes por ESE archivo: mirar solo qué
|
|
41
42
|
* gestor hay se equivoca con un tarball en una máquina con `dpkg`.
|
|
42
43
|
*
|
|
43
|
-
* @
|
|
44
|
+
* @param {any} [o]
|
|
45
|
+
* @returns {any} `{ ok:true, kind:'deb'|'rpm'|'tar'|'mac', app? }` o `{ ok:false, code, reason }`
|
|
44
46
|
*/
|
|
45
47
|
export function installKind ({ exe, platform = process.platform, arch = process.arch, run = execFileSync, writable = canWrite } = {}) {
|
|
46
48
|
if (!exe) return fail('no-exe', 'the desktop app was not found')
|
|
@@ -83,6 +85,11 @@ function asRoot (cmd, args, { run, uid }) {
|
|
|
83
85
|
/**
|
|
84
86
|
* Pone el archivo ya verificado. Devuelve `{ ok:true }` o por qué no se pudo; si el archivo
|
|
85
87
|
* quedó bajado y sirve para instalarlo a mano, va en `file`.
|
|
88
|
+
*
|
|
89
|
+
* @param {string} file
|
|
90
|
+
* @param {any} how
|
|
91
|
+
* @param {any} [o]
|
|
92
|
+
* @returns {any}
|
|
86
93
|
*/
|
|
87
94
|
export function install (file, how, { exe, run = execFileSync, uid = process.getuid?.() } = {}) {
|
|
88
95
|
try {
|
|
@@ -131,7 +138,8 @@ export function install (file, how, { exe, run = execFileSync, uid = process.get
|
|
|
131
138
|
* Todo el camino: mirar, bajar, verificar, instalar. `say(step, data)` va contando por dónde
|
|
132
139
|
* va, para que quien lo enseñe lo diga en su idioma.
|
|
133
140
|
*
|
|
134
|
-
* @
|
|
141
|
+
* @param {any} [o]
|
|
142
|
+
* @returns {Promise<any>} `{ ok:true, version, updated, newer?, kind? }` o `{ ok:false, code, reason, file? }`
|
|
135
143
|
*/
|
|
136
144
|
export async function updateDesktop ({ exe, current, check = false, say = () => {}, latest = latestDesktop, fetchVerifiedImpl = fetchVerified, kindOf = installKind, installImpl = install } = {}) {
|
|
137
145
|
const r = await latest({ version: current })
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/terminal-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.40.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": {
|
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
"desktop.js",
|
|
20
20
|
"link.js",
|
|
21
21
|
"local.js",
|
|
22
|
+
"service.js",
|
|
22
23
|
"title.js",
|
|
23
24
|
"update.js",
|
|
24
25
|
"bin",
|
package/service.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* service.js — el agente como SERVICIO del usuario: arranca solo con la máquina.
|
|
3
|
+
*
|
|
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
|
+
* alguien se siente delante. `dotrino-terminal service install` lo deja a cargo del sistema:
|
|
7
|
+
*
|
|
8
|
+
* · Linux — una unidad de systemd DEL USUARIO (`~/.config/systemd/user`), sin `sudo`. Con
|
|
9
|
+
* «linger» arranca al encender, antes de que nadie inicie sesión; sin él, al iniciarla.
|
|
10
|
+
* · macOS — un LaunchAgent (`~/Library/LaunchAgents`): arranca al iniciar sesión.
|
|
11
|
+
*
|
|
12
|
+
* Es de usuario a propósito (CONVENCIONES §15): así el agente se sigue actualizando solo, y
|
|
13
|
+
* con alguien que lo levante ya puede reiniciarse para estrenar la versión nueva.
|
|
14
|
+
*
|
|
15
|
+
* Una unidad por PERFIL: cada perfil es un agente con su enlace.
|
|
16
|
+
*/
|
|
17
|
+
import fs from 'node:fs'
|
|
18
|
+
import os from 'node:os'
|
|
19
|
+
import path from 'node:path'
|
|
20
|
+
import { execFileSync } from 'node:child_process'
|
|
21
|
+
|
|
22
|
+
const fail = (code, message) => Object.assign(new Error(message), { code })
|
|
23
|
+
|
|
24
|
+
export const unitName = (name) => `dotrino-terminal-agent-${name}.service`
|
|
25
|
+
export const plistLabel = (name) => `com.dotrino.terminal-agent.${name}`
|
|
26
|
+
|
|
27
|
+
export function unitPath (name, home = os.homedir()) {
|
|
28
|
+
return path.join(home, '.config', 'systemd', 'user', unitName(name))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function plistPath (name, home = os.homedir()) {
|
|
32
|
+
return path.join(home, 'Library', 'LaunchAgents', `${plistLabel(name)}.plist`)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** systemd parte `ExecStart` por espacios: lo que los lleve va entre comillas. */
|
|
36
|
+
const unitArg = (s) => (/[\s"'\\$%]/.test(s) ? `"${s.replace(/[\\"]/g, '\\$&').replace(/%/g, '%%').replace(/\$/g, '$$$$')}"` : s)
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* La unidad de systemd. `--local`: sin TTY el agente nunca pregunta; si el perfil no está
|
|
40
|
+
* enlazado atiende solo a las ventanas de esta máquina, igual que cuando lo levanta una ventana.
|
|
41
|
+
*
|
|
42
|
+
* El PATH es el de quien instala: el de un servicio de usuario es mínimo y no trae el Node
|
|
43
|
+
* de nvm ni las herramientas que las consolas esperan encontrar.
|
|
44
|
+
*/
|
|
45
|
+
export function unitText ({ name, node, cli, pathEnv }) {
|
|
46
|
+
return `[Unit]
|
|
47
|
+
Description=Dotrino Terminal agent (${name})
|
|
48
|
+
After=network-online.target
|
|
49
|
+
Wants=network-online.target
|
|
50
|
+
|
|
51
|
+
[Service]
|
|
52
|
+
ExecStart=${unitArg(node)} ${unitArg(cli)} --name ${name} --local
|
|
53
|
+
Environment=${unitArg(`PATH=${pathEnv}`)}
|
|
54
|
+
Restart=always
|
|
55
|
+
RestartSec=3
|
|
56
|
+
|
|
57
|
+
[Install]
|
|
58
|
+
WantedBy=default.target
|
|
59
|
+
`
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const xml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
63
|
+
|
|
64
|
+
/** El LaunchAgent de macOS. `DOTRINO_SUPERVISED`: launchd lo levanta si sale (§15). */
|
|
65
|
+
export function plistText ({ name, node, cli, pathEnv, log }) {
|
|
66
|
+
const args = [node, cli, '--name', name, '--local'].map((a) => ` <string>${xml(a)}</string>`).join('\n')
|
|
67
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
68
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
69
|
+
<plist version="1.0"><dict>
|
|
70
|
+
<key>Label</key><string>${xml(plistLabel(name))}</string>
|
|
71
|
+
<key>ProgramArguments</key>
|
|
72
|
+
<array>
|
|
73
|
+
${args}
|
|
74
|
+
</array>
|
|
75
|
+
<key>EnvironmentVariables</key>
|
|
76
|
+
<dict>
|
|
77
|
+
<key>PATH</key><string>${xml(pathEnv)}</string>
|
|
78
|
+
<key>DOTRINO_SUPERVISED</key><string>1</string>
|
|
79
|
+
</dict>
|
|
80
|
+
<key>RunAtLoad</key><true/>
|
|
81
|
+
<key>KeepAlive</key><true/>
|
|
82
|
+
<key>StandardOutPath</key><string>${xml(log)}</string>
|
|
83
|
+
<key>StandardErrorPath</key><string>${xml(log)}</string>
|
|
84
|
+
</dict></plist>
|
|
85
|
+
`
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function quiet (run, cmd, args) {
|
|
89
|
+
try { run(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' }); return { ok: true } } catch (e) {
|
|
90
|
+
return { ok: false, reason: String(e.stderr || e.message).trim().split('\n').pop() }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function must (run, cmd, args) {
|
|
95
|
+
const r = quiet(run, cmd, args)
|
|
96
|
+
if (!r.ok) throw fail('service-command-failed', `${cmd} ${args.join(' ')}: ${r.reason}`)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** ¿Ya arrancan los servicios de ese usuario al encender? systemd lo apunta con un archivo. */
|
|
100
|
+
const lingers = (user, root = LINGER_DIR) => fs.existsSync(path.join(root, user))
|
|
101
|
+
const LINGER_DIR = '/var/lib/systemd/linger'
|
|
102
|
+
|
|
103
|
+
/** ¿Deja este sistema instalar el servicio? Lanza con el motivo si no. */
|
|
104
|
+
function platformOf ({ platform, run }) {
|
|
105
|
+
if (platform === 'darwin') return 'launchd'
|
|
106
|
+
if (platform !== 'linux') throw fail('unsupported-platform', `there is no service support for ${platform}`)
|
|
107
|
+
// Sin systemd de usuario (un contenedor, WSL sin systemd, otra init) no hay dónde ponerlo.
|
|
108
|
+
if (!quiet(run, 'systemctl', ['--user', 'show-environment']).ok) throw fail('no-user-systemd', 'this session has no systemd user manager')
|
|
109
|
+
return 'systemd'
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Instala y enciende el servicio del perfil `name`.
|
|
114
|
+
*
|
|
115
|
+
* `running`: ya hay un agente de ese perfil corriendo por su cuenta (lo levantó una ventana).
|
|
116
|
+
* Dos agentes con el mismo enlace son la misma llave, y parar ese cerraría sus consolas: el
|
|
117
|
+
* servicio queda puesto y toma el relevo cuando ese agente termine o al próximo arranque.
|
|
118
|
+
*
|
|
119
|
+
* @returns {{ kind:'systemd'|'launchd', file:string, started:boolean, boot?:boolean, lingerReason?:string }}
|
|
120
|
+
*/
|
|
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 }) {
|
|
122
|
+
const kind = platformOf({ platform, run })
|
|
123
|
+
if (kind === 'launchd') {
|
|
124
|
+
const file = plistPath(name, home)
|
|
125
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
126
|
+
fs.writeFileSync(file, plistText({ name, node, cli, pathEnv, log: path.join(dir, 'agent.log') }), { mode: 0o644 })
|
|
127
|
+
if (running) return { kind, file, started: false }
|
|
128
|
+
// Si ya estaba cargado (una instalación anterior), se recarga con el archivo nuevo.
|
|
129
|
+
quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
130
|
+
must(run, 'launchctl', ['bootstrap', `gui/${uid}`, file])
|
|
131
|
+
return { kind, file, started: true }
|
|
132
|
+
}
|
|
133
|
+
const file = unitPath(name, home)
|
|
134
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
135
|
+
fs.writeFileSync(file, unitText({ name, node, cli, pathEnv }), { mode: 0o644 })
|
|
136
|
+
must(run, 'systemctl', ['--user', 'daemon-reload'])
|
|
137
|
+
must(run, 'systemctl', ['--user', 'enable', unitName(name)])
|
|
138
|
+
if (!running) must(run, 'systemctl', ['--user', 'restart', unitName(name)])
|
|
139
|
+
// Arrancar al ENCENDER, sin que nadie inicie sesión. Si el sistema no lo deja sin
|
|
140
|
+
// administrador, el servicio arranca al iniciar sesión, y se dice.
|
|
141
|
+
if (lingers(user)) return { kind, file, started: !running, boot: true }
|
|
142
|
+
const linger = quiet(run, 'loginctl', ['enable-linger', user])
|
|
143
|
+
return { kind, file, started: !running, boot: linger.ok, ...(linger.ok ? {} : { lingerReason: linger.reason }) }
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Arranca el servicio ya instalado de ese perfil. `false` si el perfil no tiene servicio (o
|
|
148
|
+
* este sistema no los tiene): entonces el agente lo levanta la ventana, como siempre. Lo usa
|
|
149
|
+
* `dotrino-terminal` cuando no encuentra agente, para no levantar uno propio al lado de un
|
|
150
|
+
* servicio que el sistema arrancaría después con la misma llave.
|
|
151
|
+
*/
|
|
152
|
+
export function startService ({ name, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
|
|
153
|
+
if (platform === 'darwin') {
|
|
154
|
+
const file = plistPath(name, home)
|
|
155
|
+
if (!fs.existsSync(file)) return false
|
|
156
|
+
// Cargado y parado no puede estar (KeepAlive): si no corre, es que no está cargado.
|
|
157
|
+
quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
158
|
+
must(run, 'launchctl', ['bootstrap', `gui/${uid}`, file])
|
|
159
|
+
return true
|
|
160
|
+
}
|
|
161
|
+
if (platform !== 'linux' || !fs.existsSync(unitPath(name, home))) return false
|
|
162
|
+
must(run, 'systemctl', ['--user', 'start', unitName(name)])
|
|
163
|
+
return true
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 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 }) {
|
|
168
|
+
const kind = platformOf({ platform, run })
|
|
169
|
+
const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
|
|
170
|
+
if (!fs.existsSync(file)) return { kind, file, removed: false }
|
|
171
|
+
if (kind === 'launchd') quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
172
|
+
else must(run, 'systemctl', ['--user', 'disable', '--now', unitName(name)])
|
|
173
|
+
fs.rmSync(file)
|
|
174
|
+
if (kind === 'systemd') must(run, 'systemctl', ['--user', 'daemon-reload'])
|
|
175
|
+
return { kind, file, removed: true }
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** ¿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 }) {
|
|
180
|
+
const kind = platformOf({ platform, run })
|
|
181
|
+
const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
|
|
182
|
+
const installed = fs.existsSync(file)
|
|
183
|
+
const active = installed && (kind === 'launchd'
|
|
184
|
+
? quiet(run, 'launchctl', ['print', `gui/${uid}/${plistLabel(name)}`]).ok
|
|
185
|
+
: quiet(run, 'systemctl', ['--user', 'is-active', '--quiet', unitName(name)]).ok)
|
|
186
|
+
return { kind, file, installed, active }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export default { startService, installService, uninstallService, serviceStatus, unitText, plistText, unitName, unitPath, plistLabel, plistPath }
|