@dotrino/terminal-agent 0.54.0 → 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/local.js CHANGED
@@ -30,25 +30,38 @@ import path from 'node:path'
30
30
  import crypto from 'node:crypto'
31
31
 
32
32
  export const SOCKET_NAME = 'terminal.sock'
33
+ /** @typedef {import('./types/agent.js').SessionLike} SessionLike */
34
+ /** Quien escucha un evento de una sesión local: el mensaje, o nada al cerrar. */
35
+ /** @typedef {Record<'message' | 'close', ((msg?: any) => void)[]>} Handlers */
36
+
37
+ /** @param {string} dir */
33
38
  export const socketPath = (dir) => path.join(dir, SOCKET_NAME)
34
39
  /** Windows: el archivo que dice cómo se llama la tubería del agente y con qué llave se entra. */
35
40
  export const PIPE_FILE = 'terminal.pipe'
41
+ /** @param {string} dir */
36
42
  export const pipeFile = (dir) => path.join(dir, PIPE_FILE)
43
+ /** @param {string} platform */
37
44
  const isWindows = (platform) => platform === 'win32'
38
45
  /** Lo más largo que admite la ruta de un socket Unix (macOS: 104 bytes con el nulo; Linux: 108). */
39
46
  export const MAX_SOCKET_PATH = 103
40
47
 
48
+ /** @param {string} file */
41
49
  function checkLength (file) {
42
50
  if (Buffer.byteLength(file) > MAX_SOCKET_PATH) {
43
51
  throw Object.assign(new Error(`socket path too long (${Buffer.byteLength(file)} bytes, max ${MAX_SOCKET_PATH}): ${file}. Use a shorter DOTRINO_AGENT_HOME`), { code: 'ESOCKPATH' })
44
52
  }
45
53
  }
46
54
 
