@dotrino/terminal-agent 0.54.0 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 } }
package/update.js CHANGED
@@ -20,11 +20,13 @@ import { loadLink } from './link.js'
20
20
  export const PKG = '@dotrino/terminal-agent'
21
21
  export const REPO = 'imdotrino/dotrino-terminal'
22
22
  /** Este repo también lleva la PWA y el escritorio: las releases del agente van con prefijo. */
23
+ /** @param {string} version */
23
24
  export const releaseTag = (version) => `agent-v${version}`
24
25
 
25
26
  /** Cada cuánto se mira si ya no quedan consolas para reiniciar con la versión instalada. */
26
27
  export const IDLE_CHECK_MS = 60_000
27
28
 
29
+ /** @type {(code: string, message: string) => Error & { code: string }} */
28
30
  const fail = (code, message) => Object.assign(new Error(message), { code })
29
31
 
30
32
  /**
@@ -33,8 +35,8 @@ const fail = (code, message) => Object.assign(new Error(message), { code })
33
35
  * del disco. El papel se renueva mientras el agente corre, y el agente puede arrancar sin
34
36
  * enlace y enlazarse después: una conexión fijada al arrancar se quedaría vieja.
35
37
  *
36
- * @param {{ dir: string, product?: string, log?: (m: string) => void, load?: (dir: string) => any, make?: (o: any) => any }} o
37
- * @returns {{ mayUpdate: Function, onUpdated: Function, onNeedsRoot: Function }}
38
+ * @param {{ dir: string, product?: string, log?: (m: string) => void, load?: (dir: string) => DotrinoDeviceLink | null, make?: typeof vaultUpdateHooks }} o
39
+ * @returns {import('@dotrino/vault/service').UpdateHooks}
38
40
  */
39
41
  export function vaultHooks ({ dir, product = PKG, log = console.log, load = loadLink, make = vaultUpdateHooks }) {
40
42
  const now = () => {
@@ -62,12 +64,14 @@ export function vaultHooks ({ dir, product = PKG, log = console.log, load = load
62
64
  * `dir` es la carpeta de datos de ESTA instancia (su enlace y sus ajustes) y `version` la
63
65
  * que está en marcha. Lo demás es para las pruebas.
64
66
  *
65
- * @param {{ dir: string, version: string, agent: { consoles: { consoles: Map<string, unknown> }, close: () => void }, exit?: (code: number) => void, log?: (m: string) => void, watch?: (o: any) => (() => void), hooks?: object, idleCheckMs?: number }} o
67
+ * @param {{ dir: string, version: string, agent: { consoles: { consoles: Map<string, unknown> }, close: () => void }, exit?: (code: number) => void, log?: (m: string) => void, watch?: typeof watchSelfUpdateNpm, hooks?: import('@dotrino/vault/service').UpdateHooks, idleCheckMs?: number }} o
66
68
  * @returns {() => void} para dejar de mirar
67
69
  */
68
70
  export function startSelfUpdate ({ dir, version, agent, exit = (code) => process.exit(code), log = console.log, watch = watchSelfUpdateNpm, hooks = vaultHooks({ dir, log }), idleCheckMs = IDLE_CHECK_MS }) {
71
+ /** @type {ReturnType<typeof setInterval> | null} */
69
72
  let waiting = null
70
73
  const open = () => agent.consoles.consoles.size
74
+ /** @param {string} v */
71
75
  const restart = (v) => {
72
76
  log(`[terminal-agent] restarting to run ${v}`)
73
77
  agent.close()
@@ -86,8 +90,8 @@ export function startSelfUpdate ({ dir, version, agent, exit = (code) => process
86
90
  if (!open()) return restart(v)
87
91
  if (waiting) return
88
92
  log(`[terminal-agent] ${v} is installed · ${open()} console(s) open, so it restarts when none is left`)
89
- waiting = setInterval(() => { if (!open()) { clearInterval(waiting); waiting = null; restart(v) } }, idleCheckMs)
90
- waiting.unref?.()
93
+ const timer = waiting = setInterval(() => { if (!open()) { clearInterval(timer); waiting = null; restart(v) } }, idleCheckMs)
94
+ timer.unref?.()
91
95
  },
92
96
  log
93
97
  })
package/uploads.js CHANGED
@@ -24,9 +24,14 @@ export const UPLOAD_CHUNK_MAX = 256 * 1024
24
24
  /** Lo que se guarda una imagen: después se borra sola. */
25
25
  export const UPLOAD_KEEP_MS = 7 * 24 * 60 * 60 * 1000
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
 
29
30
  /** La extensión de una imagen por sus primeros bytes, o null si no es una de las admitidas. */
31
+ /**
32
+ * @param {Buffer} buf
33
+ * @returns {'png' | 'jpg' | 'gif' | 'webp' | null}
34
+ */
30
35
  export function imageExt (buf) {
31
36
  if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png'
32
37
  if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpg'
@@ -36,19 +41,25 @@ export function imageExt (buf) {
36
41
  }
37
42
 
38
43
  /** Borra las imágenes que ya cumplieron su tiempo. Un fallo aquí se dice y no para nada más. */
44
+ /**
45
+ * @param {string} dir
46
+ * @param {number} [now]
47
+ */
39
48
  export function pruneUploads (dir, now = Date.now()) {
40
49
  let names
41
- try { names = fs.readdirSync(dir) } catch (e) { if (e.code === 'ENOENT') return; throw e }
50
+ try { names = fs.readdirSync(dir) } catch (e) { if (/** @type {Thrown} */ (e).code === 'ENOENT') return; throw e }
42
51
  for (const name of names) {
43
52
  if (!/^img-.*\.(png|jpg|gif|webp)$/.test(name)) continue
44
53
  const file = path.join(dir, name)
45
54
  try { if (now - fs.statSync(file).mtimeMs > UPLOAD_KEEP_MS) fs.rmSync(file) } catch (e) {
46
- console.error('[terminal-agent] could not remove an old image', file, '-', e.message)
55
+ console.error('[terminal-agent] could not remove an old image', file, '-', /** @type {Thrown} */ (e).message)
47
56
  }
48
57
  }
49
58
  }
50
59
 
60
+ /** @param {Date} d */
51
61
  const stamp = (d) => {
62
+ /** @param {number} n */
52
63
  const p = (n) => String(n).padStart(2, '0')
53
64
  return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`
54
65
  }
@@ -59,10 +70,16 @@ const stamp = (d) => {
59
70
  * @param {string} dir la carpeta donde se guardan (se crea, solo para el usuario).
60
71
  * @returns {{ take: (msg: { up: string, seq: number, data: string, last?: boolean }) => { up: string, seq: number, path?: string }, drop: () => void }}
61
72
  */
73
+ /** @param {string} dir */
62
74
  export function makeUploads (dir) {
63
75
  /** @type {{ up: string, next: number, size: number, parts: Buffer[] } | null} */
64
76
  let cur = null
65
77
  return {
78
+ /**
79
+ * Un trozo de una imagen. `msg` llega de la red: se comprueba campo a campo.
80
+ * @param {any} msg
81
+ * @returns {{ up: string, seq: number, path?: string }}
82
+ */
66
83
  take (msg) {
67
84
  const up = typeof msg.up === 'string' ? msg.up.slice(0, 64) : ''
68
85
  const seq = msg.seq