dsh-lan-guard 0.3.5 → 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";
@@ -1906,8 +1906,37 @@ const REPLACED_REQUEST_HEADERS = [
1906
1906
  "cookie",
1907
1907
  VISITOR_HEADER
1908
1908
  ];
1909
- /** Response headers dropped on top of the hop-by-hop set. */
1910
- 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
+ }
1911
1940
  /**
1912
1941
  * The `host:port` authority of an origin URL — the value the upstream fence
1913
1942
  * binds cookies to.
@@ -1950,6 +1979,13 @@ function normalizeRequestTarget(rawTarget) {
1950
1979
  * @param input.authority - upstream `host:port`.
1951
1980
  * @param input.upstreamCookie - the loopback session cookie to inject, if known.
1952
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.
1953
1989
  * @returns headers safe to hand to `http.request`.
1954
1990
  */
1955
1991
  function buildUpstreamRequestHeaders(input) {
@@ -1966,21 +2002,36 @@ function buildUpstreamRequestHeaders(input) {
1966
2002
  outgoing[VISITOR_HEADER] = "1";
1967
2003
  outgoing.host = input.authority;
1968
2004
  if (input.headers.origin !== void 0) outgoing.origin = `http://${input.authority}`;
1969
- 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
+ }
1970
2009
  return outgoing;
1971
2010
  }
1972
2011
  /**
1973
2012
  * Filter an upstream response's headers for the browser.
1974
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
+ *
1975
2019
  * @param headers - upstream response headers.
2020
+ * @param relayCookieNames - the plugin's own cookie names that may round-trip.
1976
2021
  * @returns headers safe to write to the visitor's response.
1977
2022
  */
1978
- function buildUpstreamResponseHeaders(headers) {
2023
+ function buildUpstreamResponseHeaders(headers, relayCookieNames = []) {
1979
2024
  const outgoing = {};
1980
- const dropped = /* @__PURE__ */ new Set([...HOP_BY_HOP_HEADERS, ...DROPPED_RESPONSE_HEADERS]);
2025
+ const dropped = new Set(HOP_BY_HOP_HEADERS);
1981
2026
  for (const [name, value] of Object.entries(headers)) {
1982
2027
  if (value === void 0) continue;
1983
- 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;
1984
2035
  outgoing[name] = value;
1985
2036
  }
1986
2037
  return outgoing;
@@ -2104,6 +2155,20 @@ function forwardUpgrade(options) {
2104
2155
  * The gate is NOT part of this module's P1 scope; P2 inserts it in front of
2105
2156
  * both the HTTP and the upgrade path.
2106
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];
2107
2172
  /** Bind one port, resolving on `listening` and rejecting on `error`. */
2108
2173
  function listenOnce(server, host, port) {
2109
2174
  return new Promise((resolve, reject) => {
@@ -2215,7 +2280,8 @@ async function startProxy(options) {
2215
2280
  const headers = buildUpstreamRequestHeaders({
2216
2281
  headers: req.headers,
2217
2282
  authority,
2218
- upstreamCookie: cookie
2283
+ upstreamCookie: cookie,
2284
+ relayCookieNames: RELAY_COOKIE_NAMES
2219
2285
  });
2220
2286
  const upstreamReq = request({
2221
2287
  hostname: upstream.hostname,
@@ -2232,7 +2298,7 @@ async function startProxy(options) {
2232
2298
  forwardHttp(req, res, target, false);
2233
2299
  return;
2234
2300
  }
2235
- 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));
2236
2302
  upstreamRes.pipe(res);
2237
2303
  });
2238
2304
  upstreamReq.on("error", (error) => {
@@ -2313,7 +2379,8 @@ async function startProxy(options) {
2313
2379
  headers: req.headers,
2314
2380
  authority,
2315
2381
  upstreamCookie: cookie,
2316
- upgrade: true
2382
+ upgrade: true,
2383
+ relayCookieNames: RELAY_COOKIE_NAMES
2317
2384
  }),
2318
2385
  logger
2319
2386
  });
@@ -2420,6 +2487,345 @@ async function buildAccessInfo(options) {
2420
2487
  }
2421
2488
  return info;
2422
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
+ }
2423
2829
  //#endregion
2424
2830
  //#region src/settings/index-tap.ts
2425
2831
  /** The page global DSH's connection client reads its transport facts from. */
@@ -3029,6 +3435,86 @@ function registerManagementRoutes(options) {
3029
3435
  handler: handleDevices
3030
3436
  }));
3031
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
+ /**
3032
3518
  * Update detection (SPEC F8). Read-only: it reports what npm has and the
3033
3519
  * settings page offers a copyable command — the host never installs anything.
3034
3520
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-lan-guard",
3
- "version": "0.3.5",
3
+ "version": "0.3.6",
4
4
  "description": "DSH web plugin: expose the official desktop Web UI to the local network through a gated reverse proxy, without touching DSH's own loopback binding.",
5
5
  "license": "MIT",
6
6
  "type": "module",