@tianacloud/dsh-remote 0.2.2 → 0.2.4

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/client.js CHANGED
@@ -407,6 +407,14 @@
407
407
  statusPaused: '已暂停监听',
408
408
  statusUnconfigured: '尚未绑定',
409
409
  statusReconnecting: '正在重连 Relay…',
410
+ statusLoading: '加载中…',
411
+ statusAccessDenied: '访问受限',
412
+ statusError: '加载失败',
413
+ adminErrorTitle: '无法加载主机管理状态',
414
+ adminAccessDeniedTitle: '主机管理接口访问受限',
415
+ adminErrorHint: '请确认当前浏览器通过本机或受信任的局域网/Tailnet 地址访问 DSH(且已配置 --trusted-host 并具备有效的本机所有者会话)。',
416
+ retry: '重试',
417
+ loadingOverview: '正在加载 Tiana Remote 状态…',
410
418
  toggleLabel: '启用远程访问',
411
419
  remoteUrl: '托管访问地址',
412
420
  copy: '复制',
@@ -477,6 +485,14 @@
477
485
  statusPaused: 'Paused',
478
486
  statusUnconfigured: 'Not configured',
479
487
  statusReconnecting: 'Reconnecting…',
488
+ statusLoading: 'Loading…',
489
+ statusAccessDenied: 'Access Denied',
490
+ statusError: 'Error',
491
+ adminErrorTitle: 'Unable to load host management status',
492
+ adminAccessDeniedTitle: 'Host admin API access denied',
493
+ adminErrorHint: 'Verify you are accessing DSH over loopback or a private LAN/Tailnet address configured via --trusted-host with an active owner session.',
494
+ retry: 'Retry',
495
+ loadingOverview: 'Loading Tiana Remote status…',
480
496
  toggleLabel: 'Enable Remote Access',
481
497
  remoteUrl: 'Hosted Remote URL',
482
498
  copy: 'Copy',
@@ -570,7 +586,9 @@
570
586
  background: transparent; color: var(--dsw-alias-label-secondary, #94a3b8);
571
587
  }
