dsh-local-link 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.d.mts CHANGED
@@ -14,124 +14,20 @@ interface PluginConfig {
14
14
  diagnosticsFile?: string;
15
15
  stateFile: string;
16
16
  }
17
- interface ResolvedConfig {
18
- readonly listenHost: string;
19
- readonly listenPort: number;
20
- readonly upstreamOrigin: URL;
21
- readonly accessMode: AccessMode;
22
- readonly pairingTtlMs: number;
23
- readonly deviceTtlMs: number;
24
- readonly diagnosticsEnabled: boolean;
25
- readonly diagnosticsMaxEntries: number;
26
- readonly diagnosticsFile: string;
27
- readonly stateFile: string;
28
- }
29
17
  declare const Config: z<PluginConfig>;
30
- declare function parseConfig(value: PluginConfig): ResolvedConfig;
31
18
  //#endregion
32
19
  //#region src/plugin.d.ts
20
+ interface LocalLinkGatewayService {
21
+ readonly trustedHosts: readonly string[];
22
+ }
23
+ declare module '@deepseek-ai/cordis' {
24
+ interface Context {
25
+ localLinkGateway: LocalLinkGatewayService;
26
+ }
27
+ }
33
28
  declare const name = "dsh-local-link";
34
29
  declare const inject: string[];
35
30
  declare function apply(ctx: Context, config: PluginConfig): Promise<void>;
36
31
  //#endregion
37
- //#region src/auth/device-store.d.ts
38
- interface DeviceView {
39
- readonly id: string;
40
- readonly name: string;
41
- readonly deviceType: string;
42
- readonly browser: string;
43
- readonly createdAt: string;
44
- readonly lastSeenAt: string;
45
- }
46
- declare class DeviceStore {
47
- private readonly file;
48
- private readonly ttlMs;
49
- private devices;
50
- private loaded;
51
- private writeTail;
52
- constructor(file: string, ttlMs: number);
53
- load(): Promise<void>;
54
- list(): DeviceView[];
55
- add(metadata: unknown): Promise<{
56
- readonly device: DeviceView;
57
- readonly token: string;
58
- }>;
59
- authorize(credential: string | undefined): DeviceView | undefined;
60
- revoke(id: string): Promise<boolean>;
61
- renameDevice(id: string, name: unknown): Promise<DeviceView | undefined>;
62
- private persist;
63
- }
64
- //#endregion
65
- //#region src/auth/pairing.d.ts
66
- type PairingStatus = 'active' | 'consumed' | 'expired' | 'unknown';
67
- declare class PairingTokens {
68
- private readonly ttlMs;
69
- private current;
70
- constructor(ttlMs: number);
71
- issue(now?: number): {
72
- readonly id: string;
73
- readonly token: string;
74
- readonly expiresAt: string;
75
- };
76
- consume(token: unknown, now?: number): boolean;
77
- getStatus(id: unknown, now?: number): PairingStatus;
78
- }
79
- //#endregion
80
- //#region src/gateway/html.d.ts
81
- /**
82
- * Mark the proxied page as authenticated and make Settings wait for our client
83
- * trust adapter. The rest of the stock Harness graph remains byte-for-byte the
84
- * same JSON data.
85
- */
86
- declare function rewriteAuthenticatedIndex(html: string): string;
87
- //#endregion
88
- //#region src/diagnostics.d.ts
89
- type DiagnosticLevel = 'warn' | 'error';
90
- type DiagnosticCode = 'PAIRING_GENERATION_FAILED' | 'PAIRING_REJECTED' | 'PAIRING_INVALID' | 'REQUEST_REJECTED' | 'AUTH_REQUIRED' | 'HTTP_UPSTREAM_ERROR' | 'INDEX_REWRITE_ERROR' | 'WS_REJECTED' | 'WS_UPSTREAM_ERROR' | 'CLIPBOARD_COPY_FAILED' | 'DEVICE_REVOKE_FAILED' | 'DEVICE_RENAME_FAILED' | 'DIAGNOSTICS_STATE_RESET';
91
- type DiagnosticValue = string | number | boolean;
92
- interface DiagnosticEvent {
93
- readonly id: string;
94
- readonly at: string;
95
- readonly level: DiagnosticLevel;
96
- readonly code: DiagnosticCode;
97
- readonly context?: Readonly<Record<string, DiagnosticValue>>;
98
- }
99
- //#endregion
100
- //#region src/gateway/local-gateway.d.ts
101
- declare class LocalGateway {
102
- readonly config: ResolvedConfig;
103
- private readonly devices;
104
- private readonly pairing;
105
- private readonly diagnostics;
106
- private readonly upgradedSockets;
107
- private server;
108
- private addresses;
109
- constructor(config: ResolvedConfig);
110
- start(): Promise<void>;
111
- pairedDevices(): readonly DeviceView[];
112
- issuePairing(sessionId?: string): {
113
- readonly id: string;
114
- readonly url: string;
115
- readonly expiresAt: string;
116
- };
117
- pairingStatus(id: unknown): PairingStatus;
118
- diagnosticEvents(): readonly DiagnosticEvent[];
119
- clearDiagnostics(): Promise<void>;
120
- recordActionError(code: Extract<DiagnosticCode, 'PAIRING_GENERATION_FAILED' | 'CLIPBOARD_COPY_FAILED' | 'DEVICE_REVOKE_FAILED' | 'DEVICE_RENAME_FAILED'>): void;
121
- revoke(id: string): Promise<boolean>;
122
- renameDevice(id: string, name: unknown): Promise<DeviceView | undefined>;
123
- close(): Promise<void>;
124
- private requestTrusted;
125
- private authorized;
126
- private handle;
127
- private proxyHttp;
128
- private proxyWebSocket;
129
- }
130
- //#endregion
131
- //#region src/network.d.ts
132
- declare function isPrivateAddress(input: string | undefined): boolean;
133
- declare function privateInterfaceAddresses(): string[];
134
- declare function allowedGatewayHost(value: string | undefined, listenHost: string, listenPort: number, addresses: readonly string[]): boolean;
135
- //#endregion
136
- export { type AccessMode, Config, DeviceStore, type DeviceView, LocalGateway, PairingTokens, type PluginConfig, type ResolvedConfig, allowedGatewayHost, apply, inject, isPrivateAddress, name, parseConfig, privateInterfaceAddresses, rewriteAuthenticatedIndex };
32
+ export { type AccessMode, Config, type PluginConfig, apply, inject, name };
137
33
  //# sourceMappingURL=index.d.mts.map
