@dotrino/terminal-agent 0.19.0 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/access.js +96 -0
  2. package/package.json +2 -1
package/access.js ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * access.js — la CLAVE de esta máquina (un PIN o una contraseña), opcional.
3
+ *
4
+ * Sin clave puesta no cambia nada: abre una consola cualquier aparato de la cuenta con `sign`,
5
+ * como siempre. Con clave, además de ser de la cuenta hay que escribirla en cada conexión
6
+ * remota. Las ventanas de ESTA máquina (el socket local) no la piden: son del mismo usuario
7
+ * que ya puede leer este archivo.
8
+ *
9
+ * En el disco queda la sal y el resumen (scrypt), nunca la clave. La clave viaja dentro de la
10
+ * sesión cifrada entre el aparato y el agente, así que el proxio no la ve.
11
+ *
12
+ * Los fallos se frenan POR AGENTE y no por sesión: quien prueba claves puede abrir otra
13
+ * conexión, y eso no le da intentos nuevos.
14
+ */
15
+ import crypto from 'node:crypto'
16
+ import fs from 'node:fs'
17
+ import path from 'node:path'
18
+
19
+ export const ACCESS_FILE = 'access.json'
20
+ export const MIN_LENGTH = 4
21
+ /** Fallos seguidos que se dejan pasar sin esperar. */
22
+ export const FREE_TRIES = 5
23
+ const BASE_WAIT_MS = 30_000
24
+ const MAX_WAIT_MS = 60 * 60_000
25
+ const SCRYPT = { N: 1 << 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }
26
+
27
+ const fail = (code, message, extra = {}) => Object.assign(new Error(message), { code, ...extra })
28
+ const file = (dir) => path.join(dir, ACCESS_FILE)
29
+ const digest = (secret, salt, params) => crypto.scryptSync(String(secret).normalize('NFKC'), salt, 32, params)
30
+
31
+ /** Si esta máquina tiene clave. Un archivo que existe y no se puede leer NO es «sin clave»: se lanza. */
32
+ export function hasAccessCode (dir) {
33
+ return readRecord(dir) !== null
34
+ }
35
+
36
+ function readRecord (dir) {
37
+ let raw
38
+ try { raw = fs.readFileSync(file(dir), 'utf8') } catch (e) {
39
+ if (e.code === 'ENOENT') return null
40
+ throw fail('access-unreadable', `cannot read ${ACCESS_FILE}: ${e.message}`)
41
+ }
42
+ let r
43
+ try { r = JSON.parse(raw) } catch (_) { throw fail('access-unreadable', `${ACCESS_FILE} is not valid JSON`) }
44
+ if (r?.v !== 1 || typeof r.salt !== 'string' || typeof r.hash !== 'string' || !r.params) {
45
+ throw fail('access-unreadable', `${ACCESS_FILE} has an unknown shape`)
46
+ }
47
+ return r
48
+ }
49
+
50
+ /** Pone o cambia la clave. */
51
+ export function setAccessCode (dir, secret) {
52
+ if (typeof secret !== 'string' || secret.length < MIN_LENGTH) throw fail('too-short', `the code needs at least ${MIN_LENGTH} characters`)
53
+ const salt = crypto.randomBytes(16)
54
+ const record = { v: 1, salt: salt.toString('base64'), hash: digest(secret, salt, SCRYPT).toString('base64'), params: SCRYPT }
55
+ const tmp = file(dir) + '.tmp'
56
+ fs.writeFileSync(tmp, JSON.stringify(record), { mode: 0o600 })
57
+ fs.renameSync(tmp, file(dir))
58
+ }
59
+
60
+ /** Quita la clave. */
61
+ export function clearAccessCode (dir) {
62
+ fs.rmSync(file(dir), { force: true })
63
+ }
64
+
65
+ /** Si `secret` es la clave de esta máquina. Sin frenos: para la orden local que la cambia. */
66
+ export function checkAccessCode (dir, secret) {
67
+ const r = readRecord(dir)
68
+ if (!r) throw fail('no-access-code', 'this machine has no code')
69
+ const want = Buffer.from(r.hash, 'base64')
70
+ const got = digest(secret ?? '', Buffer.from(r.salt, 'base64'), r.params)
71
+ return want.length === got.length && crypto.timingSafeEqual(want, got)
72
+ }
73
+
74
+ /**
75
+ * La puerta de un agente: comprueba la clave y frena los fallos seguidos. Una por agente,
76
+ * compartida por todas sus sesiones.
77
+ * @param {string} dir
78
+ * @param {{ now?: () => number }} [opts]
79
+ */
80
+ export function makeGate (dir, { now = Date.now } = {}) {
81
+ let fails = 0
82
+ let until = 0
83
+ return {
84
+ /** Si hay que escribir la clave para entrar. Lanza `access-unreadable` si no se puede saber. */
85
+ required: () => hasAccessCode(dir),
86
+ /** Lanza `wait` (con `retryMs`) o `bad-code`; si no lanza, la clave era la buena. */
87
+ check (secret) {
88
+ const left = until - now()
89
+ if (left > 0) throw fail('wait', 'too many wrong codes', { retryMs: left })
90
+ if (checkAccessCode(dir, secret)) { fails = 0; until = 0; return }
91
+ fails++
92
+ if (fails >= FREE_TRIES) until = now() + Math.min(BASE_WAIT_MS * 2 ** (fails - FREE_TRIES), MAX_WAIT_MS)
93
+ throw fail('bad-code', 'wrong code', until ? { retryMs: until - now() } : {})
94
+ }
95
+ }
96
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dotrino/terminal-agent",
3
- "version": "0.19.0",
3
+ "version": "0.19.1",
4
4
  "description": "Dotrino Terminal: las ventanas de esta máquina (dotrino-terminal) y su agente, que deja abrir esas mismas consolas desde los otros aparatos de tu cuenta, cifrado punto a punto.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -12,6 +12,7 @@
12
12
  },
13
13
  "files": [
14
14
  "index.js",
15
+ "access.js",
15
16
  "consoles.js",
16
17
  "link.js",
17
18
  "local.js",