dsh-lan-guard 0.3.4 → 0.3.6

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 CHANGED
@@ -1,5 +1,5 @@
1
- import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
- import { dirname, join } from "node:path";
1
+ import { chmod, mkdir, readFile, readdir, realpath, rename, stat, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
3
3
  import { X509Certificate, createHash, createPrivateKey, createPublicKey, pbkdf2, randomBytes, timingSafeEqual } from "node:crypto";
4
4
  import { promisify } from "node:util";
5
5
  import { homedir, networkInterfaces } from "node:os";
@@ -1104,7 +1104,7 @@ function notice(state, lockedUntilMs, now) {
1104
1104
  if (state === "csrf") return "<p class=\"notice error\">请求来源校验未通过,请从本页重新登录。</p>";
1105
1105
  if (state === "link-inactive") return "<p class=\"notice error\">这条免密链接无效,或当前「仅密码」模式不使用免密链接。<br>请输入访问密码;若希望链接可用,请在运行本程序的电脑上把验证模式改为「令牌 + 密码」。</p>";
1106
1106
  if (state === "pending-approval") return "<p class=\"notice\">⏳ <strong>这台设备正在等待管理员批准。</strong><br>请在运行本程序的电脑上打开设置 → 局域网访问 → 已授权设备,点「批准」后刷新本页即可进入。</p>";
1107
- if (state === "device-removed") return "<p class=\"notice error\"><strong>此设备已被移除访问权限。</strong><br>请联系管理员在「已授权设备」中「解除拉黑」,同一台设备会立即恢复;若该记录已被删除,请清除本浏览器的本站数据后再访问。</p>";
1107
+ if (state === "device-removed") return "<p class=\"notice error\"><strong>此设备已被移除访问权限。</strong><br>请联系管理员在「已授权设备」中「解除拉黑」,同一台设备会立即恢复。</p>";
1108
1108
  if (state === "token-only") return "<p class=\"notice warn\">当前验证模式为<strong>仅安全 Token</strong>,不接受密码登录。请使用管理员提供的免密链接或二维码。</p>";
1109
1109
  if (state === "no-password") return "<p class=\"notice warn\"><strong>尚未设置访问密码。</strong><br>出于安全考虑,未设置密码时门禁不会放行任何设备。请在桌面 DSH 的「设置 → 局域网访问」中设置访问密码。</p>";
1110
1110
  return "";
@@ -1239,10 +1239,10 @@ var VisitorGate = class {
1239
1239
  return "handled";
1240
1240
  }
1241
1241
  const deviceToken = readCookie(req, DEVICE_COOKIE);
1242
- if (deviceToken !== void 0) {
1243
- const device = this.#devices?.lookup(deviceToken);
1244
- if (device === void 0 || device.revokedAtMs !== null || device.status === "blocked") {
1245
- this.#logger.warn("refused a revoked, blocked or unknown device ip=%s", clientIp(req));
1242
+ const device = deviceToken === void 0 ? void 0 : this.#devices?.lookup(deviceToken);
1243
+ if (device !== void 0) {
1244
+ if (device.revokedAtMs !== null || device.status === "blocked") {
1245
+ this.#logger.warn("refused a revoked or blocked device ip=%s", clientIp(req));
1246
1246
  this.#sendRemoved(req, res);
1247
1247
  return "handled";
1248
1248
  }
@@ -1255,6 +1255,7 @@ var VisitorGate = class {
1255
1255
  });
1256
1256
  return "allow";
1257
1257
  }
1258
+ if (deviceToken !== void 0) this.#logger.debug?.("device cookie matches no record; continuing to the auth flow ip=%s", clientIp(req));
1258
1259
  const link = url.searchParams.get("auth");
1259
1260
  if (link !== null) return await this.#handleAuthLink(req, res, url, link);
1260
1261
  const verdict = await this.#auth.verifyRequest(req);
@@ -1288,9 +1289,9 @@ var VisitorGate = class {
1288
1289
  */
1289
1290
  async verifyUpgrade(req) {
1290
1291
  const deviceToken = readCookie(req, DEVICE_COOKIE);
1291
- if (deviceToken !== void 0) {
1292
- const device = this.#devices?.lookup(deviceToken);
1293
- if (device === void 0 || device.revokedAtMs !== null || device.status === "blocked") {
1292
+ const device = deviceToken === void 0 ? void 0 : this.#devices?.lookup(deviceToken);
1293
+ if (device !== void 0) {
1294
+ if (device.revokedAtMs !== null || device.status === "blocked") {
1294
1295
  this.#logger.warn("upgrade refused: revoked or blocked device ip=%s", clientIp(req));
1295
1296
  return {
1296
1297
  status: 403,
@@ -1905,8 +1906,37 @@ const REPLACED_REQUEST_HEADERS = [
1905
1906
  "cookie",
1906
1907
  VISITOR_HEADER
1907
1908
  ];
1908
- /** Response headers dropped on top of the hop-by-hop set. */
1909
- const DROPPED_RESPONSE_HEADERS = ["set-cookie"];
1909
+ /**
1910
+ * Read one `name=value` pair out of a `Cookie` request header.
1911
+ *
1912
+ * Deliberately not a cookie parser: the value is relayed byte-for-byte, and the
1913
+ * only decision here is which NAME to keep.
1914
+ *
1915
+ * @param header - the visitor's `cookie` header.
1916
+ * @param name - the cookie name to extract.
1917
+ * @returns the exact `name=value` pair, or `undefined`.
1918
+ */
1919
+ function cookiePairOf(header, name) {
1920
+ if (header === void 0 || header === "") return void 0;
1921
+ for (const part of header.split(";")) {
1922
+ const trimmed = part.trim();
1923
+ const eq = trimmed.indexOf("=");
1924
+ if (eq <= 0) continue;
1925
+ if (trimmed.slice(0, eq).trim() === name) return trimmed;
1926
+ }
1927
+ }
1928
+ /** The cookie name of one `Set-Cookie` entry. */
1929
+ function setCookieName(entry) {
1930
+ const eq = entry.indexOf("=");
1931
+ if (eq <= 0) return void 0;
1932
+ const name = entry.slice(0, eq).trim();
1933
+ return name === "" ? void 0 : name;
1934
+ }
1935
+ /** Normalize a header value that may be a single string or a list. */
1936
+ function toArray(value) {
1937
+ if (value === void 0) return [];
1938
+ return Array.isArray(value) ? value : [value];
1939
+ }
1910
1940
  /**
1911
1941
  * The `host:port` authority of an origin URL — the value the upstream fence
1912
1942
  * binds cookies to.
@@ -1949,6 +1979,13 @@ function normalizeRequestTarget(rawTarget) {
1949
1979
  * @param input.authority - upstream `host:port`.
1950
1980
  * @param input.upstreamCookie - the loopback session cookie to inject, if known.
1951
1981
  * @param input.upgrade - true for a WebSocket upgrade (keeps `connection`/`upgrade`).
1982
+ * @param input.relayCookieNames - the plugin's OWN cookie names that must reach
1983
+ * the upstream. DSH's session cookie is injected by the proxy, and the
1984
+ * visitor's other cookies (the gate session and device identity) belong to the
1985
+ * proxy origin and must never reach DSH — but this plugin mints an admin
1986
+ * session cookie that DSH's web server has to SEE to honour, and the proxy is
1987
+ * the only path that request takes. Relaying a name allowlist (rather than the
1988
+ * whole header) keeps both properties.
1952
1989
  * @returns headers safe to hand to `http.request`.
1953
1990
  */
1954
1991
  function buildUpstreamRequestHeaders(input) {
@@ -1965,21 +2002,36 @@ function buildUpstreamRequestHeaders(input) {
1965
2002
  outgoing[VISITOR_HEADER] = "1";
1966
2003
  outgoing.host = input.authority;
1967
2004
  if (input.headers.origin !== void 0) outgoing.origin = `http://${input.authority}`;
1968
- if (input.upstreamCookie !== void 0 && input.upstreamCookie !== "") outgoing.cookie = input.upstreamCookie;
2005
+ if (input.upstreamCookie !== void 0 && input.upstreamCookie !== "") {
2006
+ const relayed = (input.relayCookieNames ?? []).map((name) => cookiePairOf(input.headers.cookie, name)).filter((pair) => pair !== void 0);
2007
+ outgoing.cookie = relayed.length === 0 ? input.upstreamCookie : `${input.upstreamCookie}; ${relayed.join("; ")}`;
2008
+ }
1969
2009
  return outgoing;
1970
2010
  }
1971
2011
  /**
1972
2012
  * Filter an upstream response's headers for the browser.
1973
2013
  *
2014
+ * `set-cookie` stays dropped EXCEPT for the plugin's own cookie names (see
2015
+ * {@link buildUpstreamRequestHeaders}): DSH's own session cookie must never
2016
+ * reach a visitor, while this plugin's admin session has to be stored by the
2017
+ * visitor's browser or remote management could never unlock.
2018
+ *
1974
2019
  * @param headers - upstream response headers.
2020
+ * @param relayCookieNames - the plugin's own cookie names that may round-trip.
1975
2021
  * @returns headers safe to write to the visitor's response.
1976
2022
  */
1977
- function buildUpstreamResponseHeaders(headers) {
2023
+ function buildUpstreamResponseHeaders(headers, relayCookieNames = []) {
1978
2024
  const outgoing = {};
1979
- const dropped = /* @__PURE__ */ new Set([...HOP_BY_HOP_HEADERS, ...DROPPED_RESPONSE_HEADERS]);
2025
+ const dropped = new Set(HOP_BY_HOP_HEADERS);
1980
2026
  for (const [name, value] of Object.entries(headers)) {
1981
2027
  if (value === void 0) continue;
1982
- if (dropped.has(name.toLowerCase())) continue;
2028
+ const lower = name.toLowerCase();
2029
+ if (lower === "set-cookie") {
2030
+ const kept = toArray(value).filter((entry) => relayCookieNames.includes(setCookieName(entry) ?? ""));
2031
+ if (kept.length > 0) outgoing["set-cookie"] = kept;
2032
+ continue;
2033
+ }
2034
+ if (dropped.has(lower)) continue;
1983
2035
  outgoing[name] = value;
1984
2036
  }
1985
2037
  return outgoing;
@@ -2103,6 +2155,20 @@ function forwardUpgrade(options) {
2103
2155
  * The gate is NOT part of this module's P1 scope; P2 inserts it in front of
2104
2156
  * both the HTTP and the upgrade path.
2105
2157
  */
2158
+ /**
2159
+ * The visitor cookies this proxy relays in BOTH directions.
2160
+ *
2161
+ * The proxy injects DSH's loopback session cookie itself and never forwards the
2162
+ * visitor's other cookies (the gate session and the device identity belong to
2163
+ * the proxy origin). But this plugin mints its OWN admin session cookie, and the
2164
+ * only code that can validate it — the management route — runs on DSH's web
2165
+ * server, behind this proxy. Dropping it made `adminPolicy: password_unlock`
2166
+ * unsatisfiable for every remote device: the unlock POST returned 200 and the
2167
+ * very next request was locked again (reported 2026-09-26: "远程选了密码解锁,
2168
+ * 添加工作区里仍然是空的"). Relaying exactly this name keeps DSH's own cookie
2169
+ * out of the visitor's browser while letting the plugin's credential round-trip.
2170
+ */
2171
+ const RELAY_COOKIE_NAMES = [ADMIN_COOKIE];
2106
2172
  /** Bind one port, resolving on `listening` and rejecting on `error`. */
2107
2173
  function listenOnce(server, host, port) {
2108
2174
  return new Promise((resolve, reject) => {
@@ -2131,6 +2197,55 @@ function parseUpstream(origin) {
2131
2197
  function isSafeMethod(method) {
2132
2198
  return method === "GET" || method === "HEAD";
2133
2199
  }
2200
+ /** The peer address of a socket whose own typing does not carry one. */
2201
+ function peerOf(socket) {
2202
+ const address = socket.remoteAddress;
2203
+ return typeof address === "string" && address !== "" ? address : "unknown";
2204
+ }
2205
+ /**
2206
+ * Answer a plaintext HTTP request that reached the TLS port with a redirect to
2207
+ * the same address over `https`.
2208
+ *
2209
+ * Three facts shape this function:
2210
+ *
2211
+ * 1. it only ever runs for a connection whose handshake ALREADY failed, so it
2212
+ * cannot affect a working TLS session;
2213
+ * 2. the request line and headers are gone by then — the TLS parser consumed
2214
+ * and rejected them — so the redirect targets the root of the address the
2215
+ * client connected to, not the path it asked for;
2216
+ * 3. a plaintext reply cannot travel through the `TLSSocket` at all (writing to
2217
+ * it is encrypted into nothing — measured: the client receives zero bytes),
2218
+ * so only the raw socket underneath can carry it. Node exposes that as the
2219
+ * private `_parent`; the field is verified on Node 20, 22 and 24. When it is
2220
+ * absent — a future Node change — this returns false and the caller destroys
2221
+ * the socket, which is exactly the behaviour before this function existed.
2222
+ *
2223
+ * @param socket - the socket whose TLS handshake failed.
2224
+ * @param logger - logger, used only for the degraded path.
2225
+ * @returns whether the redirect was written.
2226
+ */
2227
+ function redirectPlaintextToHttps(socket, logger) {
2228
+ const raw = socket._parent;
2229
+ if (raw === void 0 || raw === null || raw.writable !== true || typeof raw.end !== "function") {
2230
+ logger.debug?.("plaintext redirect unavailable: no writable raw socket");
2231
+ return false;
2232
+ }
2233
+ const address = socket.localAddress;
2234
+ const port = socket.localPort;
2235
+ if (address === void 0 || address === "" || port === void 0) return false;
2236
+ const host = address.includes(":") ? `[${address}]` : address;
2237
+ try {
2238
+ raw.end.call(raw, `HTTP/1.1 301 Moved Permanently\r
2239
+ location: https://${host}:${String(port)}/\r\ncontent-length: 0\r
2240
+ connection: close\r
2241
+ \r
2242
+ `);
2243
+ return true;
2244
+ } catch (error) {
2245
+ logger.warn("plaintext redirect failed name=%s", error.name);
2246
+ return false;
2247
+ }
2248
+ }
2134
2249
  /**
2135
2250
  * Start the proxy listener.
2136
2251
  *
@@ -2165,7 +2280,8 @@ async function startProxy(options) {
2165
2280
  const headers = buildUpstreamRequestHeaders({
2166
2281
  headers: req.headers,
2167
2282
  authority,
2168
- upstreamCookie: cookie
2283
+ upstreamCookie: cookie,
2284
+ relayCookieNames: RELAY_COOKIE_NAMES
2169
2285
  });
2170
2286
  const upstreamReq = request({
2171
2287
  hostname: upstream.hostname,
@@ -2182,7 +2298,7 @@ async function startProxy(options) {
2182
2298
  forwardHttp(req, res, target, false);
2183
2299
  return;
2184
2300
  }
2185
- res.writeHead(status, upstreamRes.statusMessage === "" ? void 0 : upstreamRes.statusMessage, buildUpstreamResponseHeaders(upstreamRes.headers));
2301
+ res.writeHead(status, upstreamRes.statusMessage === "" ? void 0 : upstreamRes.statusMessage, buildUpstreamResponseHeaders(upstreamRes.headers, RELAY_COOKIE_NAMES));
2186
2302
  upstreamRes.pipe(res);
2187
2303
  });
2188
2304
  upstreamReq.on("error", (error) => {
@@ -2210,14 +2326,30 @@ async function startProxy(options) {
2210
2326
  await forwardHttp(req, res, normalizeRequestTarget(req.url), true);
2211
2327
  })();
2212
2328
  };
2213
- const server = options.tls === void 0 ? createServer(handler) : createServer$1({
2329
+ const httpsServer = options.tls === void 0 ? void 0 : createServer$1({
2214
2330
  cert: options.tls.cert,
2215
2331
  key: options.tls.key
2216
2332
  }, handler);
2333
+ const server = httpsServer ?? createServer(handler);
2217
2334
  server.on("connection", (socket) => {
2218
2335
  sockets.add(socket);
2219
2336
  socket.on("close", () => sockets.delete(socket));
2220
2337
  });
2338
+ if (httpsServer !== void 0) httpsServer.on("tlsClientError", (error, socket) => {
2339
+ const code = error.code ?? error.name;
2340
+ const plaintext = code === "ERR_SSL_HTTP_REQUEST";
2341
+ logger.warn("tls handshake failed code=%s plaintextHttp=%s ip=%s", code, plaintext ? "yes" : "no", peerOf(socket));
2342
+ if (plaintext && redirectPlaintextToHttps(socket, logger)) return;
2343
+ socket.destroy();
2344
+ });
2345
+ server.on("clientError", (error, socket) => {
2346
+ logger.warn("malformed request code=%s ip=%s", error.code ?? error.name, peerOf(socket));
2347
+ if (error.code === "ECONNRESET" || socket.writable !== true) {
2348
+ socket.destroy();
2349
+ return;
2350
+ }
2351
+ socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
2352
+ });
2221
2353
  server.on("upgrade", (req, socket, head) => {
2222
2354
  guardUpgradeSocket(socket, logger);
2223
2355
  (async () => {
@@ -2247,7 +2379,8 @@ async function startProxy(options) {
2247
2379
  headers: req.headers,
2248
2380
  authority,
2249
2381
  upstreamCookie: cookie,
2250
- upgrade: true
2382
+ upgrade: true,
2383
+ relayCookieNames: RELAY_COOKIE_NAMES
2251
2384
  }),
2252
2385
  logger
2253
2386
  });
@@ -2354,6 +2487,345 @@ async function buildAccessInfo(options) {
2354
2487
  }
2355
2488
  return info;
2356
2489
  }
2490
+ /**
2491
+ * Names that are never listed, never entered, and never accepted as a target.
2492
+ *
2493
+ * The list is the union of the reference implementation's and the obvious
2494
+ * credential stores; matching is case-insensitive so a macOS case-insensitive
2495
+ * volume cannot smuggle `.SSH` past it.
2496
+ */
2497
+ const SENSITIVE_NAMES = /* @__PURE__ */ new Set([
2498
+ ".ssh",
2499
+ ".gnupg",
2500
+ ".aws",
2501
+ ".azure",
2502
+ ".kube",
2503
+ ".git",
2504
+ ".svn",
2505
+ ".hg",
2506
+ ".env",
2507
+ ".npmrc",
2508
+ ".netrc",
2509
+ ".bash_history",
2510
+ ".zsh_history",
2511
+ ".profile",
2512
+ ".bash_profile",
2513
+ ".bashrc",
2514
+ ".zshrc",
2515
+ "id_rsa",
2516
+ "id_ed25519",
2517
+ "id_ecdsa",
2518
+ "id_dsa",
2519
+ "credentials",
2520
+ "shadow",
2521
+ "passwd",
2522
+ "system volume information",
2523
+ "$recycle.bin"
2524
+ ]);
2525
+ /** POSIX system prefixes, refused on the requested path AND on its realpath. */
2526
+ const POSIX_BLOCKED_PREFIXES = [
2527
+ "/etc",
2528
+ "/root",
2529
+ "/sys",
2530
+ "/proc",
2531
+ "/dev",
2532
+ "/boot",
2533
+ "/bin",
2534
+ "/sbin",
2535
+ "/lib",
2536
+ "/lib64",
2537
+ "/usr/bin",
2538
+ "/usr/sbin",
2539
+ "/private/etc",
2540
+ "/private/var/db",
2541
+ "/private/var/root",
2542
+ "/var/run",
2543
+ "/var/root",
2544
+ "/Library/Keychains",
2545
+ "/System/Library"
2546
+ ];
2547
+ /**
2548
+ * Windows system prefixes, compared against the part AFTER the drive letter
2549
+ * (or against a UNC path, which is refused outright).
2550
+ */
2551
+ const WINDOWS_BLOCKED_PREFIXES = [
2552
+ "windows",
2553
+ "winnt",
2554
+ "program files",
2555
+ "program files (x86)",
2556
+ "system volume information",
2557
+ "$recycle.bin",
2558
+ "recovery",
2559
+ "perflogs",
2560
+ "boot",
2561
+ "programdata\\microsoft"
2562
+ ];
2563
+ /** Whether this process is Windows. */
2564
+ const IS_WINDOWS = process.platform === "win32";
2565
+ /** Whether one path segment is a sensitive name. */
2566
+ function isSensitiveName(name) {
2567
+ return SENSITIVE_NAMES.has(name.trim().toLowerCase());
2568
+ }
2569
+ /**
2570
+ * Whether a path is FULLY QUALIFIED.
2571
+ *
2572
+ * `isAbsolute` alone is not enough on Windows: `\foo` and `/foo` are "rooted"
2573
+ * without naming a drive, so they resolve against the process's current drive
2574
+ * and are not the fixed location the caller meant. Both forms are refused, as
2575
+ * are UNC paths (a network share is not this machine's directory tree).
2576
+ *
2577
+ * @param candidate - the trimmed caller-supplied path.
2578
+ * @returns whether the path names one fixed location.
2579
+ */
2580
+ function isFullyQualified(candidate) {
2581
+ if (!IS_WINDOWS) return isAbsolute(candidate);
2582
+ if (/^[A-Za-z]:[\\/]/.test(candidate)) return true;
2583
+ return /^\\\\[^\\/]+[\\/][^\\/]+/.test(candidate);
2584
+ }
2585
+ /** The comparison key for one absolute path (case-insensitive on Windows). */
2586
+ function key(path) {
2587
+ return IS_WINDOWS ? path.toLowerCase() : path;
2588
+ }
2589
+ /**
2590
+ * Whether an absolute path sits in (or IS) a blocked system location.
2591
+ *
2592
+ * @param absolutePath - a resolved absolute path.
2593
+ * @returns the offending prefix, or `undefined` when the path is allowed.
2594
+ */
2595
+ function blockedPrefixOf(absolutePath) {
2596
+ const normalized = key(absolutePath);
2597
+ if (IS_WINDOWS) {
2598
+ if (normalized.startsWith("\\\\")) return "\\\\ (UNC)";
2599
+ const rest = /^[a-z]:\\(.*)$/.exec(normalized)?.[1];
2600
+ if (rest === void 0) return void 0;
2601
+ for (const prefix of WINDOWS_BLOCKED_PREFIXES) if (rest === prefix || rest.startsWith(`${prefix}\\`)) return prefix;
2602
+ return;
2603
+ }
2604
+ for (const prefix of POSIX_BLOCKED_PREFIXES) if (normalized === prefix || normalized.startsWith(`${prefix}${sep}`)) return prefix;
2605
+ }
2606
+ /**
2607
+ * Resolve one caller-supplied path to the canonical directory it names.
2608
+ *
2609
+ * The order matters: the cheap shape checks run first, then every segment is
2610
+ * screened, and only then is the path resolved through the filesystem — so a
2611
+ * symlink is followed to its real target and the WHOLE fence is applied again
2612
+ * to that target. A symlink therefore cannot be used to reach a blocked
2613
+ * directory, and a symlink cannot be used to reach a sensitive one either.
2614
+ *
2615
+ * @param raw - the caller-supplied path (`?path=` or a body field).
2616
+ * @returns the canonical directory path, or a stable failure.
2617
+ */
2618
+ async function resolveBrowsablePath(raw) {
2619
+ if (typeof raw !== "string" || raw.trim() === "") return {
2620
+ ok: false,
2621
+ error: "invalid_path",
2622
+ message: "路径不能为空"
2623
+ };
2624
+ const candidate = raw.trim();
2625
+ if (candidate.includes("\0")) return {
2626
+ ok: false,
2627
+ error: "invalid_path",
2628
+ message: "路径包含非法字符"
2629
+ };
2630
+ if (!isFullyQualified(candidate)) return {
2631
+ ok: false,
2632
+ error: "not_absolute",
2633
+ message: "必须使用完整的绝对路径"
2634
+ };
2635
+ const resolved = resolve(candidate);
2636
+ const segments = resolved.split(/[\\/]/).filter((part) => part !== "");
2637
+ for (const segment of segments) if (isSensitiveName(segment)) return {
2638
+ ok: false,
2639
+ error: "blocked",
2640
+ message: `禁止访问敏感目录「${segment}」`
2641
+ };
2642
+ const directBlock = blockedPrefixOf(resolved);
2643
+ if (directBlock !== void 0) return {
2644
+ ok: false,
2645
+ error: "blocked",
2646
+ message: `禁止访问系统目录「${directBlock}」`
2647
+ };
2648
+ let canonical;
2649
+ try {
2650
+ canonical = await realpath(resolved);
2651
+ } catch (error) {
2652
+ const code = error.code;
2653
+ if (code === "ENOENT" || code === "ENOTDIR") return {
2654
+ ok: false,
2655
+ error: "not_found",
2656
+ message: "目录不存在"
2657
+ };
2658
+ return {
2659
+ ok: false,
2660
+ error: "unreadable",
2661
+ message: `无法访问该目录(${code ?? "unknown"})`
2662
+ };
2663
+ }
2664
+ for (const segment of canonical.split(/[\\/]/).filter((part) => part !== "")) if (isSensitiveName(segment)) return {
2665
+ ok: false,
2666
+ error: "blocked",
2667
+ message: `符号链接指向敏感目录「${segment}」`
2668
+ };
2669
+ const realBlock = blockedPrefixOf(canonical);
2670
+ if (realBlock !== void 0) return {
2671
+ ok: false,
2672
+ error: "blocked",
2673
+ message: `符号链接指向系统目录「${realBlock}」`
2674
+ };
2675
+ try {
2676
+ if (!(await stat(canonical)).isDirectory()) return {
2677
+ ok: false,
2678
+ error: "not_a_directory",
2679
+ message: "该路径不是文件夹"
2680
+ };
2681
+ } catch (error) {
2682
+ return {
2683
+ ok: false,
2684
+ error: "unreadable",
2685
+ message: `无法访问该目录(${error.code ?? "unknown"})`
2686
+ };
2687
+ }
2688
+ return {
2689
+ ok: true,
2690
+ path: canonical
2691
+ };
2692
+ }
2693
+ /** The filesystem root for this platform (`/`, or the current drive's root). */
2694
+ function rootOf(path) {
2695
+ return parse(path).root === "" ? sep : parse(path).root;
2696
+ }
2697
+ /**
2698
+ * Build the root → current breadcrumb chain.
2699
+ *
2700
+ * Each crumb is a jump target, and the root keeps its full path as its name
2701
+ * (`/` on POSIX, `C:\` on Windows) because that is what it actually is.
2702
+ *
2703
+ * @param current - the canonical directory being listed.
2704
+ * @returns the chain, root first.
2705
+ */
2706
+ function crumbsOf(current) {
2707
+ const crumbs = [];
2708
+ let cursor = current;
2709
+ for (;;) {
2710
+ const root = rootOf(cursor);
2711
+ const name = basename(cursor);
2712
+ crumbs.push({
2713
+ name: name === "" ? cursor : name,
2714
+ path: cursor
2715
+ });
2716
+ if (key(cursor) === key(root)) break;
2717
+ const parent = resolve(cursor, "..");
2718
+ if (key(parent) === key(cursor)) break;
2719
+ cursor = parent;
2720
+ }
2721
+ return crumbs.reverse();
2722
+ }
2723
+ /** Shortcut rows that exist on this machine. */
2724
+ async function quickAccess() {
2725
+ const home = homedir();
2726
+ const rows = [{
2727
+ name: "🏠 用户主目录",
2728
+ path: home,
2729
+ hidden: false
2730
+ }];
2731
+ for (const item of [
2732
+ {
2733
+ name: "💻 桌面",
2734
+ segment: "Desktop"
2735
+ },
2736
+ {
2737
+ name: "📁 文档",
2738
+ segment: "Documents"
2739
+ },
2740
+ {
2741
+ name: "📥 下载",
2742
+ segment: "Downloads"
2743
+ },
2744
+ {
2745
+ name: "📦 Projects",
2746
+ segment: "Projects"
2747
+ },
2748
+ {
2749
+ name: "💻 code",
2750
+ segment: "code"
2751
+ },
2752
+ {
2753
+ name: "💻 src",
2754
+ segment: "src"
2755
+ }
2756
+ ]) {
2757
+ const candidate = join(home, item.segment);
2758
+ try {
2759
+ if ((await stat(candidate)).isDirectory()) rows.push({
2760
+ name: item.name,
2761
+ path: candidate,
2762
+ hidden: false
2763
+ });
2764
+ } catch {}
2765
+ }
2766
+ rows.push({
2767
+ name: IS_WINDOWS ? `${parse(home).root} 盘根目录` : "根目录 /",
2768
+ path: rootOf(home),
2769
+ hidden: false
2770
+ });
2771
+ return rows;
2772
+ }
2773
+ /**
2774
+ * List one directory level.
2775
+ *
2776
+ * Only DIRECTORIES are returned: a workspace is a folder, so files would be
2777
+ * noise on a phone. Symlinked directories are followed (that is how macOS
2778
+ * exposes `/tmp` and friends), but each target goes through the same fence as
2779
+ * an explicitly requested path — a link to a blocked or sensitive location is
2780
+ * silently skipped rather than listed as a dead row.
2781
+ *
2782
+ * @param raw - the requested absolute path; absent or blank lists the home directory.
2783
+ * @returns the listing, or a stable failure.
2784
+ */
2785
+ async function listDirectories(raw) {
2786
+ const resolved = await resolveBrowsablePath(typeof raw === "string" && raw.trim() !== "" ? raw : homedir());
2787
+ if (!resolved.ok) return resolved;
2788
+ const current = resolved.path;
2789
+ const entries = [];
2790
+ let truncated = false;
2791
+ try {
2792
+ const dirents = await readdir(current, { withFileTypes: true });
2793
+ dirents.sort((a, b) => a.name.localeCompare(b.name));
2794
+ for (const dirent of dirents) {
2795
+ if (isSensitiveName(dirent.name)) continue;
2796
+ const childPath = join(current, dirent.name);
2797
+ let isDirectory = dirent.isDirectory();
2798
+ if (dirent.isSymbolicLink()) {
2799
+ if (!(await resolveBrowsablePath(childPath)).ok) continue;
2800
+ isDirectory = true;
2801
+ }
2802
+ if (!isDirectory) continue;
2803
+ if (entries.length >= 1e3) {
2804
+ truncated = true;
2805
+ break;
2806
+ }
2807
+ entries.push({
2808
+ name: dirent.name,
2809
+ path: childPath,
2810
+ hidden: dirent.name.startsWith(".")
2811
+ });
2812
+ }
2813
+ } catch (error) {
2814
+ return {
2815
+ ok: false,
2816
+ error: "unreadable",
2817
+ message: `无法读取该目录(${error.code ?? "unknown"})`
2818
+ };
2819
+ }
2820
+ return {
2821
+ ok: true,
2822
+ path: current,
2823
+ crumbs: crumbsOf(current),
2824
+ quick: await quickAccess(),
2825
+ entries,
2826
+ truncated
2827
+ };
2828
+ }
2357
2829
  //#endregion
2358
2830
  //#region src/settings/index-tap.ts
2359
2831
  /** The page global DSH's connection client reads its transport facts from. */
@@ -2963,6 +3435,86 @@ function registerManagementRoutes(options) {
2963
3435
  handler: handleDevices
2964
3436
  }));
2965
3437
  /**
3438
+ * Remote workspace picker: ONE directory level per request.
3439
+ *
3440
+ * DSH resolves its directory-picker seam once at boot, and on a loopback-only
3441
+ * bind with a display that resolution is `native` — the OS folder dialog
3442
+ * opens on THIS machine's screen. A browser arriving through the LAN gateway
3443
+ * therefore cannot use "添加工作区" at all. The browser half of this plugin
3444
+ * shadows the official flow occupant and drives this route instead; the
3445
+ * picked path still goes back through DSH's own workspace flow, so nothing is
3446
+ * registered here.
3447
+ *
3448
+ * AUTHORITY: reading the host's directory tree is a privileged operation, so
3449
+ * it needs the SAME authority as every other management call — the machine's
3450
+ * own operator, or a remote session that unlocked the console. Under the
3451
+ * default `local_only` policy a remote device gets `read_only_remote`, which
3452
+ * the page explains instead of failing silently.
3453
+ *
3454
+ * RATE LIMIT: a runaway UI loop must not turn into unbounded filesystem
3455
+ * walks. The bucket is keyed by the socket address plus the visitor marker,
3456
+ * and because the proxy connects from loopback and does not forward the
3457
+ * client address, every proxied visitor shares ONE bucket — this is a runaway
3458
+ * guard, not a per-device quota.
3459
+ */
3460
+ const BROWSE_RATE_LIMIT = 240;
3461
+ const BROWSE_RATE_WINDOW_MS = 6e4;
3462
+ const browseBudget = /* @__PURE__ */ new Map();
3463
+ /** Consume one unit from the caller's budget; false when it is exhausted. */
3464
+ const overBrowseBudget = (req) => {
3465
+ const key = `${req.socket.remoteAddress ?? "unknown"}:${req.headers["x-dsh-lan-guard-visitor"] === void 0 ? "local" : "visitor"}`;
3466
+ const now = Date.now();
3467
+ if (browseBudget.size > 64) {
3468
+ for (const [existing, entry] of browseBudget) if (entry.resetAtMs <= now) browseBudget.delete(existing);
3469
+ }
3470
+ const bucket = browseBudget.get(key);
3471
+ if (bucket === void 0 || bucket.resetAtMs <= now) {
3472
+ browseBudget.set(key, {
3473
+ used: 1,
3474
+ resetAtMs: now + BROWSE_RATE_WINDOW_MS
3475
+ });
3476
+ return false;
3477
+ }
3478
+ bucket.used += 1;
3479
+ return bucket.used > BROWSE_RATE_LIMIT;
3480
+ };
3481
+ const handleWorkspaces = async (req, res) => {
3482
+ if (refusedByFence(req, res)) return;
3483
+ if (isRemoteReadOnly(req)) {
3484
+ sendJson(res, 403, {
3485
+ ok: false,
3486
+ error: "read_only_remote"
3487
+ });
3488
+ return;
3489
+ }
3490
+ if (needsAdmin(req)) {
3491
+ sendJson(res, 403, {
3492
+ ok: false,
3493
+ error: "admin_required"
3494
+ });
3495
+ return;
3496
+ }
3497
+ if (overBrowseBudget(req)) {
3498
+ sendJson(res, 429, {
3499
+ ok: false,
3500
+ error: "rate_limited"
3501
+ });
3502
+ return;
3503
+ }
3504
+ const result = await listDirectories(new URL(req.url ?? "/", "http://dsh-lan-guard.invalid").searchParams.get("path"));
3505
+ if (result.ok) {
3506
+ sendJson(res, 200, result);
3507
+ return;
3508
+ }
3509
+ const status = result.error === "blocked" ? 403 : result.error === "not_found" ? 404 : result.error === "unreadable" ? 500 : 400;
3510
+ sendJson(res, status, result);
3511
+ };
3512
+ disposers.push(options.webServer.register({
3513
+ kind: "exact",
3514
+ path: `${MANAGEMENT_BASE}/workspaces`,
3515
+ handler: handleWorkspaces
3516
+ }));
3517
+ /**
2966
3518
  * Update detection (SPEC F8). Read-only: it reports what npm has and the
2967
3519
  * settings page offers a copyable command — the host never installs anything.
2968
3520
  */