package/lib/index.mjs CHANGED
@@ -2,10 +2,65 @@ import QRCode from "qrcode";
2
2
  import { dirname, isAbsolute, join, resolve } from "node:path";
3
3
  import { connect, isIP } from "node:net";
4
4
  import z from "@deepseek-ai/schemastery";
5
+ import { networkInterfaces } from "node:os";
5
6
  import { createServer, request } from "node:http";
6
7
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
7
8
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
- import { networkInterfaces } from "node:os";
9
+ //#region src/network.ts
10
+ function normalizeAddress(address) {
11
+ const zone = address.indexOf("%");
12
+ return zone < 0 ? address : address.slice(0, zone);
13
+ }
14
+ function isPrivateAddress(input) {
15
+ if (input === void 0) return false;
16
+ const address = normalizeAddress(input.replace(/^::ffff:/u, ""));
17
+ if (address === "::1" || address === "127.0.0.1") return true;
18
+ if (isIP(address) === 4) {
19
+ const octets = address.split(".").map(Number);
20
+ const first = octets[0] ?? -1;
21
+ const second = octets[1] ?? -1;
22
+ return first === 10 || first === 127 || first === 169 && second === 254 || first === 172 && second >= 16 && second <= 31 || first === 192 && second === 168;
23
+ }
24
+ if (isIP(address) === 6) {
25
+ const lower = address.toLowerCase();
26
+ return lower.startsWith("fc") || lower.startsWith("fd") || lower.startsWith("fe8") || lower.startsWith("fe9") || lower.startsWith("fea") || lower.startsWith("feb");
27
+ }
28
+ return false;
29
+ }
30
+ function privateInterfaceAddresses() {
31
+ const result = /* @__PURE__ */ new Map();
32
+ for (const [name, entries] of Object.entries(networkInterfaces())) for (const entry of entries ?? []) {
33
+ if (entry.internal || entry.family !== "IPv4" || !isPrivateAddress(entry.address)) continue;
34
+ const normalizedName = name.toLowerCase();
35
+ let score = 0;
36
+ if (/wi-?fi|wlan|wireless|ethernet|local area|локальн/u.test(normalizedName)) score += 100;
37
+ if (/tailscale|docker|vethernet|wsl|hyper-v|virtual|vpn|wireguard|amnezia|zerotier/u.test(normalizedName)) score -= 200;
38
+ if (entry.address.startsWith("192.168.")) score += 30;
39
+ else if (entry.address.startsWith("10.")) score += 20;
40
+ else if (entry.address.startsWith("172.")) score += 10;
41
+ result.set(entry.address, Math.max(result.get(entry.address) ?? Number.NEGATIVE_INFINITY, score));
42
+ }
43
+ return [...result].sort(([addressA, scoreA], [addressB, scoreB]) => scoreB - scoreA || addressA.localeCompare(addressB)).map(([address]) => address);
44
+ }
45
+ function parseHostHeader(value) {
46
+ if (value === void 0 || value.length > 255) return void 0;
47
+ try {
48
+ const url = new URL(`http://${value}`);
49
+ if (url.username !== "" || url.password !== "" || url.pathname !== "/" || url.search !== "" || url.hash !== "") return void 0;
50
+ return {
51
+ hostname: normalizeAddress(url.hostname.replace(/^\[|\]$/gu, "")),
52
+ port: Number(url.port || "80")
53
+ };
54
+ } catch {
55
+ return;
56
+ }
57
+ }
58
+ function allowedGatewayHost(value, listenHost, listenPort, addresses) {
59
+ const parsed = parseHostHeader(value);
60
+ if (parsed === void 0 || parsed.port !== listenPort) return false;
61
+ return (listenHost === "0.0.0.0" ? addresses : [listenHost]).includes(parsed.hostname);
62
+ }
63
+ //#endregion
9
64
  //#region src/config.ts
