@dotrino/terminal-agent 0.54.1 → 0.56.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/access.js +3 -136
- package/bin/cli.js +2 -9
- package/bin/terminal.js +9 -55
- package/index.js +9 -21
- package/package.json +6 -6
- package/service.js +18 -349
package/access.js
CHANGED
|
@@ -1,138 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* access.js — la CLAVE de esta máquina
|
|
3
|
-
*
|
|
4
|
-
* Sin clave puesta no cambia nada: abre una consola cualquier aparato de la cuenta con `sign`,
|
|
5
|
-
* como siempre. Con clave, además de ser de la cuenta hay que escribirla en cada conexión
|
|
6
|
-
* remota. Las ventanas de ESTA máquina (el socket local) no la piden: son del mismo usuario
|
|
7
|
-
* que ya puede leer este archivo.
|
|
8
|
-
*
|
|
9
|
-
* En el disco queda la sal y el resumen (scrypt), nunca la clave. La clave viaja dentro de la
|
|
10
|
-
* sesión cifrada entre el aparato y el agente, así que el proxio no la ve.
|
|
11
|
-
*
|
|
12
|
-
* Los fallos se frenan POR AGENTE y no por sesión: quien prueba claves puede abrir otra
|
|
13
|
-
* conexión, y eso no le da intentos nuevos. A los TRES seguidos (dueño, 2026-10-07) empieza
|
|
14
|
-
* la espera, que se dobla con cada fallo más: es un bloqueo LOCAL de este servicio, nada más.
|
|
15
|
-
*
|
|
16
|
-
* Y a los tres fallos seguidos de UN MISMO aparato se avisa (`onIncident`): la bóveda se lo
|
|
17
|
-
* pone en la mesa a quien aprueba, que bloquea o ignora desde el teléfono. Avisar no decide
|
|
18
|
-
* nada aquí; el freno de arriba sigue igual.
|
|
2
|
+
* access.js — la CLAVE de esta máquina. La pieza es común (`@dotrino/remote-agent/access`, la
|
|
3
|
+
* usa también el escritorio remoto); se reexporta aquí para quien la importa por esta ruta.
|
|
19
4
|
*/
|
|
20
|
-
|
|
21
|
-
import fs from 'node:fs'
|
|
22
|
-
import path from 'node:path'
|
|
23
|
-
|
|
24
|
-
export const ACCESS_FILE = 'access.json'
|
|
25
|
-
export const MIN_LENGTH = 4
|
|
26
|
-
/** Fallos seguidos que se dejan pasar sin esperar: al tercero empieza la espera. */
|
|
27
|
-
export const FREE_TRIES = 3
|
|
28
|
-
/** Fallos seguidos de un mismo aparato que disparan el aviso a la bóveda. */
|
|
29
|
-
export const INCIDENT_AFTER = 3
|
|
30
|
-
const BASE_WAIT_MS = 30_000
|
|
31
|
-
const MAX_WAIT_MS = 60 * 60_000
|
|
32
|
-
const SCRYPT = { N: 1 << 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }
|
|
33
|
-
|
|
34
|
-
/** @type {(code: string, message: string, extra?: object) => Error & { code: string }} */
|
|
35
|
-
const fail = (code, message, extra = {}) => Object.assign(new Error(message), { code, ...extra })
|
|
36
|
-
/** @param {string} dir */
|
|
37
|
-
const file = (dir) => path.join(dir, ACCESS_FILE)
|
|
38
|
-
/** @type {(secret: unknown, salt: Buffer, params: import('node:crypto').ScryptOptions) => Buffer} */
|
|
39
|
-
const digest = (secret, salt, params) => crypto.scryptSync(String(secret).normalize('NFKC'), salt, 32, params)
|
|
40
|
-
|
|
41
|
-
/** Si esta máquina tiene clave. Un archivo que existe y no se puede leer NO es «sin clave»: se lanza. */
|
|
42
|
-
/** @param {string} dir */
|
|
43
|
-
export function hasAccessCode (dir) {
|
|
44
|
-
return readRecord(dir) !== null
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* @param {string} dir
|
|
49
|
-
* @returns {{ v: 1, salt: string, hash: string, params: import('node:crypto').ScryptOptions } | null}
|
|
50
|
-
*/
|
|
51
|
-
function readRecord (dir) {
|
|
52
|
-
let raw
|
|
53
|
-
try { raw = fs.readFileSync(file(dir), 'utf8') } catch (e) {
|
|
54
|
-
if (/** @type {Thrown} */ (e).code === 'ENOENT') return null
|
|
55
|
-
throw fail('access-unreadable', `cannot read ${ACCESS_FILE}: ${/** @type {Thrown} */ (e).message}`)
|
|
56
|
-
}
|
|
57
|
-
let r
|
|
58
|
-
try { r = JSON.parse(raw) } catch (_) { throw fail('access-unreadable', `${ACCESS_FILE} is not valid JSON`) }
|
|
59
|
-
if (r?.v !== 1 || typeof r.salt !== 'string' || typeof r.hash !== 'string' || !r.params) {
|
|
60
|
-
throw fail('access-unreadable', `${ACCESS_FILE} has an unknown shape`)
|
|
61
|
-
}
|
|
62
|
-
return r
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Pone o cambia la clave.
|
|
67
|
-
* @param {string} dir
|
|
68
|
-
* @param {unknown} secret
|
|
69
|
-
*/
|
|
70
|
-
export function setAccessCode (dir, secret) {
|
|
71
|
-
if (typeof secret !== 'string' || secret.length < MIN_LENGTH) throw fail('too-short', `the code needs at least ${MIN_LENGTH} characters`)
|
|
72
|
-
const salt = crypto.randomBytes(16)
|
|
73
|
-
const record = { v: 1, salt: salt.toString('base64'), hash: digest(secret, salt, SCRYPT).toString('base64'), params: SCRYPT }
|
|
74
|
-
const tmp = file(dir) + '.tmp'
|
|
75
|
-
fs.writeFileSync(tmp, JSON.stringify(record), { mode: 0o600 })
|
|
76
|
-
fs.renameSync(tmp, file(dir))
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Quita la clave.
|
|
81
|
-
* @param {string} dir
|
|
82
|
-
*/
|
|
83
|
-
export function clearAccessCode (dir) {
|
|
84
|
-
fs.rmSync(file(dir), { force: true })
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* Si `secret` es la clave de esta máquina. Sin frenos: para la orden local que la cambia.
|
|
89
|
-
* @param {string} dir
|
|
90
|
-
* @param {unknown} secret
|
|
91
|
-
*/
|
|
92
|
-
export function checkAccessCode (dir, secret) {
|
|
93
|
-
const r = readRecord(dir)
|
|
94
|
-
if (!r) throw fail('no-access-code', 'this machine has no code')
|
|
95
|
-
const want = Buffer.from(r.hash, 'base64')
|
|
96
|
-
const got = digest(secret ?? '', Buffer.from(r.salt, 'base64'), r.params)
|
|
97
|
-
return want.length === got.length && crypto.timingSafeEqual(want, got)
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
/**
|
|
101
|
-
* La puerta de un agente: comprueba la clave y frena los fallos seguidos. Una por agente,
|
|
102
|
-
* compartida por todas sus sesiones.
|
|
103
|
-
* @param {string} dir
|
|
104
|
-
* @param {{ now?: () => number, onIncident?: ((i: { device: string, tries: number }) => void) | null }} [opts]
|
|
105
|
-
* `onIncident`: un mismo aparato (`device`, su pubkey) falló `INCIDENT_AFTER` veces seguidas.
|
|
106
|
-
* Se llama UNA vez por racha; la racha se corta al acertar.
|
|
107
|
-
*/
|
|
108
|
-
export function makeGate (dir, { now = Date.now, onIncident = null } = {}) {
|
|
109
|
-
let fails = 0
|
|
110
|
-
let until = 0
|
|
111
|
-
/** Fallos seguidos por aparato: el aviso es sobre QUIÉN, y el freno sobre el agente. */
|
|
112
|
-
const byDevice = new Map()
|
|
113
|
-
return {
|
|
114
|
-
/** Si hay que escribir la clave para entrar. Lanza `access-unreadable` si no se puede saber. */
|
|
115
|
-
required: () => hasAccessCode(dir),
|
|
116
|
-
/**
|
|
117
|
-
* Lanza `wait` (con `retryMs`) o `bad-code`; si no lanza, la clave era la buena.
|
|
118
|
-
* `device` es quién la escribió (pubkey), para contar sus fallos y avisar.
|
|
119
|
-
*/
|
|
120
|
-
/**
|
|
121
|
-
* @param {unknown} secret
|
|
122
|
-
* @param {string | null} [device]
|
|
123
|
-
*/
|
|
124
|
-
check (secret, device = null) {
|
|
125
|
-
const left = until - now()
|
|
126
|
-
if (left > 0) throw fail('wait', 'too many wrong codes', { retryMs: left })
|
|
127
|
-
if (checkAccessCode(dir, secret)) { fails = 0; until = 0; if (device) byDevice.delete(device); return }
|
|
128
|
-
fails++
|
|
129
|
-
if (fails >= FREE_TRIES) until = now() + Math.min(BASE_WAIT_MS * 2 ** (fails - FREE_TRIES), MAX_WAIT_MS)
|
|
130
|
-
if (device) {
|
|
131
|
-
const n = (byDevice.get(device) || 0) + 1
|
|
132
|
-
byDevice.set(device, n)
|
|
133
|
-
if (n === INCIDENT_AFTER && onIncident) { try { onIncident({ device, tries: n }) } catch (_) {} }
|
|
134
|
-
}
|
|
135
|
-
throw fail('bad-code', 'wrong code', until ? { retryMs: until - now() } : {})
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
}
|
|
5
|
+
export * from '@dotrino/remote-agent/access'
|
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/bin/terminal.js
CHANGED
|
@@ -52,7 +52,7 @@ import { connectLocal } from '../local.js'
|
|
|
52
52
|
import { titleFilter } from '../title.js'
|
|
53
53
|
import { clipboardImage, uploadImage, typedPath } from '../clipboard.js'
|
|
54
54
|
import { farMessage as farMessageFor } from '../far-messages.js'
|
|
55
|
-
import {
|
|
55
|
+
import { lockCommand, askHidden as askHiddenOrFail } from '../access.js'
|
|
56
56
|
import { configureEditors, terminalProfile } from '../editors.js'
|
|
57
57
|
|
|
58
58
|
/** @type {{ version: string }} */
|
|
@@ -630,37 +630,6 @@ function ask (q) {
|
|
|
630
630
|
return new Promise((resolve) => rl.question(q, (a) => { rl.close(); resolve(a.trim()) }))
|
|
631
631
|
}
|
|
632
632
|
|
|
633
|
-
/**
|
|
634
|
-
* Pregunta algo que no debe verse al teclearlo. Solo en una TTY: una clave no se pasa por una tubería.
|
|
635
|
-
* @param {string} q
|
|
636
|
-
* @returns {Promise<string>}
|
|
637
|
-
*/
|
|
638
|
-
function askHidden (q) {
|
|
639
|
-
if (!process.stdin.isTTY) die(t('la clave se teclea: hace falta una terminal', 'the code is typed: a terminal is needed'))
|
|
640
|
-
process.stdout.write(q)
|
|
641
|
-
process.stdin.setRawMode(true)
|
|
642
|
-
process.stdin.resume()
|
|
643
|
-
return new Promise((resolve) => {
|
|
644
|
-
let typed = ''
|
|
645
|
-
const onData = (/** @type {Buffer} */ b) => {
|
|
646
|
-
// Una tecla que no es texto (flechas, Fin, el teclado numérico SIN Bloq Num) llega como una
|
|
647
|
-
// secuencia de escape: se descarta entera. Antes solo se saltaba el ESC y el resto («[F»)
|
|
648
|
-
// entraba en la clave sin que se viera, así que la clave guardada no era la tecleada.
|
|
649
|
-
const typedText = b.toString('utf8').replace(/\x1b(?:\[[0-9;?]*[ -/]*[@-~]|O.|.)?/g, '')
|
|
650
|
-
for (const ch of typedText) {
|
|
651
|
-
if (ch === '\r' || ch === '\n') {
|
|
652
|
-
process.stdin.off('data', onData); process.stdin.setRawMode(false); process.stdin.pause()
|
|
653
|
-
process.stdout.write('\n'); resolve(typed); return
|
|
654
|
-
}
|
|
655
|
-
if (ch === '\x03') { process.stdin.setRawMode(false); process.stdout.write('\n'); process.exit(130) }
|
|
656
|
-
if (ch === '\x7f' || ch === '\b') typed = typed.slice(0, -1)
|
|
657
|
-
else if (ch >= ' ') typed += ch
|
|
658
|
-
}
|
|
659
|
-
}
|
|
660
|
-
process.stdin.on('data', onData)
|
|
661
|
-
})
|
|
662
|
-
}
|
|
663
|
-
|
|
664
633
|
/**
|
|
665
634
|
* La clave de esta máquina (access.js). Se pone AQUÍ, en la máquina, y la piden solo los otros
|
|
666
635
|
* aparatos: quien está sentado delante ya es el usuario que puede leer y borrar el archivo, así
|
|
@@ -668,28 +637,13 @@ function askHidden (q) {
|
|
|
668
637
|
*/
|
|
669
638
|
async function lock () {
|
|
670
639
|
const dir = opt('--dir') || dataDir(opt('--name'))
|
|
671
|
-
|
|
672
|
-
console.log(
|
|
673
|
-
|
|
674
|
-
:
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
if (!hasAccessCode(dir)) { console.log(t('Esta máquina no tenía clave.', 'This machine had no code.')); return }
|
|
679
|
-
clearAccessCode(dir)
|
|
680
|
-
console.log(t('Clave quitada. Cualquier aparato de tu cuenta vuelve a abrir consolas aquí.', 'Code removed. Any device of your account opens consoles here again.'))
|
|
681
|
-
return
|
|
682
|
-
}
|
|
683
|
-
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
684
|
-
const changing = hasAccessCode(dir)
|
|
685
|
-
const first = await askHidden(t(`Clave nueva (PIN o contraseña, mínimo ${MIN_LENGTH}): `, `New code (PIN or password, at least ${MIN_LENGTH}): `))
|
|
686
|
-
if (first.length < MIN_LENGTH) die(t(`demasiado corta: mínimo ${MIN_LENGTH} caracteres`, `too short: at least ${MIN_LENGTH} characters`))
|
|
687
|
-
const again = await askHidden(t('Otra vez: ', 'Again: '))
|
|
688
|
-
if (again !== first) die(t('no coinciden. No se cambió nada.', 'they do not match. Nothing was changed.'))
|
|
689
|
-
setAccessCode(dir, first)
|
|
690
|
-
console.log(changing
|
|
691
|
-
? t('Clave cambiada. Los aparatos que ya estaban dentro siguen hasta que se desconecten.', 'Code changed. Devices already in stay until they disconnect.')
|
|
692
|
-
: t('Clave puesta. Tus otros aparatos la escriben para abrir consolas en esta máquina; las ventanas de esta máquina no la piden.', 'Code set. Your other devices type it to open consoles on this machine; this machine\'s own windows do not ask for it.'))
|
|
640
|
+
try {
|
|
641
|
+
console.log(await lockCommand({
|
|
642
|
+
dir, args, lang: /** @type {'es' | 'en'} */ (t('es', 'en')),
|
|
643
|
+
what: { es: 'abrir consolas', en: 'open consoles' },
|
|
644
|
+
localNote: { es: 'Las ventanas de esta máquina no la piden.', en: "This machine's own windows do not ask for it." }
|
|
645
|
+
}))
|
|
646
|
+
} catch (e) { die(/** @type {Thrown} */ (e).message) }
|
|
693
647
|
}
|
|
694
648
|
|
|
695
649
|
/**
|
|
@@ -835,7 +789,7 @@ async function goVia (conn, ref) {
|
|
|
835
789
|
// Lo tecleado aquí es la clave, no entrada para la consola.
|
|
836
790
|
process.stdin.off('data', earlyTap)
|
|
837
791
|
early.length = 0
|
|
838
|
-
const code = await
|
|
792
|
+
const code = await askHiddenOrFail(t(`Clave de ${name}: `, `Code for ${name}: `)).catch(() => die(t('la clave se teclea: hace falta una terminal', 'the code is typed: a terminal is needed')))
|
|
839
793
|
if (!code) die(t('sin clave no se entra.', 'no code, no entry.'))
|
|
840
794
|
probe = await farRequest(conn, { type: 'unlock', code }, 'unlocked')
|
|
841
795
|
if (probe.type === 'unlocked') break
|
package/index.js
CHANGED
|
@@ -46,7 +46,7 @@ import { listTransports, netReport } from '@dotrino/proxy-client'
|
|
|
46
46
|
import { shortId } from './far.js'
|
|
47
47
|
import { ConsoleHub, pieces, isTyped, cwdOf } from './consoles.js'
|
|
48
48
|
import { listenLocal } from './local.js'
|
|
49
|
-
import { makeGate } from './access.js'
|
|
49
|
+
import { makeGate, makeLock } from './access.js'
|
|
50
50
|
import { makeFar } from './far.js'
|
|
51
51
|
import { makeUploads } from './uploads.js'
|
|
52
52
|
import { readPiece } from './downloads.js'
|
|
@@ -151,17 +151,10 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
|
|
|
151
151
|
const release = () => { if (current) { current.detach(viewer); current = null } }
|
|
152
152
|
/** @type {(code: string, message: string, extra?: object) => unknown} */
|
|
153
153
|
const fail = (code, message, extra = {}) => session.send({ type: 'fail', code, message, ...extra })
|
|
154
|
-
// La clave de la máquina: una vez escrita vale para ESTA
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
const mayPass = () =>
|
|
158
|
-
if (origin !== 'remote' || !gate || unlocked) return true
|
|
159
|
-
try {
|
|
160
|
-
if (!gate.required()) return true
|
|
161
|
-
} catch (e) { fail(/** @type {Thrown} */ (e).code || 'access-unreadable', /** @type {Thrown} */ (e).message); return false }
|
|
162
|
-
fail('locked', 'this machine asks for its code')
|
|
163
|
-
return false
|
|
164
|
-
}
|
|
154
|
+
// La clave de la máquina (`@dotrino/remote-agent/access`): una vez escrita vale para ESTA
|
|
155
|
+
// conexión. Solo la piden las sesiones remotas; no saber si hay clave = no pasa.
|
|
156
|
+
const lock = makeLock({ gate: origin === 'remote' ? gate : null, device: viewer.device, send: (m) => session.send(m) })
|
|
157
|
+
const mayPass = () => lock.mayPass()
|
|
165
158
|
/** @param {any} msg lo que llegó de la sesión */
|
|
166
159
|
const takeSize = (msg) => { if (msg.cols && msg.rows) { size = { cols: msg.cols, rows: msg.rows }; viewer.size = size } }
|
|
167
160
|
// La etiqueta con la que se presenta quien mira (una ventana de la app de escritorio).
|
|
@@ -223,15 +216,7 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
|
|
|
223
216
|
|
|
224
217
|
session.on('message', (msg) => {
|
|
225
218
|
if (!msg || typeof msg !== 'object') return
|
|
226
|
-
if (msg
|
|
227
|
-
if (origin !== 'remote' || !gate) { session.send({ type: 'unlocked' }); return }
|
|
228
|
-
try {
|
|
229
|
-
if (gate.required()) gate.check(msg.code, viewer.device)
|
|
230
|
-
unlocked = true
|
|
231
|
-
session.send({ type: 'unlocked' })
|
|
232
|
-
} catch (e) { fail(/** @type {Thrown} */ (e).code || 'access-unreadable', /** @type {Thrown} */ (e).message, /** @type {Thrown} */ (e).retryMs ? { retryMs: /** @type {Thrown} */ (e).retryMs } : {}) }
|
|
233
|
-
return
|
|
234
|
-
}
|
|
219
|
+
if (lock.handle(msg)) return
|
|
235
220
|
if (!mayPass()) return
|
|
236
221
|
// Qué versión corre: tras actualizar el paquete, el agente en marcha sigue con la anterior.
|
|
237
222
|
if (msg.type === 'version') { session.send({ type: 'version', version: VERSION }); return }
|
|
@@ -399,6 +384,9 @@ export async function startAgent (opts = {}) {
|
|
|
399
384
|
let stopped = false
|
|
400
385
|
const startRemote = () => startRemoteAgent({
|
|
401
386
|
label: LABEL,
|
|
387
|
+
// Solo quien tenga `terminal` en el acta abre consolas (auditoría del 2026-11-16): con `sign`
|
|
388
|
+
// bastaba, y cualquier aparato de la cuenta —un bot, un navegador prestado— abría una shell.
|
|
389
|
+
needs: ['terminal'],
|
|
402
390
|
dir,
|
|
403
391
|
proxyUrl: opts.proxyUrl,
|
|
404
392
|
quiet: opts.quiet,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/terminal-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.56.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.139.0",
|
|
41
|
+
"@dotrino/proxy-client": "0.49.1",
|
|
42
|
+
"@dotrino/remote-agent": "0.39.2",
|
|
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 }
|