@dotrino/terminal-agent 0.54.0 → 0.54.1

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.54.1",
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",
package/service.js CHANGED
@@ -24,29 +24,51 @@ import os from 'node:os'
24
24
  import path from 'node:path'
25
25
  import { execFileSync, spawn as childSpawn } from 'node:child_process'
26
26
 
27
+ /** @type {(code: string, message: string) => Error & { code: string }} */
27
28
  const fail = (code, message) => Object.assign(new Error(message), { code })
28
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 */
29
38
  export const unitName = (name) => `dotrino-terminal-agent-${name}.service`
39
+ /** @param {string} name */
30
40
  export const plistLabel = (name) => `com.dotrino.terminal-agent.${name}`
31
41
 
42
+ /**
43
+ * @param {string} name
44
+ * @param {string} [home]
45
+ */
32
46
  export function unitPath (name, home = os.homedir()) {
33
47
  return path.join(home, '.config', 'systemd', 'user', unitName(name))
34
48
  }
35
49
 
50
+ /**
51
+ * @param {string} name
52
+ * @param {string} [home]
53
+ */
36
54
  export function plistPath (name, home = os.homedir()) {
37
55
  return path.join(home, 'Library', 'LaunchAgents', `${plistLabel(name)}.plist`)
38
56
  }
39
57
 
40
58
  /** Windows: la clave de lo que arranca al iniciar sesión, y el nombre del valor de cada perfil. */
41
59
  export const RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
60
+ /** @param {string} name */
42
61
  export const runValue = (name) => `DotrinoTerminalAgent-${name}`
43
62
  /** Lo que se apunta en la clave: Node, el CLI y el supervisor del perfil. */
63
+ /** @param {Launch} o */
44
64
  export const runCommand = ({ name, node, cli }) => `"${node}" "${cli}" supervise --name ${name}`
65
+ /** @param {string} dir */
45
66
  export const supervisorPidFile = (dir) => path.join(dir, 'supervisor.pid')
46
67
  /** Cuánto espera el supervisor antes de volver a levantar el agente (como `RestartSec`). */
47
68
  export const RESTART_MS = 3000
48
69
 
49
70
  /** systemd parte `ExecStart` por espacios: lo que los lleve va entre comillas. */
