@dotrino/terminal-agent 0.49.5 → 0.50.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.
Files changed (3) hide show
  1. package/downloads.js +80 -0
  2. package/index.js +16 -3
  3. package/package.json +2 -1
package/downloads.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * downloads.js — un archivo de ESTA máquina, para abrirlo en el aparato que mira la consola.
3
+ *
4
+ * Para qué: la consola enseña rutas (`/tmp/informe.pdf`, `~/fotos/a.png`) y desde el teléfono o
5
+ * el navegador no hay otra forma de ver ese archivo. El aparato la pide por la sesión (cifrada,
6
+ * como todo lo demás) y se le manda en trozos.
7
+ *
8
+ * Quien llega hasta aquí ya tiene una shell en la máquina, así que leer un archivo no le da nada
9
+ * que no tuviera con `cat`. Lo que se cuida es otra cosa: solo archivos normales (ni carpetas ni
10
+ * dispositivos) y con tope de tamaño, para que una ruta mal leída no se ponga a mandar gigas.
11
+ *
12
+ * Sin estado: cada trozo se pide con la ruta y su número (`seq`), y cada respuesta lleva el
13
+ * tamaño y la fecha del archivo; si cambian a mitad, quien pide lo ve y para.
14
+ */
15
+ import fs from 'node:fs'
16
+ import os from 'node:os'
17
+ import path from 'node:path'
18
+
19
+ /** Lo más que pesa un archivo que se manda. */
20
+ export const FETCH_MAX = 50 * 1024 * 1024
21
+ /** Lo que lleva cada trozo, antes del base64 (el mismo tamaño que las subidas del cliente). */
22
+ export const FETCH_CHUNK = 96 * 1024
23
+
24
+ const fail = (code, message) => Object.assign(new Error(message), { code })
25
+
26
+ /**
27
+ * La ruta absoluta de lo que se pide. `~` es la carpeta personal; una ruta relativa cuelga de
28
+ * `cwd` (la carpeta de la shell de la consola), y sin ella no se adivina: se dice.
29
+ */
30
+ export function resolvePath (p, cwd = null) {
31
+ if (typeof p !== 'string' || !p || p.length > 4096 || p.includes('\0')) throw fail('bad-fetch', 'fetch: needs a `path`')
32
+ const home = os.homedir()
33
+ const expand = (s) => s === '~' ? home : s.startsWith('~/') ? path.join(home, s.slice(2)) : s
34
+ const full = expand(p)
35
+ if (path.isAbsolute(full)) return path.normalize(full)
36
+ if (!cwd) throw fail('no-cwd', `fetch: ${p} is relative and the folder of the console is unknown`)
37
+ return path.resolve(expand(cwd), full)
38
+ }
39
+
40
+ /**
41
+ * Un trozo del archivo.
42
+ * @param {{ id: string, path: string, seq: number }} msg
43
+ * @param {string|null} cwd la carpeta de la consola enganchada, para las rutas relativas.
44
+ * @returns {{ id: string, seq: number, path: string, name: string, size: number, mtime: number, data: string, last?: true }}
45
+ */
46
+ export function readPiece (msg, cwd = null) {
47
+ const id = typeof msg.id === 'string' ? msg.id.slice(0, 64) : ''
48
+ const seq = msg.seq
49
+ if (!id || !Number.isInteger(seq) || seq < 0) throw fail('bad-fetch', 'fetch: needs `id`, `path` and `seq`')
50
+ const file = resolvePath(msg.path, cwd)
51
+ let st
52
+ try { st = fs.statSync(file) } catch (e) {
53
+ if (e.code === 'ENOENT' || e.code === 'ENOTDIR') throw fail('no-file', `no such file: ${file}`)
54
+ if (e.code === 'EACCES' || e.code === 'EPERM') throw fail('no-read', `not allowed to read: ${file}`)
55
+ throw e
56
+ }
57
+ if (st.isDirectory()) throw fail('is-dir', `that is a folder: ${file}`)
58
+ if (!st.isFile()) throw fail('not-file', `that is not a regular file: ${file}`)
59
+ if (st.size > FETCH_MAX) throw fail('too-big', `the file is over ${FETCH_MAX / 1024 / 1024} MB`)
60
+ const at = seq * FETCH_CHUNK
61
+ if (at > st.size || (at === st.size && st.size > 0)) throw fail('bad-fetch', 'fetch: that piece is past the end of the file')
62
+ const len = Math.min(FETCH_CHUNK, st.size - at)
63
+ const buf = Buffer.alloc(len)
64
+ let fd
65
+ try { fd = fs.openSync(file, 'r') } catch (e) {
66
+ if (e.code === 'EACCES' || e.code === 'EPERM') throw fail('no-read', `not allowed to read: ${file}`)
67
+ throw e
68
+ }
69
+ try {
70
+ let got = 0
71
+ while (got < len) {
72
+ const n = fs.readSync(fd, buf, got, len - got, at + got)
73
+ if (n === 0) break
74
+ got += n
75
+ }
76
+ if (got < len) throw fail('changed', 'the file got shorter while it was being sent')
77
+ } finally { fs.closeSync(fd) }
78
+ const last = at + len >= st.size
79
+ return { id, seq, path: file, name: path.basename(file), size: st.size, mtime: st.mtimeMs, data: buf.toString('base64'), ...(last ? { last: true } : {}) }
80
+ }
package/index.js CHANGED
@@ -21,12 +21,16 @@
21
21
  * { type:'unlock', code } (la clave de la máquina, si tiene: access.js) ·
