dsh-lan-guard 0.3.5 → 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/CHANGELOG.md +137 -0
- package/README.md +58 -2
- package/README.zh.md +57 -2
- package/lib/client.js +1038 -13
- package/lib/client.js.map +1 -1
- package/lib/index.d.ts +81 -0
- package/lib/index.js +992 -52
- package/package.json +1 -1
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";
|
|
@@ -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",
|
|
@@ -1906,8 +1930,37 @@ const REPLACED_REQUEST_HEADERS = [
|
|
|
1906
1930
|
"cookie",
|
|
1907
1931
|
VISITOR_HEADER
|
|
1908
1932
|
];
|
|
1909
|
-
/**
|
|
1910
|
-
|
|
1933
|
+
/**
|
|
1934
|
+
* Read one `name=value` pair out of a `Cookie` request header.
|
|
1935
|
+
*
|
|
1936
|
+
* Deliberately not a cookie parser: the value is relayed byte-for-byte, and the
|
|
1937
|
+
* only decision here is which NAME to keep.
|
|
1938
|
+
*
|
|
1939
|
+
* @param header - the visitor's `cookie` header.
|
|
1940
|
+
* @param name - the cookie name to extract.
|
|
1941
|
+
* @returns the exact `name=value` pair, or `undefined`.
|
|
1942
|
+
*/
|
|
1943
|
+
function cookiePairOf(header, name) {
|
|
1944
|
+
if (header === void 0 || header === "") return void 0;
|
|
1945
|
+
for (const part of header.split(";")) {
|
|
1946
|
+
const trimmed = part.trim();
|
|
1947
|
+
const eq = trimmed.indexOf("=");
|
|
1948
|
+
if (eq <= 0) continue;
|
|
1949
|
+
if (trimmed.slice(0, eq).trim() === name) return trimmed;
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
/** The cookie name of one `Set-Cookie` entry. */
|
|
1953
|
+
function setCookieName(entry) {
|
|
1954
|
+
const eq = entry.indexOf("=");
|
|
1955
|
+
if (eq <= 0) return void 0;
|
|
1956
|
+
const name = entry.slice(0, eq).trim();
|
|
1957
|
+
return name === "" ? void 0 : name;
|
|
1958
|
+
}
|
|
1959
|
+
/** Normalize a header value that may be a single string or a list. */
|
|
1960
|
+
function toArray(value) {
|
|
1961
|
+
if (value === void 0) return [];
|
|
1962
|
+
return Array.isArray(value) ? value : [value];
|
|
1963
|
+
}
|
|
1911
1964
|
/**
|
|
1912
1965
|
* The `host:port` authority of an origin URL — the value the upstream fence
|
|
1913
1966
|
* binds cookies to.
|
|
@@ -1950,6 +2003,13 @@ function normalizeRequestTarget(rawTarget) {
|
|
|
1950
2003
|
* @param input.authority - upstream `host:port`.
|
|
1951
2004
|
* @param input.upstreamCookie - the loopback session cookie to inject, if known.
|
|
1952
2005
|
* @param input.upgrade - true for a WebSocket upgrade (keeps `connection`/`upgrade`).
|
|
2006
|
+
* @param input.relayCookieNames - the plugin's OWN cookie names that must reach
|
|
2007
|
+
* the upstream. DSH's session cookie is injected by the proxy, and the
|
|
2008
|
+
* visitor's other cookies (the gate session and device identity) belong to the
|
|
2009
|
+
* proxy origin and must never reach DSH — but this plugin mints an admin
|
|
2010
|
+
* session cookie that DSH's web server has to SEE to honour, and the proxy is
|
|
2011
|
+
* the only path that request takes. Relaying a name allowlist (rather than the
|
|
2012
|
+
* whole header) keeps both properties.
|
|
1953
2013
|
* @returns headers safe to hand to `http.request`.
|
|
1954
2014
|
*/
|
|
1955
2015
|
function buildUpstreamRequestHeaders(input) {
|
|
@@ -1966,21 +2026,36 @@ function buildUpstreamRequestHeaders(input) {
|
|
|
1966
2026
|
outgoing[VISITOR_HEADER] = "1";
|
|
1967
2027
|
outgoing.host = input.authority;
|
|
1968
2028
|
if (input.headers.origin !== void 0) outgoing.origin = `http://${input.authority}`;
|
|
1969
|
-
if (input.upstreamCookie !== void 0 && input.upstreamCookie !== "")
|
|
2029
|
+
if (input.upstreamCookie !== void 0 && input.upstreamCookie !== "") {
|
|
2030
|
+
const relayed = (input.relayCookieNames ?? []).map((name) => cookiePairOf(input.headers.cookie, name)).filter((pair) => pair !== void 0);
|
|
2031
|
+
outgoing.cookie = relayed.length === 0 ? input.upstreamCookie : `${input.upstreamCookie}; ${relayed.join("; ")}`;
|
|
2032
|
+
}
|
|
1970
2033
|
return outgoing;
|
|
1971
2034
|
}
|
|
1972
2035
|
/**
|
|
1973
2036
|
* Filter an upstream response's headers for the browser.
|
|
1974
2037
|
*
|
|
2038
|
+
* `set-cookie` stays dropped EXCEPT for the plugin's own cookie names (see
|
|
2039
|
+
* {@link buildUpstreamRequestHeaders}): DSH's own session cookie must never
|
|
2040
|
+
* reach a visitor, while this plugin's admin session has to be stored by the
|
|
2041
|
+
* visitor's browser or remote management could never unlock.
|
|
2042
|
+
*
|
|
1975
2043
|
* @param headers - upstream response headers.
|
|
2044
|
+
* @param relayCookieNames - the plugin's own cookie names that may round-trip.
|
|
1976
2045
|
* @returns headers safe to write to the visitor's response.
|
|
1977
2046
|
*/
|
|
1978
|
-
function buildUpstreamResponseHeaders(headers) {
|
|
2047
|
+
function buildUpstreamResponseHeaders(headers, relayCookieNames = []) {
|
|
1979
2048
|
const outgoing = {};
|
|
1980
|
-
const dropped =
|
|
2049
|
+
const dropped = new Set(HOP_BY_HOP_HEADERS);
|
|
1981
2050
|
for (const [name, value] of Object.entries(headers)) {
|
|
1982
2051
|
if (value === void 0) continue;
|
|
1983
|
-
|
|
2052
|
+
const lower = name.toLowerCase();
|
|
2053
|
+
if (lower === "set-cookie") {
|
|
2054
|
+
const kept = toArray(value).filter((entry) => relayCookieNames.includes(setCookieName(entry) ?? ""));
|
|
2055
|
+
if (kept.length > 0) outgoing["set-cookie"] = kept;
|
|
2056
|
+
continue;
|
|
2057
|
+
}
|
|
2058
|
+
if (dropped.has(lower)) continue;
|
|
1984
2059
|
outgoing[name] = value;
|
|
1985
2060
|
}
|
|
1986
2061
|
return outgoing;
|
|
@@ -2011,6 +2086,171 @@ function buildUpgradeResponseHead(headers, statusCode, statusMessage) {
|
|
|
2011
2086
|
}
|
|
2012
2087
|
return `${lines.join("\r\n")}\r\n\r\n`;
|
|
2013
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
|
+
}
|
|
2014
2254
|
//#endregion
|
|
2015
2255
|
//#region src/websocket.ts
|
|
2016
2256
|
/**
|
|
@@ -2028,6 +2268,12 @@ function buildUpgradeResponseHead(headers, statusCode, statusMessage) {
|
|
|
2028
2268
|
* take the whole process down. This is also why the gate in P2 can await
|
|
2029
2269
|
* safely.
|
|
2030
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.
|
|
2031
2277
|
*/
|
|
2032
2278
|
/** Attach the mandatory `error` handler to a socket we now own. */
|
|
2033
2279
|
function guardUpgradeSocket(socket, logger = noopLogger) {
|
|
@@ -2046,6 +2292,24 @@ function forwardUpgrade(options) {
|
|
|
2046
2292
|
const { req, socket, head, upstream, headers, target } = options;
|
|
2047
2293
|
const logger = options.logger ?? noopLogger;
|
|
2048
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
|
+
};
|
|
2049
2313
|
const upstreamReq = request({
|
|
2050
2314
|
hostname: upstream.hostname,
|
|
2051
2315
|
port: upstream.port,
|
|
@@ -2061,30 +2325,61 @@ function forwardUpgrade(options) {
|
|
|
2061
2325
|
socket.on("close", () => upstreamDuplex.destroy());
|
|
2062
2326
|
socket.write(buildUpgradeResponseHead(upstreamRes.headers, upstreamRes.statusCode ?? 101, upstreamRes.statusMessage === "" ? "Switching Protocols" : upstreamRes.statusMessage ?? "Switching Protocols"));
|
|
2063
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
|
+
});
|
|
2064
2351
|
upstreamDuplex.pipe(socket);
|
|
2065
2352
|
socket.pipe(upstreamDuplex);
|
|
2066
2353
|
});
|
|
2067
2354
|
upstreamReq.on("response", (upstreamRes) => {
|
|
2068
2355
|
logger.debug?.("upgrade refused by upstream status=%d", upstreamRes.statusCode ?? 0);
|
|
2069
2356
|
upstreamRes.resume();
|
|
2357
|
+
const status = upstreamRes.statusCode ?? 502;
|
|
2070
2358
|
if (!socket.destroyed) {
|
|
2071
|
-
const status = upstreamRes.statusCode ?? 502;
|
|
2072
2359
|
const message = upstreamRes.statusMessage === "" ? "Upstream Refused" : upstreamRes.statusMessage ?? "Upstream Refused";
|
|
2073
|
-
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`);
|
|
2074
2361
|
}
|
|
2362
|
+
report({
|
|
2363
|
+
upgraded: false,
|
|
2364
|
+
status
|
|
2365
|
+
});
|
|
2075
2366
|
socket.destroy();
|
|
2076
2367
|
});
|
|
2077
2368
|
upstreamReq.on("error", (error) => {
|
|
2078
2369
|
logger.warn("upgrade upstream error name=%s", error.name);
|
|
2370
|
+
report({ upgraded: false });
|
|
2079
2371
|
socket.destroy();
|
|
2080
2372
|
});
|
|
2081
2373
|
if (head.length > 0) upstreamReq.write(head);
|
|
2082
2374
|
upstreamReq.end();
|
|
2083
|
-
return {
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2375
|
+
return {
|
|
2376
|
+
destroy() {
|
|
2377
|
+
upstreamReq.destroy();
|
|
2378
|
+
upstreamSocket?.destroy();
|
|
2379
|
+
socket.destroy();
|
|
2380
|
+
},
|
|
2381
|
+
heartbeatAnswered: () => answerer?.stats().answered ?? 0
|
|
2382
|
+
};
|
|
2088
2383
|
}
|
|
2089
2384
|
//#endregion
|
|
2090
2385
|
//#region src/proxy.ts
|
|
@@ -2104,6 +2399,20 @@ function forwardUpgrade(options) {
|
|
|
2104
2399
|
* The gate is NOT part of this module's P1 scope; P2 inserts it in front of
|
|
2105
2400
|
* both the HTTP and the upgrade path.
|
|
2106
2401
|
*/
|
|
2402
|
+
/**
|
|
2403
|
+
* The visitor cookies this proxy relays in BOTH directions.
|
|
2404
|
+
*
|
|
2405
|
+
* The proxy injects DSH's loopback session cookie itself and never forwards the
|
|
2406
|
+
* visitor's other cookies (the gate session and the device identity belong to
|
|
2407
|
+
* the proxy origin). But this plugin mints its OWN admin session cookie, and the
|
|
2408
|
+
* only code that can validate it — the management route — runs on DSH's web
|
|
2409
|
+
* server, behind this proxy. Dropping it made `adminPolicy: password_unlock`
|
|
2410
|
+
* unsatisfiable for every remote device: the unlock POST returned 200 and the
|
|
2411
|
+
* very next request was locked again (reported 2026-09-26: "远程选了密码解锁,
|
|
2412
|
+
* 添加工作区里仍然是空的"). Relaying exactly this name keeps DSH's own cookie
|
|
2413
|
+
* out of the visitor's browser while letting the plugin's credential round-trip.
|
|
2414
|
+
*/
|
|
2415
|
+
const RELAY_COOKIE_NAMES = [ADMIN_COOKIE];
|
|
2107
2416
|
/** Bind one port, resolving on `listening` and rejecting on `error`. */
|
|
2108
2417
|
function listenOnce(server, host, port) {
|
|
2109
2418
|
return new Promise((resolve, reject) => {
|
|
@@ -2192,6 +2501,44 @@ async function startProxy(options) {
|
|
|
2192
2501
|
const upstream = parseUpstream(options.upstreamOrigin);
|
|
2193
2502
|
const authority = authorityOf(options.upstreamOrigin);
|
|
2194
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
|
+
};
|
|
2195
2542
|
const fail = (res, code, body) => {
|
|
2196
2543
|
if (res.headersSent) {
|
|
2197
2544
|
res.destroy();
|
|
@@ -2215,7 +2562,8 @@ async function startProxy(options) {
|
|
|
2215
2562
|
const headers = buildUpstreamRequestHeaders({
|
|
2216
2563
|
headers: req.headers,
|
|
2217
2564
|
authority,
|
|
2218
|
-
upstreamCookie: cookie
|
|
2565
|
+
upstreamCookie: cookie,
|
|
2566
|
+
relayCookieNames: RELAY_COOKIE_NAMES
|
|
2219
2567
|
});
|
|
2220
2568
|
const upstreamReq = request({
|
|
2221
2569
|
hostname: upstream.hostname,
|
|
@@ -2232,7 +2580,7 @@ async function startProxy(options) {
|
|
|
2232
2580
|
forwardHttp(req, res, target, false);
|
|
2233
2581
|
return;
|
|
2234
2582
|
}
|
|
2235
|
-
res.writeHead(status, upstreamRes.statusMessage === "" ? void 0 : upstreamRes.statusMessage, buildUpstreamResponseHeaders(upstreamRes.headers));
|
|
2583
|
+
res.writeHead(status, upstreamRes.statusMessage === "" ? void 0 : upstreamRes.statusMessage, buildUpstreamResponseHeaders(upstreamRes.headers, RELAY_COOKIE_NAMES));
|
|
2236
2584
|
upstreamRes.pipe(res);
|
|
2237
2585
|
});
|
|
2238
2586
|
upstreamReq.on("error", (error) => {
|
|
@@ -2286,10 +2634,12 @@ async function startProxy(options) {
|
|
|
2286
2634
|
});
|
|
2287
2635
|
server.on("upgrade", (req, socket, head) => {
|
|
2288
2636
|
guardUpgradeSocket(socket, logger);
|
|
2637
|
+
const upgradeTarget = normalizeRequestTarget(req.url);
|
|
2289
2638
|
(async () => {
|
|
2290
2639
|
if (options.gate !== void 0) {
|
|
2291
2640
|
const refusal = await options.gate.verifyUpgrade(req);
|
|
2292
2641
|
if (refusal !== void 0) {
|
|
2642
|
+
recordRefusal(upgradeTarget, refusal.status);
|
|
2293
2643
|
if (!socket.destroyed) socket.write(`HTTP/1.1 ${String(refusal.status)} Unauthorized\r\nconnection: close\r\ncontent-length: 0\r\n\r\n`);
|
|
2294
2644
|
socket.destroy();
|
|
2295
2645
|
return;
|
|
@@ -2300,23 +2650,39 @@ async function startProxy(options) {
|
|
|
2300
2650
|
cookie = await options.auth.cookieHeader();
|
|
2301
2651
|
} catch (error) {
|
|
2302
2652
|
logger.warn("upgrade authentication failed name=%s", error.name);
|
|
2653
|
+
recordRefusal(upgradeTarget, 502);
|
|
2303
2654
|
socket.destroy();
|
|
2304
2655
|
return;
|
|
2305
2656
|
}
|
|
2306
|
-
|
|
2657
|
+
let tunnel;
|
|
2658
|
+
tunnel = forwardUpgrade({
|
|
2307
2659
|
req,
|
|
2308
2660
|
socket,
|
|
2309
2661
|
head,
|
|
2310
2662
|
upstream,
|
|
2311
|
-
target:
|
|
2663
|
+
target: upgradeTarget,
|
|
2312
2664
|
headers: buildUpstreamRequestHeaders({
|
|
2313
2665
|
headers: req.headers,
|
|
2314
2666
|
authority,
|
|
2315
2667
|
upstreamCookie: cookie,
|
|
2316
|
-
upgrade: true
|
|
2668
|
+
upgrade: true,
|
|
2669
|
+
relayCookieNames: RELAY_COOKIE_NAMES
|
|
2317
2670
|
}),
|
|
2318
|
-
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
|
+
}
|
|
2319
2684
|
});
|
|
2685
|
+
if (tunnel !== void 0) liveTunnels.add(tunnel);
|
|
2320
2686
|
})();
|
|
2321
2687
|
});
|
|
2322
2688
|
const attempts = options.portProbeAttempts ?? 0;
|
|
@@ -2338,6 +2704,17 @@ async function startProxy(options) {
|
|
|
2338
2704
|
port,
|
|
2339
2705
|
requestedPort,
|
|
2340
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
|
+
},
|
|
2341
2718
|
close() {
|
|
2342
2719
|
return new Promise((resolve, reject) => {
|
|
2343
2720
|
server.close((error) => {
|
|
@@ -2420,17 +2797,359 @@ async function buildAccessInfo(options) {
|
|
|
2420
2797
|
}
|
|
2421
2798
|
return info;
|
|
2422
2799
|
}
|
|
2800
|
+
/**
|
|
2801
|
+
* Names that are never listed, never entered, and never accepted as a target.
|
|
2802
|
+
*
|
|
2803
|
+
* The list is the union of the reference implementation's and the obvious
|
|
2804
|
+
* credential stores; matching is case-insensitive so a macOS case-insensitive
|
|
2805
|
+
* volume cannot smuggle `.SSH` past it.
|
|
2806
|
+
*/
|
|
2807
|
+
const SENSITIVE_NAMES = /* @__PURE__ */ new Set([
|
|
2808
|
+
".ssh",
|
|
2809
|
+
".gnupg",
|
|
2810
|
+
".aws",
|
|
2811
|
+
".azure",
|
|
2812
|
+
".kube",
|
|
2813
|
+
".git",
|
|
2814
|
+
".svn",
|
|
2815
|
+
".hg",
|
|
2816
|
+
".env",
|
|
2817
|
+
".npmrc",
|
|
2818
|
+
".netrc",
|
|
2819
|
+
".bash_history",
|
|
2820
|
+
".zsh_history",
|
|
2821
|
+
".profile",
|
|
2822
|
+
".bash_profile",
|
|
2823
|
+
".bashrc",
|
|
2824
|
+
".zshrc",
|
|
2825
|
+
"id_rsa",
|
|
2826
|
+
"id_ed25519",
|
|
2827
|
+
"id_ecdsa",
|
|
2828
|
+
"id_dsa",
|
|
2829
|
+
"credentials",
|
|
2830
|
+
"shadow",
|
|
2831
|
+
"passwd",
|
|
2832
|
+
"system volume information",
|
|
2833
|
+
"$recycle.bin"
|
|
2834
|
+
]);
|
|
2835
|
+
/** POSIX system prefixes, refused on the requested path AND on its realpath. */
|
|
2836
|
+
const POSIX_BLOCKED_PREFIXES = [
|
|
2837
|
+
"/etc",
|
|
2838
|
+
"/root",
|
|
2839
|
+
"/sys",
|
|
2840
|
+
"/proc",
|
|
2841
|
+
"/dev",
|
|
2842
|
+
"/boot",
|
|
2843
|
+
"/bin",
|
|
2844
|
+
"/sbin",
|
|
2845
|
+
"/lib",
|
|
2846
|
+
"/lib64",
|
|
2847
|
+
"/usr/bin",
|
|
2848
|
+
"/usr/sbin",
|
|
2849
|
+
"/private/etc",
|
|
2850
|
+
"/private/var/db",
|
|
2851
|
+
"/private/var/root",
|
|
2852
|
+
"/var/run",
|
|
2853
|
+
"/var/root",
|
|
2854
|
+
"/Library/Keychains",
|
|
2855
|
+
"/System/Library"
|
|
2856
|
+
];
|
|
2857
|
+
/**
|
|
2858
|
+
* Windows system prefixes, compared against the part AFTER the drive letter
|
|
2859
|
+
* (or against a UNC path, which is refused outright).
|
|
2860
|
+
*/
|
|
2861
|
+
const WINDOWS_BLOCKED_PREFIXES = [
|
|
2862
|
+
"windows",
|
|
2863
|
+
"winnt",
|
|
2864
|
+
"program files",
|
|
2865
|
+
"program files (x86)",
|
|
2866
|
+
"system volume information",
|
|
2867
|
+
"$recycle.bin",
|
|
2868
|
+
"recovery",
|
|
2869
|
+
"perflogs",
|
|
2870
|
+
"boot",
|
|
2871
|
+
"programdata\\microsoft"
|
|
2872
|
+
];
|
|
2873
|
+
/** Whether this process is Windows. */
|
|
2874
|
+
const IS_WINDOWS = process.platform === "win32";
|
|
2875
|
+
/** Whether one path segment is a sensitive name. */
|
|
2876
|
+
function isSensitiveName(name) {
|
|
2877
|
+
return SENSITIVE_NAMES.has(name.trim().toLowerCase());
|
|
2878
|
+
}
|
|
2879
|
+
/**
|
|
2880
|
+
* Whether a path is FULLY QUALIFIED.
|
|
2881
|
+
*
|
|
2882
|
+
* `isAbsolute` alone is not enough on Windows: `\foo` and `/foo` are "rooted"
|
|
2883
|
+
* without naming a drive, so they resolve against the process's current drive
|
|
2884
|
+
* and are not the fixed location the caller meant. Both forms are refused, as
|
|
2885
|
+
* are UNC paths (a network share is not this machine's directory tree).
|
|
2886
|
+
*
|
|
2887
|
+
* @param candidate - the trimmed caller-supplied path.
|
|
2888
|
+
* @returns whether the path names one fixed location.
|
|
2889
|
+
*/
|
|
2890
|
+
function isFullyQualified(candidate) {
|
|
2891
|
+
if (!IS_WINDOWS) return isAbsolute(candidate);
|
|
2892
|
+
if (/^[A-Za-z]:[\\/]/.test(candidate)) return true;
|
|
2893
|
+
return /^\\\\[^\\/]+[\\/][^\\/]+/.test(candidate);
|
|
2894
|
+
}
|
|
2895
|
+
/** The comparison key for one absolute path (case-insensitive on Windows). */
|
|
2896
|
+
function key(path) {
|
|
2897
|
+
return IS_WINDOWS ? path.toLowerCase() : path;
|
|
2898
|
+
}
|
|
2899
|
+
/**
|
|
2900
|
+
* Whether an absolute path sits in (or IS) a blocked system location.
|
|
2901
|
+
*
|
|
2902
|
+
* @param absolutePath - a resolved absolute path.
|
|
2903
|
+
* @returns the offending prefix, or `undefined` when the path is allowed.
|
|
2904
|
+
*/
|
|
2905
|
+
function blockedPrefixOf(absolutePath) {
|
|
2906
|
+
const normalized = key(absolutePath);
|
|
2907
|
+
if (IS_WINDOWS) {
|
|
2908
|
+
if (normalized.startsWith("\\\\")) return "\\\\ (UNC)";
|
|
2909
|
+
const rest = /^[a-z]:\\(.*)$/.exec(normalized)?.[1];
|
|
2910
|
+
if (rest === void 0) return void 0;
|
|
2911
|
+
for (const prefix of WINDOWS_BLOCKED_PREFIXES) if (rest === prefix || rest.startsWith(`${prefix}\\`)) return prefix;
|
|
2912
|
+
return;
|
|
2913
|
+
}
|
|
2914
|
+
for (const prefix of POSIX_BLOCKED_PREFIXES) if (normalized === prefix || normalized.startsWith(`${prefix}${sep}`)) return prefix;
|
|
2915
|
+
}
|
|
2916
|
+
/**
|
|
2917
|
+
* Resolve one caller-supplied path to the canonical directory it names.
|
|
2918
|
+
*
|
|
2919
|
+
* The order matters: the cheap shape checks run first, then every segment is
|
|
2920
|
+
* screened, and only then is the path resolved through the filesystem — so a
|
|
2921
|
+
* symlink is followed to its real target and the WHOLE fence is applied again
|
|
2922
|
+
* to that target. A symlink therefore cannot be used to reach a blocked
|
|
2923
|
+
* directory, and a symlink cannot be used to reach a sensitive one either.
|
|
2924
|
+
*
|
|
2925
|
+
* @param raw - the caller-supplied path (`?path=` or a body field).
|
|
2926
|
+
* @returns the canonical directory path, or a stable failure.
|
|
2927
|
+
*/
|
|
2928
|
+
async function resolveBrowsablePath(raw) {
|
|
2929
|
+
if (typeof raw !== "string" || raw.trim() === "") return {
|
|
2930
|
+
ok: false,
|
|
2931
|
+
error: "invalid_path",
|
|
2932
|
+
message: "路径不能为空"
|
|
2933
|
+
};
|
|
2934
|
+
const candidate = raw.trim();
|
|
2935
|
+
if (candidate.includes("\0")) return {
|
|
2936
|
+
ok: false,
|
|
2937
|
+
error: "invalid_path",
|
|
2938
|
+
message: "路径包含非法字符"
|
|
2939
|
+
};
|
|
2940
|
+
if (!isFullyQualified(candidate)) return {
|
|
2941
|
+
ok: false,
|
|
2942
|
+
error: "not_absolute",
|
|
2943
|
+
message: "必须使用完整的绝对路径"
|
|
2944
|
+
};
|
|
2945
|
+
const resolved = resolve(candidate);
|
|
2946
|
+
const segments = resolved.split(/[\\/]/).filter((part) => part !== "");
|
|
2947
|
+
for (const segment of segments) if (isSensitiveName(segment)) return {
|
|
2948
|
+
ok: false,
|
|
2949
|
+
error: "blocked",
|
|
2950
|
+
message: `禁止访问敏感目录「${segment}」`
|
|
2951
|
+
};
|
|
2952
|
+
const directBlock = blockedPrefixOf(resolved);
|
|
2953
|
+
if (directBlock !== void 0) return {
|
|
2954
|
+
ok: false,
|
|
2955
|
+
error: "blocked",
|
|
2956
|
+
message: `禁止访问系统目录「${directBlock}」`
|
|
2957
|
+
};
|
|
2958
|
+
let canonical;
|
|
2959
|
+
try {
|
|
2960
|
+
canonical = await realpath(resolved);
|
|
2961
|
+
} catch (error) {
|
|
2962
|
+
const code = error.code;
|
|
2963
|
+
if (code === "ENOENT" || code === "ENOTDIR") return {
|
|
2964
|
+
ok: false,
|
|
2965
|
+
error: "not_found",
|
|
2966
|
+
message: "目录不存在"
|
|
2967
|
+
};
|
|
2968
|
+
return {
|
|
2969
|
+
ok: false,
|
|
2970
|
+
error: "unreadable",
|
|
2971
|
+
message: `无法访问该目录(${code ?? "unknown"})`
|
|
2972
|
+
};
|
|
2973
|
+
}
|
|
2974
|
+
for (const segment of canonical.split(/[\\/]/).filter((part) => part !== "")) if (isSensitiveName(segment)) return {
|
|
2975
|
+
ok: false,
|
|
2976
|
+
error: "blocked",
|
|
2977
|
+
message: `符号链接指向敏感目录「${segment}」`
|
|
2978
|
+
};
|
|
2979
|
+
const realBlock = blockedPrefixOf(canonical);
|
|
2980
|
+
if (realBlock !== void 0) return {
|
|
2981
|
+
ok: false,
|
|
2982
|
+
error: "blocked",
|
|
2983
|
+
message: `符号链接指向系统目录「${realBlock}」`
|
|
2984
|
+
};
|
|
2985
|
+
try {
|
|
2986
|
+
if (!(await stat(canonical)).isDirectory()) return {
|
|
2987
|
+
ok: false,
|
|
2988
|
+
error: "not_a_directory",
|
|
2989
|
+
message: "该路径不是文件夹"
|
|
2990
|
+
};
|
|
2991
|
+
} catch (error) {
|
|
2992
|
+
return {
|
|
2993
|
+
ok: false,
|
|
2994
|
+
error: "unreadable",
|
|
2995
|
+
message: `无法访问该目录(${error.code ?? "unknown"})`
|
|
2996
|
+
};
|
|
2997
|
+
}
|
|
2998
|
+
return {
|
|
2999
|
+
ok: true,
|
|
3000
|
+
path: canonical
|
|
3001
|
+
};
|
|
3002
|
+
}
|
|
3003
|
+
/** The filesystem root for this platform (`/`, or the current drive's root). */
|
|
3004
|
+
function rootOf(path) {
|
|
3005
|
+
return parse(path).root === "" ? sep : parse(path).root;
|
|
3006
|
+
}
|
|
3007
|
+
/**
|
|
3008
|
+
* Build the root → current breadcrumb chain.
|
|
3009
|
+
*
|
|
3010
|
+
* Each crumb is a jump target, and the root keeps its full path as its name
|
|
3011
|
+
* (`/` on POSIX, `C:\` on Windows) because that is what it actually is.
|
|
3012
|
+
*
|
|
3013
|
+
* @param current - the canonical directory being listed.
|
|
3014
|
+
* @returns the chain, root first.
|
|
3015
|
+
*/
|
|
3016
|
+
function crumbsOf(current) {
|
|
3017
|
+
const crumbs = [];
|
|
3018
|
+
let cursor = current;
|
|
3019
|
+
for (;;) {
|
|
3020
|
+
const root = rootOf(cursor);
|
|
3021
|
+
const name = basename(cursor);
|
|
3022
|
+
crumbs.push({
|
|
3023
|
+
name: name === "" ? cursor : name,
|
|
3024
|
+
path: cursor
|
|
3025
|
+
});
|
|
3026
|
+
if (key(cursor) === key(root)) break;
|
|
3027
|
+
const parent = resolve(cursor, "..");
|
|
3028
|
+
if (key(parent) === key(cursor)) break;
|
|
3029
|
+
cursor = parent;
|
|
3030
|
+
}
|
|
3031
|
+
return crumbs.reverse();
|
|
3032
|
+
}
|
|
3033
|
+
/** Shortcut rows that exist on this machine. */
|
|
3034
|
+
async function quickAccess() {
|
|
3035
|
+
const home = homedir();
|
|
3036
|
+
const rows = [{
|
|
3037
|
+
name: "🏠 用户主目录",
|
|
3038
|
+
path: home,
|
|
3039
|
+
hidden: false
|
|
3040
|
+
}];
|
|
3041
|
+
for (const item of [
|
|
3042
|
+
{
|
|
3043
|
+
name: "💻 桌面",
|
|
3044
|
+
segment: "Desktop"
|
|
3045
|
+
},
|
|
3046
|
+
{
|
|
3047
|
+
name: "📁 文档",
|
|
3048
|
+
segment: "Documents"
|
|
3049
|
+
},
|
|
3050
|
+
{
|
|
3051
|
+
name: "📥 下载",
|
|
3052
|
+
segment: "Downloads"
|
|
3053
|
+
},
|
|
3054
|
+
{
|
|
3055
|
+
name: "📦 Projects",
|
|
3056
|
+
segment: "Projects"
|
|
3057
|
+
},
|
|
3058
|
+
{
|
|
3059
|
+
name: "💻 code",
|
|
3060
|
+
segment: "code"
|
|
3061
|
+
},
|
|
3062
|
+
{
|
|
3063
|
+
name: "💻 src",
|
|
3064
|
+
segment: "src"
|
|
3065
|
+
}
|
|
3066
|
+
]) {
|
|
3067
|
+
const candidate = join(home, item.segment);
|
|
3068
|
+
try {
|
|
3069
|
+
if ((await stat(candidate)).isDirectory()) rows.push({
|
|
3070
|
+
name: item.name,
|
|
3071
|
+
path: candidate,
|
|
3072
|
+
hidden: false
|
|
3073
|
+
});
|
|
3074
|
+
} catch {}
|
|
3075
|
+
}
|
|
3076
|
+
rows.push({
|
|
3077
|
+
name: IS_WINDOWS ? `${parse(home).root} 盘根目录` : "根目录 /",
|
|
3078
|
+
path: rootOf(home),
|
|
3079
|
+
hidden: false
|
|
3080
|
+
});
|
|
3081
|
+
return rows;
|
|
3082
|
+
}
|
|
3083
|
+
/**
|
|
3084
|
+
* List one directory level.
|
|
3085
|
+
*
|
|
3086
|
+
* Only DIRECTORIES are returned: a workspace is a folder, so files would be
|
|
3087
|
+
* noise on a phone. Symlinked directories are followed (that is how macOS
|
|
3088
|
+
* exposes `/tmp` and friends), but each target goes through the same fence as
|
|
3089
|
+
* an explicitly requested path — a link to a blocked or sensitive location is
|
|
3090
|
+
* silently skipped rather than listed as a dead row.
|
|
3091
|
+
*
|
|
3092
|
+
* @param raw - the requested absolute path; absent or blank lists the home directory.
|
|
3093
|
+
* @returns the listing, or a stable failure.
|
|
3094
|
+
*/
|
|
3095
|
+
async function listDirectories(raw) {
|
|
3096
|
+
const resolved = await resolveBrowsablePath(typeof raw === "string" && raw.trim() !== "" ? raw : homedir());
|
|
3097
|
+
if (!resolved.ok) return resolved;
|
|
3098
|
+
const current = resolved.path;
|
|
3099
|
+
const entries = [];
|
|
3100
|
+
let truncated = false;
|
|
3101
|
+
try {
|
|
3102
|
+
const dirents = await readdir(current, { withFileTypes: true });
|
|
3103
|
+
dirents.sort((a, b) => a.name.localeCompare(b.name));
|
|
3104
|
+
for (const dirent of dirents) {
|
|
3105
|
+
if (isSensitiveName(dirent.name)) continue;
|
|
3106
|
+
const childPath = join(current, dirent.name);
|
|
3107
|
+
let isDirectory = dirent.isDirectory();
|
|
3108
|
+
if (dirent.isSymbolicLink()) {
|
|
3109
|
+
if (!(await resolveBrowsablePath(childPath)).ok) continue;
|
|
3110
|
+
isDirectory = true;
|
|
3111
|
+
}
|
|
3112
|
+
if (!isDirectory) continue;
|
|
3113
|
+
if (entries.length >= 1e3) {
|
|
3114
|
+
truncated = true;
|
|
3115
|
+
break;
|
|
3116
|
+
}
|
|
3117
|
+
entries.push({
|
|
3118
|
+
name: dirent.name,
|
|
3119
|
+
path: childPath,
|
|
3120
|
+
hidden: dirent.name.startsWith(".")
|
|
3121
|
+
});
|
|
3122
|
+
}
|
|
3123
|
+
} catch (error) {
|
|
3124
|
+
return {
|
|
3125
|
+
ok: false,
|
|
3126
|
+
error: "unreadable",
|
|
3127
|
+
message: `无法读取该目录(${error.code ?? "unknown"})`
|
|
3128
|
+
};
|
|
3129
|
+
}
|
|
3130
|
+
return {
|
|
3131
|
+
ok: true,
|
|
3132
|
+
path: current,
|
|
3133
|
+
crumbs: crumbsOf(current),
|
|
3134
|
+
quick: await quickAccess(),
|
|
3135
|
+
entries,
|
|
3136
|
+
truncated
|
|
3137
|
+
};
|
|
3138
|
+
}
|
|
2423
3139
|
//#endregion
|
|
2424
3140
|
//#region src/settings/index-tap.ts
|
|
2425
3141
|
/** The page global DSH's connection client reads its transport facts from. */
|
|
2426
3142
|
const TRANSPORT_GLOBAL = "__DSH_TRANSPORT__";
|
|
2427
|
-
/**
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
* A tap runs once per index response, so this is a cheap idempotency guard for
|
|
2431
|
-
* a second registration or a re-render of an already-transformed body.
|
|
2432
|
-
*/
|
|
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. */
|
|
2433
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*/";
|
|
2434
3153
|
/**
|
|
2435
3154
|
* The exact head markup that makes the page look like the host's own surface.
|
|
2436
3155
|
*
|
|
@@ -2441,22 +3160,132 @@ const UNLOCK_MARKER = "/*dsh-lan-guard:settings-unlock*/";
|
|
|
2441
3160
|
* @returns one inline `<script>` element.
|
|
2442
3161
|
*/
|
|
2443
3162
|
function settingsUnlockScript() {
|
|
2444
|
-
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>`;
|
|
2445
3164
|
}
|
|
3165
|
+
/** Marker proving the mobile scroll fix was injected. */
|
|
3166
|
+
const MOBILE_SCROLL_MARKER = "/*dsh-lan-guard:mobile-scroll*/";
|
|
2446
3167
|
/**
|
|
2447
|
-
*
|
|
3168
|
+
* The narrow-screen scroll correction (2026-09-28 user report: "聊天区无法上下滑动").
|
|
3169
|
+
*
|
|
3170
|
+
* Measured facts behind it:
|
|
2448
3171
|
*
|
|
2449
|
-
*
|
|
2450
|
-
*
|
|
2451
|
-
*
|
|
2452
|
-
*
|
|
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.
|
|
3234
|
+
*
|
|
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.
|
|
2453
3245
|
*
|
|
2454
3246
|
* @param html - the index body as DSH rendered it.
|
|
2455
3247
|
* @returns the body with the script inserted.
|
|
2456
3248
|
*/
|
|
2457
3249
|
function injectSettingsUnlock(html) {
|
|
2458
3250
|
if (html.includes("/*dsh-lan-guard:settings-unlock*/")) return html;
|
|
2459
|
-
|
|
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) {
|
|
2460
3289
|
const open = /<head(?:\s[^>]*)?>/i.exec(html);
|
|
2461
3290
|
if (open === null) return `${markup}${html}`;
|
|
2462
3291
|
const at = open.index + open[0].length;
|
|
@@ -2465,22 +3294,24 @@ function injectSettingsUnlock(html) {
|
|
|
2465
3294
|
/**
|
|
2466
3295
|
* Install the index tap, when the host exposes one.
|
|
2467
3296
|
*
|
|
2468
|
-
*
|
|
2469
|
-
* switch needs only a page refresh — never a restart.
|
|
2470
|
-
*
|
|
2471
|
-
* @param options.webServer - DSH's web server service (or a stub).
|
|
2472
|
-
* @param options.enabled - the live `settingsUnlock` switch.
|
|
2473
|
-
* @param options.logger - logger; a missing seam is a warning, not a failure.
|
|
3297
|
+
* @param options - see {@link RegisterIndexPatchesOptions}.
|
|
2474
3298
|
* @returns the disposer removing the tap, or `undefined` when unsupported.
|
|
2475
3299
|
*/
|
|
2476
|
-
function
|
|
3300
|
+
function registerIndexPatches(options) {
|
|
2477
3301
|
const logger = options.logger ?? noopLogger;
|
|
2478
3302
|
const tapIndex = options.webServer?.tapIndex;
|
|
2479
3303
|
if (typeof tapIndex !== "function") {
|
|
2480
|
-
logger.warn("webServer.tapIndex is unavailable; the
|
|
3304
|
+
logger.warn("webServer.tapIndex is unavailable; the index patches were not installed");
|
|
2481
3305
|
return;
|
|
2482
3306
|
}
|
|
2483
|
-
return tapIndex.call(options.webServer, (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
|
+
});
|
|
2484
3315
|
}
|
|
2485
3316
|
//#endregion
|
|
2486
3317
|
//#region src/store/preferences.ts
|
|
@@ -2549,6 +3380,16 @@ function sanitizePreferencePatch(patch) {
|
|
|
2549
3380
|
if (typeof source.settingsUnlock !== "boolean") throw new PreferenceError("settingsUnlock must be a boolean");
|
|
2550
3381
|
result.settingsUnlock = source.settingsUnlock;
|
|
2551
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
|
+
}
|
|
2552
3393
|
if (Object.hasOwn(source, "requireApproval")) {
|
|
2553
3394
|
if (typeof source.requireApproval !== "boolean") throw new PreferenceError("requireApproval must be a boolean");
|
|
2554
3395
|
result.requireApproval = source.requireApproval;
|
|
@@ -2590,6 +3431,10 @@ function toSettingsPatch(values) {
|
|
|
2590
3431
|
if (values.listenHost !== void 0) patch.listenHost = values.listenHost;
|
|
2591
3432
|
if (values.networkInterface !== void 0) patch.networkInterface = values.networkInterface;
|
|
2592
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;
|
|
2593
3438
|
if (values.requirePairing !== void 0) auth.requirePairing = values.requirePairing;
|
|
2594
3439
|
if (values.requireApproval !== void 0) auth.requireApproval = values.requireApproval;
|
|
2595
3440
|
if (values.mode !== void 0) auth.mode = values.mode;
|
|
@@ -2723,6 +3568,10 @@ function registerManagementRoutes(options) {
|
|
|
2723
3568
|
listenHost: options.switches.listenHost(),
|
|
2724
3569
|
networkInterface: options.switches.networkInterface() ?? "",
|
|
2725
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(),
|
|
2726
3575
|
mode: options.switches.mode(),
|
|
2727
3576
|
adminPolicy: options.switches.adminPolicy(),
|
|
2728
3577
|
adminProtection: options.switches.adminProtection(),
|
|
@@ -2743,6 +3592,8 @@ function registerManagementRoutes(options) {
|
|
|
2743
3592
|
pendingCount: options.devices.list().filter((device) => device.status === "pending").length
|
|
2744
3593
|
};
|
|
2745
3594
|
if (token !== void 0) snapshot.secretToken = token;
|
|
3595
|
+
const relay = options.relay;
|
|
3596
|
+
if (relay !== void 0) snapshot.connection = relay.stats();
|
|
2746
3597
|
return snapshot;
|
|
2747
3598
|
};
|
|
2748
3599
|
/** Run the native fence; returns true when the request was refused. */
|
|
@@ -3029,6 +3880,86 @@ function registerManagementRoutes(options) {
|
|
|
3029
3880
|
handler: handleDevices
|
|
3030
3881
|
}));
|
|
3031
3882
|
/**
|
|
3883
|
+
* Remote workspace picker: ONE directory level per request.
|
|
3884
|
+
*
|
|
3885
|
+
* DSH resolves its directory-picker seam once at boot, and on a loopback-only
|
|
3886
|
+
* bind with a display that resolution is `native` — the OS folder dialog
|
|
3887
|
+
* opens on THIS machine's screen. A browser arriving through the LAN gateway
|
|
3888
|
+
* therefore cannot use "添加工作区" at all. The browser half of this plugin
|
|
3889
|
+
* shadows the official flow occupant and drives this route instead; the
|
|
3890
|
+
* picked path still goes back through DSH's own workspace flow, so nothing is
|
|
3891
|
+
* registered here.
|
|
3892
|
+
*
|
|
3893
|
+
* AUTHORITY: reading the host's directory tree is a privileged operation, so
|
|
3894
|
+
* it needs the SAME authority as every other management call — the machine's
|
|
3895
|
+
* own operator, or a remote session that unlocked the console. Under the
|
|
3896
|
+
* default `local_only` policy a remote device gets `read_only_remote`, which
|
|
3897
|
+
* the page explains instead of failing silently.
|
|
3898
|
+
*
|
|
3899
|
+
* RATE LIMIT: a runaway UI loop must not turn into unbounded filesystem
|
|
3900
|
+
* walks. The bucket is keyed by the socket address plus the visitor marker,
|
|
3901
|
+
* and because the proxy connects from loopback and does not forward the
|
|
3902
|
+
* client address, every proxied visitor shares ONE bucket — this is a runaway
|
|
3903
|
+
* guard, not a per-device quota.
|
|
3904
|
+
*/
|
|
3905
|
+
const BROWSE_RATE_LIMIT = 240;
|
|
3906
|
+
const BROWSE_RATE_WINDOW_MS = 6e4;
|
|
3907
|
+
const browseBudget = /* @__PURE__ */ new Map();
|
|
3908
|
+
/** Consume one unit from the caller's budget; false when it is exhausted. */
|
|
3909
|
+
const overBrowseBudget = (req) => {
|
|
3910
|
+
const key = `${req.socket.remoteAddress ?? "unknown"}:${req.headers["x-dsh-lan-guard-visitor"] === void 0 ? "local" : "visitor"}`;
|
|
3911
|
+
const now = Date.now();
|
|
3912
|
+
if (browseBudget.size > 64) {
|
|
3913
|
+
for (const [existing, entry] of browseBudget) if (entry.resetAtMs <= now) browseBudget.delete(existing);
|
|
3914
|
+
}
|
|
3915
|
+
const bucket = browseBudget.get(key);
|
|
3916
|
+
if (bucket === void 0 || bucket.resetAtMs <= now) {
|
|
3917
|
+
browseBudget.set(key, {
|
|
3918
|
+
used: 1,
|
|
3919
|
+
resetAtMs: now + BROWSE_RATE_WINDOW_MS
|
|
3920
|
+
});
|
|
3921
|
+
return false;
|
|
3922
|
+
}
|
|
3923
|
+
bucket.used += 1;
|
|
3924
|
+
return bucket.used > BROWSE_RATE_LIMIT;
|
|
3925
|
+
};
|
|
3926
|
+
const handleWorkspaces = async (req, res) => {
|
|
3927
|
+
if (refusedByFence(req, res)) return;
|
|
3928
|
+
if (isRemoteReadOnly(req)) {
|
|
3929
|
+
sendJson(res, 403, {
|
|
3930
|
+
ok: false,
|
|
3931
|
+
error: "read_only_remote"
|
|
3932
|
+
});
|
|
3933
|
+
return;
|
|
3934
|
+
}
|
|
3935
|
+
if (needsAdmin(req)) {
|
|
3936
|
+
sendJson(res, 403, {
|
|
3937
|
+
ok: false,
|
|
3938
|
+
error: "admin_required"
|
|
3939
|
+
});
|
|
3940
|
+
return;
|
|
3941
|
+
}
|
|
3942
|
+
if (overBrowseBudget(req)) {
|
|
3943
|
+
sendJson(res, 429, {
|
|
3944
|
+
ok: false,
|
|
3945
|
+
error: "rate_limited"
|
|
3946
|
+
});
|
|
3947
|
+
return;
|
|
3948
|
+
}
|
|
3949
|
+
const result = await listDirectories(new URL(req.url ?? "/", "http://dsh-lan-guard.invalid").searchParams.get("path"));
|
|
3950
|
+
if (result.ok) {
|
|
3951
|
+
sendJson(res, 200, result);
|
|
3952
|
+
return;
|
|
3953
|
+
}
|
|
3954
|
+
const status = result.error === "blocked" ? 403 : result.error === "not_found" ? 404 : result.error === "unreadable" ? 500 : 400;
|
|
3955
|
+
sendJson(res, status, result);
|
|
3956
|
+
};
|
|
3957
|
+
disposers.push(options.webServer.register({
|
|
3958
|
+
kind: "exact",
|
|
3959
|
+
path: `${MANAGEMENT_BASE}/workspaces`,
|
|
3960
|
+
handler: handleWorkspaces
|
|
3961
|
+
}));
|
|
3962
|
+
/**
|
|
3032
3963
|
* Update detection (SPEC F8). Read-only: it reports what npm has and the
|
|
3033
3964
|
* settings page offers a copyable command — the host never installs anything.
|
|
3034
3965
|
*/
|
|
@@ -3067,21 +3998,27 @@ function registerManagementRoutes(options) {
|
|
|
3067
3998
|
}
|
|
3068
3999
|
}));
|
|
3069
4000
|
/**
|
|
3070
|
-
*
|
|
4001
|
+
* Index patches: the remote settings-page unlock, the mobile compatibility
|
|
4002
|
+
* shims and the client-side socket watchdog.
|
|
3071
4003
|
*
|
|
3072
4004
|
* DSH disables its OFFICIAL settings surface for any page whose address bar
|
|
3073
4005
|
* is not loopback, which is every device arriving through this gateway; the
|
|
3074
4006
|
* proxy cannot change that because the decision is made in the visitor's
|
|
3075
|
-
* browser. The
|
|
3076
|
-
* served document, and
|
|
3077
|
-
* 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.
|
|
3078
4010
|
*/
|
|
3079
|
-
const
|
|
4011
|
+
const disposePatches = registerIndexPatches({
|
|
3080
4012
|
webServer: options.webServer,
|
|
3081
|
-
|
|
4013
|
+
switches: {
|
|
4014
|
+
settingsUnlock: () => options.switches.settingsUnlock(),
|
|
4015
|
+
mobileCompat: () => options.switches.mobileCompat(),
|
|
4016
|
+
mobileScrollFix: () => options.switches.mobileScrollFix(),
|
|
4017
|
+
socketWatchdog: () => options.switches.socketWatchdog()
|
|
4018
|
+
},
|
|
3082
4019
|
logger
|
|
3083
4020
|
});
|
|
3084
|
-
if (
|
|
4021
|
+
if (disposePatches !== void 0) disposers.push(disposePatches);
|
|
3085
4022
|
return () => {
|
|
3086
4023
|
for (const dispose of disposers.reverse()) dispose();
|
|
3087
4024
|
};
|
|
@@ -3729,6 +4666,7 @@ async function startLanGuard(host, rawConfig) {
|
|
|
3729
4666
|
upstreamOrigin: config.upstreamOrigin,
|
|
3730
4667
|
auth: upstreamAuth,
|
|
3731
4668
|
gate,
|
|
4669
|
+
answerHeartbeat: () => switches.answerHeartbeat(),
|
|
3732
4670
|
...tls === void 0 ? {} : { tls: {
|
|
3733
4671
|
cert: tls.cert,
|
|
3734
4672
|
key: tls.key
|
|
@@ -3763,7 +4701,8 @@ async function startLanGuard(host, rawConfig) {
|
|
|
3763
4701
|
portFallback: () => proxy.portFallback
|
|
3764
4702
|
},
|
|
3765
4703
|
devices,
|
|
3766
|
-
updates
|
|
4704
|
+
updates,
|
|
4705
|
+
relay: { stats: () => proxy.stats() }
|
|
3767
4706
|
});
|
|
3768
4707
|
if (proxy.portFallback) logger.warn("configured port %d was taken; listening on %d instead", proxy.requestedPort, proxy.port);
|
|
3769
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());
|
|
@@ -3889,6 +4828,7 @@ async function apply(ctx, rawConfig) {
|
|
|
3889
4828
|
listener: deps.listener,
|
|
3890
4829
|
devices: deps.devices,
|
|
3891
4830
|
updates: deps.updates,
|
|
4831
|
+
...deps.relay === void 0 ? {} : { relay: deps.relay },
|
|
3892
4832
|
logger: deps.logger
|
|
3893
4833
|
})
|
|
3894
4834
|
}, rawConfig);
|