dsh-hiss-plugins 1.3.0 → 1.4.0
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/README.md +40 -11
- package/cordis.patch.yml +7 -0
- package/lib/client.js +260 -6
- package/lib/colgrep/index.js +55 -4
- package/lib/lan-access/gateway.js +348 -0
- package/lib/lan-access/index.js +298 -0
- package/lib/lan-access/qr.js +442 -0
- package/locale/en.json +15 -3
- package/locale/zh.json +15 -3
- package/package.json +6 -3
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The LAN gateway: one listener on this machine's network address that forwards
|
|
3
|
+
* the browser surface to the loopback Host.
|
|
4
|
+
*
|
|
5
|
+
* The Host's browser-trust fence accepts loopback, its own bind address, or a
|
|
6
|
+
* configured authority, and its signed cookie is bound to the authority the
|
|
7
|
+
* request names. Rewriting Host to the bare loopback authority therefore does
|
|
8
|
+
* two things at once: the fence admits the request, and every device's cookie
|
|
9
|
+
* stays valid across restarts even though the Host's port is assigned afresh
|
|
10
|
+
* each launch.
|
|
11
|
+
*
|
|
12
|
+
* Pairing: the QR page never carries the Host's launch token. A phone opens
|
|
13
|
+
* `/?pair=<secret>` once; the gateway performs the token exchange itself,
|
|
14
|
+
* keeps the resulting Host cookie for that client address, and stamps it on
|
|
15
|
+
* every later request from that address. The phone therefore needs neither the
|
|
16
|
+
* Host token nor working cookies, and a stale QR page fails loudly instead of
|
|
17
|
+
* silently signing in the wrong generation.
|
|
18
|
+
*
|
|
19
|
+
* @module dsh-hiss-plugins/lan-access/gateway
|
|
20
|
+
*/
|
|
21
|
+
import { createServer, request as httpRequest } from "node:http";
|
|
22
|
+
import { networkInterfaces } from "node:os";
|
|
23
|
+
|
|
24
|
+
/** Bare loopback authority every forwarded request claims. */
|
|
25
|
+
const AUTHORITY = "127.0.0.1";
|
|
26
|
+
/** The relay target when no address is named. */
|
|
27
|
+
const LOOPBACK = "127.0.0.1";
|
|
28
|
+
/** Headers a proxy must not pass on: they describe one hop, not the request. */
|
|
29
|
+
const HOP_BY_HOP = new Set(["connection", "keep-alive", "proxy-connection", "transfer-encoding", "te", "trailer", "upgrade"]);
|
|
30
|
+
/** Interface names Windows and the usual VPN tools use for adapters no phone can reach. */
|
|
31
|
+
const VIRTUAL = /vEthernet|Hyper-V|VirtualBox|VMware|WSL|Tailscale|ZeroTier|Docker|Bluetooth/iu;
|
|
32
|
+
/** Paired clients kept at once; a LAN feature does not need more. */
|
|
33
|
+
const SESSION_LIMIT = 32;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The machine's reachable IPv4 addresses, network adapters before virtual ones.
|
|
37
|
+
* `virtual` marks adapters a phone cannot reach (Hyper-V, VPN); callers use it to
|
|
38
|
+
* skip such an address when a scan target is needed.
|
|
39
|
+
* @param interfaces - a `os.networkInterfaces()` shaped table.
|
|
40
|
+
* @returns `{ name, address, virtual }` entries; empty when nothing is reachable.
|
|
41
|
+
*/
|
|
42
|
+
export function lanAddresses(interfaces = networkInterfaces()) {
|
|
43
|
+
const found = [];
|
|
44
|
+
for (const [name, entries] of Object.entries(interfaces)) {
|
|
45
|
+
for (const entry of entries ?? []) {
|
|
46
|
+
if ((entry.family !== "IPv4" && entry.family !== 4) || entry.internal || entry.address.startsWith("169.254.")) continue;
|
|
47
|
+
found.push({ name, address: entry.address, virtual: VIRTUAL.test(name) });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// A phone on the Wi-Fi belongs to the physical adapter, so the virtual ones
|
|
51
|
+
// (Hyper-V, VPN) come after every candidate a phone can actually reach.
|
|
52
|
+
found.sort((left, right) => Number(left.virtual) - Number(right.virtual) || left.name.localeCompare(right.name));
|
|
53
|
+
return found.map(({ name, address, virtual }) => ({ name, address, virtual }));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The headers one forwarded request carries.
|
|
58
|
+
*
|
|
59
|
+
* `Host` always names loopback. `Origin` is rewritten only when it already
|
|
60
|
+
* matched the authority the request arrived on, so a cross-site Origin keeps its
|
|
61
|
+
* mismatch and the Host's fence still refuses it.
|
|
62
|
+
*
|
|
63
|
+
* @param headers - the incoming request headers.
|
|
64
|
+
* @param options - `inboundAuthority`: the Host header the browser sent.
|
|
65
|
+
* @returns a fresh header object.
|
|
66
|
+
*/
|
|
67
|
+
export function rewriteHeaders(headers, { inboundAuthority }) {
|
|
68
|
+
const rewritten = {};
|
|
69
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
70
|
+
if (value === undefined || HOP_BY_HOP.has(name.toLowerCase())) continue;
|
|
71
|
+
rewritten[name] = value;
|
|
72
|
+
}
|
|
73
|
+
// shortcut: every forwarded request claims the loopback authority, so a future
|
|
74
|
+
// unauthenticated loopback-only route would also be reachable through this
|
|
75
|
+
// listener; revisit if the Connection fence stops requiring the browser cookie
|
|
76
|
+
// on every /api route.
|
|
77
|
+
rewritten.host = AUTHORITY;
|
|
78
|
+
const origin = headers.origin;
|
|
79
|
+
if (typeof origin === "string" && namesSameAuthority(origin, inboundAuthority)) rewritten.origin = `http://${AUTHORITY}`;
|
|
80
|
+
return rewritten;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Whether an Origin header names one authority.
|
|
85
|
+
* @param origin - the Origin header value.
|
|
86
|
+
* @param authority - a `host[:port]` authority.
|
|
87
|
+
* @returns true when the origin's authority matches.
|
|
88
|
+
*/
|
|
89
|
+
function namesSameAuthority(origin, authority) {
|
|
90
|
+
try {
|
|
91
|
+
return new URL(origin).host === authority;
|
|
92
|
+
} catch {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The response headers one forwarded answer carries.
|
|
99
|
+
* @param headers - the upstream response headers.
|
|
100
|
+
* @returns a copy without the hop-by-hop names.
|
|
101
|
+
*/
|
|
102
|
+
function responseHeaders(headers) {
|
|
103
|
+
const copied = {};
|
|
104
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
105
|
+
if (value === undefined || HOP_BY_HOP.has(name.toLowerCase())) continue;
|
|
106
|
+
copied[name] = value;
|
|
107
|
+
}
|
|
108
|
+
return copied;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Render raw header pairs as a header block without its terminating blank line.
|
|
113
|
+
* @param raw - the `rawHeaders` array of name/value pairs.
|
|
114
|
+
* @returns CRLF-joined header lines.
|
|
115
|
+
*/
|
|
116
|
+
function rawHeaders(raw) {
|
|
117
|
+
const lines = [];
|
|
118
|
+
for (let index = 0; index + 1 < raw.length; index += 2) lines.push(`${raw[index]}: ${raw[index + 1]}`);
|
|
119
|
+
return lines.join("\r\n");
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* The first cookie pair of a Set-Cookie header value.
|
|
124
|
+
* @param setCookie - the header value, or the array Node keeps for repeats.
|
|
125
|
+
* @returns `name=value`, or undefined when the response set no cookie.
|
|
126
|
+
*/
|
|
127
|
+
function sessionCookieOf(setCookie) {
|
|
128
|
+
if (setCookie === undefined) return undefined;
|
|
129
|
+
const value = Array.isArray(setCookie) ? setCookie[0] : setCookie;
|
|
130
|
+
if (typeof value !== "string" || value === "") return undefined;
|
|
131
|
+
return value.split(";")[0];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Forward one buffered HTTP request and stream the answer back.
|
|
136
|
+
* @param request - the incoming request.
|
|
137
|
+
* @param response - the answer to write.
|
|
138
|
+
* @param relay - the upstream address and the session roster.
|
|
139
|
+
* @param session - the Host cookie this client is entitled to, when paired.
|
|
140
|
+
*/
|
|
141
|
+
function forward(request, response, relay, session) {
|
|
142
|
+
const headers = rewriteHeaders(request.headers, { inboundAuthority: request.headers.host });
|
|
143
|
+
if (session !== undefined) headers.cookie = session;
|
|
144
|
+
const upstream = httpRequest({
|
|
145
|
+
host: relay.targetHost,
|
|
146
|
+
port: relay.targetPort,
|
|
147
|
+
method: request.method,
|
|
148
|
+
path: request.url,
|
|
149
|
+
headers,
|
|
150
|
+
});
|
|
151
|
+
upstream.on("response", (answer) => {
|
|
152
|
+
if (answer.statusCode === 401 && session !== undefined) relay.sessions.delete(relay.client);
|
|
153
|
+
// Only refusals are worth a line: they are what "the phone shows 401" means.
|
|
154
|
+
if (answer.statusCode !== undefined && answer.statusCode >= 400) {
|
|
155
|
+
relay.log?.({ event: "forward", client: relay.client, path: String(request.url ?? "").split("?")[0], session: session !== undefined, status: answer.statusCode });
|
|
156
|
+
}
|
|
157
|
+
response.writeHead(answer.statusCode ?? 502, responseHeaders(answer.headers));
|
|
158
|
+
// An error on either stream must not surface as an unhandled 'error' event:
|
|
159
|
+
// that would take the whole Host process down with one dropped connection.
|
|
160
|
+
answer.on("error", () => response.destroy());
|
|
161
|
+
response.on("error", () => upstream.destroy());
|
|
162
|
+
answer.pipe(response);
|
|
163
|
+
});
|
|
164
|
+
upstream.on("error", () => {
|
|
165
|
+
if (!response.headersSent) response.writeHead(502, { "content-type": "text/plain; charset=utf-8" });
|
|
166
|
+
response.end("lan-access: the DSH Host is not reachable\n");
|
|
167
|
+
});
|
|
168
|
+
request.on("aborted", () => upstream.destroy());
|
|
169
|
+
request.on("error", () => upstream.destroy());
|
|
170
|
+
request.pipe(upstream);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Tunnel one WebSocket upgrade in both directions, relaying a refusal as-is.
|
|
175
|
+
* @param request - the upgrade request.
|
|
176
|
+
* @param socket - the browser socket.
|
|
177
|
+
* @param head - bytes read past the request head.
|
|
178
|
+
* @param relay - the upstream address, the session roster, and the diagnostics sink.
|
|
179
|
+
* @param session - the Host cookie this client is entitled to, when paired.
|
|
180
|
+
*/
|
|
181
|
+
function tunnel(request, socket, head, relay, session) {
|
|
182
|
+
const headers = {
|
|
183
|
+
...rewriteHeaders(request.headers, { inboundAuthority: request.headers.host }),
|
|
184
|
+
connection: "Upgrade",
|
|
185
|
+
upgrade: request.headers.upgrade,
|
|
186
|
+
};
|
|
187
|
+
if (session !== undefined) headers.cookie = session;
|
|
188
|
+
const upstream = httpRequest({
|
|
189
|
+
host: relay.targetHost,
|
|
190
|
+
port: relay.targetPort,
|
|
191
|
+
method: request.method,
|
|
192
|
+
path: request.url,
|
|
193
|
+
headers,
|
|
194
|
+
});
|
|
195
|
+
const destroy = () => {
|
|
196
|
+
socket.destroy();
|
|
197
|
+
upstream.destroy();
|
|
198
|
+
};
|
|
199
|
+
socket.on("error", destroy);
|
|
200
|
+
upstream.on("error", destroy);
|
|
201
|
+
upstream.on("response", (answer) => {
|
|
202
|
+
// The Host answered the handshake instead of upgrading (403/401): relay
|
|
203
|
+
// the status line and headers so the browser reports the real refusal.
|
|
204
|
+
socket.write(`HTTP/1.1 ${answer.statusCode} ${answer.statusMessage ?? "Error"}\r\n${rawHeaders(answer.rawHeaders)}\r\n\r\n`);
|
|
205
|
+
answer.resume();
|
|
206
|
+
socket.end();
|
|
207
|
+
});
|
|
208
|
+
upstream.on("upgrade", (answer, upstreamSocket, upstreamHead) => {
|
|
209
|
+
relay.upgrades.add(upstreamSocket);
|
|
210
|
+
upstreamSocket.once("close", () => relay.upgrades.delete(upstreamSocket));
|
|
211
|
+
upstreamSocket.on("error", destroy);
|
|
212
|
+
socket.write(`HTTP/1.1 ${answer.statusCode} ${answer.statusMessage ?? "Switching Protocols"}\r\n${rawHeaders(answer.rawHeaders)}\r\n\r\n`);
|
|
213
|
+
if (upstreamHead.length > 0) socket.write(upstreamHead);
|
|
214
|
+
upstreamSocket.pipe(socket).pipe(upstreamSocket);
|
|
215
|
+
socket.on("close", () => upstreamSocket.destroy());
|
|
216
|
+
});
|
|
217
|
+
if (head.length > 0) upstream.write(head);
|
|
218
|
+
upstream.end();
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Bind the LAN listener.
|
|
223
|
+
* @param options - `targetPort` (required), `targetHost`, `listenHost`, `listenPort`,
|
|
224
|
+
* `pair` (the pairing secret), `tokenUrl` (a function returning a tokenized loopback
|
|
225
|
+
* URL), and `log` (an optional diagnostics sink).
|
|
226
|
+
* @returns the bound port and address plus a close that frees them.
|
|
227
|
+
*/
|
|
228
|
+
export async function startGateway({ targetHost = LOOPBACK, targetPort, listenHost, listenPort = 0, pair, tokenUrl, log }) {
|
|
229
|
+
if (!Number.isInteger(targetPort) || targetPort < 1 || targetPort > 65535) {
|
|
230
|
+
throw new Error(`lan-access: targetPort must be the Host's listening port, got ${JSON.stringify(targetPort)}`);
|
|
231
|
+
}
|
|
232
|
+
const upgrades = new Set();
|
|
233
|
+
const sockets = new Set();
|
|
234
|
+
/** client address -> the Host cookie minted for its pairing. */
|
|
235
|
+
const sessions = new Map();
|
|
236
|
+
const relay = { targetHost, targetPort, upgrades, sessions, log };
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Exchange the gateway's own token URL for a Host cookie.
|
|
240
|
+
* @returns the cookie pair, or undefined when the Host refused.
|
|
241
|
+
*/
|
|
242
|
+
const exchangeToken = () => new Promise((resolve) => {
|
|
243
|
+
let url;
|
|
244
|
+
try {
|
|
245
|
+
url = new URL(tokenUrl());
|
|
246
|
+
} catch {
|
|
247
|
+
resolve(undefined);
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
const upstream = httpRequest({
|
|
251
|
+
host: targetHost,
|
|
252
|
+
port: targetPort,
|
|
253
|
+
method: "GET",
|
|
254
|
+
path: `${url.pathname}${url.search}`,
|
|
255
|
+
headers: { host: AUTHORITY },
|
|
256
|
+
}, (answer) => {
|
|
257
|
+
answer.resume();
|
|
258
|
+
const cookie = sessionCookieOf(answer.headers["set-cookie"]);
|
|
259
|
+
resolve(answer.statusCode === 303 && cookie !== undefined ? cookie : undefined);
|
|
260
|
+
});
|
|
261
|
+
upstream.on("error", () => resolve(undefined));
|
|
262
|
+
upstream.setTimeout(5000, () => {
|
|
263
|
+
upstream.destroy();
|
|
264
|
+
resolve(undefined);
|
|
265
|
+
});
|
|
266
|
+
upstream.end();
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Handle one pairing attempt; the answer is owned either way.
|
|
271
|
+
* @param request - the incoming request.
|
|
272
|
+
* @param response - the answer to write.
|
|
273
|
+
* @param supplied - the `pair` query value.
|
|
274
|
+
*/
|
|
275
|
+
const pairClient = async (request, response, supplied) => {
|
|
276
|
+
const client = request.socket?.remoteAddress ?? "";
|
|
277
|
+
const cookie = supplied === pair ? await exchangeToken() : undefined;
|
|
278
|
+
if (cookie === undefined) {
|
|
279
|
+
log?.({ event: "pair", client, ok: false });
|
|
280
|
+
response.writeHead(401, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
|
|
281
|
+
response.end("lan-access: pairing expired; reopen the QR page on the computer that runs DSH\n");
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
sessions.delete(client);
|
|
285
|
+
sessions.set(client, cookie);
|
|
286
|
+
while (sessions.size > SESSION_LIMIT) sessions.delete(sessions.keys().next().value);
|
|
287
|
+
log?.({ event: "pair", client, ok: true });
|
|
288
|
+
response.writeHead(303, { location: "./", "cache-control": "no-store", "referrer-policy": "no-referrer" });
|
|
289
|
+
response.end();
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
const server = createServer((request, response) => {
|
|
293
|
+
const client = request.socket?.remoteAddress ?? "";
|
|
294
|
+
let target;
|
|
295
|
+
try {
|
|
296
|
+
target = new URL(request.url ?? "/", "http://gateway.invalid");
|
|
297
|
+
} catch {
|
|
298
|
+
response.writeHead(400);
|
|
299
|
+
response.end();
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (pair !== undefined && target.searchParams.has("pair")) {
|
|
303
|
+
pairClient(request, response, target.searchParams.get("pair")).catch(() => {
|
|
304
|
+
response.destroy();
|
|
305
|
+
});
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
const session = sessions.get(client);
|
|
309
|
+
if (session !== undefined) {
|
|
310
|
+
// Touch the entry so the roster keeps the clients still talking.
|
|
311
|
+
sessions.delete(client);
|
|
312
|
+
sessions.set(client, session);
|
|
313
|
+
}
|
|
314
|
+
forward(request, response, { ...relay, client }, session);
|
|
315
|
+
});
|
|
316
|
+
server.on("connection", (socket) => {
|
|
317
|
+
sockets.add(socket);
|
|
318
|
+
socket.once("close", () => sockets.delete(socket));
|
|
319
|
+
});
|
|
320
|
+
server.on("upgrade", (request, socket, head) => {
|
|
321
|
+
const client = request.socket?.remoteAddress ?? "";
|
|
322
|
+
tunnel(request, socket, head, { ...relay, client }, sessions.get(client));
|
|
323
|
+
});
|
|
324
|
+
await new Promise((resolve, reject) => {
|
|
325
|
+
const onError = (error) => reject(error);
|
|
326
|
+
server.once("error", onError);
|
|
327
|
+
server.listen(listenPort, listenHost, () => {
|
|
328
|
+
server.off("error", onError);
|
|
329
|
+
// A socket error must not take the Host down; the failing connection is
|
|
330
|
+
// already destroyed by the handlers above.
|
|
331
|
+
server.on("error", () => {});
|
|
332
|
+
resolve();
|
|
333
|
+
});
|
|
334
|
+
});
|
|
335
|
+
const address = server.address();
|
|
336
|
+
return {
|
|
337
|
+
port: address.port,
|
|
338
|
+
address: listenHost,
|
|
339
|
+
/** Stop accepting, then drop what is still open so the port really frees. */
|
|
340
|
+
close: async () => {
|
|
341
|
+
// An upgraded socket is not an HTTP connection any more: `server.close()`
|
|
342
|
+
// waits for it forever, so every accepted socket is destroyed explicitly.
|
|
343
|
+
for (const socket of sockets) socket.destroy();
|
|
344
|
+
for (const socket of upgrades) socket.destroy();
|
|
345
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
346
|
+
},
|
|
347
|
+
};
|
|
348
|
+
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The lan-access row: one LAN listener that relays this Web Host, the
|
|
3
|
+
* `/lan` command that hands a phone the tokenized URL, and the loopback page
|
|
4
|
+
* that shows that URL as a QR code.
|
|
5
|
+
*
|
|
6
|
+
* The Desktop Host always binds the Host to loopback and reports
|
|
7
|
+
* `http://127.0.0.1:<port>` to its window, so the LAN surface cannot be the
|
|
8
|
+
* Host's own listener: it is a gateway beside it. See `./gateway.js` for why
|
|
9
|
+
* the forwarded request claims the loopback authority.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-hiss-plugins/lan-access
|
|
12
|
+
*/
|
|
13
|
+
import { randomBytes } from "node:crypto";
|
|
14
|
+
import { appendFileSync, mkdirSync, statSync } from "node:fs";
|
|
15
|
+
import { homedir } from "node:os";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
import { lanAddresses, startGateway } from "./gateway.js";
|
|
18
|
+
import { qrMatrix, qrSvg } from "./qr.js";
|
|
19
|
+
|
|
20
|
+
export const name = "lan-access";
|
|
21
|
+
export const inject = ["webServer"];
|
|
22
|
+
|
|
23
|
+
/** The stable LAN port a phone bookmark can keep. */
|
|
24
|
+
const DEFAULT_PORT = 7505;
|
|
25
|
+
/** Every IPv4 interface, so a DHCP address change never invalidates the bind. */
|
|
26
|
+
const WILDCARD = "0.0.0.0";
|
|
27
|
+
/** Loopback page that renders the pairing URL as a QR code. */
|
|
28
|
+
const PAGE_PATH = "/lan-access";
|
|
29
|
+
/** Diagnostics log: only refusals and pairing events, capped. */
|
|
30
|
+
const LOG_PATH = join(homedir(), ".dsh", "lan-access.log");
|
|
31
|
+
const LOG_LIMIT_BYTES = 256 * 1024;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Mount the gateway, the QR page, and the command.
|
|
35
|
+
* @param {import("@deepseek-ai/cordis").Context} ctx - host context carrying `webServer`.
|
|
36
|
+
* @param {{ host?: string, port?: number | string }} [config] - profile-patch overrides.
|
|
37
|
+
*/
|
|
38
|
+
export function apply(ctx, config = {}) {
|
|
39
|
+
const port = portOf(config?.port);
|
|
40
|
+
const host = typeof config?.host === "string" && config.host !== "" ? config.host : undefined;
|
|
41
|
+
// Off by default: tests and ordinary users must not grow a log file; turning it
|
|
42
|
+
// on in the profile patch is what makes a phone-side refusal diagnosable.
|
|
43
|
+
const debug = config?.debug === true;
|
|
44
|
+
const pair = randomBytes(18).toString("base64url");
|
|
45
|
+
const state = { status: "starting", error: undefined, bindHost: undefined, port: undefined, pageUrl: undefined, pair };
|
|
46
|
+
|
|
47
|
+
ctx.inject(["connection"], (connectionCtx) => {
|
|
48
|
+
const connection = connectionCtx.connection;
|
|
49
|
+
const webServer = connectionCtx.get("webServer");
|
|
50
|
+
|
|
51
|
+
if (webServer !== undefined && typeof webServer.register === "function") {
|
|
52
|
+
connectionCtx.effect(() => webServer.register({
|
|
53
|
+
kind: "exact",
|
|
54
|
+
path: PAGE_PATH,
|
|
55
|
+
handler: (request, response) => servePage(request, response, { state, connection, addresses: lanAddresses() }),
|
|
56
|
+
}), "lan-access.page");
|
|
57
|
+
try {
|
|
58
|
+
state.pageUrl = new URL(PAGE_PATH, webServer.getOrigin()).href;
|
|
59
|
+
} catch {
|
|
60
|
+
state.pageUrl = undefined;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
connectionCtx.effect(async () => {
|
|
65
|
+
const server = connectionCtx.get("webServer");
|
|
66
|
+
if (server === undefined) return;
|
|
67
|
+
if (!isLoopback(server.host)) {
|
|
68
|
+
// Someone already ran `dsh web --host <address>`; a second listener
|
|
69
|
+
// would only add a surface without adding reach.
|
|
70
|
+
state.status = "direct";
|
|
71
|
+
state.bindHost = server.host;
|
|
72
|
+
state.port = server.port;
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
const gateway = await bindGateway(server, port, host, {
|
|
77
|
+
pair,
|
|
78
|
+
tokenUrl: () => connection.authenticatedUrl(`${server.getOrigin()}/`),
|
|
79
|
+
log: debug ? writeLog : undefined,
|
|
80
|
+
});
|
|
81
|
+
if (debug) writeLog({ event: "listen", address: gateway.address, port: gateway.port });
|
|
82
|
+
state.status = "listening";
|
|
83
|
+
state.bindHost = gateway.address;
|
|
84
|
+
state.port = gateway.port;
|
|
85
|
+
connectionCtx.logger.warn(`lan-access: serving the browser surface on port ${String(gateway.port)} over plain HTTP; disable the row to stop it`);
|
|
86
|
+
return async () => {
|
|
87
|
+
await gateway.close();
|
|
88
|
+
state.status = "closed";
|
|
89
|
+
};
|
|
90
|
+
} catch (error) {
|
|
91
|
+
state.status = "failed";
|
|
92
|
+
state.error = messageOf(error);
|
|
93
|
+
connectionCtx.logger.warn(`lan-access: ${state.error}`);
|
|
94
|
+
}
|
|
95
|
+
}, "lan-access.listen");
|
|
96
|
+
|
|
97
|
+
ctx.inject(["commands"], (commandCtx) => {
|
|
98
|
+
commandCtx.commands.register({
|
|
99
|
+
name: "lan",
|
|
100
|
+
description: "Show the LAN URL (and QR page) a phone can use for this Web GUI",
|
|
101
|
+
handler: (invocation) => (invocation.rawInput.trim() === ""
|
|
102
|
+
? report(state, connection, lanAddresses())
|
|
103
|
+
: { kind: "error", text: "Usage: /lan (no arguments)" }),
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Bind the LAN gateway, falling back to one concrete address when the wildcard
|
|
111
|
+
* port is already taken by this Host's own loopback listener on the same port.
|
|
112
|
+
* @param {{ host: string, port: number }} server - the Host's web server facts.
|
|
113
|
+
* @param {number} port - the configured LAN port.
|
|
114
|
+
* @param {string | undefined} pinned - an explicitly configured bind address.
|
|
115
|
+
* @returns the started gateway.
|
|
116
|
+
*/
|
|
117
|
+
async function bindGateway(server, port, pinned, pairing) {
|
|
118
|
+
const listenHost = pinned ?? WILDCARD;
|
|
119
|
+
const options = { targetHost: server.host, targetPort: server.port, listenPort: port, ...pairing };
|
|
120
|
+
try {
|
|
121
|
+
return await startGateway({ ...options, listenHost });
|
|
122
|
+
} catch (error) {
|
|
123
|
+
const fallback = pinned === undefined && error?.code === "EADDRINUSE"
|
|
124
|
+
? lanAddresses().find((entry) => entry.virtual !== true)?.address
|
|
125
|
+
: undefined;
|
|
126
|
+
if (fallback === undefined) throw error;
|
|
127
|
+
return startGateway({ ...options, listenHost: fallback });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Build the `/lan` answer from the listener's current state; LAN addresses are
|
|
133
|
+
* read at call time, not at boot, so a DHCP change shows up instead of going stale.
|
|
134
|
+
* @param {{ status: string, error?: string, bindHost?: string, port?: number, pageUrl?: string }} state - the listener state.
|
|
135
|
+
* @param {{ authenticatedUrl: (base: string) => string }} connection - the browser-auth carrier.
|
|
136
|
+
* @param {{ name: string, address: string }[]} addresses - the current LAN addresses.
|
|
137
|
+
* @returns {{ kind: "success" | "error", text: string }} the command result.
|
|
138
|
+
*/
|
|
139
|
+
export function report(state, connection, addresses) {
|
|
140
|
+
if (state.status === "listening") {
|
|
141
|
+
const physical = addresses.filter((entry) => entry.virtual !== true);
|
|
142
|
+
const ignored = addresses.filter((entry) => entry.virtual === true);
|
|
143
|
+
if (physical.length === 0) return { kind: "error", text: "LAN access is listening but this machine has no physical LAN IPv4 address right now." };
|
|
144
|
+
const url = `http://${physical[0].address}:${String(state.port)}/?pair=${String(state.pair)}`;
|
|
145
|
+
const lines = [
|
|
146
|
+
`LAN access: ${url}`,
|
|
147
|
+
state.pageUrl === undefined ? "Open this URL once on a phone on the same network; the signed browser cookie then lasts 30 days." : `QR code: open ${state.pageUrl} on this computer and scan it with the phone.`,
|
|
148
|
+
`Plain HTTP on the LAN: only use it on a network you trust (Windows firewall must allow TCP ${String(state.port)} for this app).`,
|
|
149
|
+
];
|
|
150
|
+
if (physical.length > 1) lines.push(`Other addresses: ${physical.slice(1).map((entry) => `${entry.address} (${entry.name})`).join(", ")}.`);
|
|
151
|
+
if (ignored.length > 0) lines.push(`Ignored virtual adapters (a phone cannot reach them): ${ignored.map((entry) => `${entry.address} (${entry.name})`).join(", ")}.`);
|
|
152
|
+
return { kind: "success", text: lines.join("\n") };
|
|
153
|
+
}
|
|
154
|
+
if (state.status === "direct") {
|
|
155
|
+
const url = connection.authenticatedUrl(`http://${state.bindHost}:${String(state.port)}/`);
|
|
156
|
+
return { kind: "success", text: `The Host already listens on a network address: ${url}` };
|
|
157
|
+
}
|
|
158
|
+
if (state.status === "failed") return { kind: "error", text: `LAN access is not running: ${state.error}. Set \`host\` or \`port\` in the profile patch and reload the row.` };
|
|
159
|
+
if (state.status === "closed") return { kind: "error", text: "LAN access is disabled; enable the lan-access row in the Plugins page." };
|
|
160
|
+
return { kind: "error", text: "LAN access is still starting; run /lan again in a moment." };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Serve the QR page to an authenticated owner only: it carries the launch token.
|
|
165
|
+
* @param {import("node:http").IncomingMessage} request - the page request.
|
|
166
|
+
* @param {import("node:http").ServerResponse} response - the answer.
|
|
167
|
+
* @param {{ state: object, connection: object, addresses: { name: string, address: string }[] }} deps - listener state, browser auth, and the LAN addresses to show.
|
|
168
|
+
*/
|
|
169
|
+
export function servePage(request, response, { state, connection, addresses }) {
|
|
170
|
+
let admission;
|
|
171
|
+
try {
|
|
172
|
+
admission = connection.admit(request);
|
|
173
|
+
} catch {
|
|
174
|
+
admission = { rejection: 401 };
|
|
175
|
+
}
|
|
176
|
+
if (admission.rejection !== undefined) {
|
|
177
|
+
response.writeHead(admission.rejection, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
|
|
178
|
+
response.end(admission.rejection === 401 ? "Open this page from the DSH window on this computer.\n" : "forbidden\n");
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
let embed = false;
|
|
182
|
+
try {
|
|
183
|
+
embed = new URL(request.url ?? "/", "http://lan.invalid").searchParams.get("embed") === "1";
|
|
184
|
+
} catch {
|
|
185
|
+
embed = false;
|
|
186
|
+
}
|
|
187
|
+
response.writeHead(200, {
|
|
188
|
+
"content-type": "text/html; charset=utf-8",
|
|
189
|
+
"cache-control": "no-store",
|
|
190
|
+
"referrer-policy": "no-referrer",
|
|
191
|
+
});
|
|
192
|
+
response.end(renderPage(state, connection, addresses, { embed }));
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Render the QR page.
|
|
197
|
+
* @param {{ status: string, error?: string, bindHost?: string, port?: number }} state - the listener state.
|
|
198
|
+
* @param {{ authenticatedUrl: (base: string) => string }} connection - the browser-auth carrier.
|
|
199
|
+
* @param {{ name: string, address: string }[]} addresses - the current LAN addresses.
|
|
200
|
+
* @param {{ embed?: boolean }} [options] - `embed` drops the page chrome for the in-app popup.
|
|
201
|
+
* @returns the HTML document.
|
|
202
|
+
*/
|
|
203
|
+
export function renderPage(state, connection, addresses, { embed = false } = {}) {
|
|
204
|
+
const parts = [
|
|
205
|
+
"<!doctype html><html lang=\"zh\"><head><meta charset=\"utf-8\">",
|
|
206
|
+
"<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">",
|
|
207
|
+
"<title>DSH 手机访问</title><style>body{font:15px/1.6 system-ui,sans-serif;margin:24px;color:#111;background:#fafafa}",
|
|
208
|
+
"section{background:#fff;border:1px solid #e4e4e7;border-radius:12px;padding:16px;margin:16px 0;max-width:420px}",
|
|
209
|
+
"h1{font-size:20px}h2{font-size:14px;color:#52525b;margin:0 0 12px}",
|
|
210
|
+
// The URL is read, not copied by sight: keep the body face at a readable size.
|
|
211
|
+
"code{font:inherit;font-size:14px;line-height:1.5;color:#3f3f46;word-break:break-all}svg{max-width:100%;height:auto}",
|
|
212
|
+
embed ? "body{margin:0;padding:8px;background:#fff;overflow:hidden}section{margin:0;border:none;padding:0;max-width:none}svg{display:block;margin:0 auto}" : "",
|
|
213
|
+
"</style></head><body>",
|
|
214
|
+
];
|
|
215
|
+
if (!embed) parts.push("<h1>手机访问本机 DSH</h1>");
|
|
216
|
+
if (state.status === "listening") {
|
|
217
|
+
const physical = addresses.filter((entry) => entry.virtual !== true);
|
|
218
|
+
if (physical.length === 0) parts.push("<p>本机当前只有虚拟网卡(Hyper-V / VPN),手机无法连接。</p>");
|
|
219
|
+
for (const entry of physical) {
|
|
220
|
+
const url = `http://${entry.address}:${String(state.port)}/?pair=${String(state.pair)}`;
|
|
221
|
+
parts.push(
|
|
222
|
+
`<section><h2>${escapeHtml(entry.name)} · ${escapeHtml(entry.address)}</h2>`,
|
|
223
|
+
qrSvg(qrMatrix(url), { scale: embed ? 6 : 8, border: 4 }),
|
|
224
|
+
`<p><code>${escapeHtml(url)}</code></p></section>`,
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
// No instructions here: the popup below the frame and /lan already say it,
|
|
228
|
+
// and a virtual adapter with no phone-reachable route is simply not listed.
|
|
229
|
+
} else if (state.status === "direct") {
|
|
230
|
+
parts.push(`<p>Host 已监听网络地址 <code>http://${escapeHtml(String(state.bindHost))}:${String(state.port)}/</code>,无需网关。</p>`);
|
|
231
|
+
} else if (state.status === "failed") {
|
|
232
|
+
parts.push(`<p role=\"alert\"><strong>局域网监听失败:</strong>${escapeHtml(String(state.error))}</p>`, "<p>在 profile 的 <code>cordis.patch.yml</code> 里给 <code>dsh-hiss-plugins-lan-access</code> 行设置 <code>config.host</code> / <code>config.port</code> 后重启。</p>");
|
|
233
|
+
} else {
|
|
234
|
+
parts.push("<p>正在启动局域网监听,稍后刷新本页。</p>");
|
|
235
|
+
}
|
|
236
|
+
parts.push("</body></html>");
|
|
237
|
+
return parts.join("");
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Escape text for HTML text and attribute contexts.
|
|
242
|
+
* @param value - the text.
|
|
243
|
+
* @returns the escaped text.
|
|
244
|
+
*/
|
|
245
|
+
function escapeHtml(value) {
|
|
246
|
+
return String(value).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Append one diagnostic line, dropping the file instead of growing without
|
|
251
|
+
* bound. Every write failure is ignored: diagnostics never break the listener.
|
|
252
|
+
* @param entry - the event record.
|
|
253
|
+
*/
|
|
254
|
+
function writeLog(entry) {
|
|
255
|
+
try {
|
|
256
|
+
mkdirSync(join(homedir(), ".dsh"), { recursive: true });
|
|
257
|
+
let size = 0;
|
|
258
|
+
try {
|
|
259
|
+
size = statSync(LOG_PATH).size;
|
|
260
|
+
} catch {
|
|
261
|
+
size = 0;
|
|
262
|
+
}
|
|
263
|
+
const stamp = new Date().toISOString();
|
|
264
|
+
appendFileSync(LOG_PATH, `${stamp} ${JSON.stringify(entry)}\n`, { flag: size > LOG_LIMIT_BYTES ? "w" : "a" });
|
|
265
|
+
} catch {
|
|
266
|
+
// Diagnostics are optional.
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Read the configured LAN port.
|
|
272
|
+
* @param value - the profile patch value, or undefined.
|
|
273
|
+
* @returns the listening port; 0 asks the OS to pick one.
|
|
274
|
+
*/
|
|
275
|
+
function portOf(value) {
|
|
276
|
+
if (value === undefined) return DEFAULT_PORT;
|
|
277
|
+
const port = Number(value);
|
|
278
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error(`lan-access: port must be an integer 0-65535, got ${JSON.stringify(value)}`);
|
|
279
|
+
return port;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Whether an address is the loopback authority.
|
|
284
|
+
* @param host - a bind address literal.
|
|
285
|
+
* @returns true for `localhost`, `::1`, and 127/8.
|
|
286
|
+
*/
|
|
287
|
+
function isLoopback(host) {
|
|
288
|
+
return host === "localhost" || host === "::1" || /^127\./u.test(host);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* Readable text for anything thrown.
|
|
293
|
+
* @param error - the thrown value.
|
|
294
|
+
* @returns its message.
|
|
295
|
+
*/
|
|
296
|
+
function messageOf(error) {
|
|
297
|
+
return error instanceof Error ? error.message : String(error);
|
|
298
|
+
}
|