dsh-local-link 0.1.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/lib/index.mjs ADDED
@@ -0,0 +1,902 @@
1
+ import QRCode from "qrcode";
2
+ import { dirname, isAbsolute, join, resolve } from "node:path";
3
+ import { connect, isIP } from "node:net";
4
+ import z from "@deepseek-ai/schemastery";
5
+ import { createServer, request } from "node:http";
6
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
7
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import { networkInterfaces } from "node:os";
9
+ //#region src/config.ts
10
+ const Config = z.object({
11
+ listenHost: z.string().default("0.0.0.0"),
12
+ listenPort: z.natural().max(65535).default(3088),
13
+ upstreamOrigin: z.string().default("http://127.0.0.1:3080"),
14
+ accessMode: z.union([z.const("pairing"), z.const("trusted-lan")]).default("pairing"),
15
+ pairingTtlSeconds: z.natural().default(300),
16
+ deviceTtlDays: z.natural().default(90),
17
+ diagnosticsEnabled: z.boolean().default(true),
18
+ diagnosticsMaxEntries: z.natural().max(200).default(15),
19
+ diagnosticsFile: z.string(),
20
+ stateFile: z.string().required()
21
+ });
22
+ function boundedInteger(value, name, fallback, minimum, maximum) {
23
+ const resolved = value ?? fallback;
24
+ if (typeof resolved !== "number" || !Number.isSafeInteger(resolved) || resolved < minimum || resolved > maximum) throw new Error(`${name} must be an integer from ${minimum} through ${maximum}`);
25
+ return resolved;
26
+ }
27
+ function parseConfig(value) {
28
+ const listenHost = value.listenHost ?? "0.0.0.0";
29
+ if (isIP(listenHost) === 0) throw new Error("listenHost must be an IP literal");
30
+ const upstreamOrigin = new URL(value.upstreamOrigin ?? "http://127.0.0.1:3080");
31
+ if (upstreamOrigin.protocol !== "http:" || upstreamOrigin.hostname !== "127.0.0.1" || upstreamOrigin.port === "" || upstreamOrigin.pathname !== "/" || upstreamOrigin.search !== "" || upstreamOrigin.hash !== "" || upstreamOrigin.username !== "" || upstreamOrigin.password !== "") throw new Error("upstreamOrigin must be an explicit http://127.0.0.1:<port> origin");
32
+ if (!isAbsolute(value.stateFile)) throw new Error("stateFile must be an absolute path");
33
+ if (value.diagnosticsFile !== void 0 && !isAbsolute(value.diagnosticsFile)) throw new Error("diagnosticsFile must be an absolute path");
34
+ const accessMode = value.accessMode ?? "pairing";
35
+ if (accessMode !== "pairing" && accessMode !== "trusted-lan") throw new Error("accessMode is not supported");
36
+ const stateFile = resolve(value.stateFile);
37
+ return Object.freeze({
38
+ listenHost,
39
+ listenPort: boundedInteger(value.listenPort, "listenPort", 3088, 1, 65535),
40
+ upstreamOrigin,
41
+ accessMode,
42
+ pairingTtlMs: boundedInteger(value.pairingTtlSeconds, "pairingTtlSeconds", 300, 30, 3600) * 1e3,
43
+ deviceTtlMs: boundedInteger(value.deviceTtlDays, "deviceTtlDays", 90, 1, 3650) * 864e5,
44
+ diagnosticsEnabled: value.diagnosticsEnabled ?? true,
45
+ diagnosticsMaxEntries: boundedInteger(value.diagnosticsMaxEntries, "diagnosticsMaxEntries", 15, 5, 200),
46
+ diagnosticsFile: resolve(value.diagnosticsFile ?? join(dirname(stateFile), "diagnostics.json")),
47
+ stateFile
48
+ });
49
+ }
50
+ //#endregion
51
+ //#region src/auth/device-store.ts
52
+ function hashToken(token) {
53
+ return createHash("sha256").update(token, "utf8").digest();
54
+ }
55
+ function safeHashEqual(expectedHex, actual) {
56
+ let expected;
57
+ try {
58
+ expected = Buffer.from(expectedHex, "hex");
59
+ } catch {
60
+ return false;
61
+ }
62
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
63
+ }
64
+ function sanitizeText(value, fallback, maxLength = 64) {
65
+ if (typeof value !== "string") return fallback;
66
+ return value.trim().replace(/[\u0000-\u001f\u007f]/gu, "").slice(0, maxLength) || fallback;
67
+ }
68
+ function legacyType(label) {
69
+ if (/ipad|tablet/iu.test(label)) return "Tablet";
70
+ if (/iphone|android|mobile|phone|linux\s+arm/iu.test(label)) return "Phone";
71
+ return "Computer";
72
+ }
73
+ var DeviceStore = class {
74
+ file;
75
+ ttlMs;
76
+ devices = /* @__PURE__ */ new Map();
77
+ loaded = false;
78
+ writeTail = Promise.resolve();
79
+ constructor(file, ttlMs) {
80
+ this.file = file;
81
+ this.ttlMs = ttlMs;
82
+ }
83
+ async load() {
84
+ if (this.loaded) return;
85
+ this.loaded = true;
86
+ try {
87
+ const parsed = JSON.parse(await readFile(this.file, "utf8"));
88
+ if (!Array.isArray(parsed.devices) || parsed.version !== 1 && parsed.version !== 2) throw new Error("unsupported device state");
89
+ const cutoff = Date.now() - this.ttlMs;
90
+ for (const device of parsed.devices) {
91
+ if (typeof device.id !== "string" || typeof device.tokenHash !== "string" || Date.parse(device.lastSeenAt) < cutoff) continue;
92
+ const migrated = parsed.version === 1 ? {
93
+ id: device.id,
94
+ name: "My device",
95
+ deviceType: legacyType(device.label),
96
+ browser: "Browser",
97
+ tokenHash: device.tokenHash,
98
+ createdAt: device.createdAt,
99
+ lastSeenAt: device.lastSeenAt
100
+ } : device;
101
+ this.devices.set(migrated.id, migrated);
102
+ }
103
+ } catch (error) {
104
+ if (error.code !== "ENOENT") throw error;
105
+ }
106
+ }
107
+ list() {
108
+ return [...this.devices.values()].map(({ tokenHash: _tokenHash, ...view }) => view).sort((a, b) => b.lastSeenAt.localeCompare(a.lastSeenAt));
109
+ }
110
+ async add(metadata) {
111
+ const value = metadata !== null && typeof metadata === "object" && !Array.isArray(metadata) ? metadata : {};
112
+ const token = randomBytes(32).toString("base64url");
113
+ const now = (/* @__PURE__ */ new Date()).toISOString();
114
+ const stored = {
115
+ id: randomUUID(),
116
+ name: "My device",
117
+ deviceType: sanitizeText(value.type, "Computer", 32),
118
+ browser: sanitizeText(value.browser, "Browser", 32),
119
+ tokenHash: hashToken(token).toString("hex"),
120
+ createdAt: now,
121
+ lastSeenAt: now
122
+ };
123
+ this.devices.set(stored.id, stored);
124
+ await this.persist();
125
+ const { tokenHash: _tokenHash, ...device } = stored;
126
+ return {
127
+ device,
128
+ token: `${stored.id}.${token}`
129
+ };
130
+ }
131
+ authorize(credential) {
132
+ if (credential === void 0 || credential.length > 256) return void 0;
133
+ const separator = credential.indexOf(".");
134
+ if (separator < 1) return void 0;
135
+ const id = credential.slice(0, separator);
136
+ const token = credential.slice(separator + 1);
137
+ const device = this.devices.get(id);
138
+ if (device === void 0 || !safeHashEqual(device.tokenHash, hashToken(token))) return void 0;
139
+ if (Date.parse(device.lastSeenAt) < Date.now() - this.ttlMs) {
140
+ this.devices.delete(id);
141
+ this.persist();
142
+ return;
143
+ }
144
+ const now = Date.now();
145
+ if (now - Date.parse(device.lastSeenAt) >= 6e4) {
146
+ this.devices.set(id, {
147
+ ...device,
148
+ lastSeenAt: new Date(now).toISOString()
149
+ });
150
+ this.persist();
151
+ }
152
+ const { tokenHash: _tokenHash, ...view } = device;
153
+ return view;
154
+ }
155
+ async revoke(id) {
156
+ const removed = this.devices.delete(id);
157
+ if (removed) await this.persist();
158
+ return removed;
159
+ }
160
+ async renameDevice(id, name) {
161
+ const device = this.devices.get(id);
162
+ if (device === void 0) return void 0;
163
+ const renamed = {
164
+ ...device,
165
+ name: sanitizeText(name, "My device")
166
+ };
167
+ this.devices.set(id, renamed);
168
+ await this.persist();
169
+ const { tokenHash: _tokenHash, ...view } = renamed;
170
+ return view;
171
+ }
172
+ persist() {
173
+ const snapshot = {
174
+ version: 2,
175
+ devices: [...this.devices.values()]
176
+ };
177
+ this.writeTail = this.writeTail.then(async () => {
178
+ await mkdir(dirname(this.file), { recursive: true });
179
+ const temporary = `${this.file}.${process.pid}.tmp`;
180
+ await writeFile(temporary, `${JSON.stringify(snapshot, null, 2)}\n`, {
181
+ encoding: "utf8",
182
+ mode: 384
183
+ });
184
+ await rename(temporary, this.file);
185
+ });
186
+ return this.writeTail;
187
+ }
188
+ };
189
+ //#endregion
190
+ //#region src/auth/pairing.ts
191
+ var PairingTokens = class {
192
+ ttlMs;
193
+ current;
194
+ constructor(ttlMs) {
195
+ this.ttlMs = ttlMs;
196
+ }
197
+ issue(now = Date.now()) {
198
+ const id = randomBytes(12).toString("base64url");
199
+ const token = randomBytes(24).toString("base64url");
200
+ const expiry = now + this.ttlMs;
201
+ this.current = {
202
+ id,
203
+ token,
204
+ expiry,
205
+ status: "active"
206
+ };
207
+ return {
208
+ id,
209
+ token,
210
+ expiresAt: new Date(expiry).toISOString()
211
+ };
212
+ }
213
+ consume(token, now = Date.now()) {
214
+ if (typeof token !== "string" || token.length > 128) return false;
215
+ const current = this.current;
216
+ if (current === void 0 || current.status !== "active" || current.token !== token) return false;
217
+ if (current.expiry < now) {
218
+ current.status = "expired";
219
+ return false;
220
+ }
221
+ current.status = "consumed";
222
+ return true;
223
+ }
224
+ getStatus(id, now = Date.now()) {
225
+ if (typeof id !== "string" || id.length > 128 || this.current?.id !== id) return "unknown";
226
+ if (this.current.status === "active" && this.current.expiry < now) this.current.status = "expired";
227
+ return this.current.status;
228
+ }
229
+ };
230
+ //#endregion
231
+ //#region src/diagnostics.ts
232
+ const SAFE_CONTEXT_KEYS = /* @__PURE__ */ new Set([
233
+ "reason",
234
+ "method",
235
+ "requestKind"
236
+ ]);
237
+ const DIAGNOSTIC_CODES = /* @__PURE__ */ new Set([
238
+ "PAIRING_GENERATION_FAILED",
239
+ "PAIRING_REJECTED",
240
+ "PAIRING_INVALID",
241
+ "REQUEST_REJECTED",
242
+ "AUTH_REQUIRED",
243
+ "HTTP_UPSTREAM_ERROR",
244
+ "INDEX_REWRITE_ERROR",
245
+ "WS_REJECTED",
246
+ "WS_UPSTREAM_ERROR",
247
+ "CLIPBOARD_COPY_FAILED",
248
+ "DEVICE_REVOKE_FAILED",
249
+ "DEVICE_RENAME_FAILED",
250
+ "DIAGNOSTICS_STATE_RESET"
251
+ ]);
252
+ const DUPLICATE_WINDOW_MS = 5e3;
253
+ function eventSignature(level, code, context) {
254
+ return JSON.stringify([
255
+ level,
256
+ code,
257
+ context === void 0 ? [] : Object.entries(context).sort(([left], [right]) => left.localeCompare(right))
258
+ ]);
259
+ }
260
+ function safeContext(value) {
261
+ const result = {};
262
+ for (const [key, item] of Object.entries(value)) {
263
+ if (!SAFE_CONTEXT_KEYS.has(key)) continue;
264
+ if (typeof item === "string") result[key] = item.replace(/[\u0000-\u001f\u007f]/gu, "").slice(0, 80);
265
+ else if (typeof item === "number" && Number.isFinite(item)) result[key] = item;
266
+ else if (typeof item === "boolean") result[key] = item;
267
+ }
268
+ return Object.keys(result).length === 0 ? void 0 : result;
269
+ }
270
+ function normalizeEvent(value) {
271
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return void 0;
272
+ const event = value;
273
+ if (typeof event.id !== "string" || event.id.length > 64 || typeof event.at !== "string" || !Number.isFinite(Date.parse(event.at)) || event.level !== "warn" && event.level !== "error" || typeof event.code !== "string" || !DIAGNOSTIC_CODES.has(event.code)) return void 0;
274
+ const rawContext = {};
275
+ if (event.context !== null && typeof event.context === "object" && !Array.isArray(event.context)) {
276
+ for (const [key, item] of Object.entries(event.context)) if (typeof item === "string" || typeof item === "number" || typeof item === "boolean") rawContext[key] = item;
277
+ }
278
+ const context = safeContext(rawContext);
279
+ return {
280
+ id: event.id,
281
+ at: event.at,
282
+ level: event.level,
283
+ code: event.code,
284
+ ...context === void 0 ? {} : { context }
285
+ };
286
+ }
287
+ var DiagnosticStore = class {
288
+ file;
289
+ maxEntries;
290
+ enabled;
291
+ events = [];
292
+ writeTail = Promise.resolve();
293
+ constructor(file, maxEntries, enabled) {
294
+ this.file = file;
295
+ this.maxEntries = maxEntries;
296
+ this.enabled = enabled;
297
+ }
298
+ async load() {
299
+ if (!this.enabled) return;
300
+ try {
301
+ const parsed = JSON.parse(await readFile(this.file, "utf8"));
302
+ if (parsed.version !== 1 || !Array.isArray(parsed.events)) throw new Error("unsupported diagnostics state");
303
+ const normalized = parsed.events.flatMap((value) => {
304
+ const event = normalizeEvent(value);
305
+ return event === void 0 ? [] : [event];
306
+ });
307
+ this.events = normalized.slice(-this.maxEntries);
308
+ if (this.events.length !== parsed.events.length) await this.persist();
309
+ } catch (error) {
310
+ if (error.code === "ENOENT") return;
311
+ this.events = [];
312
+ await this.record("warn", "DIAGNOSTICS_STATE_RESET", { reason: "unreadable_state" });
313
+ }
314
+ }
315
+ list() {
316
+ return [...this.events].reverse();
317
+ }
318
+ record(level, code, context = {}) {
319
+ if (!this.enabled) return Promise.resolve();
320
+ const safe = safeContext(context);
321
+ const now = Date.now();
322
+ const signature = eventSignature(level, code, safe);
323
+ if (this.events.some((event) => now - Date.parse(event.at) < DUPLICATE_WINDOW_MS && eventSignature(event.level, event.code, event.context) === signature)) return Promise.resolve();
324
+ const event = {
325
+ id: randomUUID(),
326
+ at: (/* @__PURE__ */ new Date()).toISOString(),
327
+ level,
328
+ code,
329
+ ...safe === void 0 ? {} : { context: safe }
330
+ };
331
+ this.events.push(event);
332
+ if (this.events.length > this.maxEntries) this.events.splice(0, this.events.length - this.maxEntries);
333
+ return this.persist();
334
+ }
335
+ async clear() {
336
+ this.events = [];
337
+ if (this.enabled) await this.persist();
338
+ }
339
+ persist() {
340
+ const snapshot = {
341
+ version: 1,
342
+ events: [...this.events]
343
+ };
344
+ this.writeTail = this.writeTail.catch(() => void 0).then(async () => {
345
+ await mkdir(dirname(this.file), { recursive: true });
346
+ const temporary = `${this.file}.${process.pid}.tmp`;
347
+ await writeFile(temporary, `${JSON.stringify(snapshot, null, 2)}\n`, {
348
+ encoding: "utf8",
349
+ mode: 384
350
+ });
351
+ await rename(temporary, this.file);
352
+ }).catch(() => void 0);
353
+ return this.writeTail;
354
+ }
355
+ };
356
+ //#endregion
357
+ //#region src/network.ts
358
+ function normalizeAddress(address) {
359
+ const zone = address.indexOf("%");
360
+ return zone < 0 ? address : address.slice(0, zone);
361
+ }
362
+ function isPrivateAddress(input) {
363
+ if (input === void 0) return false;
364
+ const address = normalizeAddress(input.replace(/^::ffff:/u, ""));
365
+ if (address === "::1" || address === "127.0.0.1") return true;
366
+ if (isIP(address) === 4) {
367
+ const octets = address.split(".").map(Number);
368
+ const first = octets[0] ?? -1;
369
+ const second = octets[1] ?? -1;
370
+ return first === 10 || first === 127 || first === 169 && second === 254 || first === 172 && second >= 16 && second <= 31 || first === 192 && second === 168;
371
+ }
372
+ if (isIP(address) === 6) {
373
+ const lower = address.toLowerCase();
374
+ return lower.startsWith("fc") || lower.startsWith("fd") || lower.startsWith("fe8") || lower.startsWith("fe9") || lower.startsWith("fea") || lower.startsWith("feb");
375
+ }
376
+ return false;
377
+ }
378
+ function privateInterfaceAddresses() {
379
+ const result = /* @__PURE__ */ new Map();
380
+ for (const [name, entries] of Object.entries(networkInterfaces())) for (const entry of entries ?? []) {
381
+ if (entry.internal || entry.family !== "IPv4" || !isPrivateAddress(entry.address)) continue;
382
+ const normalizedName = name.toLowerCase();
383
+ let score = 0;
384
+ if (/wi-?fi|wlan|wireless|ethernet|local area|локальн/u.test(normalizedName)) score += 100;
385
+ if (/tailscale|docker|vethernet|wsl|hyper-v|virtual|vpn|wireguard|amnezia|zerotier/u.test(normalizedName)) score -= 200;
386
+ if (entry.address.startsWith("192.168.")) score += 30;
387
+ else if (entry.address.startsWith("10.")) score += 20;
388
+ else if (entry.address.startsWith("172.")) score += 10;
389
+ result.set(entry.address, Math.max(result.get(entry.address) ?? Number.NEGATIVE_INFINITY, score));
390
+ }
391
+ return [...result].sort(([addressA, scoreA], [addressB, scoreB]) => scoreB - scoreA || addressA.localeCompare(addressB)).map(([address]) => address);
392
+ }
393
+ function parseHostHeader(value) {
394
+ if (value === void 0 || value.length > 255) return void 0;
395
+ try {
396
+ const url = new URL(`http://${value}`);
397
+ if (url.username !== "" || url.password !== "" || url.pathname !== "/" || url.search !== "" || url.hash !== "") return void 0;
398
+ return {
399
+ hostname: normalizeAddress(url.hostname.replace(/^\[|\]$/gu, "")),
400
+ port: Number(url.port || "80")
401
+ };
402
+ } catch {
403
+ return;
404
+ }
405
+ }
406
+ function allowedGatewayHost(value, listenHost, listenPort, addresses) {
407
+ const parsed = parseHostHeader(value);
408
+ if (parsed === void 0 || parsed.port !== listenPort) return false;
409
+ return (listenHost === "0.0.0.0" ? addresses : [listenHost]).includes(parsed.hostname);
410
+ }
411
+ //#endregion
412
+ //#region src/gateway/html.ts
413
+ const CLIENT_ID = "dsh-local-link";
414
+ const SETTINGS_ID = "@deepseek-ai/dsh-client-ui-settings";
415
+ const RANDOM_UUID_POLYFILL = `if(!window.crypto.randomUUID){window.crypto.randomUUID=function(){const b=new Uint8Array(16);window.crypto.getRandomValues(b);b[6]=(b[6]&15)|64;b[8]=(b[8]&63)|128;const h=Array.from(b,value=>value.toString(16).padStart(2,'0'));return h.slice(0,4).join('')+'-'+h.slice(4,6).join('')+'-'+h.slice(6,8).join('')+'-'+h.slice(8,10).join('')+'-'+h.slice(10).join('')}};`;
416
+ /**
417
+ * Mark the proxied page as authenticated and make Settings wait for our client
418
+ * trust adapter. The rest of the stock Harness graph remains byte-for-byte the
419
+ * same JSON data.
420
+ */
421
+ function rewriteAuthenticatedIndex(html) {
422
+ const assignment = /(?:window\.__DSH_BOOT__|globalThis\["__DSH_BOOT__"\])\s*=\s*/u.exec(html);
423
+ if (assignment?.index === void 0) return html;
424
+ const valueStart = assignment.index + assignment[0].length;
425
+ const scriptEnd = html.indexOf("<\/script>", valueStart);
426
+ if (scriptEnd < 0) throw new Error("DSH boot manifest script is incomplete");
427
+ const source = html.slice(valueStart, scriptEnd).trim().replace(/;$/u, "");
428
+ const manifest = JSON.parse(source);
429
+ if (!Array.isArray(manifest.entries)) throw new Error("DSH boot manifest has no entries");
430
+ const entries = manifest.entries;
431
+ if (!entries.some((entry) => entry.id === CLIENT_ID)) throw new Error("dsh-local-link client is absent from DSH boot manifest");
432
+ const settings = entries.filter((entry) => entry.id === SETTINGS_ID);
433
+ if (settings.length !== 1 || !Array.isArray(settings[0]?.inject)) throw new Error("DSH settings boot entry is incompatible");
434
+ if (!settings[0].inject.includes(CLIENT_ID)) settings[0].inject = [...settings[0].inject, CLIENT_ID];
435
+ const prefix = `${RANDOM_UUID_POLYFILL}window.__DSH_LOCAL_LINK_AUTHENTICATED__=true;`;
436
+ return `${html.slice(0, assignment.index)}${prefix}${assignment[0]}${JSON.stringify(manifest)};${html.slice(scriptEnd)}`;
437
+ }
438
+ //#endregion
439
+ //#region src/gateway/pair-page.ts
440
+ const PAIR_PATH = "/__dsh-local-link/pair";
441
+ const PAIR_PAGE = `<!doctype html>
442
+ <html lang="en">
443
+ <meta charset="utf-8">
444
+ <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
445
+ <meta name="color-scheme" content="light dark">
446
+ <title>Connecting to DeepSeek Harness</title>
447
+ <style>
448
+ :root{font-family:system-ui,sans-serif;color-scheme:light dark}body{margin:0;min-height:100dvh;display:grid;place-items:center;background:#101216;color:#f5f7fa}main{box-sizing:border-box;width:min(380px,calc(100% - 32px));padding:28px;text-align:center;border:1px solid #343942;border-radius:20px;background:#191c22;box-shadow:0 20px 60px #0008}h1{margin:0 0 8px;font-size:24px}p{margin:0;color:#b8c0cc;line-height:1.5}.spinner{width:32px;height:32px;margin:0 auto 20px;border:3px solid #3a414d;border-top-color:#2878ff;border-radius:50%;animation:spin .8s linear infinite}output{display:block;min-height:22px;margin-top:16px;color:#ffb4ab}@keyframes spin{to{transform:rotate(360deg)}}
449
+ </style>
450
+ <main>
451
+ <div class="spinner" aria-hidden="true"></div>
452
+ <h1>DeepSeek Harness</h1>
453
+ <p>Connecting this device…</p>
454
+ <output id="status"></output>
455
+ </main>
456
+ <script>
457
+ const status=document.getElementById('status');
458
+ const stop=(message)=>{document.querySelector('.spinner')?.remove();status.textContent=message;};
459
+ void (async()=>{try{
460
+ const params=new URLSearchParams(location.hash.slice(1));const token=params.get('token');const sessionId=params.get('session');
461
+ if(!token)throw new Error('This connection link is incomplete.');
462
+ try{history.replaceState(null,'',location.pathname);}catch{}
463
+ const ua=navigator.userAgent;const mobile=navigator.userAgentData?.mobile===true;
464
+ const type=/iPad|Tablet/i.test(ua)||(/Android/i.test(ua)&&!/Mobile/i.test(ua))?'Tablet':mobile||/iPhone|iPod|Android|Mobile/i.test(ua)?'Phone':'Computer';
465
+ const browser=/EdgA?|EdgiOS|Edg/i.test(ua)?'Edge':/CriOS|Chrome/i.test(ua)?'Chrome':/FxiOS|Firefox/i.test(ua)?'Firefox':/Safari/i.test(ua)?'Safari':'Browser';
466
+ await new Promise((resolve,reject)=>{
467
+ const request=new XMLHttpRequest();request.open('POST',location.pathname);request.timeout=12000;request.setRequestHeader('content-type','application/json');
468
+ request.onload=()=>request.status===204?resolve():reject(new Error(request.status===410?'This QR code expired or was already used.':'Could not connect this device.'));
469
+ request.onerror=()=>reject(new Error('Could not reach this computer. Check the local network and try again.'));
470
+ request.ontimeout=()=>reject(new Error('Connection timed out. Generate a new code and try again.'));
471
+ request.send(JSON.stringify({token,device:{type,browser}}));
472
+ });
473
+ if(sessionId)try{localStorage.setItem('dsh.sessions.current',JSON.stringify({sessionId}));}catch{}
474
+ location.replace('/');
475
+ }catch(error){stop(error instanceof Error?error.message:'Could not connect this device.');}})();
476
+ <\/script>
477
+ </html>`;
478
+ //#endregion
479
+ //#region src/gateway/local-gateway.ts
480
+ const COOKIE_NAME = "dsh_local_link_device";
481
+ const MAX_PAIR_BODY = 4096;
482
+ const EVENT_PATHS = /* @__PURE__ */ new Set(["/api/events.mux", "/api/events.host"]);
483
+ const HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
484
+ "connection",
485
+ "keep-alive",
486
+ "proxy-authenticate",
487
+ "proxy-authorization",
488
+ "proxy-connection",
489
+ "te",
490
+ "trailer",
491
+ "transfer-encoding",
492
+ "upgrade"
493
+ ]);
494
+ function cookieValue(request, name) {
495
+ for (const part of (request.headers.cookie ?? "").split(";")) {
496
+ const [key, ...value] = part.trim().split("=");
497
+ if (key === name) return decodeURIComponent(value.join("="));
498
+ }
499
+ }
500
+ async function readJson(request) {
501
+ const chunks = [];
502
+ let size = 0;
503
+ for await (const chunk of request) {
504
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
505
+ size += buffer.length;
506
+ if (size > MAX_PAIR_BODY) throw new Error("body_too_large");
507
+ chunks.push(buffer);
508
+ }
509
+ const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
510
+ if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("bad_json");
511
+ return value;
512
+ }
513
+ function send(response, status, body, type = "text/plain; charset=utf-8") {
514
+ response.writeHead(status, {
515
+ "content-type": type,
516
+ "content-length": Buffer.byteLength(body),
517
+ "cache-control": "no-store",
518
+ "x-content-type-options": "nosniff",
519
+ "referrer-policy": "no-referrer"
520
+ });
521
+ response.end(body);
522
+ }
523
+ function proxyRequestHeaders(request, upstream, websocket = false) {
524
+ const headers = {};
525
+ for (const [name, value] of Object.entries(request.headers)) {
526
+ const lower = name.toLowerCase();
527
+ if (value === void 0 || lower === "host" || lower === "cookie" || lower.startsWith("x-forwarded-") || !websocket && HOP_BY_HOP_HEADERS.has(lower)) continue;
528
+ headers[lower] = value;
529
+ }
530
+ headers.host = upstream.host;
531
+ headers.origin = upstream.origin;
532
+ headers["sec-fetch-site"] = "same-origin";
533
+ if (request.headers.referer !== void 0) headers.referer = `${upstream.origin}/`;
534
+ return headers;
535
+ }
536
+ function proxyResponseHeaders(headers) {
537
+ const result = {};
538
+ for (const [name, value] of Object.entries(headers)) {
539
+ const lower = name.toLowerCase();
540
+ if (value === void 0 || HOP_BY_HOP_HEADERS.has(lower) || lower === "set-cookie") continue;
541
+ result[lower] = value;
542
+ }
543
+ return result;
544
+ }
545
+ function serializeHeaders(headers) {
546
+ const lines = [];
547
+ for (const [name, value] of Object.entries(headers)) {
548
+ if (value === void 0) continue;
549
+ if (Array.isArray(value)) for (const entry of value) lines.push(`${name}: ${entry}`);
550
+ else lines.push(`${name}: ${String(value)}`);
551
+ }
552
+ return lines;
553
+ }
554
+ function requestKind(pathname) {
555
+ if (pathname === "/") return "root";
556
+ if (EVENT_PATHS.has(pathname)) return "events";
557
+ if (pathname.startsWith("/api/")) return "api";
558
+ if (/\.[a-z0-9]{1,8}$/iu.test(pathname)) return "asset";
559
+ return "page";
560
+ }
561
+ var LocalGateway = class {
562
+ config;
563
+ devices;
564
+ pairing;
565
+ diagnostics;
566
+ upgradedSockets = /* @__PURE__ */ new Set();
567
+ server;
568
+ addresses = [];
569
+ constructor(config) {
570
+ this.config = config;
571
+ this.devices = new DeviceStore(config.stateFile, config.deviceTtlMs);
572
+ this.pairing = new PairingTokens(config.pairingTtlMs);
573
+ this.diagnostics = new DiagnosticStore(config.diagnosticsFile, config.diagnosticsMaxEntries, config.diagnosticsEnabled);
574
+ }
575
+ async start() {
576
+ if (this.server !== void 0) return;
577
+ await Promise.all([this.devices.load(), this.diagnostics.load()]);
578
+ this.addresses = this.config.listenHost === "0.0.0.0" ? privateInterfaceAddresses() : [this.config.listenHost];
579
+ if (this.addresses.length === 0) throw new Error("no private IPv4 interface is available");
580
+ const server = createServer((request, response) => {
581
+ this.handle(request, response);
582
+ });
583
+ server.on("upgrade", (request, socket, head) => {
584
+ this.proxyWebSocket(request, socket, head);
585
+ });
586
+ await new Promise((resolve, reject) => {
587
+ server.once("error", reject);
588
+ server.listen(this.config.listenPort, this.config.listenHost, () => {
589
+ server.off("error", reject);
590
+ resolve();
591
+ });
592
+ });
593
+ this.server = server;
594
+ }
595
+ pairedDevices() {
596
+ return this.devices.list();
597
+ }
598
+ issuePairing(sessionId) {
599
+ const address = this.addresses[0];
600
+ if (address === void 0) throw new Error("gateway is not running");
601
+ const issued = this.pairing.issue();
602
+ return {
603
+ id: issued.id,
604
+ url: `http://${address}:${this.config.listenPort}${PAIR_PATH}#token=${encodeURIComponent(issued.token)}${sessionId === void 0 ? "" : `&session=${encodeURIComponent(sessionId)}`}`,
605
+ expiresAt: issued.expiresAt
606
+ };
607
+ }
608
+ pairingStatus(id) {
609
+ return this.pairing.getStatus(id);
610
+ }
611
+ diagnosticEvents() {
612
+ return this.diagnostics.list();
613
+ }
614
+ clearDiagnostics() {
615
+ return this.diagnostics.clear();
616
+ }
617
+ recordActionError(code) {
618
+ this.diagnostics.record("error", code);
619
+ }
620
+ async revoke(id) {
621
+ return this.devices.revoke(id);
622
+ }
623
+ async renameDevice(id, name) {
624
+ return this.devices.renameDevice(id, name);
625
+ }
626
+ async close() {
627
+ const server = this.server;
628
+ this.server = void 0;
629
+ if (server === void 0) return;
630
+ for (const socket of this.upgradedSockets) socket.destroy();
631
+ this.upgradedSockets.clear();
632
+ await new Promise((resolve, reject) => server.close((error) => error === void 0 ? resolve() : reject(error)));
633
+ }
634
+ requestTrusted(request) {
635
+ return isPrivateAddress(request.socket.remoteAddress) && allowedGatewayHost(request.headers.host, this.config.listenHost, this.config.listenPort, this.addresses);
636
+ }
637
+ authorized(request) {
638
+ return this.config.accessMode === "trusted-lan" || this.devices.authorize(cookieValue(request, COOKIE_NAME)) !== void 0;
639
+ }
640
+ async handle(request, response) {
641
+ if (!this.requestTrusted(request)) {
642
+ this.diagnostics.record("warn", "REQUEST_REJECTED", { reason: "untrusted_source" });
643
+ send(response, 403, "Local-network request rejected");
644
+ return;
645
+ }
646
+ const url = new URL(request.url ?? "/", `http://${request.headers.host}`);
647
+ if (url.pathname.startsWith("/__dsh-local-link/admin")) {
648
+ send(response, 404, "Not found");
649
+ return;
650
+ }
651
+ if (url.pathname === "/__dsh-local-link/pair" && request.method === "GET") {
652
+ send(response, 200, PAIR_PAGE, "text/html; charset=utf-8");
653
+ return;
654
+ }
655
+ if (url.pathname === "/__dsh-local-link/pair" && request.method === "POST") {
656
+ try {
657
+ const body = await readJson(request);
658
+ if (!this.pairing.consume(body.token)) {
659
+ this.diagnostics.record("warn", "PAIRING_REJECTED", { reason: "expired_or_used" });
660
+ send(response, 410, "Pairing token expired or already used");
661
+ return;
662
+ }
663
+ const credential = cookieValue(request, COOKIE_NAME);
664
+ if (this.devices.authorize(credential) === void 0) {
665
+ const created = await this.devices.add(body.device);
666
+ response.setHeader("set-cookie", `${COOKIE_NAME}=${encodeURIComponent(created.token)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${Math.floor(this.config.deviceTtlMs / 1e3)}`);
667
+ }
668
+ send(response, 204, "");
669
+ } catch {
670
+ this.diagnostics.record("warn", "PAIRING_INVALID", { reason: "invalid_request" });
671
+ send(response, 400, "Invalid pairing request");
672
+ }
673
+ return;
674
+ }
675
+ if (!this.authorized(request)) {
676
+ const kind = requestKind(url.pathname);
677
+ if (kind === "root" || kind === "page") this.diagnostics.record("warn", "AUTH_REQUIRED", {
678
+ method: request.method ?? "UNKNOWN",
679
+ requestKind: kind
680
+ });
681
+ send(response, 401, "This browser is not paired. Open Local access in the computer sidebar and scan its QR code.");
682
+ return;
683
+ }
684
+ this.proxyHttp(request, response, request.method === "GET" && url.pathname === "/");
685
+ }
686
+ proxyHttp(request$1, response, interceptIndex) {
687
+ const headers = proxyRequestHeaders(request$1, this.config.upstreamOrigin);
688
+ if (interceptIndex) headers["accept-encoding"] = "identity";
689
+ const upstreamRequest = request({
690
+ hostname: this.config.upstreamOrigin.hostname,
691
+ port: Number(this.config.upstreamOrigin.port),
692
+ method: request$1.method,
693
+ path: request$1.url,
694
+ headers,
695
+ agent: false
696
+ }, (upstreamResponse) => {
697
+ if (!interceptIndex || !String(upstreamResponse.headers["content-type"] ?? "").includes("text/html")) {
698
+ response.writeHead(upstreamResponse.statusCode ?? 502, proxyResponseHeaders(upstreamResponse.headers));
699
+ upstreamResponse.pipe(response);
700
+ return;
701
+ }
702
+ const chunks = [];
703
+ upstreamResponse.on("data", (chunk) => chunks.push(Buffer.from(chunk)));
704
+ upstreamResponse.on("end", () => {
705
+ try {
706
+ const body = rewriteAuthenticatedIndex(Buffer.concat(chunks).toString("utf8"));
707
+ const outgoing = proxyResponseHeaders(upstreamResponse.headers);
708
+ delete outgoing["content-length"];
709
+ delete outgoing["content-encoding"];
710
+ outgoing["content-length"] = Buffer.byteLength(body);
711
+ outgoing["cache-control"] = "no-store";
712
+ response.writeHead(upstreamResponse.statusCode ?? 502, outgoing);
713
+ response.end(body);
714
+ } catch (error) {
715
+ this.diagnostics.record("error", "INDEX_REWRITE_ERROR", { reason: "rewrite_failed" });
716
+ if (!response.headersSent) send(response, 502, error instanceof Error ? error.message : "index rewrite failed");
717
+ else response.destroy();
718
+ }
719
+ });
720
+ });
721
+ upstreamRequest.once("error", () => {
722
+ this.diagnostics.record("error", "HTTP_UPSTREAM_ERROR", { requestKind: requestKind(new URL(request$1.url ?? "/", this.config.upstreamOrigin).pathname) });
723
+ if (!response.headersSent) send(response, 502, "DeepSeek Harness is unavailable");
724
+ else response.destroy();
725
+ });
726
+ request$1.pipe(upstreamRequest);
727
+ }
728
+ async proxyWebSocket(request, client, head) {
729
+ const trusted = this.requestTrusted(request);
730
+ const authorized = trusted && this.authorized(request);
731
+ if (!trusted || !authorized) {
732
+ this.diagnostics.record("warn", "WS_REJECTED", { reason: trusted ? "unauthorized" : "untrusted_source" });
733
+ client.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
734
+ return;
735
+ }
736
+ const target = new URL(request.url ?? "/", this.config.upstreamOrigin);
737
+ if (target.search !== "" || !EVENT_PATHS.has(target.pathname)) {
738
+ this.diagnostics.record("warn", "WS_REJECTED", { reason: "unsupported_path" });
739
+ client.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n");
740
+ return;
741
+ }
742
+ const upstream = connect(Number(this.config.upstreamOrigin.port), this.config.upstreamOrigin.hostname);
743
+ this.upgradedSockets.add(client);
744
+ this.upgradedSockets.add(upstream);
745
+ const cleanup = () => {
746
+ this.upgradedSockets.delete(client);
747
+ this.upgradedSockets.delete(upstream);
748
+ };
749
+ client.once("close", cleanup);
750
+ upstream.once("close", cleanup);
751
+ client.once("error", () => upstream.destroy());
752
+ upstream.once("error", () => {
753
+ this.diagnostics.record("error", "WS_UPSTREAM_ERROR", { reason: "connect_failed" });
754
+ if (!client.destroyed) client.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n");
755
+ });
756
+ upstream.once("connect", () => {
757
+ const headers = proxyRequestHeaders(request, this.config.upstreamOrigin, true);
758
+ upstream.write([
759
+ `${request.method ?? "GET"} ${request.url ?? "/"} HTTP/1.1`,
760
+ ...serializeHeaders(headers),
761
+ "",
762
+ ""
763
+ ].join("\r\n"));
764
+ if (head.length > 0) upstream.write(head);
765
+ upstream.pipe(client);
766
+ client.pipe(upstream);
767
+ client.resume();
768
+ });
769
+ }
770
+ };
771
+ //#endregion
772
+ //#region src/plugin.ts
773
+ const name = "dsh-local-link";
774
+ const inject = ["webServer"];
775
+ const ADMIN_PREFIX = "/__dsh-local-link/admin";
776
+ const CLIENT_DIAGNOSTIC_CODES = /* @__PURE__ */ new Set([
777
+ "CLIPBOARD_COPY_FAILED",
778
+ "DEVICE_REVOKE_FAILED",
779
+ "DEVICE_RENAME_FAILED"
780
+ ]);
781
+ function sendJson(response, status, value) {
782
+ const body = JSON.stringify(value);
783
+ response.writeHead(status, {
784
+ "content-type": "application/json; charset=utf-8",
785
+ "content-length": Buffer.byteLength(body),
786
+ "cache-control": "no-store",
787
+ "x-content-type-options": "nosniff"
788
+ });
789
+ response.end(body);
790
+ }
791
+ function localAdminRequest(request) {
792
+ const remote = request.socket.remoteAddress?.replace(/^::ffff:/u, "");
793
+ const host = request.headers.host?.toLowerCase();
794
+ return (remote === "127.0.0.1" || remote === "::1") && (host?.startsWith("127.") === true || host?.startsWith("localhost:") === true || host?.startsWith("[::1]:") === true) && (request.headers.origin === void 0 || request.headers.origin.startsWith("http://127.") || request.headers.origin.startsWith("http://localhost:"));
795
+ }
796
+ async function readBody(request) {
797
+ const chunks = [];
798
+ let size = 0;
799
+ for await (const chunk of request) {
800
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
801
+ size += buffer.length;
802
+ if (size > 4096) throw new Error("body_too_large");
803
+ chunks.push(buffer);
804
+ }
805
+ const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
806
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("bad_json");
807
+ return parsed;
808
+ }
809
+ async function apply(ctx, config) {
810
+ const gateway = new LocalGateway(parseConfig(config));
811
+ await gateway.start();
812
+ const adminRoute = {
813
+ kind: "prefix",
814
+ path: ADMIN_PREFIX,
815
+ handler: async (request, response) => {
816
+ if (!localAdminRequest(request)) {
817
+ sendJson(response, 403, { error: "loopback_required" });
818
+ return;
819
+ }
820
+ const url = new URL(request.url ?? "/", `http://${request.headers.host}`);
821
+ try {
822
+ if (request.method === "GET" && url.pathname === `${ADMIN_PREFIX}/devices`) {
823
+ sendJson(response, 200, { devices: gateway.pairedDevices() });
824
+ return;
825
+ }
826
+ if (request.method === "GET" && url.pathname === `${ADMIN_PREFIX}/diagnostics`) {
827
+ sendJson(response, 200, {
828
+ version: 1,
829
+ events: gateway.diagnosticEvents(),
830
+ privacy: "No tokens, cookies, IP addresses, device IDs, session IDs, device names, or request paths."
831
+ });
832
+ return;
833
+ }
834
+ if (request.method === "POST" && url.pathname === `${ADMIN_PREFIX}/diagnostics/clear`) {
835
+ await gateway.clearDiagnostics();
836
+ sendJson(response, 200, { cleared: true });
837
+ return;
838
+ }
839
+ if (request.method === "POST" && url.pathname === `${ADMIN_PREFIX}/diagnostics/event`) {
840
+ const body = await readBody(request);
841
+ if (typeof body.code !== "string" || !CLIENT_DIAGNOSTIC_CODES.has(body.code)) throw new Error("bad_diagnostic_code");
842
+ gateway.recordActionError(body.code);
843
+ sendJson(response, 202, { recorded: true });
844
+ return;
845
+ }
846
+ if (request.method === "POST" && url.pathname === `${ADMIN_PREFIX}/pairing`) {
847
+ const body = await readBody(request);
848
+ if (body.sessionId !== void 0 && (typeof body.sessionId !== "string" || body.sessionId.length > 256)) throw new Error("bad_session_id");
849
+ const pairing = gateway.issuePairing(body.sessionId);
850
+ const qrDataUrl = await QRCode.toDataURL(pairing.url, {
851
+ margin: 1,
852
+ width: 280,
853
+ errorCorrectionLevel: "M"
854
+ });
855
+ sendJson(response, 201, {
856
+ ...pairing,
857
+ qrDataUrl
858
+ });
859
+ return;
860
+ }
861
+ if (request.method === "GET" && url.pathname === `${ADMIN_PREFIX}/pairing/status`) {
862
+ sendJson(response, 200, { status: gateway.pairingStatus(url.searchParams.get("id")) });
863
+ return;
864
+ }
865
+ if (request.method === "POST" && url.pathname === `${ADMIN_PREFIX}/revoke`) {
866
+ const body = await readBody(request);
867
+ if (typeof body.id !== "string") throw new Error("bad_device_id");
868
+ sendJson(response, 200, { revoked: await gateway.revoke(body.id) });
869
+ return;
870
+ }
871
+ if (request.method === "POST" && url.pathname === `${ADMIN_PREFIX}/rename`) {
872
+ const body = await readBody(request);
873
+ if (typeof body.id !== "string") throw new Error("bad_device_id");
874
+ const device = await gateway.renameDevice(body.id, body.name);
875
+ if (device === void 0) {
876
+ sendJson(response, 404, { error: "device_not_found" });
877
+ return;
878
+ }
879
+ sendJson(response, 200, { device });
880
+ return;
881
+ }
882
+ sendJson(response, 404, { error: "not_found" });
883
+ } catch (error) {
884
+ if (url.pathname === `${ADMIN_PREFIX}/pairing`) gateway.recordActionError("PAIRING_GENERATION_FAILED");
885
+ else if (url.pathname === `${ADMIN_PREFIX}/revoke`) gateway.recordActionError("DEVICE_REVOKE_FAILED");
886
+ else if (url.pathname === `${ADMIN_PREFIX}/rename`) gateway.recordActionError("DEVICE_RENAME_FAILED");
887
+ sendJson(response, 400, { error: error instanceof Error ? error.message : "bad_request" });
888
+ }
889
+ }
890
+ };
891
+ await ctx.effect(async () => {
892
+ const unregister = ctx.webServer.register(adminRoute);
893
+ return async () => {
894
+ unregister();
895
+ await gateway.close();
896
+ };
897
+ }, "dsh-local-link: local authenticated mobile gateway");
898
+ }
899
+ //#endregion
900
+ export { Config, DeviceStore, LocalGateway, PairingTokens, allowedGatewayHost, apply, inject, isPrivateAddress, name, parseConfig, privateInterfaceAddresses, rewriteAuthenticatedIndex };
901
+
902
+ //# sourceMappingURL=index.mjs.map