@dotrino/terminal-agent 0.38.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 CHANGED
@@ -50,6 +50,8 @@ dotrino-terminal profiles [--json] # los perfiles (agentes con nombre) de
50
50
  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
+ 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
53
55
  ```
54
56
 
55
57
  Cerrar la ventana no cierra la consola: sigue viva en el agente y se retoma después (se cierra
@@ -148,3 +150,15 @@ En la app de escritorio: menú **Perfil → Poner o cambiar la clave… / Quitar
148
150
  nunca la clave. Viaja dentro de la sesión cifrada: el proxio no la ve.
149
151
  - Hace falta agente ≥ 0.19.0, y web ≥ 0.8.9 o las apps ≥ 0.8.9 para poder escribirla. Un
150
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
@@ -16,6 +16,9 @@
16
16
  * dotrino-terminal lock --off [--name <n>] la quita
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
+ * 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
19
22
  *
20
23
  * Un PERFIL es un agente con nombre (`~/.dotrino/agent/terminal-agent/<nombre>/`), enlazado a
21
24
  * una bóveda o solo local. Cada consola vive en el agente de un perfil.
@@ -28,6 +31,7 @@
28
31
  * cierra saliendo de su shell (`exit`) o desde el panel.
29
32
  */
30
33
  import fs from 'node:fs'
34
+ import os from 'node:os'
31
35
  import path from 'node:path'
32
36
  import { spawn } from 'node:child_process'
33
37
  import { fileURLToPath } from 'node:url'
@@ -78,6 +82,13 @@ if (args.includes('-h') || args.includes('--help')) {
78
82
  dotrino-terminal vscode [--name <n>] hace que la terminal embebida de VS Code (y de
79
83
  VS Code Insiders, VSCodium y Cursor) abra consolas de aquí
80
84
  dotrino-terminal vscode --off lo deshace
85
+ dotrino-terminal desktop update actualiza la app de escritorio (la ventana): baja la
86
+ versión nueva, comprueba su firma y la instala
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
81
92
 
82
93
  Dentro de una consola: Ctrl+] y luego d la suelta sin cerrarla; Ctrl+] n abre otra
83
94
  (y suelta la actual); Ctrl+] a <id> Enter pasa a esa consola; Ctrl+] p fija el tamaño de la
@@ -107,6 +118,13 @@ Cerrar la ventana no cierra la consola: sigue abierta y se retoma después.`, `u
107
118
  dotrino-terminal vscode [--name <n>] make the integrated terminal of VS Code (and VS Code
108
119
  Insiders, VSCodium and Cursor) open consoles from here
109
120
  dotrino-terminal vscode --off undo it
121
+ dotrino-terminal desktop update update the desktop app (the window): downloads the
122
+ new version, checks its signature and installs it
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
110
128
 
111
129
  Inside a console: Ctrl+] then d detaches without closing it; Ctrl+] n opens another
112
130
  (detaching the current one); Ctrl+] a <id> Enter switches to that console; Ctrl+] p pins the
@@ -162,13 +180,18 @@ async function agent (dir) {
162
180
  }
163
181
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
164
182
  const log = path.join(dir, 'agent.log')
165
- const fd = fs.openSync(log, 'a', 0o600)
166
- const cli = fileURLToPath(new URL('./cli.js', import.meta.url))
167
- const extra = opt('--name') ? ['--name', opt('--name')] : []
168
- // Sin TTY: si la máquina no está enlazada, el agente atiende solo a las ventanas locales.
169
- const child = spawn(process.execPath, [cli, ...extra], { detached: true, stdio: ['ignore', fd, fd], env: process.env })
170
- child.unref()
171
- fs.closeSync(fd)
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
+ }
172
195
  const t0 = Date.now()
173
196
  while (Date.now() - t0 < 10000) {
174
197
  await new Promise((r) => setTimeout(r, 100))
@@ -215,6 +238,120 @@ function vscode () {
215
238
  if (!off) console.log(t('\nLas terminales nuevas del editor ya abren aquí. Si actualizas o cambias de Node, vuelve a correr esta orden.', '\nNew terminals in the editor now open here. If you update or switch Node, run this command again.'))
216
239
  }
217
240
 
241
+ /** Dónde está la app de escritorio, si no lo dijo quien llama: la del PATH. */
242
+ function findDesktop (name) {
243
+ for (const d of (process.env.PATH || '').split(path.delimiter)) {
244
+ if (!d) continue
245
+ const f = path.join(d, name)
246
+ try { fs.accessSync(f, fs.constants.X_OK); return fs.realpathSync(f) } catch (_) {}
247
+ }
248
+ return null
249
+ }
250
+
251
+ /**
252
+ * Actualiza la app de escritorio. La app lo corre desde su menú con `--current` (su versión)
253
+ * y `--exe` (su binario); a mano basta `dotrino-terminal desktop update`.
254
+ */
255
+ async function desktop () {
256
+ if (args[1] !== 'update') die(t('uso: dotrino-terminal desktop update [--check]', 'usage: dotrino-terminal desktop update [--check]'))
257
+ const { updateDesktop, BINARY } = await import('../desktop.js')
258
+ const current = opt('--current')
259
+ const exe = opt('--exe') || findDesktop(BINARY)
260
+ const check = args.includes('--check')
261
+ if (!exe && !check) die(t(`no encontré ${BINARY} en esta máquina. Bájala de https://terminal.dotrino.com/`, `could not find ${BINARY} on this machine. Get it from https://terminal.dotrino.com/`))
262
+ const say = (step, d) => {
263
+ if (step === 'latest') console.log(d.current ? t(`Publicada: ${d.version} · esta: ${d.current}`, `Published: ${d.version} · this one: ${d.current}`) : t(`Publicada: ${d.version}`, `Published: ${d.version}`))
264
+ if (step === 'download') console.log(t(`Bajando ${d.name} y comprobando su firma…`, `Downloading ${d.name} and checking its signature…`))
265
+ if (step === 'verified') console.log(t(`Firmado por la release de ${d.repo} ✓`, `Signed by the release of ${d.repo} ✓`))
266
+ if (step === 'install' && (d.kind === 'deb' || d.kind === 'rpm') && process.getuid?.() !== 0) console.log(t('Instalar un paquete del sistema pide tu contraseña:', 'Installing a system package asks for your password:'))
267
+ }
268
+ console.log(t('Mirando qué hay publicado…', 'Checking what is published…'))
269
+ const r = await updateDesktop({ exe, current, check, say })
270
+ if (!r.ok) {
271
+ const why = {
272
+ 'could-not-check': t(`No se pudo mirar (${r.reason}). No es que estés al día: es que no se sabe.`, `Could not check (${r.reason}). That does not mean you are up to date: it is unknown.`),
273
+ NO_GH: t('NO se instala nada: falta GitHub CLI (gh), que es con lo que se comprueba la firma. Instálalo (https://cli.github.com; no hace falta iniciar sesión) y repite.', 'Nothing is installed: GitHub CLI (gh) is missing, and it is what checks the signature. Install it (https://cli.github.com; no login needed) and try again.'),
274
+ GH_TOO_OLD: t('NO se instala nada: este gh es anterior a la 2.49 y no sabe comprobar firmas. Actualiza GitHub CLI y repite.', 'Nothing is installed: this gh predates 2.49 and cannot check signatures. Update GitHub CLI and try again.'),
275
+ 'not-writable': t(`NO se instala nada: no puedo escribir donde está la app (${r.reason}). Bájala de https://terminal.dotrino.com/`, `Nothing is installed: I cannot write where the app is (${r.reason}). Get it from https://terminal.dotrino.com/`)
276
+ }[r.code] || t(`NO se instala nada: ${r.reason}`, `Nothing is installed: ${r.reason}`)
277
+ die(r.file ? `${why}\n${t('El archivo, ya comprobado, quedó en', 'The file, already checked, is at')} ${r.file}` : why)
278
+ }
279
+ if (r.updated) console.log(t(`\nInstalada la ${r.version}. Las ventanas abiertas siguen con la anterior: cierra Dotrino Terminal y vuelve a abrirla. Tus consolas no se cierran.`, `\nInstalled ${r.version}. Open windows keep the old one: quit Dotrino Terminal and open it again. Your consoles stay open.`))
280
+ else if (r.newer) console.log(t('Hay versión nueva. Tráela con: dotrino-terminal desktop update', 'There is a new version. Get it with: dotrino-terminal desktop update'))
281
+ else console.log(t(`La app está al día (${current}).`, `The app is up to date (${current}).`))
282
+ }
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
+
218
355
  /** Enlaza un perfil. Sin `--name`, lo pregunta. Uno ya enlazado no se pisa: eso es `enroll`. */
