dsh-lan-guard 0.1.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/lib/index.js ADDED
@@ -0,0 +1,3343 @@
1
+ import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { X509Certificate, createHash, createPrivateKey, createPublicKey, pbkdf2, randomBytes, timingSafeEqual } from "node:crypto";
4
+ import { promisify } from "node:util";
5
+ import z from "@deepseek-ai/schemastery";
6
+ import { Bonjour } from "bonjour-service";
7
+ import { networkInterfaces } from "node:os";
8
+ import { createServer, request } from "node:http";
9
+ import { createServer as createServer$1 } from "node:https";
10
+ import QRCode from "qrcode";
11
+ import { createServer as createServer$2 } from "node:net";
12
+ import { generate } from "selfsigned";
13
+ //#region src/config.ts
14
+ /**
15
+ * dsh-lan-guard — the non-sensitive configuration model.
16
+ *
17
+ * Everything here lands in a profile patch file (`cordis.patch.yml`), which is
18
+ * plain text a user may share or commit, so NO credential ever belongs in this
19
+ * schema (docs/SPEC.md F3 "存储位置" table). Passwords, hashes and the
20
+ * passwordless-link token live in the plugin's private dataDir instead.
21
+ *
22
+ * This module owns two things:
23
+ *
24
+ * - `Config`: the Schemastery schema the Loader validates the entry with. On
25
+ * DSH 0.1.7 a plugin's own `Config` IS its settings form (Config-derived
26
+ * forms), which is why the field set below is the documented SPEC §5 field
27
+ * set rather than an internal one.
28
+ * - `parseConfig`: the semantic checks Schemastery cannot express (loopback
29
+ * upstream, literal listen address, the `auth.enabled === false` bind rule,
30
+ * the required `dataDir`). Invalid values must be REJECTED — a silently
31
+ * widened default is the failure mode this module exists to prevent.
32
+ */
33
+ /** Default bind address: loopback only, so a fresh install never exposes anything. */
34
+ const DEFAULT_LISTEN_HOST = "127.0.0.1";
35
+ /**
36
+ * Default proxy port: DSH's own port + 1, which is the mental model the user
37
+ * asked for ("3081, 3082, 3083 … take the first free one"). It stays clear of
38
+ * 3080 (DSH itself), 3443 (dsh-mobile gateway) and 3444 (dsh-mobile origin).
39
+ */
40
+ const DEFAULT_LISTEN_PORT = 3081;
41
+ /** Default upstream: DSH's own loopback web server. */
42
+ const DEFAULT_UPSTREAM_ORIGIN = "http://127.0.0.1:3080";
43
+ /**
44
+ * The entry's config schema. Also the `dsh-lan-guard` settings form on DSH
45
+ * 0.1.7 — the Loader entry id is the form namespace, so this object must stay
46
+ * the documented field set.
47
+ *
48
+ * The five NON-SENSITIVE switches (docs/SPEC.md F6, PLAN §5 工作项 9) are
49
+ * `.volatile()`: an edit commits into the running references and emits a
50
+ * volatile update instead of remounting the plugin, and the host `settings`
51
+ * service refuses to write any path that is not volatile
52
+ * (docs/RESEARCH.md §4.1). A volatile field's runtime value is a stable
53
+ * reference with `get()`, not the bare value — {@link parseConfig} unwraps it,
54
+ * and {@link liveSwitches} keeps the reference so later edits are visible
55
+ * without a restart.
56
+ *
57
+ * NOTE on the nullable fields: Schemastery treats a `null` default as "no
58
+ * fallback" (`if (isNullable(fallback)) return [data]`), so a field declared
59
+ * `.default(null)` stays `undefined` when omitted. The documented `null`
60
+ * defaults are therefore expressed as an empty string in the schema and
61
+ * normalized back to `null` in {@link parseConfig} — an explicit `null` in a
62
+ * patch file is accepted and normalized the same way.
63
+ */
64
+ const Config = z.object({
65
+ enabled: z.boolean().default(true).volatile(),
66
+ listenHost: z.string().default(DEFAULT_LISTEN_HOST),
67
+ listenPort: z.natural().max(65535).default(DEFAULT_LISTEN_PORT).volatile(),
68
+ upstreamOrigin: z.string().default(DEFAULT_UPSTREAM_ORIGIN),
69
+ networkInterface: z.string().default("").volatile(),
70
+ dataDir: z.string().default(""),
71
+ auth: z.object({
72
+ enabled: z.boolean().default(true),
73
+ mode: z.union([
74
+ z.const("password"),
75
+ z.const("token"),
76
+ z.const("token_and_password")
77
+ ]).default("token_and_password").volatile(),
78
+ adminPolicy: z.union([
79
+ z.const("password_unlock"),
80
+ z.const("local_only"),
81
+ z.const("open")
82
+ ]).default("local_only").volatile(),
83
+ adminProtection: z.boolean().default(true).volatile(),
84
+ allowLoopback: z.boolean().default(true).volatile(),
85
+ requirePairing: z.boolean().default(true).volatile(),
86
+ sessionMaxAgeMs: z.natural().default(2592e6),
87
+ adminSessionMaxAgeMs: z.natural().default(18e5),
88
+ maxFailedAttempts: z.natural().default(5),
89
+ lockoutMs: z.natural().default(6e4)
90
+ }),
91
+ tls: z.object({
92
+ mode: z.union([
93
+ z.const("self-signed"),
94
+ z.const("provided"),
95
+ z.const("off")
96
+ ]).default("self-signed"),
97
+ caCertFile: z.string().default(""),
98
+ caKeyFile: z.string().default(""),
99
+ certFile: z.string().default(""),
100
+ keyFile: z.string().default(""),
101
+ allowInsecureLan: z.boolean().default(false)
102
+ }),
103
+ mdns: z.object({ enabled: z.boolean().default(false) })
104
+ });
105
+ /** Whether a resolved value is a volatile reference rather than a bare value. */
106
+ function isVolatileLike(value) {
107
+ return typeof value === "object" && value !== null && typeof value.get === "function";
108
+ }
109
+ /** Read a possibly-volatile field, falling back when absent. */
110
+ function readField(value, fallback) {
111
+ if (isVolatileLike(value)) return value.get();
112
+ return value === void 0 || value === null ? fallback : value;
113
+ }
114
+ /**
115
+ * Build the live switch accessors over a raw Loader config.
116
+ *
117
+ * When the Loader resolved the schema, the fields are volatile references, so
118
+ * an edit made through the settings service is visible immediately. Tests and
119
+ * plain objects fall back to the resolved values.
120
+ *
121
+ * @param rawConfig - the config as `apply` received it.
122
+ * @param resolved - the normalized config from {@link parseConfig}.
123
+ * @returns accessors for the five switches.
124
+ */
125
+ function liveSwitches(rawConfig, resolved) {
126
+ const root = typeof rawConfig === "object" && rawConfig !== null ? rawConfig : {};
127
+ const auth = typeof root.auth === "object" && root.auth !== null ? root.auth : {};
128
+ return {
129
+ enabled: () => readField(root.enabled, resolved.enabled),
130
+ networkInterface: () => emptyToNull(readField(root.networkInterface, "")),
131
+ listenPort: () => readField(root.listenPort, resolved.listenPort),
132
+ mode: () => readField(root.auth === void 0 ? void 0 : auth.mode, resolved.auth.mode),
133
+ adminPolicy: () => readField(root.auth === void 0 ? void 0 : auth.adminPolicy, resolved.auth.adminPolicy),
134
+ adminProtection: () => readField(root.auth === void 0 ? void 0 : auth.adminProtection, resolved.auth.adminProtection),
135
+ allowLoopback: () => readField(root.auth === void 0 ? void 0 : auth.allowLoopback, resolved.auth.allowLoopback),
136
+ requirePairing: () => readField(root.auth === void 0 ? void 0 : auth.requirePairing, resolved.auth.requirePairing)
137
+ };
138
+ }
139
+ /** Wrap plain values as live switches (used by tests and by callers without a raw config). */
140
+ function staticSwitches(config) {
141
+ return {
142
+ enabled: () => config.enabled,
143
+ networkInterface: () => config.networkInterface,
144
+ listenPort: () => config.listenPort,
145
+ mode: () => config.auth.mode,
146
+ adminPolicy: () => config.auth.adminPolicy,
147
+ adminProtection: () => config.auth.adminProtection,
148
+ allowLoopback: () => config.auth.allowLoopback,
149
+ requirePairing: () => config.auth.requirePairing
150
+ };
151
+ }
152
+ /** Raised when a config value is syntactically valid but semantically unsafe. */
153
+ var LanGuardConfigError = class extends Error {
154
+ constructor(message) {
155
+ super(message);
156
+ this.name = "LanGuardConfigError";
157
+ }
158
+ };
159
+ const IPV4_LITERAL = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
160
+ /** Whether an address literal is IPv4. Hostnames are rejected on purpose: a name can be re-resolved. */
161
+ function isIpv4Literal(value) {
162
+ if (!IPV4_LITERAL.test(value)) return false;
163
+ return value.split(".").every((part) => Number(part) <= 255);
164
+ }
165
+ /** Whether a host literal is loopback (IPv4 `127/8`, IPv6 `::1`, or `localhost`). */
166
+ function isLoopbackHost(value) {
167
+ if (value === "localhost" || value === "::1" || value === "[::1]") return true;
168
+ if (!isIpv4Literal(value)) return false;
169
+ return value.split(".")[0] === "127";
170
+ }
171
+ /** Whether an origin URL points at this machine's loopback interface. */
172
+ function isLoopbackOrigin(origin) {
173
+ let url;
174
+ try {
175
+ url = new URL(origin);
176
+ } catch {
177
+ return false;
178
+ }
179
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
180
+ return isLoopbackHost(url.hostname);
181
+ }
182
+ function requireNonEmptyString(value, field) {
183
+ if (typeof value !== "string" || value.trim() === "") throw new LanGuardConfigError(`dsh-lan-guard: ${field} must be a non-empty string`);
184
+ return value;
185
+ }
186
+ /** Map an absent-or-blank optional path to the documented `null`. */
187
+ function emptyToNull(value) {
188
+ if (value === null || value === void 0) return null;
189
+ const trimmed = value.trim();
190
+ return trimmed === "" ? null : trimmed;
191
+ }
192
+ /**
193
+ * Apply defaults, then enforce every constraint Schemastery cannot express.
194
+ *
195
+ * @param input - the raw Loader config (or `undefined` for a bare `insert` row).
196
+ * @returns the normalized, fully defaulted config.
197
+ * @throws LanGuardConfigError when a value would make the listener unsafe.
198
+ */
199
+ /**
200
+ * Unwrap the volatile references of an already-resolved config.
201
+ *
202
+ * The Loader validates the entry through this schema BEFORE calling `apply`,
203
+ * so at runtime `apply` receives the RESOLVED config: the five volatile
204
+ * switches are `{ get() }` references, not booleans. Re-validating that value
205
+ * as if it were the raw patch would reject it, so the references are unwrapped
206
+ * first. Raw patches (tests, direct callers) pass through untouched.
207
+ *
208
+ * @param input - a raw patch or an already-resolved config.
209
+ * @returns the same shape with volatile references replaced by their values.
210
+ */
211
+ function unwrapVolatileInput(input) {
212
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return input;
213
+ const source = input;
214
+ const result = { ...source };
215
+ for (const key of [
216
+ "enabled",
217
+ "networkInterface",
218
+ "listenPort"
219
+ ]) {
220
+ const value = result[key];
221
+ if (isVolatileLike(value)) result[key] = value.get();
222
+ }
223
+ if (typeof source.auth === "object" && source.auth !== null) {
224
+ const auth = { ...source.auth };
225
+ for (const key of [
226
+ "enabled",
227
+ "mode",
228
+ "adminPolicy",
229
+ "adminProtection",
230
+ "allowLoopback",
231
+ "requirePairing"
232
+ ]) {
233
+ const value = auth[key];
234
+ if (isVolatileLike(value)) auth[key] = value.get();
235
+ }
236
+ result.auth = auth;
237
+ }
238
+ return result;
239
+ }
240
+ function parseConfig(input) {
241
+ let resolved;
242
+ try {
243
+ resolved = Config(unwrapVolatileInput(input ?? {}));
244
+ } catch (error) {
245
+ throw new LanGuardConfigError(`dsh-lan-guard: invalid config: ${error.message}`);
246
+ }
247
+ const rawAuth = resolved.auth ?? {};
248
+ const rawTls = resolved.tls ?? {};
249
+ const rawMdns = resolved.mdns ?? {};
250
+ const config = {
251
+ enabled: readField(resolved.enabled, true),
252
+ listenHost: readField(resolved.listenHost, DEFAULT_LISTEN_HOST),
253
+ listenPort: readField(resolved.listenPort, DEFAULT_LISTEN_PORT),
254
+ upstreamOrigin: readField(resolved.upstreamOrigin, DEFAULT_UPSTREAM_ORIGIN),
255
+ networkInterface: emptyToNull(readField(resolved.networkInterface, "")),
256
+ dataDir: emptyToNull(readField(resolved.dataDir, "")),
257
+ auth: {
258
+ enabled: readField(rawAuth.enabled, true),
259
+ mode: readField(rawAuth.mode, "token_and_password"),
260
+ adminPolicy: readField(rawAuth.adminPolicy, "local_only"),
261
+ adminProtection: readField(rawAuth.adminProtection, true),
262
+ allowLoopback: readField(rawAuth.allowLoopback, true),
263
+ requirePairing: readField(rawAuth.requirePairing, true),
264
+ sessionMaxAgeMs: readField(rawAuth.sessionMaxAgeMs, 2592e6),
265
+ adminSessionMaxAgeMs: readField(rawAuth.adminSessionMaxAgeMs, 18e5),
266
+ maxFailedAttempts: readField(rawAuth.maxFailedAttempts, 5),
267
+ lockoutMs: readField(rawAuth.lockoutMs, 6e4)
268
+ },
269
+ tls: {
270
+ mode: readField(rawTls.mode, "self-signed"),
271
+ caCertFile: emptyToNull(readField(rawTls.caCertFile, "")),
272
+ caKeyFile: emptyToNull(readField(rawTls.caKeyFile, "")),
273
+ certFile: emptyToNull(readField(rawTls.certFile, "")),
274
+ keyFile: emptyToNull(readField(rawTls.keyFile, "")),
275
+ allowInsecureLan: readField(rawTls.allowInsecureLan, false)
276
+ },
277
+ mdns: { enabled: readField(rawMdns.enabled, false) }
278
+ };
279
+ const dataDir = config.dataDir;
280
+ if (dataDir === null || dataDir.trim() === "") throw new LanGuardConfigError("dsh-lan-guard: dataDir is not set; the plugin never guesses a profile path — set it in this entry's config (cordis.patch.yml), e.g. dataDir: ~/.dsh/dsh-lan-guard");
281
+ 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)`);
282
+ 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)`);
283
+ 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`);
284
+ 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`);
285
+ 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 (docs/SPEC.md §6.2).`);
286
+ if (config.auth.sessionMaxAgeMs <= 0) throw new LanGuardConfigError("dsh-lan-guard: auth.sessionMaxAgeMs must be greater than zero");
287
+ if (config.auth.adminSessionMaxAgeMs <= 0) throw new LanGuardConfigError("dsh-lan-guard: auth.adminSessionMaxAgeMs must be greater than zero");
288
+ if (config.auth.maxFailedAttempts < 1) throw new LanGuardConfigError("dsh-lan-guard: auth.maxFailedAttempts must be at least 1");
289
+ if (config.auth.lockoutMs < 0) throw new LanGuardConfigError("dsh-lan-guard: auth.lockoutMs must not be negative");
290
+ if (config.tls.mode === "provided") {
291
+ requireNonEmptyString(config.tls.certFile, "tls.certFile");
292
+ requireNonEmptyString(config.tls.keyFile, "tls.keyFile");
293
+ }
294
+ return config;
295
+ }
296
+ //#endregion
297
+ //#region src/log.ts
298
+ /** A logger that discards everything; used when no logger is supplied. */
299
+ const noopLogger = {
300
+ info() {},
301
+ warn() {},
302
+ debug() {}
303
+ };
304
+ //#endregion
305
+ //#region src/store/secrets.ts
306
+ /**
307
+ * dsh-lan-guard — sensitive state on disk.
308
+ *
309
+ * Everything a user would not want in a shareable text file lives here, under
310
+ * the plugin's private `dataDir`, with file mode 600 (docs/SPEC.md F3
311
+ * "存储位置", docs/GUARDRAILS.md §4):
312
+ *
313
+ * - the access password hash + salt,
314
+ * - the independent admin password hash + salt,
315
+ * - the passwordless-link token (`secretToken`),
316
+ * - persistent visitor sessions.
317
+ *
318
+ * Admin sessions are deliberately NOT persisted: they are memory-only and die
319
+ * with the process (docs/SPEC.md F3).
320
+ *
321
+ * No value read or written here is ever logged; only names and lengths may be.
322
+ */
323
+ /** An empty secrets document. */
324
+ function emptySecrets() {
325
+ return {
326
+ version: 1,
327
+ passwordHash: null,
328
+ passwordSalt: null,
329
+ adminPasswordHash: null,
330
+ adminPasswordSalt: null,
331
+ secretToken: null
332
+ };
333
+ }
334
+ /** Read and validate one JSON document, returning `undefined` when absent or unusable. */
335
+ async function readJson(path, logger) {
336
+ let raw;
337
+ try {
338
+ raw = await readFile(path, "utf8");
339
+ } catch (error) {
340
+ if (error.code === "ENOENT") return void 0;
341
+ throw error;
342
+ }
343
+ try {
344
+ return JSON.parse(raw);
345
+ } catch {
346
+ logger.warn("ignoring unreadable json path=%s", path);
347
+ return;
348
+ }
349
+ }
350
+ /**
351
+ * Per-path write queue.
352
+ *
353
+ * Two writes to the same document must never interleave: with a SHARED
354
+ * temporary name one `rename` wins and the other fails with ENOENT, and that
355
+ * rejection used to escape the request path and kill the whole dsh process
356
+ * (2026-09-24: "如果手机访问 DS,也会崩溃" — a phone fires dozens of parallel
357
+ * requests, each of which refreshed the device's "last seen").
358
+ */
359
+ const writeQueues = /* @__PURE__ */ new Map();
360
+ /** Write one JSON document atomically with mode 600. */
361
+ async function writeJson(path, value) {
362
+ await mkdir(dirname(path), {
363
+ recursive: true,
364
+ mode: 448
365
+ });
366
+ const body = `${JSON.stringify(value, null, 2)}\n`;
367
+ const next = (writeQueues.get(path) ?? Promise.resolve()).then(async () => {
368
+ const temporary = `${path}.${String(process.pid)}.${randomBytes(6).toString("hex")}.tmp`;
369
+ await writeFile(temporary, body, { mode: 384 });
370
+ await rename(temporary, path);
371
+ await chmod(path, 384);
372
+ });
373
+ writeQueues.set(path, next.catch(() => void 0));
374
+ return await next;
375
+ }
376
+ /**
377
+ * Owns the plugin's private data directory.
378
+ */
379
+ var SecretsStore = class {
380
+ /** Absolute plugin data directory (never guessed — it comes from config). */
381
+ #dataDir;
382
+ #logger;
383
+ constructor(dataDir, logger = noopLogger) {
384
+ this.#dataDir = dataDir;
385
+ this.#logger = logger;
386
+ }
387
+ /** Absolute path of the secrets document. */
388
+ get secretsPath() {
389
+ return join(this.#dataDir, "secrets.json");
390
+ }
391
+ /** Absolute path of the persistent session document. */
392
+ get sessionsPath() {
393
+ return join(this.#dataDir, "sessions.json");
394
+ }
395
+ /** Absolute path of the paired-device document. */
396
+ get devicesPath() {
397
+ return join(this.#dataDir, "devices.json");
398
+ }
399
+ /** Create the private directory if needed. */
400
+ async ensureDir() {
401
+ await mkdir(this.#dataDir, {
402
+ recursive: true,
403
+ mode: 448
404
+ });
405
+ }
406
+ /**
407
+ * Load the secrets document.
408
+ *
409
+ * @returns the stored secrets, or an empty document when none exists yet.
410
+ * @throws when the file exists but is unreadable — refusing to start beats
411
+ * starting with an empty password (the "any password works" failure).
412
+ */
413
+ async loadSecrets() {
414
+ const parsed = await readJson(this.secretsPath, this.#logger);
415
+ if (parsed === void 0) return emptySecrets();
416
+ if (parsed.version !== 1) throw new Error("dsh-lan-guard: unsupported secrets.json version; refusing to start");
417
+ return {
418
+ ...emptySecrets(),
419
+ ...parsed
420
+ };
421
+ }
422
+ /** Persist the secrets document with mode 600. */
423
+ async saveSecrets(secrets) {
424
+ await writeJson(this.secretsPath, secrets);
425
+ }
426
+ /** Load persisted visitor sessions; a corrupt file yields an empty list (sessions are renewable). */
427
+ async loadSessions() {
428
+ const parsed = await readJson(this.sessionsPath, this.#logger);
429
+ if (!Array.isArray(parsed)) return [];
430
+ return parsed.filter((record) => typeof record === "object" && record !== null && typeof record.token === "string" && typeof record.expiresAtMs === "number");
431
+ }
432
+ /** Persist visitor sessions with mode 600. */
433
+ async saveSessions(records) {
434
+ await writeJson(this.sessionsPath, records);
435
+ }
436
+ /** Load paired devices; a corrupt file yields an empty list (no device is trusted by default). */
437
+ async loadDevices() {
438
+ const parsed = await readJson(this.devicesPath, this.#logger);
439
+ if (parsed === void 0 || !Array.isArray(parsed.devices)) return [];
440
+ return parsed.devices.filter((entry) => typeof entry === "object" && entry !== null && typeof entry.id === "string" && typeof entry.label === "string" && typeof entry.tokenHash === "string");
441
+ }
442
+ /** Persist paired devices with mode 600. */
443
+ async saveDevices(devices) {
444
+ await writeJson(this.devicesPath, {
445
+ version: 1,
446
+ devices
447
+ });
448
+ }
449
+ };
450
+ //#endregion
451
+ //#region src/auth/manager.ts
452
+ /**
453
+ * dsh-lan-guard — the visitor gate (docs/SPEC.md F3).
454
+ *
455
+ * The gate is the ONLY thing standing between the LAN and a remote-code-
456
+ * execution UI, so its order of operations is part of the spec:
457
+ *
458
+ * 1. `auth.enabled: false` is only legal on a loopback listener (enforced in
459
+ * `config.ts`), so a network listener always reaches step 2+;
460
+ * 2. loopback visitors may be exempted (`allowLoopback`) — the local user
461
+ * already has direct DSH access;
462
+ * 3. a locked-out IP is refused BEFORE any password comparison;
463
+ * 4. an unexpired session cookie passes;
464
+ * 5. otherwise the request is unauthorized.
465
+ *
466
+ * Field semantics and parameters follow dsh-bridge
467
+ * (docs/RESEARCH.md §5.5): PBKDF2-SHA256 with 600000 iterations and an
468
+ * algorithm-prefixed hash, `timingSafeEqual` for every comparison, dual
469
+ * passwords, a `dsh_`-prefixed passwordless-link token, persistent visitor
470
+ * sessions and memory-only admin sessions, per-IP failure lockout.
471
+ */
472
+ const pbkdf2Async = promisify(pbkdf2);
473
+ /** Current PBKDF2 iteration count (hundreds of milliseconds — always async). */
474
+ const PBKDF2_ITERATIONS = 6e5;
475
+ /** Iterations assumed for a legacy bare-hex hash. */
476
+ const LEGACY_PBKDF2_ITERATIONS = 1e4;
477
+ /** Digest. */
478
+ const PBKDF2_DIGEST = "sha256";
479
+ /** Salt length in bytes. */
480
+ const SALT_BYTES = 16;
481
+ /** Session/admin cookie names on the proxy origin. */
482
+ const SESSION_COOKIE = "dsh_lan_guard_session";
483
+ const ADMIN_COOKIE = "dsh_lan_guard_admin";
484
+ /** Cookie carrying a device's paired identity (P4-g). */
485
+ const DEVICE_COOKIE = "dsh_lan_guard_device";
486
+ /** A paired device keeps its identity for a year. */
487
+ const DEVICE_COOKIE_MAX_AGE_MS = 31536e6;
488
+ /** How often expired sessions are swept. */
489
+ const SWEEP_INTERVAL_MS = 36e5;
490
+ /** Derive a PBKDF2-SHA256 hash in the documented storage format. */
491
+ async function hashPassword(password, saltHex, iterations = PBKDF2_ITERATIONS) {
492
+ const derived = await pbkdf2Async(password, Buffer.from(saltHex, "hex"), iterations, 32, PBKDF2_DIGEST);
493
+ return `pbkdf2-sha256$${String(iterations)}$${derived.toString("hex")}`;
494
+ }
495
+ /** Generate a fresh salt as hex. */
496
+ function generateSalt() {
497
+ return randomBytes(SALT_BYTES).toString("hex");
498
+ }
499
+ /** Generate a passwordless-link token: `dsh_` + 36 hex characters. */
500
+ function generateSecretToken() {
501
+ return `dsh_${randomBytes(18).toString("hex")}`;
502
+ }
503
+ /** Constant-time comparison of two strings. */
504
+ function safeEqual(actual, expected) {
505
+ const actualBytes = Buffer.from(actual, "utf8");
506
+ const expectedBytes = Buffer.from(expected, "utf8");
507
+ if (actualBytes.byteLength !== expectedBytes.byteLength) return false;
508
+ return timingSafeEqual(actualBytes, expectedBytes);
509
+ }
510
+ /** Compare a candidate password against a stored hash, supporting legacy bare hex. */
511
+ async function verifyPassword(password, saltHex, stored) {
512
+ if (stored === null || stored === "" || saltHex === null || saltHex === "") return false;
513
+ const parts = stored.split("$");
514
+ const isPrefixed = parts.length === 3 && parts[0] === "pbkdf2-sha256";
515
+ const iterations = isPrefixed ? Number.parseInt(parts[1] ?? "", 10) : LEGACY_PBKDF2_ITERATIONS;
516
+ const expectedHex = isPrefixed ? parts[2] ?? "" : stored;
517
+ if (!Number.isFinite(iterations) || iterations <= 0 || expectedHex === "") return false;
518
+ return safeEqual((await pbkdf2Async(password, Buffer.from(saltHex, "hex"), iterations, 32, PBKDF2_DIGEST)).toString("hex"), expectedHex);
519
+ }
520
+ /** Whether an address literal is loopback (IPv4 `127/8`, IPv6 `::1`, or v4-mapped). */
521
+ function isLoopbackAddress(address) {
522
+ if (address === void 0) return false;
523
+ const normalized = address.startsWith("::ffff:") ? address.slice(7) : address;
524
+ if (normalized === "::1") return true;
525
+ return normalized.startsWith("127.");
526
+ }
527
+ /** Read one cookie value by name from a request. */
528
+ function readCookie(req, name) {
529
+ const header = req.headers.cookie;
530
+ if (header === void 0) return void 0;
531
+ for (const segment of header.split(";")) {
532
+ const at = segment.indexOf("=");
533
+ if (at === -1) continue;
534
+ if (segment.slice(0, at).trim() === name) return segment.slice(at + 1).trim();
535
+ }
536
+ }
537
+ /** Build a `Set-Cookie` value for one of the gate's own cookies. */
538
+ function buildSessionCookie(name, token, expiresAtMs, now) {
539
+ const maxAge = Math.max(0, Math.floor((expiresAtMs - now) / 1e3));
540
+ return `${name}=${token}; Max-Age=${String(maxAge)}; Path=/; Expires=${new Date(expiresAtMs).toUTCString()}; HttpOnly; SameSite=Strict`;
541
+ }
542
+ /** Build the cookie that clears one of the gate's cookies. */
543
+ function buildClearedCookie(name) {
544
+ return `${name}=; Max-Age=0; Path=/; HttpOnly; SameSite=Strict`;
545
+ }
546
+ /** The visitor gate. */
547
+ var AuthManager = class {
548
+ #store;
549
+ #auth;
550
+ #switches;
551
+ #logger;
552
+ #now;
553
+ #secrets = emptySecrets();
554
+ #sessions = /* @__PURE__ */ new Map();
555
+ #adminSessions = /* @__PURE__ */ new Map();
556
+ #failures = /* @__PURE__ */ new Map();
557
+ #sweeper;
558
+ constructor(options) {
559
+ this.#store = options.store;
560
+ this.#auth = options.auth;
561
+ this.#switches = options.switches ?? staticSwitches({
562
+ enabled: options.auth.enabled,
563
+ listenHost: "127.0.0.1",
564
+ listenPort: 0,
565
+ upstreamOrigin: "http://127.0.0.1:0",
566
+ networkInterface: null,
567
+ dataDir: null,
568
+ auth: options.auth,
569
+ tls: {
570
+ mode: "off",
571
+ caCertFile: null,
572
+ caKeyFile: null,
573
+ certFile: null,
574
+ keyFile: null,
575
+ allowInsecureLan: false
576
+ },
577
+ mdns: { enabled: false }
578
+ });
579
+ this.#logger = options.logger ?? noopLogger;
580
+ this.#now = options.now ?? (() => Date.now());
581
+ }
582
+ /** Load persisted secrets and sessions, then start the expiry sweeper. */
583
+ async init() {
584
+ await this.#store.ensureDir();
585
+ this.#secrets = await this.#store.loadSecrets();
586
+ const stored = await this.#store.loadSessions();
587
+ const now = this.#now();
588
+ this.#sessions = new Map(stored.filter((record) => record.expiresAtMs > now).map((record) => [record.token, record]));
589
+ this.#sweeper = setInterval(() => {
590
+ this.#sweep();
591
+ }, SWEEP_INTERVAL_MS);
592
+ this.#sweeper.unref();
593
+ }
594
+ /** Stop the sweeper. */
595
+ dispose() {
596
+ if (this.#sweeper !== void 0) clearInterval(this.#sweeper);
597
+ this.#sweeper = void 0;
598
+ }
599
+ /** Whether an access password is configured at all. */
600
+ get hasPassword() {
601
+ return this.#secrets.passwordHash !== null && this.#secrets.passwordHash !== "";
602
+ }
603
+ /** Whether an independent admin password is configured. */
604
+ get hasAdminPassword() {
605
+ return this.#secrets.adminPasswordHash !== null && this.#secrets.adminPasswordHash !== "";
606
+ }
607
+ /** Whether a passwordless-link token exists. */
608
+ get hasSecretToken() {
609
+ return this.#secrets.secretToken !== null && this.#secrets.secretToken !== "";
610
+ }
611
+ /** The live visitor credential mode (drives the login page). */
612
+ get mode() {
613
+ return this.#switches.mode();
614
+ }
615
+ /** Whether the gate is switched on. */
616
+ get enabled() {
617
+ return this.#auth.enabled;
618
+ }
619
+ /** The passwordless-link token, for the admin-unlocked settings view only. */
620
+ secretToken() {
621
+ return this.#secrets.secretToken ?? void 0;
622
+ }
623
+ /** Set (or replace) the access password. */
624
+ async setPassword(password) {
625
+ const salt = generateSalt();
626
+ this.#secrets = {
627
+ ...this.#secrets,
628
+ passwordSalt: salt,
629
+ passwordHash: await hashPassword(password, salt)
630
+ };
631
+ await this.#store.saveSecrets(this.#secrets);
632
+ }
633
+ /** Set (or replace) the independent admin password. */
634
+ async setAdminPassword(password) {
635
+ const salt = generateSalt();
636
+ this.#secrets = {
637
+ ...this.#secrets,
638
+ adminPasswordSalt: salt,
639
+ adminPasswordHash: await hashPassword(password, salt)
640
+ };
641
+ await this.#store.saveSecrets(this.#secrets);
642
+ }
643
+ /** Ensure a passwordless-link token exists, returning it. */
644
+ async ensureSecretToken() {
645
+ if (this.#secrets.secretToken !== null && this.#secrets.secretToken !== "") return this.#secrets.secretToken;
646
+ const token = generateSecretToken();
647
+ this.#secrets = {
648
+ ...this.#secrets,
649
+ secretToken: token
650
+ };
651
+ await this.#store.saveSecrets(this.#secrets);
652
+ return token;
653
+ }
654
+ /** Replace the passwordless-link token with a fresh one. */
655
+ async rotateSecretToken() {
656
+ const token = generateSecretToken();
657
+ this.#secrets = {
658
+ ...this.#secrets,
659
+ secretToken: token
660
+ };
661
+ await this.#store.saveSecrets(this.#secrets);
662
+ return token;
663
+ }
664
+ /** Per-IP failure state, for the login page's honest lockout display. */
665
+ lockoutFor(ip) {
666
+ const state = this.#failures.get(ip);
667
+ if (state === void 0) return {
668
+ failures: 0,
669
+ lockedUntilMs: 0
670
+ };
671
+ return {
672
+ failures: state.count,
673
+ lockedUntilMs: state.lockedUntilMs
674
+ };
675
+ }
676
+ /**
677
+ * Decide whether one request may proceed.
678
+ *
679
+ * @param req - the incoming request (HTTP or upgrade).
680
+ * @returns the verdict; `ok: false` carries why.
681
+ */
682
+ verifyRequest(req) {
683
+ if (!this.#auth.enabled) return {
684
+ ok: true,
685
+ via: "disabled"
686
+ };
687
+ const ip = clientIp(req);
688
+ if (this.#switches.allowLoopback() && isLoopbackAddress(req.socket.remoteAddress)) return {
689
+ ok: true,
690
+ via: "loopback"
691
+ };
692
+ const state = this.#failures.get(ip);
693
+ const now = this.#now();
694
+ if (state !== void 0 && state.lockedUntilMs > now) return {
695
+ ok: false,
696
+ reason: "locked",
697
+ lockedUntilMs: state.lockedUntilMs
698
+ };
699
+ if (this.#sessionIsValid(readCookie(req, "dsh_lan_guard_session"))) return {
700
+ ok: true,
701
+ via: "session"
702
+ };
703
+ return {
704
+ ok: false,
705
+ reason: "unauthorized"
706
+ };
707
+ }
708
+ /**
709
+ * Validate one visitor password and, on success, mint a session.
710
+ *
711
+ * @param req - the login request (for the client IP).
712
+ * @param password - the submitted password.
713
+ * @returns the session cookie to send, or why it failed.
714
+ */
715
+ async login(req, password) {
716
+ const ip = clientIp(req);
717
+ const now = this.#now();
718
+ const state = this.#failures.get(ip);
719
+ if (state !== void 0 && state.lockedUntilMs > now) return {
720
+ ok: false,
721
+ reason: "locked",
722
+ lockedUntilMs: state.lockedUntilMs
723
+ };
724
+ if (!this.hasPassword) return {
725
+ ok: false,
726
+ reason: "no-password"
727
+ };
728
+ if (!await verifyPassword(password, this.#secrets.passwordSalt, this.#secrets.passwordHash)) {
729
+ const lockedUntilMs = this.#recordFailure(ip);
730
+ return lockedUntilMs > 0 ? {
731
+ ok: false,
732
+ reason: "locked",
733
+ lockedUntilMs
734
+ } : {
735
+ ok: false,
736
+ reason: "invalid"
737
+ };
738
+ }
739
+ this.#failures.delete(ip);
740
+ const token = randomBytes(32).toString("base64url");
741
+ const expiresAtMs = now + this.#auth.sessionMaxAgeMs;
742
+ this.#sessions.set(token, {
743
+ token,
744
+ expiresAtMs,
745
+ createdAtMs: now
746
+ });
747
+ await this.#persistSessions();
748
+ return {
749
+ ok: true,
750
+ cookie: buildSessionCookie(SESSION_COOKIE, token, expiresAtMs, now),
751
+ expiresAtMs
752
+ };
753
+ }
754
+ /** Verify a candidate against the access password (the "change password" flow). */
755
+ async verifyAccessPassword(candidate) {
756
+ return verifyPassword(candidate, this.#secrets.passwordSalt, this.#secrets.passwordHash);
757
+ }
758
+ /** Verify a candidate against the admin password, falling back to the access password when unset. */
759
+ async verifyAdminPassword(candidate) {
760
+ const useAdmin = this.hasAdminPassword;
761
+ return verifyPassword(candidate, useAdmin ? this.#secrets.adminPasswordSalt : this.#secrets.passwordSalt, useAdmin ? this.#secrets.adminPasswordHash : this.#secrets.passwordHash);
762
+ }
763
+ /** Validate the passwordless-link token. */
764
+ async verifySecretToken(candidate) {
765
+ const token = this.#secrets.secretToken;
766
+ if (token === null || token === "") return false;
767
+ return safeEqual(candidate, token);
768
+ }
769
+ /** Mint a session without a password (a validated passwordless link). */
770
+ async issueSession() {
771
+ const now = this.#now();
772
+ const token = randomBytes(32).toString("base64url");
773
+ const expiresAtMs = now + this.#auth.sessionMaxAgeMs;
774
+ this.#sessions.set(token, {
775
+ token,
776
+ expiresAtMs,
777
+ createdAtMs: now
778
+ });
779
+ await this.#persistSessions();
780
+ return {
781
+ cookie: buildSessionCookie(SESSION_COOKIE, token, expiresAtMs, now),
782
+ expiresAtMs
783
+ };
784
+ }
785
+ /**
786
+ * Validate the admin password and unlock the management surface.
787
+ *
788
+ * Deliberately independent of any visitor session: the researched
789
+ * dsh-bridge deadlock was an unlock that required a valid visitor session,
790
+ * so an expired session made the management console permanently unlockable
791
+ * (docs/RESEARCH.md §5.5).
792
+ *
793
+ * @param password - the submitted admin password (falls back to the access password when unset).
794
+ * @returns the admin cookie, or `undefined` when the password is wrong.
795
+ */
796
+ async unlockAdmin(password) {
797
+ const useAdmin = this.hasAdminPassword;
798
+ if (!await verifyPassword(password, useAdmin ? this.#secrets.adminPasswordSalt : this.#secrets.passwordSalt, useAdmin ? this.#secrets.adminPasswordHash : this.#secrets.passwordHash)) return void 0;
799
+ const now = this.#now();
800
+ const token = randomBytes(32).toString("base64url");
801
+ const expiresAtMs = now + this.#auth.adminSessionMaxAgeMs;
802
+ this.#adminSessions.set(token, expiresAtMs);
803
+ return {
804
+ cookie: buildSessionCookie(ADMIN_COOKIE, token, expiresAtMs, now),
805
+ expiresAtMs
806
+ };
807
+ }
808
+ /** Lock the management surface again. */
809
+ lockAdmin(req) {
810
+ const token = readCookie(req, ADMIN_COOKIE);
811
+ if (token !== void 0) this.#adminSessions.delete(token);
812
+ }
813
+ /** Whether this request carries a live admin session. */
814
+ isAdminUnlocked(req) {
815
+ if (!this.#switches.adminProtection()) return true;
816
+ const token = readCookie(req, ADMIN_COOKIE);
817
+ if (token === void 0) return false;
818
+ const expiresAtMs = this.#adminSessions.get(token);
819
+ if (expiresAtMs === void 0) return false;
820
+ if (expiresAtMs <= this.#now()) {
821
+ this.#adminSessions.delete(token);
822
+ return false;
823
+ }
824
+ return true;
825
+ }
826
+ /** Whether the admin surface should be shown locked, given the policy. */
827
+ requiresAdminUnlock(req) {
828
+ if (this.#switches.adminPolicy() === "open") return false;
829
+ if (this.#switches.adminPolicy() === "local_only") return !isLoopbackAddress(req.socket.remoteAddress);
830
+ return !this.isAdminUnlocked(req);
831
+ }
832
+ /** Validate a session cookie without touching failure counters. */
833
+ #sessionIsValid(token) {
834
+ if (token === void 0) return false;
835
+ const record = this.#sessions.get(token);
836
+ if (record === void 0) return false;
837
+ if (record.expiresAtMs <= this.#now()) {
838
+ this.#sessions.delete(token);
839
+ return false;
840
+ }
841
+ return true;
842
+ }
843
+ /** Record a failed attempt and report when the lockout ends (0 = not locked). */
844
+ #recordFailure(ip) {
845
+ const now = this.#now();
846
+ const count = (this.#failures.get(ip) ?? {
847
+ count: 0,
848
+ lockedUntilMs: 0
849
+ }).count + 1;
850
+ if (count >= this.#auth.maxFailedAttempts) {
851
+ const lockedUntilMs = now + this.#auth.lockoutMs;
852
+ this.#failures.set(ip, {
853
+ count: 0,
854
+ lockedUntilMs
855
+ });
856
+ this.#logger.warn("visitor lockout engaged failures=%d lockoutMs=%d", count, this.#auth.lockoutMs);
857
+ return lockedUntilMs;
858
+ }
859
+ this.#failures.set(ip, {
860
+ count,
861
+ lockedUntilMs: 0
862
+ });
863
+ return 0;
864
+ }
865
+ /** Persist the live visitor sessions (admin sessions stay in memory). */
866
+ async #persistSessions() {
867
+ await this.#store.saveSessions([...this.#sessions.values()]);
868
+ }
869
+ /**
870
+ * Drop every visitor session.
871
+ *
872
+ * Called when the access password or the auth mode changes: otherwise a phone
873
+ * that already logged in keeps its 30-day session and never sees the new
874
+ * requirement (user report 2026-09-24: "我改成了需要密码,但用户却不需要输入").
875
+ *
876
+ * @returns how many sessions were dropped.
877
+ */
878
+ async revokeAllSessions() {
879
+ const dropped = this.#sessions.size;
880
+ this.#sessions.clear();
881
+ this.#adminSessions.clear();
882
+ await this.#persistSessions();
883
+ if (dropped > 0) this.#logger.warn("all visitor sessions revoked count=%d", dropped);
884
+ return dropped;
885
+ }
886
+ /** Drop expired sessions and persist the remainder. */
887
+ async #sweep() {
888
+ const now = this.#now();
889
+ let changed = false;
890
+ for (const [token, record] of this.#sessions) if (record.expiresAtMs <= now) {
891
+ this.#sessions.delete(token);
892
+ changed = true;
893
+ }
894
+ for (const [token, expiresAtMs] of this.#adminSessions) if (expiresAtMs <= now) this.#adminSessions.delete(token);
895
+ if (changed) await this.#persistSessions();
896
+ }
897
+ };
898
+ /** The client IP used for lockout accounting. */
899
+ function clientIp(req) {
900
+ return req.socket.remoteAddress ?? "unknown";
901
+ }
902
+ /**
903
+ * Whether a state-changing request passes the CSRF check
904
+ * (docs/SPEC.md F3/§6.5).
905
+ *
906
+ * A malicious page on the LAN can reach the proxy port, so a same-origin
907
+ * check is required on every state change: `Sec-Fetch-Site: cross-site` is
908
+ * refused outright, and when an `Origin` is present its host must equal the
909
+ * request's Host.
910
+ *
911
+ * @param req - the state-changing request.
912
+ * @returns true when the request may proceed.
913
+ */
914
+ function passesCsrfCheck(req) {
915
+ const site = req.headers["sec-fetch-site"];
916
+ if (site === "cross-site") return false;
917
+ if (site === "same-origin" || site === "same-site" || site === "none") return true;
918
+ const origin = req.headers.origin;
919
+ if (origin === void 0 || origin === "null") return true;
920
+ const host = req.headers.host;
921
+ if (host === void 0) return false;
922
+ try {
923
+ const parsed = new URL(origin);
924
+ return parsed.host === host || parsed.hostname === host.split(":")[0];
925
+ } catch {
926
+ return true;
927
+ }
928
+ }
929
+ //#endregion
930
+ //#region src/auth/login-page.ts
931
+ /**
932
+ * Render the device-pairing page (P4-g).
933
+ *
934
+ * Shown to a device that has just passed the password/link gate but carries no
935
+ * device identity: naming it is what makes the "已授权设备" list meaningful and
936
+ * what makes a later revoke effective (user request 2026-09-24, modelled on
937
+ * dsh-mobile's pairing screen).
938
+ */
939
+ function renderPairingPage(options) {
940
+ const notice = options.error === "csrf" ? "<p class=\"notice error\">请求来源校验未通过,请重新提交。</p>" : options.error === "invalid" ? "<p class=\"notice error\">设备名称不能为空。</p>" : "";
941
+ return `<!doctype html>
942
+ <html lang="zh-CN">
943
+ <head>
944
+ <meta charset="utf-8">
945
+ <meta name="viewport" content="width=device-width,initial-scale=1">
946
+ <meta name="robots" content="noindex,nofollow">
947
+ <title>确认设备 · DSH 局域网访问</title>
948
+ <style>${LOGIN_CSS}</style>
949
+ </head>
950
+ <body>
951
+ <main class="card">
952
+ <h1>确认这台设备</h1>
953
+ <p class="sub">给它起个名字,方便你在「已授权设备」里识别、也方便日后单独吊销。</p>
954
+ ${notice}
955
+ <div class="lg-mono-static">来源地址:${escapeHtml(options.ip)}</div>
956
+ <form method="post" action="/__dsh_lan_guard__/pair" autocomplete="off">
957
+ <label for="label">设备名称</label>
958
+ <input id="label" name="label" type="text" value="${escapeHtml(options.defaultLabel)}" autofocus required>
959
+ <button type="submit">确认并进入 DSH</button>
960
+ </form>
961
+ <p class="hint">管理员随时可以在设置页吊销这台设备;吊销后本设备需要重新确认。</p>
962
+ </main>
963
+ </body>
964
+ </html>
965
+ `;
966
+ }
967
+ /** Escape text for HTML text nodes and attribute values. */
968
+ function escapeHtml(value) {
969
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;").replaceAll("'", "&#39;");
970
+ }
971
+ /** Human-readable remaining lockout time. */
972
+ function remainingSeconds(lockedUntilMs, now) {
973
+ if (lockedUntilMs === void 0) return 0;
974
+ return Math.max(0, Math.ceil((lockedUntilMs - now) / 1e3));
975
+ }
976
+ const LOGIN_CSS = `
977
+ :root{color-scheme:light dark}
978
+ *{box-sizing:border-box}
979
+ body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;
980
+ background:var(--dsw-alias-bg-base,#f6f7f9);color:var(--dsw-alias-text-primary,#1f2329);
981
+ font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"PingFang SC","Microsoft YaHei",sans-serif}
982
+ .card{width:min(400px,calc(100vw - 32px));background:var(--dsw-alias-bg-elevated,#fff);
983
+ border:1px solid var(--dsw-alias-border-subtle,#e5e6eb);border-radius:14px;padding:24px;
984
+ box-shadow:0 8px 28px rgba(0,0,0,.06)}
985
+ h1{margin:0 0 6px;font-size:18px}
986
+ .sub{margin:0 0 18px;font-size:13px;color:var(--dsw-alias-text-secondary,#6b7280)}
987
+ label{display:block;font-size:13px;margin:0 0 6px;color:var(--dsw-alias-text-secondary,#6b7280)}
988
+ input[type=password],input[type=text]{width:100%;height:44px;padding:0 12px;font-size:16px;border-radius:10px;
989
+ border:1px solid var(--dsw-alias-border-subtle,#d0d3d9);background:var(--dsw-alias-bg-base,#fff);
990
+ color:var(--dsw-alias-text-primary,#1f2329)}
991
+ input[type=password]:focus{outline:2px solid var(--dsw-alias-brand-primary,#4f46e5);outline-offset:1px}
992
+ button{width:100%;height:44px;margin-top:14px;border:0;border-radius:10px;font-size:15px;font-weight:600;
993
+ color:#fff;background:var(--dsw-alias-brand-primary,#4f46e5);cursor:pointer}
994
+ button:disabled{opacity:.6;cursor:not-allowed}
995
+ .notice{margin:0 0 16px;padding:10px 12px;border-radius:10px;font-size:13px;line-height:1.5}
996
+ .notice.error{background:var(--dsw-alias-bg-danger,#fef2f2);color:var(--dsw-alias-text-danger,#b91c1c);
997
+ border:1px solid var(--dsw-alias-border-danger,#fecaca)}
998
+ .notice.warn{background:var(--dsw-alias-bg-warning,#fffbeb);color:var(--dsw-alias-text-warning,#92400e);
999
+ border:1px solid var(--dsw-alias-border-warning,#fde68a)}
1000
+ .hint{margin:14px 0 0;font-size:12px;line-height:1.6;color:var(--dsw-alias-text-secondary,#6b7280)}
1001
+ .lg-mono-static{margin:0 0 16px;padding:10px 12px;border-radius:10px;background:var(--dsw-alias-bg-secondary,#f1f2f4);
1002
+ font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px;color:var(--dsw-alias-text-primary,#1f2329)}
1003
+ @media (hover:none) and (pointer:coarse){button,input[type=password]{height:48px}}
1004
+ `.trim();
1005
+ /** Build the state-specific notice block. */
1006
+ function notice(state, lockedUntilMs, now) {
1007
+ if (state === "invalid") return "<p class=\"notice error\">密码错误,请重试。</p>";
1008
+ if (state === "locked") {
1009
+ const seconds = remainingSeconds(lockedUntilMs, now);
1010
+ return `<p class="notice error">尝试次数过多,该地址已被临时锁定${seconds > 0 ? `,请在约 ${String(seconds)} 秒后重试` : ",请稍后重试"}。</p>`;
1011
+ }
1012
+ if (state === "csrf") return "<p class=\"notice error\">请求来源校验未通过,请从本页重新登录。</p>";
1013
+ if (state === "device-removed") return "<p class=\"notice error\"><strong>此设备已被移除访问权限。</strong><br>请联系管理员在「已授权设备」中重新放行,或让管理员删除该记录后重新确认。</p>";
1014
+ if (state === "token-only") return "<p class=\"notice warn\">当前验证模式为<strong>仅安全 Token</strong>,不接受密码登录。请使用管理员提供的免密链接或二维码。</p>";
1015
+ if (state === "no-password") return "<p class=\"notice warn\"><strong>尚未设置访问密码。</strong><br>出于安全考虑,未设置密码时门禁不会放行任何设备。请在桌面 DSH 的「设置 → 局域网访问」中设置访问密码。</p>";
1016
+ return "";
1017
+ }
1018
+ /**
1019
+ * Render the login page.
1020
+ *
1021
+ * @param options - the state, the auth mode and optional lockout/redirect data.
1022
+ * @returns a complete HTML document.
1023
+ */
1024
+ function renderLoginPage(options) {
1025
+ const now = options.now ?? Date.now();
1026
+ const blocked = options.state === "locked" || options.state === "no-password" || options.state === "device-removed";
1027
+ const next = options.next !== void 0 && options.next.startsWith("/") ? options.next : "/";
1028
+ const modeHint = options.mode === "password" ? "本设备需要输入访问密码。" : options.mode === "token" ? "本设备使用免密链接访问;如已失效,请向管理员索取新的二维码。" : "输入访问密码,或使用管理员提供的免密链接。";
1029
+ return `<!doctype html>
1030
+ <html lang="zh-CN">
1031
+ <head>
1032
+ <meta charset="utf-8">
1033
+ <meta name="viewport" content="width=device-width,initial-scale=1">
1034
+ <meta name="robots" content="noindex,nofollow">
1035
+ <title>需要访问密码 · DSH 局域网访问</title>
1036
+ <style>${LOGIN_CSS}</style>
1037
+ </head>
1038
+ <body>
1039
+ <main class="card">
1040
+ <h1>局域网访问</h1>
1041
+ <p class="sub">${escapeHtml(modeHint)}</p>
1042
+ ${notice(options.state, options.lockedUntilMs, now)}
1043
+ <form method="post" action="/__dsh_lan_guard__/login" autocomplete="off">
1044
+ <input type="hidden" name="next" value="${escapeHtml(next)}">
1045
+ <label for="password">访问密码</label>
1046
+ <input id="password" name="password" type="password" autocomplete="current-password"
1047
+ autofocus ${blocked ? "disabled" : ""} required>
1048
+ <button type="submit" ${blocked ? "disabled" : ""}>进入 DSH</button>
1049
+ </form>
1050
+ <p class="hint">此页面由 dsh-lan-guard 提供。密码通过 HTTPS 或局域网传输,请仅在可信网络中访问。</p>
1051
+ </main>
1052
+ </body>
1053
+ </html>
1054
+ `;
1055
+ }
1056
+ //#endregion
1057
+ //#region src/auth/gate.ts
1058
+ /** Path prefix the gate owns on the proxy origin. */
1059
+ const GATE_PREFIX = "/__dsh_lan_guard__";
1060
+ /** The login form's action path. */
1061
+ const LOGIN_PATH = `${GATE_PREFIX}/login`;
1062
+ /** The device-pairing form's action path. */
1063
+ const PAIR_PATH = `${GATE_PREFIX}/pair`;
1064
+ /** Largest accepted login body. */
1065
+ const MAX_LOGIN_BODY_BYTES = 4096;
1066
+ /** Guess a friendly device name from the User-Agent, as a pairing default. */
1067
+ function guessDeviceLabel(userAgent) {
1068
+ const ua = userAgent ?? "";
1069
+ if (/iPhone/i.test(ua)) return "我的 iPhone";
1070
+ if (/iPad/i.test(ua)) return "我的 iPad";
1071
+ if (/Android/i.test(ua)) return "我的 Android 设备";
1072
+ if (/Macintosh|Mac OS X/i.test(ua)) return "我的 Mac";
1073
+ if (/Windows/i.test(ua)) return "我的 Windows 电脑";
1074
+ if (/Linux/i.test(ua)) return "我的 Linux 设备";
1075
+ return "我的设备";
1076
+ }
1077
+ /** Whether a request accepts an HTML document. */
1078
+ function wantsHtml(req) {
1079
+ const accept = req.headers.accept;
1080
+ return typeof accept === "string" && accept.includes("text/html");
1081
+ }
1082
+ /** Whether a path belongs to the `/api` surface. */
1083
+ function isApiPath(pathname) {
1084
+ return pathname === "/api" || pathname.startsWith("/api/");
1085
+ }
1086
+ /** Validate a post-login redirect target: a local absolute path only. */
1087
+ function safeNextPath(candidate) {
1088
+ if (candidate === null || candidate === void 0) return "/";
1089
+ if (!candidate.startsWith("/") || candidate.startsWith("//")) return "/";
1090
+ return candidate;
1091
+ }
1092
+ /** The visitor gate. */
1093
+ var VisitorGate = class {
1094
+ #auth;
1095
+ #devices;
1096
+ #requirePairing;
1097
+ #logger;
1098
+ constructor(options) {
1099
+ this.#auth = options.auth;
1100
+ this.#devices = options.devices;
1101
+ this.#requirePairing = options.requirePairing ?? (() => false);
1102
+ this.#logger = options.logger ?? noopLogger;
1103
+ }
1104
+ /**
1105
+ * Handle one HTTP request.
1106
+ *
1107
+ * @param req - the visitor's request.
1108
+ * @param res - the response, owned when the gate returns `'handled'`.
1109
+ * @returns `'allow'` when the caller may forward the request upstream.
1110
+ */
1111
+ async handleHttp(req, res) {
1112
+ const url = new URL(req.url ?? "/", "http://dsh-lan-guard.invalid");
1113
+ if (url.pathname === LOGIN_PATH) {
1114
+ if (req.method === "POST") {
1115
+ await this.#handleLogin(req, res);
1116
+ return "handled";
1117
+ }
1118
+ if (req.method === "GET" || req.method === "HEAD") {
1119
+ this.#sendLoginPage(req, res, "prompt", 200);
1120
+ return "handled";
1121
+ }
1122
+ this.#sendJson(res, 405, {
1123
+ ok: false,
1124
+ error: "method_not_allowed"
1125
+ });
1126
+ return "handled";
1127
+ }
1128
+ if (url.pathname === PAIR_PATH) {
1129
+ if (req.method === "POST") {
1130
+ await this.#handlePair(req, res);
1131
+ return "handled";
1132
+ }
1133
+ this.#sendPairingPage(req, res);
1134
+ return "handled";
1135
+ }
1136
+ if (url.pathname.startsWith(`/__dsh_lan_guard__/`)) {
1137
+ this.#sendJson(res, 404, {
1138
+ ok: false,
1139
+ error: "not_found"
1140
+ });
1141
+ return "handled";
1142
+ }
1143
+ const deviceToken = readCookie(req, DEVICE_COOKIE);
1144
+ if (deviceToken !== void 0) {
1145
+ const device = this.#devices?.verify(deviceToken);
1146
+ if (device === void 0) {
1147
+ this.#logger.warn("refused a revoked or unknown device ip=%s", clientIp(req));
1148
+ this.#sendRemoved(req, res);
1149
+ return "handled";
1150
+ }
1151
+ await this.#devices?.touch(device.id, clientIp(req)).catch((error) => {
1152
+ this.#logger.warn("device touch failed name=%s", error.name);
1153
+ });
1154
+ return "allow";
1155
+ }
1156
+ const link = url.searchParams.get("auth");
1157
+ if (link !== null) return await this.#handleAuthLink(req, res, url, link);
1158
+ const verdict = await this.#auth.verifyRequest(req);
1159
+ if (verdict.ok) {
1160
+ if (this.#requirePairing() && verdict.via === "session") {
1161
+ this.#sendPairingPage(req, res);
1162
+ return "handled";
1163
+ }
1164
+ return "allow";
1165
+ }
1166
+ this.#sendUnauthorized(req, res, verdict);
1167
+ return "handled";
1168
+ }
1169
+ /**
1170
+ * Decide whether an upgrade may proceed.
1171
+ *
1172
+ * The caller must have attached its socket error handler BEFORE awaiting
1173
+ * this (docs/RESEARCH.md §5.7 ①).
1174
+ *
1175
+ * @param req - the upgrade request.
1176
+ * @returns `undefined` when the upgrade may proceed, else the status to send.
1177
+ */
1178
+ async verifyUpgrade(req) {
1179
+ const deviceToken = readCookie(req, DEVICE_COOKIE);
1180
+ if (deviceToken !== void 0) {
1181
+ const device = this.#devices?.verify(deviceToken);
1182
+ if (device === void 0) {
1183
+ this.#logger.warn("upgrade refused: revoked device ip=%s", clientIp(req));
1184
+ return {
1185
+ status: 403,
1186
+ reason: "device_revoked"
1187
+ };
1188
+ }
1189
+ await this.#devices?.touch(device.id, clientIp(req)).catch(() => void 0);
1190
+ return;
1191
+ }
1192
+ const verdict = await this.#auth.verifyRequest(req);
1193
+ if (!verdict.ok) {
1194
+ this.#logger.warn("upgrade refused reason=%s ip=%s", verdict.reason, clientIp(req));
1195
+ return {
1196
+ status: 401,
1197
+ reason: verdict.reason
1198
+ };
1199
+ }
1200
+ if (this.#requirePairing() && verdict.via === "session") return {
1201
+ status: 403,
1202
+ reason: "pairing_required"
1203
+ };
1204
+ }
1205
+ /** Create the device identity for a request that already passed the gate. */
1206
+ async #handlePair(req, res) {
1207
+ if (this.#devices === void 0) {
1208
+ this.#sendJson(res, 503, {
1209
+ ok: false,
1210
+ error: "pairing_unavailable"
1211
+ });
1212
+ return;
1213
+ }
1214
+ if (!passesCsrfCheck(req)) {
1215
+ this.#sendPairingPage(req, res, "csrf");
1216
+ return;
1217
+ }
1218
+ const verdict = await this.#auth.verifyRequest(req);
1219
+ if (!verdict.ok) {
1220
+ this.#sendUnauthorized(req, res, verdict);
1221
+ return;
1222
+ }
1223
+ const body = await readBody(req);
1224
+ const label = new URLSearchParams(body ?? "").get("label") ?? "";
1225
+ if (label.trim() === "") {
1226
+ this.#sendPairingPage(req, res, "invalid");
1227
+ return;
1228
+ }
1229
+ const { device, token } = await this.#devices.add(label);
1230
+ await this.#devices.touch(device.id, clientIp(req)).catch(() => void 0);
1231
+ const expiresAtMs = Date.now() + DEVICE_COOKIE_MAX_AGE_MS;
1232
+ res.writeHead(302, {
1233
+ location: "/",
1234
+ "set-cookie": buildSessionCookie(DEVICE_COOKIE, token, expiresAtMs, Date.now()),
1235
+ "cache-control": "no-store",
1236
+ "referrer-policy": "no-referrer"
1237
+ });
1238
+ res.end();
1239
+ }
1240
+ /** Serve the pairing page (HTML) or a JSON hint for API calls. */
1241
+ #sendPairingPage(req, res, error) {
1242
+ if (isApiPath(new URL(req.url ?? "/", "http://dsh-lan-guard.invalid").pathname) || !wantsHtml(req)) {
1243
+ this.#sendJson(res, 428, {
1244
+ ok: false,
1245
+ error: "pairing_required"
1246
+ });
1247
+ return;
1248
+ }
1249
+ const html = renderPairingPage({
1250
+ defaultLabel: guessDeviceLabel(req.headers["user-agent"]),
1251
+ ip: clientIp(req),
1252
+ ...error === void 0 ? {} : { error }
1253
+ });
1254
+ res.writeHead(200, {
1255
+ "content-type": "text/html; charset=utf-8",
1256
+ "cache-control": "no-store",
1257
+ "referrer-policy": "no-referrer",
1258
+ "x-content-type-options": "nosniff"
1259
+ });
1260
+ res.end(html);
1261
+ }
1262
+ /** Tell a revoked device it no longer has access. */
1263
+ #sendRemoved(req, res) {
1264
+ if (isApiPath(new URL(req.url ?? "/", "http://dsh-lan-guard.invalid").pathname) || !wantsHtml(req)) {
1265
+ this.#sendJson(res, 403, {
1266
+ ok: false,
1267
+ error: "device_revoked"
1268
+ });
1269
+ return;
1270
+ }
1271
+ const html = renderLoginPage({
1272
+ state: "device-removed",
1273
+ mode: this.#auth.mode
1274
+ });
1275
+ res.writeHead(403, {
1276
+ "content-type": "text/html; charset=utf-8",
1277
+ "cache-control": "no-store",
1278
+ "referrer-policy": "no-referrer"
1279
+ });
1280
+ res.end(html);
1281
+ }
1282
+ /** Exchange a passwordless link for a session, then redirect to the clean URL. */
1283
+ async #handleAuthLink(req, res, url, link) {
1284
+ if (this.#auth.mode === "password") {
1285
+ const verdict = await this.#auth.verifyRequest(req);
1286
+ if (verdict.ok) return "allow";
1287
+ this.#sendUnauthorized(req, res, verdict);
1288
+ return "handled";
1289
+ }
1290
+ const masterAccepted = await this.#auth.verifySecretToken(link);
1291
+ const device = masterAccepted ? void 0 : this.#devices?.verify(link);
1292
+ if (!(masterAccepted || device !== void 0)) {
1293
+ this.#logger.warn("passwordless link rejected ip=%s", clientIp(req));
1294
+ const verdict = await this.#auth.verifyRequest(req);
1295
+ if (verdict.ok) return "allow";
1296
+ this.#sendUnauthorized(req, res, verdict);
1297
+ return "handled";
1298
+ }
1299
+ const session = await this.#auth.issueSession();
1300
+ if (device !== void 0) await this.#devices?.touch(device.id, clientIp(req));
1301
+ const clean = new URL(url.toString());
1302
+ clean.searchParams.delete("auth");
1303
+ res.writeHead(302, {
1304
+ location: `${clean.pathname}${clean.search}`,
1305
+ "set-cookie": session.cookie,
1306
+ "cache-control": "no-store",
1307
+ "referrer-policy": "no-referrer"
1308
+ });
1309
+ res.end();
1310
+ return "handled";
1311
+ }
1312
+ /** Handle the login form submission. */
1313
+ async #handleLogin(req, res) {
1314
+ if (!passesCsrfCheck(req)) {
1315
+ this.#logger.warn("login refused by csrf check sec-fetch-site=%s origin=%s host=%s", req.headers["sec-fetch-site"] ?? "(none)", req.headers.origin ?? "(none)", req.headers.host ?? "(none)");
1316
+ this.#sendLoginPage(req, res, "csrf", 403);
1317
+ return;
1318
+ }
1319
+ if (this.#auth.mode === "token") {
1320
+ this.#sendLoginPage(req, res, "token-only", 403);
1321
+ return;
1322
+ }
1323
+ const body = await readBody(req);
1324
+ if (body === void 0) {
1325
+ this.#sendJson(res, 413, {
1326
+ ok: false,
1327
+ error: "body_too_large"
1328
+ });
1329
+ return;
1330
+ }
1331
+ const form = new URLSearchParams(body);
1332
+ const password = form.get("password") ?? "";
1333
+ const next = safeNextPath(form.get("next"));
1334
+ const result = await this.#auth.login(req, password);
1335
+ if (result.ok) {
1336
+ res.writeHead(302, {
1337
+ location: next,
1338
+ "set-cookie": result.cookie,
1339
+ "cache-control": "no-store",
1340
+ "referrer-policy": "no-referrer"
1341
+ });
1342
+ res.end();
1343
+ return;
1344
+ }
1345
+ if (result.reason === "locked") {
1346
+ this.#sendLoginPage(req, res, "locked", 429, result.lockedUntilMs);
1347
+ return;
1348
+ }
1349
+ if (result.reason === "no-password") {
1350
+ this.#sendLoginPage(req, res, "no-password", 403);
1351
+ return;
1352
+ }
1353
+ this.#sendLoginPage(req, res, "invalid", 401);
1354
+ }
1355
+ /** Answer a refused request with the login page or a JSON error. */
1356
+ #sendUnauthorized(req, res, verdict) {
1357
+ const url = new URL(req.url ?? "/", "http://dsh-lan-guard.invalid");
1358
+ const lockedUntilMs = verdict.ok ? void 0 : verdict.lockedUntilMs;
1359
+ if (verdict.ok || verdict.reason !== "locked") this.#logger.info("request refused reason=%s ip=%s", verdict.ok ? "ok" : verdict.reason, clientIp(req));
1360
+ if (!this.#auth.hasPassword) {
1361
+ if (wantsHtml(req)) {
1362
+ this.#sendLoginPage(req, res, "no-password", 403);
1363
+ return;
1364
+ }
1365
+ this.#sendJson(res, 403, {
1366
+ ok: false,
1367
+ error: "no_password_configured"
1368
+ });
1369
+ return;
1370
+ }
1371
+ if (verdict.ok === false && verdict.reason === "locked") {
1372
+ if (wantsHtml(req)) {
1373
+ this.#sendLoginPage(req, res, "locked", 429, lockedUntilMs);
1374
+ return;
1375
+ }
1376
+ this.#sendJson(res, 429, {
1377
+ ok: false,
1378
+ error: "locked",
1379
+ lockedUntilMs: lockedUntilMs ?? 0
1380
+ });
1381
+ return;
1382
+ }
1383
+ if (isApiPath(url.pathname) || !wantsHtml(req)) {
1384
+ this.#sendJson(res, 401, {
1385
+ ok: false,
1386
+ error: "unauthorized"
1387
+ });
1388
+ return;
1389
+ }
1390
+ const next = safeNextPath(`${url.pathname}${url.search}`);
1391
+ this.#sendLoginPage(req, res, "prompt", 401, void 0, next);
1392
+ }
1393
+ /** Write the login page. */
1394
+ #sendLoginPage(req, res, state, status, lockedUntilMs, next) {
1395
+ const html = renderLoginPage({
1396
+ state,
1397
+ mode: this.#auth.mode,
1398
+ ...lockedUntilMs === void 0 ? {} : { lockedUntilMs },
1399
+ ...next === void 0 ? {} : { next }
1400
+ });
1401
+ res.writeHead(status, {
1402
+ "content-type": "text/html; charset=utf-8",
1403
+ "cache-control": "no-store",
1404
+ "referrer-policy": "no-referrer",
1405
+ "x-content-type-options": "nosniff"
1406
+ });
1407
+ res.end(req.method === "HEAD" ? void 0 : html);
1408
+ }
1409
+ /** Write a JSON error. */
1410
+ #sendJson(res, status, body) {
1411
+ res.writeHead(status, {
1412
+ "content-type": "application/json; charset=utf-8",
1413
+ "cache-control": "no-store"
1414
+ });
1415
+ res.end(`${JSON.stringify(body)}\n`);
1416
+ }
1417
+ };
1418
+ /** Read a small request body, or `undefined` when it exceeds the limit. */
1419
+ async function readBody(req) {
1420
+ const chunks = [];
1421
+ let size = 0;
1422
+ for await (const chunk of req) {
1423
+ const buffer = chunk;
1424
+ size += buffer.length;
1425
+ if (size > MAX_LOGIN_BODY_BYTES) return void 0;
1426
+ chunks.push(buffer);
1427
+ }
1428
+ return Buffer.concat(chunks).toString("utf8");
1429
+ }
1430
+ //#endregion
1431
+ //#region src/mdns.ts
1432
+ /**
1433
+ * dsh-lan-guard — optional mDNS/DNS-SD advertisement (P4-d).
1434
+ *
1435
+ * OFF BY DEFAULT (`mdns.enabled: false`): advertising a service on the LAN is a
1436
+ * new, discoverable surface, and this project's stance everywhere else is
1437
+ * "closed unless explicitly opened". When enabled, phones that speak mDNS can
1438
+ * find the console without typing an address.
1439
+ *
1440
+ * Honest limits (documented in README): iOS Safari and Android Chrome do NOT
1441
+ * resolve `.local` names for arbitrary web pages in practice, so mDNS helps
1442
+ * discovery tools and desktop browsers more than phone browsers. The QR code
1443
+ * remains the reliable path on a phone.
1444
+ *
1445
+ * The publisher is injectable so the lifecycle is testable without multicast.
1446
+ */
1447
+ /** Service type advertised as `_dsh-lan-guard._tcp`. */
1448
+ const MDNS_SERVICE_TYPE = "dsh-lan-guard";
1449
+ /** Default instance name. */
1450
+ const MDNS_INSTANCE_NAME = "DSH 局域网访问";
1451
+ /** Build the advertisement for a running listener. */
1452
+ function mdnsAdvertisement(input) {
1453
+ const scheme = input.secure ? "https" : "http";
1454
+ const url = input.address === null ? null : `${scheme}://${input.address}:${String(input.port)}/`;
1455
+ return {
1456
+ name: MDNS_INSTANCE_NAME,
1457
+ type: MDNS_SERVICE_TYPE,
1458
+ port: input.port,
1459
+ txt: {
1460
+ scheme,
1461
+ ...url === null ? {} : { url },
1462
+ ...input.address === null ? {} : { host: input.address }
1463
+ }
1464
+ };
1465
+ }
1466
+ /**
1467
+ * Start advertising, containing any failure.
1468
+ *
1469
+ * @param options - the advertisement plus an optional publisher (tests).
1470
+ * @returns a handle whose `stop()` tears the advertisement down.
1471
+ */
1472
+ function startMdns(options) {
1473
+ const logger = options.logger ?? noopLogger;
1474
+ let publisher;
1475
+ try {
1476
+ publisher = options.publisher ?? new Bonjour();
1477
+ } catch (error) {
1478
+ logger.warn("mdns unavailable name=%s", error.name);
1479
+ return { stop() {} };
1480
+ }
1481
+ try {
1482
+ publisher.publish(options.advertisement);
1483
+ logger.info("mdns advertising type=_%s._tcp port=%d", options.advertisement.type, options.advertisement.port);
1484
+ } catch (error) {
1485
+ logger.warn("mdns publish failed name=%s", error.name);
1486
+ return { stop() {} };
1487
+ }
1488
+ let stopped = false;
1489
+ return { stop() {
1490
+ if (stopped) return;
1491
+ stopped = true;
1492
+ try {
1493
+ publisher.unpublishAll(() => {
1494
+ try {
1495
+ publisher.destroy();
1496
+ } catch {}
1497
+ });
1498
+ } catch (error) {
1499
+ logger.warn("mdns unpublish failed name=%s", error.name);
1500
+ }
1501
+ } };
1502
+ }
1503
+ //#endregion
1504
+ //#region src/network.ts
1505
+ /**
1506
+ * dsh-lan-guard — network interface discovery (docs/SPEC.md F5).
1507
+ *
1508
+ * The LAN address a phone must type depends on which NIC is actually on the
1509
+ * same network. Virtual adapters (WSL, VMware, Docker, Tailscale, VPN tunnels)
1510
+ * usually have an address that looks fine but is unreachable from the phone, so
1511
+ * they are reported but DOWN-RANKED rather than hidden: hiding them would make
1512
+ * a legitimate VPN-only setup impossible, and ranking them first would make the
1513
+ * common case wrong.
1514
+ */
1515
+ /** Interface-name prefixes that almost never serve a phone on the same Wi-Fi. */
1516
+ const VIRTUAL_INTERFACE_PATTERNS = [
1517
+ {
1518
+ pattern: /^(bridge|docker|veth|virbr|vmnet|vboxnet)/i,
1519
+ reason: "container/virtual bridge"
1520
+ },
1521
+ {
1522
+ pattern: /^(utun|tun|tap|wg|ppp|ipsec|tailscale)/i,
1523
+ reason: "VPN or tunnel"
1524
+ },
1525
+ {
1526
+ pattern: /^(awdl|llw|ap\d)/i,
1527
+ reason: "Apple peer-to-peer / hotspot"
1528
+ }
1529
+ ];
1530
+ /** Address ranges that are never a phone-reachable LAN address. */
1531
+ const NON_ROUTABLE_PREFIXES = [
1532
+ "169.254.",
1533
+ "172.17.",
1534
+ "172.18.",
1535
+ "172.19."
1536
+ ];
1537
+ /** Whether an address is IPv4 and not loopback / link-local. */
1538
+ function isUsable(address, family) {
1539
+ if (family !== "IPv4" && family !== 4) return false;
1540
+ if (address.startsWith("127.")) return false;
1541
+ return true;
1542
+ }
1543
+ /** Classify one interface/address pair as virtual (down-ranked) or real. */
1544
+ function classifyInterface(name, address) {
1545
+ for (const entry of VIRTUAL_INTERFACE_PATTERNS) if (entry.pattern.test(name)) return {
1546
+ virtual: true,
1547
+ reason: entry.reason
1548
+ };
1549
+ for (const prefix of NON_ROUTABLE_PREFIXES) if (address.startsWith(prefix)) return {
1550
+ virtual: true,
1551
+ reason: "non-routable private range"
1552
+ };
1553
+ return { virtual: false };
1554
+ }
1555
+ /**
1556
+ * Enumerate the machine's non-internal IPv4 addresses, best candidate first.
1557
+ *
1558
+ * @returns addresses sorted by rank (real Wi-Fi/Ethernet first, virtual last).
1559
+ */
1560
+ function listNetworkAddresses() {
1561
+ const found = [];
1562
+ for (const [name, entries] of Object.entries(networkInterfaces())) for (const entry of entries ?? []) {
1563
+ if (!isUsable(entry.address, entry.family)) continue;
1564
+ const { virtual, reason } = classifyInterface(name, entry.address);
1565
+ found.push({
1566
+ interface: name,
1567
+ address: entry.address,
1568
+ netmask: entry.netmask,
1569
+ virtual,
1570
+ ...reason === void 0 ? {} : { virtualReason: reason },
1571
+ rank: virtual ? 1 : 0
1572
+ });
1573
+ }
1574
+ return found.sort((left, right) => left.rank - right.rank || left.interface.localeCompare(right.interface) || left.address.localeCompare(right.address));
1575
+ }
1576
+ /**
1577
+ * Pick the address a phone should use.
1578
+ *
1579
+ * @param addresses - the enumerated list.
1580
+ * @param preferredInterface - an explicit `networkInterface` from config, if any.
1581
+ * @returns the chosen address, or `undefined` when nothing is usable.
1582
+ */
1583
+ function selectAddress(addresses, preferredInterface) {
1584
+ if (preferredInterface !== void 0 && preferredInterface !== null && preferredInterface !== "") {
1585
+ const match = addresses.find((entry) => entry.interface === preferredInterface);
1586
+ if (match !== void 0) return match;
1587
+ const byAddress = addresses.find((entry) => entry.address === preferredInterface);
1588
+ if (byAddress !== void 0) return byAddress;
1589
+ return;
1590
+ }
1591
+ return addresses[0];
1592
+ }
1593
+ /**
1594
+ * Build the visitor URL for one address.
1595
+ *
1596
+ * @param address - the chosen address.
1597
+ * @param port - the proxy port.
1598
+ * @param secure - whether the listener serves TLS.
1599
+ * @returns the URL a phone can open.
1600
+ */
1601
+ function accessUrl(address, port, secure) {
1602
+ return `${secure ? "https" : "http"}://${address}:${String(port)}/`;
1603
+ }
1604
+ //#endregion
1605
+ //#region src/headers.ts
1606
+ /** Hop-by-hop headers that must not be forwarded in either direction (RFC 9110 §7.6.1). */
1607
+ const HOP_BY_HOP_HEADERS = [
1608
+ "connection",
1609
+ "keep-alive",
1610
+ "proxy-authenticate",
1611
+ "proxy-authorization",
1612
+ "proxy-connection",
1613
+ "te",
1614
+ "trailer",
1615
+ "transfer-encoding",
1616
+ "upgrade"
1617
+ ];
1618
+ /**
1619
+ * Headers a WebSocket 101 may carry upstream → browser. Everything else the
1620
+ * upstream sends is dropped (docs/RESEARCH.md §5.3).
1621
+ */
1622
+ const UPGRADE_RESPONSE_HEADERS = [
1623
+ "connection",
1624
+ "upgrade",
1625
+ "sec-websocket-accept",
1626
+ "sec-websocket-extensions",
1627
+ "sec-websocket-protocol"
1628
+ ];
1629
+ /**
1630
+ * Header the proxy stamps on every request it forwards upstream.
1631
+ *
1632
+ * The proxy rewrites `host` to loopback, so DSH's own web server cannot tell a
1633
+ * request that came from this machine from one that came in over the LAN. The
1634
+ * management surface needs that distinction — "127.0.0.1 has physical
1635
+ * unlock privilege, remote access must be locked" (user decision 2026-09-24) —
1636
+ * so the proxy marks what it forwards. The incoming copy is DELETED first, so a
1637
+ * visitor cannot forge the marker on a direct request.
1638
+ */
1639
+ const VISITOR_HEADER = "x-dsh-lan-guard-visitor";
1640
+ /** Request headers the proxy always replaces, never forwards verbatim. */
1641
+ const REPLACED_REQUEST_HEADERS = [
1642
+ "host",
1643
+ "origin",
1644
+ "cookie",
1645
+ VISITOR_HEADER
1646
+ ];
1647
+ /** Response headers dropped on top of the hop-by-hop set. */
1648
+ const DROPPED_RESPONSE_HEADERS = ["set-cookie"];
1649
+ /**
1650
+ * The `host:port` authority of an origin URL — the value the upstream fence
1651
+ * binds cookies to.
1652
+ *
1653
+ * @param origin - an absolute http(s) origin.
1654
+ * @returns the authority, e.g. `127.0.0.1:3080`.
1655
+ * @throws when the origin cannot be parsed.
1656
+ */
1657
+ function authorityOf(origin) {
1658
+ return new URL(origin).host;
1659
+ }
1660
+ /**
1661
+ * Normalize a request target before forwarding.
1662
+ *
1663
+ * Node hands us the raw request target. A bare-origin request already arrives
1664
+ * as `/`, but an absolute-form target (or a target with no path at all) must
1665
+ * still land on `/`, because the shipped shell carries `<base href="./">` and
1666
+ * resolves every relative asset against the directory it was served from
1667
+ * (docs/RESEARCH.md §7.1). We mount at the root only, so no prefix is ever
1668
+ * stripped and no target is rewritten beyond this normalization.
1669
+ *
1670
+ * @param rawTarget - `req.url` as received.
1671
+ * @returns a root-relative path plus its exact query string.
1672
+ */
1673
+ function normalizeRequestTarget(rawTarget) {
1674
+ if (rawTarget === void 0 || rawTarget === "") return "/";
1675
+ if (rawTarget === "*") return "*";
1676
+ if (rawTarget.startsWith("/")) return rawTarget;
1677
+ if (rawTarget.startsWith("?")) return `/${rawTarget}`;
1678
+ try {
1679
+ const url = new URL(rawTarget);
1680
+ return `${url.pathname === "" ? "/" : url.pathname}${url.search}`;
1681
+ } catch {
1682
+ return rawTarget.startsWith("?") ? `/${rawTarget}` : `/${rawTarget}`;
1683
+ }
1684
+ }
1685
+ /**
1686
+ * Build the header set sent upstream.
1687
+ *
1688
+ * @param input.headers - the visitor's request headers.
1689
+ * @param input.authority - upstream `host:port`.
1690
+ * @param input.upstreamCookie - the loopback session cookie to inject, if known.
1691
+ * @param input.upgrade - true for a WebSocket upgrade (keeps `connection`/`upgrade`).
1692
+ * @returns headers safe to hand to `http.request`.
1693
+ */
1694
+ function buildUpstreamRequestHeaders(input) {
1695
+ const outgoing = {};
1696
+ const hopByHop = new Set(HOP_BY_HOP_HEADERS);
1697
+ const replaced = new Set(REPLACED_REQUEST_HEADERS);
1698
+ for (const [name, value] of Object.entries(input.headers)) {
1699
+ if (value === void 0) continue;
1700
+ const lower = name.toLowerCase();
1701
+ if (replaced.has(lower)) continue;
1702
+ if (hopByHop.has(lower) && !input.upgrade) continue;
1703
+ outgoing[lower] = value;
1704
+ }
1705
+ outgoing[VISITOR_HEADER] = "1";
1706
+ outgoing.host = input.authority;
1707
+ if (input.headers.origin !== void 0) outgoing.origin = `http://${input.authority}`;
1708
+ if (input.upstreamCookie !== void 0 && input.upstreamCookie !== "") outgoing.cookie = input.upstreamCookie;
1709
+ return outgoing;
1710
+ }
1711
+ /**
1712
+ * Filter an upstream response's headers for the browser.
1713
+ *
1714
+ * @param headers - upstream response headers.
1715
+ * @returns headers safe to write to the visitor's response.
1716
+ */
1717
+ function buildUpstreamResponseHeaders(headers) {
1718
+ const outgoing = {};
1719
+ const dropped = /* @__PURE__ */ new Set([...HOP_BY_HOP_HEADERS, ...DROPPED_RESPONSE_HEADERS]);
1720
+ for (const [name, value] of Object.entries(headers)) {
1721
+ if (value === void 0) continue;
1722
+ if (dropped.has(name.toLowerCase())) continue;
1723
+ outgoing[name] = value;
1724
+ }
1725
+ return outgoing;
1726
+ }
1727
+ /**
1728
+ * Serialize the response head of a proxied WebSocket 101.
1729
+ *
1730
+ * Only {@link UPGRADE_RESPONSE_HEADERS} survive, so an upstream cannot inject
1731
+ * arbitrary headers into the upgraded stream.
1732
+ *
1733
+ * @param headers - upstream 101 response headers.
1734
+ * @param statusCode - upstream status code.
1735
+ * @param statusMessage - upstream status message.
1736
+ * @returns the raw head bytes to write to the visitor's socket.
1737
+ */
1738
+ function buildUpgradeResponseHead(headers, statusCode, statusMessage) {
1739
+ const lines = [`HTTP/1.1 ${statusCode} ${statusMessage}`];
1740
+ const allowed = new Set(UPGRADE_RESPONSE_HEADERS);
1741
+ for (const [name, value] of Object.entries(headers)) {
1742
+ if (value === void 0) continue;
1743
+ const lower = name.toLowerCase();
1744
+ if (!allowed.has(lower)) continue;
1745
+ if (Array.isArray(value)) {
1746
+ for (const item of value) lines.push(`${lower}: ${item}`);
1747
+ continue;
1748
+ }
1749
+ lines.push(`${lower}: ${value}`);
1750
+ }
1751
+ return `${lines.join("\r\n")}\r\n\r\n`;
1752
+ }
1753
+ //#endregion
1754
+ //#region src/websocket.ts
1755
+ /**
1756
+ * dsh-lan-guard — WebSocket upgrade forwarding.
1757
+ *
1758
+ * DSH serves its Remote stream on `/api/remote.mux` over a WebSocket upgrade
1759
+ * (docs/RESEARCH.md §7), and the shipped UI keeps that socket open for the
1760
+ * whole session. The proxy therefore has to relay the upgrade itself rather
1761
+ * than treat it as an ordinary HTTP response.
1762
+ *
1763
+ * Two rules from the researched reference implementations are applied here:
1764
+ *
1765
+ * - The visitor's socket gets an `error` handler IMMEDIATELY, before any
1766
+ * asynchronous work (docs/RESEARCH.md §5.7 ①). A phone reconnecting drops
1767
+ * upgrade sockets constantly; an unhandled `error` during an await would
1768
+ * take the whole process down. This is also why the gate in P2 can await
1769
+ * safely.
1770
+ * - The upstream 101 passes only the handshake headers a browser needs
1771
+ * (docs/RESEARCH.md §5.3) — never the upstream's arbitrary header set.
1772
+ */
1773
+ /** Attach the mandatory `error` handler to a socket we now own. */
1774
+ function guardUpgradeSocket(socket, logger = noopLogger) {
1775
+ socket.on("error", (error) => {
1776
+ logger.debug?.("upgrade socket error name=%s", error.name);
1777
+ socket.destroy();
1778
+ });
1779
+ }
1780
+ /**
1781
+ * Relay one WebSocket upgrade to the upstream and pipe both directions.
1782
+ *
1783
+ * @param options - the upgrade request, its socket, and the prepared headers.
1784
+ * @returns a handle whose `destroy()` tears the tunnel down.
1785
+ */
1786
+ function forwardUpgrade(options) {
1787
+ const { req, socket, head, upstream, headers, target } = options;
1788
+ const logger = options.logger ?? noopLogger;
1789
+ guardUpgradeSocket(socket, logger);
1790
+ const upstreamReq = request({
1791
+ hostname: upstream.hostname,
1792
+ port: upstream.port,
1793
+ method: req.method ?? "GET",
1794
+ path: target,
1795
+ headers
1796
+ });
1797
+ let upstreamSocket;
1798
+ upstreamReq.on("upgrade", (upstreamRes, upstreamDuplex, upstreamHead) => {
1799
+ upstreamSocket = upstreamDuplex;
1800
+ guardUpgradeSocket(upstreamDuplex, logger);
1801
+ upstreamDuplex.on("close", () => socket.destroy());
1802
+ socket.on("close", () => upstreamDuplex.destroy());
1803
+ socket.write(buildUpgradeResponseHead(upstreamRes.headers, upstreamRes.statusCode ?? 101, upstreamRes.statusMessage === "" ? "Switching Protocols" : upstreamRes.statusMessage ?? "Switching Protocols"));
1804
+ if (upstreamHead.length > 0) socket.write(upstreamHead);
1805
+ upstreamDuplex.pipe(socket);
1806
+ socket.pipe(upstreamDuplex);
1807
+ });
1808
+ upstreamReq.on("response", (upstreamRes) => {
1809
+ logger.debug?.("upgrade refused by upstream status=%d", upstreamRes.statusCode ?? 0);
1810
+ upstreamRes.resume();
1811
+ if (!socket.destroyed) {
1812
+ const status = upstreamRes.statusCode ?? 502;
1813
+ const message = upstreamRes.statusMessage === "" ? "Upstream Refused" : upstreamRes.statusMessage ?? "Upstream Refused";
1814
+ socket.write(`HTTP/1.1 ${status} ${message}\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`);
1815
+ }
1816
+ socket.destroy();
1817
+ });
1818
+ upstreamReq.on("error", (error) => {
1819
+ logger.warn("upgrade upstream error name=%s", error.name);
1820
+ socket.destroy();
1821
+ });
1822
+ if (head.length > 0) upstreamReq.write(head);
1823
+ upstreamReq.end();
1824
+ return { destroy() {
1825
+ upstreamReq.destroy();
1826
+ upstreamSocket?.destroy();
1827
+ socket.destroy();
1828
+ } };
1829
+ }
1830
+ //#endregion
1831
+ //#region src/proxy.ts
1832
+ /**
1833
+ * dsh-lan-guard — the reverse proxy itself.
1834
+ *
1835
+ * The proxy owns its own listener; it never touches DSH's binding
1836
+ * (docs/RESEARCH.md §2.1, §4). Requests are relayed transparently to the
1837
+ * loopback upstream:
1838
+ *
1839
+ * - HTTP: one `http.request` per visitor request, streamed both ways. Nothing
1840
+ * is buffered, so a large or streaming response keeps its semantics
1841
+ * (docs/SPEC.md F1).
1842
+ * - WebSocket: the upgrade is relayed by {@link forwardUpgrade}.
1843
+ * - A `401` from the upstream means our cached loopback cookie died (DSH
1844
+ * restarted, or the cookie was rotated). For a safe method the request is
1845
+ * re-authenticated and retried ONCE — never for a body-carrying method.
1846
+ *
1847
+ * The gate is NOT part of this module's P1 scope; P2 inserts it in front of
1848
+ * both the HTTP and the upgrade path.
1849
+ */
1850
+ /** Bind one port, resolving on `listening` and rejecting on `error`. */
1851
+ function listenOnce(server, host, port) {
1852
+ return new Promise((resolve, reject) => {
1853
+ const onError = (error) => {
1854
+ server.off("listening", onListening);
1855
+ reject(error);
1856
+ };
1857
+ const onListening = () => {
1858
+ server.off("error", onError);
1859
+ resolve();
1860
+ };
1861
+ server.once("error", onError);
1862
+ server.once("listening", onListening);
1863
+ server.listen(port, host);
1864
+ });
1865
+ }
1866
+ /** Resolve an origin URL into the hostname/port pair `http.request` needs. */
1867
+ function parseUpstream(origin) {
1868
+ const url = new URL(origin);
1869
+ return {
1870
+ hostname: url.hostname,
1871
+ port: url.port === "" ? 80 : Number(url.port)
1872
+ };
1873
+ }
1874
+ /** Whether a request method may be retried after a `401` without side effects. */
1875
+ function isSafeMethod(method) {
1876
+ return method === "GET" || method === "HEAD";
1877
+ }
1878
+ /**
1879
+ * Start the proxy listener.
1880
+ *
1881
+ * @param options - bind address, upstream origin and the cookie owner.
1882
+ * @returns the running proxy, resolved once the socket is bound.
1883
+ */
1884
+ async function startProxy(options) {
1885
+ const logger = options.logger ?? noopLogger;
1886
+ const upstream = parseUpstream(options.upstreamOrigin);
1887
+ const authority = authorityOf(options.upstreamOrigin);
1888
+ const sockets = /* @__PURE__ */ new Set();
1889
+ const fail = (res, code, body) => {
1890
+ if (res.headersSent) {
1891
+ res.destroy();
1892
+ return;
1893
+ }
1894
+ res.writeHead(code, {
1895
+ "content-type": "text/plain; charset=utf-8",
1896
+ "cache-control": "no-store"
1897
+ });
1898
+ res.end(`${body}\n`);
1899
+ };
1900
+ const forwardHttp = async (req, res, target, mayRetry) => {
1901
+ let cookie;
1902
+ try {
1903
+ cookie = await options.auth.cookieHeader();
1904
+ } catch (error) {
1905
+ logger.warn("upstream authentication failed name=%s", error.name);
1906
+ fail(res, 502, "dsh-lan-guard: upstream authentication unavailable");
1907
+ return;
1908
+ }
1909
+ const headers = buildUpstreamRequestHeaders({
1910
+ headers: req.headers,
1911
+ authority,
1912
+ upstreamCookie: cookie
1913
+ });
1914
+ const upstreamReq = request({
1915
+ hostname: upstream.hostname,
1916
+ port: upstream.port,
1917
+ method: req.method,
1918
+ path: target,
1919
+ headers
1920
+ });
1921
+ upstreamReq.on("response", (upstreamRes) => {
1922
+ const status = upstreamRes.statusCode ?? 502;
1923
+ if (status === 401 && mayRetry && isSafeMethod(req.method)) {
1924
+ upstreamRes.resume();
1925
+ options.auth.invalidate("upstream returned 401");
1926
+ forwardHttp(req, res, target, false);
1927
+ return;
1928
+ }
1929
+ res.writeHead(status, upstreamRes.statusMessage === "" ? void 0 : upstreamRes.statusMessage, buildUpstreamResponseHeaders(upstreamRes.headers));
1930
+ upstreamRes.pipe(res);
1931
+ });
1932
+ upstreamReq.on("error", (error) => {
1933
+ logger.warn("upstream request failed name=%s code=%s", error.name, error.code ?? "none");
1934
+ fail(res, 502, "dsh-lan-guard: upstream unavailable");
1935
+ });
1936
+ res.on("close", () => {
1937
+ if (!upstreamReq.destroyed) upstreamReq.destroy();
1938
+ });
1939
+ if (isSafeMethod(req.method)) upstreamReq.end();
1940
+ else req.pipe(upstreamReq);
1941
+ };
1942
+ const handler = (req, res) => {
1943
+ (async () => {
1944
+ if (options.gate !== void 0) {
1945
+ if (await options.gate.handleHttp(req, res).catch((error) => {
1946
+ logger.warn("gate failed name=%s", error.name);
1947
+ if (!res.headersSent) {
1948
+ res.writeHead(500, { "content-type": "application/json; charset=utf-8" });
1949
+ res.end("{\"ok\":false,\"error\":\"internal_error\"}");
1950
+ } else res.end();
1951
+ return "handled";
1952
+ }) === "handled") return;
1953
+ }
1954
+ await forwardHttp(req, res, normalizeRequestTarget(req.url), true);
1955
+ })();
1956
+ };
1957
+ const server = options.tls === void 0 ? createServer(handler) : createServer$1({
1958
+ cert: options.tls.cert,
1959
+ key: options.tls.key
1960
+ }, handler);
1961
+ server.on("connection", (socket) => {
1962
+ sockets.add(socket);
1963
+ socket.on("close", () => sockets.delete(socket));
1964
+ });
1965
+ server.on("upgrade", (req, socket, head) => {
1966
+ guardUpgradeSocket(socket, logger);
1967
+ (async () => {
1968
+ if (options.gate !== void 0) {
1969
+ const refusal = await options.gate.verifyUpgrade(req);
1970
+ if (refusal !== void 0) {
1971
+ if (!socket.destroyed) socket.write(`HTTP/1.1 ${String(refusal.status)} Unauthorized\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`);
1972
+ socket.destroy();
1973
+ return;
1974
+ }
1975
+ }
1976
+ let cookie;
1977
+ try {
1978
+ cookie = await options.auth.cookieHeader();
1979
+ } catch (error) {
1980
+ logger.warn("upgrade authentication failed name=%s", error.name);
1981
+ socket.destroy();
1982
+ return;
1983
+ }
1984
+ forwardUpgrade({
1985
+ req,
1986
+ socket,
1987
+ head,
1988
+ upstream,
1989
+ target: normalizeRequestTarget(req.url),
1990
+ headers: buildUpstreamRequestHeaders({
1991
+ headers: req.headers,
1992
+ authority,
1993
+ upstreamCookie: cookie,
1994
+ upgrade: true
1995
+ }),
1996
+ logger
1997
+ });
1998
+ })();
1999
+ });
2000
+ const attempts = options.portProbeAttempts ?? 0;
2001
+ const requestedPort = options.listenPort;
2002
+ let boundPort = requestedPort;
2003
+ for (let offset = 0;; offset += 1) try {
2004
+ await listenOnce(server, options.listenHost, boundPort);
2005
+ break;
2006
+ } catch (error) {
2007
+ if (!(error.code === "EADDRINUSE") || requestedPort === 0 || offset >= attempts) throw error;
2008
+ const next = requestedPort + offset + 1;
2009
+ logger.warn("port %d is taken; trying %d", boundPort, next);
2010
+ boundPort = next;
2011
+ }
2012
+ const address = server.address();
2013
+ const port = typeof address === "object" && address !== null ? address.port : options.listenPort;
2014
+ return {
2015
+ host: options.listenHost,
2016
+ port,
2017
+ requestedPort,
2018
+ portFallback: port !== requestedPort,
2019
+ close() {
2020
+ return new Promise((resolve, reject) => {
2021
+ server.close((error) => {
2022
+ if (error) reject(error);
2023
+ else resolve();
2024
+ });
2025
+ for (const socket of sockets) socket.destroy();
2026
+ sockets.clear();
2027
+ });
2028
+ }
2029
+ };
2030
+ }
2031
+ //#endregion
2032
+ //#region src/qrcode.ts
2033
+ /**
2034
+ * dsh-lan-guard — the access URL set and its QR codes (docs/SPEC.md F7).
2035
+ *
2036
+ * The QR is generated on the HOST, because only the host knows the real NIC
2037
+ * addresses and the passwordless token. It is emitted as an SVG string (the
2038
+ * researched dsh-mobile approach, docs/RESEARCH.md §5.8): no base64 bloat, and
2039
+ * the client can let it inherit theme colours.
2040
+ *
2041
+ * The token-bearing URL is a credential: it is only ever produced for an
2042
+ * admin-unlocked caller, and it is never logged (docs/GUARDRAILS.md §4).
2043
+ */
2044
+ /** Render one QR as an SVG string. */
2045
+ async function qrSvg(text) {
2046
+ return await QRCode.toString(text, {
2047
+ type: "svg",
2048
+ margin: 1,
2049
+ errorCorrectionLevel: "M"
2050
+ });
2051
+ }
2052
+ /**
2053
+ * Build the access information for the settings page.
2054
+ *
2055
+ * Rebuilt on every request on purpose: a NIC change, a TLS change, a port
2056
+ * change or a token rotation therefore refreshes the QR automatically
2057
+ * (docs/SPEC.md F7 "刷新时机").
2058
+ *
2059
+ * @param options - port, TLS mode and the optional token.
2060
+ * @returns the URL set plus QR codes.
2061
+ */
2062
+ async function buildAccessInfo(options) {
2063
+ const secure = options.tlsMode !== "off";
2064
+ const loopbackOnly = options.listenHost === "127.0.0.1" || options.listenHost === "::1";
2065
+ const candidates = [...options.addresses ?? listNetworkAddresses()];
2066
+ const chosen = selectAddress(candidates, options.networkInterface ?? null);
2067
+ const addresses = candidates.map((entry) => ({
2068
+ interface: entry.interface,
2069
+ address: entry.address,
2070
+ url: accessUrl(entry.address, options.port, secure),
2071
+ virtual: entry.virtual,
2072
+ ...entry.virtualReason === void 0 ? {} : { virtualReason: entry.virtualReason },
2073
+ selected: chosen !== void 0 && entry.address === chosen.address
2074
+ }));
2075
+ const info = {
2076
+ port: options.port,
2077
+ portFallbackFrom: options.portFallbackFrom ?? null,
2078
+ secure,
2079
+ tlsMode: options.tlsMode,
2080
+ caFingerprint: options.caFingerprint ?? null,
2081
+ addresses,
2082
+ selectedUrl: loopbackOnly ? accessUrl("127.0.0.1", options.port, secure) : chosen === void 0 ? null : accessUrl(chosen.address, options.port, secure),
2083
+ qrSvg: null,
2084
+ loopbackOnly
2085
+ };
2086
+ if (loopbackOnly) {
2087
+ info.unavailableReason = "当前仅绑定回环地址,局域网设备无法访问;请将 listenHost 设为 0.0.0.0 或指定网卡地址";
2088
+ return info;
2089
+ }
2090
+ if (chosen === void 0) {
2091
+ info.unavailableReason = options.networkInterface === null || options.networkInterface === void 0 ? "未检测到可用的局域网 IPv4 地址" : `配置的网卡 ${String(options.networkInterface)} 不存在或没有 IPv4 地址`;
2092
+ return info;
2093
+ }
2094
+ info.qrSvg = await qrSvg(info.selectedUrl ?? "");
2095
+ const token = options.secretToken ?? null;
2096
+ if (token !== null && token !== "" && info.selectedUrl !== null) {
2097
+ info.tokenUrl = `${info.selectedUrl}?auth=${token}`;
2098
+ info.tokenQrSvg = await qrSvg(info.tokenUrl);
2099
+ }
2100
+ return info;
2101
+ }
2102
+ //#endregion
2103
+ //#region src/store/preferences.ts
2104
+ /** Values accepted by each enumerated switch. */
2105
+ const AUTH_MODES = [
2106
+ "password",
2107
+ "token",
2108
+ "token_and_password"
2109
+ ];
2110
+ const ADMIN_POLICIES = [
2111
+ "password_unlock",
2112
+ "local_only",
2113
+ "open"
2114
+ ];
2115
+ /** Raised when a patch carries a value the endpoint must refuse. */
2116
+ var PreferenceError = class extends Error {
2117
+ constructor(message) {
2118
+ super(message);
2119
+ this.name = "PreferenceError";
2120
+ }
2121
+ };
2122
+ /**
2123
+ * Validate one client-supplied patch, dropping unknown keys.
2124
+ *
2125
+ * Dropping is deliberate (docs/SPEC.md F6): an unknown key is either a typo or
2126
+ * an attempt to reach a field this endpoint does not own, and neither may
2127
+ * reach the settings writer.
2128
+ *
2129
+ * @param patch - the decoded JSON body.
2130
+ * @returns only the known keys, validated.
2131
+ * @throws PreferenceError when a known key carries an invalid value.
2132
+ */
2133
+ function sanitizePreferencePatch(patch) {
2134
+ if (typeof patch !== "object" || patch === null || Array.isArray(patch)) throw new PreferenceError("dsh-lan-guard: config patch must be a JSON object");
2135
+ const source = patch;
2136
+ const result = {};
2137
+ if (Object.hasOwn(source, "enabled")) {
2138
+ if (typeof source.enabled !== "boolean") throw new PreferenceError("enabled must be a boolean");
2139
+ result.enabled = source.enabled;
2140
+ }
2141
+ if (Object.hasOwn(source, "listenPort")) {
2142
+ const value = source.listenPort;
2143
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 65535) throw new PreferenceError("listenPort must be an integer between 0 and 65535");
2144
+ result.listenPort = value;
2145
+ }
2146
+ if (Object.hasOwn(source, "networkInterface")) {
2147
+ const value = source.networkInterface;
2148
+ if (typeof value !== "string") throw new PreferenceError("networkInterface must be a string");
2149
+ if (value !== "" && !/^[A-Za-z0-9_.:-]{1,64}$/.test(value)) throw new PreferenceError("networkInterface must be an interface name or an address literal");
2150
+ result.networkInterface = value;
2151
+ }
2152
+ if (Object.hasOwn(source, "requirePairing")) {
2153
+ if (typeof source.requirePairing !== "boolean") throw new PreferenceError("requirePairing must be a boolean");
2154
+ result.requirePairing = source.requirePairing;
2155
+ }
2156
+ if (Object.hasOwn(source, "mode")) {
2157
+ if (!AUTH_MODES.includes(source.mode)) throw new PreferenceError(`mode must be one of ${AUTH_MODES.join(", ")}`);
2158
+ result.mode = source.mode;
2159
+ }
2160
+ if (Object.hasOwn(source, "adminPolicy")) {
2161
+ if (!ADMIN_POLICIES.includes(source.adminPolicy)) throw new PreferenceError(`adminPolicy must be one of ${ADMIN_POLICIES.join(", ")}`);
2162
+ result.adminPolicy = source.adminPolicy;
2163
+ }
2164
+ if (Object.hasOwn(source, "adminProtection")) {
2165
+ if (typeof source.adminProtection !== "boolean") throw new PreferenceError("adminProtection must be a boolean");
2166
+ result.adminProtection = source.adminProtection;
2167
+ }
2168
+ if (Object.hasOwn(source, "allowLoopback")) {
2169
+ if (typeof source.allowLoopback !== "boolean") throw new PreferenceError("allowLoopback must be a boolean");
2170
+ result.allowLoopback = source.allowLoopback;
2171
+ }
2172
+ return result;
2173
+ }
2174
+ /**
2175
+ * Flatten preference values into the nested patch the host settings writer
2176
+ * expects (`{ auth: { mode } }`, not `{ mode }`).
2177
+ *
2178
+ * @param values - validated values.
2179
+ * @returns a nested patch containing only the keys that were supplied.
2180
+ */
2181
+ function toSettingsPatch(values) {
2182
+ const patch = {};
2183
+ const auth = {};
2184
+ if (values.enabled !== void 0) patch.enabled = values.enabled;
2185
+ if (values.listenPort !== void 0) patch.listenPort = values.listenPort;
2186
+ if (values.networkInterface !== void 0) patch.networkInterface = values.networkInterface;
2187
+ if (values.requirePairing !== void 0) auth.requirePairing = values.requirePairing;
2188
+ if (values.mode !== void 0) auth.mode = values.mode;
2189
+ if (values.adminPolicy !== void 0) auth.adminPolicy = values.adminPolicy;
2190
+ if (values.adminProtection !== void 0) auth.adminProtection = values.adminProtection;
2191
+ if (values.allowLoopback !== void 0) auth.allowLoopback = values.allowLoopback;
2192
+ if (Object.keys(auth).length > 0) patch.auth = auth;
2193
+ return patch;
2194
+ }
2195
+ //#endregion
2196
+ //#region src/settings/routes.ts
2197
+ /** Route prefix owned by this plugin on DSH's own web server. */
2198
+ const MANAGEMENT_BASE = "/plugins/dsh-lan-guard";
2199
+ /** Largest accepted management body. */
2200
+ const MAX_BODY_BYTES = 16384;
2201
+ /** Project a stored device onto its public view. */
2202
+ function deviceView(device) {
2203
+ return {
2204
+ id: device.id,
2205
+ label: device.label,
2206
+ createdAtMs: device.createdAtMs,
2207
+ lastSeenAtMs: device.lastSeenAtMs,
2208
+ lastIp: device.lastIp,
2209
+ revoked: device.revokedAtMs !== null
2210
+ };
2211
+ }
2212
+ /**
2213
+ * Whether a port is free, probed on LOOPBACK ONLY.
2214
+ *
2215
+ * Probing loopback never opens a network-facing socket (the gate-before-listen
2216
+ * rule), and it is conservative: if anything already holds the port on any
2217
+ * interface, binding loopback fails too, so a busy port is never reported free.
2218
+ */
2219
+ async function isPortAvailable(port) {
2220
+ return await new Promise((resolve) => {
2221
+ const probe = createServer$2();
2222
+ probe.once("error", () => {
2223
+ resolve(false);
2224
+ });
2225
+ probe.once("listening", () => {
2226
+ probe.close(() => {
2227
+ resolve(true);
2228
+ });
2229
+ });
2230
+ probe.listen(port, "127.0.0.1");
2231
+ });
2232
+ }
2233
+ /** Whether a request is a state change that needs the CSRF check. */
2234
+ function isStateChanging(method) {
2235
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
2236
+ }
2237
+ /** Read a small JSON body. */
2238
+ async function readJsonBody(req) {
2239
+ const chunks = [];
2240
+ let size = 0;
2241
+ for await (const chunk of req) {
2242
+ const buffer = chunk;
2243
+ size += buffer.length;
2244
+ if (size > MAX_BODY_BYTES) throw new PreferenceError("request body too large");
2245
+ chunks.push(buffer);
2246
+ }
2247
+ const raw = Buffer.concat(chunks).toString("utf8").trim();
2248
+ if (raw === "") return {};
2249
+ try {
2250
+ return JSON.parse(raw);
2251
+ } catch {
2252
+ throw new PreferenceError("request body must be JSON");
2253
+ }
2254
+ }
2255
+ /**
2256
+ * Register the management routes.
2257
+ *
2258
+ * @param options - the DSH seams plus the gate state.
2259
+ * @returns a disposer removing every route.
2260
+ */
2261
+ function registerManagementRoutes(options) {
2262
+ const logger = options.logger ?? noopLogger;
2263
+ const disposers = [];
2264
+ const sendJson = (res, status, body) => {
2265
+ res.writeHead(status, {
2266
+ "content-type": "application/json; charset=utf-8",
2267
+ "cache-control": "no-store"
2268
+ });
2269
+ res.end(`${JSON.stringify(body)}\n`);
2270
+ };
2271
+ /** Whether the request arrived directly on loopback (no visitor marker). */
2272
+ const isLocalRequest = (req) => isLoopbackAddress(req.socket.remoteAddress) && req.headers["x-dsh-lan-guard-visitor"] === void 0;
2273
+ /**
2274
+ * How the management console treats THIS request.
2275
+ *
2276
+ * - a direct loopback client is the operator: never locked (physical unlock
2277
+ * privilege — user decision 2026-09-24, matching the reference console);
2278
+ * - remote access under `local_only` is read-only (SPEC F3: "only local
2279
+ * loopback may manage; other devices are read-only");
2280
+ * - remote access under `password_unlock` must unlock first;
2281
+ * - `open` never locks.
2282
+ */
2283
+ const adminStateOf = (req) => {
2284
+ const policy = options.switches.adminPolicy();
2285
+ if (policy === "open") return "open";
2286
+ if (isLocalRequest(req)) return "local";
2287
+ if (policy === "local_only") return "readonly";
2288
+ return options.auth.isAdminUnlocked(req) ? "open" : "locked";
2289
+ };
2290
+ /** Build the redacted status. */
2291
+ const statusOf = (req) => ({
2292
+ pluginEnabled: options.switches.enabled(),
2293
+ localAccess: isLocalRequest(req),
2294
+ adminRequired: adminStateOf(req) === "locked",
2295
+ remoteReadOnly: adminStateOf(req) === "readonly",
2296
+ gateEnabled: options.config.auth.enabled,
2297
+ mode: options.switches.mode(),
2298
+ adminPolicy: options.switches.adminPolicy(),
2299
+ adminProtection: options.switches.adminProtection(),
2300
+ allowLoopback: options.switches.allowLoopback(),
2301
+ hasPassword: options.auth.hasPassword,
2302
+ hasAdminPassword: options.auth.hasAdminPassword,
2303
+ hasSecretToken: options.auth.hasSecretToken,
2304
+ adminUnlocked: options.auth.isAdminUnlocked(req)
2305
+ });
2306
+ /** Build the settings snapshot, including the token only when unlocked. */
2307
+ const snapshotOf = async (req) => {
2308
+ const token = mayManage(req) ? options.auth.secretToken() : void 0;
2309
+ const snapshot = {
2310
+ ok: true,
2311
+ preferences: {
2312
+ enabled: options.switches.enabled(),
2313
+ listenPort: options.switches.listenPort(),
2314
+ networkInterface: options.switches.networkInterface() ?? "",
2315
+ mode: options.switches.mode(),
2316
+ adminPolicy: options.switches.adminPolicy(),
2317
+ adminProtection: options.switches.adminProtection(),
2318
+ allowLoopback: options.switches.allowLoopback(),
2319
+ requirePairing: options.switches.requirePairing()
2320
+ },
2321
+ listener: {
2322
+ listenHost: options.config.listenHost,
2323
+ listenPort: options.listener.port(),
2324
+ configuredPort: options.switches.listenPort(),
2325
+ portFallback: options.listener.portFallback(),
2326
+ upstreamOrigin: options.config.upstreamOrigin
2327
+ },
2328
+ authStatus: statusOf(req),
2329
+ access: await options.access(token ?? null),
2330
+ devices: options.devices.list().map(deviceView)
2331
+ };
2332
+ if (token !== void 0) snapshot.secretToken = token;
2333
+ return snapshot;
2334
+ };
2335
+ /** Run the native fence; returns true when the request was refused. */
2336
+ const refusedByFence = (req, res) => {
2337
+ const rejection = options.connection.requestRejection(req);
2338
+ if (rejection === void 0) return false;
2339
+ sendJson(res, rejection, {
2340
+ ok: false,
2341
+ error: rejection === 403 ? "forbidden" : "unauthorized"
2342
+ });
2343
+ return true;
2344
+ };
2345
+ /**
2346
+ * Whether the caller may manage this console at all: the machine's own
2347
+ * operator (direct loopback) or an explicitly unlocked remote session. The
2348
+ * passwordless link is a credential and is only handed to these callers.
2349
+ */
2350
+ const mayManage = (req) => {
2351
+ const state = adminStateOf(req);
2352
+ return state === "open" || state === "local";
2353
+ };
2354
+ /** Whether the caller may not write at all (remote + `local_only`). */
2355
+ const isRemoteReadOnly = (req) => adminStateOf(req) === "readonly";
2356
+ /** Whether the caller must be admin-unlocked for management writes. */
2357
+ const needsAdmin = (req) => options.switches.adminProtection() && adminStateOf(req) === "locked";
2358
+ /** Write non-sensitive switches through the host settings service. */
2359
+ const writePreferences = async (values) => {
2360
+ const writer = options.settings;
2361
+ if (writer === void 0) throw new PreferenceError("settings service is unavailable; cannot persist switches");
2362
+ const row = writer.describe().find((entry) => entry.ns === "dsh-lan-guard");
2363
+ await writer.update("dsh-lan-guard", toSettingsPatch(values), row?.revision);
2364
+ };
2365
+ const handleConfig = async (req, res) => {
2366
+ if (refusedByFence(req, res)) return;
2367
+ if (!isStateChanging(req.method)) {
2368
+ if (mayManage(req)) await options.auth.ensureSecretToken();
2369
+ sendJson(res, 200, await snapshotOf(req));
2370
+ return;
2371
+ }
2372
+ if (!passesCsrfCheck(req)) {
2373
+ sendJson(res, 403, {
2374
+ ok: false,
2375
+ error: "csrf"
2376
+ });
2377
+ return;
2378
+ }
2379
+ if (isRemoteReadOnly(req)) {
2380
+ sendJson(res, 403, {
2381
+ ok: false,
2382
+ error: "read_only_remote"
2383
+ });
2384
+ return;
2385
+ }
2386
+ let body;
2387
+ try {
2388
+ const parsed = await readJsonBody(req);
2389
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new PreferenceError("request body must be a JSON object");
2390
+ body = parsed;
2391
+ } catch (error) {
2392
+ sendJson(res, 400, {
2393
+ ok: false,
2394
+ error: error.message
2395
+ });
2396
+ return;
2397
+ }
2398
+ const extraCookies = [];
2399
+ try {
2400
+ if (typeof body.adminUnlock === "string") {
2401
+ const unlocked = await options.auth.unlockAdmin(body.adminUnlock);
2402
+ if (unlocked === void 0) {
2403
+ logger.warn("admin unlock failed");
2404
+ sendJson(res, 401, {
2405
+ ok: false,
2406
+ error: "admin_password_invalid"
2407
+ });
2408
+ return;
2409
+ }
2410
+ extraCookies.push(unlocked.cookie);
2411
+ }
2412
+ if (body.adminLock === true) {
2413
+ options.auth.lockAdmin(req);
2414
+ extraCookies.push(buildClearedCookie(ADMIN_COOKIE));
2415
+ }
2416
+ if (body.preferences !== void 0) {
2417
+ if (needsAdmin(req)) {
2418
+ sendJson(res, 403, {
2419
+ ok: false,
2420
+ error: "admin_required"
2421
+ });
2422
+ return;
2423
+ }
2424
+ const values = sanitizePreferencePatch(body.preferences);
2425
+ await writePreferences(values);
2426
+ if (values.mode !== void 0) await options.auth.revokeAllSessions();
2427
+ }
2428
+ if (body.setPassword !== void 0) {
2429
+ const request = body.setPassword;
2430
+ if (typeof request?.next !== "string" || request.next.length < 8) throw new PreferenceError(`setPassword.next must be at least ${String(8)} characters`);
2431
+ if (!(!options.auth.hasPassword || mayManage(req) || typeof request.current === "string" && await options.auth.verifyAccessPassword(request.current))) {
2432
+ sendJson(res, 403, {
2433
+ ok: false,
2434
+ error: "current_password_required"
2435
+ });
2436
+ return;
2437
+ }
2438
+ const wasBootstrap = !options.auth.hasPassword;
2439
+ await options.auth.setPassword(request.next);
2440
+ await options.auth.revokeAllSessions();
2441
+ if (wasBootstrap) {
2442
+ const unlocked = await options.auth.unlockAdmin(request.next);
2443
+ if (unlocked !== void 0) extraCookies.push(unlocked.cookie);
2444
+ }
2445
+ }
2446
+ if (body.setAdminPassword !== void 0) {
2447
+ const request = body.setAdminPassword;
2448
+ if (typeof request?.next !== "string" || request.next.length < 8) throw new PreferenceError(`setAdminPassword.next must be at least ${String(8)} characters`);
2449
+ if (!(!options.auth.hasAdminPassword || mayManage(req) || typeof request.current === "string" && await options.auth.verifyAdminPassword(request.current))) {
2450
+ sendJson(res, 403, {
2451
+ ok: false,
2452
+ error: "current_password_required"
2453
+ });
2454
+ return;
2455
+ }
2456
+ await options.auth.setAdminPassword(request.next);
2457
+ }
2458
+ if (body.rotateToken === true) {
2459
+ if (needsAdmin(req)) {
2460
+ sendJson(res, 403, {
2461
+ ok: false,
2462
+ error: "admin_required"
2463
+ });
2464
+ return;
2465
+ }
2466
+ await options.auth.rotateSecretToken();
2467
+ }
2468
+ } catch (error) {
2469
+ if (error instanceof PreferenceError) {
2470
+ sendJson(res, 400, {
2471
+ ok: false,
2472
+ error: error.message
2473
+ });
2474
+ return;
2475
+ }
2476
+ const detail = error.message;
2477
+ logger.warn("management write failed name=%s message=%s", error.name, detail);
2478
+ sendJson(res, 500, {
2479
+ ok: false,
2480
+ error: "internal_error",
2481
+ detail: detail.slice(0, 300)
2482
+ });
2483
+ return;
2484
+ }
2485
+ if (mayManage(req)) await options.auth.ensureSecretToken();
2486
+ const snapshot = await snapshotOf(req);
2487
+ if (extraCookies.length === 0) {
2488
+ sendJson(res, 200, snapshot);
2489
+ return;
2490
+ }
2491
+ res.writeHead(200, {
2492
+ "content-type": "application/json; charset=utf-8",
2493
+ "cache-control": "no-store",
2494
+ "set-cookie": extraCookies
2495
+ });
2496
+ res.end(`${JSON.stringify(snapshot)}\n`);
2497
+ };
2498
+ const handleAuthStatus = (req, res) => {
2499
+ if (refusedByFence(req, res)) return;
2500
+ sendJson(res, 200, {
2501
+ ok: true,
2502
+ ...statusOf(req)
2503
+ });
2504
+ };
2505
+ disposers.push(options.webServer.register({
2506
+ kind: "exact",
2507
+ path: `${MANAGEMENT_BASE}/config`,
2508
+ handler: handleConfig
2509
+ }));
2510
+ disposers.push(options.webServer.register({
2511
+ kind: "exact",
2512
+ path: `${MANAGEMENT_BASE}/auth-status`,
2513
+ handler: handleAuthStatus
2514
+ }));
2515
+ /**
2516
+ * Paired devices (P4-g): list, add, revoke.
2517
+ *
2518
+ * Adding returns the token exactly ONCE; the list never carries a token or
2519
+ * its hash. Writes need the same authority as any other management write
2520
+ * (the machine's own operator, or an unlocked remote session).
2521
+ */
2522
+ const handleDevices = async (req, res) => {
2523
+ if (refusedByFence(req, res)) return;
2524
+ if (!isStateChanging(req.method)) {
2525
+ sendJson(res, 200, {
2526
+ ok: true,
2527
+ devices: options.devices.list().map(deviceView)
2528
+ });
2529
+ return;
2530
+ }
2531
+ if (!passesCsrfCheck(req)) {
2532
+ sendJson(res, 403, {
2533
+ ok: false,
2534
+ error: "csrf"
2535
+ });
2536
+ return;
2537
+ }
2538
+ if (isRemoteReadOnly(req) || needsAdmin(req)) {
2539
+ sendJson(res, 403, {
2540
+ ok: false,
2541
+ error: isRemoteReadOnly(req) ? "read_only_remote" : "admin_required"
2542
+ });
2543
+ return;
2544
+ }
2545
+ let body;
2546
+ try {
2547
+ const parsed = await readJsonBody(req);
2548
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new PreferenceError("request body must be a JSON object");
2549
+ body = parsed;
2550
+ } catch (error) {
2551
+ sendJson(res, 400, {
2552
+ ok: false,
2553
+ error: error.message
2554
+ });
2555
+ return;
2556
+ }
2557
+ try {
2558
+ if (body.action === "delete") {
2559
+ if (typeof body.id !== "string") throw new PreferenceError("id must be a string");
2560
+ const removed = await options.devices.remove(body.id);
2561
+ sendJson(res, removed ? 200 : 404, {
2562
+ ok: removed,
2563
+ ...removed ? {} : { error: "unknown_device" },
2564
+ devices: options.devices.list().map(deviceView)
2565
+ });
2566
+ return;
2567
+ }
2568
+ if (body.action === "revoke") {
2569
+ if (typeof body.id !== "string") throw new PreferenceError("id must be a string");
2570
+ const revoked = await options.devices.revoke(body.id);
2571
+ sendJson(res, revoked ? 200 : 404, {
2572
+ ok: revoked,
2573
+ ...revoked ? {} : { error: "unknown_or_revoked_device" },
2574
+ devices: options.devices.list().map(deviceView)
2575
+ });
2576
+ return;
2577
+ }
2578
+ throw new PreferenceError("action must be \"revoke\" or \"delete\"");
2579
+ } catch (error) {
2580
+ if (error instanceof PreferenceError) {
2581
+ sendJson(res, 400, {
2582
+ ok: false,
2583
+ error: error.message
2584
+ });
2585
+ return;
2586
+ }
2587
+ logger.warn("device operation failed name=%s", error.name);
2588
+ sendJson(res, 500, {
2589
+ ok: false,
2590
+ error: "internal_error"
2591
+ });
2592
+ }
2593
+ };
2594
+ disposers.push(options.webServer.register({
2595
+ kind: "exact",
2596
+ path: `${MANAGEMENT_BASE}/devices`,
2597
+ handler: handleDevices
2598
+ }));
2599
+ disposers.push(options.webServer.register({
2600
+ kind: "exact",
2601
+ path: `${MANAGEMENT_BASE}/port-check`,
2602
+ handler: async (req, res) => {
2603
+ if (refusedByFence(req, res)) return;
2604
+ const url = new URL(req.url ?? "/", "http://dsh-lan-guard.invalid");
2605
+ const port = Number.parseInt(url.searchParams.get("port") ?? "", 10);
2606
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
2607
+ sendJson(res, 400, {
2608
+ ok: false,
2609
+ error: "invalid_port"
2610
+ });
2611
+ return;
2612
+ }
2613
+ sendJson(res, 200, {
2614
+ ok: true,
2615
+ port,
2616
+ available: await isPortAvailable(port)
2617
+ });
2618
+ }
2619
+ }));
2620
+ return () => {
2621
+ for (const dispose of disposers.reverse()) dispose();
2622
+ };
2623
+ }
2624
+ //#endregion
2625
+ //#region src/store/devices.ts
2626
+ /**
2627
+ * dsh-lan-guard — paired devices (P4-g).
2628
+ *
2629
+ * The master passwordless link (`secretToken`) is all-or-nothing: revoking it
2630
+ * logs out every phone at once. Paired devices give the operator one revocable
2631
+ * credential per phone, so a lost device can be cut off without disturbing the
2632
+ * others.
2633
+ *
2634
+ * Credential hygiene (docs/GUARDRAILS.md §4):
2635
+ *
2636
+ * - the plaintext token is returned exactly ONCE, when the device is created;
2637
+ * - only its SHA-256 hash is persisted, with mode 600, in the plugin dataDir;
2638
+ * - comparison is constant-time, and a revoked device never authenticates.
2639
+ */
2640
+ /** How long a device's "last seen" may go unrefreshed before it is rewritten. */
2641
+ const TOUCH_INTERVAL_MS = 3e5;
2642
+ /** Prefix that distinguishes a device token from the master passwordless token. */
2643
+ const DEVICE_TOKEN_PREFIX = "dsh_dev_";
2644
+ /** Whether a presented token is shaped like a device token. */
2645
+ function isDeviceToken(token) {
2646
+ return token.startsWith(DEVICE_TOKEN_PREFIX);
2647
+ }
2648
+ /** SHA-256 hex of a token; only this ever reaches disk. */
2649
+ function hashToken(token) {
2650
+ return createHash("sha256").update(token).digest("hex");
2651
+ }
2652
+ /** The paired-device registry. */
2653
+ var DeviceRegistry = class {
2654
+ #store;
2655
+ #logger;
2656
+ #now;
2657
+ #devices = [];
2658
+ constructor(options) {
2659
+ this.#store = options.store;
2660
+ this.#logger = options.logger ?? noopLogger;
2661
+ this.#now = options.now ?? (() => Date.now());
2662
+ }
2663
+ /** Load the persisted device list. */
2664
+ async init() {
2665
+ this.#devices = await this.#store.loadDevices();
2666
+ }
2667
+ /** Active and revoked devices, newest first. */
2668
+ list() {
2669
+ return [...this.#devices].sort((left, right) => right.createdAtMs - left.createdAtMs);
2670
+ }
2671
+ /** Number of active (non-revoked) devices. */
2672
+ get activeCount() {
2673
+ return this.#devices.filter((device) => device.revokedAtMs === null).length;
2674
+ }
2675
+ /**
2676
+ * Create a device and return its token ONCE.
2677
+ *
2678
+ * @param label - operator-facing name.
2679
+ * @returns the stored record plus the plaintext token.
2680
+ */
2681
+ async add(label) {
2682
+ const token = `${DEVICE_TOKEN_PREFIX}${randomBytes(18).toString("hex")}`;
2683
+ const device = {
2684
+ id: randomBytes(4).toString("hex"),
2685
+ label: label.trim() === "" ? "未命名设备" : label.trim().slice(0, 60),
2686
+ tokenHash: hashToken(token),
2687
+ createdAtMs: this.#now(),
2688
+ lastSeenAtMs: null,
2689
+ lastIp: null,
2690
+ revokedAtMs: null
2691
+ };
2692
+ this.#devices = [...this.#devices, device];
2693
+ await this.#store.saveDevices(this.#devices);
2694
+ this.#logger.info("device paired id=%s label=%s", device.id, device.label);
2695
+ return {
2696
+ device,
2697
+ token
2698
+ };
2699
+ }
2700
+ /**
2701
+ * Revoke a device.
2702
+ *
2703
+ * @param id - device id.
2704
+ * @returns whether a device was revoked.
2705
+ */
2706
+ async revoke(id) {
2707
+ const target = this.#devices.find((device) => device.id === id);
2708
+ if (target === void 0 || target.revokedAtMs !== null) return false;
2709
+ const revokedAtMs = this.#now();
2710
+ this.#devices = this.#devices.map((device) => device.id === id ? {
2711
+ ...device,
2712
+ revokedAtMs
2713
+ } : device);
2714
+ await this.#store.saveDevices(this.#devices);
2715
+ this.#logger.info("device revoked id=%s", id);
2716
+ return true;
2717
+ }
2718
+ /**
2719
+ * Delete a device record entirely, so the device may pair again.
2720
+ *
2721
+ * @param id - device id.
2722
+ * @returns whether a record was removed.
2723
+ */
2724
+ async remove(id) {
2725
+ const before = this.#devices.length;
2726
+ this.#devices = this.#devices.filter((device) => device.id !== id);
2727
+ if (this.#devices.length === before) return false;
2728
+ await this.#store.saveDevices(this.#devices);
2729
+ return true;
2730
+ }
2731
+ /**
2732
+ * Verify a presented device token.
2733
+ *
2734
+ * @param token - the `?auth=` value.
2735
+ * @returns the matching active device, or `undefined`.
2736
+ */
2737
+ verify(token) {
2738
+ if (!isDeviceToken(token)) return void 0;
2739
+ const presented = Buffer.from(hashToken(token), "utf8");
2740
+ for (const device of this.#devices) {
2741
+ if (device.revokedAtMs !== null) continue;
2742
+ const stored = Buffer.from(device.tokenHash, "utf8");
2743
+ if (stored.byteLength !== presented.byteLength) continue;
2744
+ if (timingSafeEqual(stored, presented)) return device;
2745
+ }
2746
+ }
2747
+ /**
2748
+ * Record that a device just used its link.
2749
+ *
2750
+ * Throttled: a loaded page issues dozens of requests, and rewriting the file
2751
+ * on each one is both wasteful and a crash risk (see {@link writeJson}).
2752
+ *
2753
+ * @param id - device id.
2754
+ * @param ip - the address the request came from.
2755
+ */
2756
+ async touch(id, ip) {
2757
+ const now = this.#now();
2758
+ const target = this.#devices.find((device) => device.id === id);
2759
+ if (target === void 0) return;
2760
+ if (target.lastSeenAtMs !== null && now - target.lastSeenAtMs < TOUCH_INTERVAL_MS && target.lastIp === ip) return;
2761
+ this.#devices = this.#devices.map((device) => device.id === id ? {
2762
+ ...device,
2763
+ lastSeenAtMs: now,
2764
+ lastIp: ip
2765
+ } : device);
2766
+ await this.#store.saveDevices(this.#devices);
2767
+ }
2768
+ };
2769
+ //#endregion
2770
+ //#region src/tls/ca.ts
2771
+ /**
2772
+ * dsh-lan-guard — the self-signed certificate authority (docs/SPEC.md F4).
2773
+ *
2774
+ * The CA is the long-lived identity a phone trusts once. Parameters follow the
2775
+ * researched dsh-mobile set (docs/RESEARCH.md §5.1): EC P-256, SHA-256,
2776
+ * `basicConstraints: cA: true`, `keyUsage` with `keyCertSign`.
2777
+ *
2778
+ * The subject common name is a user decision (2026-09-24): "DSH LAN Guard CA".
2779
+ *
2780
+ * The CA private key never leaves the plugin's private dataDir, is written with
2781
+ * mode 600, and is never logged.
2782
+ */
2783
+ /** The CA subject common name (user decision, 2026-09-24). */
2784
+ const CA_COMMON_NAME = "DSH LAN Guard CA";
2785
+ /** CA validity in days (5 years). */
2786
+ const CA_VALIDITY_DAYS = 1825;
2787
+ /** Write a file that must not be world-readable. */
2788
+ async function writePrivateFile(path, content) {
2789
+ await mkdir(dirname(path), {
2790
+ recursive: true,
2791
+ mode: 448
2792
+ });
2793
+ await writeFile(path, content, { mode: 384 });
2794
+ await chmod(path, 384);
2795
+ }
2796
+ /** Write a public certificate (safe to be readable). */
2797
+ async function writePublicFile(path, content) {
2798
+ await mkdir(dirname(path), {
2799
+ recursive: true,
2800
+ mode: 448
2801
+ });
2802
+ await writeFile(path, content, { mode: 420 });
2803
+ }
2804
+ /** The SHA-256 fingerprint of a PEM certificate. */
2805
+ function fingerprintOf(certPem) {
2806
+ return new X509Certificate(certPem).fingerprint256;
2807
+ }
2808
+ /**
2809
+ * Assert that a certificate and a private key belong together.
2810
+ *
2811
+ * Without this check a rotated or half-copied pair fails much later, as an
2812
+ * opaque TLS handshake error on the phone.
2813
+ *
2814
+ * @param certPem - PEM certificate.
2815
+ * @param keyPem - PEM private key.
2816
+ * @throws when the pair does not match or the certificate is not a CA.
2817
+ */
2818
+ function assertMatchingCa(certPem, keyPem) {
2819
+ const certificate = new X509Certificate(certPem);
2820
+ if (!certificate.ca) throw new Error("dsh-lan-guard: CA certificate is not a CA (basicConstraints cA)");
2821
+ if (certificate.subject !== certificate.issuer) throw new Error("dsh-lan-guard: CA certificate is not self-signed");
2822
+ if (!certificate.verify(certificate.publicKey)) throw new Error("dsh-lan-guard: CA certificate signature does not verify against its own key");
2823
+ const keyPublic = createPublicKey(createPrivateKey(keyPem));
2824
+ const certPublic = certificate.publicKey;
2825
+ const keyDer = keyPublic.export({
2826
+ type: "spki",
2827
+ format: "der"
2828
+ });
2829
+ const certDer = certPublic.export({
2830
+ type: "spki",
2831
+ format: "der"
2832
+ });
2833
+ if (!Buffer.from(keyDer).equals(Buffer.from(certDer))) throw new Error("dsh-lan-guard: CA private key does not match the CA certificate");
2834
+ }
2835
+ /** Generate a fresh self-signed CA. */
2836
+ async function generateCa() {
2837
+ const notBeforeDate = /* @__PURE__ */ new Date(Date.now() - 3e5);
2838
+ const notAfterDate = new Date(Date.now() + CA_VALIDITY_DAYS * 24 * 60 * 60 * 1e3);
2839
+ const pems = await generate([{
2840
+ name: "commonName",
2841
+ value: CA_COMMON_NAME
2842
+ }], {
2843
+ keyType: "ec",
2844
+ curve: "P-256",
2845
+ algorithm: "sha256",
2846
+ notBeforeDate,
2847
+ notAfterDate,
2848
+ extensions: [{
2849
+ name: "basicConstraints",
2850
+ cA: true,
2851
+ critical: true
2852
+ }, {
2853
+ name: "keyUsage",
2854
+ digitalSignature: true,
2855
+ keyCertSign: true,
2856
+ cRLSign: true,
2857
+ critical: true
2858
+ }]
2859
+ });
2860
+ return {
2861
+ cert: pems.cert,
2862
+ key: pems.private,
2863
+ fingerprint: fingerprintOf(pems.cert)
2864
+ };
2865
+ }
2866
+ /** Load a CA from disk and prove the pair matches. */
2867
+ async function loadCa(certPath, keyPath) {
2868
+ const [cert, key] = await Promise.all([readFile(certPath, "utf8"), readFile(keyPath, "utf8")]);
2869
+ assertMatchingCa(cert, key);
2870
+ return {
2871
+ cert,
2872
+ key,
2873
+ fingerprint: fingerprintOf(cert)
2874
+ };
2875
+ }
2876
+ /**
2877
+ * Load the CA from disk, generating it once when missing.
2878
+ *
2879
+ * The CA identity is retained across restarts on purpose: replacing it would
2880
+ * force every phone to re-trust a new CA (docs/RESEARCH.md §5.1).
2881
+ *
2882
+ * @param certPath - where the CA certificate lives.
2883
+ * @param keyPath - where the CA private key lives.
2884
+ * @returns the CA material.
2885
+ */
2886
+ async function ensureCa(certPath, keyPath) {
2887
+ try {
2888
+ return await loadCa(certPath, keyPath);
2889
+ } catch (error) {
2890
+ if (error.code !== "ENOENT") throw error;
2891
+ }
2892
+ const generated = await generateCa();
2893
+ await writePrivateFile(keyPath, generated.key);
2894
+ await writePublicFile(certPath, generated.cert);
2895
+ return generated;
2896
+ }
2897
+ /** Renew this long before expiry so a phone never meets an expired certificate. */
2898
+ const RENEW_BEFORE_MS = 6048e5;
2899
+ /** Whether an existing leaf still satisfies the request. */
2900
+ function leafIsReusable(certPem, ca, addresses, now) {
2901
+ let certificate;
2902
+ try {
2903
+ certificate = new X509Certificate(certPem);
2904
+ } catch {
2905
+ return false;
2906
+ }
2907
+ try {
2908
+ if (!certificate.verify(new X509Certificate(ca.cert).publicKey)) return false;
2909
+ } catch {
2910
+ return false;
2911
+ }
2912
+ if (new Date(certificate.validTo).getTime() - RENEW_BEFORE_MS <= now) return false;
2913
+ for (const address of addresses) try {
2914
+ if (!certificate.checkIP(address)) return false;
2915
+ } catch {
2916
+ return false;
2917
+ }
2918
+ return true;
2919
+ }
2920
+ /**
2921
+ * Ensure a leaf certificate signed by the CA covers the given addresses.
2922
+ *
2923
+ * @param options - the CA, the addresses and the on-disk locations.
2924
+ * @returns the leaf material in use.
2925
+ */
2926
+ async function ensureLeaf(options) {
2927
+ const now = (options.now ?? (() => Date.now()))();
2928
+ const wanted = [.../* @__PURE__ */ new Set([
2929
+ ...options.addresses,
2930
+ "127.0.0.1",
2931
+ "::1"
2932
+ ])];
2933
+ try {
2934
+ const existing = await readFile(options.certPath, "utf8");
2935
+ if (leafIsReusable(existing, options.ca, wanted, now)) return {
2936
+ cert: existing,
2937
+ key: await readFile(options.keyPath, "utf8"),
2938
+ fingerprint: fingerprintOf(existing),
2939
+ addresses: wanted
2940
+ };
2941
+ } catch (error) {
2942
+ if (error.code !== "ENOENT") throw error;
2943
+ }
2944
+ const notBeforeDate = /* @__PURE__ */ new Date(now - 3e5);
2945
+ const notAfterDate = new Date(now + 31536e6);
2946
+ const pems = await generate([{
2947
+ name: "commonName",
2948
+ value: "dsh-lan-guard"
2949
+ }], {
2950
+ keyType: "ec",
2951
+ curve: "P-256",
2952
+ algorithm: "sha256",
2953
+ notBeforeDate,
2954
+ notAfterDate,
2955
+ ca: {
2956
+ key: options.ca.key,
2957
+ cert: options.ca.cert
2958
+ },
2959
+ extensions: [
2960
+ {
2961
+ name: "basicConstraints",
2962
+ cA: false
2963
+ },
2964
+ {
2965
+ name: "keyUsage",
2966
+ digitalSignature: true,
2967
+ keyEncipherment: true
2968
+ },
2969
+ {
2970
+ name: "extKeyUsage",
2971
+ serverAuth: true
2972
+ },
2973
+ {
2974
+ name: "subjectAltName",
2975
+ altNames: wanted.map((address) => ({
2976
+ type: 7,
2977
+ ip: address
2978
+ }))
2979
+ }
2980
+ ]
2981
+ });
2982
+ await writePrivateFile(options.keyPath, pems.private);
2983
+ await writePublicFile(options.certPath, pems.cert);
2984
+ return {
2985
+ cert: pems.cert,
2986
+ key: pems.private,
2987
+ fingerprint: fingerprintOf(pems.cert),
2988
+ addresses: wanted
2989
+ };
2990
+ }
2991
+ //#endregion
2992
+ //#region src/upstream-auth.ts
2993
+ /**
2994
+ * dsh-lan-guard — upstream loopback authentication (SPEC §3 F2, route A).
2995
+ *
2996
+ * The browser holds a cookie for the PROXY origin; DSH's fence authenticates a
2997
+ * cookie bound to the authority `127.0.0.1:<dshPort>` (docs/RESEARCH.md §3.4).
2998
+ * So the proxy cannot reuse the visitor's cookie and must hold one of its own.
2999
+ *
3000
+ * Route A (the decided route) uses only the public seam
3001
+ * `ctx.connection.authenticatedUrl(origin)`:
3002
+ *
3003
+ * GET /?token=<launch token> → 303 + Set-Cookie + Location: ./
3004
+ *
3005
+ * and caches the resulting cookie. The launch token is process-scoped, so a
3006
+ * DSH restart invalidates it — this class detects that by re-reading the
3007
+ * token through the seam on every call and re-exchanging when it changes.
3008
+ *
3009
+ * Route B (reading the credentials file and signing a cookie ourselves) is
3010
+ * deliberately NOT implemented: it would depend on DSH's private format and
3011
+ * fail silently with a 401 after any format change.
3012
+ *
3013
+ * The launch token and the session cookie are credentials: they are held in
3014
+ * memory only, never logged, never written to disk (docs/GUARDRAILS.md §4).
3015
+ */
3016
+ /** How long to wait for the token→cookie exchange before giving up. */
3017
+ const EXCHANGE_TIMEOUT_MS = 5e3;
3018
+ /** Re-exchange this long before the cookie expires, so a request never races expiry. */
3019
+ const REFRESH_SKEW_MS = 6e4;
3020
+ /** Fallback cookie lifetime when the upstream sends neither Max-Age nor Expires. */
3021
+ const FALLBACK_MAX_AGE_MS = 2592e6;
3022
+ /** Raised when the upstream refuses to mint a loopback session. */
3023
+ var UpstreamAuthError = class extends Error {
3024
+ constructor(message) {
3025
+ super(message);
3026
+ this.name = "UpstreamAuthError";
3027
+ }
3028
+ };
3029
+ /** Parse the `Max-Age`/`Expires` attributes of one `Set-Cookie` value. */
3030
+ function cookieExpiry(value, now) {
3031
+ const attributes = value.split(";").slice(1);
3032
+ for (const attribute of attributes) {
3033
+ const at = attribute.indexOf("=");
3034
+ if (at === -1) continue;
3035
+ const name = attribute.slice(0, at).trim().toLowerCase();
3036
+ const raw = attribute.slice(at + 1).trim();
3037
+ if (name === "max-age") {
3038
+ const seconds = Number.parseInt(raw, 10);
3039
+ if (Number.isFinite(seconds) && seconds > 0) return now + seconds * 1e3;
3040
+ }
3041
+ if (name === "expires") {
3042
+ const parsed = Date.parse(raw);
3043
+ if (Number.isFinite(parsed) && parsed > now) return parsed;
3044
+ }
3045
+ }
3046
+ return now + FALLBACK_MAX_AGE_MS;
3047
+ }
3048
+ /** Extract the `name=value` pair from the first `Set-Cookie` header. */
3049
+ function firstCookiePair(setCookie) {
3050
+ const first = Array.isArray(setCookie) ? setCookie[0] : setCookie;
3051
+ if (typeof first !== "string") return void 0;
3052
+ const pair = first.split(";")[0]?.trim() ?? "";
3053
+ if (pair.indexOf("=") <= 0) return void 0;
3054
+ return pair;
3055
+ }
3056
+ /** Perform one exchange request without following redirects (the 303 carries the cookie). */
3057
+ function exchangeRequest(url) {
3058
+ return new Promise((resolve, reject) => {
3059
+ const req = request({
3060
+ protocol: url.protocol,
3061
+ hostname: url.hostname,
3062
+ port: url.port === "" ? void 0 : Number(url.port),
3063
+ method: "GET",
3064
+ path: `${url.pathname}${url.search}`,
3065
+ headers: {
3066
+ host: url.host,
3067
+ accept: "text/html,application/xhtml+xml",
3068
+ "cache-control": "no-store"
3069
+ }
3070
+ }, (res) => {
3071
+ const response = {
3072
+ statusCode: res.statusCode ?? 0,
3073
+ statusMessage: res.statusMessage ?? "",
3074
+ headers: res.headers
3075
+ };
3076
+ res.resume();
3077
+ resolve(response);
3078
+ });
3079
+ req.setTimeout(EXCHANGE_TIMEOUT_MS, () => {
3080
+ req.destroy(new UpstreamAuthError("dsh-lan-guard: upstream token exchange timed out"));
3081
+ });
3082
+ req.on("error", (error) => {
3083
+ reject(error instanceof UpstreamAuthError ? error : new UpstreamAuthError(`dsh-lan-guard: upstream token exchange failed: ${error.message}`));
3084
+ });
3085
+ req.end();
3086
+ });
3087
+ }
3088
+ /**
3089
+ * Owns the proxy's loopback session cookie: acquisition, caching and renewal.
3090
+ */
3091
+ var UpstreamAuth = class {
3092
+ #origin;
3093
+ #authenticatedUrl;
3094
+ #now;
3095
+ #logger;
3096
+ #session;
3097
+ #inflight;
3098
+ constructor(options) {
3099
+ this.#origin = options.origin;
3100
+ this.#authenticatedUrl = options.authenticatedUrl;
3101
+ this.#now = options.now ?? (() => Date.now());
3102
+ this.#logger = options.logger ?? noopLogger;
3103
+ }
3104
+ /** The launch token currently offered by the seam. Never logged. */
3105
+ #currentToken() {
3106
+ const token = new URL(this.#authenticatedUrl(this.#origin)).searchParams.get("token");
3107
+ if (token === null || token === "") throw new UpstreamAuthError("dsh-lan-guard: ctx.connection.authenticatedUrl() returned no launch token; the upstream authentication seam changed (see docs/RESEARCH.md §3.3)");
3108
+ return token;
3109
+ }
3110
+ /** Whether the cached session still matches the live token and has not neared expiry. */
3111
+ #isFresh(session, token) {
3112
+ return session.launchToken === token && this.#now() < session.expiresAtMs - REFRESH_SKEW_MS;
3113
+ }
3114
+ /**
3115
+ * Return the `name=value` pair to inject upstream, exchanging when needed.
3116
+ *
3117
+ * @returns the cookie pair.
3118
+ * @throws UpstreamAuthError when no session could be established.
3119
+ */
3120
+ async cookieHeader() {
3121
+ const token = this.#currentToken();
3122
+ const cached = this.#session;
3123
+ if (cached !== void 0 && this.#isFresh(cached, token)) return cached.cookie;
3124
+ if (this.#inflight === void 0) this.#inflight = this.#exchange(token).finally(() => {
3125
+ this.#inflight = void 0;
3126
+ });
3127
+ return (await this.#inflight).cookie;
3128
+ }
3129
+ /**
3130
+ * Drop the cached session so the next call re-exchanges.
3131
+ *
3132
+ * @param reason - short, non-secret reason for the log line.
3133
+ */
3134
+ invalidate(reason) {
3135
+ if (this.#session === void 0) return;
3136
+ this.#session = void 0;
3137
+ this.#logger.warn("upstream session invalidated reason=%s", reason);
3138
+ }
3139
+ /** Perform one token→cookie exchange. */
3140
+ async #exchange(token) {
3141
+ const response = await exchangeRequest(new URL(this.#authenticatedUrl(this.#origin)));
3142
+ if (response.statusCode !== 303) throw new UpstreamAuthError(`dsh-lan-guard: upstream token exchange expected 303, received ${response.statusCode}`);
3143
+ const pair = firstCookiePair(response.headers["set-cookie"]);
3144
+ if (pair === void 0) throw new UpstreamAuthError("dsh-lan-guard: upstream token exchange returned no session cookie");
3145
+ const location = response.headers.location;
3146
+ if (location !== "./") this.#logger.warn("upstream token exchange returned unexpected location=%s", String(location));
3147
+ const cookieName = pair.slice(0, pair.indexOf("="));
3148
+ const expiresAtMs = cookieExpiry(Array.isArray(response.headers["set-cookie"]) ? response.headers["set-cookie"][0] ?? "" : response.headers["set-cookie"] ?? "", this.#now());
3149
+ const session = {
3150
+ cookie: pair,
3151
+ cookieName,
3152
+ expiresAtMs,
3153
+ launchToken: token
3154
+ };
3155
+ this.#session = session;
3156
+ this.#logger.info("upstream session established cookie=%s expiresInMs=%d", cookieName, expiresAtMs - this.#now());
3157
+ return session;
3158
+ }
3159
+ };
3160
+ //#endregion
3161
+ //#region src/index.ts
3162
+ /** Stable Cordis plugin name; also the Loader entry id and the settings namespace. */
3163
+ const name = "dsh-lan-guard";
3164
+ /** `connection` supplies the launch-token seam and the native fence; `webServer` hosts the management routes. */
3165
+ const inject = ["webServer", "connection"];
3166
+ /**
3167
+ * Validate config and bring the plugin up.
3168
+ *
3169
+ * @param host - the host capabilities above.
3170
+ * @param rawConfig - the Loader config for this entry.
3171
+ * @returns the running runtime, or `undefined` when the plugin is switched off.
3172
+ */
3173
+ async function startLanGuard(host, rawConfig) {
3174
+ const logger = host.logger ?? noopLogger;
3175
+ const config = parseConfig(rawConfig);
3176
+ const switches = liveSwitches(rawConfig, config);
3177
+ if (!switches.enabled()) {
3178
+ logger.info("plugin disabled; no listener opened");
3179
+ return;
3180
+ }
3181
+ 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");
3182
+ 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)`);
3183
+ const store = new SecretsStore(config.dataDir ?? "", logger);
3184
+ const auth = new AuthManager({
3185
+ store,
3186
+ auth: config.auth,
3187
+ switches,
3188
+ logger
3189
+ });
3190
+ await auth.init();
3191
+ if (!auth.hasPassword) logger.warn("no access password configured; the gate will refuse every device until one is set");
3192
+ const devices = new DeviceRegistry({
3193
+ store,
3194
+ logger
3195
+ });
3196
+ await devices.init();
3197
+ const gate = new VisitorGate({
3198
+ auth,
3199
+ devices,
3200
+ requirePairing: () => switches.requirePairing(),
3201
+ logger
3202
+ });
3203
+ const upstreamAuth = new UpstreamAuth({
3204
+ origin: config.upstreamOrigin,
3205
+ authenticatedUrl: host.authenticatedUrl,
3206
+ logger
3207
+ });
3208
+ const tls = await materializeTls(config, logger);
3209
+ const proxy = await startProxy({
3210
+ listenHost: config.listenHost,
3211
+ listenPort: config.listenPort,
3212
+ portProbeAttempts: 10,
3213
+ upstreamOrigin: config.upstreamOrigin,
3214
+ auth: upstreamAuth,
3215
+ gate,
3216
+ ...tls === void 0 ? {} : { tls: {
3217
+ cert: tls.cert,
3218
+ key: tls.key
3219
+ } },
3220
+ logger
3221
+ });
3222
+ const mdns = config.mdns.enabled ? startMdns({
3223
+ advertisement: mdnsAdvertisement({
3224
+ port: proxy.port,
3225
+ secure: config.tls.mode !== "off",
3226
+ address: selectAddress(listNetworkAddresses(), config.networkInterface)?.address ?? null
3227
+ }),
3228
+ logger
3229
+ }) : void 0;
3230
+ const access = (secretToken) => buildAccessInfo({
3231
+ port: proxy.port,
3232
+ portFallbackFrom: proxy.portFallback ? proxy.requestedPort : null,
3233
+ listenHost: config.listenHost,
3234
+ tlsMode: config.tls.mode,
3235
+ networkInterface: switches.networkInterface(),
3236
+ caFingerprint: tls?.caFingerprint ?? null,
3237
+ secretToken: secretToken ?? null
3238
+ });
3239
+ const disposeManagement = host.registerManagement?.({
3240
+ auth,
3241
+ switches,
3242
+ config,
3243
+ logger,
3244
+ access,
3245
+ listener: {
3246
+ port: () => proxy.port,
3247
+ portFallback: () => proxy.portFallback
3248
+ },
3249
+ devices
3250
+ });
3251
+ if (proxy.portFallback) logger.warn("configured port %d was taken; listening on %d instead", proxy.requestedPort, proxy.port);
3252
+ logger.info("listening host=%s port=%d upstream=%s tls=%s gate=%s mode=%s", proxy.host, proxy.port, config.upstreamOrigin, config.tls.mode, switches.enabled() ? "on" : "off", switches.mode());
3253
+ return {
3254
+ proxy,
3255
+ auth,
3256
+ devices,
3257
+ async close() {
3258
+ mdns?.stop();
3259
+ disposeManagement?.();
3260
+ auth.dispose();
3261
+ await proxy.close();
3262
+ }
3263
+ };
3264
+ }
3265
+ /**
3266
+ * Produce the listener's TLS material.
3267
+ *
3268
+ * `self-signed` keeps a long-lived CA and re-signs a leaf for the CURRENT
3269
+ * addresses, so a DHCP change never invalidates a phone's trust
3270
+ * (docs/RESEARCH.md §5.1).
3271
+ */
3272
+ async function materializeTls(config, logger) {
3273
+ if (config.tls.mode === "off") {
3274
+ logger.warn("TLS is disabled; the gate password travels in clear text on this listener");
3275
+ return;
3276
+ }
3277
+ if (config.tls.mode === "provided") {
3278
+ const certFile = config.tls.certFile;
3279
+ const keyFile = config.tls.keyFile;
3280
+ if (certFile === null || keyFile === null) throw new Error("dsh-lan-guard: tls.mode \"provided\" requires certFile and keyFile");
3281
+ const [cert, key] = await Promise.all([readFile(certFile, "utf8"), readFile(keyFile, "utf8")]);
3282
+ const caCertFile = config.tls.caCertFile;
3283
+ return {
3284
+ cert,
3285
+ key,
3286
+ caFingerprint: caCertFile === null ? null : fingerprintOf(await readFile(caCertFile, "utf8"))
3287
+ };
3288
+ }
3289
+ const directory = join(config.dataDir ?? "", "tls");
3290
+ const ca = await ensureCa(join(directory, "ca.pem"), join(directory, "ca-key.pem"));
3291
+ const leaf = await ensureLeaf({
3292
+ ca,
3293
+ addresses: listNetworkAddresses().map((entry) => entry.address),
3294
+ certPath: join(directory, "leaf.pem"),
3295
+ keyPath: join(directory, "leaf-key.pem")
3296
+ });
3297
+ logger.info("self-signed TLS ready caFingerprint=%s addresses=%d", ca.fingerprint, leaf.addresses.length);
3298
+ return {
3299
+ cert: leaf.cert,
3300
+ key: leaf.key,
3301
+ caFingerprint: ca.fingerprint
3302
+ };
3303
+ }
3304
+ function optionalSettings(ctx) {
3305
+ const lookup = ctx.get;
3306
+ if (typeof lookup !== "function") return void 0;
3307
+ try {
3308
+ const service = lookup.call(ctx, "settings");
3309
+ return service === void 0 || service === null ? void 0 : service;
3310
+ } catch {
3311
+ return;
3312
+ }
3313
+ }
3314
+ /**
3315
+ * Cordis entry point.
3316
+ *
3317
+ * @param ctx - the plugin's context (injects `webServer` and `connection`).
3318
+ * @param rawConfig - the Loader config for this entry.
3319
+ */
3320
+ async function apply(ctx, rawConfig) {
3321
+ const logger = ctx.logger(name);
3322
+ const runtime = await startLanGuard({
3323
+ authenticatedUrl: (baseUrl) => ctx.connection.authenticatedUrl(baseUrl),
3324
+ webServerPort: ctx.webServer.port,
3325
+ logger,
3326
+ registerManagement: (deps) => registerManagementRoutes({
3327
+ connection: { requestRejection: (request) => ctx.connection.requestRejection(request) },
3328
+ webServer: ctx.webServer,
3329
+ settings: optionalSettings(ctx),
3330
+ auth: deps.auth,
3331
+ switches: deps.switches,
3332
+ config: deps.config,
3333
+ access: deps.access,
3334
+ listener: deps.listener,
3335
+ devices: deps.devices,
3336
+ logger: deps.logger
3337
+ })
3338
+ }, rawConfig);
3339
+ if (runtime === void 0) return;
3340
+ ctx.effect(() => () => runtime.close(), "dsh-lan-guard listener, gate and management routes");
3341
+ }
3342
+ //#endregion
3343
+ export { Config, apply, inject, name, startLanGuard };