@dotrino/terminal-agent 0.2.15 → 0.3.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 +17 -30
- package/bin/cli.js +27 -26
- package/index.js +55 -191
- package/link.js +14 -102
- package/package.json +25 -8
- package/e2e.js +0 -75
- package/node-globals.js +0 -37
- package/tsconfig.json +0 -39
package/README.md
CHANGED
|
@@ -1,45 +1,32 @@
|
|
|
1
1
|
# @dotrino/terminal-agent
|
|
2
2
|
|
|
3
|
-
Agente de
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
Agente de [Dotrino Terminal](https://terminal.dotrino.com): abre una shell (PTY) en
|
|
4
|
+
esta máquina solo para los aparatos de tu cuenta. Lo común (enrolamiento, saludo contra
|
|
5
|
+
el acta, canal cifrado, revocación, renovación) es
|
|
6
|
+
[`@dotrino/remote-agent`](https://www.npmjs.com/package/@dotrino/remote-agent); esto
|
|
7
|
+
añade el PTY.
|
|
6
8
|
|
|
7
|
-
|
|
8
|
-
enrola con el vault como un dispositivo más, así que **no necesita la maestra** —
|
|
9
|
-
solo su propia sub-clave `D` + `cert` y la pública maestra pineada.
|
|
10
|
-
|
|
11
|
-
- **Autorización = el vault**: cliente y agente son peers certificados por el mismo
|
|
12
|
-
vault; cada uno verifica que el `cert` del otro encadena a la maestra
|
|
13
|
-
(`@dotrino/identity` `verifyChain`). Revocable desde el vault (el agente refresca
|
|
14
|
-
la lista con `vault.devices` por el proxy).
|
|
15
|
-
- **Transporte = el proxy** (`@dotrino/proxy-client`): el agente se identifica bajo
|
|
16
|
-
SU pubkey; el cliente lo direcciona por ella.
|
|
17
|
-
- **Cifrado E2E**: ECDH → AES-GCM por sesión; el proxy solo ve texto cifrado.
|
|
18
|
-
|
|
19
|
-
## Requisitos
|
|
20
|
-
|
|
21
|
-
- Que el vault esté accesible **al enrolar** (para el pairing). Después, las
|
|
22
|
-
sesiones no necesitan el vault online (la confianza está pineada a la pública
|
|
23
|
-
maestra; el TTL del cert acota el riesgo si no puede refrescar revocaciones).
|
|
24
|
-
- Toolchain de C++ para compilar `node-pty` (`build-essential`, `python3`).
|
|
25
|
-
|
|
26
|
-
## Uso
|
|
9
|
+
**Cómo se instala y se usa:** [wiki.dotrino.com/herramientas/terminal](https://wiki.dotrino.com/herramientas/terminal/).
|
|
27
10
|
|
|
28
11
|
```sh
|
|
29
|
-
npx @dotrino/terminal-agent
|
|
30
|
-
npx @dotrino/terminal-agent
|
|
12
|
+
npx @dotrino/terminal-agent # enlaza (si falta) y corre
|
|
13
|
+
npx @dotrino/terminal-agent enroll # re-enlaza y corre
|
|
31
14
|
# [--proxy wss://…] [--shell /bin/zsh] [--dir /ruta]
|
|
32
15
|
```
|
|
33
16
|
|
|
17
|
+
Enlazar pide una terminal interactiva: se pega la invitación de `dotrino-vault pair` y
|
|
18
|
+
se aprueba con `dotrino-vault approve <código>`. Después puede correr como servicio
|
|
19
|
+
(systemd, pm2). Una vez al día avisa si hay versión nueva; no se actualiza solo.
|
|
20
|
+
|
|
34
21
|
Como librería:
|
|
35
22
|
|
|
36
23
|
```js
|
|
37
24
|
import { startAgent } from '@dotrino/terminal-agent'
|
|
38
|
-
const agent = await startAgent({ /* dir, proxyUrl, shell, quiet */ })
|
|
39
|
-
// agent.machine
|
|
40
|
-
// agent.machineId → id corto legible
|
|
41
|
-
// agent.close()
|
|
25
|
+
const agent = await startAgent({ /* dir, proxyUrl, shell, quiet, onRevoked */ })
|
|
26
|
+
// agent.machine · agent.machineId · agent.close()
|
|
42
27
|
```
|
|
43
28
|
|
|
44
|
-
Datos en `~/.local/share/dotrino-terminal-agent` (override `DOTRINO_TERMINAL_DIR`).
|
|
29
|
+
Datos en `~/.local/share/dotrino-terminal-agent` (override `DOTRINO_TERMINAL_DIR`). El
|
|
30
|
+
`link.json` guarda la llave privada de la máquina: trátalo como una llave SSH.
|
|
31
|
+
|
|
45
32
|
MIT.
|
package/bin/cli.js
CHANGED
|
@@ -5,14 +5,16 @@
|
|
|
5
5
|
* dotrino-terminal-agent # enlaza (si falta) y CORRE el agente
|
|
6
6
|
* dotrino-terminal-agent enroll # re-enlaza (sobrescribe) y corre el agente
|
|
7
7
|
*
|
|
8
|
-
* El agente es un
|
|
9
|
-
*
|
|
10
|
-
* su "dirección de máquina" (pubkey), aunque aparece sola en terminal.dotrino.com.
|
|
8
|
+
* El agente es un aparato más de tu cuenta: puede vivir en cualquier máquina. Con un
|
|
9
|
+
* solo comando queda enlazado y aparece solo en terminal.dotrino.com.
|
|
11
10
|
*/
|
|
12
11
|
import readline from 'node:readline'
|
|
12
|
+
import { createRequire } from 'node:module'
|
|
13
|
+
import { watchForUpdate } from '@dotrino/update'
|
|
13
14
|
import { startAgent } from '../index.js'
|
|
14
15
|
import { enroll, parseQr, loadLink, dataDir } from '../link.js'
|
|
15
16
|
|
|
17
|
+
const { version: VERSION } = createRequire(import.meta.url)('../package.json')
|
|
16
18
|
const args = process.argv.slice(2)
|
|
17
19
|
const cmd = args[0] && !args[0].startsWith('-') ? args[0] : 'run'
|
|
18
20
|
const opt = (name) => { const i = args.indexOf(name); return i >= 0 ? args[i + 1] : undefined }
|
|
@@ -26,42 +28,38 @@ if (args.includes('-h') || args.includes('--help')) {
|
|
|
26
28
|
console.log(`uso:
|
|
27
29
|
dotrino-terminal-agent enlaza esta máquina (si falta) y corre el agente
|
|
28
30
|
dotrino-terminal-agent enroll re-enlaza (sobrescribe el enlace) y corre el agente
|
|
29
|
-
opciones: [--
|
|
31
|
+
opciones: [--proxy <wss://…>] [--shell <bin>] [--dir <ruta>]
|
|
30
32
|
|
|
31
33
|
datos en ${dataDir()} (override DOTRINO_TERMINAL_DIR)`)
|
|
32
34
|
process.exit(0)
|
|
33
35
|
}
|
|
34
36
|
|
|
35
37
|
async function doEnroll (dir) {
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
console.log('
|
|
40
|
-
console.log('
|
|
41
|
-
const
|
|
42
|
-
const qr = parseQr(text)
|
|
38
|
+
if (!process.stdin.isTTY) {
|
|
39
|
+
throw new Error('this machine is not linked, and linking needs an interactive terminal. Run it once in a terminal, then start it as a service.')
|
|
40
|
+
}
|
|
41
|
+
console.log('Enlazar esta máquina con tu bóveda.')
|
|
42
|
+
console.log('En el PC de tu bóveda corre `dotrino-vault pair` y copia la invitación.\n')
|
|
43
|
+
const qr = await parseQr(await ask('Pega la invitación y pulsa Enter:\n> '))
|
|
43
44
|
console.log('\nConectando…')
|
|
44
45
|
await enroll({
|
|
45
46
|
qr,
|
|
46
47
|
dir,
|
|
47
|
-
label: opt('--label') || 'terminal-agent',
|
|
48
48
|
onChallenge: ({ deviceId, code }) => {
|
|
49
49
|
console.log('\n Escribe ESTE código en tu bóveda para aprobar esta máquina:')
|
|
50
|
-
console.log(` código:
|
|
50
|
+
console.log(` código: ${code}`)
|
|
51
51
|
console.log(` máquina: ${deviceId}`)
|
|
52
|
-
console.log(
|
|
53
|
-
console.log(
|
|
54
|
-
console.log(' Esperando aprobación…')
|
|
52
|
+
console.log(` (en el PC de la bóveda: dotrino-vault approve ${code})\n`)
|
|
53
|
+
console.log(' Esperando la aprobación…')
|
|
55
54
|
}
|
|
56
55
|
})
|
|
57
|
-
console.log('\n ✓ Máquina enlazada
|
|
56
|
+
console.log('\n ✓ Máquina enlazada. Levantando el agente…\n')
|
|
58
57
|
}
|
|
59
58
|
|
|
60
59
|
try {
|
|
61
60
|
const dir = opt('--dir')
|
|
62
|
-
//
|
|
63
|
-
//
|
|
64
|
-
// y LEVANTA el servicio (antes moría tras enrolar y había que relanzarlo).
|
|
61
|
+
// Sin `enroll`, enlaza solo si aún no lo está; `enroll` re-enlaza aunque ya lo esté.
|
|
62
|
+
// En los dos casos sigue y LEVANTA el servicio.
|
|
65
63
|
if (cmd === 'enroll' || !loadLink(dir)) {
|
|
66
64
|
if (cmd === 'enroll' && loadLink(dir)) console.log('Re-enlazando esta máquina (sobrescribe el enlace actual).\n')
|
|
67
65
|
await doEnroll(dir)
|
|
@@ -69,15 +67,18 @@ try {
|
|
|
69
67
|
|
|
70
68
|
const agent = await startAgent({
|
|
71
69
|
dir, proxyUrl: opt('--proxy'), shell: opt('--shell'),
|
|
72
|
-
onRevoked: () => { console.log(' Esta máquina
|
|
70
|
+
onRevoked: () => { console.log(' Esta máquina se quitó de tu bóveda. Para volver a usarla, enlázala otra vez.\n'); process.exit(0) }
|
|
73
71
|
})
|
|
74
72
|
console.log('\n Dotrino Terminal — agente activo')
|
|
75
|
-
console.log('
|
|
76
|
-
console.log('
|
|
77
|
-
|
|
73
|
+
console.log(' versión:', VERSION)
|
|
74
|
+
console.log(' máquina:', agent.machineId, '\n')
|
|
75
|
+
// §15: una vez al día mira si hay versión nueva y lo dice. Solo avisa: instalar lo decide una persona.
|
|
76
|
+
watchForUpdate({
|
|
77
|
+
current: VERSION, source: 'npm', pkg: '@dotrino/terminal-agent',
|
|
78
|
+
onNewer: (r) => console.log(`[terminal-agent] version ${r.version} is available (running ${r.current}): npx @dotrino/terminal-agent@latest`)
|
|
79
|
+
})
|
|
78
80
|
// Mantener vivo el servicio aunque stdin no sea una TTY (systemd/pm2/`nohup </dev/null`):
|
|
79
|
-
// el socket del
|
|
80
|
-
// justo después de arrancar. Vive hasta SIGINT/SIGTERM (o auto-borrado por revocación).
|
|
81
|
+
// el socket del proxio va `unref`'d, así que sin esto el proceso saldría al arrancar.
|
|
81
82
|
const keepAlive = setInterval(() => {}, 1 << 30)
|
|
82
83
|
const bye = () => { clearInterval(keepAlive); agent.close(); process.exit(0) }
|
|
83
84
|
process.on('SIGINT', bye); process.on('SIGTERM', bye)
|
package/index.js
CHANGED
|
@@ -1,215 +1,79 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @dotrino/terminal-agent — abre una shell real (PTY) SOLO para
|
|
3
|
-
* enlazados al mismo vault. Puede correr en CUALQUIER máquina: se enrola con el
|
|
4
|
-
* vault como un dispositivo más (ver link.js), así que NO necesita la maestra —
|
|
5
|
-
* solo su propia sub-clave `D` + `cert` y la pública maestra pineada (`iss`).
|
|
2
|
+
* @dotrino/terminal-agent — abre una shell real (PTY) SOLO para aparatos de tu cuenta.
|
|
6
3
|
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* adjunta su `cert`, para que el cliente compruebe que habla con una máquina que
|
|
12
|
-
* el vault certificó (anti-MITM del relay).
|
|
4
|
+
* Lo común (enrolarse con la bóveda, handshake contra el ACTA, canal cifrado por sesión,
|
|
5
|
+
* revocación, renovación del papel, auditoría) lo hace `@dotrino/remote-agent`: este
|
|
6
|
+
* paquete solo sabe de PTY. Antes lo hacía todo a mano (su propio enrolamiento, su propio
|
|
7
|
+
* cifrado) y por eso se quedó atrás: con la bóveda actual no podía ni emparejarse.
|
|
13
8
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
9
|
+
* Payloads de dominio (van cifrados dentro de la sesión, el proxio no los ve):
|
|
10
|
+
* cliente → agente: { type:'open', cols, rows } · { type:'input', data } ·
|
|
11
|
+
* { type:'resize', cols, rows } · { type:'close' }
|
|
12
|
+
* agente → cliente: { type:'out', data } · { type:'exit', code }
|
|
18
13
|
*/
|
|
19
14
|
import os from 'node:os'
|
|
20
|
-
import fs from 'node:fs'
|
|
21
|
-
import path from 'node:path'
|
|
22
15
|
import { createRequire } from 'node:module'
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import { makeEphemeral, deriveKey, seal, open } from './e2e.js'
|
|
26
|
-
import { loadLink, dataDir } from './link.js'
|
|
16
|
+
import { startRemoteAgent } from '@dotrino/remote-agent/agent'
|
|
17
|
+
import { dataDir, LABEL } from './link.js'
|
|
27
18
|
|
|
28
19
|
const require = createRequire(import.meta.url)
|
|
29
20
|
|
|
30
|
-
|
|
31
|
-
HS: 'terminal.hs', ACK: 'terminal.hs.ack', CMD: 'terminal.cmd', OUT: 'terminal.out', ERROR: 'terminal.error',
|
|
32
|
-
PING: 'terminal.ping', PONG: 'terminal.pong'
|
|
33
|
-
}
|
|
34
|
-
const VMSG = { DEVICES: 'vault.devices', DEVICES_RESULT: 'vault.devices.result', REVOKED: 'vault.revoked' }
|
|
35
|
-
const SIGN_SCOPE = 'vault:sign'
|
|
36
|
-
const SESSION_TTL_MS = 30 * 60 * 1000
|
|
37
|
-
const REVOKE_REFRESH_MS = 5 * 60 * 1000
|
|
38
|
-
|
|
39
|
-
export async function startAgent (opts = {}) {
|
|
40
|
-
const dir = opts.dir || dataDir()
|
|
41
|
-
const link = opts.link || loadLink(dir)
|
|
42
|
-
if (!link?.device?.privateJwk || !link?.cert || !link?.iss) {
|
|
43
|
-
throw new Error('esta máquina no está enlazada. Ejecuta primero: `npx @dotrino/terminal-agent enroll`.')
|
|
44
|
-
}
|
|
45
|
-
const master = link.iss
|
|
46
|
-
const myPub = link.device.publickey
|
|
47
|
-
const myId = (await pubkeyId(myPub)).slice(0, 8).toUpperCase().replace(/(.{4})(.{4})/, '$1-$2')
|
|
48
|
-
|
|
49
|
-
installNodeGlobals(dir)
|
|
50
|
-
|
|
51
|
-
// PTY nativo con binarios PREBUILT (Linux/macOS/Windows, sin toolchain): el fork
|
|
52
|
-
// `@homebridge/node-pty-prebuilt-multiarch` es API-idéntico a node-pty. Fallback a
|
|
53
|
-
// `node-pty` por si una instalación vieja lo trae.
|
|
54
|
-
let pty
|
|
55
|
-
try { pty = require('@homebridge/node-pty-prebuilt-multiarch') } catch {
|
|
56
|
-
try { pty = require('node-pty') } catch {
|
|
57
|
-
throw new Error('falta el módulo PTY. Reinstala el agente: `npx @dotrino/terminal-agent` (baja el binario prebuilt).')
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
const { getWebSocketProxyClient } = await import('@dotrino/proxy-client')
|
|
62
|
-
const proxyUrl = opts.proxyUrl || process.env.PROXY_URL || link.proxy || 'wss://proxy.dotrino.com'
|
|
63
|
-
const client = getWebSocketProxyClient({
|
|
64
|
-
url: proxyUrl, enableWebRTC: false, autoReconnect: true,
|
|
65
|
-
maxReconnectAttempts: 100000, reconnectDelay: 4000
|
|
66
|
-
})
|
|
67
|
-
await client.connect()
|
|
68
|
-
|
|
69
|
-
// Identificarse bajo la pubkey de ESTA máquina (firmado con su D).
|
|
70
|
-
const identify = async () => {
|
|
71
|
-
if (!client.token) return
|
|
72
|
-
const data = { op: 'identify', publickey: myPub, token: client.token, ts: Date.now() }
|
|
73
|
-
const { signature } = await signWithDevice({ privateJwk: link.device.privateJwk, data })
|
|
74
|
-
await client.identify({ data, signature })
|
|
75
|
-
}
|
|
76
|
-
await identify()
|
|
77
|
-
client.on('token', () => { identify().catch(() => {}) })
|
|
78
|
-
|
|
79
|
-
// Bitácora persistente de sesiones (sessions.log, JSONL): qué dispositivo abrió
|
|
80
|
-
// consola y cuándo — auditoría local si un dispositivo tuyo cae en malas manos.
|
|
81
|
-
const sessionsLog = path.join(dir, 'sessions.log')
|
|
82
|
-
const audit = (op, info = {}) => {
|
|
83
|
-
try { fs.appendFileSync(sessionsLog, JSON.stringify({ ts: Date.now(), op, ...info }) + '\n') } catch (_) {}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
const send = (to, obj) => { try { client.send(to, obj) } catch (e) { if (!opts.quiet) console.error('[terminal] send:', e.message) } }
|
|
87
|
-
|
|
88
|
-
// --- Revocación: refrescar la lista del vault por el proxy (best-effort) ---
|
|
89
|
-
let revokedSet = new Set()
|
|
90
|
-
async function refreshRevocations () {
|
|
91
|
-
try {
|
|
92
|
-
const data = { op: 'devices', publickey: myPub, ts: Date.now() }
|
|
93
|
-
const { signature } = await signWithDevice({ privateJwk: link.device.privateJwk, data })
|
|
94
|
-
const res = await new Promise((resolve, reject) => {
|
|
95
|
-
const off = client.on('message', (_f, p) => {
|
|
96
|
-
if (p?.type === VMSG.DEVICES_RESULT) { off(); resolve(p) }
|
|
97
|
-
else if (p?.type === 'vault.error') { off(); reject(new Error(p.error)) }
|
|
98
|
-
})
|
|
99
|
-
setTimeout(() => { off(); reject(new Error('timeout')) }, 15000)
|
|
100
|
-
client.sendByPubkey(master, { type: VMSG.DEVICES, data, signature, cert: link.cert })
|
|
101
|
-
})
|
|
102
|
-
revokedSet = new Set((res.revoked || []).map((r) => r.nonce || r))
|
|
103
|
-
} catch (e) {
|
|
104
|
-
if (!opts.quiet) console.error('[terminal] no pude refrescar revocaciones (uso la cache):', e.message)
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
refreshRevocations()
|
|
108
|
-
const revTimer = setInterval(refreshRevocations, REVOKE_REFRESH_MS); revTimer.unref?.()
|
|
109
|
-
|
|
110
|
-
// sid -> { key, term, from, exp }
|
|
111
|
-
const sessions = new Map()
|
|
112
|
-
const sweeper = setInterval(() => {
|
|
113
|
-
const now = Date.now()
|
|
114
|
-
for (const [sid, s] of sessions) if (now > s.exp) { try { s.term?.kill() } catch {}; sessions.delete(sid); audit('session-expire', { sid: sid.slice(0, 8) }) }
|
|
115
|
-
}, 60 * 1000); sweeper.unref?.()
|
|
21
|
+
export { LABEL }
|
|
116
22
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
async function handleHandshake (from, p) {
|
|
124
|
-
const { data, signature, cert } = p
|
|
125
|
-
if (!data || !signature || !cert) return send(from, { type: T.ERROR, error: 'handshake incompleto' })
|
|
126
|
-
// FRESCURA anti-replay: el HS debe ser reciente (±5 min); sin esto un relay
|
|
127
|
-
// malicioso podía reproducir handshakes viejos (sesiones huérfanas / DoS).
|
|
128
|
-
if (typeof data.ts !== 'number' || Math.abs(Date.now() - data.ts) > 5 * 60 * 1000) {
|
|
129
|
-
return send(from, { type: T.ERROR, error: 'handshake vencido (posible replay, o el reloj del dispositivo está desfasado)' })
|
|
130
|
-
}
|
|
131
|
-
const chk = await verifyChain({ data, signature, cert, expectedScope: SIGN_SCOPE, trustedIssuer: master, revoked: revokedSet })
|
|
132
|
-
if (!chk.ok) return send(from, { type: T.ERROR, error: 'no autorizado: ' + chk.reason })
|
|
133
|
-
if (data.op !== 'terminal.hs' || typeof data.eph !== 'string') return send(from, { type: T.ERROR, error: 'handshake inválido' })
|
|
134
|
-
|
|
135
|
-
const eph = await makeEphemeral()
|
|
136
|
-
const sid = [...crypto.getRandomValues(new Uint8Array(16))].map((x) => x.toString(16).padStart(2, '0')).join('')
|
|
137
|
-
const key = await deriveKey(eph.privateKey, data.eph, sid)
|
|
138
|
-
// Ack firmado con la D de ESTA máquina + su cert: el cliente verifica la
|
|
139
|
-
// cadena a la maestra y que la pub efímera viene de una máquina certificada.
|
|
140
|
-
// `publickey` va DENTRO del dato firmado (verifyChain lo exige: firma contra
|
|
141
|
-
// data.publickey y cert.sub === data.publickey).
|
|
142
|
-
const ack = { op: 'terminal.hs.ack', sid, seph: eph.pub, ceph: data.eph, machine: myPub, publickey: myPub, ts: Date.now() }
|
|
143
|
-
const { signature: ackSig } = await signWithDevice({ privateJwk: link.device.privateJwk, data: ack })
|
|
144
|
-
|
|
145
|
-
sessions.set(sid, { sid, key, term: null, from, exp: Date.now() + SESSION_TTL_MS })
|
|
146
|
-
audit('session-open', { sid: sid.slice(0, 8), device: (await pubkeyId(chk.device)).slice(0, 8).toUpperCase() })
|
|
147
|
-
send(from, { type: T.ACK, sid, ack, signature: ackSig, cert: link.cert })
|
|
148
|
-
if (!opts.quiet) console.log(`[terminal] sesión ${sid.slice(0, 8)} autorizada (device ${chk.device?.slice?.(0, 8) || '?'})`)
|
|
23
|
+
export function loadPty () {
|
|
24
|
+
// Binarios PREBUILT (Linux/macOS/Windows, sin toolchain), API idéntica a node-pty.
|
|
25
|
+
try { return require('@homebridge/node-pty-prebuilt-multiarch') } catch (e) {
|
|
26
|
+
throw new Error('PTY module missing. Reinstall the agent: `npx @dotrino/terminal-agent` (' + e.message + ')')
|
|
149
27
|
}
|
|
28
|
+
}
|
|
150
29
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
s.from = from
|
|
156
|
-
let msg
|
|
157
|
-
try { msg = await open(s.key, p.env) } catch { return send(from, { type: T.ERROR, error: 'sobre inválido' }) }
|
|
30
|
+
/** Atiende una sesión cifrada: una shell por sesión. Exportada para las pruebas. */
|
|
31
|
+
export function servePty (session, pty, opts) {
|
|
32
|
+
let term = null
|
|
33
|
+
const kill = () => { try { term?.kill() } catch (_) {} term = null }
|
|
158
34
|
|
|
35
|
+
session.on('message', (msg) => {
|
|
36
|
+
if (!msg || typeof msg !== 'object') return
|
|
159
37
|
if (msg.type === 'open') {
|
|
160
|
-
if (
|
|
38
|
+
if (term) return
|
|
161
39
|
const shell = opts.shell || process.env.SHELL || (process.platform === 'win32' ? 'powershell.exe' : 'bash')
|
|
162
|
-
|
|
40
|
+
term = pty.spawn(shell, [], {
|
|
163
41
|
name: 'xterm-256color', cols: msg.cols || 80, rows: msg.rows || 24,
|
|
164
42
|
cwd: os.homedir(), env: { ...process.env, TERM: 'xterm-256color' }
|
|
165
43
|
})
|
|
166
|
-
|
|
167
|
-
|
|
44
|
+
term.onData((data) => { session.send({ type: 'out', data }) })
|
|
45
|
+
term.onExit(({ exitCode }) => { session.send({ type: 'exit', code: exitCode }); term = null })
|
|
168
46
|
return
|
|
169
47
|
}
|
|
170
|
-
if (msg.type === 'input')
|
|
171
|
-
if (msg.type === 'resize') { try {
|
|
172
|
-
if (msg.type === 'close') {
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
const stop = () => {
|
|
176
|
-
clearInterval(revTimer); clearInterval(sweeper)
|
|
177
|
-
for (const s of sessions.values()) { try { s.term?.kill() } catch {} }
|
|
178
|
-
try { client.close() } catch {}
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// AUTO-BORRADO al ser REVOCADA: la bóveda envía un REVOKED FIRMADO por la maestra
|
|
182
|
-
// dirigido a ESTA máquina (al revocar, o cuando reaparece: ver @dotrino/vault). Solo
|
|
183
|
-
// nos borramos si la firma valida y el body es para nuestra pubkey → un proxy/peer
|
|
184
|
-
// malicioso NO puede borrarnos con un mensaje falso (cierra el wipe-DoS). Borra el
|
|
185
|
-
// enlace (link.json) y detiene el agente.
|
|
186
|
-
async function handleRevoked (p) {
|
|
187
|
-
const b = p?.body
|
|
188
|
-
if (!b || b.op !== 'revoke' || b.sub !== myPub) return
|
|
189
|
-
if (typeof b.exp === 'number' && Date.now() > b.exp) return
|
|
190
|
-
if (!await verifyDeviceSig({ publickey: master, data: b, signature: p.signature })) return
|
|
191
|
-
audit('revoked', { nonce: b.nonce })
|
|
192
|
-
if (!opts.quiet) console.log('\n[terminal] tu bóveda REVOCÓ esta máquina → borro el enlace y salgo.')
|
|
193
|
-
try { fs.rmSync(path.join(dir, 'link.json'), { force: true }) } catch (_) {}
|
|
194
|
-
stop()
|
|
195
|
-
if (opts.onRevoked) { try { opts.onRevoked() } catch (_) {} }
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
client.on('message', (from, payload) => {
|
|
199
|
-
if (!payload || typeof payload !== 'object') return
|
|
200
|
-
if (payload.type === T.HS) handleHandshake(from, payload).catch((e) => send(from, { type: T.ERROR, error: e.message }))
|
|
201
|
-
else if (payload.type === T.CMD) handleCmd(from, payload).catch((e) => send(from, { type: T.ERROR, error: e.message }))
|
|
202
|
-
// Sonda de presencia (liveness): el cliente hace ping y respondemos pong con el
|
|
203
|
-
// mismo nonce → así la app sabe que esta máquina está online (sin abrir sesión).
|
|
204
|
-
else if (payload.type === T.PING) send(from, { type: T.PONG, n: payload.n })
|
|
205
|
-
else if (payload.type === VMSG.REVOKED) handleRevoked(payload).catch(() => {})
|
|
48
|
+
if (msg.type === 'input') { term?.write(String(msg.data ?? '')); return }
|
|
49
|
+
if (msg.type === 'resize') { try { term?.resize(msg.cols, msg.rows) } catch (_) {} return }
|
|
50
|
+
if (msg.type === 'close') { kill(); session.close() }
|
|
206
51
|
})
|
|
52
|
+
// La sesión se cierra por inactividad o al parar el agente: la shell muere con ella.
|
|
53
|
+
session.on('close', kill)
|
|
54
|
+
}
|
|
207
55
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
56
|
+
/**
|
|
57
|
+
* Arranca el agente. Devuelve lo mismo que `startRemoteAgent`:
|
|
58
|
+
* `{ machine, machineId, master, client, close }`.
|
|
59
|
+
*
|
|
60
|
+
* @param {object} [opts]
|
|
61
|
+
* @param {string} [opts.dir] dónde vive el enlace (default dataDir()).
|
|
62
|
+
* @param {string} [opts.proxyUrl] override del proxio del enlace.
|
|
63
|
+
* @param {string} [opts.shell] shell a lanzar (default $SHELL).
|
|
64
|
+
* @param {boolean} [opts.quiet]
|
|
65
|
+
* @param {()=>void} [opts.onRevoked]
|
|
66
|
+
*/
|
|
67
|
+
export async function startAgent (opts = {}) {
|
|
68
|
+
const pty = loadPty()
|
|
69
|
+
return startRemoteAgent({
|
|
70
|
+
label: LABEL,
|
|
71
|
+
dir: opts.dir || dataDir(),
|
|
72
|
+
proxyUrl: opts.proxyUrl,
|
|
73
|
+
quiet: opts.quiet,
|
|
74
|
+
onRevoked: opts.onRevoked,
|
|
75
|
+
onSession: (session) => servePty(session, pty, opts)
|
|
76
|
+
})
|
|
213
77
|
}
|
|
214
78
|
|
|
215
|
-
export default { startAgent }
|
|
79
|
+
export default { startAgent, LABEL }
|
package/link.js
CHANGED
|
@@ -1,118 +1,30 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* link.js —
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* sub-clave `D` + `cert` (cadena `D ← maestra`); la maestra NUNCA vive aquí, solo
|
|
6
|
-
* su pública pineada (`iss`).
|
|
7
|
-
*
|
|
8
|
-
* Persistencia en un directorio propio (por defecto
|
|
9
|
-
* `~/.local/share/dotrino-terminal-agent`, override `DOTRINO_TERMINAL_DIR`): NO
|
|
10
|
-
* comparte carpeta con el vault, así el agente puede correr en otro host.
|
|
2
|
+
* link.js — el enlace de esta máquina con la bóveda. Todo lo hace
|
|
3
|
+
* `@dotrino/remote-agent/link` (que a su vez usa `enrollWithVault`, el único
|
|
4
|
+
* enrolamiento headless del ecosistema); aquí solo se decide DÓNDE vive el enlace.
|
|
11
5
|
*/
|
|
12
|
-
import fs from 'node:fs'
|
|
13
6
|
import path from 'node:path'
|
|
14
7
|
import os from 'node:os'
|
|
15
|
-
import {
|
|
16
|
-
makeDeviceKey, signWithDevice, verifyDelegation, makePairingCode, commitCode, pubkeyId
|
|
17
|
-
} from '@dotrino/identity/capabilities'
|
|
18
|
-
import { installNodeGlobals } from './node-globals.js'
|
|
8
|
+
import { enroll as raEnroll, loadLink as raLoad, parseQr } from '@dotrino/remote-agent/link'
|
|
19
9
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
ERROR: 'vault.error'
|
|
25
|
-
}
|
|
10
|
+
export { parseQr }
|
|
11
|
+
|
|
12
|
+
/** Label con el que se enrola y con el que la app encuentra las máquinas. */
|
|
13
|
+
export const LABEL = 'terminal-agent'
|
|
26
14
|
|
|
15
|
+
/** `~/.local/share/dotrino-terminal-agent` (override `DOTRINO_TERMINAL_DIR`). */
|
|
27
16
|
export function dataDir () {
|
|
28
17
|
if (process.env.DOTRINO_TERMINAL_DIR) return process.env.DOTRINO_TERMINAL_DIR
|
|
29
18
|
const base = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share')
|
|
30
19
|
return path.join(base, 'dotrino-terminal-agent')
|
|
31
20
|
}
|
|
32
21
|
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
export function loadLink (dir = dataDir()) {
|
|
36
|
-
try { return JSON.parse(fs.readFileSync(linkPath(dir), 'utf8')) } catch { return null }
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function saveLink (dir, link) {
|
|
40
|
-
fs.mkdirSync(dir, { recursive: true })
|
|
41
|
-
fs.writeFileSync(linkPath(dir), JSON.stringify(link, null, 2), { mode: 0o600 })
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// Decodifica base64url a string UTF-8 (Node). El código copiable de la web
|
|
45
|
-
// (profile.dotrino.com/#myvault) viaja en base64url para no exponer iss/token/sn.
|
|
46
|
-
function b64urlDecode (s) {
|
|
47
|
-
s = String(s).replace(/-/g, '+').replace(/_/g, '/')
|
|
48
|
-
while (s.length % 4) s += '='
|
|
49
|
-
return Buffer.from(s, 'base64').toString('utf8')
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function parseQr (text) {
|
|
53
|
-
let s = String(text ?? '').trim()
|
|
54
|
-
const i = s.indexOf('#vault=')
|
|
55
|
-
if (i >= 0) s = s.slice(i + 7).trim() // profile.dotrino.com/#vault=…
|
|
56
|
-
if (!s.startsWith('{')) { // no es JSON crudo → probar base64url
|
|
57
|
-
const json = b64urlDecode(s)
|
|
58
|
-
if (json && json.trim().startsWith('{')) s = json
|
|
59
|
-
else throw new Error('código de emparejamiento inválido (se espera JSON o base64url)')
|
|
60
|
-
}
|
|
61
|
-
const qr = JSON.parse(s)
|
|
62
|
-
if (!qr?.iss || !qr?.proxy || !qr?.token || !qr?.sn) throw new Error('QR inválido (v2): faltan iss/proxy/token/sn')
|
|
63
|
-
return qr
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
async function freshClient (proxyUrl, dir) {
|
|
67
|
-
installNodeGlobals(dir)
|
|
68
|
-
const { WebSocketProxyClient } = await import('@dotrino/proxy-client')
|
|
69
|
-
const client = new WebSocketProxyClient({ url: proxyUrl, enableWebRTC: false, autoReconnect: false })
|
|
70
|
-
await client.connect()
|
|
71
|
-
return client
|
|
72
|
-
}
|
|
22
|
+
export const loadLink = (dir = dataDir()) => raLoad(dir)
|
|
73
23
|
|
|
74
24
|
/**
|
|
75
|
-
* Enrola esta máquina
|
|
76
|
-
*
|
|
77
|
-
* @param {(c:{deviceId:string,code:string})=>void} onChallenge mostrar el CÓDIGO para que un humano lo TIPEE en la bóveda al aprobar (el código NO viaja de aquí)
|
|
25
|
+
* Enrola esta máquina con la invitación de la bóveda (cualquiera de sus formas).
|
|
26
|
+
* @param {{ qr:object|string, dir?:string, label?:string, onChallenge?:(c:{deviceId:string,code:string})=>void }} args
|
|
78
27
|
*/
|
|
79
|
-
export
|
|
80
|
-
|
|
81
|
-
try {
|
|
82
|
-
const device = await makeDeviceKey({ label })
|
|
83
|
-
const deviceId = (await pubkeyId(device.publickey)).slice(0, 8).toUpperCase().replace(/(.{4})(.{4})/, '$1-$2')
|
|
84
|
-
// Código de emparejamiento ALEATORIO (un secreto, NO derivable de valores públicos):
|
|
85
|
-
// lo mostramos y NO lo enviamos. La bóveda lo aprende solo cuando un humano lo tipea
|
|
86
|
-
// y nos lo ECHA de vuelta → así aprobar exige TENER esta máquina (de aquí sale el código).
|
|
87
|
-
const code = makePairingCode()
|
|
88
|
-
// El COMPROMISO del código (nunca el código): la bóveda lo recompone con lo que
|
|
89
|
-
// tipeas y solo entonces firma el cert → aprobar exige haber leído esta pantalla.
|
|
90
|
-
const commit = await commitCode({ code, dpub: device.publickey, sn: qr.sn })
|
|
91
|
-
const data = { op: 'enroll', dpub: device.publickey, token: qr.token, sn: qr.sn, commit, label, ts: Date.now() }
|
|
92
|
-
const { signature } = await signWithDevice({ privateJwk: device.privateJwk, data })
|
|
93
|
-
|
|
94
|
-
const done = new Promise((resolve, reject) => {
|
|
95
|
-
const off = client.on('message', (_from, p) => {
|
|
96
|
-
if (!p || typeof p !== 'object') return
|
|
97
|
-
if (p.type === MSG.ENROLL_CHALLENGE) onChallenge?.({ deviceId, code })
|
|
98
|
-
// Aceptamos SOLO si el código echado coincide con el que generamos (anti
|
|
99
|
-
// aprobación-a-ciegas / bóveda impostora). Un eco distinto se IGNORA y seguimos
|
|
100
|
-
// esperando la aprobación correcta (o el timeout).
|
|
101
|
-
else if (p.type === MSG.ENROLLED) { if (String(p.code || '').trim() === code) { cleanup(); resolve(p) } }
|
|
102
|
-
else if (p.type === MSG.ERROR) { cleanup(); reject(new Error(p.error)) }
|
|
103
|
-
})
|
|
104
|
-
const t = setTimeout(() => { cleanup(); reject(new Error('timeout esperando la aprobación en el vault')) }, timeoutMs)
|
|
105
|
-
const cleanup = () => { off(); clearTimeout(t) }
|
|
106
|
-
})
|
|
107
|
-
client.sendByPubkey(qr.iss, { type: MSG.ENROLL, data, signature })
|
|
108
|
-
const res = await done
|
|
109
|
-
|
|
110
|
-
const v = await verifyDelegation({ cert: res.cert, expectedSub: device.publickey })
|
|
111
|
-
if (!v.ok) throw new Error('cert inválido: ' + v.reason)
|
|
112
|
-
if (res.cert.iss !== qr.iss) throw new Error('cert firmado por otra maestra (posible proxy malicioso)')
|
|
113
|
-
|
|
114
|
-
const link = { device, cert: res.cert, iss: qr.iss, proxy: qr.proxy, label, at: Date.now() }
|
|
115
|
-
saveLink(dir, link)
|
|
116
|
-
return link
|
|
117
|
-
} finally { client.close() }
|
|
28
|
+
export function enroll ({ qr, dir = dataDir(), label = LABEL, onChallenge }) {
|
|
29
|
+
return raEnroll({ qr, dir, label, onChallenge })
|
|
118
30
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/terminal-agent",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Agente de Dotrino Terminal: abre una shell (PTY) en
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "Agente de Dotrino Terminal: abre una shell (PTY) en esta máquina solo para los aparatos de tu cuenta, cifrada punto a punto, vía @dotrino/remote-agent.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"dotrino-terminal-agent": "bin/cli.js"
|
|
@@ -9,19 +9,36 @@
|
|
|
9
9
|
"exports": {
|
|
10
10
|
".": "./index.js"
|
|
11
11
|
},
|
|
12
|
+
"files": [
|
|
13
|
+
"index.js",
|
|
14
|
+
"link.js",
|
|
15
|
+
"bin"
|
|
16
|
+
],
|
|
12
17
|
"scripts": {
|
|
13
18
|
"start": "node bin/cli.js",
|
|
19
|
+
"test": "node --test \"test/**/*.test.mjs\"",
|
|
14
20
|
"type-check": "tsc --noEmit"
|
|
15
21
|
},
|
|
16
22
|
"dependencies": {
|
|
17
|
-
"@dotrino/identity": "0.
|
|
18
|
-
"@dotrino/proxy-client": "0.
|
|
19
|
-
"@
|
|
20
|
-
"
|
|
23
|
+
"@dotrino/identity": "0.105.0",
|
|
24
|
+
"@dotrino/proxy-client": "0.25.0",
|
|
25
|
+
"@dotrino/remote-agent": "0.10.0",
|
|
26
|
+
"@dotrino/update": "0.2.2",
|
|
27
|
+
"@dotrino/vault": "0.74.0",
|
|
28
|
+
"@homebridge/node-pty-prebuilt-multiarch": "0.14.1-beta.2"
|
|
29
|
+
},
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=20"
|
|
21
32
|
},
|
|
22
33
|
"license": "MIT",
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "git+https://github.com/imdotrino/dotrino-terminal.git",
|
|
37
|
+
"directory": "agent"
|
|
38
|
+
},
|
|
39
|
+
"homepage": "https://terminal.dotrino.com/",
|
|
23
40
|
"devDependencies": {
|
|
24
|
-
"
|
|
25
|
-
"
|
|
41
|
+
"@types/node": "^22.0.0",
|
|
42
|
+
"typescript": "5.9.3"
|
|
26
43
|
}
|
|
27
44
|
}
|
package/e2e.js
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
// COPIA de ../shared/e2e.js (fuente única en shared/). No editar aquí: tras cambiar
|
|
2
|
-
// shared/e2e.js, volver a copiarlo (el paquete npm no incluye ../shared).
|
|
3
|
-
/**
|
|
4
|
-
* e2e.js — canal cifrado punto a punto entre el dispositivo enlazado y el agente
|
|
5
|
-
* de la máquina del vault. Isomórfico: usa WebCrypto (`globalThis.crypto.subtle`),
|
|
6
|
-
* disponible tanto en el navegador (PWA) como en Node ≥ 18.
|
|
7
|
-
*
|
|
8
|
-
* NO reimplementa la identidad ni la firma del ecosistema: la AUTORIZACIÓN la da
|
|
9
|
-
* el vault (cert de dispositivo verificado con `@dotrino/identity/capabilities`
|
|
10
|
-
* → cadena hasta la maestra). Este módulo solo levanta un secreto de sesión
|
|
11
|
-
* efímero (ECDH P-256 → HKDF → AES-256-GCM) para que el relay del túnel
|
|
12
|
-
* (`r.dotrino.com`) vea únicamente texto cifrado. La identidad de las dos puntas
|
|
13
|
-
* ya la garantizan las firmas del vault que envuelven las claves efímeras.
|
|
14
|
-
*
|
|
15
|
-
* El mismo archivo se copia a `agent/` y a `web/src/` (fuente única en `shared/`).
|
|
16
|
-
*/
|
|
17
|
-
|
|
18
|
-
const subtle = () => globalThis.crypto.subtle
|
|
19
|
-
|
|
20
|
-
const b64 = {
|
|
21
|
-
enc (buf) {
|
|
22
|
-
const b = new Uint8Array(buf)
|
|
23
|
-
let s = ''
|
|
24
|
-
for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i])
|
|
25
|
-
return btoa(s)
|
|
26
|
-
},
|
|
27
|
-
dec (str) {
|
|
28
|
-
const bin = atob(str)
|
|
29
|
-
const out = new Uint8Array(bin.length)
|
|
30
|
-
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
|
31
|
-
return out
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** Genera un par ECDH P-256 efímero. Devuelve la pub en raw (base64) + privada. */
|
|
36
|
-
export async function makeEphemeral () {
|
|
37
|
-
const kp = await subtle().generateKey({ name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits'])
|
|
38
|
-
const raw = await subtle().exportKey('raw', kp.publicKey)
|
|
39
|
-
return { privateKey: kp.privateKey, pub: b64.enc(raw) }
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Deriva la clave AES-256-GCM de la sesión a partir de la privada propia y la
|
|
44
|
-
* pub efímera (base64 raw) del otro extremo. `salt` liga la clave a la sesión.
|
|
45
|
-
*/
|
|
46
|
-
export async function deriveKey (privateKey, otherPubB64, salt) {
|
|
47
|
-
const otherPub = await subtle().importKey(
|
|
48
|
-
'raw', b64.dec(otherPubB64), { name: 'ECDH', namedCurve: 'P-256' }, false, []
|
|
49
|
-
)
|
|
50
|
-
const bits = await subtle().deriveBits({ name: 'ECDH', public: otherPub }, privateKey, 256)
|
|
51
|
-
const hkdfKey = await subtle().importKey('raw', bits, 'HKDF', false, ['deriveKey'])
|
|
52
|
-
return subtle().deriveKey(
|
|
53
|
-
{ name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode(salt), info: new TextEncoder().encode('dotrino-terminal-e2e') },
|
|
54
|
-
hkdfKey,
|
|
55
|
-
{ name: 'AES-GCM', length: 256 },
|
|
56
|
-
false,
|
|
57
|
-
['encrypt', 'decrypt']
|
|
58
|
-
)
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/** Cifra un objeto JSON → sobre { iv, ct } (ambos base64). */
|
|
62
|
-
export async function seal (key, obj) {
|
|
63
|
-
const iv = globalThis.crypto.getRandomValues(new Uint8Array(12))
|
|
64
|
-
const pt = new TextEncoder().encode(JSON.stringify(obj))
|
|
65
|
-
const ct = await subtle().encrypt({ name: 'AES-GCM', iv }, key, pt)
|
|
66
|
-
return { iv: b64.enc(iv), ct: b64.enc(ct) }
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/** Descifra un sobre { iv, ct } → objeto JSON. Lanza si el tag GCM no valida. */
|
|
70
|
-
export async function open (key, env) {
|
|
71
|
-
const pt = await subtle().decrypt({ name: 'AES-GCM', iv: b64.dec(env.iv) }, key, b64.dec(env.ct))
|
|
72
|
-
return JSON.parse(new TextDecoder().decode(pt))
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export { b64 }
|
package/node-globals.js
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Instala los globals del navegador que los paquetes del ecosistema esperan
|
|
3
|
-
* cuando corren headless en Node: `WebSocket` (paquete `ws`) y un `localStorage`
|
|
4
|
-
* respaldado en archivo (lo usa `@dotrino/proxy-client` para su keypair de
|
|
5
|
-
* transporte estable). Mismo patrón que `dotrino-bots/src/core/node-globals.js`
|
|
6
|
-
* — NO se reimplementa nada, solo se inyecta el entorno.
|
|
7
|
-
*/
|
|
8
|
-
import fs from 'node:fs'
|
|
9
|
-
import path from 'node:path'
|
|
10
|
-
import WebSocket from 'ws'
|
|
11
|
-
|
|
12
|
-
/** localStorage síncrono respaldado por un archivo JSON (solo lo que usan los paquetes). */
|
|
13
|
-
export function fileLocalStorage (filePath) {
|
|
14
|
-
let data = {}
|
|
15
|
-
try { if (fs.existsSync(filePath)) data = JSON.parse(fs.readFileSync(filePath, 'utf8')) || {} } catch (_) {}
|
|
16
|
-
const flush = () => {
|
|
17
|
-
fs.mkdirSync(path.dirname(filePath), { recursive: true })
|
|
18
|
-
fs.writeFileSync(filePath, JSON.stringify(data), { mode: 0o600 })
|
|
19
|
-
}
|
|
20
|
-
return {
|
|
21
|
-
getItem: (k) => (k in data ? data[k] : null),
|
|
22
|
-
setItem: (k, v) => { data[k] = String(v); flush() },
|
|
23
|
-
removeItem: (k) => { delete data[k]; flush() },
|
|
24
|
-
clear: () => { data = {}; flush() },
|
|
25
|
-
key: (i) => Object.keys(data)[i] ?? null,
|
|
26
|
-
get length () { return Object.keys(data).length }
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
let _installed = false
|
|
31
|
-
export function installNodeGlobals (dir) {
|
|
32
|
-
if (_installed) return
|
|
33
|
-
if (typeof globalThis.WebSocket === 'undefined') globalThis.WebSocket = WebSocket
|
|
34
|
-
// Node ≥22 expone un `localStorage` no funcional sin flag → forzamos el shim.
|
|
35
|
-
globalThis.localStorage = fileLocalStorage(path.join(dir, 'transport.json'))
|
|
36
|
-
_installed = true
|
|
37
|
-
}
|
package/tsconfig.json
DELETED
|
@@ -1,39 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"target": "ES2022",
|
|
4
|
-
"module": "NodeNext",
|
|
5
|
-
"moduleResolution": "NodeNext",
|
|
6
|
-
"lib": [
|
|
7
|
-
"ES2022",
|
|
8
|
-
"DOM"
|
|
9
|
-
],
|
|
10
|
-
"allowJs": true,
|
|
11
|
-
"checkJs": true,
|
|
12
|
-
"strict": false,
|
|
13
|
-
"noImplicitAny": false,
|
|
14
|
-
"strictNullChecks": false,
|
|
15
|
-
"skipLibCheck": true,
|
|
16
|
-
"esModuleInterop": true,
|
|
17
|
-
"resolveJsonModule": true,
|
|
18
|
-
"baseUrl": ".",
|
|
19
|
-
"noEmit": true,
|
|
20
|
-
"types": [
|
|
21
|
-
"node"
|
|
22
|
-
]
|
|
23
|
-
},
|
|
24
|
-
"include": [
|
|
25
|
-
"src/**/*.js",
|
|
26
|
-
"src/**/*.mjs",
|
|
27
|
-
"src/**/*.d.ts",
|
|
28
|
-
"bin/**/*.js",
|
|
29
|
-
"server.js",
|
|
30
|
-
"index.js"
|
|
31
|
-
],
|
|
32
|
-
"exclude": [
|
|
33
|
-
"node_modules",
|
|
34
|
-
"dist",
|
|
35
|
-
"coverage",
|
|
36
|
-
"**/*.test.*",
|
|
37
|
-
"**/*.spec.*"
|
|
38
|
-
]
|
|
39
|
-
}
|