10
65
  const Config = z.object({
11
66
  listenHost: z.string().default("0.0.0.0"),
@@ -27,6 +82,7 @@ function boundedInteger(value, name, fallback, minimum, maximum) {
27
82
  function parseConfig(value) {
28
83
  const listenHost = value.listenHost ?? "0.0.0.0";
29
84
  if (isIP(listenHost) === 0) throw new Error("listenHost must be an IP literal");
85
+ if (listenHost !== "0.0.0.0" && !isPrivateAddress(listenHost)) throw new Error("listenHost must be 0.0.0.0 or a private/loopback IP literal");
30
86
  const upstreamOrigin = new URL(value.upstreamOrigin ?? "http://127.0.0.1:3080");
31
87
  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
88
  if (!isAbsolute(value.stateFile)) throw new Error("stateFile must be an absolute path");
@@ -48,6 +104,41 @@ function parseConfig(value) {
48
104
  });
49
105
  }
50
106
  //#endregion
107
+ //#region src/gateway/admin-auth.ts
108
+ function loopbackHostname(value) {
109
+ const hostname = value.toLowerCase().replace(/^\[|\]$/gu, "");
110
+ if (hostname === "localhost" || hostname === "::1") return true;
111
+ if (isIP(hostname) !== 4) return false;
112
+ return Number(hostname.split(".")[0]) === 127;
113
+ }
114
+ function loopbackAuthority(value) {
115
+ if (value === void 0 || value.length > 255) return false;
116
+ try {
117
+ const url = new URL(`http://${value}`);
118
+ return url.username === "" && url.password === "" && url.pathname === "/" && url.search === "" && url.hash === "" && loopbackHostname(url.hostname);
119
+ } catch {
120
+ return false;
121
+ }
122
+ }
123
+ function loopbackOrigin(value) {
124
+ if (value === void 0) return true;
125
+ try {
126
+ const url = new URL(value);
127
+ return url.protocol === "http:" && url.username === "" && url.password === "" && url.pathname === "/" && url.search === "" && url.hash === "" && loopbackHostname(url.hostname);
128
+ } catch {
129
+ return false;
130
+ }
131
+ }
132
+ /**
133
+ * The administration API belongs to the loopback Harness page only. Parse
134
+ * authorities structurally so lookalike DNS names such as 127.example cannot
135
+ * pass a string-prefix check.
136
+ */
137
+ function isLoopbackAdminSource(remoteAddress, host, origin) {
138
+ const remote = remoteAddress?.replace(/^::ffff:/u, "");
139
+ return (remote === "127.0.0.1" || remote === "::1") && loopbackAuthority(host) && loopbackOrigin(origin);
140
+ }
141
+ //#endregion
51
142
  //#region src/auth/device-store.ts
52
143
  function hashToken(token) {
53
144
  return createHash("sha256").update(token, "utf8").digest();
@@ -174,7 +265,7 @@ var DeviceStore = class {
174
265
  version: 2,
175
266
  devices: [...this.devices.values()]
176
267
  };
177
- this.writeTail = this.writeTail.then(async () => {
268
+ const write = this.writeTail.catch(() => void 0).then(async () => {
178
269
  await mkdir(dirname(this.file), { recursive: true });
179
270
  const temporary = `${this.file}.${process.pid}.tmp`;
180
271
  await writeFile(temporary, `${JSON.stringify(snapshot, null, 2)}\n`, {
@@ -183,7 +274,8 @@ var DeviceStore = class {
183
274
  });
184
275
  await rename(temporary, this.file);
185
276
  });
186
- return this.writeTail;
277
+ this.writeTail = write.catch(() => void 0);
278
+ return write;
187
279
  }
188
280
  };
189
281
  //#endregion
@@ -305,7 +397,7 @@ var DiagnosticStore = class {
305
397
  return event === void 0 ? [] : [event];
306
398
  });
307
399
  this.events = normalized.slice(-this.maxEntries);
308
- if (this.events.length !== parsed.events.length) await this.persist();
400
+ if (this.events.length !== parsed.events.length) await this.persist().catch(() => void 0);
309
401
  } catch (error) {
310
402
  if (error.code === "ENOENT") return;
311
403
  this.events = [];
@@ -330,7 +422,7 @@ var DiagnosticStore = class {
330
422
  };
331
423
  this.events.push(event);
332
424
  if (this.events.length > this.maxEntries) this.events.splice(0, this.events.length - this.maxEntries);
333
- return this.persist();
425
+ return this.persist().catch(() => void 0);
334
426
  }
335
427
  async clear() {
336
428
  this.events = [];
@@ -341,7 +433,7 @@ var DiagnosticStore = class {
341
433
  version: 1,
342
434
  events: [...this.events]
343
435
  };
344
- this.writeTail = this.writeTail.catch(() => void 0).then(async () => {
436
+ const write = this.writeTail.catch(() => void 0).then(async () => {
345
437
  await mkdir(dirname(this.file), { recursive: true });
346
438
  const temporary = `${this.file}.${process.pid}.tmp`;
347
439
  await writeFile(temporary, `${JSON.stringify(snapshot, null, 2)}\n`, {
@@ -349,74 +441,36 @@ var DiagnosticStore = class {
349
441
  mode: 384
350
442
  });
351
443
  await rename(temporary, this.file);
352
- }).catch(() => void 0);
353
- return this.writeTail;
444
+ });
445
+ this.writeTail = write.catch(() => void 0);
446
+ return write;
354
447
  }
355
448
  };
356
449
  //#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
450
  //#region src/gateway/html.ts
413
451
  const CLIENT_ID = "dsh-local-link";
414
- const SETTINGS_ID = "@deepseek-ai/dsh-client-ui-settings";
452
+ const HOST_DIRECTORY_PICKER_IDS = /* @__PURE__ */ new Set(["@deepseek-ai/dsh-client-ui-directory-picker-native", "@deepseek-ai/dsh-client-ui-directory-picker-browse"]);
415
453
  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('')}};`;
454
+ function ensureResponsiveViewport(html) {
455
+ const match = /<meta\b(?=[^>]*\bname\s*=\s*["']viewport["'])[^>]*>/iu.exec(html);
456
+ if (match === null) {
457
+ const head = /<head\b[^>]*>/iu.exec(html);
458
+ if (head?.index === void 0) return html;
459
+ const offset = head.index + head[0].length;
460
+ return `${html.slice(0, offset)}<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">${html.slice(offset)}`;
461
+ }
462
+ if (/\bviewport-fit\s*=\s*cover\b/iu.test(match[0])) return html;
463
+ const content = /\bcontent\s*=\s*(["'])(.*?)\1/iu;
464
+ const replacement = content.test(match[0]) ? match[0].replace(content, (_whole, quote, value) => `content=${quote}${value},viewport-fit=cover${quote}`) : match[0].replace(/\s*\/?>$/u, " content=\"width=device-width,initial-scale=1,viewport-fit=cover\">");
465
+ return `${html.slice(0, match.index)}${replacement}${html.slice(match.index + match[0].length)}`;
466
+ }
467
+ function removeHostDirectoryPickers(entries) {
468
+ for (let index = entries.length - 1; index >= 0; index -= 1) if (HOST_DIRECTORY_PICKER_IDS.has(String(entries[index]?.id))) entries.splice(index, 1);
469
+ }
416
470
  /**
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.
471
+ * Keep the shipped Harness root and every dynamic child slot. The gateway only
472
+ * removes Host-side directory picker capabilities from remote browsers and
473
+ * adds the secure-context polyfill required by the stock browser transport.
420
474
  */
421
475
  function rewriteAuthenticatedIndex(html) {
422
476
  const assignment = /(?:window\.__DSH_BOOT__|globalThis\["__DSH_BOOT__"\])\s*=\s*/u.exec(html);
@@ -429,50 +483,92 @@ function rewriteAuthenticatedIndex(html) {
429
483
  if (!Array.isArray(manifest.entries)) throw new Error("DSH boot manifest has no entries");
430
484
  const entries = manifest.entries;
431
485
  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)}`;
486
+ removeHostDirectoryPickers(entries);
487
+ return ensureResponsiveViewport(`${html.slice(0, assignment.index)}${RANDOM_UUID_POLYFILL}${assignment[0]}${JSON.stringify(manifest)};${html.slice(scriptEnd)}`);
437
488
  }
438
489
  //#endregion
490
+ //#region src/locales/en.json
491
+ var pair_title$1 = "Connecting to DeepSeek Harness";
492
+ var pair_connecting$1 = "Connecting this device…";
493
+ var pair_incomplete$1 = "This connection link is incomplete.";
494
+ var pair_expired$1 = "This QR code expired or was already used.";
495
+ var pair_failed$1 = "Could not connect this device.";
496
+ var pair_unreachable$1 = "Could not reach this computer. Check the local network and try again.";
497
+ var pair_timeout$1 = "Connection timed out. Generate a new code and try again.";
498
+ //#endregion
499
+ //#region src/locales/zh.json
500
+ var pair_title = "正在连接 DeepSeek Harness";
501
+ var pair_connecting = "正在连接此设备…";
502
+ var pair_incomplete = "此连接链接不完整。";
503
+ var pair_expired = "此二维码已过期或已被使用。";
504
+ var pair_failed = "无法连接此设备。";
505
+ var pair_unreachable = "无法访问此计算机。请检查本地网络后重试。";
506
+ var pair_timeout = "连接超时。请生成新二维码后重试。";
507
+ //#endregion
439
508
  //#region src/gateway/pair-page.ts
440
509
  const PAIR_PATH = "/__dsh-local-link/pair";
510
+ const pairCopies = {
511
+ en: {
512
+ title: pair_title$1,
513
+ connecting: pair_connecting$1,
514
+ incomplete: pair_incomplete$1,
515
+ expired: pair_expired$1,
516
+ failed: pair_failed$1,
517
+ unreachable: pair_unreachable$1,
518
+ timeout: pair_timeout$1
519
+ },
520
+ zh: {
521
+ title: pair_title,
522
+ connecting: pair_connecting,
523
+ incomplete: pair_incomplete,
524
+ expired: pair_expired,
525
+ failed: pair_failed,
526
+ unreachable: pair_unreachable,
527
+ timeout: pair_timeout
528
+ }
529
+ };
530
+ function escapeHtml(value) {
531
+ return value.replace(/&/gu, "&amp;").replace(/</gu, "&lt;").replace(/>/gu, "&gt;").replace(/"/gu, "&quot;").replace(/'/gu, "&#39;");
532
+ }
533
+ const copySource = JSON.stringify(pairCopies).replace(/</gu, "\\u003c");
441
534
  const PAIR_PAGE = `<!doctype html>
442
535
  <html lang="en">
443
536
  <meta charset="utf-8">
444
537
  <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
445
538
  <meta name="color-scheme" content="light dark">
446
- <title>Connecting to DeepSeek Harness</title>
539
+ <title>${escapeHtml(pairCopies.en.title)}</title>
447
540
  <style>
448
541
  :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
542
  </style>
450
543
  <main>
451
544
  <div class="spinner" aria-hidden="true"></div>
452
545
  <h1>DeepSeek Harness</h1>
453
- <p>Connecting this device…</p>
546
+ <p id="message">${escapeHtml(pairCopies.en.connecting)}</p>
454
547
  <output id="status"></output>
455
548
  </main>
456
549
  <script>
550
+ const copies=${copySource};
551
+ const languages=navigator.languages??[navigator.language];const language=languages.some(value=>String(value).toLowerCase().startsWith('zh'))?'zh':'en';const copy=copies[language];
552
+ if(document.documentElement)document.documentElement.lang=language;document.title=copy.title;document.getElementById('message').textContent=copy.connecting;
457
553
  const status=document.getElementById('status');
458
554
  const stop=(message)=>{document.querySelector('.spinner')?.remove();status.textContent=message;};
459
555
  void (async()=>{try{
460
556
  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.');
557
+ if(!token)throw new Error(copy.incomplete);
462
558
  try{history.replaceState(null,'',location.pathname);}catch{}
463
559
  const ua=navigator.userAgent;const mobile=navigator.userAgentData?.mobile===true;
464
560
  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
561
  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
562
  await new Promise((resolve,reject)=>{
467
563
  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.'));
564
+ request.onload=()=>request.status===204?resolve():reject(new Error(request.status===410?copy.expired:copy.failed));
565
+ request.onerror=()=>reject(new Error(copy.unreachable));
566
+ request.ontimeout=()=>reject(new Error(copy.timeout));
471
567
  request.send(JSON.stringify({token,device:{type,browser}}));
472
568
  });
473
569
  if(sessionId)try{localStorage.setItem('dsh.sessions.current',JSON.stringify({sessionId}));}catch{}
474
570
  location.replace('/');
475
- }catch(error){stop(error instanceof Error?error.message:'Could not connect this device.');}})();
571
+ }catch(error){stop(error instanceof Error?error.message:copy.failed);}})();
476
572
  <\/script>
