dsh-lan-guard 0.3.1 → 0.3.2
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/CHANGELOG.md +144 -35
- package/README.md +152 -93
- package/README.zh.md +147 -88
- package/cordis.patch.yml +4 -3
- package/lib/client.js +154 -30
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +30 -19
- package/lib/index.js +188 -69
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -2,9 +2,9 @@ import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
|
2
2
|
import { dirname, join } from "node:path";
|
|
3
3
|
import { X509Certificate, createHash, createPrivateKey, createPublicKey, pbkdf2, randomBytes, timingSafeEqual } from "node:crypto";
|
|
4
4
|
import { promisify } from "node:util";
|
|
5
|
+
import { homedir, networkInterfaces } from "node:os";
|
|
5
6
|
import z from "@deepseek-ai/schemastery";
|
|
6
7
|
import { Bonjour } from "bonjour-service";
|
|
7
|
-
import { networkInterfaces } from "node:os";
|
|
8
8
|
import { createServer, request } from "node:http";
|
|
9
9
|
import { createServer as createServer$1 } from "node:https";
|
|
10
10
|
import QRCode from "qrcode";
|
|
@@ -16,7 +16,7 @@ import { generate } from "selfsigned";
|
|
|
16
16
|
*
|
|
17
17
|
* Everything here lands in a profile patch file (`cordis.patch.yml`), which is
|
|
18
18
|
* plain text a user may share or commit, so NO credential ever belongs in this
|
|
19
|
-
* schema
|
|
19
|
+
* schema. Passwords, hashes and the
|
|
20
20
|
* passwordless-link token live in the plugin's private dataDir instead.
|
|
21
21
|
*
|
|
22
22
|
* This module owns two things:
|
|
@@ -27,11 +27,21 @@ import { generate } from "selfsigned";
|
|
|
27
27
|
* set rather than an internal one.
|
|
28
28
|
* - `parseConfig`: the semantic checks Schemastery cannot express (loopback
|
|
29
29
|
* upstream, literal listen address, the `auth.enabled === false` bind rule,
|
|
30
|
-
* the
|
|
31
|
-
*
|
|
30
|
+
* and the resolution of `dataDir`, whose default is derived from the active
|
|
31
|
+
* profile rather than demanded from the operator). Invalid values must be
|
|
32
|
+
* REJECTED — a silently widened default is the failure mode this module
|
|
33
|
+
* exists to prevent.
|
|
32
34
|
*/
|
|
33
|
-
/**
|
|
34
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Default bind address: every interface, because this plugin's whole purpose is
|
|
37
|
+
* LAN access and a fresh install must work after ONE restart.
|
|
38
|
+
*
|
|
39
|
+
* The exposure is gated, not silent: `auth.enabled` defaults to true and a
|
|
40
|
+
* fresh install has NO access password, so the gate refuses every device until
|
|
41
|
+
* one is set; TLS defaults to self-signed, so nothing travels in clear. The
|
|
42
|
+
* settings page offers a 「仅本机」 switch for anyone who wants loopback only.
|
|
43
|
+
*/
|
|
44
|
+
const DEFAULT_LISTEN_HOST = "0.0.0.0";
|
|
35
45
|
/**
|
|
36
46
|
* Default proxy port: DSH's own port + 1, which is the mental model the user
|
|
37
47
|
* asked for ("3081, 3082, 3083 … take the first free one"). It stays clear of
|
|
@@ -45,14 +55,19 @@ const DEFAULT_UPSTREAM_ORIGIN = "http://127.0.0.1:3080";
|
|
|
45
55
|
* 0.1.7 — the Loader entry id is the form namespace, so this object must stay
|
|
46
56
|
* the documented field set.
|
|
47
57
|
*
|
|
48
|
-
* The
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
58
|
+
* The NON-SENSITIVE switches are `.volatile()`: an edit
|
|
59
|
+
* commits into the running references and emits a volatile update instead of
|
|
60
|
+
* remounting the plugin, and the host `settings` service refuses to write any
|
|
61
|
+
* path that is not volatile. A volatile field's runtime
|
|
62
|
+
* value is a stable reference with `get()`, not the bare value —
|
|
63
|
+
* {@link parseConfig} unwraps it, and {@link liveSwitches} keeps the reference
|
|
64
|
+
* so later edits are visible without a restart.
|
|
65
|
+
*
|
|
66
|
+
* `listenHost` is volatile too, and deliberately so: the settings page offers a
|
|
67
|
+
* 「仅本机 / 局域网」 switch, and a switch the operator cannot write is worse
|
|
68
|
+
* than no switch. The BIND still happens once at startup from the resolved
|
|
69
|
+
* value, so the switch takes effect on the next dsh restart — the same contract
|
|
70
|
+
* `listenPort` already has.
|
|
56
71
|
*
|
|
57
72
|
* NOTE on the nullable fields: Schemastery treats a `null` default as "no
|
|
58
73
|
* fallback" (`if (isNullable(fallback)) return [data]`), so a field declared
|
|
@@ -63,7 +78,7 @@ const DEFAULT_UPSTREAM_ORIGIN = "http://127.0.0.1:3080";
|
|
|
63
78
|
*/
|
|
64
79
|
const Config = z.object({
|
|
65
80
|
enabled: z.boolean().default(true).volatile(),
|
|
66
|
-
listenHost: z.string().default(DEFAULT_LISTEN_HOST),
|
|
81
|
+
listenHost: z.string().default(DEFAULT_LISTEN_HOST).volatile(),
|
|
67
82
|
listenPort: z.natural().max(65535).default(DEFAULT_LISTEN_PORT).volatile(),
|
|
68
83
|
upstreamOrigin: z.string().default(DEFAULT_UPSTREAM_ORIGIN),
|
|
69
84
|
networkInterface: z.string().default("").volatile(),
|
|
@@ -121,7 +136,7 @@ function readField(value, fallback) {
|
|
|
121
136
|
*
|
|
122
137
|
* @param rawConfig - the config as `apply` received it.
|
|
123
138
|
* @param resolved - the normalized config from {@link parseConfig}.
|
|
124
|
-
* @returns accessors for the
|
|
139
|
+
* @returns accessors for the writable switches.
|
|
125
140
|
*/
|
|
126
141
|
function liveSwitches(rawConfig, resolved) {
|
|
127
142
|
const root = typeof rawConfig === "object" && rawConfig !== null ? rawConfig : {};
|
|
@@ -130,6 +145,7 @@ function liveSwitches(rawConfig, resolved) {
|
|
|
130
145
|
enabled: () => readField(root.enabled, resolved.enabled),
|
|
131
146
|
networkInterface: () => emptyToNull(readField(root.networkInterface, "")),
|
|
132
147
|
listenPort: () => readField(root.listenPort, resolved.listenPort),
|
|
148
|
+
listenHost: () => readField(root.listenHost, resolved.listenHost),
|
|
133
149
|
mode: () => readField(root.auth === void 0 ? void 0 : auth.mode, resolved.auth.mode),
|
|
134
150
|
adminPolicy: () => readField(root.auth === void 0 ? void 0 : auth.adminPolicy, resolved.auth.adminPolicy),
|
|
135
151
|
adminProtection: () => readField(root.auth === void 0 ? void 0 : auth.adminProtection, resolved.auth.adminProtection),
|
|
@@ -144,6 +160,7 @@ function staticSwitches(config) {
|
|
|
144
160
|
enabled: () => config.enabled,
|
|
145
161
|
networkInterface: () => config.networkInterface,
|
|
146
162
|
listenPort: () => config.listenPort,
|
|
163
|
+
listenHost: () => config.listenHost,
|
|
147
164
|
mode: () => config.auth.mode,
|
|
148
165
|
adminPolicy: () => config.auth.adminPolicy,
|
|
149
166
|
adminProtection: () => config.auth.adminProtection,
|
|
@@ -192,13 +209,54 @@ function emptyToNull(value) {
|
|
|
192
209
|
const trimmed = value.trim();
|
|
193
210
|
return trimmed === "" ? null : trimmed;
|
|
194
211
|
}
|
|
212
|
+
/** Directory this plugin owns under the active profile's `data` directory. */
|
|
213
|
+
const DATA_DIR_NAME = "dsh-lan-guard";
|
|
195
214
|
/**
|
|
196
|
-
*
|
|
215
|
+
* Expand a leading `~` against the OS home.
|
|
197
216
|
*
|
|
198
|
-
*
|
|
199
|
-
*
|
|
200
|
-
*
|
|
217
|
+
* Local on purpose: `@deepseek-ai/dsh-home-paths` would be a new runtime
|
|
218
|
+
* dependency for three lines.
|
|
219
|
+
*
|
|
220
|
+
* @param value - a configured path that may start with `~`.
|
|
221
|
+
* @returns the expanded path, or the value unchanged.
|
|
222
|
+
*/
|
|
223
|
+
function expandTilde(value) {
|
|
224
|
+
if (value === "~") return homedir();
|
|
225
|
+
if (value.startsWith("~/") || value.startsWith("~\\")) return join(homedir(), value.slice(2));
|
|
226
|
+
return value;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Resolve the private-state directory.
|
|
230
|
+
*
|
|
231
|
+
* Precedence:
|
|
232
|
+
*
|
|
233
|
+
* 1. an explicit `dataDir` from this entry's config — the documented override;
|
|
234
|
+
* 2. `<profileDir>/data/dsh-lan-guard`, derived from DSH's own `profileContext`.
|
|
235
|
+
*
|
|
236
|
+
* The plugin still refuses to guess from its OWN module location: a profile may
|
|
237
|
+
* link the package and Node resolves symlinks, so `import.meta.url` can point at
|
|
238
|
+
* a checkout rather than the profile. A host that can
|
|
239
|
+
* name neither source gets an error instead of a silently shared directory.
|
|
240
|
+
*
|
|
241
|
+
* @param rawConfig - the raw Loader config (a volatile reference is unwrapped).
|
|
242
|
+
* @param profileDir - the active profile directory, when the host can name it.
|
|
243
|
+
* @returns the resolution, or `null` when neither source is available.
|
|
201
244
|
*/
|
|
245
|
+
function resolveDataDir(rawConfig, profileDir) {
|
|
246
|
+
const raw = (typeof rawConfig === "object" && rawConfig !== null ? rawConfig : {}).dataDir;
|
|
247
|
+
const value = isVolatileLike(raw) ? raw.get() : raw;
|
|
248
|
+
const explicit = typeof value === "string" ? emptyToNull(value) : null;
|
|
249
|
+
if (explicit !== null) return {
|
|
250
|
+
dir: expandTilde(explicit),
|
|
251
|
+
source: "config"
|
|
252
|
+
};
|
|
253
|
+
const derived = emptyToNull(profileDir);
|
|
254
|
+
if (derived === null) return null;
|
|
255
|
+
return {
|
|
256
|
+
dir: join(expandTilde(derived), "data", DATA_DIR_NAME),
|
|
257
|
+
source: "profile"
|
|
258
|
+
};
|
|
259
|
+
}
|
|
202
260
|
/**
|
|
203
261
|
* Unwrap the volatile references of an already-resolved config.
|
|
204
262
|
*
|
|
@@ -218,7 +276,8 @@ function unwrapVolatileInput(input) {
|
|
|
218
276
|
for (const key of [
|
|
219
277
|
"enabled",
|
|
220
278
|
"networkInterface",
|
|
221
|
-
"listenPort"
|
|
279
|
+
"listenPort",
|
|
280
|
+
"listenHost"
|
|
222
281
|
]) {
|
|
223
282
|
const value = result[key];
|
|
224
283
|
if (isVolatileLike(value)) result[key] = value.get();
|
|
@@ -241,7 +300,15 @@ function unwrapVolatileInput(input) {
|
|
|
241
300
|
}
|
|
242
301
|
return result;
|
|
243
302
|
}
|
|
244
|
-
|
|
303
|
+
/**
|
|
304
|
+
* Apply defaults, then enforce every constraint Schemastery cannot express.
|
|
305
|
+
*
|
|
306
|
+
* @param input - the raw Loader config (or `undefined` for a bare `insert` row).
|
|
307
|
+
* @param profileDir - the active profile directory; supplies the derived `dataDir`.
|
|
308
|
+
* @returns the normalized, fully defaulted config.
|
|
309
|
+
* @throws LanGuardConfigError when a value would make the listener unsafe.
|
|
310
|
+
*/
|
|
311
|
+
function parseConfig(input, profileDir) {
|
|
245
312
|
let resolved;
|
|
246
313
|
try {
|
|
247
314
|
resolved = Config(unwrapVolatileInput(input ?? {}));
|
|
@@ -251,13 +318,14 @@ function parseConfig(input) {
|
|
|
251
318
|
const rawAuth = resolved.auth ?? {};
|
|
252
319
|
const rawTls = resolved.tls ?? {};
|
|
253
320
|
const rawMdns = resolved.mdns ?? {};
|
|
321
|
+
const dataDir = resolveDataDir(input, profileDir);
|
|
254
322
|
const config = {
|
|
255
323
|
enabled: readField(resolved.enabled, true),
|
|
256
324
|
listenHost: readField(resolved.listenHost, DEFAULT_LISTEN_HOST),
|
|
257
325
|
listenPort: readField(resolved.listenPort, DEFAULT_LISTEN_PORT),
|
|
258
326
|
upstreamOrigin: readField(resolved.upstreamOrigin, DEFAULT_UPSTREAM_ORIGIN),
|
|
259
327
|
networkInterface: emptyToNull(readField(resolved.networkInterface, "")),
|
|
260
|
-
dataDir:
|
|
328
|
+
dataDir: dataDir?.dir ?? null,
|
|
261
329
|
auth: {
|
|
262
330
|
enabled: readField(rawAuth.enabled, true),
|
|
263
331
|
mode: readField(rawAuth.mode, "token_and_password"),
|
|
@@ -281,13 +349,13 @@ function parseConfig(input) {
|
|
|
281
349
|
},
|
|
282
350
|
mdns: { enabled: readField(rawMdns.enabled, false) }
|
|
283
351
|
};
|
|
284
|
-
const
|
|
285
|
-
if (
|
|
352
|
+
const dataDirPath = config.dataDir;
|
|
353
|
+
if (dataDirPath === null || dataDirPath.trim() === "") throw new LanGuardConfigError("dsh-lan-guard: no dataDir could be resolved: this entry configures none and the host exposes no profile directory. Set it in this entry's config (cordis.patch.yml), e.g. dataDir: ~/.dsh/profiles/web/data/dsh-lan-guard");
|
|
286
354
|
if (!isIpv4Literal(config.listenHost)) throw new LanGuardConfigError(`dsh-lan-guard: listenHost ${JSON.stringify(config.listenHost)} must be an IPv4 literal (e.g. '127.0.0.1', '0.0.0.0', or one NIC address)`);
|
|
287
355
|
if (!isLoopbackOrigin(config.upstreamOrigin)) throw new LanGuardConfigError(`dsh-lan-guard: upstreamOrigin ${JSON.stringify(config.upstreamOrigin)} must be a loopback http(s) origin (the gate cookie is injected into upstream requests, so a non-loopback upstream would leak it)`);
|
|
288
356
|
if (new URL(config.upstreamOrigin).protocol !== "http:") throw new LanGuardConfigError(`dsh-lan-guard: upstreamOrigin ${JSON.stringify(config.upstreamOrigin)} must use http:// — DSH's loopback web server does not serve TLS`);
|
|
289
357
|
if (!config.auth.enabled && !isLoopbackHost(config.listenHost)) throw new LanGuardConfigError(`dsh-lan-guard: auth.enabled is false while listenHost is ${JSON.stringify(config.listenHost)}; the gate may only be disabled on a loopback listener`);
|
|
290
|
-
if (!isLoopbackHost(config.listenHost) && config.tls.mode === "off" && !config.tls.allowInsecureLan) throw new LanGuardConfigError(`dsh-lan-guard: listenHost ${JSON.stringify(config.listenHost)} with tls.mode "off" would serve the gate password and the upstream session over plain HTTP on the network. Enable TLS (the default self-signed mode), bind 127.0.0.1, or set tls.allowInsecureLan: true to accept that risk explicitly
|
|
358
|
+
if (!isLoopbackHost(config.listenHost) && config.tls.mode === "off" && !config.tls.allowInsecureLan) throw new LanGuardConfigError(`dsh-lan-guard: listenHost ${JSON.stringify(config.listenHost)} with tls.mode "off" would serve the gate password and the upstream session over plain HTTP on the network. Enable TLS (the default self-signed mode), bind 127.0.0.1, or set tls.allowInsecureLan: true to accept that risk explicitly.`);
|
|
291
359
|
if (config.auth.sessionMaxAgeMs <= 0) throw new LanGuardConfigError("dsh-lan-guard: auth.sessionMaxAgeMs must be greater than zero");
|
|
292
360
|
if (config.auth.adminSessionMaxAgeMs <= 0) throw new LanGuardConfigError("dsh-lan-guard: auth.adminSessionMaxAgeMs must be greater than zero");
|
|
293
361
|
if (config.auth.maxFailedAttempts < 1) throw new LanGuardConfigError("dsh-lan-guard: auth.maxFailedAttempts must be at least 1");
|
|
@@ -312,8 +380,7 @@ const noopLogger = {
|
|
|
312
380
|
* dsh-lan-guard — sensitive state on disk.
|
|
313
381
|
*
|
|
314
382
|
* Everything a user would not want in a shareable text file lives here, under
|
|
315
|
-
* the plugin's private `dataDir`, with file mode 600
|
|
316
|
-
* "存储位置", docs/GUARDRAILS.md §4):
|
|
383
|
+
* the plugin's private `dataDir`, with file mode 600:
|
|
317
384
|
*
|
|
318
385
|
* - the access password hash + salt,
|
|
319
386
|
* - the independent admin password hash + salt,
|
|
@@ -321,7 +388,7 @@ const noopLogger = {
|
|
|
321
388
|
* - persistent visitor sessions.
|
|
322
389
|
*
|
|
323
390
|
* Admin sessions are deliberately NOT persisted: they are memory-only and die
|
|
324
|
-
* with the process
|
|
391
|
+
* with the process.
|
|
325
392
|
*
|
|
326
393
|
* No value read or written here is ever logged; only names and lengths may be.
|
|
327
394
|
*/
|
|
@@ -459,7 +526,7 @@ var SecretsStore = class {
|
|
|
459
526
|
//#endregion
|
|
460
527
|
//#region src/auth/manager.ts
|
|
461
528
|
/**
|
|
462
|
-
* dsh-lan-guard — the visitor gate
|
|
529
|
+
* dsh-lan-guard — the visitor gate.
|
|
463
530
|
*
|
|
464
531
|
* The gate is the ONLY thing standing between the LAN and a remote-code-
|
|
465
532
|
* execution UI, so its order of operations is part of the spec:
|
|
@@ -472,8 +539,7 @@ var SecretsStore = class {
|
|
|
472
539
|
* 4. an unexpired session cookie passes;
|
|
473
540
|
* 5. otherwise the request is unauthorized.
|
|
474
541
|
*
|
|
475
|
-
* Field semantics and parameters follow dsh-bridge
|
|
476
|
-
* (docs/RESEARCH.md §5.5): PBKDF2-SHA256 with 600000 iterations and an
|
|
542
|
+
* Field semantics and parameters follow dsh-bridge: PBKDF2-SHA256 with 600000 iterations and an
|
|
477
543
|
* algorithm-prefixed hash, `timingSafeEqual` for every comparison, dual
|
|
478
544
|
* passwords, a `dsh_`-prefixed passwordless-link token, persistent visitor
|
|
479
545
|
* sessions and memory-only admin sessions, per-IP failure lockout.
|
|
@@ -796,8 +862,7 @@ var AuthManager = class {
|
|
|
796
862
|
*
|
|
797
863
|
* Deliberately independent of any visitor session: the researched
|
|
798
864
|
* dsh-bridge deadlock was an unlock that required a valid visitor session,
|
|
799
|
-
* so an expired session made the management console permanently unlockable
|
|
800
|
-
* (docs/RESEARCH.md §5.5).
|
|
865
|
+
* so an expired session made the management console permanently unlockable.
|
|
801
866
|
*
|
|
802
867
|
* @param password - the submitted admin password (falls back to the access password when unset).
|
|
803
868
|
* @returns the admin cookie, or `undefined` when the password is wrong.
|
|
@@ -909,8 +974,7 @@ function clientIp(req) {
|
|
|
909
974
|
return req.socket.remoteAddress ?? "unknown";
|
|
910
975
|
}
|
|
911
976
|
/**
|
|
912
|
-
* Whether a state-changing request passes the CSRF check
|
|
913
|
-
* (docs/SPEC.md F3/§6.5).
|
|
977
|
+
* Whether a state-changing request passes the CSRF check.
|
|
914
978
|
*
|
|
915
979
|
* A malicious page on the LAN can reach the proxy port, so a same-origin
|
|
916
980
|
* check is required on every state change: `Sec-Fetch-Site: cross-site` is
|
|
@@ -1196,7 +1260,7 @@ var VisitorGate = class {
|
|
|
1196
1260
|
* Decide whether an upgrade may proceed.
|
|
1197
1261
|
*
|
|
1198
1262
|
* The caller must have attached its socket error handler BEFORE awaiting
|
|
1199
|
-
* this
|
|
1263
|
+
* this.
|
|
1200
1264
|
*
|
|
1201
1265
|
* @param req - the upgrade request.
|
|
1202
1266
|
* @returns `undefined` when the upgrade may proceed, else the status to send.
|
|
@@ -1678,7 +1742,7 @@ var UpdateChecker = class {
|
|
|
1678
1742
|
//#endregion
|
|
1679
1743
|
//#region src/network.ts
|
|
1680
1744
|
/**
|
|
1681
|
-
* dsh-lan-guard — network interface discovery
|
|
1745
|
+
* dsh-lan-guard — network interface discovery.
|
|
1682
1746
|
*
|
|
1683
1747
|
* The LAN address a phone must type depends on which NIC is actually on the
|
|
1684
1748
|
* same network. Virtual adapters (WSL, VMware, Docker, Tailscale, VPN tunnels)
|
|
@@ -1792,7 +1856,7 @@ const HOP_BY_HOP_HEADERS = [
|
|
|
1792
1856
|
];
|
|
1793
1857
|
/**
|
|
1794
1858
|
* Headers a WebSocket 101 may carry upstream → browser. Everything else the
|
|
1795
|
-
* upstream sends is dropped
|
|
1859
|
+
* upstream sends is dropped.
|
|
1796
1860
|
*/
|
|
1797
1861
|
const UPGRADE_RESPONSE_HEADERS = [
|
|
1798
1862
|
"connection",
|
|
@@ -1838,8 +1902,7 @@ function authorityOf(origin) {
|
|
|
1838
1902
|
* Node hands us the raw request target. A bare-origin request already arrives
|
|
1839
1903
|
* as `/`, but an absolute-form target (or a target with no path at all) must
|
|
1840
1904
|
* still land on `/`, because the shipped shell carries `<base href="./">` and
|
|
1841
|
-
* resolves every relative asset against the directory it was served from
|
|
1842
|
-
* (docs/RESEARCH.md §7.1). We mount at the root only, so no prefix is ever
|
|
1905
|
+
* resolves every relative asset against the directory it was served from. We mount at the root only, so no prefix is ever
|
|
1843
1906
|
* stripped and no target is rewritten beyond this normalization.
|
|
1844
1907
|
*
|
|
1845
1908
|
* @param rawTarget - `req.url` as received.
|
|
@@ -1930,20 +1993,18 @@ function buildUpgradeResponseHead(headers, statusCode, statusMessage) {
|
|
|
1930
1993
|
/**
|
|
1931
1994
|
* dsh-lan-guard — WebSocket upgrade forwarding.
|
|
1932
1995
|
*
|
|
1933
|
-
* DSH serves its Remote stream on `/api/remote.mux` over a WebSocket upgrade
|
|
1934
|
-
* (docs/RESEARCH.md §7), and the shipped UI keeps that socket open for the
|
|
1996
|
+
* DSH serves its Remote stream on `/api/remote.mux` over a WebSocket upgrade, and the shipped UI keeps that socket open for the
|
|
1935
1997
|
* whole session. The proxy therefore has to relay the upgrade itself rather
|
|
1936
1998
|
* than treat it as an ordinary HTTP response.
|
|
1937
1999
|
*
|
|
1938
2000
|
* Two rules from the researched reference implementations are applied here:
|
|
1939
2001
|
*
|
|
1940
2002
|
* - The visitor's socket gets an `error` handler IMMEDIATELY, before any
|
|
1941
|
-
* asynchronous work
|
|
2003
|
+
* asynchronous work. A phone reconnecting drops
|
|
1942
2004
|
* upgrade sockets constantly; an unhandled `error` during an await would
|
|
1943
2005
|
* take the whole process down. This is also why the gate in P2 can await
|
|
1944
2006
|
* safely.
|
|
1945
|
-
* - The upstream 101 passes only the handshake headers a browser needs
|
|
1946
|
-
* (docs/RESEARCH.md §5.3) — never the upstream's arbitrary header set.
|
|
2007
|
+
* - The upstream 101 passes only the handshake headers a browser needs— never the upstream's arbitrary header set.
|
|
1947
2008
|
*/
|
|
1948
2009
|
/** Attach the mandatory `error` handler to a socket we now own. */
|
|
1949
2010
|
function guardUpgradeSocket(socket, logger = noopLogger) {
|
|
@@ -2007,13 +2068,11 @@ function forwardUpgrade(options) {
|
|
|
2007
2068
|
/**
|
|
2008
2069
|
* dsh-lan-guard — the reverse proxy itself.
|
|
2009
2070
|
*
|
|
2010
|
-
* The proxy owns its own listener; it never touches DSH's binding
|
|
2011
|
-
* (docs/RESEARCH.md §2.1, §4). Requests are relayed transparently to the
|
|
2071
|
+
* The proxy owns its own listener; it never touches DSH's binding. Requests are relayed transparently to the
|
|
2012
2072
|
* loopback upstream:
|
|
2013
2073
|
*
|
|
2014
2074
|
* - HTTP: one `http.request` per visitor request, streamed both ways. Nothing
|
|
2015
|
-
* is buffered, so a large or streaming response keeps its semantics
|
|
2016
|
-
* (docs/SPEC.md F1).
|
|
2075
|
+
* is buffered, so a large or streaming response keeps its semantics.
|
|
2017
2076
|
* - WebSocket: the upgrade is relayed by {@link forwardUpgrade}.
|
|
2018
2077
|
* - A `401` from the upstream means our cached loopback cookie died (DSH
|
|
2019
2078
|
* restarted, or the cookie was rotated). For a safe method the request is
|
|
@@ -2206,15 +2265,15 @@ async function startProxy(options) {
|
|
|
2206
2265
|
//#endregion
|
|
2207
2266
|
//#region src/qrcode.ts
|
|
2208
2267
|
/**
|
|
2209
|
-
* dsh-lan-guard — the access URL set and its QR codes
|
|
2268
|
+
* dsh-lan-guard — the access URL set and its QR codes.
|
|
2210
2269
|
*
|
|
2211
2270
|
* The QR is generated on the HOST, because only the host knows the real NIC
|
|
2212
2271
|
* addresses and the passwordless token. It is emitted as an SVG string (the
|
|
2213
|
-
* researched dsh-mobile approach
|
|
2272
|
+
* researched dsh-mobile approach): no base64 bloat, and
|
|
2214
2273
|
* the client can let it inherit theme colours.
|
|
2215
2274
|
*
|
|
2216
2275
|
* The token-bearing URL is a credential: it is only ever produced for an
|
|
2217
|
-
* admin-unlocked caller, and it is never logged
|
|
2276
|
+
* admin-unlocked caller, and it is never logged.
|
|
2218
2277
|
*/
|
|
2219
2278
|
/** Render one QR as an SVG string. */
|
|
2220
2279
|
async function qrSvg(text) {
|
|
@@ -2228,8 +2287,7 @@ async function qrSvg(text) {
|
|
|
2228
2287
|
* Build the access information for the settings page.
|
|
2229
2288
|
*
|
|
2230
2289
|
* Rebuilt on every request on purpose: a NIC change, a TLS change, a port
|
|
2231
|
-
* change or a token rotation therefore refreshes the QR automatically
|
|
2232
|
-
* (docs/SPEC.md F7 "刷新时机").
|
|
2290
|
+
* change or a token rotation therefore refreshes the QR automatically.
|
|
2233
2291
|
*
|
|
2234
2292
|
* @param options - port, TLS mode and the optional token.
|
|
2235
2293
|
* @returns the URL set plus QR codes.
|
|
@@ -2287,6 +2345,14 @@ const ADMIN_POLICIES = [
|
|
|
2287
2345
|
"local_only",
|
|
2288
2346
|
"open"
|
|
2289
2347
|
];
|
|
2348
|
+
/**
|
|
2349
|
+
* The bind addresses the settings page may write.
|
|
2350
|
+
*
|
|
2351
|
+
* Deliberately a closed set: this endpoint is reachable from the LAN under the
|
|
2352
|
+
* default policy, and "write any address string" is a needless widening. A
|
|
2353
|
+
* specific NIC literal remains available through the profile patch.
|
|
2354
|
+
*/
|
|
2355
|
+
const LISTEN_HOSTS = ["0.0.0.0", "127.0.0.1"];
|
|
2290
2356
|
/** Raised when a patch carries a value the endpoint must refuse. */
|
|
2291
2357
|
var PreferenceError = class extends Error {
|
|
2292
2358
|
constructor(message) {
|
|
@@ -2297,7 +2363,7 @@ var PreferenceError = class extends Error {
|
|
|
2297
2363
|
/**
|
|
2298
2364
|
* Validate one client-supplied patch, dropping unknown keys.
|
|
2299
2365
|
*
|
|
2300
|
-
* Dropping is deliberate
|
|
2366
|
+
* Dropping is deliberate: an unknown key is either a typo or
|
|
2301
2367
|
* an attempt to reach a field this endpoint does not own, and neither may
|
|
2302
2368
|
* reach the settings writer.
|
|
2303
2369
|
*
|
|
@@ -2318,6 +2384,11 @@ function sanitizePreferencePatch(patch) {
|
|
|
2318
2384
|
if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 65535) throw new PreferenceError("listenPort must be an integer between 0 and 65535");
|
|
2319
2385
|
result.listenPort = value;
|
|
2320
2386
|
}
|
|
2387
|
+
if (Object.hasOwn(source, "listenHost")) {
|
|
2388
|
+
const value = source.listenHost;
|
|
2389
|
+
if (typeof value !== "string" || !LISTEN_HOSTS.includes(value)) throw new PreferenceError(`listenHost must be one of ${LISTEN_HOSTS.join(", ")}`);
|
|
2390
|
+
result.listenHost = value;
|
|
2391
|
+
}
|
|
2321
2392
|
if (Object.hasOwn(source, "networkInterface")) {
|
|
2322
2393
|
const value = source.networkInterface;
|
|
2323
2394
|
if (typeof value !== "string") throw new PreferenceError("networkInterface must be a string");
|
|
@@ -2362,6 +2433,7 @@ function toSettingsPatch(values) {
|
|
|
2362
2433
|
const auth = {};
|
|
2363
2434
|
if (values.enabled !== void 0) patch.enabled = values.enabled;
|
|
2364
2435
|
if (values.listenPort !== void 0) patch.listenPort = values.listenPort;
|
|
2436
|
+
if (values.listenHost !== void 0) patch.listenHost = values.listenHost;
|
|
2365
2437
|
if (values.networkInterface !== void 0) patch.networkInterface = values.networkInterface;
|
|
2366
2438
|
if (values.requirePairing !== void 0) auth.requirePairing = values.requirePairing;
|
|
2367
2439
|
if (values.requireApproval !== void 0) auth.requireApproval = values.requireApproval;
|
|
@@ -2493,6 +2565,7 @@ function registerManagementRoutes(options) {
|
|
|
2493
2565
|
preferences: {
|
|
2494
2566
|
enabled: options.switches.enabled(),
|
|
2495
2567
|
listenPort: options.switches.listenPort(),
|
|
2568
|
+
listenHost: options.switches.listenHost(),
|
|
2496
2569
|
networkInterface: options.switches.networkInterface() ?? "",
|
|
2497
2570
|
mode: options.switches.mode(),
|
|
2498
2571
|
adminPolicy: options.switches.adminPolicy(),
|
|
@@ -2606,6 +2679,13 @@ function registerManagementRoutes(options) {
|
|
|
2606
2679
|
return;
|
|
2607
2680
|
}
|
|
2608
2681
|
const values = sanitizePreferencePatch(body.preferences);
|
|
2682
|
+
if (values.listenHost !== void 0 && values.listenHost !== "127.0.0.1" && !options.config.auth.enabled) {
|
|
2683
|
+
sendJson(res, 400, {
|
|
2684
|
+
ok: false,
|
|
2685
|
+
error: "gate_disabled_requires_loopback"
|
|
2686
|
+
});
|
|
2687
|
+
return;
|
|
2688
|
+
}
|
|
2609
2689
|
await writePreferences(values);
|
|
2610
2690
|
if (values.mode !== void 0) await options.auth.revokeAllSessions();
|
|
2611
2691
|
}
|
|
@@ -2844,7 +2924,7 @@ function registerManagementRoutes(options) {
|
|
|
2844
2924
|
* credential per phone, so a lost device can be cut off without disturbing the
|
|
2845
2925
|
* others.
|
|
2846
2926
|
*
|
|
2847
|
-
* Credential hygiene
|
|
2927
|
+
* Credential hygiene:
|
|
2848
2928
|
*
|
|
2849
2929
|
* - the plaintext token is returned exactly ONCE, when the device is created;
|
|
2850
2930
|
* - only its SHA-256 hash is persisted, with mode 600, in the plugin dataDir;
|
|
@@ -3016,10 +3096,10 @@ var DeviceRegistry = class {
|
|
|
3016
3096
|
//#endregion
|
|
3017
3097
|
//#region src/tls/ca.ts
|
|
3018
3098
|
/**
|
|
3019
|
-
* dsh-lan-guard — the self-signed certificate authority
|
|
3099
|
+
* dsh-lan-guard — the self-signed certificate authority.
|
|
3020
3100
|
*
|
|
3021
3101
|
* The CA is the long-lived identity a phone trusts once. Parameters follow the
|
|
3022
|
-
* researched dsh-mobile set
|
|
3102
|
+
* researched dsh-mobile set: EC P-256, SHA-256,
|
|
3023
3103
|
* `basicConstraints: cA: true`, `keyUsage` with `keyCertSign`.
|
|
3024
3104
|
*
|
|
3025
3105
|
* The subject common name is a user decision (2026-09-24): "DSH LAN Guard CA".
|
|
@@ -3124,7 +3204,7 @@ async function loadCa(certPath, keyPath) {
|
|
|
3124
3204
|
* Load the CA from disk, generating it once when missing.
|
|
3125
3205
|
*
|
|
3126
3206
|
* The CA identity is retained across restarts on purpose: replacing it would
|
|
3127
|
-
* force every phone to re-trust a new CA
|
|
3207
|
+
* force every phone to re-trust a new CA.
|
|
3128
3208
|
*
|
|
3129
3209
|
* @param certPath - where the CA certificate lives.
|
|
3130
3210
|
* @param keyPath - where the CA private key lives.
|
|
@@ -3241,13 +3321,13 @@ async function ensureLeaf(options) {
|
|
|
3241
3321
|
* dsh-lan-guard — upstream loopback authentication (SPEC §3 F2, route A).
|
|
3242
3322
|
*
|
|
3243
3323
|
* The browser holds a cookie for the PROXY origin; DSH's fence authenticates a
|
|
3244
|
-
* cookie bound to the authority `127.0.0.1:<dshPort
|
|
3324
|
+
* cookie bound to the authority `127.0.0.1:<dshPort>`.
|
|
3245
3325
|
* So the proxy cannot reuse the visitor's cookie and must hold one of its own.
|
|
3246
3326
|
*
|
|
3247
3327
|
* Route A (the decided route) uses only the public seam
|
|
3248
3328
|
* `ctx.connection.authenticatedUrl(origin)`:
|
|
3249
3329
|
*
|
|
3250
|
-
* GET /?token=<launch token> → 303 + Set-Cookie + Location
|
|
3330
|
+
* GET /?token=<launch token> → 303 + Set-Cookie + Location:./
|
|
3251
3331
|
*
|
|
3252
3332
|
* and caches the resulting cookie. The launch token is process-scoped, so a
|
|
3253
3333
|
* DSH restart invalidates it — this class detects that by re-reading the
|
|
@@ -3258,7 +3338,7 @@ async function ensureLeaf(options) {
|
|
|
3258
3338
|
* fail silently with a 401 after any format change.
|
|
3259
3339
|
*
|
|
3260
3340
|
* The launch token and the session cookie are credentials: they are held in
|
|
3261
|
-
* memory only, never logged, never written to disk
|
|
3341
|
+
* memory only, never logged, never written to disk.
|
|
3262
3342
|
*/
|
|
3263
3343
|
/** How long to wait for the token→cookie exchange before giving up. */
|
|
3264
3344
|
const EXCHANGE_TIMEOUT_MS = 5e3;
|
|
@@ -3351,7 +3431,7 @@ var UpstreamAuth = class {
|
|
|
3351
3431
|
/** The launch token currently offered by the seam. Never logged. */
|
|
3352
3432
|
#currentToken() {
|
|
3353
3433
|
const token = new URL(this.#authenticatedUrl(this.#origin)).searchParams.get("token");
|
|
3354
|
-
if (token === null || token === "") throw new UpstreamAuthError("dsh-lan-guard: ctx.connection.authenticatedUrl() returned no launch token; the upstream authentication seam changed
|
|
3434
|
+
if (token === null || token === "") throw new UpstreamAuthError("dsh-lan-guard: ctx.connection.authenticatedUrl() returned no launch token; the upstream authentication seam changed");
|
|
3355
3435
|
return token;
|
|
3356
3436
|
}
|
|
3357
3437
|
/** Whether the cached session still matches the live token and has not neared expiry. */
|
|
@@ -3429,7 +3509,8 @@ async function readPackageVersion() {
|
|
|
3429
3509
|
}
|
|
3430
3510
|
async function startLanGuard(host, rawConfig) {
|
|
3431
3511
|
const logger = host.logger ?? noopLogger;
|
|
3432
|
-
const
|
|
3512
|
+
const dataDir = resolveDataDir(rawConfig, host.profileDir);
|
|
3513
|
+
const config = parseConfig(rawConfig, host.profileDir);
|
|
3433
3514
|
const switches = liveSwitches(rawConfig, config);
|
|
3434
3515
|
if (!switches.enabled()) {
|
|
3435
3516
|
logger.info("plugin disabled; no listener opened");
|
|
@@ -3438,6 +3519,7 @@ async function startLanGuard(host, rawConfig) {
|
|
|
3438
3519
|
if (!isLoopbackHost(config.listenHost) && config.tls.mode === "off") logger.warn("plain HTTP on a non-loopback listener was explicitly acknowledged; the gate password is not encrypted");
|
|
3439
3520
|
if (host.webServerPort !== void 0 && config.listenPort !== 0 && config.listenPort === host.webServerPort) throw new Error(`dsh-lan-guard: listenPort ${config.listenPort} is DSH's own web server port; choose a different port (default 3445)`);
|
|
3440
3521
|
const store = new SecretsStore(config.dataDir ?? "", logger);
|
|
3522
|
+
logger.info("private state dir=%s source=%s", config.dataDir ?? "", dataDir?.source ?? "config");
|
|
3441
3523
|
const auth = new AuthManager({
|
|
3442
3524
|
store,
|
|
3443
3525
|
auth: config.auth,
|
|
@@ -3530,8 +3612,7 @@ async function startLanGuard(host, rawConfig) {
|
|
|
3530
3612
|
* Produce the listener's TLS material.
|
|
3531
3613
|
*
|
|
3532
3614
|
* `self-signed` keeps a long-lived CA and re-signs a leaf for the CURRENT
|
|
3533
|
-
* addresses, so a DHCP change never invalidates a phone's trust
|
|
3534
|
-
* (docs/RESEARCH.md §5.1).
|
|
3615
|
+
* addresses, so a DHCP change never invalidates a phone's trust.
|
|
3535
3616
|
*/
|
|
3536
3617
|
async function materializeTls(config, logger) {
|
|
3537
3618
|
if (config.tls.mode === "off") {
|
|
@@ -3565,17 +3646,54 @@ async function materializeTls(config, logger) {
|
|
|
3565
3646
|
caFingerprint: ca.fingerprint
|
|
3566
3647
|
};
|
|
3567
3648
|
}
|
|
3568
|
-
|
|
3649
|
+
/**
|
|
3650
|
+
* Look a host service up without requiring it.
|
|
3651
|
+
*
|
|
3652
|
+
* `ctx.<service>` would throw for a service this plugin does not declare in
|
|
3653
|
+
* `inject`, and declaring one would stop the plugin from loading in hosts that
|
|
3654
|
+
* ship none. `ctx.get(name)` is the optional lookup, so a missing service
|
|
3655
|
+
* degrades one feature instead of taking the whole plugin down.
|
|
3656
|
+
*
|
|
3657
|
+
* @param ctx - the plugin context.
|
|
3658
|
+
* @param name - the host service name.
|
|
3659
|
+
* @returns the service, or `undefined` when it is absent.
|
|
3660
|
+
*/
|
|
3661
|
+
function optionalService(ctx, name) {
|
|
3569
3662
|
const lookup = ctx.get;
|
|
3570
3663
|
if (typeof lookup !== "function") return void 0;
|
|
3571
3664
|
try {
|
|
3572
|
-
const service = lookup.call(ctx,
|
|
3665
|
+
const service = lookup.call(ctx, name);
|
|
3573
3666
|
return service === void 0 || service === null ? void 0 : service;
|
|
3574
3667
|
} catch {
|
|
3575
3668
|
return;
|
|
3576
3669
|
}
|
|
3577
3670
|
}
|
|
3578
3671
|
/**
|
|
3672
|
+
* The host `settings` service, when this profile ships one.
|
|
3673
|
+
*
|
|
3674
|
+
* Without it the management endpoint degrades to read-only instead of taking
|
|
3675
|
+
* the plugin down, and it never pretends a write succeeded.
|
|
3676
|
+
*
|
|
3677
|
+
* @param ctx - the plugin context.
|
|
3678
|
+
* @returns the settings writer, or `undefined`.
|
|
3679
|
+
*/
|
|
3680
|
+
function optionalSettings(ctx) {
|
|
3681
|
+
return optionalService(ctx, "settings");
|
|
3682
|
+
}
|
|
3683
|
+
/**
|
|
3684
|
+
* The active profile directory, read from DSH's own `profileContext` service.
|
|
3685
|
+
*
|
|
3686
|
+
* This is the FACT the plugin derives its default `dataDir` from — never its
|
|
3687
|
+
* own module location, which a linked package moves.
|
|
3688
|
+
*
|
|
3689
|
+
* @param ctx - the plugin context.
|
|
3690
|
+
* @returns the directory, or `undefined` when the host cannot name one.
|
|
3691
|
+
*/
|
|
3692
|
+
function activeProfileDir(ctx) {
|
|
3693
|
+
const dir = optionalService(ctx, "profileContext")?.dir;
|
|
3694
|
+
return typeof dir === "string" && dir.trim() !== "" ? dir : void 0;
|
|
3695
|
+
}
|
|
3696
|
+
/**
|
|
3579
3697
|
* Cordis entry point.
|
|
3580
3698
|
*
|
|
3581
3699
|
* @param ctx - the plugin's context (injects `webServer` and `connection`).
|
|
@@ -3586,6 +3704,7 @@ async function apply(ctx, rawConfig) {
|
|
|
3586
3704
|
const runtime = await startLanGuard({
|
|
3587
3705
|
authenticatedUrl: (baseUrl) => ctx.connection.authenticatedUrl(baseUrl),
|
|
3588
3706
|
webServerPort: ctx.webServer.port,
|
|
3707
|
+
profileDir: activeProfileDir(ctx),
|
|
3589
3708
|
logger,
|
|
3590
3709
|
registerManagement: (deps) => registerManagementRoutes({
|
|
3591
3710
|
connection: { requestRejection: (request) => ctx.connection.requestRejection(request) },
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-lan-guard",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "DSH web plugin: expose the official desktop Web UI to the local network through a gated reverse proxy, without touching DSH's own loopback binding.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|