@dotrino/terminal-agent 0.38.0 → 0.39.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,7 @@ 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
53
54
  ```
54
55
 
55
56
  Cerrar la ventana no cierra la consola: sigue viva en el agente y se retoma después (se cierra
package/bin/terminal.js CHANGED
@@ -16,6 +16,7 @@
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)
19
20
  *
20
21
  * Un PERFIL es un agente con nombre (`~/.dotrino/agent/terminal-agent/<nombre>/`), enlazado a
21
22
  * una bóveda o solo local. Cada consola vive en el agente de un perfil.
@@ -78,6 +79,9 @@ if (args.includes('-h') || args.includes('--help')) {
78
79
  dotrino-terminal vscode [--name <n>] hace que la terminal embebida de VS Code (y de
79
80
  VS Code Insiders, VSCodium y Cursor) abra consolas de aquí
80
81
  dotrino-terminal vscode --off lo deshace
82
+ dotrino-terminal desktop update actualiza la app de escritorio (la ventana): baja la
83
+ versión nueva, comprueba su firma y la instala
84
+ (--check solo mira si hay una)
81
85
 
82
86
  Dentro de una consola: Ctrl+] y luego d la suelta sin cerrarla; Ctrl+] n abre otra
83
87
  (y suelta la actual); Ctrl+] a <id> Enter pasa a esa consola; Ctrl+] p fija el tamaño de la
@@ -107,6 +111,9 @@ Cerrar la ventana no cierra la consola: sigue abierta y se retoma después.`, `u
107
111
  dotrino-terminal vscode [--name <n>] make the integrated terminal of VS Code (and VS Code
108
112
  Insiders, VSCodium and Cursor) open consoles from here
109
113
  dotrino-terminal vscode --off undo it
114
+ dotrino-terminal desktop update update the desktop app (the window): downloads the
115
+ new version, checks its signature and installs it
116
+ (--check only looks for one)
110
117
 
111
118
  Inside a console: Ctrl+] then d detaches without closing it; Ctrl+] n opens another
112
119
  (detaching the current one); Ctrl+] a <id> Enter switches to that console; Ctrl+] p pins the
@@ -215,6 +222,49 @@ function vscode () {
215
222
  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
223
  }
217
224
 
225
+ /** Dónde está la app de escritorio, si no lo dijo quien llama: la del PATH. */
226
+ function findDesktop (name) {
227
+ for (const d of (process.env.PATH || '').split(path.delimiter)) {
228
+ if (!d) continue
229
+ const f = path.join(d, name)
230
+ try { fs.accessSync(f, fs.constants.X_OK); return fs.realpathSync(f) } catch (_) {}
231
+ }
232
+ return null
233
+ }
234
+
235
+ /**
236
+ * Actualiza la app de escritorio. La app lo corre desde su menú con `--current` (su versión)
237
+ * y `--exe` (su binario); a mano basta `dotrino-terminal desktop update`.
238
+ */
239
+ async function desktop () {
240
+ if (args[1] !== 'update') die(t('uso: dotrino-terminal desktop update [--check]', 'usage: dotrino-terminal desktop update [--check]'))
241
+ const { updateDesktop, BINARY } = await import('../desktop.js')
242
+ const current = opt('--current')
243
+ const exe = opt('--exe') || findDesktop(BINARY)
244
+ const check = args.includes('--check')
245
+ 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/`))
246
+ const say = (step, d) => {
247
+ 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}`))
248
+ if (step === 'download') console.log(t(`Bajando ${d.name} y comprobando su firma…`, `Downloading ${d.name} and checking its signature…`))
249
+ if (step === 'verified') console.log(t(`Firmado por la release de ${d.repo} ✓`, `Signed by the release of ${d.repo} ✓`))
250
+ 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:'))
251
+ }
252
+ console.log(t('Mirando qué hay publicado…', 'Checking what is published…'))
253
+ const r = await updateDesktop({ exe, current, check, say })
254
+ if (!r.ok) {
255
+ const why = {
256
+ '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.`),
257
+ 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.'),
258
+ 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.'),
259
+ '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/`)
260
+ }[r.code] || t(`NO se instala nada: ${r.reason}`, `Nothing is installed: ${r.reason}`)
261
+ die(r.file ? `${why}\n${t('El archivo, ya comprobado, quedó en', 'The file, already checked, is at')} ${r.file}` : why)
262
+ }
263
+ 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.`))
264
+ 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'))
265
+ else console.log(t(`La app está al día (${current}).`, `The app is up to date (${current}).`))
266
+ }
267
+
218
268
  /** Enlaza un perfil. Sin `--name`, lo pregunta. Uno ya enlazado no se pisa: eso es `enroll`. */
219
269
  async function link () {
220
270
  let name = opt('--name')
@@ -689,6 +739,7 @@ try {
689
739
  if (cmd === 'rename') { await rename(); process.exit(0) }
690
740
  if (cmd === 'lock') { await lock(); process.exit(0) }
691
741
  if (cmd === 'vscode') { vscode(); process.exit(0) }
742
+ if (cmd === 'desktop') { await desktop(); process.exit(0) }
692
743
  if (cmd === 'note') { await note(); process.exit(0) }
693
744
  const dir = opt('--dir') || dataDir(opt('--name'))
694
745
  if (cmd === 'open' || cmd === 'attach') captureEarly()
package/desktop.js ADDED
@@ -0,0 +1,166 @@
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
+ const fail = (code, reason, extra = {}) => ({ ok: false, code, reason, ...extra })
33
+
34
+ /** La última release del escritorio. `{ ok:false }` si no se pudo mirar, que NO es «al día». */
35
+ export const latestDesktop = (opts = {}) =>
36
+ latestVersion({ source: 'github', repo: REPO, tagPrefix: DESKTOP_TAG, product: PRODUCT, ...opts })
37
+
38
+ /**
39
+ * Cómo está instalada la app que corre desde `exe`, que es lo que decide qué archivo se baja
40
+ * y cómo se pone. Se le pregunta al gestor de paquetes por ESE archivo: mirar solo qué
41
+ * gestor hay se equivoca con un tarball en una máquina con `dpkg`.
42
+ *
43
+ * @returns {{ok:true, kind:'deb'|'rpm'|'tar'|'mac', app?:string} | {ok:false, code:string, reason:string}}
44
+ */
45
+ export function installKind ({ exe, platform = process.platform, arch = process.arch, run = execFileSync, writable = canWrite } = {}) {
46
+ if (!exe) return fail('no-exe', 'the desktop app was not found')
47
+ if (platform === 'darwin') {
48
+ const m = /^(.+\.app)\/Contents\/MacOS\/[^/]+$/.exec(exe)
49
+ if (!m) return fail('not-a-bundle', `${exe} is not inside an .app bundle`)
50
+ if (!writable(path.dirname(m[1]))) return fail('not-writable', `cannot write in ${path.dirname(m[1])}`)
51
+ return { ok: true, kind: 'mac', app: m[1] }
52
+ }
53
+ if (platform !== 'linux') return fail('unsupported-platform', `there is no desktop app for ${platform}`)
54
+ if (arch !== 'x64') return fail('unsupported-arch', `there is no desktop app for ${arch}`)
55
+ const owns = (cmd, args) => { try { run(cmd, args, { stdio: 'ignore' }); return true } catch (_) { return false } }
56
+ if (owns('dpkg', ['-S', exe])) return { ok: true, kind: 'deb' }
57
+ if (owns('rpm', ['-qf', exe])) return { ok: true, kind: 'rpm' }
58
+ if (!writable(path.dirname(exe))) return fail('not-writable', `${exe} does not belong to a package and its folder is not writable`)
59
+ return { ok: true, kind: 'tar' }
60
+ }
61
+
62
+ function canWrite (dir) {
63
+ try { fs.accessSync(dir, fs.constants.W_OK); return true } catch (_) { return false }
64
+ }
65
+
66
+ const MATCH = {
67
+ deb: { kind: 'deb', re: /_amd64\.deb$/ },
68
+ rpm: { kind: 'rpm', re: /\.x86_64\.rpm$/ },
69
+ tar: { kind: 'tar', re: /-linux-x64\.tar\.gz$/ },
70
+ mac: { kind: 'mac', re: /-macos-universal\.zip$/ }
71
+ }
72
+
73
+ /** El archivo de la release que le toca a esa forma de instalación. */
74
+ export const assetFor = (assets, kind) => pickAsset(assets, [MATCH[kind]])
75
+
76
+ /** Como root no hace falta `sudo`; si no, se pide en la ventana. */
77
+ function asRoot (cmd, args, { run, uid }) {
78
+ const [c, a] = uid === 0 ? [cmd, args] : ['sudo', [cmd, ...args]]
79
+ run(c, a, { stdio: 'inherit' })
80
+ return [c, ...a].join(' ')
81
+ }
82
+
83
+ /**
84
+ * Pone el archivo ya verificado. Devuelve `{ ok:true }` o por qué no se pudo; si el archivo
85
+ * quedó bajado y sirve para instalarlo a mano, va en `file`.
86
+ */
87
+ export function install (file, how, { exe, run = execFileSync, uid = process.getuid?.() } = {}) {
88
+ try {
89
+ if (how.kind === 'deb') { asRoot('dpkg', ['-i', file], { run, uid }); return { ok: true } }
90
+ if (how.kind === 'rpm') { asRoot('rpm', ['-U', file], { run, uid }); return { ok: true } }
91
+ } catch (e) {
92
+ return fail('install-failed', `the package manager did not install it: ${e.message}`, { file })
93
+ }
94
+ if (how.kind === 'tar') {
95
+ const work = path.dirname(file)
96
+ try { run('tar', ['xzf', file, '-C', work], { stdio: ['ignore', 'ignore', 'pipe'] }) } catch (e) {
97
+ return fail('unpack-failed', `could not unpack the release: ${String(e.stderr || e.message).trim()}`, { file })
98
+ }
99
+ const src = fs.readdirSync(work).map((d) => path.join(work, d, BINARY)).find((f) => fs.existsSync(f))
100
+ if (!src) return fail('bad-tarball', `the tarball has no ${BINARY} inside`, { file })
101
+ // Al lado y renombrado encima: nunca queda un binario a medias, y la ventana que corre
102
+ // sigue con el suyo (el archivo viejo vive mientras alguien lo tenga abierto).
103
+ const tmp = path.join(path.dirname(exe), `.${path.basename(exe)}.new`)
104
+ fs.copyFileSync(src, tmp)
105
+ fs.chmodSync(tmp, 0o755)
106
+ fs.renameSync(tmp, exe)
107
+ return { ok: true }
108
+ }
109
+ if (how.kind === 'mac') {
110
+ // Se desempaqueta AL LADO del .app (mismo volumen) para poder cambiarlo renombrando.
111
+ const parent = path.dirname(how.app)
112
+ const work = fs.mkdtempSync(path.join(parent, '.dotrino-terminal-update-'))
113
+ try {
114
+ run('ditto', ['-x', '-k', file, work], { stdio: ['ignore', 'ignore', 'pipe'] })
115
+ const fresh = fs.readdirSync(work).map((d) => path.join(work, d)).find((d) => d.endsWith('.app') && fs.existsSync(path.join(d, 'Contents', 'MacOS', BINARY)))
116
+ if (!fresh) return fail('bad-zip', `the zip has no .app with ${BINARY} inside`, { file })
117
+ const old = path.join(work, 'old.app')
118
+ fs.renameSync(how.app, old)
119
+ try { fs.renameSync(fresh, how.app) } catch (e) { fs.renameSync(old, how.app); throw e }
120
+ return { ok: true }
121
+ } catch (e) {
122
+ return fail('install-failed', `could not replace the app: ${String(e.stderr || e.message).trim()}`, { file })
123
+ } finally {
124
+ fs.rmSync(work, { recursive: true, force: true })
125
+ }
126
+ }
127
+ return fail('unknown-kind', `unknown install kind: ${how.kind}`)
128
+ }
129
+
130
+ /**
131
+ * Todo el camino: mirar, bajar, verificar, instalar. `say(step, data)` va contando por dónde
132
+ * va, para que quien lo enseñe lo diga en su idioma.
133
+ *
134
+ * @returns {Promise<{ok:true, version:string, updated:boolean, kind?:string} | {ok:false, code:string, reason:string, file?:string}>}
135
+ */
136
+ export async function updateDesktop ({ exe, current, check = false, say = () => {}, latest = latestDesktop, fetchVerifiedImpl = fetchVerified, kindOf = installKind, installImpl = install } = {}) {
137
+ const r = await latest({ version: current })
138
+ if (!r.ok) return fail('could-not-check', r.reason)
139
+ say('latest', { version: r.version, current })
140
+ if (current && !isNewer(r.version, current)) return { ok: true, version: r.version, updated: false }
141
+ if (check) return { ok: true, version: r.version, updated: false, newer: true }
142
+ const how = kindOf({ exe })
143
+ if (!how.ok) return how
144
+ const pick = assetFor(r.assets, how.kind)
145
+ if (!pick.ok) return fail('no-asset', pick.reason)
146
+ say('download', { name: pick.asset.name })
147
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dotrino-terminal-update-'))
148
+ let keep = false
149
+ try {
150
+ let got
151
+ try { got = await fetchVerifiedImpl(pick.asset, { repo: REPO, product: PRODUCT, version: current, dir }) } catch (e) {
152
+ return fail(e.code || 'download-failed', e.message)
153
+ }
154
+ // Lo que no pasa la verificación no se deja en el disco: nadie debe instalarlo a mano.
155
+ if (!got.ok) return fail(got.code || 'not-verified', got.reason)
156
+ say('verified', { name: pick.asset.name, repo: REPO })
157
+ say('install', { kind: how.kind })
158
+ const done = installImpl(got.file, how, { exe })
159
+ if (!done.ok) { keep = !!done.file; return done }
160
+ return { ok: true, version: r.version, updated: true, kind: how.kind }
161
+ } finally {
162
+ if (!keep) fs.rmSync(dir, { recursive: true, force: true })
163
+ }
164
+ }
165
+
166
+ 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.39.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,6 +16,7 @@
16
16
  "far.js",
17
17
  "editors.js",
18
18
  "consoles.js",
19
+ "desktop.js",
19
20
  "link.js",
20
21
  "local.js",
21
22
  "title.js",
@@ -32,7 +33,7 @@
32
33
  "@dotrino/identity": "0.107.2",
33
34
  "@dotrino/proxy-client": "0.30.3",
34
35
  "@dotrino/remote-agent": "0.18.1",
35
- "@dotrino/update": "0.5.1",
36
+ "@dotrino/update": "0.8.0",
36
37
  "@dotrino/vault": "0.82.1",
37
38
  "@xterm/addon-serialize": "0.13.0",
38
39
  "@xterm/headless": "5.5.0",