dsh-lan-guard 0.3.6 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -84,6 +84,10 @@ const Config = z.object({
84
84
  networkInterface: z.string().default("").volatile(),
85
85
  dataDir: z.string().default(""),
86
86
  settingsUnlock: z.boolean().default(true).volatile(),
87
+ answerHeartbeat: z.boolean().default(true).volatile(),
88
+ socketWatchdog: z.boolean().default(true).volatile(),
89
+ mobileCompat: z.boolean().default(true).volatile(),
90
+ mobileScrollFix: z.boolean().default(true).volatile(),
87
91
  auth: z.object({
88
92
  enabled: z.boolean().default(true),
89
93
  mode: z.union([
@@ -148,6 +152,10 @@ function liveSwitches(rawConfig, resolved) {
148
152
  listenPort: () => readField(root.listenPort, resolved.listenPort),
149
153
  listenHost: () => readField(root.listenHost, resolved.listenHost),
150
154
  settingsUnlock: () => readField(root.settingsUnlock, resolved.settingsUnlock),
155
+ answerHeartbeat: () => readField(root.answerHeartbeat, resolved.answerHeartbeat),
156
+ socketWatchdog: () => readField(root.socketWatchdog, resolved.socketWatchdog),
157
+ mobileCompat: () => readField(root.mobileCompat, resolved.mobileCompat),
158
+ mobileScrollFix: () => readField(root.mobileScrollFix, resolved.mobileScrollFix),
151
159
  mode: () => readField(root.auth === void 0 ? void 0 : auth.mode, resolved.auth.mode),
152
160
  adminPolicy: () => readField(root.auth === void 0 ? void 0 : auth.adminPolicy, resolved.auth.adminPolicy),
153
161
  adminProtection: () => readField(root.auth === void 0 ? void 0 : auth.adminProtection, resolved.auth.adminProtection),
@@ -164,6 +172,10 @@ function staticSwitches(config) {
164
172
  listenPort: () => config.listenPort,
165
173
  listenHost: () => config.listenHost,
166
174
  settingsUnlock: () => config.settingsUnlock,
175
+ answerHeartbeat: () => config.answerHeartbeat,
176
+ socketWatchdog: () => config.socketWatchdog,
177
+ mobileCompat: () => config.mobileCompat,
178
+ mobileScrollFix: () => config.mobileScrollFix,
167
179
  mode: () => config.auth.mode,
168
180
  adminPolicy: () => config.auth.adminPolicy,
169
181
  adminProtection: () => config.auth.adminProtection,
@@ -281,7 +293,11 @@ function unwrapVolatileInput(input) {
281
293
  "networkInterface",
282
294
  "listenPort",
283
295
  "listenHost",
284
- "settingsUnlock"
296
+ "settingsUnlock",
297
+ "answerHeartbeat",
298
+ "socketWatchdog",
299
+ "mobileCompat",
300
+ "mobileScrollFix"
285
301
  ]) {
286
302
  const value = result[key];
287
303
  if (isVolatileLike(value)) result[key] = value.get();
@@ -331,6 +347,10 @@ function parseConfig(input, profileDir) {
331
347
  networkInterface: emptyToNull(readField(resolved.networkInterface, "")),
332
348
  dataDir: dataDir?.dir ?? null,
333
349
  settingsUnlock: readField(resolved.settingsUnlock, true),
350
+ answerHeartbeat: readField(resolved.answerHeartbeat, true),
351
+ socketWatchdog: readField(resolved.socketWatchdog, true),
352
+ mobileCompat: readField(resolved.mobileCompat, true),
353
+ mobileScrollFix: readField(resolved.mobileScrollFix, true),
334
354
  auth: {
335
355
  enabled: readField(rawAuth.enabled, true),
336
356
  mode: readField(rawAuth.mode, "token_and_password"),
@@ -646,6 +666,10 @@ var AuthManager = class {
646
666
  networkInterface: null,
647
667
  dataDir: null,
648
668
  settingsUnlock: true,
669
+ answerHeartbeat: true,
670
+ socketWatchdog: true,
671
+ mobileCompat: true,
672
+ mobileScrollFix: true,
649
673
  auth: options.auth,
650
674
  tls: {
651
675
  mode: "off",
@@ -2062,6 +2086,171 @@ function buildUpgradeResponseHead(headers, statusCode, statusMessage) {
2062
2086
  }
2063
2087
  return `${lines.join("\r\n")}\r\n\r\n`;
2064
2088
  }
2089
+ /** A declared frame larger than this is garbage, not a frame. */
2090
+ const DEFAULT_MAX_FRAME_BYTES = 67108864;
2091
+ /**
2092
+ * Build one masked client→server frame.
2093
+ *
2094
+ * @param opcode - the frame opcode.
2095
+ * @param payload - at most 125 bytes (control frames only).
2096
+ * @param mask - a 4-byte mask.
2097
+ * @returns the encoded frame.
2098
+ */
2099
+ function maskedFrame(opcode, payload, mask) {
2100
+ if (payload.length > 125) throw new RangeError("dsh-lan-guard: a control frame payload is at most 125 bytes");
2101
+ const frame = Buffer.allocUnsafe(6 + payload.length);
2102
+ frame[0] = 128 | opcode & 15;
2103
+ frame[1] = 128 | payload.length;
2104
+ mask.copy(frame, 2);
2105
+ for (let index = 0; index < payload.length; index += 1) frame[6 + index] = (payload[index] ?? 0) ^ (mask[index % 4] ?? 0);
2106
+ return frame;
2107
+ }
2108
+ /** Unmask a payload captured from a masked frame. */
2109
+ function unmask(payload, mask) {
2110
+ if (mask === void 0 || mask.length !== 4) return payload;
2111
+ const copy = Buffer.from(payload);
2112
+ for (let index = 0; index < copy.length; index += 1) copy[index] = (copy[index] ?? 0) ^ (mask[index % 4] ?? 0);
2113
+ return copy;
2114
+ }
2115
+ /**
2116
+ * Create the observer.
2117
+ *
2118
+ * @param options - see {@link PingAnswererOptions}.
2119
+ * @returns the observer; safe to call with any chunk, including garbage.
2120
+ */
2121
+ function createUpstreamPingAnswerer(options) {
2122
+ const logger = options.logger ?? noopLogger;
2123
+ const maxFrameBytes = options.maxFrameBytes ?? DEFAULT_MAX_FRAME_BYTES;
2124
+ const counters = {
2125
+ frames: 0,
2126
+ pings: 0,
2127
+ answered: 0,
2128
+ payloadBytes: 0
2129
+ };
2130
+ /** Header bytes of the frame being parsed (never a payload). */
2131
+ let header = Buffer.alloc(0);
2132
+ /** Total header bytes the current frame needs (2, then possibly more). */
2133
+ let headerNeed = 2;
2134
+ /** Whether the parser is walking the payload of the current frame. */
2135
+ let inPayload = false;
2136
+ /** Payload bytes still to walk. */
2137
+ let remaining = 0;
2138
+ /** Captured Ping payload, when the frame is a Ping. */
2139
+ let captured;
2140
+ /** How many captured bytes were written so far. */
2141
+ let capturedAt = 0;
2142
+ /** Current frame's opcode and mask key. */
2143
+ let opcode = 0;
2144
+ let maskKey;
2145
+ let active = true;
2146
+ const reset = () => {
2147
+ header = Buffer.alloc(0);
2148
+ headerNeed = 2;
2149
+ inPayload = false;
2150
+ remaining = 0;
2151
+ captured = void 0;
2152
+ capturedAt = 0;
2153
+ maskKey = void 0;
2154
+ };
2155
+ const disable = (reason) => {
2156
+ if (!active) return;
2157
+ active = false;
2158
+ reset();
2159
+ logger.debug?.("upstream ping answerer disabled reason=%s", reason);
2160
+ };
2161
+ /** A fresh random mask per Pong, mirroring what a browser would send. */
2162
+ const freshMask = () => {
2163
+ const mask = Buffer.allocUnsafe(4);
2164
+ for (let index = 0; index < 4; index += 1) mask[index] = Math.floor(Math.random() * 256);
2165
+ return mask;
2166
+ };
2167
+ /** Current frame body finished: answer a Ping, then go back to header mode. */
2168
+ const finishFrame = () => {
2169
+ const payload = opcode === 9 ? unmask(captured ?? Buffer.alloc(0), maskKey) : void 0;
2170
+ reset();
2171
+ counters.frames += 1;
2172
+ if (payload === void 0) return;
2173
+ try {
2174
+ options.send(maskedFrame(10, payload, freshMask()));
2175
+ counters.answered += 1;
2176
+ } catch (error) {
2177
+ disable(`pong write failed name=${error.name}`);
2178
+ }
2179
+ };
2180
+ return {
2181
+ observe(chunk) {
2182
+ if (!active || chunk.length === 0) return;
2183
+ let cursor = 0;
2184
+ while (cursor < chunk.length) {
2185
+ if (!inPayload) {
2186
+ const take = Math.min(headerNeed - header.length, chunk.length - cursor);
2187
+ header = header.length === 0 ? chunk.subarray(cursor, cursor + take) : Buffer.concat([header, chunk.subarray(cursor, cursor + take)]);
2188
+ cursor += take;
2189
+ if (header.length < headerNeed) return;
2190
+ if (headerNeed === 2) {
2191
+ const second = header[1] ?? 0;
2192
+ const length7 = second & 127;
2193
+ const masked = (second & 128) !== 0;
2194
+ const need = 2 + (length7 === 126 ? 2 : length7 === 127 ? 8 : 0) + (masked ? 4 : 0);
2195
+ if (need > header.length) {
2196
+ headerNeed = need;
2197
+ continue;
2198
+ }
2199
+ }
2200
+ opcode = (header[0] ?? 0) & 15;
2201
+ const second = header[1] ?? 0;
2202
+ const length7 = second & 127;
2203
+ let length = length7;
2204
+ let offset = 2;
2205
+ if (length7 === 126) {
2206
+ length = header.readUInt16BE(2);
2207
+ offset = 4;
2208
+ } else if (length7 === 127) {
2209
+ const declared = header.readBigUInt64BE(2);
2210
+ if (declared > BigInt(maxFrameBytes)) {
2211
+ disable("declared frame larger than the sanity bound");
2212
+ return;
2213
+ }
2214
+ length = Number(declared);
2215
+ offset = 10;
2216
+ }
2217
+ if ((second & 128) !== 0) {
2218
+ maskKey = header.subarray(offset, offset + 4);
2219
+ offset += 4;
2220
+ } else maskKey = void 0;
2221
+ if (length > maxFrameBytes) {
2222
+ disable("frame larger than the sanity bound");
2223
+ return;
2224
+ }
2225
+ inPayload = true;
2226
+ remaining = length;
2227
+ if (opcode === 9) {
2228
+ counters.pings += 1;
2229
+ counters.payloadBytes += length;
2230
+ if (length > 125) {
2231
+ disable("ping payload longer than 125 bytes");
2232
+ return;
2233
+ }
2234
+ captured = Buffer.allocUnsafe(length);
2235
+ capturedAt = 0;
2236
+ } else captured = void 0;
2237
+ if (remaining === 0) finishFrame();
2238
+ continue;
2239
+ }
2240
+ const take = Math.min(remaining, chunk.length - cursor);
2241
+ if (captured !== void 0) {
2242
+ chunk.copy(captured, capturedAt, cursor, cursor + take);
2243
+ capturedAt += take;
2244
+ }
2245
+ remaining -= take;
2246
+ cursor += take;
2247
+ if (remaining === 0) finishFrame();
2248
+ }
2249
+ },
2250
+ stats: () => ({ ...counters }),
2251
+ active: () => active
2252
+ };
2253
+ }
2065
2254
  //#endregion
2066
2255
  //#region src/websocket.ts
2067
2256
  /**
@@ -2079,6 +2268,12 @@ function buildUpgradeResponseHead(headers, statusCode, statusMessage) {
2079
2268
  * take the whole process down. This is also why the gate in P2 can await
2080
2269
  * safely.
2081
2270
  * - The upstream 101 passes only the handshake headers a browser needs— never the upstream's arbitrary header set.
2271
+ *
2272
+ * A third rule was measured on 2026-09-28: the host pings every 2 s and
2273
+ * destroys a socket after two unanswered pings, so a phone that is suspended
2274
+ * loses the session socket after 6 s. With `answerHeartbeat` on,
2275
+ * {@link createUpstreamPingAnswerer} answers those pings from this hop; the
2276
+ * relay itself stays a byte-for-byte pipe in both directions.
2082
2277
  */
2083
2278
  /** Attach the mandatory `error` handler to a socket we now own. */
2084
2279
  function guardUpgradeSocket(socket, logger = noopLogger) {
@@ -2097,6 +2292,24 @@ function forwardUpgrade(options) {
2097
2292
  const { req, socket, head, upstream, headers, target } = options;
2098
2293
  const logger = options.logger ?? noopLogger;
2099
2294
  guardUpgradeSocket(socket, logger);
2295
+ const startedAtMs = Date.now();
2296
+ let answerer;
2297
+ let bytesToVisitor = 0;
2298
+ let bytesToUpstream = 0;
2299
+ let sawCloseFrame = false;
2300
+ let reported = false;
2301
+ const report = (outcome) => {
2302
+ if (reported) return;
2303
+ reported = true;
2304
+ options.onOutcome?.(target, {
2305
+ upgraded: outcome.upgraded,
2306
+ ...outcome.status === void 0 ? {} : { status: outcome.status },
2307
+ durationMs: Date.now() - startedAtMs,
2308
+ bytesToVisitor,
2309
+ bytesToUpstream,
2310
+ sawCloseFrame
2311
+ });
2312
+ };
2100
2313
  const upstreamReq = request({
2101
2314
  hostname: upstream.hostname,
2102
2315
  port: upstream.port,
@@ -2112,30 +2325,61 @@ function forwardUpgrade(options) {
2112
2325
  socket.on("close", () => upstreamDuplex.destroy());
2113
2326
  socket.write(buildUpgradeResponseHead(upstreamRes.headers, upstreamRes.statusCode ?? 101, upstreamRes.statusMessage === "" ? "Switching Protocols" : upstreamRes.statusMessage ?? "Switching Protocols"));
2114
2327
  if (upstreamHead.length > 0) socket.write(upstreamHead);
2328
+ options.onUpgraded?.(target);
2329
+ upstreamDuplex.on("data", (chunk) => {
2330
+ bytesToVisitor += chunk.length;
2331
+ if (((chunk[0] ?? 0) & 15) === 8) sawCloseFrame = true;
2332
+ });
2333
+ if (options.answerHeartbeat === true) {
2334
+ answerer = createUpstreamPingAnswerer({
2335
+ send: (frame) => {
2336
+ if (!upstreamDuplex.destroyed) upstreamDuplex.write(frame);
2337
+ },
2338
+ logger
2339
+ });
2340
+ const observer = answerer;
2341
+ upstreamDuplex.on("data", (chunk) => {
2342
+ observer.observe(chunk);
2343
+ });
2344
+ }
2345
+ socket.on("data", (chunk) => {
2346
+ bytesToUpstream += chunk.length;
2347
+ });
2348
+ socket.on("close", () => {
2349
+ report({ upgraded: true });
2350
+ });
2115
2351
  upstreamDuplex.pipe(socket);
2116
2352
  socket.pipe(upstreamDuplex);
2117
2353
  });
2118
2354
  upstreamReq.on("response", (upstreamRes) => {
2119
2355
  logger.debug?.("upgrade refused by upstream status=%d", upstreamRes.statusCode ?? 0);
2120
2356
  upstreamRes.resume();
2357
+ const status = upstreamRes.statusCode ?? 502;
2121
2358
  if (!socket.destroyed) {
2122
- const status = upstreamRes.statusCode ?? 502;
2123
2359
  const message = upstreamRes.statusMessage === "" ? "Upstream Refused" : upstreamRes.statusMessage ?? "Upstream Refused";
2124
- socket.write(`HTTP/1.1 ${status} ${message}\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`);
2360
+ socket.write(`HTTP/1.1 ${String(status)} ${message}\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`);
2125
2361
  }
2362
+ report({
2363
+ upgraded: false,
2364
+ status
2365
+ });
2126
2366
  socket.destroy();
2127
2367
  });
2128
2368
  upstreamReq.on("error", (error) => {
2129
2369
  logger.warn("upgrade upstream error name=%s", error.name);
2370
+ report({ upgraded: false });
2130
2371
  socket.destroy();
2131
2372
  });
2132
2373
  if (head.length > 0) upstreamReq.write(head);
2133
2374
  upstreamReq.end();
2134
- return { destroy() {
2135
- upstreamReq.destroy();
2136
- upstreamSocket?.destroy();
2137
- socket.destroy();
2138
- } };
2375
+ return {
2376
+ destroy() {
2377
+ upstreamReq.destroy();
2378
+ upstreamSocket?.destroy();
2379
+ socket.destroy();
2380
+ },
2381
+ heartbeatAnswered: () => answerer?.stats().answered ?? 0
2382
+ };
2139
2383
  }
2140
2384
  //#endregion
2141
2385
  //#region src/proxy.ts
@@ -2257,6 +2501,44 @@ async function startProxy(options) {
2257
2501
  const upstream = parseUpstream(options.upstreamOrigin);
2258
2502
  const authority = authorityOf(options.upstreamOrigin);
2259
2503
  const sockets = /* @__PURE__ */ new Set();
2504
+ /** Live read of the heartbeat switch; a plain boolean is a fixed decision. */
2505
+ const heartbeatEnabled = () => typeof options.answerHeartbeat === "function" ? options.answerHeartbeat() : options.answerHeartbeat === true;
2506
+ const recent = [];
2507
+ const liveTunnels = /* @__PURE__ */ new Set();
2508
+ let wsActive = 0;
2509
+ let wsUpgrades = 0;
2510
+ let wsRefused = 0;
2511
+ /** Pongs answered by tunnels that have already closed. */
2512
+ let heartbeatAnsweredClosed = 0;
2513
+ const recordRelay = (target, outcome) => {
2514
+ if (outcome.upgraded) wsActive = Math.max(0, wsActive - 1);
2515
+ else wsRefused += 1;
2516
+ recent.unshift({
2517
+ atMs: Date.now(),
2518
+ target,
2519
+ upgraded: outcome.upgraded,
2520
+ ...outcome.status === void 0 ? {} : { status: outcome.status },
2521
+ durationMs: outcome.durationMs,
2522
+ bytesToVisitor: outcome.bytesToVisitor,
2523
+ bytesToUpstream: outcome.bytesToUpstream,
2524
+ sawCloseFrame: outcome.sawCloseFrame
2525
+ });
2526
+ if (recent.length > 12) recent.pop();
2527
+ };
2528
+ const recordRefusal = (target, status) => {
2529
+ wsRefused += 1;
2530
+ recent.unshift({
2531
+ atMs: Date.now(),
2532
+ target,
2533
+ upgraded: false,
2534
+ status,
2535
+ durationMs: 0,
2536
+ bytesToVisitor: 0,
2537
+ bytesToUpstream: 0,
2538
+ sawCloseFrame: false
2539
+ });
2540
+ if (recent.length > 12) recent.pop();
2541
+ };
2260
2542
  const fail = (res, code, body) => {
2261
2543
  if (res.headersSent) {
2262
2544
  res.destroy();
@@ -2352,10 +2634,12 @@ async function startProxy(options) {
2352
2634
  });
2353
2635
  server.on("upgrade", (req, socket, head) => {
2354
2636
  guardUpgradeSocket(socket, logger);
2637
+ const upgradeTarget = normalizeRequestTarget(req.url);
2355
2638
  (async () => {
2356
2639
  if (options.gate !== void 0) {
2357
2640
  const refusal = await options.gate.verifyUpgrade(req);
2358
2641
  if (refusal !== void 0) {
2642
+ recordRefusal(upgradeTarget, refusal.status);
2359
2643
  if (!socket.destroyed) socket.write(`HTTP/1.1 ${String(refusal.status)} Unauthorized\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`);
2360
2644
  socket.destroy();
2361
2645
  return;
@@ -2366,15 +2650,17 @@ async function startProxy(options) {
2366
2650
  cookie = await options.auth.cookieHeader();
2367
2651
  } catch (error) {
2368
2652
  logger.warn("upgrade authentication failed name=%s", error.name);
2653
+ recordRefusal(upgradeTarget, 502);
2369
2654
  socket.destroy();
2370
2655
  return;
2371
2656
  }
2372
- forwardUpgrade({
2657
+ let tunnel;
2658
+ tunnel = forwardUpgrade({
2373
2659
  req,
2374
2660
  socket,
2375
2661
  head,
2376
2662
  upstream,
2377
- target: normalizeRequestTarget(req.url),
2663
+ target: upgradeTarget,
2378
2664
  headers: buildUpstreamRequestHeaders({
2379
2665
  headers: req.headers,
2380
2666
  authority,
@@ -2382,8 +2668,21 @@ async function startProxy(options) {
2382
2668
  upgrade: true,
2383
2669
  relayCookieNames: RELAY_COOKIE_NAMES
2384
2670
  }),
2385
- logger
2671
+ logger,
2672
+ answerHeartbeat: heartbeatEnabled(),
2673
+ onUpgraded: () => {
2674
+ wsActive += 1;
2675
+ wsUpgrades += 1;
2676
+ },
2677
+ onOutcome: (target, outcome) => {
2678
+ if (tunnel !== void 0) {
2679
+ liveTunnels.delete(tunnel);
2680
+ heartbeatAnsweredClosed += tunnel.heartbeatAnswered();
2681
+ }
2682
+ recordRelay(target, outcome);
2683
+ }
2386
2684
  });
2685
+ if (tunnel !== void 0) liveTunnels.add(tunnel);
2387
2686
  })();
2388
2687
  });
2389
2688
  const attempts = options.portProbeAttempts ?? 0;
@@ -2405,6 +2704,17 @@ async function startProxy(options) {
2405
2704
  port,
2406
2705
  requestedPort,
2407
2706
  portFallback: port !== requestedPort,
2707
+ stats() {
2708
+ let heartbeatAnswered = heartbeatAnsweredClosed;
2709
+ for (const tunnel of liveTunnels) heartbeatAnswered += tunnel.heartbeatAnswered();
2710
+ return {
2711
+ wsActive,
2712
+ wsUpgrades,
2713
+ wsRefused,
2714
+ heartbeatAnswered,
2715
+ recent: [...recent]
2716
+ };
2717
+ },
2408
2718
  close() {
2409
2719
  return new Promise((resolve, reject) => {
2410
2720
  server.close((error) => {
@@ -2830,13 +3140,16 @@ async function listDirectories(raw) {
2830
3140
  //#region src/settings/index-tap.ts
2831
3141
  /** The page global DSH's connection client reads its transport facts from. */
2832
3142
  const TRANSPORT_GLOBAL = "__DSH_TRANSPORT__";
2833
- /**
2834
- * Marker proving this file already injected the script.
2835
- *
2836
- * A tap runs once per index response, so this is a cheap idempotency guard for
2837
- * a second registration or a re-render of an already-transformed body.
2838
- */
3143
+ /** Page global listing which patches this page actually received (health panel). */
3144
+ const PATCHES_GLOBAL = "__DSH_LAN_GUARD__";
3145
+ /** Marker proving this file already injected the settings unlock. */
2839
3146
  const UNLOCK_MARKER = "/*dsh-lan-guard:settings-unlock*/";
3147
+ /** Marker proving the mobile compatibility shims were injected. */
3148
+ const MOBILE_COMPAT_MARKER = "/*dsh-lan-guard:mobile-compat*/";
3149
+ /** Marker proving the mobile metas were injected. */
3150
+ const MOBILE_META_MARKER = "<!--dsh-lan-guard:mobile-meta-->";
3151
+ /** Marker proving the socket watchdog was injected. */
3152
+ const SOCKET_WATCHDOG_MARKER = "/*dsh-lan-guard:socket-watchdog*/";
2840
3153
  /**
2841
3154
  * The exact head markup that makes the page look like the host's own surface.
2842
3155
  *
@@ -2847,22 +3160,132 @@ const UNLOCK_MARKER = "/*dsh-lan-guard:settings-unlock*/";
2847
3160
  * @returns one inline `<script>` element.
2848
3161
  */
2849
3162
  function settingsUnlockScript() {
2850
- return `<script>${UNLOCK_MARKER}(function(){var t=globalThis.${TRANSPORT_GLOBAL};globalThis.${TRANSPORT_GLOBAL}=Object.assign({},t!==null&&typeof t==="object"?t:{},{ownsHost:true});})()<\/script>`;
3163
+ return `<script>${UNLOCK_MARKER}(function(){var t=globalThis.${TRANSPORT_GLOBAL};globalThis.${TRANSPORT_GLOBAL}=Object.assign({},t!==null&&typeof t==="object"?t:{},{ownsHost:true});globalThis.${PATCHES_GLOBAL}=Object.assign({},globalThis.${PATCHES_GLOBAL},{settingsUnlock:true});})()<\/script>`;
2851
3164
  }
3165
+ /** Marker proving the mobile scroll fix was injected. */
3166
+ const MOBILE_SCROLL_MARKER = "/*dsh-lan-guard:mobile-scroll*/";
2852
3167
  /**
2853
- * Insert the unlock script into one index document.
3168
+ * The narrow-screen scroll correction (2026-09-28 user report: "聊天区无法上下滑动").
3169
+ *
3170
+ * Measured facts behind it:
3171
+ *
3172
+ * - On the SAME iPhone viewport in desktop Chrome the chat column scrolls fine
3173
+ * (a wheel scroll reveals «加载更早»), so the relay and the app are not broken;
3174
+ * the failure is iOS-specific layout/touch behaviour inside DSH's own shell —
3175
+ * whose root layer is `dsh-sc-layer` (`position:fixed`, full height,
3176
+ * `overflow-y:hidden`).
3177
+ * - On a phone the symptom is "content is visible, the bottom half is covered by
3178
+ * the fixed composer/goal/quick-reply floats, and the column cannot be dragged".
3179
+ *
3180
+ * The script is deliberately conservative and ONLY acts when the page as a whole
3181
+ * cannot scroll AND it finds a layer that is clipping overflowing content. Then
3182
+ * it turns exactly those layers into touch-scrollable ones. A page that can
3183
+ * already scroll (every desktop browser, and a healthy phone) is never touched.
3184
+ *
3185
+ * `?lgdiag=1` appends an on-screen report (and clears itself on reload); that is
3186
+ * the diagnostic that made this fix possible without a Mac attached to the
3187
+ * phone.
3188
+ *
3189
+ * @returns one inline `<script>` element.
3190
+ */
3191
+ function mobileScrollFixScript() {
3192
+ return `<script>${MOBILE_SCROLL_MARKER}(function(){try{var diag=/[?&]lgdiag/.test(self.location.search);var out=[];function log(s){out.push(s);if(diag)draw()}function draw(){try{var p=document.getElementById("lgsc");if(!p){p=document.createElement("pre");p.id="lgsc";p.style.cssText="position:fixed;left:0;top:0;right:0;height:46%;z-index:2147483647;background:rgba(0,0,0,.92);color:#0f0;font:10px/1.3 monospace;padding:6px;margin:0;overflow:auto;white-space:pre-wrap;pointer-events:none";(document.body||document.documentElement).appendChild(p)}p.textContent="[lan-guard 手机滚动诊断]"+String.fromCharCode(10)+out.join(String.fromCharCode(10))}catch(e){}}function pageScrolls(){var d=document.documentElement,b=document.body;return (d&&d.scrollHeight>d.clientHeight+8)||(b&&b.scrollHeight>b.clientHeight+8)}function clipping(){var r=[];var all=document.querySelectorAll("div");var lim=Math.min(all.length,5000);for(var i=0;i<lim;i++){var el=all[i];var cs=getComputedStyle(el);if(cs.overflowY!=="hidden"&&cs.overflowY!=="clip")continue;if(el.clientHeight<150)continue;if(el.scrollHeight<=el.clientHeight+8)continue;r.push(el)}r.sort(function(a,b){return (b.scrollHeight-b.clientHeight)-(a.scrollHeight-a.clientHeight)});return r}function run(){var narrow=self.matchMedia?self.matchMedia("(max-width: 1023px)").matches:false;var mobile=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent||"");log("narrow="+narrow+" mobile="+mobile+" innerH="+innerHeight+" vv="+(self.visualViewport?self.visualViewport.height:"-")+" pageScrolls="+pageScrolls());if(!narrow||!mobile)return;if(pageScrolls()){log("page already scrolls; no patch");return}var list=clipping();log("clippingLayers="+list.length);for(var i=0;i<list.length&&i<3;i++){var el=list[i];var cls=typeof el.className==="string"?el.className:"";log(" C"+i+" "+cls+" "+el.clientHeight+"/"+el.scrollHeight);el.style.setProperty("overflow-y","auto","important");el.style.setProperty("-webkit-overflow-scrolling","touch");el.style.setProperty("touch-action","pan-y","important");log(" C"+i+" patched -> scrollable="+(el.scrollHeight>el.clientHeight+8));}}var tries=0;run();var t=setInterval(function(){tries++;run();if(tries>15)clearInterval(t)},1200);}catch(e){}})()<\/script>`;
3193
+ }
3194
+ /**
3195
+ * Insert the narrow-screen scroll correction.
3196
+ *
3197
+ * @param html - the index body as DSH rendered it.
3198
+ * @returns the body with the correction inserted.
3199
+ */
3200
+ function injectMobileScrollFix(html) {
3201
+ if (html.includes("/*dsh-lan-guard:mobile-scroll*/")) return html;
3202
+ return insertAfterHead(html, mobileScrollFixScript());
3203
+ }
3204
+ /**
3205
+ * The mobile compatibility shims, in one inline script.
3206
+ *
3207
+ * Every branch is guarded by a `typeof` check, so a browser that already has
3208
+ * the API (or a future DSH that installs its own shim first) is untouched, and
3209
+ * the whole thing is wrapped in `try` so a hostile environment cannot break the
3210
+ * remaining scripts.
3211
+ *
3212
+ * @returns one inline `<script>` element.
3213
+ */
3214
+ function mobileCompatScript() {
3215
+ return `<script>${MOBILE_COMPAT_MARKER}(function(){try{var S=self.AbortSignal;if(S&&typeof S.any!=="function"){S.any=function(signals){var list=Array.prototype.slice.call(signals||[]);var c=new self.AbortController();var i;for(i=0;i<list.length;i++){if(list[i]&&list[i].aborted){try{c.abort(list[i].reason)}catch(e){c.abort()}return c.signal}}var off=function(ev){var src=ev&&ev.target?ev.target:ev;for(var j=0;j<list.length;j++){try{list[j].removeEventListener("abort",off)}catch(e){}}try{c.abort(src?src.reason:undefined)}catch(e){c.abort()}};for(i=0;i<list.length;i++){try{list[i].addEventListener("abort",off,{once:true})}catch(e){}}return c.signal}}if(S&&typeof S.timeout!=="function"){S.timeout=function(ms){var c=new self.AbortController();setTimeout(function(){try{c.abort(new Error("The operation timed out."))}catch(e){c.abort()}},Math.max(0,Number(ms)||0));return c.signal}}if(typeof Promise!=="undefined"&&typeof Promise.withResolvers!=="function"){Promise.withResolvers=function(){var resolve,reject;var promise=new Promise(function(res,rej){resolve=res;reject=rej});return{promise:promise,resolve:resolve,reject:reject}}}if(typeof self.Iterator==="undefined"){var proto=null;try{proto=Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))}catch(e){proto=null}var Shim=function Iterator(){};if(proto){Shim.prototype=proto}self.Iterator=Shim}globalThis.${PATCHES_GLOBAL}=Object.assign({},globalThis.${PATCHES_GLOBAL},{mobileCompat:true});}catch(e){}})()<\/script>`;
3216
+ }
3217
+ /** The mobile/PWA metas DSH's own index does not carry. */
3218
+ function mobileMetaMarkup() {
3219
+ return `${MOBILE_META_MARKER}<meta name="apple-mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"><meta name="apple-mobile-web-app-title" content="DSH"><meta name="theme-color" content="#1e1e2e">`;
3220
+ }
3221
+ /**
3222
+ * The client-side socket watchdog, in one inline script.
3223
+ *
3224
+ * Behaviour, in order of aggressiveness:
3225
+ *
3226
+ * 1. every `WebSocket` the page creates is tracked, and one still CONNECTING
3227
+ * after 8 s is closed so DSH's own retry loop advances instead of hanging;
3228
+ * 2. on `visibilitychange` → visible and on a bfcache `pageshow`, the page gets
3229
+ * a 10 s grace period; if by then at least one socket exists and none is
3230
+ * OPEN, the page is reloaded once;
3231
+ * 3. reloads are capped (3 in a row, counted in sessionStorage so a reload loop
3232
+ * cannot bootstrap itself) and rate-limited with a doubling cooldown; one
3233
+ * successful socket open clears the escalation.
2854
3234
  *
2855
- * The script goes immediately after the opening `<head>` tag — the same
2856
- * placement DSH uses for its own injected globals — and is prepended when the
2857
- * document has no head at all. A document that already carries
2858
- * {@link UNLOCK_MARKER} is returned untouched.
3235
+ * A page that never created a socket (the app failed to boot for some other
3236
+ * reason) is never reloaded.
3237
+ *
3238
+ * @returns one inline `<script>` element.
3239
+ */
3240
+ function socketWatchdogScript() {
3241
+ return `<script>${SOCKET_WATCHDOG_MARKER}(function(){try{var W=self.WebSocket;if(typeof W!=="function")return;var flags=globalThis.${PATCHES_GLOBAL};if(flags&&flags.socketWatchdog===true)return;globalThis.${PATCHES_GLOBAL}=Object.assign({},flags,{socketWatchdog:true});var CONNECT_TIMEOUT_MS=8000,STUCK_AFTER_MS=15000,RESUME_GRACE_MS=10000;var COOLDOWN_BASE_MS=20000,COOLDOWN_MAX_MS=300000,MAX_RELOADS=3;var sockets=[],firstSeenAt=0,lastOpenAt=0,hiddenAt=0,visibleSince=Date.now();var lastReloadAt=0,cooldown=COOLDOWN_BASE_MS;function readReloads(){try{return Number(self.sessionStorage.getItem("dshLanGuardReloads")||"0")||0}catch(e){return 0}}function writeReloads(n){try{self.sessionStorage.setItem("dshLanGuardReloads",String(n))}catch(e){}}var reloads=readReloads();function track(ws){sockets.push(ws);if(sockets.length>32)sockets.shift();if(firstSeenAt===0)firstSeenAt=Date.now();var timer=setTimeout(function(){try{if(ws.readyState===0)ws.close()}catch(e){}},CONNECT_TIMEOUT_MS);ws.addEventListener("open",function(){lastOpenAt=Date.now();reloads=0;writeReloads(0);cooldown=COOLDOWN_BASE_MS});ws.addEventListener("close",function(){clearTimeout(timer)});return ws}function Wrapped(url,protocols){var ws=protocols===undefined?new W(url):new W(url,protocols);return track(ws)}Wrapped.prototype=W.prototype;Wrapped.CONNECTING=0;Wrapped.OPEN=1;Wrapped.CLOSING=2;Wrapped.CLOSED=3;self.WebSocket=Wrapped;function openCount(){var n=0;for(var i=0;i<sockets.length;i++){if(sockets[i].readyState===1)n+=1}return n}function judge(reason){try{var doc=self.document;if(doc&&doc.visibilityState==="hidden")return;if(sockets.length===0)return;if(openCount()>0)return;var t=Date.now();if(t-visibleSince<RESUME_GRACE_MS)return;if(t-Math.max(lastOpenAt,firstSeenAt)<STUCK_AFTER_MS)return;if(lastReloadAt!==0&&t-lastReloadAt<cooldown)return;if(reloads>=MAX_RELOADS)return;reloads+=1;writeReloads(reloads);lastReloadAt=t;cooldown=Math.min(COOLDOWN_MAX_MS,cooldown*2);try{console.warn("[dsh-lan-guard] reloading: the session socket is not open ("+reason+")")}catch(e){}self.location.reload()}catch(e){}}setInterval(function(){judge("watchdog")},2000);var doc=self.document;if(doc&&typeof doc.addEventListener==="function"){doc.addEventListener("visibilitychange",function(){if(doc.visibilityState==="hidden"){hiddenAt=Date.now();return}if(hiddenAt!==0&&Date.now()-hiddenAt>1000){visibleSince=Date.now()}setTimeout(function(){judge("resume")},RESUME_GRACE_MS+500)})}if(typeof self.addEventListener==="function"){self.addEventListener("pageshow",function(event){if(event&&event.persisted){visibleSince=Date.now();setTimeout(function(){judge("bfcache")},RESUME_GRACE_MS+500)}})}}catch(e){}})()<\/script>`;
3242
+ }
3243
+ /**
3244
+ * Insert the unlock script into one index document.
2859
3245
  *
2860
3246
  * @param html - the index body as DSH rendered it.
2861
3247
  * @returns the body with the script inserted.
2862
3248
  */
2863
3249
  function injectSettingsUnlock(html) {
2864
3250
  if (html.includes("/*dsh-lan-guard:settings-unlock*/")) return html;
2865
- const markup = settingsUnlockScript();
3251
+ return insertAfterHead(html, settingsUnlockScript());
3252
+ }
3253
+ /**
3254
+ * Insert the mobile metas (and rewrite the viewport meta) plus the shims.
3255
+ *
3256
+ * The existing viewport meta is REPLACED rather than duplicated: with two
3257
+ * viewport metas the winner differs between engines, and `viewport-fit=cover`
3258
+ * (the notch) is the only part DSH's own tag lacks. Zoom stays enabled — this
3259
+ * plugin's mobile contract is about target sizes and horizontal scrolling, not
3260
+ * about taking the user's pinch gesture away.
3261
+ *
3262
+ * @param html - the index body as DSH rendered it.
3263
+ * @returns the body with the metas and shims inserted.
3264
+ */
3265
+ function injectMobileCompat(html) {
3266
+ if (html.includes("/*dsh-lan-guard:mobile-compat*/")) return html;
3267
+ return insertAfterHead(injectMobileMetas(html), mobileCompatScript());
3268
+ }
3269
+ /**
3270
+ * Insert the socket watchdog.
3271
+ *
3272
+ * @param html - the index body as DSH rendered it.
3273
+ * @returns the body with the watchdog inserted.
3274
+ */
3275
+ function injectSocketWatchdog(html) {
3276
+ if (html.includes("/*dsh-lan-guard:socket-watchdog*/")) return html;
3277
+ return insertAfterHead(html, socketWatchdogScript());
3278
+ }
3279
+ /** Add the mobile metas and upgrade the viewport tag, idempotently. */
3280
+ function injectMobileMetas(html) {
3281
+ if (html.includes("<!--dsh-lan-guard:mobile-meta-->")) return html;
3282
+ const viewport = /<meta\s+name=["']viewport["'][^>]*>/i;
3283
+ const replacement = "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, viewport-fit=cover\">" + mobileMetaMarkup();
3284
+ if (viewport.test(html)) return html.replace(viewport, replacement);
3285
+ return insertAfterHead(html, replacement);
3286
+ }
3287
+ /** Insert markup immediately after the opening `<head>`, or prepend it. */
3288
+ function insertAfterHead(html, markup) {
2866
3289
  const open = /<head(?:\s[^>]*)?>/i.exec(html);
2867
3290
  if (open === null) return `${markup}${html}`;
2868
3291
  const at = open.index + open[0].length;
@@ -2871,22 +3294,24 @@ function injectSettingsUnlock(html) {
2871
3294
  /**
2872
3295
  * Install the index tap, when the host exposes one.
2873
3296
  *
2874
- * `enabled` is read on EVERY index render rather than captured, so flipping the
2875
- * switch needs only a page refresh — never a restart.
2876
- *
2877
- * @param options.webServer - DSH's web server service (or a stub).
2878
- * @param options.enabled - the live `settingsUnlock` switch.
2879
- * @param options.logger - logger; a missing seam is a warning, not a failure.
3297
+ * @param options - see {@link RegisterIndexPatchesOptions}.
2880
3298
  * @returns the disposer removing the tap, or `undefined` when unsupported.
2881
3299
  */
2882
- function registerSettingsUnlock(options) {
3300
+ function registerIndexPatches(options) {
2883
3301
  const logger = options.logger ?? noopLogger;
2884
3302
  const tapIndex = options.webServer?.tapIndex;
2885
3303
  if (typeof tapIndex !== "function") {
2886
- logger.warn("webServer.tapIndex is unavailable; the remote settings-page unlock was not installed");
3304
+ logger.warn("webServer.tapIndex is unavailable; the index patches were not installed");
2887
3305
  return;
2888
3306
  }
2889
- return tapIndex.call(options.webServer, (html) => options.enabled() ? injectSettingsUnlock(html) : html);
3307
+ return tapIndex.call(options.webServer, (html) => {
3308
+ let out = html;
3309
+ if (options.switches.mobileCompat()) out = injectMobileCompat(out);
3310
+ if (options.switches.mobileScrollFix()) out = injectMobileScrollFix(out);
3311
+ if (options.switches.socketWatchdog()) out = injectSocketWatchdog(out);
3312
+ if (options.switches.settingsUnlock()) out = injectSettingsUnlock(out);
3313
+ return out;
3314
+ });
2890
3315
  }
2891
3316
  //#endregion
2892
3317
  //#region src/store/preferences.ts
@@ -2955,6 +3380,16 @@ function sanitizePreferencePatch(patch) {
2955
3380
  if (typeof source.settingsUnlock !== "boolean") throw new PreferenceError("settingsUnlock must be a boolean");
2956
3381
  result.settingsUnlock = source.settingsUnlock;
2957
3382
  }
3383
+ for (const key of [
3384
+ "answerHeartbeat",
3385
+ "socketWatchdog",
3386
+ "mobileCompat",
3387
+ "mobileScrollFix"
3388
+ ]) {
3389
+ if (!Object.hasOwn(source, key)) continue;
3390
+ if (typeof source[key] !== "boolean") throw new PreferenceError(`${key} must be a boolean`);
3391
+ result[key] = source[key];
3392
+ }
2958
3393
  if (Object.hasOwn(source, "requireApproval")) {
2959
3394
  if (typeof source.requireApproval !== "boolean") throw new PreferenceError("requireApproval must be a boolean");
2960
3395
  result.requireApproval = source.requireApproval;
@@ -2996,6 +3431,10 @@ function toSettingsPatch(values) {
2996
3431
  if (values.listenHost !== void 0) patch.listenHost = values.listenHost;
2997
3432
  if (values.networkInterface !== void 0) patch.networkInterface = values.networkInterface;
2998
3433
  if (values.settingsUnlock !== void 0) patch.settingsUnlock = values.settingsUnlock;
3434
+ if (values.answerHeartbeat !== void 0) patch.answerHeartbeat = values.answerHeartbeat;
3435
+ if (values.socketWatchdog !== void 0) patch.socketWatchdog = values.socketWatchdog;
3436
+ if (values.mobileCompat !== void 0) patch.mobileCompat = values.mobileCompat;
3437
+ if (values.mobileScrollFix !== void 0) patch.mobileScrollFix = values.mobileScrollFix;
2999
3438
  if (values.requirePairing !== void 0) auth.requirePairing = values.requirePairing;
3000
3439
  if (values.requireApproval !== void 0) auth.requireApproval = values.requireApproval;
3001
3440
  if (values.mode !== void 0) auth.mode = values.mode;
@@ -3129,6 +3568,10 @@ function registerManagementRoutes(options) {
3129
3568
  listenHost: options.switches.listenHost(),
3130
3569
  networkInterface: options.switches.networkInterface() ?? "",
3131
3570
  settingsUnlock: options.switches.settingsUnlock(),
3571
+ answerHeartbeat: options.switches.answerHeartbeat(),
3572
+ socketWatchdog: options.switches.socketWatchdog(),
3573
+ mobileCompat: options.switches.mobileCompat(),
3574
+ mobileScrollFix: options.switches.mobileScrollFix(),
3132
3575
  mode: options.switches.mode(),
3133
3576
  adminPolicy: options.switches.adminPolicy(),
3134
3577
  adminProtection: options.switches.adminProtection(),
@@ -3149,6 +3592,8 @@ function registerManagementRoutes(options) {
3149
3592
  pendingCount: options.devices.list().filter((device) => device.status === "pending").length
3150
3593
  };
3151
3594
  if (token !== void 0) snapshot.secretToken = token;
3595
+ const relay = options.relay;
3596
+ if (relay !== void 0) snapshot.connection = relay.stats();
3152
3597
  return snapshot;
3153
3598
  };
3154
3599
  /** Run the native fence; returns true when the request was refused. */
@@ -3553,21 +3998,27 @@ function registerManagementRoutes(options) {
3553
3998
  }
3554
3999
  }));
3555
4000
  /**
3556
- * Remote settings-page unlock.
4001
+ * Index patches: the remote settings-page unlock, the mobile compatibility
4002
+ * shims and the client-side socket watchdog.
3557
4003
  *
3558
4004
  * DSH disables its OFFICIAL settings surface for any page whose address bar
3559
4005
  * is not loopback, which is every device arriving through this gateway; the
3560
4006
  * proxy cannot change that because the decision is made in the visitor's
3561
- * browser. The index tap puts the flag DSH's desktop shell uses into the
3562
- * served document, and reads the live switch on every render so a toggle
3563
- * needs only a page refresh.
4007
+ * browser. The same tap is where the phone-side shims belong: both are
4008
+ * "the served document must carry this", and both read their live switch on
4009
+ * every render so a toggle needs only a page refresh.
3564
4010
  */
3565
- const disposeUnlock = registerSettingsUnlock({
4011
+ const disposePatches = registerIndexPatches({
3566
4012
  webServer: options.webServer,
3567
- enabled: () => options.switches.settingsUnlock(),
4013
+ switches: {
4014
+ settingsUnlock: () => options.switches.settingsUnlock(),
4015
+ mobileCompat: () => options.switches.mobileCompat(),
4016
+ mobileScrollFix: () => options.switches.mobileScrollFix(),
4017
+ socketWatchdog: () => options.switches.socketWatchdog()
4018
+ },
3568
4019
  logger
3569
4020
  });
3570
- if (disposeUnlock !== void 0) disposers.push(disposeUnlock);
4021
+ if (disposePatches !== void 0) disposers.push(disposePatches);
3571
4022
  return () => {
3572
4023
  for (const dispose of disposers.reverse()) dispose();
3573
4024
  };
@@ -4215,6 +4666,7 @@ async function startLanGuard(host, rawConfig) {
4215
4666
  upstreamOrigin: config.upstreamOrigin,
4216
4667
  auth: upstreamAuth,
4217
4668
  gate,
4669
+ answerHeartbeat: () => switches.answerHeartbeat(),
4218
4670
  ...tls === void 0 ? {} : { tls: {
4219
4671
  cert: tls.cert,
4220
4672
  key: tls.key
@@ -4249,7 +4701,8 @@ async function startLanGuard(host, rawConfig) {
4249
4701
  portFallback: () => proxy.portFallback
4250
4702
  },
4251
4703
  devices,
4252
- updates
4704
+ updates,
4705
+ relay: { stats: () => proxy.stats() }
4253
4706
  });
4254
4707
  if (proxy.portFallback) logger.warn("configured port %d was taken; listening on %d instead", proxy.requestedPort, proxy.port);
4255
4708
  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());
@@ -4375,6 +4828,7 @@ async function apply(ctx, rawConfig) {
4375
4828
  listener: deps.listener,
4376
4829
  devices: deps.devices,
4377
4830
  updates: deps.updates,
4831
+ ...deps.relay === void 0 ? {} : { relay: deps.relay },
4378
4832
  logger: deps.logger
4379
4833
  })
4380
4834
  }, rawConfig);