477
573
  </html>`;
478
574
  //#endregion
@@ -491,10 +587,18 @@ const HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
491
587
  "transfer-encoding",
492
588
  "upgrade"
493
589
  ]);
590
+ function formatAuthority(address, port) {
591
+ return `${address.includes(":") ? `[${address}]` : address}:${port}`;
592
+ }
494
593
  function cookieValue(request, name) {
495
594
  for (const part of (request.headers.cookie ?? "").split(";")) {
496
595
  const [key, ...value] = part.trim().split("=");
497
- if (key === name) return decodeURIComponent(value.join("="));
596
+ if (key !== name) continue;
597
+ try {
598
+ return decodeURIComponent(value.join("="));
599
+ } catch {
600
+ return;
601
+ }
498
602
  }
499
603
  }
500
604
  async function readJson(request) {
@@ -520,17 +624,13 @@ function send(response, status, body, type = "text/plain; charset=utf-8") {
520
624
  });
521
625
  response.end(body);
522
626
  }
523
- function proxyRequestHeaders(request, upstream, websocket = false) {
627
+ function proxyRequestHeaders(request, websocket = false) {
524
628
  const headers = {};
525
629
  for (const [name, value] of Object.entries(request.headers)) {
526
630
  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;
631
+ if (value === void 0 || lower === "cookie" || lower.startsWith("x-forwarded-") || !websocket && HOP_BY_HOP_HEADERS.has(lower)) continue;
528
632
  headers[lower] = value;
529
633
  }
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
634
  return headers;
535
635
  }
536
636
  function proxyResponseHeaders(headers) {
@@ -601,13 +701,16 @@ var LocalGateway = class {
601
701
  const issued = this.pairing.issue();
602
702
  return {
603
703
  id: issued.id,
604
- url: `http://${address}:${this.config.listenPort}${PAIR_PATH}#token=${encodeURIComponent(issued.token)}${sessionId === void 0 ? "" : `&session=${encodeURIComponent(sessionId)}`}`,
704
+ url: `http://${formatAuthority(address, this.config.listenPort)}${PAIR_PATH}#token=${encodeURIComponent(issued.token)}${sessionId === void 0 ? "" : `&session=${encodeURIComponent(sessionId)}`}`,
605
705
  expiresAt: issued.expiresAt