47
- /** Mensajes JSON por líneas sobre un socket. */
55
+ /**
56
+ * Mensajes JSON por líneas sobre un socket.
57
+ * @param {import('node:net').Socket} sock
58
+ * @param {(msg: any) => void} onMessage lo que llega es JSON de fuera: quien lo recibe lo comprueba
59
+ * @returns {(obj: object) => void}
60
+ */
48
61
  function framed (sock, onMessage) {
49
62
  let buf = ''
50
63
  sock.setEncoding('utf8')
51
- sock.on('data', (chunk) => {
64
+ sock.on('data', (/** @type {string} */ chunk) => {
52
65
  buf += chunk
53
66
  let i
54
67
  while ((i = buf.indexOf('\n')) >= 0) {
@@ -62,7 +75,11 @@ function framed (sock, onMessage) {
62
75
  return (obj) => { if (!sock.destroyed) sock.write(JSON.stringify(obj) + '\n') }
63
76
  }
64
77
 
65
- /** ¿Contesta alguien en ese socket? */
78
+ /**
79
+ * ¿Contesta alguien en ese socket?
80
+ * @param {string} file
81
+ * @returns {Promise<boolean>}
82
+ */
66
83
  function answers (file) {
67
84
  return new Promise((resolve) => {
68
85
  const s = net.connect(file)
@@ -71,30 +88,41 @@ function answers (file) {
71
88
  })
72
89
  }
73
90
 
74
- /** Windows: lo apuntado por el agente que escucha (o escuchó) en esa carpeta. `null` si no hay. */
91
+ /**
92
+ * Windows: lo apuntado por el agente que escucha (o escuchó) en esa carpeta. `null` si no hay.
93
+ * @param {string} dir
94
+ * @returns {{ pipe: string, key: string } | null}
95
+ */
75
96
  function readPipe (dir) {
76
97
  let text
77
- try { text = fs.readFileSync(pipeFile(dir), 'utf8') } catch (e) { if (e.code === 'ENOENT') return null; throw e }
98
+ try { text = fs.readFileSync(pipeFile(dir), 'utf8') } catch (e) { if (/** @type {Thrown} */ (e).code === 'ENOENT') return null; throw e }
78
99
  const rec = JSON.parse(text)
79
100
  if (typeof rec?.pipe !== 'string' || typeof rec?.key !== 'string') throw Object.assign(new Error(`${pipeFile(dir)} is malformed`), { code: 'EBADPIPE' })
80
101
  return rec
81
102
  }
82
103
 
83
- /** La sesión de una conexión: misma forma que las de `@dotrino/remote-agent`. */
104
+ /**
105
+ * La sesión de una conexión: misma forma que las de `@dotrino/remote-agent`.
106
+ * @param {import('node:net').Socket} sock
107
+ * @param {(session: SessionLike) => void} serve
108
+ * @param {string | null} key Windows: la llave que la ventana manda en su primera línea
109
+ */
84
110
  function sessionOf (sock, serve, key) {
111
+ /** @type {Handlers} */
85
112
  const h = { message: [], close: [] }
86
113
  let closed = false
87
114
  let allowed = !key
115
+ /** @type {SessionLike} */
88
116
  const session = {
89
117
  device: null,
90
- send: async (payload) => { if (allowed) write(payload) },
91
- on (ev, cb) { h[ev]?.push(cb); return this }
118
+ send: async (/** @type {object} */ payload) => { if (allowed) write(payload) },
119
+ on (/** @type {'message' | 'close'} */ ev, /** @type {(msg?: any) => void} */ cb) { h[ev]?.push(cb); return this }
92
120
  }
93
121
  const write = framed(sock, (msg) => {
94
122
  // Windows: la primera línea es la llave. Cualquier otra cosa corta, sin contestar.
95
123
  if (!allowed) {
96
124
  const got = Buffer.from(String(msg?.type === 'local-auth' ? msg.key : ''))
97
- const want = Buffer.from(key)
125
+ const want = Buffer.from(/** @type {string} */ (key))
98
126
  if (got.length !== want.length || !crypto.timingSafeEqual(got, want)) { sock.destroy(); return }
99
127
  allowed = true
100
128
  serve(session)
@@ -113,13 +141,16 @@ function sessionOf (sock, serve, key) {
113
141
  * `@dotrino/remote-agent` (`send`, `on('message'|'close')`), así que `serve` es
114
142
  * `serveSession` tal cual.
115
143
  *
116
- * @param {{ dir: string, serve: (session: object) => void, platform?: string }} opts
144
+ * @param {{ dir: string, serve: (session: SessionLike) => void, platform?: string }} opts
117
145
  * @returns {Promise<{ path: string, close: () => void }>}
118
146
  */
119
147
  export async function listenLocal ({ dir, serve, platform = process.platform }) {
120
148
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
121
149
  fs.chmodSync(dir, 0o700)
122
- let file, key = null
150
+ /** @type {string} */
151
+ let file
152
+ /** @type {string | null} */
153
+ let key = null
123
154
  if (isWindows(platform)) {
124
155
  const old = readPipe(dir)
125
156
  if (old && await answers(old.pipe)) throw Object.assign(new Error(`another agent is already listening on ${old.pipe}`), { code: 'EALREADY' })
@@ -133,16 +164,17 @@ export async function listenLocal ({ dir, serve, platform = process.platform })
133
164
  fs.rmSync(file) // lo dejó un agente que murió sin limpiar
134
165
  }
135
166
  }
167
+ /** @type {Set<import('node:net').Socket>} */
136
168
  const socks = new Set()
137
169
  const server = net.createServer((sock) => {
138
170
  socks.add(sock)
139
171
  sock.on('close', () => socks.delete(sock))
140
172
  sessionOf(sock, serve, key)
141
173
  })
142
- await new Promise((resolve, reject) => {
174
+ await /** @type {Promise<void>} */ (new Promise((resolve, reject) => {
143
175
  server.once('error', reject)
144
176
  server.listen({ path: file, ...(key ? { readableAll: true, writableAll: true } : {}) }, () => { server.off('error', reject); resolve() })
145
- })
177
+ }))
146
178
  if (key) {
147
179
  // Se apunta DESPUÉS de escuchar: quien lo lea encuentra la tubería ya abierta.
148
180
  const tmp = pipeFile(dir) + '.tmp'
@@ -169,10 +201,13 @@ export async function listenLocal ({ dir, serve, platform = process.platform })
169
201
  *
170
202
  * @param {string} dir la carpeta del enlace del agente.
171
203
  * @param {{ platform?: string }} [opts]
172
- * @returns {Promise<{ send:(obj:object)=>void, on:(ev:'message'|'close', cb:Function)=>void, close:()=>void }>}
204
+ * @returns {Promise<{ send:(obj:object)=>void, on:(ev:'message'|'close', cb:(msg?: any) => void)=>void, close:()=>void }>}
173
205
  */
174
206
  export function connectLocal (dir, { platform = process.platform } = {}) {
175
- let file, key = null
207
+ /** @type {string} */
208
+ let file
209
+ /** @type {string | null} */
210
+ let key = null
176
211
  if (isWindows(platform)) {
177
212
  const rec = readPipe(dir)
178
213
  if (!rec) return Promise.reject(Object.assign(new Error(`no terminal agent is listening in ${dir}`), { code: 'ENOAGENT' }))
@@ -183,6 +218,7 @@ export function connectLocal (dir, { platform = process.platform } = {}) {
183
218
  }
184
219
  return new Promise((resolve, reject) => {
185
220
  const sock = net.connect(file)
221
+ /** @type {Handlers} */
186
222
  const h = { message: [], close: [] }
187
223
  const send = framed(sock, (msg) => { for (const cb of h.message) cb(msg) })
188
224
  let connected = false
@@ -190,10 +226,10 @@ export function connectLocal (dir, { platform = process.platform } = {}) {
190
226
  connected = true
191
227
  if (key) send({ type: 'local-auth', key })
192
228
  sock.on('close', () => { for (const cb of h.close) cb() })
193
- resolve({ send, on: (ev, cb) => { h[ev]?.push(cb) }, close: () => sock.end() })
229
+ resolve({ send, on: (/** @type {'message' | 'close'} */ ev, /** @type {(msg?: any) => void} */ cb) => { h[ev]?.push(cb) }, close: () => sock.end() })
194
230
  })
195
231
  // Tras conectar, un error acaba en 'close', que ya se avisa arriba.
196
- sock.on('error', (e) => {
232
+ sock.on('error', (/** @type {Thrown} */ e) => {
197
233
  if (connected) return
198
234
  // Hay agente pero no deja entrar: no es lo mismo que no haber ninguno.
199
235
  if (e.code === 'EPERM' || e.code === 'EACCES') reject(Object.assign(new Error(`the terminal agent on ${file} refused this window (${e.code})`), { code: 'EAGENTACCESS', cause: e }))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/terminal-agent",
3
- "version": "0.54.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": {
@@ -28,7 +28,8 @@
28
28
  "update.js",
29
29
  "uploads.js",
30
30
  "bin",
31
- "skills"
31
+ "skills",
32
+ "types"
32
33
  ],
33
34
  "scripts": {
34
35
  "start": "node bin/cli.js",
@@ -36,11 +37,11 @@
36
37
  "type-check": "tsc --noEmit"
37
38
  },
38
39
  "dependencies": {
39
- "@dotrino/identity": "0.135.0",
40
- "@dotrino/proxy-client": "0.46.0",
41
- "@dotrino/remote-agent": "0.32.1",
42
- "@dotrino/update": "0.9.2",
43
- "@dotrino/vault": "0.115.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",
44
45
  "@xterm/addon-serialize": "0.13.0",
45
46
  "@xterm/headless": "5.5.0",
46
47
  "jsonc-parser": "3.3.1",
package/service.js CHANGED
@@ -2,298 +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
- * 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
- * · Windows — una entrada en `HKCU\…\Run`: arranca al iniciar sesión, sin administrador.
12
- * Lanza un SUPERVISOR (`dotrino-terminal-agent supervise`) que se vuelve a abrir sin
13
- * ventana y levanta el agente cada vez que sale, como `Restart=always`. No es el
14
- * Programador de tareas porque crear una tarea al iniciar sesión pide derechos que una
15
- * cuenta normal no tiene, y no es un servicio de Windows porque ese pide administrador.
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.
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
+ *
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.
21
13
  */
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
- const fail = (code, message) => Object.assign(new Error(message), { code })
28
-
29
- export const unitName = (name) => `dotrino-terminal-agent-${name}.service`
30
- export const plistLabel = (name) => `com.dotrino.terminal-agent.${name}`
14
+ import { makeService, supervise as superviseAgent, RUN_KEY, RESTART_MS, supervisorPidFile } from '@dotrino/remote-agent/service'
31
15
 
32
- export function unitPath (name, home = os.homedir()) {
33
- return path.join(home, '.config', 'systemd', 'user', unitName(name))
34
- }
16
+ /** @param {string} name */
17
+ const agentArgs = (name) => ['--name', name, '--local']
35
18
 
36
- export function plistPath (name, home = os.homedir()) {
37
- return path.join(home, 'Library', 'LaunchAgents', `${plistLabel(name)}.plist`)
38
- }
19
+ const svc = makeService({ id: 'terminal-agent', title: 'Dotrino Terminal agent', runPrefix: 'DotrinoTerminalAgent', agentArgs })
39
20
 
40
- /** Windows: la clave de lo que arranca al iniciar sesión, y el nombre del valor de cada perfil. */
41
- export const RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
42
- export const runValue = (name) => `DotrinoTerminalAgent-${name}`
43
- /** Lo que se apunta en la clave: Node, el CLI y el supervisor del perfil. */
44
- export const runCommand = ({ name, node, cli }) => `"${node}" "${cli}" supervise --name ${name}`
45
- export const supervisorPidFile = (dir) => path.join(dir, 'supervisor.pid')
46
- /** Cuánto espera el supervisor antes de volver a levantar el agente (como `RestartSec`). */
47
- export const RESTART_MS = 3000
48
-
49
- /** systemd parte `ExecStart` por espacios: lo que los lleve va entre comillas. */
50
- const unitArg = (s) => (/[\s"'\\$%]/.test(s) ? `"${s.replace(/[\\"]/g, '\\$&').replace(/%/g, '%%').replace(/\$/g, '$$$$')}"` : s)
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 }
51
26
 
52
27
  /**
53
- * La unidad de systemd. `--local`: sin TTY el agente nunca pregunta; si el perfil no está
54
- * enlazado atiende solo a las ventanas de esta máquina, igual que cuando lo levanta una ventana.
55
- *
56
- * El PATH es el de quien instala: el de un servicio de usuario es mínimo y no trae el Node
57
- * de nvm ni las herramientas que las consolas esperan encontrar.
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
58
30
  */
59
- export function unitText ({ name, node, cli, pathEnv }) {
60
- return `[Unit]
61
- Description=Dotrino Terminal agent (${name})
62
- After=network-online.target
63
- Wants=network-online.target
64
-
65
- [Service]
66
- ExecStart=${unitArg(node)} ${unitArg(cli)} --name ${name} --local
67
- Environment=${unitArg(`PATH=${pathEnv}`)}
68
- Restart=always
69
- RestartSec=3
70
-
71
- [Install]
72
- WantedBy=default.target
73
- `
74
- }
75
-
76
- const xml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
77
-
78
- /** El LaunchAgent de macOS. `DOTRINO_SUPERVISED`: launchd lo levanta si sale (§15). */
79
- export function plistText ({ name, node, cli, pathEnv, log }) {
80
- const args = [node, cli, '--name', name, '--local'].map((a) => ` <string>${xml(a)}</string>`).join('\n')
81
- return `<?xml version="1.0" encoding="UTF-8"?>
82
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
83
- <plist version="1.0"><dict>
84
- <key>Label</key><string>${xml(plistLabel(name))}</string>
85
- <key>ProgramArguments</key>
86
- <array>
87
- ${args}
88
- </array>
89
- <key>EnvironmentVariables</key>
90
- <dict>
91
- <key>PATH</key><string>${xml(pathEnv)}</string>
92
- <key>DOTRINO_SUPERVISED</key><string>1</string>
93
- </dict>
94
- <key>RunAtLoad</key><true/>
95
- <key>KeepAlive</key><true/>
96
- <key>StandardOutPath</key><string>${xml(log)}</string>
97
- <key>StandardErrorPath</key><string>${xml(log)}</string>
98
- </dict></plist>
99
- `
100
- }
101
-
102
- function quiet (run, cmd, args) {
103
- try { run(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' }); return { ok: true } } catch (e) {
104
- return { ok: false, reason: String(e.stderr || e.message).trim().split('\n').pop() }
105
- }
106
- }
107
-
108
- function must (run, cmd, args) {
109
- const r = quiet(run, cmd, args)
110
- if (!r.ok) throw fail('service-command-failed', `${cmd} ${args.join(' ')}: ${r.reason}`)
111
- }
112
-
113
- /** ¿Ya arrancan los servicios de ese usuario al encender? systemd lo apunta con un archivo. */
114
- const lingers = (user, root = LINGER_DIR) => fs.existsSync(path.join(root, user))
115
- const LINGER_DIR = '/var/lib/systemd/linger'
116
-
117
- /** ¿Deja este sistema instalar el servicio? Lanza con el motivo si no. */
118
- function platformOf ({ platform, run }) {
119
- if (platform === 'darwin') return 'launchd'
120
- if (platform === 'win32') return 'run-key'
121
- if (platform !== 'linux') throw fail('unsupported-platform', `there is no service support for ${platform}`)
122
- // Sin systemd de usuario (un contenedor, WSL sin systemd, otra init) no hay dónde ponerlo.
123
- if (!quiet(run, 'systemctl', ['--user', 'show-environment']).ok) throw fail('no-user-systemd', 'this session has no systemd user manager')
124
- return 'systemd'
125
- }
126
-
127
- const readPid = (file) => { try { return Number(fs.readFileSync(file, 'utf8')) || 0 } catch (e) { if (e.code === 'ENOENT') return 0; throw e } }
128
- const alive = (pid) => { try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' } }
129
- const runKeyFile = (name) => `${RUN_KEY}\\${runValue(name)}`
130
- const hasRunKey = (name, run) => quiet(run, 'reg', ['query', RUN_KEY, '/v', runValue(name)]).ok
131
-
132
- /** PowerShell: una cadena entre comillas simples. */
133
- const psQuote = (s) => `'${String(s).replace(/'/g, "''")}'`
134
-
135
- /**
136
- * Windows: lanza el supervisor del perfil, ya sin ventana.
137
- *
138
- * Desde una sesión SSH no vale un proceso aparte: sshd mete la sesión en un objeto de trabajo y
139
- * al cerrarla mata todo lo que lanzó, y Node no puede pedir salirse de él. Ahí lo crea WMI
140
- * (`Win32_Process.Create`), que lo lanza fuera de la sesión, y con la misma línea que queda en
141
- * `HKCU\…\Run`: así se prueba también la que correrá al iniciar sesión.
142
- *
143
- * Una cuenta sin administrador no puede pedirle eso a WMI desde SSH. Entonces no queda nada
144
- * corriendo ahora (lo que se lanzara moriría al cerrar la sesión) y se devuelve el motivo: la
145
- * entrada de `Run` ya está puesta y lo arranca al iniciar sesión.
146
- *
147
- * @returns {{ ok: true } | { ok: false, reason: string }}
148
- */
149
- function spawnSupervisor ({ name, node, cli, spawn, run, env }) {
150
- if (env.SSH_CONNECTION || env.SSH_CLIENT) {
151
- 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)" }`
152
- const r = quiet(run, 'powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script])
153
- return r.ok ? { ok: true } : { ok: false, reason: 'Windows (WMI) does not let this account start it from SSH' }
154
- }
155
- const child = spawn(node, [cli, 'supervise', '--name', name], { detached: true, windowsHide: true, stdio: 'ignore', env: { ...env, DOTRINO_SUPERVISOR: '1' } })
156
- child.unref()
157
- return { ok: true }
158
- }
159
-
160
- /**
161
- * El supervisor de Windows: levanta el agente del perfil y lo vuelve a levantar cada vez que
162
- * sale (también cuando se reinicia para estrenar una versión: §15, `DOTRINO_SUPERVISED`).
163
- * Uno por perfil: si ya hay otro vivo, lanza `already-supervised`.
164
- */
165
- export function supervise ({ name, dir, node = process.execPath, cli, spawn = childSpawn }) {
166
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
167
- const pidFile = supervisorPidFile(dir)
168
- const other = readPid(pidFile)
169
- if (other && other !== process.pid && alive(other)) throw fail('already-supervised', `profile ${name} already has a supervisor (pid ${other})`)
170
- fs.writeFileSync(pidFile, String(process.pid))
171
- let stopped = false
172
- let child = null
173
- const start = () => {
174
- const fd = fs.openSync(path.join(dir, 'agent.log'), 'a', 0o600)
175
- child = spawn(node, [cli, '--name', name, '--local'], { windowsHide: true, stdio: ['ignore', fd, fd], env: { ...process.env, DOTRINO_SUPERVISED: '1' } })
176
- fs.closeSync(fd)
177
- child.on('exit', () => { child = null; if (!stopped) setTimeout(start, RESTART_MS) })
178
- }
179
- start()
180
- return {
181
- stop: () => {
182
- stopped = true
183
- try { child?.kill() } catch (_) {}
184
- try { if (readPid(pidFile) === process.pid) fs.rmSync(pidFile) } catch (_) {}
185
- }
186
- }
187
- }
188
-
189
- /** Windows: para el supervisor y después el agente (matar el supervisor no se lleva al hijo). */
190
- function stopSupervised (dir) {
191
- for (const file of [supervisorPidFile(dir), path.join(dir, 'agent.pid')]) {
192
- const pid = readPid(file)
193
- if (pid && alive(pid)) process.kill(pid)
194
- }
195
- fs.rmSync(supervisorPidFile(dir), { force: true })
196
- }
197
-
198
- /**
199
- * Instala y enciende el servicio del perfil `name`.
200
- *
201
- * `running`: ya hay un agente de ese perfil corriendo por su cuenta (lo levantó una ventana).
202
- * Dos agentes con el mismo enlace son la misma llave, y parar ese cerraría sus consolas: el
203
- * servicio queda puesto y toma el relevo cuando ese agente termine o al próximo arranque.
204
- *
205
- * @returns {{ kind:'systemd'|'launchd'|'run-key', file:string, started:boolean, boot?:boolean, lingerReason?:string, startReason?:string }}
206
- */
207
- 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 }) {
208
- const kind = platformOf({ platform, run })
209
- if (kind === 'run-key') {
210
- must(run, 'reg', ['add', RUN_KEY, '/v', runValue(name), '/t', 'REG_SZ', '/d', runCommand({ name, node, cli }), '/f'])
211
- if (running) return { kind, file: runKeyFile(name), started: false }
212
- const s = spawnSupervisor({ name, node, cli, spawn, run, env })
213
- return { kind, file: runKeyFile(name), started: s.ok, ...(s.ok ? {} : { startReason: s.reason }) }
214
- }
215
- if (kind === 'launchd') {
216
- const file = plistPath(name, home)
217
- fs.mkdirSync(path.dirname(file), { recursive: true })
218
- fs.writeFileSync(file, plistText({ name, node, cli, pathEnv, log: path.join(dir, 'agent.log') }), { mode: 0o644 })
219
- if (running) return { kind, file, started: false }
220
- // Si ya estaba cargado (una instalación anterior), se recarga con el archivo nuevo.
221
- quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
222
- must(run, 'launchctl', ['bootstrap', `gui/${uid}`, file])
223
- return { kind, file, started: true }
224
- }
225
- const file = unitPath(name, home)
226
- fs.mkdirSync(path.dirname(file), { recursive: true })
227
- fs.writeFileSync(file, unitText({ name, node, cli, pathEnv }), { mode: 0o644 })
228
- must(run, 'systemctl', ['--user', 'daemon-reload'])
229
- must(run, 'systemctl', ['--user', 'enable', unitName(name)])
230
- if (!running) must(run, 'systemctl', ['--user', 'restart', unitName(name)])
231
- // Arrancar al ENCENDER, sin que nadie inicie sesión. Si el sistema no lo deja sin
232
- // administrador, el servicio arranca al iniciar sesión, y se dice.
233
- if (lingers(user)) return { kind, file, started: !running, boot: true }
234
- const linger = quiet(run, 'loginctl', ['enable-linger', user])
235
- return { kind, file, started: !running, boot: linger.ok, ...(linger.ok ? {} : { lingerReason: linger.reason }) }
236
- }
237
-
238
- /**
239
- * Arranca el servicio ya instalado de ese perfil. `false` si el perfil no tiene servicio (o
240
- * este sistema no los tiene): entonces el agente lo levanta la ventana, como siempre. Lo usa
241
- * `dotrino-terminal` cuando no encuentra agente, para no levantar uno propio al lado de un
242
- * servicio que el sistema arrancaría después con la misma llave.
243
- */
244
- 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 }) {
245
- if (platform === 'win32') {
246
- if (!hasRunKey(name, run)) return false
247
- const pid = readPid(supervisorPidFile(dir))
248
- if (pid && alive(pid)) return true
249
- // Sin poder dejarlo corriendo (cuenta normal por SSH), lo levanta la ventana, como sin servicio.
250
- return spawnSupervisor({ name, node, cli, spawn, run, env }).ok
251
- }
252
- if (platform === 'darwin') {
253
- const file = plistPath(name, home)
254
- if (!fs.existsSync(file)) return false
255
- // Cargado y parado no puede estar (KeepAlive): si no corre, es que no está cargado.
256
- quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
257
- must(run, 'launchctl', ['bootstrap', `gui/${uid}`, file])
258
- return true
259
- }
260
- if (platform !== 'linux' || !fs.existsSync(unitPath(name, home))) return false
261
- must(run, 'systemctl', ['--user', 'start', unitName(name)])
262
- return true
263
- }
264
-
265
- /** Para el servicio y lo quita. El enlace y los ajustes del perfil no se tocan. */
266
- export function uninstallService ({ name, dir, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
267
- const kind = platformOf({ platform, run })
268
- if (kind === 'run-key') {
269
- if (!hasRunKey(name, run)) return { kind, file: runKeyFile(name), removed: false }
270
- stopSupervised(dir)
271
- must(run, 'reg', ['delete', RUN_KEY, '/v', runValue(name), '/f'])
272
- return { kind, file: runKeyFile(name), removed: true }
273
- }
274
- const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
275
- if (!fs.existsSync(file)) return { kind, file, removed: false }
276
- if (kind === 'launchd') quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
277
- else must(run, 'systemctl', ['--user', 'disable', '--now', unitName(name)])
278
- fs.rmSync(file)
279
- if (kind === 'systemd') must(run, 'systemctl', ['--user', 'daemon-reload'])
280
- return { kind, file, removed: true }
281
- }
282
-
283
- /** ¿Está puesto, y está corriendo ahora bajo el sistema? */
284
- export function serviceStatus ({ name, dir, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
285
- const kind = platformOf({ platform, run })
286
- if (kind === 'run-key') {
287
- const installed = hasRunKey(name, run)
288
- const pid = installed ? readPid(supervisorPidFile(dir)) : 0
289
- return { kind, file: runKeyFile(name), installed, active: !!pid && alive(pid) }
290
- }
291
- const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
292
- const installed = fs.existsSync(file)
293
- const active = installed && (kind === 'launchd'
294
- ? quiet(run, 'launchctl', ['print', `gui/${uid}/${plistLabel(name)}`]).ok
295
- : quiet(run, 'systemctl', ['--user', 'is-active', '--quiet', unitName(name)]).ok)
296
- return { kind, file, installed, active }
297
- }
31
+ export const supervise = (o) => superviseAgent({ ...o, args: agentArgs(o.name) })
298
32
 
299
33
  export default { supervise, runCommand, runValue, RUN_KEY, startService, installService, uninstallService, serviceStatus, unitText, plistText, unitName, unitPath, plistLabel, plistPath }
@@ -0,0 +1,58 @@
1
+ // Las formas de datos del agente. Solo tipos: el código es JS con JSDoc.
2
+
3
+ /** Quién mira una consola: una sesión (de una ventana de esta máquina o de otro aparato). */
4
+ export interface Viewer {
5
+ onOut (data: string): void
6
+ onExit (code: number, why?: { byOther: boolean }): void
7
+ onMeta? (info: ConsoleInfo): void
8
+ /** 'local' (una ventana de esta máquina) | 'remote' (otro aparato). Sin él, un mirón interno. */
9
+ origin?: 'local' | 'remote'
10
+ /** La pubkey del aparato, si es remoto. */
11
+ device?: string | null
12
+ /** La etiqueta con la que se presentó (la ventana de la app de escritorio). */
13
+ tag?: string
14
+ /** El tamaño de su pantalla. */
15
+ size?: { cols: number, rows: number }
16
+ }
17
+
18
+ /** Lo que una consola cuenta de sí misma (`list`, `meta`, `attached`). */
19
+ export interface ConsoleInfo {
20
+ id: string
21
+ n: number
22
+ activity: 'busy' | 'idle'
23
+ doneAt: number | null
24
+ sizeBy: { origin: string | null, device: string | null, tag: string | null } | null
25
+ origin: string
26
+ title: string
27
+ shellTitle: string
28
+ subject: string
29
+ note: string
30
+ task: string
31
+ host: string | null
32
+ cwd: string | null
33
+ cols: number
34
+ rows: number
35
+ createdAt: number
36
+ lastActive: number
37
+ viewers: number
38
+ watchers: { origin: string, device: string | null, tag: string | null }[]
39
+ }
40
+
41
+ /** Lo que se usa de un PTY (node-pty). */
42
+ export type Pty = import('node-pty').IPty
43
+
44
+ /**
45
+ * Una sesión que atiende `serveSession`: la cifrada de otro aparato (`@dotrino/remote-agent`) o
46
+ * la de una ventana de esta máquina (`local.js`, por el socket). Lo que llega por `message` viene
47
+ * de fuera y se comprueba antes de usarlo, por eso va sin tipo.
48
+ */
49
+ export interface SessionLike {
50
+ device?: string | null
51
+ send (payload: object): unknown
52
+ on (ev: 'message', cb: (msg: any) => void): unknown
53
+ on (ev: 'close', cb: () => void): unknown
54
+ /** Solo en las remotas: ¿va ya por el canal directo? */
55
+ direct? (): boolean
56
+ /** Solo en las remotas: espera al canal directo, como mucho `ms`. */
57
+ whenDirect? (ms?: number): Promise<boolean>
58
+ }