dsh-hiss-plugins 1.5.1 → 3.0.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.
@@ -1,247 +0,0 @@
1
- import { resolve } from "node:path";
2
- import { defineTool } from "@deepseek-ai/dsh-tools";
3
-
4
- export const name = "colgrep";
5
- export const inject = ["tools", "shell", "sandboxPolicy", "systemPrompt"];
6
-
7
- const LONG_PATH_PREFIX = String.fromCharCode(92, 92, 63, 92); // "\\?\"
8
-
9
- const TOOL_DESCRIPTION = `Semantic code search over the workspace using the local colgrep CLI (ColBERT multi-vector search). Finds code by meaning, not exact text. Use a natural-language \`query\` such as "error handling for database connections". Defaults to \`search\`; search auto-indexes, so the first run in a project builds the index and is slower. Use \`command:"status"\` to inspect the index, \`command:"init"\` to (re)build it explicitly, and \`no_update:true\` for a fast search over an existing index. Pass \`root\` to search a project other than the workspace, and \`path\` to narrow the search within it. Use \`pattern\` to pre-filter by regex, \`include\` to limit file types (e.g. "*.rs"), and \`code_only\` to skip text/config files. Use \`agent:true\` for open-ended "where is X handled?" questions: colgrep's local sub-agent explores the repository and returns code locations (slower; requires the agent model).`;
10
-
11
- const GUIDANCE = [
12
- "Semantic code search is available through the `colgrep` tool. ",
13
- "Reach for it when you want code by meaning and cannot name the exact identifier — grep is for text you can already spell out. ",
14
- "It auto-indexes on demand, so the first search in a project is slower; use `pattern` for a regex pre-filter that ranks semantically after. ",
15
- "For open-ended \"where is X handled?\" questions, pass `agent:true` to run colgrep's local sub-agent search; it returns code locations and is slower than a normal search. ",
16
- "Pass `root` to search a project other than the workspace. ",
17
- ].join("");
18
-
19
- /**
20
- * Usage guidance carrying the current workspace, so the agent passes the right
21
- * default root.
22
- *
23
- * @param {string} cwd the session workspace path.
24
- * @returns {string} prompt text for the colgrep guidance section.
25
- */
26
- export function guidanceFor(cwd) {
27
- return `${GUIDANCE} Current workspace: ${cwd}; the default root.`;
28
- }
29
-
30
- export function stripPathPrefix(path) {
31
- const value = String(path);
32
- return value.startsWith(LONG_PATH_PREFIX) ? value.slice(4) : value;
33
- }
34
-
35
- export function quoteArg(value) {
36
- return "'" + String(value).replace(/'/g, "''") + "'";
37
- }
38
-
39
- export function buildArgs(args) {
40
- const command = args.command || "search";
41
- const argv = ["colgrep"];
42
- if (command === "search") {
43
- if (typeof args.query !== "string" || args.query.trim() === "") {
44
- throw new Error("query must be a non-empty string");
45
- }
46
- if (args.agent) argv.push("--agent", "--json");
47
- else argv.push("--json");
48
- argv.push("--color", "never", "-y");
49
- if (args.no_update) argv.push("--no-update");
50
- argv.push("-k", String(args.top_k ? Number(args.top_k) : 15));
51
- if (args.pattern) argv.push("-e", args.pattern);
52
- if (args.include) argv.push("--include", args.include);
53
- if (args.code_only) argv.push("--code-only");
54
- argv.push(String(args.query || ""));
55
- if (args.root) argv.push(String(args.root));
56
- if (args.path) argv.push(args.path);
57
- } else if (command === "init") {
58
- argv.push("init", "-y");
59
- if (args.root) argv.push(String(args.root));
60
- if (args.path) argv.push(args.path);
61
- } else if (command === "status") {
62
- argv.push("status");
63
- } else if (command === "clear") {
64
- argv.push("clear");
65
- } else {
66
- throw new Error("command must be one of: search, init, status, clear");
67
- }
68
- return argv;
69
- }
70
-
71
- export function normalizeResults(parsed) {
72
- return parsed.map((item) => {
73
- const unit = item && item.unit ? item.unit : {};
74
- return {
75
- file: stripPathPrefix(unit.file),
76
- name: unit.name || "",
77
- qualified_name: unit.qualified_name || "",
78
- line: unit.line,
79
- end_line: unit.end_line,
80
- language: unit.language || "",
81
- unit_type: unit.unit_type || "",
82
- signature: unit.signature || "",
83
- score: item ? item.score : null,
84
- };
85
- });
86
- }
87
-
88
- export function renderOutput(value) {
89
- if (!value || typeof value !== "object") return String(value);
90
- const lines = [];
91
- if (value.command === "search" && value.agent) {
92
- if (Array.isArray(value.locations)) {
93
- const label = value.submitted === false ? "inspected location(s)" : "location(s)";
94
- lines.push(`colgrep (agent): ${value.locations.length} ${label} for ${JSON.stringify(value.query)}`);
95
- if (value.submitted === false) lines.push("(the agent did not submit a final answer; showing the locations it inspected)");
96
- if (value.locations.length > 0) {
97
- lines.push("");
98
- for (const location of value.locations) {
99
- const start = location.line === undefined ? "?" : location.line;
100
- const end = location.end_line === undefined ? "?" : location.end_line;
101
- lines.push(`${location.file}:${start}-${end}`);
102
- }
103
- }
104
- if (value.error) lines.push(`[agent error] ${value.error}`);
105
- } else {
106
- lines.push("colgrep agent search failed");
107
- if (value.error) lines.push(`[agent error] ${value.error}`);
108
- if (value.stderr) lines.push(`[stderr]\n${value.stderr}`);
109
- else if (value.stdout) lines.push(`[stdout]\n${value.stdout}`);
110
- }
111
- } else if (value.command === "search" && Array.isArray(value.results)) {
112
- lines.push(`colgrep: ${value.results.length} result(s) for ${JSON.stringify(value.query)}`);
113
- value.results.forEach((result, index) => {
114
- const file = result.file || result.qualified_name || "?";
115
- const location = typeof result.line === "number" && typeof result.end_line === "number"
116
- ? `:${result.line}-${result.end_line}`
117
- : "";
118
- const meta = [result.language, result.unit_type, result.name].filter(Boolean).join(", ");
119
- const score = typeof result.score === "number" ? `score ${result.score.toFixed(2)}` : "";
120
- lines.push("");
121
- lines.push(`${index + 1}. ${file}${location}${meta ? ` [${meta}]` : ""}${score ? ` (${score})` : ""}`);
122
- if (result.signature) {
123
- lines.push(` ${String(result.signature).split("\n")[0].slice(0, 200)}`);
124
- }
125
- });
126
- } else if (value.command === "search") {
127
- lines.push(value.ok ? "colgrep search returned unparseable output (ok=true)" : "colgrep search failed (ok=false)");
128
- if (value.stderr) lines.push(`[stderr]\n${value.stderr}`);
129
- else if (value.stdout) lines.push(`[stdout]\n${value.stdout}`);
130
- } else {
131
- lines.push(`colgrep ${value.command} (exit ${value.exitCode})`);
132
- if (value.stdout) lines.push(value.stdout);
133
- if (!value.ok && value.stderr) lines.push(`[stderr]\n${value.stderr}`);
134
- }
135
- if (value.timedOut) lines.push("[timed out]");
136
- if (value.aborted) lines.push("[aborted]");
137
- return lines.join("\n");
138
- }
139
-
140
- export function apply(ctx) {
141
- ctx.systemPrompt.section({
142
- name: "colgrep:guidance",
143
- order: 100,
144
- text: (context) => guidanceFor(context.scope?.session?.header?.cwd ?? process.cwd()),
145
- });
146
-
147
- ctx.tools.register(defineTool({
148
- name: "colgrep",
149
- description: TOOL_DESCRIPTION,
150
- parameters: {
151
- query: { type: "string", description: "Natural-language query (used by search).", required: true },
152
- command: { type: "string", enum: ["search", "init", "status", "clear"], description: "Operation. search (default) finds code; init builds/updates the index; status reports index state; clear removes the index." },
153
- root: { type: "string", description: "Project directory to search or index (default: the workspace root). Absolute or relative to the workspace." },
154
- path: { type: "string", description: "File or directory of `root` to search (default: the whole root). colgrep searches this target and falls back to the project index, so it is a focus, not a hard filter — narrow with `include` or `pattern` instead." },
155
- top_k: { type: "integer", description: "Number of results to return (-k). Default 15." },
156
- pattern: { type: "string", description: "Regex pre-filter (-e): grep first, then rank semantically (hybrid)." },
157
- include: { type: "string", description: "Only search files matching this glob (--include), e.g. \"*.rs\"." },
158
- code_only: { type: "boolean", description: "Only search code files; skip text/config files such as md/txt/yaml/json (--code-only)." },
159
- no_update: { type: "boolean", description: "Skip automatic index update and search the existing index as-is (--no-update)." },
160
- agent: { type: "boolean", description: "Run colgrep's local sub-agent search (--agent --json); returns file:start-end locations. Requires colgrep >= 1.8.5 and the agent model (colgrep --install-agent)." },
161
- },
162
- output: {
163
- schema: { type: "json" },
164
- render(_args, value) {
165
- return [{ type: "text", text: renderOutput(value) }];
166
- },
167
- },
168
- async execute(args, exec) {
169
- const policy = ctx.sandboxPolicy.resolve({ session: exec.agent && exec.agent.session });
170
- const root = policy && typeof policy.workspaceRoot === "string" ? policy.workspaceRoot : "";
171
- const base = root.replace(/[\\/]+$/, "");
172
- const dataDir = base + "/.colgrep-data";
173
- // `root` moves the run, never the index: index data stays inside the
174
- // workspace so it remains under the sandbox policy and the same
175
- // registry serves every root.
176
- const workdir = args.root && base ? resolve(base, args.root) : base;
177
- const command = buildArgs(args).map((part, index) => (index === 0 ? part : quoteArg(part))).join(" ");
178
- const spec = ctx.shell.resolve({
179
- command,
180
- timeoutMs: args.agent ? 600000 : 300000,
181
- stdoutMaxBytes: 2 * 1024 * 1024,
182
- signal: exec.signal,
183
- sandboxPolicy: policy,
184
- ...(workdir ? { workdir, env: { COLGREP_DATA_DIR: dataDir } } : {}),
185
- });
186
- // The shell seam is `execute()` → handle → `result()` since 0.1.7; the
187
- // older `run()` that settled the outcome directly no longer exists.
188
- const run = await (await ctx.shell.execute(spec)).result();
189
- const stdout = run.stdout && run.stdout.text ? run.stdout.text : "";
190
- const stderr = run.stderr && run.stderr.text ? run.stderr.text : "";
191
- const commandName = args.command || "search";
192
- const common = {
193
- ok: run.exitCode === 0,
194
- command: commandName,
195
- exitCode: run.exitCode,
196
- ...(run.timedOut ? { timedOut: true } : {}),
197
- ...(run.aborted ? { aborted: true } : {}),
198
- };
199
- if (commandName !== "search") {
200
- return { ...common, stdout, stderr };
201
- }
202
- if (args.agent) {
203
- let parsed = null;
204
- try {
205
- parsed = JSON.parse(stdout);
206
- } catch {
207
- parsed = null;
208
- }
209
- if (parsed !== null && Array.isArray(parsed.locations)) {
210
- const locations = parsed.locations.map((entry) => ({
211
- file: stripPathPrefix(entry.file),
212
- line: entry.start_line,
213
- end_line: entry.end_line,
214
- }));
215
- const agentError = typeof parsed.error === "string" && parsed.error !== "" ? parsed.error : undefined;
216
- return {
217
- ...common,
218
- ok: common.ok && agentError === undefined,
219
- query: args.query,
220
- agent: true,
221
- submitted: parsed.submitted !== false,
222
- count: locations.length,
223
- locations,
224
- ...(agentError === undefined ? {} : { error: agentError, stderr }),
225
- };
226
- }
227
- return { ...common, query: args.query, agent: true, locations: null, stdout, stderr };
228
- }
229
- let parsed = null;
230
- try {
231
- parsed = JSON.parse(stdout);
232
- } catch {
233
- parsed = null;
234
- }
235
- let results = null;
236
- if (Array.isArray(parsed)) {
237
- results = normalizeResults(parsed);
238
- } else if (parsed && typeof parsed === "object" && Array.isArray(parsed.results)) {
239
- results = normalizeResults(parsed.results);
240
- }
241
- if (results === null) {
242
- return { ...common, query: args.query, results: null, stdout, stderr };
243
- }
244
- return { ...common, query: args.query, count: results.length, results };
245
- },
246
- }));
247
- }
@@ -1,348 +0,0 @@
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
- }