572
588
  .dshr-tab[aria-selected="true"] {
573
- background: var(--dsw-alias-brand-primary, #2563eb); border-color: transparent; color: #fff;
589
+ background: var(--dsw-alias-brand-primary, #2563eb);
590
+ border-color: transparent;
591
+ color: var(--dsw-alias-label-primary-foreground, #ffffff);
574
592
  }
575
593
  .dshr-badge {
576
594
  display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; border-radius: 999px;
@@ -581,6 +599,7 @@
581
599
  .dshr-dot { width: 8px; height: 8px; border-radius: 50%; background: #94a3b8; }
582
600
  .dshr-dot.is-online { background: #22c55e; box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.25); }
583
601
  .dshr-dot.is-warn { background: #f59e0b; }
602
+ .dshr-dot.is-error { background: var(--dsw-alias-state-error-primary, #ef4444); box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.25); }
584
603
  .dshr-mono {
585
604
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
586
605
  font-size: 13px; padding: 8px 12px; border-radius: 8px; flex: 1; min-width: 200px;
@@ -605,11 +624,18 @@
605
624
  }
606
625
  .dshr-btn:hover:not(:disabled) { filter: brightness(1.08); }
607
626
  .dshr-btn:disabled { opacity: 0.5; cursor: not-allowed; }
608
- .dshr-btn-primary {
609
- background: var(--dsw-alias-brand-primary, #2563eb); border-color: transparent; color: #fff;
627
+ .dshr-root .dshr-btn-primary,
628
+ .dshr-root a.dshr-btn-primary,
629
+ .dshr-root a.dshr-btn-primary:visited,
630
+ .dshr-root a.dshr-btn-primary:hover {
631
+ background: var(--dsw-alias-brand-primary, #2563eb);
632
+ border-color: transparent;
633
+ color: var(--dsw-alias-label-primary-foreground, #ffffff);
610
634
  }
611
635
  .dshr-btn-danger {
612
- background: rgba(220, 38, 38, 0.16); border-color: rgba(248, 113, 113, 0.45); color: #f87171;
636
+ background: rgba(220, 38, 38, 0.16);
637
+ border-color: rgba(248, 113, 113, 0.45);
638
+ color: var(--dsw-alias-state-error-primary, #f87171);
613
639
  }
614
640
  .dshr-input {
615
641
  box-sizing: border-box; width: 100%; padding: 8px 12px; border-radius: 8px; font-size: 13px;
@@ -632,7 +658,9 @@
632
658
  }
633
659
  .dshr-err {
634
660
  padding: 10px 12px; border-radius: 8px; font-size: 13px; line-height: 1.45;
635
- background: rgba(220, 38, 38, 0.14); border: 1px solid rgba(248, 113, 113, 0.45); color: #f87171;
661
+ background: rgba(220, 38, 38, 0.14);
662
+ border: 1px solid rgba(248, 113, 113, 0.45);
663
+ color: var(--dsw-alias-state-error-primary, #f87171);
636
664
  }
637
665
  .dshr-switch { display: inline-flex; align-items: center; gap: 8px; cursor: pointer; font-size: 13px; font-weight: 500; }
638
666
  dialog.dshr-dialog {
@@ -738,6 +766,8 @@
738
766
  : Boolean(globalThis.__DSH_REMOTE_SHELL__?.isRemote || globalThis.__DSH_TRANSPORT__?.ownsHost);
739
767
 
740
768
  const [overview, setOverview] = useState(null);
769
+ const [adminLoading, setAdminLoading] = useState(() => !isRemote);
770
+ const [adminLoadError, setAdminLoadError] = useState(null);
741
771
  const [publicStatus, setPublicStatus] = useState(null);
742
772
  const [shellSnap, setShellSnap] = useState(() => globalThis.__DSH_REMOTE_SHELL__?.getStatusSnapshot?.() || null);
743
773
  const [revealedKey, setRevealedKey] = useState('');
@@ -790,14 +820,42 @@
790
820
  if (resp.ok) {
791
821
  const data = await resp.json();
792
822
  setOverview(data);
823
+ setAdminLoadError(null);
793
824
  // NEVER overwrite user's in-progress form edits during background polling
794
825
  if (!settingsDirtyRef.current) {
795
826
  hydrateDraftsFromOverview(data);
796
827
  }
828
+ } else {
829
+ let errMessage = '';
830
+ try {
831
+ const errBody = await resp.json();
832
+ if (errBody && typeof errBody.error === 'string') {
833
+ errMessage = errBody.error;
834
+ }
835
+ } catch {
836
+ try {
837
+ errMessage = (await resp.text()).trim();
838
+ } catch {
839
+ // ignore body parse failures
840
+ }
841
+ }
842
+ setAdminLoadError({
843
+ status: resp.status,
844
+ message: errMessage || resp.statusText || `HTTP ${resp.status}`,
845
+ });
797
846
  }
798
847
  }
799
- } catch {
800
- // ignore transient poll errors
848
+ } catch (err) {
849
+ if (!isRemote) {
850
+ setAdminLoadError({
851
+ status: 0,
852
+ message: err instanceof Error ? err.message : String(err || 'Network error'),
853
+ });
854
+ }
855
+ } finally {
856
+ if (!isRemote) {
857
+ setAdminLoading(false);
858
+ }
801
859
  }
802
860
  }, [isRemote, hydrateDraftsFromOverview]);
803
861
 
@@ -1081,13 +1139,43 @@
1081
1139
  );
1082
1140
  };
1083
1141
 
1084
- const statusLabel = !configured
1085
- ? t('statusUnconfigured')
1086
- : !enabled
1087
- ? t('statusPaused')
1088
- : relayConnected
1089
- ? t('statusOnline')
1090
- : t('statusReconnecting');
1142
+ const handleRetryAdminLoad = async () => {
1143
+ setBusy('retry');
1144
+ try {
1145
+ await fetchState();
1146
+ } finally {
1147
+ setBusy('');
1148
+ }
1149
+ };
1150
+
1151
+ const isAdminLoadError = Boolean(adminLoadError) && (
1152
+ !overview ||
1153
+ !overview.configured ||
1154
+ adminLoadError.status === 401 ||
1155
+ adminLoadError.status === 403
1156
+ );
1157
+ const isAdminLoadingInitial = !overview && !adminLoadError && adminLoading;
1158
+ const isAccessDenied = Boolean(adminLoadError && (adminLoadError.status === 401 || adminLoadError.status === 403));
1159
+ const showConfiguredPanel = !isAdminLoadError && configured;
1160
+ const showUnconfiguredPanel = !isAdminLoadError && Boolean(overview) && !configured;
1161
+
1162
+ const statusLabel = isAdminLoadError
1163
+ ? (isAccessDenied ? t('statusAccessDenied') : t('statusError'))
1164
+ : isAdminLoadingInitial
1165
+ ? t('statusLoading')
1166
+ : !configured
1167
+ ? t('statusUnconfigured')
1168
+ : !enabled
1169
+ ? t('statusPaused')
1170
+ : relayConnected
1171
+ ? t('statusOnline')
1172
+ : t('statusReconnecting');
1173
+
1174
+ const statusDotClass = isAdminLoadError
1175
+ ? 'is-error'
1176
+ : isAdminLoadingInitial
1177
+ ? 'is-warn'
1178
+ : (enabled && relayConnected ? 'is-online' : enabled ? 'is-warn' : '');
1091
1179
 
1092
1180
  return h('div', { className: 'dshr-root', 'data-dshr-mode': 'local' },
1093
1181
  h('div', { className: 'dshr-wrap' },
@@ -1098,10 +1186,10 @@
1098
1186
  ),
1099
1187
  h('div', { className: 'dshr-row' },
1100
1188
  h('span', { className: 'dshr-badge', id: 'dshr-local-status-badge' },
1101
- h('span', { className: `dshr-dot ${enabled && relayConnected ? 'is-online' : enabled ? 'is-warn' : ''}` }),
1189
+ h('span', { className: `dshr-dot ${statusDotClass}` }),
1102
1190
  statusLabel,
1103
1191
  ),
1104
- configured && h('label', { className: 'dshr-switch' },
1192
+ showConfiguredPanel && h('label', { className: 'dshr-switch' },
1105
1193
  h('input', {
1106
1194
  type: 'checkbox',
1107
1195
  id: 'dshr-enable-toggle',
@@ -1116,8 +1204,34 @@
1116
1204
 
1117
1205
  toast && h('div', { className: 'dshr-notice', role: 'status' }, toast),
1118
1206
 
1207
+ // Explicit admin load error card (prevents falsely rendering "Not bound yet" on 403/5xx/network failure)
1208
+ isAdminLoadError && h('div', { className: 'dshr-card', id: 'dshr-admin-error-card', role: 'alert' },
1209
+ h('div', { className: 'dshr-card-head' },
1210
+ h('h3', { className: 'dshr-card-title' }, isAccessDenied ? t('adminAccessDeniedTitle') : t('adminErrorTitle')),
1211
+ h('span', { className: 'dshr-badge', id: 'dshr-admin-error-status' },
1212
+ adminLoadError.status ? `HTTP ${adminLoadError.status}` : 'NETWORK',
1213
+ ),
1214
+ ),
1215
+ h('div', { className: 'dshr-err', id: 'dshr-admin-error-message' }, adminLoadError.message),
1216
+ h('div', { className: 'dshr-label' }, t('adminErrorHint')),
1217
+ h('div', { className: 'dshr-row' },
1218
+ h('button', {
1219
+ type: 'button',
1220
+ id: 'dshr-admin-retry-btn',
1221
+ className: 'dshr-btn dshr-btn-primary',
1222
+ disabled: busy === 'retry',
1223
+ onClick: () => void handleRetryAdminLoad(),
1224
+ }, t('retry')),
1225
+ ),
1226
+ ),
1227
+
1228
+ // Initial loading card before first admin overview response
1229
+ isAdminLoadingInitial && h('div', { className: 'dshr-card', id: 'dshr-admin-loading-card' },
1230
+ h('div', { className: 'dshr-label' }, t('loadingOverview')),
1231
+ ),
1232
+
1119
1233
  // Unconfigured interactive onboarding card (Bind existing OR Create new Tiana app)
1120
- !configured && h('div', { className: 'dshr-card', id: 'dshr-unconfigured-card' },
1234
+ showUnconfiguredPanel && h('div', { className: 'dshr-card', id: 'dshr-unconfigured-card' },
1121
1235
  h('div', { className: 'dshr-card-head' },
1122
1236
  h('h3', { className: 'dshr-card-title' }, t('onboardTitle')),
1123
1237
  ),
@@ -1233,7 +1347,7 @@
1233
1347
  ),
1234
1348
 
1235
1349
  // Card 1: Remote URL & QR
1236
- configured && h('div', { className: 'dshr-card' },
1350
+ showConfiguredPanel && h('div', { className: 'dshr-card' },
1237
1351
  h('div', { className: 'dshr-card-head' },
1238
1352
  h('h3', { className: 'dshr-card-title' }, t('remoteUrl')),
1239
1353
  h('span', { className: 'dshr-label' }, overview?.host?.hostName || overview?.host?.hostId),
@@ -1251,7 +1365,7 @@
1251
1365
  ),
1252
1366
 
1253
1367
  // Card 2: E2EE Pairing Key
1254
- configured && h('div', { className: 'dshr-card' },
1368
+ showConfiguredPanel && h('div', { className: 'dshr-card' },
1255
1369
  h('div', { className: 'dshr-card-head' },
1256
1370
  h('h3', { className: 'dshr-card-title' }, t('e2eeTitle')),
1257
1371
  h('span', { className: 'dshr-badge' }, `${t('e2eeFingerprint')}: ${overview?.e2ee?.fingerprint || '—'}`),
@@ -1277,7 +1391,7 @@
1277
1391
  ),
1278
1392
 
1279
1393
  // Card 3: Active Sessions & Function Token Expiry / Renew
1280
- configured && h('div', { className: 'dshr-card' },
1394
+ showConfiguredPanel && h('div', { className: 'dshr-card' },
1281
1395
  h('div', { className: 'dshr-card-head' },
1282
1396
  h('h3', { className: 'dshr-card-title' }, `${t('sessionsTitle')} (${sessions.length})`),
1283
1397
  sessions.length > 0 && h('button', {
@@ -1316,7 +1430,7 @@
1316
1430
  ),
1317
1431
 
1318
1432
  // Card 4: Host, Network, Plugin Allowlist & Switch/Rebind Cloud App
1319
- configured && h('div', { className: 'dshr-card' },
1433
+ showConfiguredPanel && h('div', { className: 'dshr-card' },
1320
1434
  h('form', { style: { display: 'grid', gap: 14 }, onSubmit: handleSaveSettings },
1321
1435
  h('div', { className: 'dshr-card-head' },
1322
1436
  h('h3', { className: 'dshr-card-title' }, t('settingsTitle')),
package/host-main.js CHANGED
@@ -223,7 +223,7 @@ export function createHostController(options = {}) {
223
223
  if (!Array.isArray(graph?.entries)) return [];
224
224
  return graph.entries
225
225
  .map((e) => e.id)
226
- .filter((id) => typeof id === 'string' && !id.startsWith('@deepseek-ai/dsh-client-') && id !== '@tianacloud/dsh-remote');
226
+ .filter((id) => typeof id === 'string' && !id.startsWith('@deepseek-ai/dsh-') && id !== '@tianacloud/dsh-remote');
227
227
  } catch {
228
228
  return [];
229
229
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tianacloud/dsh-remote",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "type": "module",
5
5
  "description": "使用 Tiana 能力为 DeepSeek Harness 提供零公网 IP 远程访问、侧栏管理面板、无密钥流式子资源桥接与云端一键引导插件。",
6
6
  "license": "Apache-2.0",
package/src/connect.js CHANGED
@@ -394,6 +394,10 @@ export async function isLocalDshResponsive(origin, { fetchFn = fetch, timeoutMs
394
394
  }
395
395
  }
396
396
 
397
+ export function buildDshStartArgs({ profile = 'web', port = 3080 } = {}) {
398
+ return ['--profile', String(profile || 'web'), '--port', String(port), '--no-open'];
399
+ }
400
+
397
401
  export async function waitForLocalDshReady(port, timeoutMs = 15_000, { childState = null, fetchFn = fetch } = {}) {
398
402
  const deadline = Date.now() + timeoutMs;
399
403
  const origin = `http://127.0.0.1:${port}`;
@@ -508,9 +512,11 @@ export async function runConnect(options = {}, deps = {}) {
508
512
  if (deps.startDsh) {
509
513
  dshStarted = await deps.startDsh(dshInfo.bin, { profile, port });
510
514
  } else {
511
- log(`[dsh-remote] Starting local DSH (${dshInfo.bin} web --port ${port} --no-open)...`);
515
+ const spawnFn = deps.spawnFn ?? spawn;
516
+ const startArgs = buildDshStartArgs({ profile, port });
517
+ log(`[dsh-remote] Starting local DSH (${dshInfo.bin} ${startArgs.join(' ')})...`);
512
518
  const childState = { error: null, exited: false, exitCode: null };
513
- const child = spawn(dshInfo.bin, ['web', '--profile', profile, '--port', String(port), '--no-open'], {
519
+ const child = spawnFn(dshInfo.bin, startArgs, {
514
520
  stdio: 'ignore',
515
521
  detached: true,
516
522
  windowsHide: true,
@@ -137,14 +137,14 @@ function cleanBundle(file) {
137
137
  return Buffer.from(readFile(file).toString('utf8').replace(/\r?\n\/\/# source(?:Mapping)?URL=[^\r\n]*/gu, ''));
138
138
  }
139
139
 
140
- const BUILTIN_CLIENT_PREFIX = '@deepseek-ai/dsh-client-';
140
+ const BUILTIN_CLIENT_PREFIX = '@deepseek-ai/dsh-';
141
141
  const SELF_CLIENT_MODULE = '@tianacloud/dsh-remote';
142
142
 
143
143
  /**
144
144
  * Select which active DSH client modules are exposed over the remote tunnel.
145
145
  * - `allowlist: ['*']` (or `'*'`): allow all active modules.
146
146
  * - `allowlist: []` (default) or omitted: allow ONLY builtin DSH core modules
147
- * (`@deepseek-ai/dsh-client-*`) plus `@tianacloud/dsh-remote` itself; third-party plugins are blocked.
147
+ * (`@deepseek-ai/dsh-*`) plus `@tianacloud/dsh-remote` itself; third-party plugins are blocked.
148
148
  * - Explicit IDs: allow builtin core + `@tianacloud/dsh-remote` + exact allowlisted active plugins.
149
149
  */
150
150
  export function selectAllowedWebPlugins(modules, allowlist) {
package/src/remote-api.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { isIP } from 'node:net';
1
2
  import { normalizeStun } from '../web-src/peer-path.js';
2
3
  import { formatPairingKey } from './state.js';
3
4
 
@@ -14,20 +15,138 @@ function jsonResponse(status, body) {
14
15
  });
15
16
  }
16
17
 
18
+ function parseIpv4Bytes(ip) {
19
+ if (!/^(?:0|[1-9]\d{0,2})(?:\.(?:0|[1-9]\d{0,2})){3}$/u.test(ip)) return null;
20
+ const parts = ip.split('.').map(Number);
21
+ if (parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;
22
+ return parts;
23
+ }
24
+
25
+ function parseIpv6Words(ip) {
26
+ if (isIP(ip) !== 6) return null;
27
+ let normalized = ip.toLowerCase();
28
+ const lastColon = normalized.lastIndexOf(':');
29
+ const tail = normalized.slice(lastColon + 1);
30
+ if (tail.includes('.')) {
31
+ const v4 = parseIpv4Bytes(tail);
32
+ if (!v4) return null;
33
+ const hi = ((v4[0] << 8) | v4[1]).toString(16);
34
+ const lo = ((v4[2] << 8) | v4[3]).toString(16);
35
+ normalized = `${normalized.slice(0, lastColon + 1)}${hi}:${lo}`;
36
+ }
37
+ const halves = normalized.split('::');
38
+ if (halves.length > 2) return null;
39
+ const left = halves[0] ? halves[0].split(':') : [];
40
+ const right = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
41
+ let groups;
42
+ if (halves.length === 2) {
43
+ const missing = 8 - (left.length + right.length);
44
+ if (missing < 1) return null;
45
+ groups = [...left, ...Array(missing).fill('0'), ...right];
46
+ } else {
47
+ if (left.length !== 8) return null;
48
+ groups = left;
49
+ }
50
+ const words = groups.map((g) => Number.parseInt(g, 16));
51
+ if (words.length !== 8 || words.some((w) => !Number.isInteger(w) || w < 0 || w > 0xffff)) {
52
+ return null;
53
+ }
54
+ return words;
55
+ }
56
+
57
+ function parseIpAddress(addr) {
58
+ if (!addr || typeof addr !== 'string') return null;
59
+ if (/\s/u.test(addr)) return null;
60
+ let bare = addr;
61
+ const hasOpen = bare.startsWith('[');
62
+ const hasClose = bare.endsWith(']');
63
+ if (hasOpen || hasClose) {
64
+ if (!hasOpen || !hasClose) return null;
65
+ bare = bare.slice(1, -1);
66
+ if (!bare.includes(':')) return null;
67
+ }
68
+ const pctIdx = bare.indexOf('%');
69
+ if (pctIdx !== -1) {
70
+ const zone = bare.slice(pctIdx + 1);
71
+ bare = bare.slice(0, pctIdx);
72
+ if (!bare.includes(':') || !zone || !/^[a-zA-Z0-9._:-]+$/u.test(zone)) {
73
+ return null;
74
+ }
75
+ }
76
+ const v4 = parseIpv4Bytes(bare);
77
+ if (v4) return { family: 4, bytes: v4 };
78
+ const v6 = parseIpv6Words(bare);
79
+ if (!v6) return null;
80
+ // Unwrap IPv4-mapped IPv6 (::ffff:0:0/96) in both dotted-quad and hex forms
81
+ if (v6[0] === 0 && v6[1] === 0 && v6[2] === 0 && v6[3] === 0 && v6[4] === 0 && v6[5] === 0xffff) {
82
+ return {
83
+ family: 4,
84
+ bytes: [(v6[6] >>> 8) & 0xff, v6[6] & 0xff, (v6[7] >>> 8) & 0xff, v6[7] & 0xff],
85
+ };
86
+ }
87
+ return { family: 6, words: v6 };
88
+ }
89
+
90
+ function isLoopbackIpv4(bytes) {
91
+ return bytes[0] === 127;
92
+ }
93
+
94
+ function isPrivateOrLocalIpv4(bytes) {
95
+ const [a, b] = bytes;
96
+ if (a === 127) return true; // Loopback: 127.0.0.0/8
97
+ if (a === 10) return true; // RFC 1918: 10.0.0.0/8
98
+ if (a === 172 && b >= 16 && b <= 31) return true; // RFC 1918: 172.16.0.0/12
99
+ if (a === 192 && b === 168) return true; // RFC 1918: 192.168.0.0/16
100
+ if (a === 100 && b >= 64 && b <= 127) return true; // RFC 6598 / Tailscale CGNAT: 100.64.0.0/10
101
+ if (a === 169 && b === 254) return true; // RFC 3927 Link-Local: 169.254.0.0/16
102
+ return false;
103
+ }
104
+
105
+ function isLoopbackIpv6(words) {
106
+ return words[0] === 0 && words[1] === 0 && words[2] === 0 && words[3] === 0 &&
107
+ words[4] === 0 && words[5] === 0 && words[6] === 0 && words[7] === 1;
108
+ }
109
+
110
+ function isPrivateOrLocalIpv6(words) {
111
+ if (isLoopbackIpv6(words)) return true; // Loopback: ::1
112
+ if ((words[0] & 0xffc0) === 0xfe80) return true; // Link-Local: fe80::/10
113
+ if ((words[0] & 0xfe00) === 0xfc00) return true; // Unique Local (ULA, incl. Tailscale fd7a::): fc00::/7
114
+ return false;
115
+ }
116
+
17
117
  export function isLoopbackAddress(addr) {
18
- if (!addr || typeof addr !== 'string') return false;
19
- const bare = addr.trim().replace(/^\[|\]$/gu, '').toLowerCase();
20
- return bare === '127.0.0.1' || bare === '::1' || bare === '::ffff:127.0.0.1';
118
+ const parsed = parseIpAddress(addr);
119
+ if (!parsed) return false;
120
+ return parsed.family === 4 ? isLoopbackIpv4(parsed.bytes) : isLoopbackIpv6(parsed.words);
21
121
  }
22
122
 
23
- export function isLoopbackHostHeader(hostHeader) {
123
+ export function isPrivateOrLocalAddress(addr) {
124
+ const parsed = parseIpAddress(addr);
125
+ if (!parsed) return false;
126
+ return parsed.family === 4 ? isPrivateOrLocalIpv4(parsed.bytes) : isPrivateOrLocalIpv6(parsed.words);
127
+ }
128
+
129
+ export function isValidHostHeader(hostHeader) {
24
130
  if (!hostHeader || typeof hostHeader !== 'string') return false;
25
- const trimmed = hostHeader.trim();
26
- if (!trimmed || /[\s/@?#\\]/u.test(trimmed)) return false;
131
+ if (/[\s\u0000-\u001f\u007f/@?#\\]/u.test(hostHeader) || hostHeader.endsWith(':')) return false;
132
+ try {
133
+ const parsed = new URL(`http://${hostHeader}`);
134
+ if (!parsed.hostname) return false;
135
+ if (parsed.username || parsed.password || parsed.pathname !== '/' || parsed.search || parsed.hash) {
136
+ return false;
137
+ }
138
+ return true;
139
+ } catch {
140
+ return false;
141
+ }
142
+ }
143
+
144
+ export function isLoopbackHostHeader(hostHeader) {
145
+ if (!isValidHostHeader(hostHeader)) return false;
27
146
  try {
28
- const parsed = new URL(`http://${trimmed}`);
147
+ const parsed = new URL(`http://${hostHeader}`);
29
148
  const host = parsed.hostname.toLowerCase();
30
- return host === '127.0.0.1' || host === '::1' || host === '[::1]' || host === 'localhost';
149
+ return host === 'localhost' || isLoopbackAddress(host);
31
150
  } catch {
32
151
  return false;
33
152
  }
@@ -69,12 +188,22 @@ function normalizeRejectionResponse(rejection, { mapAuthToForbidden = false } =
69
188
  return jsonResponse(403, { ok: false, error: 'Request rejected' });
70
189
  }
71
190
 
191
+ function normalizeAuthTarget(nodeReq, request) {
192
+ if (!nodeReq) return request;
193
+ if (nodeReq.headers?.host === undefined && typeof nodeReq.headers?.[':authority'] === 'string') {
194
+ return Object.create(nodeReq, {
195
+ headers: { value: { ...nodeReq.headers, host: nodeReq.headers[':authority'] }, enumerable: true },
196
+ });
197
+ }
198
+ return nodeReq;
199
+ }
200
+
72
201
  /**
73
- * Triple-guard check for all local-only `/api/tiana-remote/admin/*` endpoints:
74
- * 1. Verified loopback TCP socket address (`isLoopbackAddress(remoteAddress) === true`, fail-closed when missing)
75
- * AND verified loopback `Host` header (`isLoopbackHostHeader(hostHeader) === true`, fail-closed when missing/non-loopback)
202
+ * Triple-guard check for all local/LAN/Tailnet `/api/tiana-remote/admin/*` endpoints:
203
+ * 1. Verified non-public TCP socket address (`isPrivateOrLocalAddress(remoteAddress) === true`, fail-closed when missing)
204
+ * AND syntactically valid `Host` header (for non-loopback peer or Host, `connection.requestRejection` is mandatory)
76
205
  * 2. Strict absence of `X-DSH-Remote-Tunnel` header (checked via presence, rejecting even empty-string values)
77
- * 3. Valid local DSH owner session via `connection.requestRejection` (supports numeric status code & Response return forms)
206
+ * 3. Valid DSH trusted-host + owner session via `connection.requestRejection` (supports numeric status code & Response return forms)
78
207
  */
79
208
  export async function guardAdminRequest(request, connection, meta = {}) {
80
209
  const { remoteAddress, hostHeader, hasTunnelHeader, nodeReq } = meta;
@@ -87,15 +216,20 @@ export async function guardAdminRequest(request, connection, meta = {}) {
87
216
  return jsonResponse(403, { ok: false, error: 'Admin endpoints are forbidden over remote tunnel' });
88
217
  }
89
218
 
90
- // Guard 1a: require verified TCP loopback peer address (fail-closed when absent)
91
- if (!isLoopbackAddress(remoteAddress)) {
92
- return jsonResponse(403, { ok: false, error: 'Admin endpoints require local loopback access' });
219
+ // Guard 1a: require verified loopback, private LAN, Tailscale/CGNAT, link-local, or ULA peer address (fail-closed when absent)
220
+ if (!isPrivateOrLocalAddress(remoteAddress)) {
221
+ return jsonResponse(403, { ok: false, error: 'Admin endpoints require local or private network access' });
93
222
  }
94
223
 
95
- // Guard 1b: require verified loopback Host header (fail-closed when missing or non-loopback)
224
+ // Guard 1b: require syntactically valid non-empty Host header (supporting HTTP/2 :authority)
96
225
  let effectiveHost;
97
226
  if (nodeReq) {
98
- effectiveHost = nodeReq.headers?.host;
227
+ const hHost = nodeReq.headers?.host;
228
+ const hAuth = nodeReq.headers?.[':authority'];
229
+ if (hHost !== undefined && hAuth !== undefined && String(hHost).toLowerCase() !== String(hAuth).toLowerCase()) {
230
+ return jsonResponse(403, { ok: false, error: 'Admin endpoints reject conflicting Host and :authority headers' });
231
+ }
232
+ effectiveHost = hHost ?? hAuth;
99
233
  } else if (hostHeader !== undefined) {
100
234
  effectiveHost = hostHeader;
101
235
  } else if (request.headers.has('host')) {
@@ -107,13 +241,22 @@ export async function guardAdminRequest(request, connection, meta = {}) {
107
241
  effectiveHost = '';
108
242
  }
109
243
  }
110
- if (!isLoopbackHostHeader(effectiveHost)) {
111
- return jsonResponse(403, { ok: false, error: 'Admin endpoints require a loopback Host header' });
244
+ if (!isValidHostHeader(effectiveHost)) {
245
+ return jsonResponse(403, { ok: false, error: 'Admin endpoints require a valid Host header' });
112
246
  }
113
247
 
114
- // Guard 3: verify local DSH owner session
115
- if (typeof connection?.requestRejection === 'function') {
116
- const authTarget = nodeReq ?? request;
248
+ const isLoopback = isLoopbackAddress(remoteAddress) && isLoopbackHostHeader(effectiveHost);
249
+ const hasRequestRejection = typeof connection?.requestRejection === 'function';
250
+ if (!isLoopback && !hasRequestRejection) {
251
+ return jsonResponse(403, {
252
+ ok: false,
253
+ error: 'Non-loopback admin access requires DSH trusted-host and owner-session verification',
254
+ });
255
+ }
256
+
257
+ // Guard 3: verify DSH trusted-host + owner session
258
+ if (hasRequestRejection) {
259
+ const authTarget = normalizeAuthTarget(nodeReq, request);
117
260
  const rejection = await connection.requestRejection(authTarget, { allowAuthorizationHeader: false });
118
261
  const mapped = normalizeRejectionResponse(rejection, { mapAuthToForbidden: true });
119
262
  if (mapped) return mapped;
@@ -124,7 +267,7 @@ export async function guardAdminRequest(request, connection, meta = {}) {
124
267
 
125
268
  export async function guardPublicRequest(request, connection, meta = {}) {
126
269
  if (typeof connection?.requestRejection === 'function') {
127
- const authTarget = meta.nodeReq ?? request;
270
+ const authTarget = normalizeAuthTarget(meta.nodeReq, request);
128
271
  const rejection = await connection.requestRejection(authTarget, { allowAuthorizationHeader: false });
129
272
  const mapped = normalizeRejectionResponse(rejection, { mapAuthToForbidden: false });
130
273
  if (mapped) return mapped;
@@ -343,21 +486,22 @@ export function registerWebServerRoutes(webServer, connection, controller) {
343
486
  }
344
487
  const headers = new Headers();
345
488
  for (const [k, v] of Object.entries(req.headers || {})) {
346
- if (v === undefined) continue;
489
+ if (v === undefined || k.startsWith(':')) continue;
347
490
  if (Array.isArray(v)) {
348
491
  for (const item of v) headers.append(k, String(item));
349
492
  } else {
350
493
  headers.set(k, String(v));
351
494
  }
352
495
  }
496
+ const rawHost = req.headers?.host ?? req.headers?.[':authority'];
353
497
  const fetchReq = new Request(new URL(String(req.url || '/'), 'http://127.0.0.1').href, {
354
498
  method,
355
499
  headers,
356
500
  body: method === 'GET' || method === 'HEAD' ? undefined : bodyBuf,
357
501
  });
358
502
  const response = await handler(fetchReq, {
359
- remoteAddress: req.socket?.remoteAddress,
360
- hostHeader: req.headers?.host,
503
+ remoteAddress: req.socket?.remoteAddress ?? req.stream?.session?.socket?.remoteAddress,
504
+ hostHeader: rawHost,
361
505
  hasTunnelHeader: 'x-dsh-remote-tunnel' in (req.headers || {}),
362
506
  nodeReq: req,
363
507
  });
@@ -1874,6 +1874,7 @@ function installSwScopeAlignment(appBasePath, signal, getNavToken) {
1874
1874
  const dlUrl = new URL(next, location.href);
1875
1875
  dlUrl.searchParams.set('__dsh_dl', (anchor.getAttribute('download') || '').trim() || '1');
1876
1876
  const f = document.createElement('iframe');
1877
+ f.referrerPolicy = 'same-origin';
1877
1878
  f.style.display = 'none';
1878
1879
  f.setAttribute('aria-hidden', 'true');
1879
1880
  f.src = dlUrl.href;
@@ -1883,6 +1884,13 @@ function installSwScopeAlignment(appBasePath, signal, getNavToken) {
1883
1884
 
1884
1885
  if (!iframeNavHooksInstalled && typeof HTMLIFrameElement !== 'undefined') {
1885
1886
  iframeNavHooksInstalled = true;
1887
+ const ensureSameOriginReferrer = (el, nextUrl) => {
1888
+ if (nextUrl && nextUrl.includes('__dsh_nav=')) {
1889
+ // Override document-level `Referrer-Policy: no-referrer` strictly for same-origin SW-tunneled iframes
1890
+ // without ever leaking referrers cross-origin.
1891
+ try { el.referrerPolicy = 'same-origin'; } catch { /* ignore */ }
1892
+ }
1893
+ };
1886
1894
  const desc = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'src');
1887
1895
  if (desc?.set && desc.configurable) {
1888
1896
  Object.defineProperty(HTMLIFrameElement.prototype, 'src', {
@@ -1891,6 +1899,7 @@ function installSwScopeAlignment(appBasePath, signal, getNavToken) {
1891
1899
  get: desc.get,
1892
1900
  set(val) {
1893
1901
  const next = activeSwNavRewriter ? activeSwNavRewriter(String(val)) : String(val);
1902
+ ensureSameOriginReferrer(this, next);
1894
1903
  return desc.set.call(this, next);
1895
1904
  },
1896
1905
  });
@@ -1899,6 +1908,7 @@ function installSwScopeAlignment(appBasePath, signal, getNavToken) {
1899
1908
  HTMLIFrameElement.prototype.setAttribute = function setAttribute(name, value) {
1900
1909
  if (String(name).toLowerCase() === 'src') {
1901
1910
  const next = activeSwNavRewriter ? activeSwNavRewriter(String(value)) : String(value);
1911
+ ensureSameOriginReferrer(this, next);
1902
1912
  return origSetAttr.call(this, name, next);
1903
1913
  }
1904
1914
  return origSetAttr.call(this, name, value);
@@ -349,6 +349,33 @@ function resolvePortByNavToken(navToken) {
349
349
 
350
350
  async function resolvePortForEvent(event, url) {
351
351
  const directClientId = event.clientId || '';
352
+ const dest = event.request.destination || '';
353
+ const referrer = event.request.referrer || '';
354
+ if (dest === 'iframe' || dest === 'frame') {
355
+ if (referrer) {
356
+ if (!isTrustedAppUrl(referrer)) {
357
+ return null;
358
+ }
359
+ } else {
360
+ const secFetchSite = String(event.request.headers.get('sec-fetch-site') || '').trim().toLowerCase();
361
+ if (secFetchSite !== 'same-origin') {
362
+ return null;
363
+ }
364
+ if (!directClientId) {
365
+ return null;
366
+ }
367
+ let parentClient = null;
368
+ try {
369
+ parentClient = await self.clients.get(directClientId);
370
+ } catch {
371
+ parentClient = null;
372
+ }
373
+ if (!isTrustedWindowClient(parentClient)) {
374
+ return null;
375
+ }
376
+ }
377
+ }
378
+
352
379
  if (directClientId) {
353
380
  const existingDirect = portsByClientId.get(directClientId);
354
381
  if (existingDirect) return existingDirect;
@@ -366,11 +393,6 @@ async function resolvePortForEvent(event, url) {
366
393
 
367
394
  const navToken = extractNavToken(event.request, url);
368
395
  if (navToken) {
369
- const dest = event.request.destination || '';
370
- const referrer = event.request.referrer || '';
371
- if ((dest === 'iframe' || dest === 'frame') && !isTrustedAppUrl(referrer)) {
372
- return null;
373
- }
374
396
  if (referrer && (referrer.startsWith('http://') || referrer.startsWith('https://')) && !isTrustedAppUrl(referrer)) {
375
397
  return null;
376
398
  }