@dotrino/remote-agent 0.36.0 → 0.38.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 +24 -0
- package/package.json +9 -1
- package/src/access.js +193 -0
- package/src/agent.js +45 -15
- package/src/catch-up.js +21 -0
- package/src/membership.js +16 -1
- package/src/service.js +442 -0
- package/types/src/access.d.ts +82 -0
- package/types/src/agent.d.ts +5 -5
- package/types/src/catch-up.d.ts +13 -0
- package/types/src/membership.d.ts +12 -0
- package/types/src/service.d.ts +170 -0
package/README.md
CHANGED
|
@@ -42,6 +42,8 @@ Provee lo común — y **solo** eso:
|
|
|
42
42
|
| `@dotrino/remote-agent/discover` | navegador | `listAgentsByLabel`, `probeAgents` |
|
|
43
43
|
| `@dotrino/remote-agent/update` | Node | `startSelfUpdate`, `vaultHooks`: el agente se actualiza solo (CONVENCIONES §15) y se reinicia cuando está libre (0.36.0; necesita `@dotrino/update`) |
|
|
44
44
|
| `@dotrino/remote-agent/instances` | Node | `resolveInstance`, `listInstances`, `lockInstance`, `instancesRoot` |
|
|
45
|
+
| `@dotrino/remote-agent/access` | Node | La clave de la máquina (opcional): `setAccessCode`, `makeGate` (freno por agente, aviso por aparato), `makeLock` (el candado de cada sesión: `unlock` → `unlocked`). Venía de Terminal (0.38.0) |
|
|
46
|
+
| `@dotrino/remote-agent/service` | Node | `makeService`: el agente como servicio del usuario (systemd de usuario o inicio automático del escritorio en Linux, LaunchAgent en macOS, `HKCU\…\Run` + supervisor en Windows). Sin `sudo` (0.37.0) |
|
|
45
47
|
|
|
46
48
|
## Uso
|
|
47
49
|
|
|
@@ -150,6 +152,26 @@ Sin nombre: si no hay ninguno enlazado es `default`; si hay uno, ese; si hay var
|
|
|
150
152
|
para y dice cuáles hay (la misma regla que `dotrino-env`). La raíz común se cambia con
|
|
151
153
|
`DOTRINO_AGENT_HOME`.
|
|
152
154
|
|
|
155
|
+
### Como servicio del usuario (`/service`, 0.37.0)
|
|
156
|
+
|
|
157
|
+
```js
|
|
158
|
+
import { makeService } from '@dotrino/remote-agent/service'
|
|
159
|
+
const svc = makeService({
|
|
160
|
+
id: 'remote-desktop-agent', // dotrino-<id>-<perfil>.service / .desktop, com.dotrino.<id>.<perfil>
|
|
161
|
+
title: 'Dotrino Remote Desktop agent',
|
|
162
|
+
runPrefix: 'DotrinoRemoteDesktopAgent', // el valor de HKCU\…\Run
|
|
163
|
+
agentArgs: (name) => ['--name', name], // cómo se corre el agente sin TTY
|
|
164
|
+
linux: 'autostart' // o 'systemd' (por defecto)
|
|
165
|
+
})
|
|
166
|
+
svc.installService({ name, cli, dir }) // también uninstallService, serviceStatus, startService
|
|
167
|
+
// y en el CLI: `supervise --name <n>` → svc.superviseCommand({ name, dir, cli })
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
`linux: 'systemd'` arranca al encender (con *linger*), sin sesión gráfica: vale para un agente
|
|
171
|
+
que solo necesita una shell (Terminal). `linux: 'autostart'` arranca con la sesión gráfica, que
|
|
172
|
+
es lo que necesita un agente que mira el escritorio. Los dos casos con supervisor (Windows y
|
|
173
|
+
`autostart`) le ponen `DOTRINO_SUPERVISED=1` al agente, así que `/update` puede reiniciarlo.
|
|
174
|
+
|
|
153
175
|
### Un agente como CLIENTE de otro agente (Node)
|
|
154
176
|
|
|
155
177
|
Un agente Node también puede hablar con otro agente —un bot que guarda en el node de
|
|
@@ -213,6 +235,8 @@ extraerlo luego a este paquete.
|
|
|
213
235
|
|
|
214
236
|
## Seguridad
|
|
215
237
|
|
|
238
|
+
**Permiso por producto (0.38.0).** `needs: ['desktop']` (o `terminal`) no solo se declara a la bóveda: se exige a quien saluda. Sin él, `ra.error` con `reason: 'missing-cap'` y `caps` con lo que falta; si se lo quitan con la sesión abierta, se le cierra. Un `ra.data` solo cambia por dónde se contesta (y renueva la sesión) si su sobre abre con la llave de la sesión; un saludo con la firma mal no despierta a la bóveda; los avisos de bloqueo van con freno (auditoría del 2026-11-16).
|
|
239
|
+
|
|
216
240
|
- **Autorización = el ACTA, en las dos puntas** (0.24.0). El papel (`cert`) prueba quién
|
|
217
241
|
lo emitió —una selladora del acta— pero no caduca, así que el de un aparato quitado sigue
|
|
218
242
|
bien firmado. Lo que decide es `canGreet(acta, pub)` (`src/membership.js`): el acta
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dotrino/remote-agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.38.0",
|
|
4
4
|
"description": "Middleware compartido del ecosistema Dotrino para apps de agente remoto cifrado punto a punto (handshake E2E, emparejamiento SAS con vault, revocación, descubrimiento). Lo consumen dotrino-terminal (PTY) y dotrino-ia (chat con IA).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.js",
|
|
@@ -41,6 +41,14 @@
|
|
|
41
41
|
"./update": {
|
|
42
42
|
"types": "./types/src/update.d.ts",
|
|
43
43
|
"import": "./src/update.js"
|
|
44
|
+
},
|
|
45
|
+
"./service": {
|
|
46
|
+
"types": "./types/src/service.d.ts",
|
|
47
|
+
"import": "./src/service.js"
|
|
48
|
+
},
|
|
49
|
+
"./access": {
|
|
50
|
+
"types": "./types/src/access.d.ts",
|
|
51
|
+
"import": "./src/access.js"
|
|
44
52
|
}
|
|
45
53
|
},
|
|
46
54
|
"files": [
|
package/src/access.js
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* access.js — la CLAVE de esta máquina (un PIN o una contraseña), opcional.
|
|
3
|
+
*
|
|
4
|
+
* Venía de `dotrino-terminal/agent/access.js` y ahora es común (dueño, 2026-11-16: el escritorio
|
|
5
|
+
* remoto también la lleva). Sin clave puesta no cambia nada: entra cualquier aparato de la cuenta
|
|
6
|
+
* con los permisos del producto. Con clave, además hay que escribirla en cada conexión remota.
|
|
7
|
+
* Lo que corre en ESTA máquina (las ventanas de Terminal por su socket local) no la pide: es del
|
|
8
|
+
* mismo usuario que ya puede leer este archivo.
|
|
9
|
+
*
|
|
10
|
+
* Por el cable: la sesión que todavía no la escribió recibe `{ type: 'fail', code: 'locked' }`
|
|
11
|
+
* a cualquier cosa que pida; manda `{ type: 'unlock', code }` y recibe `{ type: 'unlocked' }`, o
|
|
12
|
+
* `fail` con `bad-code` / `wait` (`retryMs`). Ver `makeLock`.
|
|
13
|
+
*
|
|
14
|
+
* En el disco queda la sal y el resumen (scrypt), nunca la clave. La clave viaja dentro de la
|
|
15
|
+
* sesión cifrada entre el aparato y el agente, así que el proxio no la ve.
|
|
16
|
+
*
|
|
17
|
+
* Los fallos se frenan POR AGENTE y no por sesión: quien prueba claves puede abrir otra
|
|
18
|
+
* conexión, y eso no le da intentos nuevos. A los TRES seguidos (dueño, 2026-10-07) empieza
|
|
19
|
+
* la espera, que se dobla con cada fallo más: es un bloqueo LOCAL de este servicio, nada más.
|
|
20
|
+
*
|
|
21
|
+
* Y a los tres fallos seguidos de UN MISMO aparato se avisa (`onIncident`): la bóveda se lo
|
|
22
|
+
* pone en la mesa a quien aprueba, que bloquea o ignora desde el teléfono. Avisar no decide
|
|
23
|
+
* nada aquí; el freno de arriba sigue igual.
|
|
24
|
+
*/
|
|
25
|
+
import crypto from 'node:crypto'
|
|
26
|
+
import fs from 'node:fs'
|
|
27
|
+
import path from 'node:path'
|
|
28
|
+
|
|
29
|
+
export const ACCESS_FILE = 'access.json'
|
|
30
|
+
export const MIN_LENGTH = 4
|
|
31
|
+
/** Fallos seguidos que se dejan pasar sin esperar: al tercero empieza la espera. */
|
|
32
|
+
export const FREE_TRIES = 3
|
|
33
|
+
/** Fallos seguidos de un mismo aparato que disparan el aviso a la bóveda. */
|
|
34
|
+
export const INCIDENT_AFTER = 3
|
|
35
|
+
const BASE_WAIT_MS = 30_000
|
|
36
|
+
const MAX_WAIT_MS = 60 * 60_000
|
|
37
|
+
const SCRYPT = { N: 1 << 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }
|
|
38
|
+
|
|
39
|
+
/** @typedef {Error & { code?: string, retryMs?: number }} Thrown */
|
|
40
|
+
|
|
41
|
+
/** @type {(code: string, message: string, extra?: object) => Error & { code: string }} */
|
|
42
|
+
const fail = (code, message, extra = {}) => Object.assign(new Error(message), { code, ...extra })
|
|
43
|
+
/** @param {string} dir */
|
|
44
|
+
const file = (dir) => path.join(dir, ACCESS_FILE)
|
|
45
|
+
/** @type {(secret: unknown, salt: Buffer, params: import('node:crypto').ScryptOptions) => Buffer} */
|
|
46
|
+
const digest = (secret, salt, params) => crypto.scryptSync(String(secret).normalize('NFKC'), salt, 32, params)
|
|
47
|
+
|
|
48
|
+
/** Si esta máquina tiene clave. Un archivo que existe y no se puede leer NO es «sin clave»: se lanza. */
|
|
49
|
+
/** @param {string} dir */
|
|
50
|
+
export function hasAccessCode (dir) {
|
|
51
|
+
return readRecord(dir) !== null
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* @param {string} dir
|
|
56
|
+
* @returns {{ v: 1, salt: string, hash: string, params: import('node:crypto').ScryptOptions } | null}
|
|
57
|
+
*/
|
|
58
|
+
function readRecord (dir) {
|
|
59
|
+
let raw
|
|
60
|
+
try { raw = fs.readFileSync(file(dir), 'utf8') } catch (e) {
|
|
61
|
+
if (/** @type {Thrown} */ (e).code === 'ENOENT') return null
|
|
62
|
+
throw fail('access-unreadable', `cannot read ${ACCESS_FILE}: ${/** @type {Thrown} */ (e).message}`)
|
|
63
|
+
}
|
|
64
|
+
let r
|
|
65
|
+
try { r = JSON.parse(raw) } catch (_) { throw fail('access-unreadable', `${ACCESS_FILE} is not valid JSON`) }
|
|
66
|
+
if (r?.v !== 1 || typeof r.salt !== 'string' || typeof r.hash !== 'string' || !r.params) {
|
|
67
|
+
throw fail('access-unreadable', `${ACCESS_FILE} has an unknown shape`)
|
|
68
|
+
}
|
|
69
|
+
return r
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Pone o cambia la clave.
|
|
74
|
+
* @param {string} dir
|
|
75
|
+
* @param {unknown} secret
|
|
76
|
+
*/
|
|
77
|
+
export function setAccessCode (dir, secret) {
|
|
78
|
+
if (typeof secret !== 'string' || secret.length < MIN_LENGTH) throw fail('too-short', `the code needs at least ${MIN_LENGTH} characters`)
|
|
79
|
+
const salt = crypto.randomBytes(16)
|
|
80
|
+
const record = { v: 1, salt: salt.toString('base64'), hash: digest(secret, salt, SCRYPT).toString('base64'), params: SCRYPT }
|
|
81
|
+
const tmp = file(dir) + '.tmp'
|
|
82
|
+
fs.writeFileSync(tmp, JSON.stringify(record), { mode: 0o600 })
|
|
83
|
+
fs.renameSync(tmp, file(dir))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Quita la clave.
|
|
88
|
+
* @param {string} dir
|
|
89
|
+
*/
|
|
90
|
+
export function clearAccessCode (dir) {
|
|
91
|
+
fs.rmSync(file(dir), { force: true })
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Si `secret` es la clave de esta máquina. Sin frenos: para la orden local que la cambia.
|
|
96
|
+
* @param {string} dir
|
|
97
|
+
* @param {unknown} secret
|
|
98
|
+
*/
|
|
99
|
+
export function checkAccessCode (dir, secret) {
|
|
100
|
+
const r = readRecord(dir)
|
|
101
|
+
if (!r) throw fail('no-access-code', 'this machine has no code')
|
|
102
|
+
const want = Buffer.from(r.hash, 'base64')
|
|
103
|
+
const got = digest(secret ?? '', Buffer.from(r.salt, 'base64'), r.params)
|
|
104
|
+
return want.length === got.length && crypto.timingSafeEqual(want, got)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* La puerta de un agente: comprueba la clave y frena los fallos seguidos. Una por agente,
|
|
109
|
+
* compartida por todas sus sesiones.
|
|
110
|
+
* @param {string} dir
|
|
111
|
+
* @param {{ now?: () => number, onIncident?: ((i: { device: string, tries: number }) => void) | null }} [opts]
|
|
112
|
+
* `onIncident`: un mismo aparato (`device`, su pubkey) falló `INCIDENT_AFTER` veces seguidas.
|
|
113
|
+
* Se llama UNA vez por racha; la racha se corta al acertar.
|
|
114
|
+
*/
|
|
115
|
+
export function makeGate (dir, { now = Date.now, onIncident = null } = {}) {
|
|
116
|
+
let fails = 0
|
|
117
|
+
let until = 0
|
|
118
|
+
/** Fallos seguidos por aparato: el aviso es sobre QUIÉN, y el freno sobre el agente. */
|
|
119
|
+
const byDevice = new Map()
|
|
120
|
+
return {
|
|
121
|
+
/** Si hay que escribir la clave para entrar. Lanza `access-unreadable` si no se puede saber. */
|
|
122
|
+
required: () => hasAccessCode(dir),
|
|
123
|
+
/**
|
|
124
|
+
* Lanza `wait` (con `retryMs`) o `bad-code`; si no lanza, la clave era la buena.
|
|
125
|
+
* `device` es quién la escribió (pubkey), para contar sus fallos y avisar.
|
|
126
|
+
*/
|
|
127
|
+
/**
|
|
128
|
+
* @param {unknown} secret
|
|
129
|
+
* @param {string | null} [device]
|
|
130
|
+
*/
|
|
131
|
+
check (secret, device = null) {
|
|
132
|
+
const left = until - now()
|
|
133
|
+
if (left > 0) throw fail('wait', 'too many wrong codes', { retryMs: left })
|
|
134
|
+
if (checkAccessCode(dir, secret)) { fails = 0; until = 0; if (device) byDevice.delete(device); return }
|
|
135
|
+
fails++
|
|
136
|
+
if (fails >= FREE_TRIES) until = now() + Math.min(BASE_WAIT_MS * 2 ** (fails - FREE_TRIES), MAX_WAIT_MS)
|
|
137
|
+
if (device) {
|
|
138
|
+
const n = (byDevice.get(device) || 0) + 1
|
|
139
|
+
byDevice.set(device, n)
|
|
140
|
+
if (n === INCIDENT_AFTER && onIncident) { try { onIncident({ device, tries: n }) } catch (_) {} }
|
|
141
|
+
}
|
|
142
|
+
throw fail('bad-code', 'wrong code', until ? { retryMs: until - now() } : {})
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* El candado de UNA sesión: hasta que escribe la clave (si la máquina tiene), no pasa nada más.
|
|
149
|
+
* Una vez escrita vale para esa conexión. Sin `gate` (lo local), siempre pasa.
|
|
150
|
+
*
|
|
151
|
+
* session.on('message', (msg) => {
|
|
152
|
+
* if (lock.handle(msg)) return // era el `unlock`: ya contestó
|
|
153
|
+
* if (!lock.mayPass()) return // ya contestó `locked` (o que no se puede saber)
|
|
154
|
+
* …
|
|
155
|
+
* })
|
|
156
|
+
*
|
|
157
|
+
* No saber si hay clave (el archivo no se puede leer) es no pasar, y se dice.
|
|
158
|
+
* @param {{ gate: ReturnType<typeof makeGate> | null, device?: string | null,
|
|
159
|
+
* send: (msg: object) => unknown }} o
|
|
160
|
+
*/
|
|
161
|
+
export function makeLock ({ gate, device = null, send }) {
|
|
162
|
+
let unlocked = false
|
|
163
|
+
/** @type {(code: string, message: string, extra?: object) => unknown} */
|
|
164
|
+
const failMsg = (code, message, extra = {}) => send({ type: 'fail', code, message, ...extra })
|
|
165
|
+
/** @param {unknown} e */
|
|
166
|
+
const failWith = (e) => {
|
|
167
|
+
const t = /** @type {Thrown} */ (e)
|
|
168
|
+
failMsg(t.code || 'access-unreadable', t.message, t.retryMs ? { retryMs: t.retryMs } : {})
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
get unlocked () { return unlocked || !gate },
|
|
172
|
+
/** True si esta sesión puede seguir; si no, ya contestó por qué. */
|
|
173
|
+
mayPass () {
|
|
174
|
+
if (!gate || unlocked) return true
|
|
175
|
+
try {
|
|
176
|
+
if (!gate.required()) return true
|
|
177
|
+
} catch (e) { failWith(e); return false }
|
|
178
|
+
failMsg('locked', 'this machine asks for its code')
|
|
179
|
+
return false
|
|
180
|
+
},
|
|
181
|
+
/** Si `msg` es el `unlock`, lo atiende y devuelve true. @param {any} msg */
|
|
182
|
+
handle (msg) {
|
|
183
|
+
if (!msg || msg.type !== 'unlock') return false
|
|
184
|
+
if (!gate) { send({ type: 'unlocked' }); return true }
|
|
185
|
+
try {
|
|
186
|
+
if (gate.required()) gate.check(msg.code, device)
|
|
187
|
+
unlocked = true
|
|
188
|
+
send({ type: 'unlocked' })
|
|
189
|
+
} catch (e) { failWith(e) }
|
|
190
|
+
return true
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
package/src/agent.js
CHANGED
|
@@ -25,10 +25,13 @@ import { verifyChain, signWithDevice, verifyDeviceSig, pubkeyId, keyLabel } from
|
|
|
25
25
|
import { sealersOf, memberCan, checkVaultReply } from '@dotrino/identity/acta'
|
|
26
26
|
import { sendToVault, acceptReply } from '@dotrino/identity/vault-seal'
|
|
27
27
|
import { adoptRecord } from './record.js'
|
|
28
|
-
import { canGreet } from './membership.js'
|
|
28
|
+
import { canGreet, missingCaps } from './membership.js'
|
|
29
29
|
import { installNodeGlobals } from '../node-globals.js'
|
|
30
30
|
import { makeEphemeral, deriveKey, seal, open } from '../e2e.js'
|
|
31
|
-
import { makeCatchUp } from './catch-up.js'
|
|
31
|
+
import { makeCatchUp, makeThrottle } from './catch-up.js'
|
|
32
|
+
|
|
33
|
+
/** Fallos de `verifyChain` que un acta más nueva no arregla: el saludo no prueba ni quién lo firmó. */
|
|
34
|
+
const PRE_AUTH = new Set(['shape', 'no-device-pubkey', 'bad-action-signature', 'cert-device-mismatch'])
|
|
32
35
|
import { HS, ACK, DATA, PING, PONG, ERROR, VMSG, SIGN_SCOPE, SESSION_TTL_MS, SESSION_GONE_MS, REVOKE_REFRESH_MS, DEFAULT_PROXY } from '../protocol.js'
|
|
33
36
|
import { loadLink, saveLink, dataDir, renewalReason, storeRenewedCert } from './link.js'
|
|
34
37
|
import { declare } from '@dotrino/compat'
|
|
@@ -125,10 +128,13 @@ export class AgentSession {
|
|
|
125
128
|
|
|
126
129
|
/** Lo que llega se entrega en el orden en que llegó, tarde lo que tarde en descifrarse cada uno. */
|
|
127
130
|
/** @param {{ iv: string, ct: string }} env */
|
|
128
|
-
|
|
131
|
+
/** @param {any} env @param {() => void} [onOpen] solo si el sobre abre, antes de repartirlo */
|
|
132
|
+
_ingest (env, onOpen) {
|
|
129
133
|
const opened = open(this.key, env).then((msg) => ({ msg }), () => null)
|
|
130
134
|
this._in = (this._in || Promise.resolve()).then(() => opened).then((r) => {
|
|
131
|
-
if (r)
|
|
135
|
+
if (!r) return
|
|
136
|
+
if (onOpen) onOpen()
|
|
137
|
+
for (const h of this._h.message) { try { h(r.msg) } catch (_) {} }
|
|
132
138
|
})
|
|
133
139
|
return this._in
|
|
134
140
|
}
|
|
@@ -161,7 +167,9 @@ export class AgentSession {
|
|
|
161
167
|
* @param {string} [opts.product] qué producto es (`accounts`, `terminal-agent`…), para el anuncio a la bóveda.
|
|
162
168
|
* @param {string} [opts.version] su versión. Sin `product`/`version` se anuncia como `remote-agent`.
|
|
163
169
|
* @param {string[]} [opts.needs] los permisos del acta que necesita, además de `sign`, que lo
|
|
164
|
-
* añade este pilar: sin él no se abre ninguna sesión (`@dotrino/compat` ≥ 0.5.0).
|
|
170
|
+
* añade este pilar: sin él no se abre ninguna sesión (`@dotrino/compat` ≥ 0.5.0). Desde 0.38.0
|
|
171
|
+
* también se EXIGEN a quien saluda: un aparato sin ellos no abre sesión (`missing-cap`), y si
|
|
172
|
+
* se los quitan con la sesión abierta, se le cierra.
|
|
165
173
|
*
|
|
166
174
|
* Devuelve además el **`client`** (el `WebSocketProxyClient` ya conectado e
|
|
167
175
|
* identificado bajo la pubkey de esta máquina). Se expone a propósito: un agente
|
|
@@ -181,6 +189,8 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
181
189
|
product: opts.product || 'remote-agent', version: opts.version || PKG_VERSION,
|
|
182
190
|
protocol: VAULT_PROTOCOL, speaks: VAULT_SPEAKS, needs: ['sign', ...(opts.needs || [])]
|
|
183
191
|
})
|
|
192
|
+
/** Lo que se exige a quien saluda, además de `sign` (`terminal`, `desktop`…). */
|
|
193
|
+
const NEEDS = Object.freeze([...(opts.needs || [])])
|
|
184
194
|
const master = /** @type {string} */ (link.iss) // comprobado arriba
|
|
185
195
|
const myPub = link.device.publickey
|
|
186
196
|
const myId = await keyLabel(myPub)
|
|
@@ -439,7 +449,8 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
439
449
|
const acta = trustedActa()
|
|
440
450
|
for (const [sid, s] of sessions) {
|
|
441
451
|
const reason = !canGreet(acta, s.device) ? 'not-in-record'
|
|
442
|
-
: (s.
|
|
452
|
+
: missingCaps(acta, s.device, NEEDS).length ? 'missing-cap'
|
|
453
|
+
: (s._certNonce && revokedSet.has(s._certNonce)) ? 'revoked' : null
|
|
443
454
|
if (!reason) continue
|
|
444
455
|
send(s.from, { type: ERROR, code: 'unauthorized', reason, sid, error: 'unauthorized: ' + reason })
|
|
445
456
|
s.close(); sessions.delete(sid)
|
|
@@ -460,11 +471,16 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
460
471
|
}
|
|
461
472
|
|
|
462
473
|
const vaultTick = async () => { await refreshRevocations(); await renewCertIfNeeded() }
|
|
474
|
+
// En cada tic se mira también la caché del proxio: si el agente se perdió el aviso de que
|
|
475
|
+
// quitaron un aparato y la bóveda está apagada, esa sesión no espera a que la bóveda vuelva.
|
|
476
|
+
const tick = async () => { try { await actaFromProxy() } catch (_) {} await vaultTick() }
|
|
463
477
|
/** Trae el acta ahora (con freno) y dice si AVANZÓ: solo entonces merece juzgar otra vez. */
|
|
464
478
|
// Ponerse al día mira primero la caché del proxio y, si no trae nada que encadene, la bóveda.
|
|
465
479
|
const catchUp = makeCatchUp({ refresh: async () => { if (!await actaFromProxy()) await vaultTick() }, seq: () => link.actaSeq ?? null })
|
|
466
|
-
|
|
467
|
-
const revTimer = setInterval(
|
|
480
|
+
tick()
|
|
481
|
+
const revTimer = setInterval(tick, REVOKE_REFRESH_MS); revTimer.unref?.()
|
|
482
|
+
// Un aviso de bloqueo lo puede mandar cualquiera: trae la lista firmada, pero con freno.
|
|
483
|
+
const refreshBlocked = makeThrottle(() => refreshRevocations())
|
|
468
484
|
|
|
469
485
|
const ttlMs = opts.sessionTtlMs ?? SESSION_TTL_MS
|
|
470
486
|
// UNA SESIÓN QUE VENCE SE LE DICE AL CLIENTE en ese momento, con el mismo `unknown-session`
|
|
@@ -506,8 +522,11 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
506
522
|
return { chk: { ...chk, device: /** @type {string} */ (chk.device) } } // ok: verifyChain dice qué aparato firmó
|
|
507
523
|
}
|
|
508
524
|
let verdict = await judge()
|
|
509
|
-
const known = (/** @type {Awaited<ReturnType<typeof judge>>} */ v) => !!v.chk && canGreet(trustedActa(), v.chk.device)
|
|
510
|
-
|
|
525
|
+
const known = (/** @type {Awaited<ReturnType<typeof judge>>} */ v) => !!v.chk && canGreet(trustedActa(), v.chk.device) && !missingCaps(trustedActa(), v.chk.device, NEEDS).length
|
|
526
|
+
// Solo se pregunta a la bóveda si un acta más nueva podría cambiar el veredicto: un saludo
|
|
527
|
+
// cuya firma no vale (o mal formado) no la despierta, por mucho que lleguen.
|
|
528
|
+
const couldChange = (/** @type {Awaited<ReturnType<typeof judge>>} */ v) => v.chk ? !known(v) : !PRE_AUTH.has(/** @type {string} */ (v.reason))
|
|
529
|
+
if (couldChange(verdict) && await catchUp()) verdict = await judge()
|
|
511
530
|
if (verdict.error) return send(from, { type: ERROR, code: verdict.code, reason: verdict.reason, error: verdict.error })
|
|
512
531
|
const chk = /** @type {NonNullable<typeof verdict.chk>} */ (verdict.chk) // sin error hay chk
|
|
513
532
|
// CERT ∩ ACTA. `verifyChain` comprueba QUIÉN EMITIÓ el papel; que el APARATO siga siendo
|
|
@@ -527,6 +546,13 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
527
546
|
if (!canGreet(trustedActa(), chk.device)) {
|
|
528
547
|
return send(from, { type: ERROR, code: 'unauthorized', reason: 'not-in-record', error: 'unauthorized: not-in-record' })
|
|
529
548
|
}
|
|
549
|
+
// EL PERMISO DEL PRODUCTO (`terminal`, `desktop`…). Se dice cuál falta, para que la app
|
|
550
|
+
// pueda enseñar la orden que lo concede (`dotrino-vault caps <ID> +desktop`).
|
|
551
|
+
const lacking = missingCaps(trustedActa(), chk.device, NEEDS)
|
|
552
|
+
if (lacking.length) {
|
|
553
|
+
audit('session-refused', { reason: 'missing-cap', caps: lacking, device: (await pubkeyId(chk.device)).slice(0, 8).toUpperCase() })
|
|
554
|
+
return send(from, { type: ERROR, code: 'unauthorized', reason: 'missing-cap', caps: lacking, error: 'unauthorized: missing-cap ' + lacking.join(',') })
|
|
555
|
+
}
|
|
530
556
|
// BLOQUEADO por un aprobador: está en el acta y su papel vale, y aun así no entra. Se le
|
|
531
557
|
// dice con su código, que no es lo mismo que un papel viejo ni que una revocación.
|
|
532
558
|
if (blockedSet.has(chk.device)) {
|
|
@@ -568,10 +594,14 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
568
594
|
// se reinició, o venció) y vuelve a saludar solo, en vez de quedarse con un error. Se
|
|
569
595
|
// comprueba por el código, no por la frase.
|
|
570
596
|
if (!s) return send(from, { type: ERROR, code: 'unknown-session', sid: p.sid, error: 'unknown or expired session' })
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
s._ingest(p.env
|
|
597
|
+
// Quién es, por dónde contestarle y que sigue vivo cambian SOLO con un sobre que abre la
|
|
598
|
+
// llave de la sesión: el `sid` viaja a la vista, y con él cualquiera desviaba la salida a su
|
|
599
|
+
// token, mantenía viva la sesión o se colaba en `acceptDirectFrom`.
|
|
600
|
+
s._ingest(p.env, () => {
|
|
601
|
+
s._exp = Date.now() + ttlMs
|
|
602
|
+
s.from = from
|
|
603
|
+
if (s._gone) { clearTimeout(s._gone); s._gone = null }
|
|
604
|
+
}).catch(() => send(from, { type: ERROR, error: 'invalid envelope' }))
|
|
575
605
|
}
|
|
576
606
|
|
|
577
607
|
// LA CONEXIÓN DEL CLIENTE SE FUE: su sesión no se queda 30 minutos. El proxio avisa de que ese
|
|
@@ -635,7 +665,7 @@ export async function startRemoteAgent (opts = {}) {
|
|
|
635
665
|
/** @param {any} payload */
|
|
636
666
|
async function onAdminEvent (payload) {
|
|
637
667
|
const ev = payload.body?.ev
|
|
638
|
-
if (ev === 'blocked' || ev === 'unblocked') return
|
|
668
|
+
if (ev === 'blocked' || ev === 'unblocked') return refreshBlocked()
|
|
639
669
|
if (payload.acta && await recordActa(payload.acta)) return
|
|
640
670
|
if (typeof payload.acta?.seq === 'number' && payload.acta.seq > (link.actaSeq ?? -1)) await catchUp()
|
|
641
671
|
}
|
package/src/catch-up.js
CHANGED
|
@@ -32,3 +32,24 @@ export function makeCatchUp ({ refresh, seq, minGapMs = CATCH_UP_GAP_MS, now = D
|
|
|
32
32
|
return running
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* UN AVISO QUE CUALQUIERA PUEDE MANDAR no dispara el trabajo cada vez: como mucho una vez cada
|
|
38
|
+
* `minGapMs`, y lo que llegue mientras tanto se junta en UNA llamada al final del hueco (así un
|
|
39
|
+
* aviso de verdad entre basura no se pierde: llega tarde, como mucho `minGapMs`).
|
|
40
|
+
* @param {() => Promise<unknown>} fn
|
|
41
|
+
* @param {{ minGapMs?: number, now?: () => number, setTimer?: (f: () => void, ms: number) => unknown }} [o]
|
|
42
|
+
* @returns {() => void}
|
|
43
|
+
*/
|
|
44
|
+
export function makeThrottle (fn, { minGapMs = CATCH_UP_GAP_MS, now = Date.now, setTimer = (f, ms) => { const t = setTimeout(f, ms); t.unref?.(); return t } } = {}) {
|
|
45
|
+
let last = -Infinity
|
|
46
|
+
let pending = false
|
|
47
|
+
const run = () => { last = now(); Promise.resolve().then(fn).catch(() => {}) }
|
|
48
|
+
return () => {
|
|
49
|
+
if (pending) return
|
|
50
|
+
const wait = last + minGapMs - now()
|
|
51
|
+
if (wait <= 0) return run()
|
|
52
|
+
pending = true
|
|
53
|
+
setTimer(() => { pending = false; run() }, wait)
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/membership.js
CHANGED
|
@@ -25,4 +25,19 @@ export function canGreet (acta, pub) {
|
|
|
25
25
|
return (acta.members || []).some((m) => samePubkey(m?.pub, pub)) && memberCan(acta, pub, 'sign')
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
/**
|
|
29
|
+
* Los permisos de PRODUCTO que le faltan a ese aparato (`terminal`, `desktop`…): los que el
|
|
30
|
+
* agente declara en `needs`, además de `sign` (dueño, 2026-11-16, tras la auditoría: con solo
|
|
31
|
+
* `sign`, cualquier aparato del acta —un bot, un navegador prestado— abría una consola o el
|
|
32
|
+
* escritorio en todas las máquinas). Sin acta faltan todos: no hay con qué decir que sí.
|
|
33
|
+
* @param {DotrinoActa | null | undefined} acta
|
|
34
|
+
* @param {unknown} pub
|
|
35
|
+
* @param {readonly string[]} needs
|
|
36
|
+
* @returns {string[]}
|
|
37
|
+
*/
|
|
38
|
+
export function missingCaps (acta, pub, needs) {
|
|
39
|
+
if (!acta || typeof pub !== 'string' || !pub) return [...needs]
|
|
40
|
+
return needs.filter((c) => !memberCan(acta, pub, c))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export default { canGreet, missingCaps }
|
package/src/service.js
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* service.js — un agente como SERVICIO del usuario: arranca solo con la máquina o con la sesión.
|
|
3
|
+
*
|
|
4
|
+
* Venía de `dotrino-terminal/agent/service.js` y ahora es común (CLAUDE.md: reusar es la norma):
|
|
5
|
+
* lo usan el agente de Terminal y el del escritorio remoto. Cada uno lo configura con
|
|
6
|
+
* `makeService({ id, title, runPrefix, agentArgs, linux })` y recibe las órdenes de siempre.
|
|
7
|
+
*
|
|
8
|
+
* · Linux, `linux: 'systemd'` — una unidad de systemd DEL USUARIO (`~/.config/systemd/user`),
|
|
9
|
+
* sin `sudo`. Con «linger» arranca al encender, antes de que nadie inicie sesión.
|
|
10
|
+
* · Linux, `linux: 'autostart'` — el inicio automático del escritorio
|
|
11
|
+
* (`~/.config/autostart/*.desktop`, XDG) lanza un SUPERVISOR que levanta el agente cada vez
|
|
12
|
+
* que sale. Para un agente que necesita la SESIÓN GRÁFICA (el escritorio remoto: `DISPLAY`,
|
|
13
|
+
* el bus de sesión, la accesibilidad): una unidad que arranca al encender no tiene nada de
|
|
14
|
+
* eso, y `graphical-session.target` no lo activan todos los escritorios (XFCE no siempre).
|
|
15
|
+
* · macOS — un LaunchAgent (`~/Library/LaunchAgents`): arranca al iniciar sesión.
|
|
16
|
+
* · Windows — una entrada en `HKCU\…\Run` que lanza el mismo supervisor sin ventana. No es el
|
|
17
|
+
* Programador de tareas ni un servicio de Windows: los dos piden derechos de administrador.
|
|
18
|
+
*
|
|
19
|
+
* Es de usuario a propósito (CONVENCIONES §15): así el agente se sigue actualizando solo, y con
|
|
20
|
+
* alguien que lo levante (`DOTRINO_SUPERVISED`) ya puede reiniciarse para estrenar la versión.
|
|
21
|
+
*
|
|
22
|
+
* Una unidad por PERFIL: cada perfil es un agente con su enlace.
|
|
23
|
+
*/
|
|
24
|
+
import fs from 'node:fs'
|
|
25
|
+
import os from 'node:os'
|
|
26
|
+
import path from 'node:path'
|
|
27
|
+
import { execFileSync, spawn as childSpawn } from 'node:child_process'
|
|
28
|
+
|
|
29
|
+
/** @typedef {Error & { code?: string, stderr?: string | Buffer }} Thrown */
|
|
30
|
+
|
|
31
|
+
/** @type {(code: string, message: string) => Error & { code: string }} */
|
|
32
|
+
const fail = (code, message) => Object.assign(new Error(message), { code })
|
|
33
|
+
|
|
34
|
+
/** Correr una orden del sistema (`execFileSync`, o su doble en las pruebas). */
|
|
35
|
+
/** @typedef {(cmd: string, args: string[], opts?: import('node:child_process').ExecFileSyncOptions) => unknown} RunFn */
|
|
36
|
+
/** Lanzar un proceso (`spawn`, o su doble en las pruebas). */
|
|
37
|
+
/** @typedef {typeof childSpawn} SpawnFn */
|
|
38
|
+
/** Lo que comparten las órdenes de servicio: el perfil, y Node y el CLI con que se lanza. */
|
|
39
|
+
/** @typedef {{ name: string, node: string, cli: string }} Launch */
|
|
40
|
+
/** @typedef {'systemd' | 'autostart' | 'launchd' | 'run-key'} ServiceKind */
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Qué agente es.
|
|
44
|
+
* @typedef {object} Product
|
|
45
|
+
* @property {string} id `terminal-agent` → `dotrino-terminal-agent-<perfil>.service`, `com.dotrino.terminal-agent.<perfil>`
|
|
46
|
+
* @property {string} title para la descripción de la unidad: `Dotrino Terminal agent`
|
|
47
|
+
* @property {string} runPrefix el valor de `HKCU\…\Run`: `DotrinoTerminalAgent` → `DotrinoTerminalAgent-<perfil>`
|
|
48
|
+
* @property {(name: string) => string[]} agentArgs con qué argumentos se corre el agente sin TTY
|
|
49
|
+
* @property {'systemd' | 'autostart'} [linux] cómo se pone en Linux (por defecto, systemd)
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
/** Windows: la clave de lo que arranca al iniciar sesión. */
|
|
53
|
+
export const RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
|
|
54
|
+
/** Cuánto espera el supervisor antes de volver a levantar el agente (como `RestartSec`). */
|
|
55
|
+
export const RESTART_MS = 3000
|
|
56
|
+
/** @param {string} dir */
|
|
57
|
+
export const supervisorPidFile = (dir) => path.join(dir, 'supervisor.pid')
|
|
58
|
+
|
|
59
|
+
/** systemd parte `ExecStart` por espacios: lo que los lleve va entre comillas. */
|
|
60
|
+
/** @param {string} s */
|
|
61
|
+
const unitArg = (s) => (/[\s"'\\$%]/.test(s) ? `"${s.replace(/[\\"]/g, '\\$&').replace(/%/g, '%%').replace(/\$/g, '$$$$')}"` : s)
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Un argumento de `Exec=` de un `.desktop` (especificación XDG): entre comillas dobles si lleva
|
|
65
|
+
* algo reservado, con `"`, `` ` ``, `$` y `\` escapados, y el `%` doblado (son los códigos de campo).
|
|
66
|
+
* La barra va cuádruple: primero se aplica el escape de las cadenas y después el de las comillas.
|
|
67
|
+
* @param {string} s
|
|
68
|
+
*/
|
|
69
|
+
export const desktopArg = (s) => {
|
|
70
|
+
const v = s.replace(/%/g, '%%')
|
|
71
|
+
if (!/[\s"'\\$`<>~|&;*?#()]/.test(v)) return v
|
|
72
|
+
return `"${v.replace(/\\/g, '\\\\\\\\').replace(/["`$]/g, '\\$&')}"`
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** @param {unknown} s */
|
|
76
|
+
const xml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* @param {RunFn} run
|
|
80
|
+
* @param {string} cmd
|
|
81
|
+
* @param {string[]} args
|
|
82
|
+
* @returns {{ ok: true } | { ok: false, reason: string | undefined }}
|
|
83
|
+
*/
|
|
84
|
+
function quiet (run, cmd, args) {
|
|
85
|
+
try { run(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' }); return { ok: true } } catch (e) {
|
|
86
|
+
return { ok: false, reason: String(/** @type {Thrown} */ (e).stderr || /** @type {Thrown} */ (e).message).trim().split('\n').pop() }
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* @param {RunFn} run
|
|
92
|
+
* @param {string} cmd
|
|
93
|
+
* @param {string[]} args
|
|
94
|
+
*/
|
|
95
|
+
function must (run, cmd, args) {
|
|
96
|
+
const r = quiet(run, cmd, args)
|
|
97
|
+
if (!r.ok) throw fail('service-command-failed', `${cmd} ${args.join(' ')}: ${r.reason}`)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const LINGER_DIR = '/var/lib/systemd/linger'
|
|
101
|
+
/** ¿Ya arrancan los servicios de ese usuario al encender? systemd lo apunta con un archivo. */
|
|
102
|
+
/** @type {(user: string, root?: string) => boolean} */
|
|
103
|
+
const lingers = (user, root = LINGER_DIR) => fs.existsSync(path.join(root, user))
|
|
104
|
+
|
|
105
|
+
/** @type {(file: string) => number} */
|
|
106
|
+
const readPid = (file) => { try { return Number(fs.readFileSync(file, 'utf8')) || 0 } catch (e) { if (/** @type {Thrown} */ (e).code === 'ENOENT') return 0; throw e } }
|
|
107
|
+
/** @type {(pid: number) => boolean} */
|
|
108
|
+
const alive = (pid) => { try { process.kill(pid, 0); return true } catch (e) { return /** @type {Thrown} */ (e).code === 'EPERM' } }
|
|
109
|
+
|
|
110
|
+
/** PowerShell: una cadena entre comillas simples. */
|
|
111
|
+
/** @param {string} s */
|
|
112
|
+
const psQuote = (s) => `'${String(s).replace(/'/g, "''")}'`
|
|
113
|
+
|
|
114
|
+
/** ¿Hay sesión gráfica en este entorno? Sin ella, un agente de `autostart` no puede arrancar ahora. */
|
|
115
|
+
/** @param {NodeJS.ProcessEnv} env */
|
|
116
|
+
const graphical = (env) => !!(env.DISPLAY || env.WAYLAND_DISPLAY)
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* El supervisor: levanta el agente del perfil y lo vuelve a levantar cada vez que sale (también
|
|
120
|
+
* cuando se reinicia para estrenar una versión: §15, `DOTRINO_SUPERVISED`). Uno por perfil: si
|
|
121
|
+
* ya hay otro vivo, lanza `already-supervised`.
|
|
122
|
+
* @param {{ name: string, dir: string, node?: string, cli: string, args: string[], spawn?: SpawnFn }} o
|
|
123
|
+
*/
|
|
124
|
+
export function supervise ({ name, dir, node = process.execPath, cli, args, spawn = childSpawn }) {
|
|
125
|
+
fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
126
|
+
const pidFile = supervisorPidFile(dir)
|
|
127
|
+
const other = readPid(pidFile)
|
|
128
|
+
if (other && other !== process.pid && alive(other)) throw fail('already-supervised', `profile ${name} already has a supervisor (pid ${other})`)
|
|
129
|
+
fs.writeFileSync(pidFile, String(process.pid))
|
|
130
|
+
let stopped = false
|
|
131
|
+
/** @type {import('node:child_process').ChildProcess | null} */
|
|
132
|
+
let child = null
|
|
133
|
+
const start = () => {
|
|
134
|
+
const fd = fs.openSync(path.join(dir, 'agent.log'), 'a', 0o600)
|
|
135
|
+
child = spawn(node, [cli, ...args], { windowsHide: true, stdio: ['ignore', fd, fd], env: { ...process.env, DOTRINO_SUPERVISED: '1' } })
|
|
136
|
+
fs.closeSync(fd)
|
|
137
|
+
child.on('exit', () => { child = null; if (!stopped) setTimeout(start, RESTART_MS) })
|
|
138
|
+
}
|
|
139
|
+
start()
|
|
140
|
+
return {
|
|
141
|
+
stop: () => {
|
|
142
|
+
stopped = true
|
|
143
|
+
try { child?.kill() } catch (_) {}
|
|
144
|
+
try { if (readPid(pidFile) === process.pid) fs.rmSync(pidFile) } catch (_) {}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Para el supervisor y después el agente. En Windows matar el supervisor no se lleva al hijo
|
|
151
|
+
* (no hay señales: `agent.pid`, si el agente lo escribe); en Linux el supervisor para a su hijo
|
|
152
|
+
* al recibir SIGTERM.
|
|
153
|
+
* @param {string} dir
|
|
154
|
+
*/
|
|
155
|
+
function stopSupervised (dir) {
|
|
156
|
+
for (const file of [supervisorPidFile(dir), path.join(dir, 'agent.pid')]) {
|
|
157
|
+
const pid = readPid(file)
|
|
158
|
+
if (pid && alive(pid)) process.kill(pid)
|
|
159
|
+
}
|
|
160
|
+
fs.rmSync(supervisorPidFile(dir), { force: true })
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Las órdenes de servicio de un agente.
|
|
165
|
+
* @param {Product} product
|
|
166
|
+
*/
|
|
167
|
+
export function makeService ({ id, title, runPrefix, agentArgs, linux = 'systemd' }) {
|
|
168
|
+
/** @param {string} name */
|
|
169
|
+
const unitName = (name) => `dotrino-${id}-${name}.service`
|
|
170
|
+
/** @param {string} name */
|
|
171
|
+
const plistLabel = (name) => `com.dotrino.${id}.${name}`
|
|
172
|
+
/** @param {string} name */
|
|
173
|
+
const runValue = (name) => `${runPrefix}-${name}`
|
|
174
|
+
/** @param {string} name @param {string} [home] */
|
|
175
|
+
const unitPath = (name, home = os.homedir()) => path.join(home, '.config', 'systemd', 'user', unitName(name))
|
|
176
|
+
/** @param {string} name @param {string} [home] */
|
|
177
|
+
const plistPath = (name, home = os.homedir()) => path.join(home, 'Library', 'LaunchAgents', `${plistLabel(name)}.plist`)
|
|
178
|
+
/** @param {string} name @param {string} [home] */
|
|
179
|
+
const autostartPath = (name, home = os.homedir()) => path.join(home, '.config', 'autostart', `dotrino-${id}-${name}.desktop`)
|
|
180
|
+
/** Lo que se apunta en la clave de Windows: Node, el CLI y el supervisor del perfil. */
|
|
181
|
+
/** @param {Launch} o */
|
|
182
|
+
const runCommand = ({ name, node, cli }) => `"${node}" "${cli}" supervise --name ${name}`
|
|
183
|
+
/** @param {string} name */
|
|
184
|
+
const runKeyFile = (name) => `${RUN_KEY}\\${runValue(name)}`
|
|
185
|
+
/** @type {(name: string, run: RunFn) => boolean} */
|
|
186
|
+
const hasRunKey = (name, run) => quiet(run, 'reg', ['query', RUN_KEY, '/v', runValue(name)]).ok
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* La unidad de systemd. El PATH es el de quien instala: el de un servicio de usuario es mínimo
|
|
190
|
+
* y no trae el Node de nvm ni las herramientas que el agente espera encontrar.
|
|
191
|
+
* @param {Launch & { pathEnv: string }} o
|
|
192
|
+
*/
|
|
193
|
+
function unitText ({ name, node, cli, pathEnv }) {
|
|
194
|
+
return `[Unit]
|
|
195
|
+
Description=${title} (${name})
|
|
196
|
+
After=network-online.target
|
|
197
|
+
Wants=network-online.target
|
|
198
|
+
|
|
199
|
+
[Service]
|
|
200
|
+
ExecStart=${[node, cli, ...agentArgs(name)].map(unitArg).join(' ')}
|
|
201
|
+
Environment=${unitArg(`PATH=${pathEnv}`)}
|
|
202
|
+
Restart=always
|
|
203
|
+
RestartSec=3
|
|
204
|
+
|
|
205
|
+
[Install]
|
|
206
|
+
WantedBy=default.target
|
|
207
|
+
`
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* La entrada del inicio automático del escritorio: lanza el supervisor del perfil. El entorno
|
|
212
|
+
* (PATH, DISPLAY, el bus de sesión) es el de la sesión, que es justo lo que hace falta.
|
|
213
|
+
* @param {Launch} o
|
|
214
|
+
*/
|
|
215
|
+
function autostartText ({ name, node, cli }) {
|
|
216
|
+
return `[Desktop Entry]
|
|
217
|
+
Type=Application
|
|
218
|
+
Name=${title} (${name})
|
|
219
|
+
Exec=${[node, cli, 'supervise', '--name', name].map(desktopArg).join(' ')}
|
|
220
|
+
Terminal=false
|
|
221
|
+
NoDisplay=true
|
|
222
|
+
X-GNOME-Autostart-enabled=true
|
|
223
|
+
`
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* El LaunchAgent de macOS. `DOTRINO_SUPERVISED`: launchd lo levanta si sale (§15).
|
|
228
|
+
* @param {Launch & { pathEnv: string, log: string }} o
|
|
229
|
+
*/
|
|
230
|
+
function plistText ({ name, node, cli, pathEnv, log }) {
|
|
231
|
+
const args = [node, cli, ...agentArgs(name)].map((a) => ` <string>${xml(a)}</string>`).join('\n')
|
|
232
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
233
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
234
|
+
<plist version="1.0"><dict>
|
|
235
|
+
<key>Label</key><string>${xml(plistLabel(name))}</string>
|
|
236
|
+
<key>ProgramArguments</key>
|
|
237
|
+
<array>
|
|
238
|
+
${args}
|
|
239
|
+
</array>
|
|
240
|
+
<key>EnvironmentVariables</key>
|
|
241
|
+
<dict>
|
|
242
|
+
<key>PATH</key><string>${xml(pathEnv)}</string>
|
|
243
|
+
<key>DOTRINO_SUPERVISED</key><string>1</string>
|
|
244
|
+
</dict>
|
|
245
|
+
<key>RunAtLoad</key><true/>
|
|
246
|
+
<key>KeepAlive</key><true/>
|
|
247
|
+
<key>StandardOutPath</key><string>${xml(log)}</string>
|
|
248
|
+
<key>StandardErrorPath</key><string>${xml(log)}</string>
|
|
249
|
+
</dict></plist>
|
|
250
|
+
`
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* ¿Deja este sistema instalar el servicio? Lanza con el motivo si no.
|
|
255
|
+
* @param {{ platform: string, run: RunFn }} o
|
|
256
|
+
* @returns {ServiceKind}
|
|
257
|
+
*/
|
|
258
|
+
function platformOf ({ platform, run }) {
|
|
259
|
+
if (platform === 'darwin') return 'launchd'
|
|
260
|
+
if (platform === 'win32') return 'run-key'
|
|
261
|
+
if (platform !== 'linux') throw fail('unsupported-platform', `there is no service support for ${platform}`)
|
|
262
|
+
if (linux === 'autostart') return 'autostart'
|
|
263
|
+
// Sin systemd de usuario (un contenedor, WSL sin systemd, otra init) no hay dónde ponerlo.
|
|
264
|
+
if (!quiet(run, 'systemctl', ['--user', 'show-environment']).ok) throw fail('no-user-systemd', 'this session has no systemd user manager')
|
|
265
|
+
return 'systemd'
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Lanza el supervisor del perfil, ya suelto (sin ventana en Windows, en su propia sesión en Linux).
|
|
270
|
+
*
|
|
271
|
+
* Windows desde SSH no vale un proceso aparte: sshd mete la sesión en un objeto de trabajo y al
|
|
272
|
+
* cerrarla mata todo lo que lanzó. Ahí lo crea WMI (`Win32_Process.Create`) con la misma línea
|
|
273
|
+
* que queda en `HKCU\…\Run`; una cuenta sin administrador no puede, y se devuelve el motivo.
|
|
274
|
+
*
|
|
275
|
+
* Linux (`autostart`) sin sesión gráfica en este entorno (por SSH): el agente no arrancaría.
|
|
276
|
+
* No se lanza nada y se dice; el inicio automático lo arranca al iniciar sesión.
|
|
277
|
+
*
|
|
278
|
+
* @param {Launch & { platform: string, spawn: SpawnFn, run: RunFn, env: NodeJS.ProcessEnv }} o
|
|
279
|
+
* @returns {{ ok: true } | { ok: false, reason: string }}
|
|
280
|
+
*/
|
|
281
|
+
function spawnSupervisor ({ name, node, cli, platform, spawn, run, env }) {
|
|
282
|
+
if (platform === 'win32' && (env.SSH_CONNECTION || env.SSH_CLIENT)) {
|
|
283
|
+
const script = `$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = ${psQuote(runCommand({ name, node, cli }))} }; if ($r.ReturnValue -ne 0) { throw "Win32_Process.Create returned $($r.ReturnValue)" }`
|
|
284
|
+
const r = quiet(run, 'powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script])
|
|
285
|
+
return r.ok ? { ok: true } : { ok: false, reason: 'Windows (WMI) does not let this account start it from SSH' }
|
|
286
|
+
}
|
|
287
|
+
if (platform === 'linux' && !graphical(env)) return { ok: false, reason: 'there is no graphical session here (DISPLAY / WAYLAND_DISPLAY)' }
|
|
288
|
+
const child = spawn(node, [cli, 'supervise', '--name', name], { detached: true, windowsHide: true, stdio: 'ignore', env: { ...env, DOTRINO_SUPERVISOR: '1' } })
|
|
289
|
+
child.unref()
|
|
290
|
+
return { ok: true }
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* La orden `supervise` del CLI del agente. La lanza el sistema (la entrada de `Run`, el inicio
|
|
295
|
+
* automático del escritorio): primero se vuelve a lanzar suelto y sale (en Windows se abre CON
|
|
296
|
+
* ventana), y ese segundo proceso es el supervisor. Para con SIGINT/SIGTERM y se lleva al agente.
|
|
297
|
+
* @param {{ name: string, dir: string, cli: string, node?: string, spawn?: SpawnFn, env?: NodeJS.ProcessEnv }} o
|
|
298
|
+
*/
|
|
299
|
+
function superviseCommand ({ name, dir, cli, node = process.execPath, spawn = childSpawn, env = process.env }) {
|
|
300
|
+
if (!env.DOTRINO_SUPERVISOR) {
|
|
301
|
+
spawn(node, [cli, 'supervise', '--name', name], { detached: true, windowsHide: true, stdio: 'ignore', env: { ...env, DOTRINO_SUPERVISOR: '1' } }).unref()
|
|
302
|
+
return { relaunched: true }
|
|
303
|
+
}
|
|
304
|
+
const s = supervise({ name, dir, node, cli, args: agentArgs(name), spawn })
|
|
305
|
+
const bye = () => { s.stop(); process.exit(0) }
|
|
306
|
+
process.on('SIGINT', bye); process.on('SIGTERM', bye)
|
|
307
|
+
return { relaunched: false, stop: s.stop }
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Instala y enciende el servicio del perfil `name`.
|
|
312
|
+
*
|
|
313
|
+
* `running`: ya hay un agente de ese perfil corriendo por su cuenta. Dos agentes con el mismo
|
|
314
|
+
* enlace son la misma llave: el servicio queda puesto y toma el relevo cuando ese termine o al
|
|
315
|
+
* próximo arranque.
|
|
316
|
+
*
|
|
317
|
+
* @param {{ name: string, node?: string, cli: string, dir: string, running?: boolean, pathEnv?: string, platform?: string, home?: string,
|
|
318
|
+
* user?: string, uid?: number, run?: RunFn, spawn?: SpawnFn, env?: NodeJS.ProcessEnv }} o
|
|
319
|
+
* @returns {{ kind: ServiceKind, file: string, started: boolean, boot?: boolean, lingerReason?: string, startReason?: string }}
|
|
320
|
+
*/
|
|
321
|
+
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 }) {
|
|
322
|
+
const kind = platformOf({ platform, run })
|
|
323
|
+
if (kind === 'run-key' || kind === 'autostart') {
|
|
324
|
+
let file
|
|
325
|
+
if (kind === 'run-key') {
|
|
326
|
+
must(run, 'reg', ['add', RUN_KEY, '/v', runValue(name), '/t', 'REG_SZ', '/d', runCommand({ name, node, cli }), '/f'])
|
|
327
|
+
file = runKeyFile(name)
|
|
328
|
+
} else {
|
|
329
|
+
file = autostartPath(name, home)
|
|
330
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
331
|
+
fs.writeFileSync(file, autostartText({ name, node, cli }), { mode: 0o644 })
|
|
332
|
+
}
|
|
333
|
+
if (running) return { kind, file, started: false }
|
|
334
|
+
const pid = readPid(supervisorPidFile(dir))
|
|
335
|
+
if (pid && alive(pid)) return { kind, file, started: true }
|
|
336
|
+
const s = spawnSupervisor({ name, node, cli, platform, spawn, run, env })
|
|
337
|
+
return { kind, file, started: s.ok, ...(s.ok ? {} : { startReason: s.reason }) }
|
|
338
|
+
}
|
|
339
|
+
if (kind === 'launchd') {
|
|
340
|
+
const file = plistPath(name, home)
|
|
341
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
342
|
+
fs.writeFileSync(file, plistText({ name, node, cli, pathEnv, log: path.join(dir, 'agent.log') }), { mode: 0o644 })
|
|
343
|
+
if (running) return { kind, file, started: false }
|
|
344
|
+
// Si ya estaba cargado (una instalación anterior), se recarga con el archivo nuevo.
|
|
345
|
+
quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
346
|
+
must(run, 'launchctl', ['bootstrap', `gui/${uid}`, file])
|
|
347
|
+
return { kind, file, started: true }
|
|
348
|
+
}
|
|
349
|
+
const file = unitPath(name, home)
|
|
350
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
351
|
+
fs.writeFileSync(file, unitText({ name, node, cli, pathEnv }), { mode: 0o644 })
|
|
352
|
+
must(run, 'systemctl', ['--user', 'daemon-reload'])
|
|
353
|
+
must(run, 'systemctl', ['--user', 'enable', unitName(name)])
|
|
354
|
+
if (!running) must(run, 'systemctl', ['--user', 'restart', unitName(name)])
|
|
355
|
+
// Arrancar al ENCENDER, sin que nadie inicie sesión. Si el sistema no lo deja sin
|
|
356
|
+
// administrador, el servicio arranca al iniciar sesión, y se dice.
|
|
357
|
+
if (lingers(user)) return { kind, file, started: !running, boot: true }
|
|
358
|
+
const linger = quiet(run, 'loginctl', ['enable-linger', user])
|
|
359
|
+
return { kind, file, started: !running, boot: linger.ok, ...(linger.ok ? {} : { lingerReason: linger.reason }) }
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Arranca el servicio ya instalado de ese perfil. `false` si el perfil no tiene servicio (o no
|
|
364
|
+
* se puede dejar corriendo desde aquí): entonces quien llama levanta el agente él mismo.
|
|
365
|
+
* @param {{ name: string, dir: string, node?: string, cli: string, platform?: string, home?: string, uid?: number,
|
|
366
|
+
* run?: RunFn, spawn?: SpawnFn, env?: NodeJS.ProcessEnv }} o
|
|
367
|
+
* @returns {boolean}
|
|
368
|
+
*/
|
|
369
|
+
function startService ({ name, dir, node = process.execPath, cli, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync, spawn = childSpawn, env = process.env }) {
|
|
370
|
+
if (platform === 'win32' || (platform === 'linux' && linux === 'autostart')) {
|
|
371
|
+
if (platform === 'win32' ? !hasRunKey(name, run) : !fs.existsSync(autostartPath(name, home))) return false
|
|
372
|
+
const pid = readPid(supervisorPidFile(dir))
|
|
373
|
+
if (pid && alive(pid)) return true
|
|
374
|
+
return spawnSupervisor({ name, node, cli, platform, spawn, run, env }).ok
|
|
375
|
+
}
|
|
376
|
+
if (platform === 'darwin') {
|
|
377
|
+
const file = plistPath(name, home)
|
|
378
|
+
if (!fs.existsSync(file)) return false
|
|
379
|
+
// Cargado y parado no puede estar (KeepAlive): si no corre, es que no está cargado.
|
|
380
|
+
quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
381
|
+
must(run, 'launchctl', ['bootstrap', `gui/${uid}`, file])
|
|
382
|
+
return true
|
|
383
|
+
}
|
|
384
|
+
if (platform !== 'linux' || !fs.existsSync(unitPath(name, home))) return false
|
|
385
|
+
must(run, 'systemctl', ['--user', 'start', unitName(name)])
|
|
386
|
+
return true
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Para el servicio y lo quita. El enlace y los ajustes del perfil no se tocan.
|
|
391
|
+
* @param {{ name: string, dir: string, platform?: string, home?: string, uid?: number, run?: RunFn }} o
|
|
392
|
+
* @returns {{ kind: ServiceKind, file: string, removed: boolean }}
|
|
393
|
+
*/
|
|
394
|
+
function uninstallService ({ name, dir, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
|
|
395
|
+
const kind = platformOf({ platform, run })
|
|
396
|
+
if (kind === 'run-key') {
|
|
397
|
+
if (!hasRunKey(name, run)) return { kind, file: runKeyFile(name), removed: false }
|
|
398
|
+
stopSupervised(dir)
|
|
399
|
+
must(run, 'reg', ['delete', RUN_KEY, '/v', runValue(name), '/f'])
|
|
400
|
+
return { kind, file: runKeyFile(name), removed: true }
|
|
401
|
+
}
|
|
402
|
+
if (kind === 'autostart') {
|
|
403
|
+
const file = autostartPath(name, home)
|
|
404
|
+
if (!fs.existsSync(file)) return { kind, file, removed: false }
|
|
405
|
+
stopSupervised(dir)
|
|
406
|
+
fs.rmSync(file)
|
|
407
|
+
return { kind, file, removed: true }
|
|
408
|
+
}
|
|
409
|
+
const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
|
|
410
|
+
if (!fs.existsSync(file)) return { kind, file, removed: false }
|
|
411
|
+
if (kind === 'launchd') quiet(run, 'launchctl', ['bootout', `gui/${uid}/${plistLabel(name)}`])
|
|
412
|
+
else must(run, 'systemctl', ['--user', 'disable', '--now', unitName(name)])
|
|
413
|
+
fs.rmSync(file)
|
|
414
|
+
if (kind === 'systemd') must(run, 'systemctl', ['--user', 'daemon-reload'])
|
|
415
|
+
return { kind, file, removed: true }
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* ¿Está puesto, y está corriendo ahora bajo el sistema?
|
|
420
|
+
* @param {{ name: string, dir: string, platform?: string, home?: string, uid?: number, run?: RunFn }} o
|
|
421
|
+
* @returns {{ kind: ServiceKind, file: string, installed: boolean, active: boolean }}
|
|
422
|
+
*/
|
|
423
|
+
function serviceStatus ({ name, dir, platform = process.platform, home = os.homedir(), uid = process.getuid?.(), run = execFileSync }) {
|
|
424
|
+
const kind = platformOf({ platform, run })
|
|
425
|
+
if (kind === 'run-key' || kind === 'autostart') {
|
|
426
|
+
const installed = kind === 'run-key' ? hasRunKey(name, run) : fs.existsSync(autostartPath(name, home))
|
|
427
|
+
const pid = installed ? readPid(supervisorPidFile(dir)) : 0
|
|
428
|
+
return { kind, file: kind === 'run-key' ? runKeyFile(name) : autostartPath(name, home), installed, active: !!pid && alive(pid) }
|
|
429
|
+
}
|
|
430
|
+
const file = kind === 'launchd' ? plistPath(name, home) : unitPath(name, home)
|
|
431
|
+
const installed = fs.existsSync(file)
|
|
432
|
+
const active = installed && (kind === 'launchd'
|
|
433
|
+
? quiet(run, 'launchctl', ['print', `gui/${uid}/${plistLabel(name)}`]).ok
|
|
434
|
+
: quiet(run, 'systemctl', ['--user', 'is-active', '--quiet', unitName(name)]).ok)
|
|
435
|
+
return { kind, file, installed, active }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
return {
|
|
439
|
+
installService, uninstallService, serviceStatus, startService, superviseCommand,
|
|
440
|
+
unitText, autostartText, plistText, unitName, unitPath, plistLabel, plistPath, autostartPath, runValue, runCommand
|
|
441
|
+
}
|
|
442
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** Si esta máquina tiene clave. Un archivo que existe y no se puede leer NO es «sin clave»: se lanza. */
|
|
2
|
+
/** @param {string} dir */
|
|
3
|
+
export function hasAccessCode(dir: string): boolean;
|
|
4
|
+
/**
|
|
5
|
+
* Pone o cambia la clave.
|
|
6
|
+
* @param {string} dir
|
|
7
|
+
* @param {unknown} secret
|
|
8
|
+
*/
|
|
9
|
+
export function setAccessCode(dir: string, secret: unknown): void;
|
|
10
|
+
/**
|
|
11
|
+
* Quita la clave.
|
|
12
|
+
* @param {string} dir
|
|
13
|
+
*/
|
|
14
|
+
export function clearAccessCode(dir: string): void;
|
|
15
|
+
/**
|
|
16
|
+
* Si `secret` es la clave de esta máquina. Sin frenos: para la orden local que la cambia.
|
|
17
|
+
* @param {string} dir
|
|
18
|
+
* @param {unknown} secret
|
|
19
|
+
*/
|
|
20
|
+
export function checkAccessCode(dir: string, secret: unknown): boolean;
|
|
21
|
+
/**
|
|
22
|
+
* La puerta de un agente: comprueba la clave y frena los fallos seguidos. Una por agente,
|
|
23
|
+
* compartida por todas sus sesiones.
|
|
24
|
+
* @param {string} dir
|
|
25
|
+
* @param {{ now?: () => number, onIncident?: ((i: { device: string, tries: number }) => void) | null }} [opts]
|
|
26
|
+
* `onIncident`: un mismo aparato (`device`, su pubkey) falló `INCIDENT_AFTER` veces seguidas.
|
|
27
|
+
* Se llama UNA vez por racha; la racha se corta al acertar.
|
|
28
|
+
*/
|
|
29
|
+
export function makeGate(dir: string, { now, onIncident }?: {
|
|
30
|
+
now?: () => number;
|
|
31
|
+
onIncident?: ((i: {
|
|
32
|
+
device: string;
|
|
33
|
+
tries: number;
|
|
34
|
+
}) => void) | null;
|
|
35
|
+
}): {
|
|
36
|
+
/** Si hay que escribir la clave para entrar. Lanza `access-unreadable` si no se puede saber. */
|
|
37
|
+
required: () => boolean;
|
|
38
|
+
/**
|
|
39
|
+
* Lanza `wait` (con `retryMs`) o `bad-code`; si no lanza, la clave era la buena.
|
|
40
|
+
* `device` es quién la escribió (pubkey), para contar sus fallos y avisar.
|
|
41
|
+
*/
|
|
42
|
+
/**
|
|
43
|
+
* @param {unknown} secret
|
|
44
|
+
* @param {string | null} [device]
|
|
45
|
+
*/
|
|
46
|
+
check(secret: unknown, device?: string | null): void;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* El candado de UNA sesión: hasta que escribe la clave (si la máquina tiene), no pasa nada más.
|
|
50
|
+
* Una vez escrita vale para esa conexión. Sin `gate` (lo local), siempre pasa.
|
|
51
|
+
*
|
|
52
|
+
* session.on('message', (msg) => {
|
|
53
|
+
* if (lock.handle(msg)) return // era el `unlock`: ya contestó
|
|
54
|
+
* if (!lock.mayPass()) return // ya contestó `locked` (o que no se puede saber)
|
|
55
|
+
* …
|
|
56
|
+
* })
|
|
57
|
+
*
|
|
58
|
+
* No saber si hay clave (el archivo no se puede leer) es no pasar, y se dice.
|
|
59
|
+
* @param {{ gate: ReturnType<typeof makeGate> | null, device?: string | null,
|
|
60
|
+
* send: (msg: object) => unknown }} o
|
|
61
|
+
*/
|
|
62
|
+
export function makeLock({ gate, device, send }: {
|
|
63
|
+
gate: ReturnType<typeof makeGate> | null;
|
|
64
|
+
device?: string | null;
|
|
65
|
+
send: (msg: object) => unknown;
|
|
66
|
+
}): {
|
|
67
|
+
readonly unlocked: boolean;
|
|
68
|
+
/** True si esta sesión puede seguir; si no, ya contestó por qué. */
|
|
69
|
+
mayPass(): boolean;
|
|
70
|
+
/** Si `msg` es el `unlock`, lo atiende y devuelve true. @param {any} msg */
|
|
71
|
+
handle(msg: any): boolean;
|
|
72
|
+
};
|
|
73
|
+
export const ACCESS_FILE: "access.json";
|
|
74
|
+
export const MIN_LENGTH: 4;
|
|
75
|
+
/** Fallos seguidos que se dejan pasar sin esperar: al tercero empieza la espera. */
|
|
76
|
+
export const FREE_TRIES: 3;
|
|
77
|
+
/** Fallos seguidos de un mismo aparato que disparan el aviso a la bóveda. */
|
|
78
|
+
export const INCIDENT_AFTER: 3;
|
|
79
|
+
export type Thrown = Error & {
|
|
80
|
+
code?: string;
|
|
81
|
+
retryMs?: number;
|
|
82
|
+
};
|
package/types/src/agent.d.ts
CHANGED
|
@@ -18,7 +18,9 @@
|
|
|
18
18
|
* @param {string} [opts.product] qué producto es (`accounts`, `terminal-agent`…), para el anuncio a la bóveda.
|
|
19
19
|
* @param {string} [opts.version] su versión. Sin `product`/`version` se anuncia como `remote-agent`.
|
|
20
20
|
* @param {string[]} [opts.needs] los permisos del acta que necesita, además de `sign`, que lo
|
|
21
|
-
* añade este pilar: sin él no se abre ninguna sesión (`@dotrino/compat` ≥ 0.5.0).
|
|
21
|
+
* añade este pilar: sin él no se abre ninguna sesión (`@dotrino/compat` ≥ 0.5.0). Desde 0.38.0
|
|
22
|
+
* también se EXIGEN a quien saluda: un aparato sin ellos no abre sesión (`missing-cap`), y si
|
|
23
|
+
* se los quitan con la sesión abierta, se le cierra.
|
|
22
24
|
*
|
|
23
25
|
* Devuelve además el **`client`** (el `WebSocketProxyClient` ya conectado e
|
|
24
26
|
* identificado bajo la pubkey de esta máquina). Se expone a propósito: un agente
|
|
@@ -140,10 +142,8 @@ export class AgentSession {
|
|
|
140
142
|
on(ev: "message" | "close", cb: (msg?: any) => void): this;
|
|
141
143
|
/** Lo que llega se entrega en el orden en que llegó, tarde lo que tarde en descifrarse cada uno. */
|
|
142
144
|
/** @param {{ iv: string, ct: string }} env */
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
ct: string;
|
|
146
|
-
}): Promise<void>;
|
|
145
|
+
/** @param {any} env @param {() => void} [onOpen] solo si el sobre abre, antes de repartirlo */
|
|
146
|
+
_ingest(env: any, onOpen?: () => void): Promise<void>;
|
|
147
147
|
close(): void;
|
|
148
148
|
}
|
|
149
149
|
declare namespace _default {
|
package/types/src/catch-up.d.ts
CHANGED
|
@@ -8,6 +8,19 @@ export function makeCatchUp({ refresh, seq, minGapMs, now }: {
|
|
|
8
8
|
minGapMs?: number;
|
|
9
9
|
now?: () => number;
|
|
10
10
|
}): () => Promise<boolean>;
|
|
11
|
+
/**
|
|
12
|
+
* UN AVISO QUE CUALQUIERA PUEDE MANDAR no dispara el trabajo cada vez: como mucho una vez cada
|
|
13
|
+
* `minGapMs`, y lo que llegue mientras tanto se junta en UNA llamada al final del hueco (así un
|
|
14
|
+
* aviso de verdad entre basura no se pierde: llega tarde, como mucho `minGapMs`).
|
|
15
|
+
* @param {() => Promise<unknown>} fn
|
|
16
|
+
* @param {{ minGapMs?: number, now?: () => number, setTimer?: (f: () => void, ms: number) => unknown }} [o]
|
|
17
|
+
* @returns {() => void}
|
|
18
|
+
*/
|
|
19
|
+
export function makeThrottle(fn: () => Promise<unknown>, { minGapMs, now, setTimer }?: {
|
|
20
|
+
minGapMs?: number;
|
|
21
|
+
now?: () => number;
|
|
22
|
+
setTimer?: (f: () => void, ms: number) => unknown;
|
|
23
|
+
}): () => void;
|
|
11
24
|
/**
|
|
12
25
|
* catch-up.js — ponerse al día con la bóveda ANTES de rechazar a alguien.
|
|
13
26
|
*
|
|
@@ -5,8 +5,20 @@
|
|
|
5
5
|
* @returns {boolean}
|
|
6
6
|
*/
|
|
7
7
|
export function canGreet(acta: DotrinoActa | null | undefined, pub: unknown): boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Los permisos de PRODUCTO que le faltan a ese aparato (`terminal`, `desktop`…): los que el
|
|
10
|
+
* agente declara en `needs`, además de `sign` (dueño, 2026-11-16, tras la auditoría: con solo
|
|
11
|
+
* `sign`, cualquier aparato del acta —un bot, un navegador prestado— abría una consola o el
|
|
12
|
+
* escritorio en todas las máquinas). Sin acta faltan todos: no hay con qué decir que sí.
|
|
13
|
+
* @param {DotrinoActa | null | undefined} acta
|
|
14
|
+
* @param {unknown} pub
|
|
15
|
+
* @param {readonly string[]} needs
|
|
16
|
+
* @returns {string[]}
|
|
17
|
+
*/
|
|
18
|
+
export function missingCaps(acta: DotrinoActa | null | undefined, pub: unknown, needs: readonly string[]): string[];
|
|
8
19
|
declare namespace _default {
|
|
9
20
|
export { canGreet };
|
|
21
|
+
export { missingCaps };
|
|
10
22
|
}
|
|
11
23
|
export default _default;
|
|
12
24
|
export type DotrinoActa = import("./shapes.js").DotrinoActa;
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* El supervisor: levanta el agente del perfil y lo vuelve a levantar cada vez que sale (también
|
|
3
|
+
* cuando se reinicia para estrenar una versión: §15, `DOTRINO_SUPERVISED`). Uno por perfil: si
|
|
4
|
+
* ya hay otro vivo, lanza `already-supervised`.
|
|
5
|
+
* @param {{ name: string, dir: string, node?: string, cli: string, args: string[], spawn?: SpawnFn }} o
|
|
6
|
+
*/
|
|
7
|
+
export function supervise({ name, dir, node, cli, args, spawn }: {
|
|
8
|
+
name: string;
|
|
9
|
+
dir: string;
|
|
10
|
+
node?: string;
|
|
11
|
+
cli: string;
|
|
12
|
+
args: string[];
|
|
13
|
+
spawn?: SpawnFn;
|
|
14
|
+
}): {
|
|
15
|
+
stop: () => void;
|
|
16
|
+
};
|
|
17
|
+
/**
|
|
18
|
+
* Las órdenes de servicio de un agente.
|
|
19
|
+
* @param {Product} product
|
|
20
|
+
*/
|
|
21
|
+
export function makeService({ id, title, runPrefix, agentArgs, linux }: Product): {
|
|
22
|
+
installService: ({ name, node, cli, dir, running, pathEnv, platform, home, user, uid, run, spawn, env }: {
|
|
23
|
+
name: string;
|
|
24
|
+
node?: string;
|
|
25
|
+
cli: string;
|
|
26
|
+
dir: string;
|
|
27
|
+
running?: boolean;
|
|
28
|
+
pathEnv?: string;
|
|
29
|
+
platform?: string;
|
|
30
|
+
home?: string;
|
|
31
|
+
user?: string;
|
|
32
|
+
uid?: number;
|
|
33
|
+
run?: RunFn;
|
|
34
|
+
spawn?: SpawnFn;
|
|
35
|
+
env?: NodeJS.ProcessEnv;
|
|
36
|
+
}) => {
|
|
37
|
+
kind: ServiceKind;
|
|
38
|
+
file: string;
|
|
39
|
+
started: boolean;
|
|
40
|
+
boot?: boolean;
|
|
41
|
+
lingerReason?: string;
|
|
42
|
+
startReason?: string;
|
|
43
|
+
};
|
|
44
|
+
uninstallService: ({ name, dir, platform, home, uid, run }: {
|
|
45
|
+
name: string;
|
|
46
|
+
dir: string;
|
|
47
|
+
platform?: string;
|
|
48
|
+
home?: string;
|
|
49
|
+
uid?: number;
|
|
50
|
+
run?: RunFn;
|
|
51
|
+
}) => {
|
|
52
|
+
kind: ServiceKind;
|
|
53
|
+
file: string;
|
|
54
|
+
removed: boolean;
|
|
55
|
+
};
|
|
56
|
+
serviceStatus: ({ name, dir, platform, home, uid, run }: {
|
|
57
|
+
name: string;
|
|
58
|
+
dir: string;
|
|
59
|
+
platform?: string;
|
|
60
|
+
home?: string;
|
|
61
|
+
uid?: number;
|
|
62
|
+
run?: RunFn;
|
|
63
|
+
}) => {
|
|
64
|
+
kind: ServiceKind;
|
|
65
|
+
file: string;
|
|
66
|
+
installed: boolean;
|
|
67
|
+
active: boolean;
|
|
68
|
+
};
|
|
69
|
+
startService: ({ name, dir, node, cli, platform, home, uid, run, spawn, env }: {
|
|
70
|
+
name: string;
|
|
71
|
+
dir: string;
|
|
72
|
+
node?: string;
|
|
73
|
+
cli: string;
|
|
74
|
+
platform?: string;
|
|
75
|
+
home?: string;
|
|
76
|
+
uid?: number;
|
|
77
|
+
run?: RunFn;
|
|
78
|
+
spawn?: SpawnFn;
|
|
79
|
+
env?: NodeJS.ProcessEnv;
|
|
80
|
+
}) => boolean;
|
|
81
|
+
superviseCommand: ({ name, dir, cli, node, spawn, env }: {
|
|
82
|
+
name: string;
|
|
83
|
+
dir: string;
|
|
84
|
+
cli: string;
|
|
85
|
+
node?: string;
|
|
86
|
+
spawn?: SpawnFn;
|
|
87
|
+
env?: NodeJS.ProcessEnv;
|
|
88
|
+
}) => {
|
|
89
|
+
relaunched: boolean;
|
|
90
|
+
stop?: undefined;
|
|
91
|
+
} | {
|
|
92
|
+
relaunched: boolean;
|
|
93
|
+
stop: () => void;
|
|
94
|
+
};
|
|
95
|
+
unitText: ({ name, node, cli, pathEnv }: Launch & {
|
|
96
|
+
pathEnv: string;
|
|
97
|
+
}) => string;
|
|
98
|
+
autostartText: ({ name, node, cli }: Launch) => string;
|
|
99
|
+
plistText: ({ name, node, cli, pathEnv, log }: Launch & {
|
|
100
|
+
pathEnv: string;
|
|
101
|
+
log: string;
|
|
102
|
+
}) => string;
|
|
103
|
+
unitName: (name: string) => string;
|
|
104
|
+
unitPath: (name: string, home?: string) => string;
|
|
105
|
+
plistLabel: (name: string) => string;
|
|
106
|
+
plistPath: (name: string, home?: string) => string;
|
|
107
|
+
autostartPath: (name: string, home?: string) => string;
|
|
108
|
+
runValue: (name: string) => string;
|
|
109
|
+
runCommand: ({ name, node, cli }: Launch) => string;
|
|
110
|
+
};
|
|
111
|
+
/** Correr una orden del sistema (`execFileSync`, o su doble en las pruebas). */
|
|
112
|
+
/** @typedef {(cmd: string, args: string[], opts?: import('node:child_process').ExecFileSyncOptions) => unknown} RunFn */
|
|
113
|
+
/** Lanzar un proceso (`spawn`, o su doble en las pruebas). */
|
|
114
|
+
/** @typedef {typeof childSpawn} SpawnFn */
|
|
115
|
+
/** Lo que comparten las órdenes de servicio: el perfil, y Node y el CLI con que se lanza. */
|
|
116
|
+
/** @typedef {{ name: string, node: string, cli: string }} Launch */
|
|
117
|
+
/** @typedef {'systemd' | 'autostart' | 'launchd' | 'run-key'} ServiceKind */
|
|
118
|
+
/**
|
|
119
|
+
* Qué agente es.
|
|
120
|
+
* @typedef {object} Product
|
|
121
|
+
* @property {string} id `terminal-agent` → `dotrino-terminal-agent-<perfil>.service`, `com.dotrino.terminal-agent.<perfil>`
|
|
122
|
+
* @property {string} title para la descripción de la unidad: `Dotrino Terminal agent`
|
|
123
|
+
* @property {string} runPrefix el valor de `HKCU\…\Run`: `DotrinoTerminalAgent` → `DotrinoTerminalAgent-<perfil>`
|
|
124
|
+
* @property {(name: string) => string[]} agentArgs con qué argumentos se corre el agente sin TTY
|
|
125
|
+
* @property {'systemd' | 'autostart'} [linux] cómo se pone en Linux (por defecto, systemd)
|
|
126
|
+
*/
|
|
127
|
+
/** Windows: la clave de lo que arranca al iniciar sesión. */
|
|
128
|
+
export const RUN_KEY: "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
|
|
129
|
+
/** Cuánto espera el supervisor antes de volver a levantar el agente (como `RestartSec`). */
|
|
130
|
+
export const RESTART_MS: 3000;
|
|
131
|
+
export function supervisorPidFile(dir: string): string;
|
|
132
|
+
export function desktopArg(s: string): string;
|
|
133
|
+
export type Thrown = Error & {
|
|
134
|
+
code?: string;
|
|
135
|
+
stderr?: string | Buffer;
|
|
136
|
+
};
|
|
137
|
+
export type RunFn = (cmd: string, args: string[], opts?: import("node:child_process").ExecFileSyncOptions) => unknown;
|
|
138
|
+
export type SpawnFn = typeof childSpawn;
|
|
139
|
+
export type Launch = {
|
|
140
|
+
name: string;
|
|
141
|
+
node: string;
|
|
142
|
+
cli: string;
|
|
143
|
+
};
|
|
144
|
+
export type ServiceKind = "systemd" | "autostart" | "launchd" | "run-key";
|
|
145
|
+
/**
|
|
146
|
+
* Qué agente es.
|
|
147
|
+
*/
|
|
148
|
+
export type Product = {
|
|
149
|
+
/**
|
|
150
|
+
* `terminal-agent` → `dotrino-terminal-agent-<perfil>.service`, `com.dotrino.terminal-agent.<perfil>`
|
|
151
|
+
*/
|
|
152
|
+
id: string;
|
|
153
|
+
/**
|
|
154
|
+
* para la descripción de la unidad: `Dotrino Terminal agent`
|
|
155
|
+
*/
|
|
156
|
+
title: string;
|
|
157
|
+
/**
|
|
158
|
+
* el valor de `HKCU\…\Run`: `DotrinoTerminalAgent` → `DotrinoTerminalAgent-<perfil>`
|
|
159
|
+
*/
|
|
160
|
+
runPrefix: string;
|
|
161
|
+
/**
|
|
162
|
+
* con qué argumentos se corre el agente sin TTY
|
|
163
|
+
*/
|
|
164
|
+
agentArgs: (name: string) => string[];
|
|
165
|
+
/**
|
|
166
|
+
* cómo se pone en Linux (por defecto, systemd)
|
|
167
|
+
*/
|
|
168
|
+
linux?: "systemd" | "autostart" | undefined;
|
|
169
|
+
};
|
|
170
|
+
import { spawn as childSpawn } from 'node:child_process';
|