606
706
  };
607
707
  }
608
708
  pairingStatus(id) {
609
709
  return this.pairing.getStatus(id);
610
710
  }
711
+ trustedAuthorities() {
712
+ return Object.freeze(this.addresses.map((address) => formatAuthority(address, this.config.listenPort)));
713
+ }
611
714
  diagnosticEvents() {
612
715
  return this.diagnostics.list();
613
716
  }
@@ -681,10 +784,11 @@ var LocalGateway = class {
681
784
  send(response, 401, "This browser is not paired. Open Local access in the computer sidebar and scan its QR code.");
682
785
  return;
683
786
  }
684
- this.proxyHttp(request, response, request.method === "GET" && url.pathname === "/");
787
+ const interceptIndex = request.method === "GET" && url.pathname === "/";
788
+ this.proxyHttp(request, response, interceptIndex);
685
789
  }
686
790
  proxyHttp(request$1, response, interceptIndex) {
687
- const headers = proxyRequestHeaders(request$1, this.config.upstreamOrigin);
791
+ const headers = proxyRequestHeaders(request$1);
688
792
  if (interceptIndex) headers["accept-encoding"] = "identity";
689
793
  const upstreamRequest = request({
690
794
  hostname: this.config.upstreamOrigin.hostname,
@@ -754,7 +858,7 @@ var LocalGateway = class {
754
858
  if (!client.destroyed) client.end("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n");
755
859
  });
756
860
  upstream.once("connect", () => {
757
- const headers = proxyRequestHeaders(request, this.config.upstreamOrigin, true);
861
+ const headers = proxyRequestHeaders(request, true);
758
862
  upstream.write([
759
863
  `${request.method ?? "GET"} ${request.url ?? "/"} HTTP/1.1`,
760
864
  ...serializeHeaders(headers),
@@ -789,9 +893,7 @@ function sendJson(response, status, value) {
789
893
  response.end(body);
790
894
  }
791
895
  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:"));
896
+ return isLoopbackAdminSource(request.socket.remoteAddress, request.headers.host, request.headers.origin);
795
897
  }
796
898
  async function readBody(request) {
797
899
  const chunks = [];
@@ -809,6 +911,7 @@ async function readBody(request) {
809
911
  async function apply(ctx, config) {
810
912
  const gateway = new LocalGateway(parseConfig(config));
811
913
  await gateway.start();
914
+ ctx.provide("localLinkGateway", Object.freeze({ trustedHosts: gateway.trustedAuthorities() }));
812
915
  const adminRoute = {
813
916
  kind: "prefix",
814
917
  path: ADMIN_PREFIX,
@@ -897,6 +1000,6 @@ async function apply(ctx, config) {
897
1000
  }, "dsh-local-link: local authenticated mobile gateway");
898
1001
  }
899
1002
  //#endregion
900
- export { Config, DeviceStore, LocalGateway, PairingTokens, allowedGatewayHost, apply, inject, isPrivateAddress, name, parseConfig, privateInterfaceAddresses, rewriteAuthenticatedIndex };
1003
+ export { Config, apply, inject, name };
901
1004
 
902
1005
  //# sourceMappingURL=index.mjs.map