dsh-lan-guard 0.3.6 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +142 -0
- package/README.md +48 -3
- package/README.zh.md +46 -2
- package/lib/client.js +164 -0
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +81 -0
- package/lib/index.js +520 -41
- package/package.json +6 -5
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 {
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
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
|
-
|
|
2657
|
+
let tunnel;
|
|
2658
|
+
tunnel = forwardUpgrade({
|
|
2373
2659
|
req,
|
|
2374
2660
|
socket,
|
|
2375
2661
|
head,
|
|
2376
2662
|
upstream,
|
|
2377
|
-
target:
|
|
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
|
-
|
|
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,157 @@ 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
|
-
*
|
|
3168
|
+
* The narrow-screen scroll correction (2026-09-28 user report: "聊天区无法上下滑动").
|
|
3169
|
+
*
|
|
3170
|
+
* Measured facts behind it:
|
|
2854
3171
|
*
|
|
2855
|
-
*
|
|
2856
|
-
*
|
|
2857
|
-
*
|
|
2858
|
-
*
|
|
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
|
+
/**
|
|
3192
|
+
* 窄屏高度链修正(2026-09-28 第三次修订,照抄 dsh-mobile 的做法)。
|
|
3193
|
+
*
|
|
3194
|
+
* 事实(真机 + 官方源码 + 竞品对照):
|
|
3195
|
+
*
|
|
3196
|
+
* - 官方外壳在窄屏 iOS 下把内容裁在 `pI_x6G_frame`(实测 clientH 844 /
|
|
3197
|
+
* scrollH 1688),而 conversation 认定的滚动层 `[data-conversation-scroll]`
|
|
3198
|
+
* 始终 754/754:内容根本没进它的流。结果:手指拖不动、官方「回到底部」
|
|
3199
|
+
* 按钮点了没反应、打开会话也不会自动停到最新消息。
|
|
3200
|
+
* - dsh-mobile 能做对,靠的是**高度链**而不是滚动补丁:
|
|
3201
|
+
* `html,body,#root{height:100%;overflow:hidden}` +
|
|
3202
|
+
* shell `height:100dvh` + 主区 `min-height:0`(flex 子项允许收缩)。
|
|
3203
|
+
*
|
|
3204
|
+
* 因此本脚本只做同一件事,并且**绝不改任何 overflow-y、绝不新建滚动容器、
|
|
3205
|
+
* 绝不加自己的按钮**:
|
|
3206
|
+
*
|
|
3207
|
+
* 1. 给 `html/body/#root` 一个确定高度(`100%`,支持时 `100dvh`)并锁住页面滚动;
|
|
3208
|
+
* 2. 沿着「被裁且内容溢出」的那一层,给链上所有 flex/grid 容器补 `min-height:0`;
|
|
3209
|
+
* 3. 立刻验证官方认定的滚动层是否真的能滚了:能 → 保留;不能 → **全部撤销**,
|
|
3210
|
+
* 页面回到与官方逐字节一致的状态(宁可不动,也不引入第二个滚动层)。
|
|
3211
|
+
*
|
|
3212
|
+
* 抽屉/遮罩打开时同样先撤销自己(0.4.2 的遮罩事故教训)。
|
|
3213
|
+
*
|
|
3214
|
+
* @returns one inline `<script>` element.
|
|
3215
|
+
*/
|
|
3216
|
+
function mobileScrollFixScript() {
|
|
3217
|
+
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){}}var touched=[];function set(el,prop,val){if(!el)return;try{el.style.setProperty(prop,val,"important");touched.push([el,prop])}catch(e){}}function undoAll(){for(var i=0;i<touched.length;i++){try{touched[i][0].style.removeProperty(touched[i][1])}catch(e){}}touched=[]}function conv(){try{return document.querySelector("[data-conversation-scroll]")}catch(e){return null}}function convScrolls(){var c=conv();return !!c&&c.scrollHeight>c.clientHeight+8}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 overlayOpen(){try{if(document.querySelector("[aria-modal=true],[role=dialog],[data-conversation-overlay]"))return true;var el=document.elementFromPoint(Math.round(innerWidth*0.92),Math.round(innerHeight*0.45));while(el&&el!==document.body){var cs=getComputedStyle(el);if((cs.position==="fixed"||cs.position==="absolute")&&cs.pointerEvents!=="none"){var r=el.getBoundingClientRect();if(r.width>innerWidth*0.85&&r.height>innerHeight*0.7)return true}el=el.parentElement}}catch(e){}return false}function touchPassThrough(){var layers=document.querySelectorAll("div");var lim=Math.min(layers.length,5000);var n=0;for(var i=0;i<lim;i++){var el=layers[i];var cs=getComputedStyle(el);if(cs.position!=="fixed"&&cs.position!=="absolute")continue;if(cs.pointerEvents==="none")continue;var r=el.getBoundingClientRect();if(r.width<innerWidth*0.9||r.height<innerHeight*0.8)continue;if(el.querySelector("button,input,textarea,select,[contenteditable]"))continue;if((el.textContent||"").length>40)continue;el.style.setProperty("pointer-events","none","important");n++}log("touch passthrough layers="+n);return n}function fix(){if(convScrolls()){log("official scroll layer works; done");return true}var list=clipping();var clip=list[0];log("clipping="+list.length+(clip?(" first="+String(typeof clip.className==="string"?clip.className:"")+" "+clip.clientHeight+"/"+clip.scrollHeight):""));var root=document.getElementById("root");set(document.documentElement,"height","100%");set(document.body,"height","100%");set(document.body,"overflow","hidden");set(root,"height","100dvh");set(root,"min-height","0");set(root,"overflow","hidden");var n=clip,d=0;while(n&&n!==document.body&&d<8){var cs=getComputedStyle(n);if(cs.display.indexOf("flex")>=0||cs.display.indexOf("grid")>=0)set(n,"min-height","0");n=n.parentElement;d++}var ok=convScrolls();log("chainFix convScroll="+(conv()?(conv().clientHeight+"/"+conv().scrollHeight):"n/a")+" scrollable="+ok);if(!ok){undoAll();log("ineffective -> reverted (stock page)")}return ok}var done=false,tries=0;function run(){if(done)return;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){done=true;return}if(overlayOpen()){undoAll();log("overlay/dialog open -> reverted");return}touchPassThrough();if(convScrolls()){log("official scroll layer already works");done=true;return}if(fix())done=true}run();var t=setInterval(function(){tries++;run();if(done||tries>30)clearInterval(t)},1500);}catch(e){}})()<\/script>`;
|
|
3218
|
+
}
|
|
3219
|
+
/**
|
|
3220
|
+
* Insert the narrow-screen scroll correction.
|
|
3221
|
+
*
|
|
3222
|
+
* @param html - the index body as DSH rendered it.
|
|
3223
|
+
* @returns the body with the correction inserted.
|
|
3224
|
+
*/
|
|
3225
|
+
function injectMobileScrollFix(html) {
|
|
3226
|
+
if (html.includes("/*dsh-lan-guard:mobile-scroll*/")) return html;
|
|
3227
|
+
return insertAfterHead(html, mobileScrollFixScript());
|
|
3228
|
+
}
|
|
3229
|
+
/**
|
|
3230
|
+
* The mobile compatibility shims, in one inline script.
|
|
3231
|
+
*
|
|
3232
|
+
* Every branch is guarded by a `typeof` check, so a browser that already has
|
|
3233
|
+
* the API (or a future DSH that installs its own shim first) is untouched, and
|
|
3234
|
+
* the whole thing is wrapped in `try` so a hostile environment cannot break the
|
|
3235
|
+
* remaining scripts.
|
|
3236
|
+
*
|
|
3237
|
+
* @returns one inline `<script>` element.
|
|
3238
|
+
*/
|
|
3239
|
+
function mobileCompatScript() {
|
|
3240
|
+
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>`;
|
|
3241
|
+
}
|
|
3242
|
+
/** The mobile/PWA metas DSH's own index does not carry. */
|
|
3243
|
+
function mobileMetaMarkup() {
|
|
3244
|
+
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">`;
|
|
3245
|
+
}
|
|
3246
|
+
/**
|
|
3247
|
+
* The client-side socket watchdog, in one inline script.
|
|
3248
|
+
*
|
|
3249
|
+
* Behaviour, in order of aggressiveness:
|
|
3250
|
+
*
|
|
3251
|
+
* 1. every `WebSocket` the page creates is tracked, and one still CONNECTING
|
|
3252
|
+
* after 8 s is closed so DSH's own retry loop advances instead of hanging;
|
|
3253
|
+
* 2. on `visibilitychange` → visible and on a bfcache `pageshow`, the page gets
|
|
3254
|
+
* a 10 s grace period; if by then at least one socket exists and none is
|
|
3255
|
+
* OPEN, the page is reloaded once;
|
|
3256
|
+
* 3. reloads are capped (3 in a row, counted in sessionStorage so a reload loop
|
|
3257
|
+
* cannot bootstrap itself) and rate-limited with a doubling cooldown; one
|
|
3258
|
+
* successful socket open clears the escalation.
|
|
3259
|
+
*
|
|
3260
|
+
* A page that never created a socket (the app failed to boot for some other
|
|
3261
|
+
* reason) is never reloaded.
|
|
3262
|
+
*
|
|
3263
|
+
* @returns one inline `<script>` element.
|
|
3264
|
+
*/
|
|
3265
|
+
function socketWatchdogScript() {
|
|
3266
|
+
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>`;
|
|
3267
|
+
}
|
|
3268
|
+
/**
|
|
3269
|
+
* Insert the unlock script into one index document.
|
|
2859
3270
|
*
|
|
2860
3271
|
* @param html - the index body as DSH rendered it.
|
|
2861
3272
|
* @returns the body with the script inserted.
|
|
2862
3273
|
*/
|
|
2863
3274
|
function injectSettingsUnlock(html) {
|
|
2864
3275
|
if (html.includes("/*dsh-lan-guard:settings-unlock*/")) return html;
|
|
2865
|
-
|
|
3276
|
+
return insertAfterHead(html, settingsUnlockScript());
|
|
3277
|
+
}
|
|
3278
|
+
/**
|
|
3279
|
+
* Insert the mobile metas (and rewrite the viewport meta) plus the shims.
|
|
3280
|
+
*
|
|
3281
|
+
* The existing viewport meta is REPLACED rather than duplicated: with two
|
|
3282
|
+
* viewport metas the winner differs between engines, and `viewport-fit=cover`
|
|
3283
|
+
* (the notch) is the only part DSH's own tag lacks. Zoom stays enabled — this
|
|
3284
|
+
* plugin's mobile contract is about target sizes and horizontal scrolling, not
|
|
3285
|
+
* about taking the user's pinch gesture away.
|
|
3286
|
+
*
|
|
3287
|
+
* @param html - the index body as DSH rendered it.
|
|
3288
|
+
* @returns the body with the metas and shims inserted.
|
|
3289
|
+
*/
|
|
3290
|
+
function injectMobileCompat(html) {
|
|
3291
|
+
if (html.includes("/*dsh-lan-guard:mobile-compat*/")) return html;
|
|
3292
|
+
return insertAfterHead(injectMobileMetas(html), mobileCompatScript());
|
|
3293
|
+
}
|
|
3294
|
+
/**
|
|
3295
|
+
* Insert the socket watchdog.
|
|
3296
|
+
*
|
|
3297
|
+
* @param html - the index body as DSH rendered it.
|
|
3298
|
+
* @returns the body with the watchdog inserted.
|
|
3299
|
+
*/
|
|
3300
|
+
function injectSocketWatchdog(html) {
|
|
3301
|
+
if (html.includes("/*dsh-lan-guard:socket-watchdog*/")) return html;
|
|
3302
|
+
return insertAfterHead(html, socketWatchdogScript());
|
|
3303
|
+
}
|
|
3304
|
+
/** Add the mobile metas and upgrade the viewport tag, idempotently. */
|
|
3305
|
+
function injectMobileMetas(html) {
|
|
3306
|
+
if (html.includes("<!--dsh-lan-guard:mobile-meta-->")) return html;
|
|
3307
|
+
const viewport = /<meta\s+name=["']viewport["'][^>]*>/i;
|
|
3308
|
+
const replacement = "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, viewport-fit=cover\">" + mobileMetaMarkup();
|
|
3309
|
+
if (viewport.test(html)) return html.replace(viewport, replacement);
|
|
3310
|
+
return insertAfterHead(html, replacement);
|
|
3311
|
+
}
|
|
3312
|
+
/** Insert markup immediately after the opening `<head>`, or prepend it. */
|
|
3313
|
+
function insertAfterHead(html, markup) {
|
|
2866
3314
|
const open = /<head(?:\s[^>]*)?>/i.exec(html);
|
|
2867
3315
|
if (open === null) return `${markup}${html}`;
|
|
2868
3316
|
const at = open.index + open[0].length;
|
|
@@ -2871,22 +3319,24 @@ function injectSettingsUnlock(html) {
|
|
|
2871
3319
|
/**
|
|
2872
3320
|
* Install the index tap, when the host exposes one.
|
|
2873
3321
|
*
|
|
2874
|
-
*
|
|
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.
|
|
3322
|
+
* @param options - see {@link RegisterIndexPatchesOptions}.
|
|
2880
3323
|
* @returns the disposer removing the tap, or `undefined` when unsupported.
|
|
2881
3324
|
*/
|
|
2882
|
-
function
|
|
3325
|
+
function registerIndexPatches(options) {
|
|
2883
3326
|
const logger = options.logger ?? noopLogger;
|
|
2884
3327
|
const tapIndex = options.webServer?.tapIndex;
|
|
2885
3328
|
if (typeof tapIndex !== "function") {
|
|
2886
|
-
logger.warn("webServer.tapIndex is unavailable; the
|
|
3329
|
+
logger.warn("webServer.tapIndex is unavailable; the index patches were not installed");
|
|
2887
3330
|
return;
|
|
2888
3331
|
}
|
|
2889
|
-
return tapIndex.call(options.webServer, (html) =>
|
|
3332
|
+
return tapIndex.call(options.webServer, (html) => {
|
|
3333
|
+
let out = html;
|
|
3334
|
+
if (options.switches.mobileCompat()) out = injectMobileCompat(out);
|
|
3335
|
+
if (options.switches.mobileScrollFix()) out = injectMobileScrollFix(out);
|
|
3336
|
+
if (options.switches.socketWatchdog()) out = injectSocketWatchdog(out);
|
|
3337
|
+
if (options.switches.settingsUnlock()) out = injectSettingsUnlock(out);
|
|
3338
|
+
return out;
|
|
3339
|
+
});
|
|
2890
3340
|
}
|
|
2891
3341
|
//#endregion
|
|
2892
3342
|
//#region src/store/preferences.ts
|
|
@@ -2955,6 +3405,16 @@ function sanitizePreferencePatch(patch) {
|
|
|
2955
3405
|
if (typeof source.settingsUnlock !== "boolean") throw new PreferenceError("settingsUnlock must be a boolean");
|
|
2956
3406
|
result.settingsUnlock = source.settingsUnlock;
|
|
2957
3407
|
}
|
|
3408
|
+
for (const key of [
|
|
3409
|
+
"answerHeartbeat",
|
|
3410
|
+
"socketWatchdog",
|
|
3411
|
+
"mobileCompat",
|
|
3412
|
+
"mobileScrollFix"
|
|
3413
|
+
]) {
|
|
3414
|
+
if (!Object.hasOwn(source, key)) continue;
|
|
3415
|
+
if (typeof source[key] !== "boolean") throw new PreferenceError(`${key} must be a boolean`);
|
|
3416
|
+
result[key] = source[key];
|
|
3417
|
+
}
|
|
2958
3418
|
if (Object.hasOwn(source, "requireApproval")) {
|
|
2959
3419
|
if (typeof source.requireApproval !== "boolean") throw new PreferenceError("requireApproval must be a boolean");
|
|
2960
3420
|
result.requireApproval = source.requireApproval;
|
|
@@ -2996,6 +3456,10 @@ function toSettingsPatch(values) {
|
|
|
2996
3456
|
if (values.listenHost !== void 0) patch.listenHost = values.listenHost;
|
|
2997
3457
|
if (values.networkInterface !== void 0) patch.networkInterface = values.networkInterface;
|
|
2998
3458
|
if (values.settingsUnlock !== void 0) patch.settingsUnlock = values.settingsUnlock;
|
|
3459
|
+
if (values.answerHeartbeat !== void 0) patch.answerHeartbeat = values.answerHeartbeat;
|
|
3460
|
+
if (values.socketWatchdog !== void 0) patch.socketWatchdog = values.socketWatchdog;
|
|
3461
|
+
if (values.mobileCompat !== void 0) patch.mobileCompat = values.mobileCompat;
|
|
3462
|
+
if (values.mobileScrollFix !== void 0) patch.mobileScrollFix = values.mobileScrollFix;
|
|
2999
3463
|
if (values.requirePairing !== void 0) auth.requirePairing = values.requirePairing;
|
|
3000
3464
|
if (values.requireApproval !== void 0) auth.requireApproval = values.requireApproval;
|
|
3001
3465
|
if (values.mode !== void 0) auth.mode = values.mode;
|
|
@@ -3129,6 +3593,10 @@ function registerManagementRoutes(options) {
|
|
|
3129
3593
|
listenHost: options.switches.listenHost(),
|
|
3130
3594
|
networkInterface: options.switches.networkInterface() ?? "",
|
|
3131
3595
|
settingsUnlock: options.switches.settingsUnlock(),
|
|
3596
|
+
answerHeartbeat: options.switches.answerHeartbeat(),
|
|
3597
|
+
socketWatchdog: options.switches.socketWatchdog(),
|
|
3598
|
+
mobileCompat: options.switches.mobileCompat(),
|
|
3599
|
+
mobileScrollFix: options.switches.mobileScrollFix(),
|
|
3132
3600
|
mode: options.switches.mode(),
|
|
3133
3601
|
adminPolicy: options.switches.adminPolicy(),
|
|
3134
3602
|
adminProtection: options.switches.adminProtection(),
|
|
@@ -3149,6 +3617,8 @@ function registerManagementRoutes(options) {
|
|
|
3149
3617
|
pendingCount: options.devices.list().filter((device) => device.status === "pending").length
|
|
3150
3618
|
};
|
|
3151
3619
|
if (token !== void 0) snapshot.secretToken = token;
|
|
3620
|
+
const relay = options.relay;
|
|
3621
|
+
if (relay !== void 0) snapshot.connection = relay.stats();
|
|
3152
3622
|
return snapshot;
|
|
3153
3623
|
};
|
|
3154
3624
|
/** Run the native fence; returns true when the request was refused. */
|
|
@@ -3553,21 +4023,27 @@ function registerManagementRoutes(options) {
|
|
|
3553
4023
|
}
|
|
3554
4024
|
}));
|
|
3555
4025
|
/**
|
|
3556
|
-
*
|
|
4026
|
+
* Index patches: the remote settings-page unlock, the mobile compatibility
|
|
4027
|
+
* shims and the client-side socket watchdog.
|
|
3557
4028
|
*
|
|
3558
4029
|
* DSH disables its OFFICIAL settings surface for any page whose address bar
|
|
3559
4030
|
* is not loopback, which is every device arriving through this gateway; the
|
|
3560
4031
|
* proxy cannot change that because the decision is made in the visitor's
|
|
3561
|
-
* browser. The
|
|
3562
|
-
* served document, and
|
|
3563
|
-
* needs only a page refresh.
|
|
4032
|
+
* browser. The same tap is where the phone-side shims belong: both are
|
|
4033
|
+
* "the served document must carry this", and both read their live switch on
|
|
4034
|
+
* every render so a toggle needs only a page refresh.
|
|
3564
4035
|
*/
|
|
3565
|
-
const
|
|
4036
|
+
const disposePatches = registerIndexPatches({
|
|
3566
4037
|
webServer: options.webServer,
|
|
3567
|
-
|
|
4038
|
+
switches: {
|
|
4039
|
+
settingsUnlock: () => options.switches.settingsUnlock(),
|
|
4040
|
+
mobileCompat: () => options.switches.mobileCompat(),
|
|
4041
|
+
mobileScrollFix: () => options.switches.mobileScrollFix(),
|
|
4042
|
+
socketWatchdog: () => options.switches.socketWatchdog()
|
|
4043
|
+
},
|
|
3568
4044
|
logger
|
|
3569
4045
|
});
|
|
3570
|
-
if (
|
|
4046
|
+
if (disposePatches !== void 0) disposers.push(disposePatches);
|
|
3571
4047
|
return () => {
|
|
3572
4048
|
for (const dispose of disposers.reverse()) dispose();
|
|
3573
4049
|
};
|
|
@@ -4215,6 +4691,7 @@ async function startLanGuard(host, rawConfig) {
|
|
|
4215
4691
|
upstreamOrigin: config.upstreamOrigin,
|
|
4216
4692
|
auth: upstreamAuth,
|
|
4217
4693
|
gate,
|
|
4694
|
+
answerHeartbeat: () => switches.answerHeartbeat(),
|
|
4218
4695
|
...tls === void 0 ? {} : { tls: {
|
|
4219
4696
|
cert: tls.cert,
|
|
4220
4697
|
key: tls.key
|
|
@@ -4249,7 +4726,8 @@ async function startLanGuard(host, rawConfig) {
|
|
|
4249
4726
|
portFallback: () => proxy.portFallback
|
|
4250
4727
|
},
|
|
4251
4728
|
devices,
|
|
4252
|
-
updates
|
|
4729
|
+
updates,
|
|
4730
|
+
relay: { stats: () => proxy.stats() }
|
|
4253
4731
|
});
|
|
4254
4732
|
if (proxy.portFallback) logger.warn("configured port %d was taken; listening on %d instead", proxy.requestedPort, proxy.port);
|
|
4255
4733
|
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 +4853,7 @@ async function apply(ctx, rawConfig) {
|
|
|
4375
4853
|
listener: deps.listener,
|
|
4376
4854
|
devices: deps.devices,
|
|
4377
4855
|
updates: deps.updates,
|
|
4856
|
+
...deps.relay === void 0 ? {} : { relay: deps.relay },
|
|
4378
4857
|
logger: deps.logger
|
|
4379
4858
|
})
|
|
4380
4859
|
}, rawConfig);
|