22
22
  * { type:'file', up, seq, data, last? } (una imagen, en trozos base64 y en
23
23
  * orden; cada trozo se acusa con `filed`, y el último trae la `path` donde
24
- * quedó en esta máquina: uploads.js)
24
+ * quedó en esta máquina: uploads.js) ·
25
+ * { type:'fetch', id, path, seq } (un trozo de un archivo de esta máquina, para
26
+ * abrirlo en el aparato; una ruta relativa cuelga de la carpeta de la consola
27
+ * enganchada: downloads.js)
25
28
  * agente → cliente: { type:'consoles', list } · { type:'attached', id, fresh } ·
26
29
  * { type:'replay', id, data, last } · { type:'out', id, data } ·
27
30
  * { type:'exit', code, closedBy? } · { type:'fail', code, message, retryMs? } ·
28
31
  * { type:'unlocked' } · { type:'noted', console } ·
29
- * { type:'filed', up, seq, path? }
32
+ * { type:'filed', up, seq, path? } ·
33
+ * { type:'fetched', id, seq, path, name, size, mtime, data, last? }
30
34
  *
31
35
  * Con clave puesta, una sesión remota que no la ha escrito recibe `fail` con `code:'locked'`
32
36
  * a todo lo que pida; tras `unlock` vale para esa conexión. `bad-code` y `wait` traen
@@ -40,11 +44,12 @@ import { startRemoteAgent } from '@dotrino/remote-agent/agent'
40
44
  import { dataDir, loadLink, LABEL } from './link.js'
41
45
  import { listTransports, netReport } from '@dotrino/proxy-client'
42
46
  import { shortId } from './far.js'
43
- import { ConsoleHub, pieces, isTyped } from './consoles.js'
47
+ import { ConsoleHub, pieces, isTyped, cwdOf } from './consoles.js'
44
48
  import { listenLocal } from './local.js'
45
49
  import { makeGate } from './access.js'
46
50
  import { makeFar } from './far.js'
47
51
  import { makeUploads } from './uploads.js'
52
+ import { readPiece } from './downloads.js'
48
53
 
49
54
  const require = createRequire(import.meta.url)
50
55
  const { version: VERSION } = require('./package.json')
@@ -254,6 +259,14 @@ export function serveSession (session, hub, { origin = 'remote', gate = null, up
254
259
  }
255
260
  return
256
261
  }
262
+ // Un archivo de esta máquina, para abrirlo en el aparato (una ruta que salió en la consola).
263
+ if (msg.type === 'fetch') {
264
+ try { session.send({ type: 'fetched', ...readPiece(msg, current ? cwdOf(current.pty?.pid) : null) }) } catch (e) {
265
+ if (!e.code || !['bad-fetch', 'no-cwd', 'no-file', 'no-read', 'is-dir', 'not-file', 'too-big', 'changed'].includes(e.code)) console.error('[terminal-agent] could not send a file:', e.message)
266
+ fail(e.code || 'fetch-failed', e.message)
267
+ }
268
+ return
269
+ }
257
270
  // El orden del panel: es de la máquina, así que lo ve igual cualquier pantalla.
258
271
  if (msg.type === 'move') {
259
272
  if (!hub.move(String(msg.id), msg.before == null ? null : String(msg.before))) return fail('no-console', 'that console no longer exists')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/terminal-agent",
3
- "version": "0.49.5",
3
+ "version": "0.50.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": {
@@ -19,6 +19,7 @@
19
19
  "claude.js",
20
20
  "consoles.js",
21
21
  "desktop.js",
22
+ "downloads.js",
22
23
  "link.js",
23
24
  "local.js",
24
25
  "service.js",