219
356
  async function link () {
220
357
  let name = opt('--name')
@@ -689,6 +826,8 @@ try {
689
826
  if (cmd === 'rename') { await rename(); process.exit(0) }
690
827
  if (cmd === 'lock') { await lock(); process.exit(0) }
691
828
  if (cmd === 'vscode') { vscode(); process.exit(0) }
829
+ if (cmd === 'desktop') { await desktop(); process.exit(0) }
830
+ if (cmd === 'service') { await service(); process.exit(0) }
692
831
  if (cmd === 'note') { await note(); process.exit(0) }
693
832
  const dir = opt('--dir') || dataDir(opt('--name'))
694
833
  if (cmd === 'open' || cmd === 'attach') captureEarly()
package/desktop.js ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * desktop.js — actualizar la APP DE ESCRITORIO (la ventana, `dotrino-terminal-desktop`).
3
+ *
4
+ * La app es un binario de Rust sin red: no baja nada ella. Su menú corre
5
+ * `dotrino-terminal desktop update` en la ventana, a la vista, y esto hace el trabajo con la
6
+ * misma pieza que el resto del ecosistema (`@dotrino/update`, CONVENCIONES §15): mira la
7
+ * release, baja el archivo que le toca a esta máquina, lo VERIFICA contra su atestación y solo
8
+ * entonces lo instala. Sin con qué verificar, se para y se dice.
9
+ *
10
+ * Cómo se instala depende de cómo llegó la app:
11
+ *
12
+ * · `.deb` / `.rpm` — el binario es de root: `sudo dpkg -i` / `sudo rpm -U`, que pide la
13
+ * contraseña en esa misma ventana.
14
+ * · tarball — el binario es del usuario: se cambia por el nuevo, de forma atómica.
15
+ * · macOS — se cambia el `.app` entero.
16
+ *
17
+ * La ventana que ya corre sigue con la versión anterior hasta que se cierre y se vuelva a abrir.
18
+ */
19
+ import fs from 'node:fs'
20
+ import os from 'node:os'
21
+ import path from 'node:path'
22
+ import { execFileSync } from 'node:child_process'
23
+ import { latestVersion, isNewer } from '@dotrino/update'
24
+ import { pickAsset, fetchVerified } from '@dotrino/update/fetch'
25
+ import { REPO } from './update.js'
26
+
27
+ /** Este repo también lleva el agente y la PWA: las releases del escritorio van con prefijo. */
28
+ export const DESKTOP_TAG = 'desktop-v'
29
+ export const BINARY = 'dotrino-terminal-desktop'
30
+ const PRODUCT = 'dotrino-terminal-desktop'
31
+
32
+ /** @returns {any} */
33
+ const fail = (code, reason, extra = {}) => ({ ok: false, code, reason, ...extra })
34
+
35
+ /** La última release del escritorio. `{ ok:false }` si no se pudo mirar, que NO es «al día». */
36
+ export const latestDesktop = (opts = {}) =>
37
+ latestVersion({ source: 'github', repo: REPO, tagPrefix: DESKTOP_TAG, product: PRODUCT, ...opts })
38
+
39
+ /**
40
+ * Cómo está instalada la app que corre desde `exe`, que es lo que decide qué archivo se baja
41
+ * y cómo se pone. Se le pregunta al gestor de paquetes por ESE archivo: mirar solo qué
42
+ * gestor hay se equivoca con un tarball en una máquina con `dpkg`.
43
+ *
44
+ * @param {any} [o]
45
+ * @returns {any} `{ ok:true, kind:'deb'|'rpm'|'tar'|'mac', app? }` o `{ ok:false, code, reason }`
46
+ */
47
+ export function installKind ({ exe, platform = process.platform, arch = process.arch, run = execFileSync, writable = canWrite } = {}) {
48
+ if (!exe) return fail('no-exe', 'the desktop app was not found')
49
+ if (platform === 'darwin') {
50
+ const m = /^(.+\.app)\/Contents\/MacOS\/[^/]+$/.exec(exe)
51
+ if (!m) return fail('not-a-bundle', `${exe} is not inside an .app bundle`)
52
+ if (!writable(path.dirname(m[1]))) return fail('not-writable', `cannot write in ${path.dirname(m[1])}`)
53
+ return { ok: true, kind: 'mac', app: m[1] }
54
+ }
55
+ if (platform !== 'linux') return fail('unsupported-platform', `there is no desktop app for ${platform}`)
56
+ if (arch !== 'x64') return fail('unsupported-arch', `there is no desktop app for ${arch}`)
57
+ const owns = (cmd, args) => { try { run(cmd, args, { stdio: 'ignore' }); return true } catch (_) { return false } }
58
+ if (owns('dpkg', ['-S', exe])) return { ok: true, kind: 'deb' }
59
+ if (owns('rpm', ['-qf', exe])) return { ok: true, kind: 'rpm' }
60
+ if (!writable(path.dirname(exe))) return fail('not-writable', `${exe} does not belong to a package and its folder is not writable`)
61
+ return { ok: true, kind: 'tar' }
62
+ }
63
+
64
+ function canWrite (dir) {
65
+ try { fs.accessSync(dir, fs.constants.W_OK); return true } catch (_) { return false }
66
+ }
67
+
68
+ const MATCH = {
69
+ deb: { kind: 'deb', re: /_amd64\.deb$/ },
70
+ rpm: { kind: 'rpm', re: /\.x86_64\.rpm$/ },
71
+ tar: { kind: 'tar', re: /-linux-x64\.tar\.gz$/ },
72
+ mac: { kind: 'mac', re: /-macos-universal\.zip$/ }
73
+ }
74
+
75
+ /** El archivo de la release que le toca a esa forma de instalación. */
76
+ export const assetFor = (assets, kind) => pickAsset(assets, [MATCH[kind]])
77
+
78
+ /** Como root no hace falta `sudo`; si no, se pide en la ventana. */
79
+ function asRoot (cmd, args, { run, uid }) {
80
+ const [c, a] = uid === 0 ? [cmd, args] : ['sudo', [cmd, ...args]]
81
+ run(c, a, { stdio: 'inherit' })
82
+ return [c, ...a].join(' ')
83
+ }
84
+
85
+ /**
86
+ * Pone el archivo ya verificado. Devuelve `{ ok:true }` o por qué no se pudo; si el archivo
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}
93
+ */
94
+ export function install (file, how, { exe, run = execFileSync, uid = process.getuid?.() } = {}) {
95
+ try {
96
+ if (how.kind === 'deb') { asRoot('dpkg', ['-i', file], { run, uid }); return { ok: true } }
97
+ if (how.kind === 'rpm') { asRoot('rpm', ['-U', file], { run, uid }); return { ok: true } }
98
+ } catch (e) {
99
+ return fail('install-failed', `the package manager did not install it: ${e.message}`, { file })
100
+ }
101
+ if (how.kind === 'tar') {
102
+ const work = path.dirname(file)
103
+ try { run('tar', ['xzf', file, '-C', work], { stdio: ['ignore', 'ignore', 'pipe'] }) } catch (e) {
104
+ return fail('unpack-failed', `could not unpack the release: ${String(e.stderr || e.message).trim()}`, { file })
105
+ }
106
+ const src = fs.readdirSync(work).map((d) => path.join(work, d, BINARY)).find((f) => fs.existsSync(f))
107
+ if (!src) return fail('bad-tarball', `the tarball has no ${BINARY} inside`, { file })
108
+ // Al lado y renombrado encima: nunca queda un binario a medias, y la ventana que corre
109
+ // sigue con el suyo (el archivo viejo vive mientras alguien lo tenga abierto).
110
+ const tmp = path.join(path.dirname(exe), `.${path.basename(exe)}.new`)
111
+ fs.copyFileSync(src, tmp)
112
+ fs.chmodSync(tmp, 0o755)
113
+ fs.renameSync(tmp, exe)
114
+ return { ok: true }
115
+ }
116
+ if (how.kind === 'mac') {
117
+ // Se desempaqueta AL LADO del .app (mismo volumen) para poder cambiarlo renombrando.
118
+ const parent = path.dirname(how.app)
119
+ const work = fs.mkdtempSync(path.join(parent, '.dotrino-terminal-update-'))
120
+ try {
121
+ run('ditto', ['-x', '-k', file, work], { stdio: ['ignore', 'ignore', 'pipe'] })
122
+ const fresh = fs.readdirSync(work).map((d) => path.join(work, d)).find((d) => d.endsWith('.app') && fs.existsSync(path.join(d, 'Contents', 'MacOS', BINARY)))
123
+ if (!fresh) return fail('bad-zip', `the zip has no .app with ${BINARY} inside`, { file })
124
+ const old = path.join(work, 'old.app')
125
+ fs.renameSync(how.app, old)
126
+ try { fs.renameSync(fresh, how.app) } catch (e) { fs.renameSync(old, how.app); throw e }
127
+ return { ok: true }
128
+ } catch (e) {
129
+ return fail('install-failed', `could not replace the app: ${String(e.stderr || e.message).trim()}`, { file })
130
+ } finally {
131
+ fs.rmSync(work, { recursive: true, force: true })
132
+ }
133
+ }
134
+ return fail('unknown-kind', `unknown install kind: ${how.kind}`)
135
+ }
136
+
137
+ /**
138
+ * Todo el camino: mirar, bajar, verificar, instalar. `say(step, data)` va contando por dónde
139
+ * va, para que quien lo enseñe lo diga en su idioma.
140
+ *
141
+ * @param {any} [o]
142
+ * @returns {Promise<any>} `{ ok:true, version, updated, newer?, kind? }` o `{ ok:false, code, reason, file? }`
143
+ */
144
+ export async function updateDesktop ({ exe, current, check = false, say = () => {}, latest = latestDesktop, fetchVerifiedImpl = fetchVerified, kindOf = installKind, installImpl = install } = {}) {
145
+ const r = await latest({ version: current })
146
+ if (!r.ok) return fail('could-not-check', r.reason)
147
+ say('latest', { version: r.version, current })
148
+ if (current && !isNewer(r.version, current)) return { ok: true, version: r.version, updated: false }
149
+ if (check) return { ok: true, version: r.version, updated: false, newer: true }
150
+ const how = kindOf({ exe })
151
+ if (!how.ok) return how
152
+ const pick = assetFor(r.assets, how.kind)
153
+ if (!pick.ok) return fail('no-asset', pick.reason)
154
+ say('download', { name: pick.asset.name })
155
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dotrino-terminal-update-'))
156
+ let keep = false
157
+ try {
158
+ let got
159
+ try { got = await fetchVerifiedImpl(pick.asset, { repo: REPO, product: PRODUCT, version: current, dir }) } catch (e) {
160
+ return fail(e.code || 'download-failed', e.message)
161
+ }
162
+ // Lo que no pasa la verificación no se deja en el disco: nadie debe instalarlo a mano.
163
+ if (!got.ok) return fail(got.code || 'not-verified', got.reason)
164
+ say('verified', { name: pick.asset.name, repo: REPO })
165
+ say('install', { kind: how.kind })
166
+ const done = installImpl(got.file, how, { exe })
167
+ if (!done.ok) { keep = !!done.file; return done }
168
+ return { ok: true, version: r.version, updated: true, kind: how.kind }
169
+ } finally {
170
+ if (!keep) fs.rmSync(dir, { recursive: true, force: true })
171
+ }
172
+ }
173
+
174
+ export default { updateDesktop, latestDesktop, installKind, assetFor, install, DESKTOP_TAG, BINARY }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/terminal-agent",
3
- "version": "0.38.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": {
@@ -16,8 +16,10 @@
16
16
  "far.js",
17
17
  "editors.js",
18
18
  "consoles.js",
19
+ "desktop.js",
19
20
  "link.js",
20
21
  "local.js",
22
+ "service.js",
21
23
  "title.js",
22
24
  "update.js",
23
25
  "bin",
@@ -32,7 +34,7 @@
32
34
  "@dotrino/identity": "0.107.2",
33
35
  "@dotrino/proxy-client": "0.30.3",
34
36
  "@dotrino/remote-agent": "0.18.1",
35
- "@dotrino/update": "0.5.1",
37
+ "@dotrino/update": "0.8.0",
36
38
  "@dotrino/vault": "0.82.1",
37
39
  "@xterm/addon-serialize": "0.13.0",
38
40
  "@xterm/headless": "5.5.0",
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, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
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 }