71
+ /** @param {string} s */
50
72
  const unitArg = (s) => (/[\s"'\\$%]/.test(s) ? `"${s.replace(/[\\"]/g, '\\$&').replace(/%/g, '%%').replace(/\$/g, '$$$$')}"` : s)
51
73
 
52
74
  /**
@@ -55,6 +77,7 @@ const unitArg = (s) => (/[\s"'\\$%]/.test(s) ? `"${s.replace(/[\\"]/g, '\\$&').r
55
77
  *
56
78
  * El PATH es el de quien instala: el de un servicio de usuario es mínimo y no trae el Node
57
79
  * de nvm ni las herramientas que las consolas esperan encontrar.
80
+ * @param {Launch & { pathEnv: string }} o
58
81
  */
59
82
  export function unitText ({ name, node, cli, pathEnv }) {
60
83
  return `[Unit]
@@ -73,9 +96,13 @@ WantedBy=default.target
73
96
  `
74
97
  }
75
98
 
99
+ /** @param {unknown} s */
76
100
  const xml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
77
101
 
78
- /** El LaunchAgent de macOS. `DOTRINO_SUPERVISED`: launchd lo levanta si sale (§15). */
102
+ /**
103
+ * El LaunchAgent de macOS. `DOTRINO_SUPERVISED`: launchd lo levanta si sale (§15).
104
+ * @param {Launch & { pathEnv: string, log: string }} o
105
+ */
79
106
  export function plistText ({ name, node, cli, pathEnv, log }) {
80
107
  const args = [node, cli, '--name', name, '--local'].map((a) => ` <string>${xml(a)}</string>`).join('\n')
81
108
  return `<?xml version="1.0" encoding="UTF-8"?>
@@ -99,22 +126,38 @@ ${args}
99
126
  `
100
127
  }
101
128
 
129
+ /**
130
+ * @param {RunFn} run
131
+ * @param {string} cmd
132
+ * @param {string[]} args
133
+ * @returns {{ ok: true } | { ok: false, reason: string | undefined }}
134
+ */
102
135
  function quiet (run, cmd, args) {
103
136
  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() }
137
+ return { ok: false, reason: String(/** @type {Thrown} */ (e).stderr || /** @type {Thrown} */ (e).message).trim().split('\n').pop() }
105
138
  }
106
139
  }
107
140
 
141
+ /**
142
+ * @param {RunFn} run
143
+ * @param {string} cmd
144
+ * @param {string[]} args
145
+ */
108
146
  function must (run, cmd, args) {
109
147
  const r = quiet(run, cmd, args)
110
148
  if (!r.ok) throw fail('service-command-failed', `${cmd} ${args.join(' ')}: ${r.reason}`)
111
149
  }
112
150
 
113
151
  /** ¿Ya arrancan los servicios de ese usuario al encender? systemd lo apunta con un archivo. */
152
+ /** @type {(user: string, root?: string) => boolean} */
114
153
  const lingers = (user, root = LINGER_DIR) => fs.existsSync(path.join(root, user))
115
154
  const LINGER_DIR = '/var/lib/systemd/linger'
116
155
 
117
- /** ¿Deja este sistema instalar el servicio? Lanza con el motivo si no. */
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
+ */
118
161
  function platformOf ({ platform, run }) {
119
162
  if (platform === 'darwin') return 'launchd'
120
163
  if (platform === 'win32') return 'run-key'
@@ -124,12 +167,17 @@ function platformOf ({ platform, run }) {
124
167
  return 'systemd'
125
168
  }
126
169
 
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' } }
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
+ /** @param {string} name */
129
175
  const runKeyFile = (name) => `${RUN_KEY}\\${runValue(name)}`
176
+ /** @type {(name: string, run: RunFn) => boolean} */
130
177
  const hasRunKey = (name, run) => quiet(run, 'reg', ['query', RUN_KEY, '/v', runValue(name)]).ok
131
178
 
132
179
  /** PowerShell: una cadena entre comillas simples. */
180
+ /** @param {string} s */
133
181
  const psQuote = (s) => `'${String(s).replace(/'/g, "''")}'`
134
182
 
135
183
  /**
@@ -144,6 +192,7 @@ const psQuote = (s) => `'${String(s).replace(/'/g, "''")}'`
144
192
  * corriendo ahora (lo que se lanzara moriría al cerrar la sesión) y se devuelve el motivo: la
145
193
  * entrada de `Run` ya está puesta y lo arranca al iniciar sesión.
146
194
  *
195
+ * @param {Launch & { spawn: SpawnFn, run: RunFn, env: NodeJS.ProcessEnv }} o
147
196
  * @returns {{ ok: true } | { ok: false, reason: string }}
148
197
  */
149
198
  function spawnSupervisor ({ name, node, cli, spawn, run, env }) {
@@ -161,6 +210,7 @@ function spawnSupervisor ({ name, node, cli, spawn, run, env }) {
161
210
  * El supervisor de Windows: levanta el agente del perfil y lo vuelve a levantar cada vez que
162
211
  * sale (también cuando se reinicia para estrenar una versión: §15, `DOTRINO_SUPERVISED`).
163
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
164
214
  */
165
215
  export function supervise ({ name, dir, node = process.execPath, cli, spawn = childSpawn }) {
166
216
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
@@ -169,6 +219,7 @@ export function supervise ({ name, dir, node = process.execPath, cli, spawn = ch
169
219
  if (other && other !== process.pid && alive(other)) throw fail('already-supervised', `profile ${name} already has a supervisor (pid ${other})`)
170
220
  fs.writeFileSync(pidFile, String(process.pid))
171
221
  let stopped = false
222
+ /** @type {import('node:child_process').ChildProcess | null} */
172
223
  let child = null
173
224
  const start = () => {
174
225
  const fd = fs.openSync(path.join(dir, 'agent.log'), 'a', 0o600)
@@ -186,7 +237,10 @@ export function supervise ({ name, dir, node = process.execPath, cli, spawn = ch
186
237
  }
187
238
  }
188
239
 
189
- /** Windows: para el supervisor y después el agente (matar el supervisor no se lleva al hijo). */
240
+ /**
241
+ * Windows: para el supervisor y después el agente (matar el supervisor no se lleva al hijo).
242
+ * @param {string} dir
243
+ */
190
244
  function stopSupervised (dir) {
191
245
  for (const file of [supervisorPidFile(dir), path.join(dir, 'agent.pid')]) {
192
246
  const pid = readPid(file)
@@ -202,6 +256,8 @@ function stopSupervised (dir) {
202
256
  * Dos agentes con el mismo enlace son la misma llave, y parar ese cerraría sus consolas: el
203
257
  * servicio queda puesto y toma el relevo cuando ese agente termine o al próximo arranque.
204
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
205
261
  * @returns {{ kind:'systemd'|'launchd'|'run-key', file:string, started:boolean, boot?:boolean, lingerReason?:string, startReason?:string }}
206
262
  */
207
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 }) {
@@ -240,6 +296,9 @@ export function installService ({ name, node = process.execPath, cli, dir, runni
240
296
  * este sistema no los tiene): entonces el agente lo levanta la ventana, como siempre. Lo usa
241
297
  * `dotrino-terminal` cuando no encuentra agente, para no levantar uno propio al lado de un
242
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}
243
302
  */
244
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 }) {
245
304
  if (platform === 'win32') {
@@ -262,7 +321,10 @@ export function startService ({ name, dir, node = process.execPath, cli, platfor
262
321
  return true
263
322
  }
264
323
 
265
- /** Para el servicio y lo quita. El enlace y los ajustes del perfil no se tocan. */
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
+ */
266
328
  export function uninstallService ({ name, dir, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
267
329
  const kind = platformOf({ platform, run })
268
330
  if (kind === 'run-key') {
@@ -280,7 +342,10 @@ export function uninstallService ({ name, dir, platform = process.platform, home
280
342
  return { kind, file, removed: true }
281
343
  }
282
344
 
283
- /** ¿Está puesto, y está corriendo ahora bajo el sistema? */
345
+ /**
346
+ * ¿Está puesto, y está corriendo ahora bajo el sistema?
347
+ * @param {{ name: string, dir: string, platform?: string, home?: string, uid?: number, run?: RunFn }} o
348
+ */
284
349
  export function serviceStatus ({ name, dir, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
285
350
  const kind = platformOf({ platform, run })
286
351
  if (kind === 'run-key') {
@@ -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
+ }
@@ -0,0 +1,173 @@
1
+ // Tipos de los pilares que usa el agente y no publican .d.ts (@dotrino/remote-agent, @dotrino/vault,
2
+ // @dotrino/update y una subruta de @dotrino/identity). Solo lo que se usa, copiado de su JSDoc.
3
+ // Cuando el pilar traiga sus tipos, se borra de aquí.
4
+
5
+ /** El enlace de un aparato con su bóveda, como lo guarda @dotrino/remote-agent (`link.json`). */
6
+ interface DotrinoDeviceLink {
7
+ device: { publickey: string, privateJwk: import('node:crypto').JsonWebKey, publicJwk?: import('node:crypto').JsonWebKey }
8
+ cert: { seq?: number, exp?: number, scope?: string[], [k: string]: unknown }
9
+ iss: string
10
+ proxy?: string
11
+ label?: string
12
+ at?: number
13
+ acta?: object
14
+ [k: string]: unknown
15
+ }
16
+
17
+ declare module '@dotrino/remote-agent/link' {
18
+ export function dataDir (name?: string): string
19
+ /** null si no existe; lanza `link-unreadable` si existe y no se puede leer. */
20
+ export function loadLink (dir?: string): DotrinoDeviceLink | null
21
+ export function parseQr (text: string): Promise<object | string>
22
+ export function enroll (args: {
23
+ qr: object | string
24
+ label?: string
25
+ dir?: string
26
+ ns?: string | null
27
+ onChallenge?: (c: { deviceId: string, code: string }) => void
28
+ timeoutMs?: number
29
+ }): Promise<DotrinoDeviceLink>
30
+ /** El enlace como lo esperan `RemoteAgentClient` y `ContentClient`. */
31
+ export function clientLink (link: DotrinoDeviceLink, opts?: { dir?: string }): { id: object, cert: object, iss: string, proxy: string }
32
+ }
33
+
34
+ declare module '@dotrino/remote-agent/instances' {
35
+ export const DEFAULT_NAME: string
36
+ export function isValidName (n: unknown): n is string
37
+ export function instancesRoot (kind: string): string
38
+ /** Nombres de las instancias enlazadas (las que tienen `link.json`). */
39
+ export function listInstances (kind: string): string[]
40
+ export function resolveInstance (kind: string, name?: string | null): { name: string, dir: string }
41
+ /** Candado de la instancia; devuelve cómo soltarlo. */
42
+ export function lockInstance (dir: string): () => void
43
+ }
44
+
45
+ declare module '@dotrino/remote-agent/client' {
46
+ export class RemoteAgentClient {
47
+ constructor (link: object, opts: { agentPubkey: string, proxyUrl?: string, trustedActa?: () => object | null })
48
+ key: CryptoKey | null
49
+ on (ev: 'message', cb: (payload: any) => void): () => void
50
+ on (ev: 'error', cb: (err: Error & { code?: string }) => void): () => void
51
+ on (ev: 'resumed', cb: () => void): () => void
52
+ connect (): Promise<void>
53
+ send (payload: object): Promise<void>
54
+ close (): Promise<void>
55
+ }
56
+ }
57
+
58
+ declare module '@dotrino/remote-agent/discover' {
59
+ export interface AgentMember { sub: string, label: string, cn: string | null }
60
+ /** `fresh`: pedir el acta a la bóveda en vez de usar la guardada. */
61
+ export function listAgentsByLabel (id: unknown, label?: string, opts?: { fresh?: boolean }): Promise<AgentMember[]>
62
+ export function probeAgents (
63
+ client: { on: Function, sendByPubkey: Function },
64
+ subs: string[],
65
+ opts?: { timeoutMs?: number },
66
+ ): Promise<Map<string, { kind: string | null }>>
67
+ }
68
+
69
+ declare module '@dotrino/remote-agent/agent' {
70
+ /** Una sesión cifrada con un aparato autorizado. */
71
+ export interface AgentSession {
72
+ sid: string
73
+ /** El token del cliente en el proxio. */
74
+ from: string
75
+ /** La pubkey del aparato cliente. */
76
+ device: string
77
+ on (ev: 'message', cb: (payload: any) => void): void
78
+ on (ev: 'close', cb: () => void): void
79
+ send (payload: object): Promise<void>
80
+ /** ¿Va por un canal directo (WebRTC) ahora mismo? */
81
+ direct (): boolean
82
+ /** Espera a que abra el canal directo, como mucho `ms`. */
83
+ whenDirect (ms?: number): Promise<boolean>
84
+ }
85
+ export interface RemoteAgent {
86
+ machine: string
87
+ machineId: string
88
+ master: string
89
+ client: import('@dotrino/proxy-client').WebSocketProxyClient
90
+ reportIncident (i: { kind: string, about: string, tries: number }): Promise<{ id: string | null, approvers: number, blocked: boolean }>
91
+ close (): void
92
+ }
93
+ export function startRemoteAgent (opts?: {
94
+ dir?: string
95
+ proxyUrl?: string
96
+ quiet?: boolean
97
+ label?: string
98
+ sessionTtlMs?: number
99
+ onRevoked?: () => void
100
+ onSession?: (session: AgentSession) => void
101
+ product?: string
102
+ version?: string
103
+ needs?: string[]
104
+ }): Promise<RemoteAgent>
105
+ }
106
+
107
+ declare module '@dotrino/identity/capabilities' {
108
+ /** El id corto de una llave, como lo enseña la bóveda: `AB12-CD34`. */
109
+ export function keyLabel (publickey: string): Promise<string>
110
+ }
111
+
112
+ declare module '@dotrino/vault/device-info' {
113
+ export interface DeviceInfo { id: string, vault: string | null, scope: string[], record: number | null, legacyExpires: number | null, proxy: string | null, publickey: string, [k: string]: unknown }
114
+ export function deviceInfo (link: { device?: { publickey?: string }, cert?: object, iss?: string, proxy?: string }, extra?: Record<string, unknown>): Promise<DeviceInfo>
115
+ export function formatDeviceInfo (info: DeviceInfo): string
116
+ }
117
+
118
+ declare module '@dotrino/vault/service' {
119
+ export interface UpdateHooks {
120
+ mayUpdate: (u: { version: string, from?: string }) => Promise<boolean>
121
+ onUpdated: (u: { version: string, from?: string }) => Promise<void>
122
+ onNeedsRoot: (u: { version: string, from?: string }) => Promise<void>
123
+ }
124
+ export function vaultUpdateHooks (o: { product: string, log?: (m: string) => void, dir?: string, proxyUrl?: string, masterPubkey?: string, device?: object, cert?: object }): UpdateHooks
125
+ }
126
+
127
+ declare module '@dotrino/update' {
128
+ export type LatestResult =
129
+ | { ok: true, version: string, source: 'npm', pkg: string }
130
+ | { ok: true, version: string, source: 'github', repo: string, assets: { name: string, url: string, size?: number }[], url: string }
131
+ | { ok: false, reason: string, code?: string }
132
+ export function latestVersion (o: { source?: string, repo?: string, pkg?: string, tagPrefix?: string, product?: string, version?: string, timeoutMs?: number }): Promise<LatestResult>
133
+ /** ¿`a` es más nueva que `b`? */
134
+ export function isNewer (a: string, b: string): boolean
135
+ }
136
+
137
+ declare module '@dotrino/update/fetch' {
138
+ export interface ReleaseAsset { name: string, url: string, size?: number }
139
+ export function pickAsset (assets: ReleaseAsset[], match: { kind: string, re: RegExp, when?: () => boolean }[]):
140
+ | { ok: true, asset: ReleaseAsset, kind: string }
141
+ | { ok: false, reason: string }
142
+ export function fetchVerified (asset: ReleaseAsset, opts?: { repo?: string, product?: string, version?: string, dir?: string | null }):
143
+ Promise<({ ok: true, out: string } | { ok: false, code?: string, reason: string }) & { file?: string }>
144
+ }
145
+
146
+ declare module '@dotrino/update/npm' {
147
+ export function watchSelfUpdateNpm (o: {
148
+ pkg: string
149
+ current: string
150
+ repo?: string
151
+ /** El tag de la release de una versión (`agent-v1.2.3`). */
152
+ tag?: (version: string) => string
153
+ dir?: string
154
+ mayUpdate?: (u: { version: string, from?: string }) => Promise<boolean>
155
+ onUpdated?: (u: { version: string, from?: string }) => Promise<void>
156
+ onNeedsRoot?: (u: { version: string, from?: string }) => Promise<void>
157
+ onInstalled?: (r: { version: string, restart: boolean }) => void
158
+ onResult?: (r: object) => void
159
+ log?: (m: string) => void
160
+ }): () => void
161
+ export function updatePrefsCommand (args?: string[], opts?: { dir?: string, lang?: string }): {
162
+ handled: boolean
163
+ ok: boolean
164
+ text: string
165
+ prefs?: { approval: boolean, notify: boolean }
166
+ }
167
+ export function updateStatusText (o: { dir?: string, current: string, lang?: string, now?: () => number }): string
168
+ }
169
+
170
+ declare module '@dotrino/update/notice' {
171
+ /** Imprime por stderr si hay versión nueva (una vez al día). Devuelve si imprimió algo. */
172
+ export function printUpdateNotice (opts?: { current?: string, source?: string, pkg?: string, product?: string, how?: string }): Promise<boolean>
173
+ }
@@ -0,0 +1,4 @@
1
+ // Tipos globales del agente (este archivo no es un módulo: lo de aquí se ve en todos).
2
+
3
+ /** Lo que llega en un `catch`: casi siempre un `Error`, a veces con `code`, `stderr` o `retryMs`. */
4
+ type Thrown = Error & { code?: string, errno?: number, stderr?: string | Buffer, retryMs?: number, cause?: { code?: string } }