@tianacloud/dsh-remote 0.0.0-stage → 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/LICENSE +204 -0
- package/README.md +44 -2
- package/cli.js +347 -0
- package/client.js +1501 -0
- package/cordis.patch.yml +3 -0
- package/host-main.js +628 -0
- package/icon.svg +7 -0
- package/locale/en-US.json +9 -0
- package/locale/zh-CN.json +9 -0
- package/package.json +89 -4
- package/relay-go/go.mod +3 -0
- package/relay-go/main.go +1711 -0
- package/scripts/build-web-dist.mjs +46 -0
- package/src/clipboard.js +94 -0
- package/src/connect.js +599 -0
- package/src/dsh-packages.js +46 -0
- package/src/frontend-assets.js +405 -0
- package/src/host-bridge.js +1412 -0
- package/src/local-transport.js +496 -0
- package/src/protocol.js +124 -0
- package/src/remote-api.js +433 -0
- package/src/state.js +379 -0
- package/src/tiana-cli.js +929 -0
- package/web-src/dsh-remote-entry.mjs +2692 -0
- package/web-src/dsh-remote-sw.js +593 -0
- package/web-src/e2ee.js +460 -0
- package/web-src/frontend-loader.js +450 -0
- package/web-src/multipath.js +375 -0
- package/web-src/peer-path.js +265 -0
- package/web-src/shell-ui.js +280 -0
- package/web-src/ws-fragments.js +46 -0
|
@@ -0,0 +1,2692 @@
|
|
|
1
|
+
/** Browser shell for the authenticated DSH Remote workbench. */
|
|
2
|
+
|
|
3
|
+
if (typeof Promise.withResolvers !== 'function') {
|
|
4
|
+
Promise.withResolvers = () => { let resolve, reject; const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); return { promise, resolve, reject }; };
|
|
5
|
+
}
|
|
6
|
+
if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.any !== 'function') {
|
|
7
|
+
AbortSignal.any = (signals) => {
|
|
8
|
+
const c = new AbortController();
|
|
9
|
+
for (const s of signals) {
|
|
10
|
+
if (!s) continue;
|
|
11
|
+
if (s.aborted) { c.abort(s.reason); return c.signal; }
|
|
12
|
+
s.addEventListener('abort', () => c.abort(s.reason), { once: true });
|
|
13
|
+
}
|
|
14
|
+
return c.signal;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
(() => {
|
|
18
|
+
const p = (typeof Iterator !== 'undefined' && Iterator.prototype) || Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
|
|
19
|
+
if (!p) return;
|
|
20
|
+
const def = (k, value) => { if (typeof p[k] !== 'function') Object.defineProperty(p, k, { configurable: true, writable: true, value }); };
|
|
21
|
+
def('map', function* map(fn) { let i = 0; for (const x of this) yield fn(x, i++); });
|
|
22
|
+
def('filter', function* filter(fn) { let i = 0; for (const x of this) if (fn(x, i++)) yield x; });
|
|
23
|
+
def('take', function* take(limit) { let n = Math.max(0, Number(limit) || 0); if (!n) return; for (const x of this) { yield x; if (--n <= 0) return; } });
|
|
24
|
+
def('toArray', function toArray() { return Array.from(this); });
|
|
25
|
+
})();
|
|
26
|
+
|
|
27
|
+
import { clearFrontendCache, clearWebFrontendCache, createFrontendLoader, requestFrontend } from './frontend-loader.js';
|
|
28
|
+
import { CHUNK_SIZE, createPath, LEASE_MS, MultipathSession, relayPacer, RELAY_GRACE_MS, RENEW_MS } from './multipath.js';
|
|
29
|
+
import { normalizeStun, PeerPath } from './peer-path.js';
|
|
30
|
+
import { createShellUI } from './shell-ui.js';
|
|
31
|
+
import { FragmentReader, sendFragments } from './ws-fragments.js';
|
|
32
|
+
import {
|
|
33
|
+
computeKeyFingerprint,
|
|
34
|
+
createClientHandshake,
|
|
35
|
+
generateLogicalSessionId,
|
|
36
|
+
MSG_E2EE_BOX,
|
|
37
|
+
MSG_E2EE_CLIENT_HELLO,
|
|
38
|
+
MSG_E2EE_CTRL,
|
|
39
|
+
MSG_E2EE_ERROR,
|
|
40
|
+
MSG_E2EE_HOST_HELLO,
|
|
41
|
+
normalizePairingKey,
|
|
42
|
+
} from './e2ee.js';
|
|
43
|
+
|
|
44
|
+
const MSG_CONTROL_JSON = 0x01, MSG_HTTP_REQ_HEAD = 0x10, MSG_HTTP_REQ_BODY = 0x11, MSG_HTTP_REQ_END = 0x12,
|
|
45
|
+
MSG_HTTP_RES_HEAD = 0x13, MSG_HTTP_RES_BODY = 0x14, MSG_HTTP_RES_END = 0x15, MSG_HTTP_ABORT = 0x16, MSG_HTTP_RES_WINDOW = 0x17,
|
|
46
|
+
MSG_WS_OPEN = 0x20, MSG_WS_OPENED = 0x21, MSG_WS_DATA_TEXT = 0x22, MSG_WS_DATA_BIN = 0x23, MSG_WS_CLOSE = 0x24;
|
|
47
|
+
|
|
48
|
+
const textEncoder = new TextEncoder(), textDecoder = new TextDecoder();
|
|
49
|
+
const nativeFetch = typeof globalThis.fetch === 'function' ? globalThis.fetch.bind(globalThis) : null;
|
|
50
|
+
const nativeEventSource = typeof globalThis.EventSource === 'function' ? globalThis.EventSource : null;
|
|
51
|
+
const nativeSwRegister = typeof navigator !== 'undefined' && typeof navigator.serviceWorker?.register === 'function'
|
|
52
|
+
? navigator.serviceWorker.register.bind(navigator.serviceWorker) : null;
|
|
53
|
+
|
|
54
|
+
export const MAX_STREAMS = 64;
|
|
55
|
+
const SUBRESOURCE_CONCURRENCY = 16, MAX_REQUEST_BYTES = 16 << 20, MAX_RESPONSE_BUFFER_BYTES = 16 << 20,
|
|
56
|
+
DEFAULT_WINDOW_BYTES = 4 << 20, WINDOW_REFILL_THRESHOLD = 512 << 10, RESPONSE_IDLE_TIMEOUT_MS = 300_000,
|
|
57
|
+
MAX_REDIRECT_HOPS = 5, SW_READY_TIMEOUT_MS = 1500, RECONNECT_BANNER_DELAY_MS = 800;
|
|
58
|
+
|
|
59
|
+
const REDIRECT_BODY_STRIPPED_HEADERS = ['content-type', 'content-length', 'content-encoding', 'content-language', 'content-location'];
|
|
60
|
+
const stripBodyHeaders = (headers) => { for (const h of REDIRECT_BODY_STRIPPED_HEADERS) headers.delete(h); };
|
|
61
|
+
|
|
62
|
+
export function sanitizeCrossOriginHeaders(rawHeaders) {
|
|
63
|
+
const out = new Headers(rawHeaders || {});
|
|
64
|
+
const toDelete = [];
|
|
65
|
+
out.forEach((_value, key) => {
|
|
66
|
+
const lower = key.toLowerCase();
|
|
67
|
+
if (lower === 'authorization' || lower === 'cookie' || lower === 'proxy-authorization' ||
|
|
68
|
+
lower.startsWith('x-tiana-') || lower.startsWith('x-dsh-')) {
|
|
69
|
+
toDelete.push(key);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
for (const key of toDelete) {
|
|
73
|
+
out.delete(key);
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function encodeWindowUpdate(creditBytes) {
|
|
79
|
+
const out = new Uint8Array(4);
|
|
80
|
+
new DataView(out.buffer).setUint32(0, creditBytes >>> 0, false);
|
|
81
|
+
return out;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function encodeClientFrame(streamId, msgType, payload) {
|
|
85
|
+
const body = payload == null ? new Uint8Array(0)
|
|
86
|
+
: payload instanceof Uint8Array ? payload
|
|
87
|
+
: payload instanceof ArrayBuffer ? new Uint8Array(payload)
|
|
88
|
+
: ArrayBuffer.isView(payload) ? new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength)
|
|
89
|
+
: textEncoder.encode(typeof payload === 'string' ? payload : JSON.stringify(payload));
|
|
90
|
+
const out = new Uint8Array(5 + body.byteLength);
|
|
91
|
+
new DataView(out.buffer).setUint32(0, streamId >>> 0, false);
|
|
92
|
+
out[4] = msgType & 0xff;
|
|
93
|
+
if (body.byteLength > 0) out.set(body, 5);
|
|
94
|
+
return out;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function decodeClientFrame(buf) {
|
|
98
|
+
const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
|
|
99
|
+
if (bytes.byteLength < 5) throw new Error(`Invalid tunnel frame length: ${bytes.byteLength}`);
|
|
100
|
+
return { streamId: new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(0, false), msgType: bytes[4], payload: bytes.subarray(5) };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function createConcurrencySemaphore(limit = SUBRESOURCE_CONCURRENCY) {
|
|
104
|
+
let active = 0;
|
|
105
|
+
const queue = [];
|
|
106
|
+
const release = () => {
|
|
107
|
+
active = Math.max(0, active - 1);
|
|
108
|
+
while (active < limit && queue.length > 0) {
|
|
109
|
+
const next = queue.shift();
|
|
110
|
+
if (next.cancelled) continue;
|
|
111
|
+
next.signal?.removeEventListener('abort', next.onAbort);
|
|
112
|
+
active += 1;
|
|
113
|
+
next.resolve(release);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
return {
|
|
118
|
+
acquire(signal) {
|
|
119
|
+
if (signal?.aborted) return Promise.reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
|
|
120
|
+
if (active < limit) { active += 1; return Promise.resolve(release); }
|
|
121
|
+
return new Promise((resolve, reject) => {
|
|
122
|
+
const entry = { resolve, reject, signal, cancelled: false, onAbort: null };
|
|
123
|
+
entry.onAbort = () => {
|
|
124
|
+
entry.cancelled = true;
|
|
125
|
+
const idx = queue.indexOf(entry);
|
|
126
|
+
if (idx !== -1) queue.splice(idx, 1);
|
|
127
|
+
reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
|
|
128
|
+
};
|
|
129
|
+
signal?.addEventListener('abort', entry.onAbort, { once: true });
|
|
130
|
+
queue.push(entry);
|
|
131
|
+
});
|
|
132
|
+
},
|
|
133
|
+
get activeCount() { return active; },
|
|
134
|
+
get queuedCount() { return queue.length; },
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function consumeLegacyPairingHash() {
|
|
139
|
+
let oneTimeSecret = null;
|
|
140
|
+
try {
|
|
141
|
+
const url = new URL(location.href);
|
|
142
|
+
const fragment = new URLSearchParams(url.hash.slice(1));
|
|
143
|
+
let dirty = false;
|
|
144
|
+
if (fragment.has('rk')) { const val = fragment.get('rk')?.trim(); if (val) oneTimeSecret = val; fragment.delete('rk'); dirty = true; }
|
|
145
|
+
if (fragment.has('k')) { fragment.delete('k'); dirty = true; }
|
|
146
|
+
if (dirty) { url.hash = fragment.toString(); history.replaceState(history.state, '', url); }
|
|
147
|
+
} catch { /* ignore */ }
|
|
148
|
+
try { for (const key of Object.keys(localStorage)) { if (key.startsWith('dsh-remote:e2ee:')) localStorage.removeItem(key); } } catch { /* ignore */ }
|
|
149
|
+
return oneTimeSecret;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const assetUrl = (relPath) => new URL(relPath, import.meta.url).href;
|
|
153
|
+
|
|
154
|
+
async function fetchConfig() {
|
|
155
|
+
const resp = await nativeFetch(assetUrl('./remote-config.json'), { cache: 'no-store' });
|
|
156
|
+
if (!resp.ok) throw new Error(`Failed to load remote-config.json (HTTP ${resp.status})`);
|
|
157
|
+
return await resp.json();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function resolveRedirectTarget(currentPath, locationHeader) {
|
|
161
|
+
if (typeof locationHeader !== 'string' || !locationHeader.trim()) return null;
|
|
162
|
+
const trimmed = locationHeader.trim();
|
|
163
|
+
const base = new URL(currentPath, 'https://dsh.local');
|
|
164
|
+
let resolved;
|
|
165
|
+
try {
|
|
166
|
+
resolved = new URL(trimmed, base);
|
|
167
|
+
} catch {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
if (resolved.origin === 'https://dsh.local') {
|
|
171
|
+
return { kind: 'tunnel', path: `${resolved.pathname}${resolved.search}` };
|
|
172
|
+
}
|
|
173
|
+
if (typeof location !== 'undefined' && resolved.origin === location.origin) {
|
|
174
|
+
const appBase = new URL('./', location.href).pathname;
|
|
175
|
+
let p = resolved.pathname;
|
|
176
|
+
if (appBase !== '/' && p.startsWith(appBase)) p = `/${p.slice(appBase.length)}`;
|
|
177
|
+
return { kind: 'tunnel', path: `${p}${resolved.search}` };
|
|
178
|
+
}
|
|
179
|
+
if ((resolved.protocol === 'http:' || resolved.protocol === 'https:') &&
|
|
180
|
+
['127.0.0.1', '[::1]', 'localhost'].includes(resolved.hostname)) {
|
|
181
|
+
return { kind: 'tunnel', path: `${resolved.pathname}${resolved.search}` };
|
|
182
|
+
}
|
|
183
|
+
if (resolved.protocol === 'https:') {
|
|
184
|
+
return { kind: 'external', url: resolved.href };
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export class TunnelClient {
|
|
190
|
+
constructor(openRelay, target, onState, onRevoked, checkSession = null, options = {}) {
|
|
191
|
+
this.openRelay = openRelay;
|
|
192
|
+
this.target = target;
|
|
193
|
+
this.onState = onState;
|
|
194
|
+
this.onRevoked = onRevoked;
|
|
195
|
+
this.checkSession = checkSession;
|
|
196
|
+
this.onHostOnline = options.onHostOnline || null;
|
|
197
|
+
this.onHostChanged = options.onHostChanged || null;
|
|
198
|
+
this.refreshTarget = options.refreshTarget || null;
|
|
199
|
+
this.onKeyRotated = options.onKeyRotated || null;
|
|
200
|
+
this.onRtt = options.onRtt || null;
|
|
201
|
+
this.p2pEnabled = true;
|
|
202
|
+
this.nextStreamId = 1;
|
|
203
|
+
this.httpStreams = new Map();
|
|
204
|
+
this.wsStreams = new Map();
|
|
205
|
+
this.legs = new Set();
|
|
206
|
+
this.lifecycle = new AbortController();
|
|
207
|
+
this.closed = false;
|
|
208
|
+
this.rttMs = null;
|
|
209
|
+
this.rttTimer = null;
|
|
210
|
+
this.subresourceSemaphore = createConcurrencySemaphore(options.subresourceConcurrency ?? SUBRESOURCE_CONCURRENCY);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
failActiveStreams(err, wsCode = 1006, wsReason = 'Tunnel error') {
|
|
214
|
+
for (const entry of this.httpStreams.values()) entry.fail(err);
|
|
215
|
+
this.httpStreams.clear();
|
|
216
|
+
for (const sock of this.wsStreams.values()) sock._remoteClose(wsCode, wsReason, false);
|
|
217
|
+
this.wsStreams.clear();
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async connect(renew = false, { allowStandby = false } = {}) {
|
|
221
|
+
const signal = AbortSignal.any([this.lifecycle.signal, AbortSignal.timeout(10_000)]);
|
|
222
|
+
const ws = await this.openRelay(renew, signal, this.target.hostId);
|
|
223
|
+
if (signal.aborted) {
|
|
224
|
+
ws.close();
|
|
225
|
+
signal.throwIfAborted();
|
|
226
|
+
}
|
|
227
|
+
ws.binaryType = 'arraybuffer';
|
|
228
|
+
const welcome = Promise.withResolvers();
|
|
229
|
+
const leg = { ws, welcome, challenge: null, welcomeMsg: null };
|
|
230
|
+
const pace = relayPacer();
|
|
231
|
+
this.legs.add(leg);
|
|
232
|
+
leg.path = createPath({
|
|
233
|
+
ready: () => ws.readyState === 1 && this.legs.has(leg),
|
|
234
|
+
send: (type, data) => {
|
|
235
|
+
if ((type === MSG_E2EE_BOX || type === MSG_E2EE_CTRL) && !pace(type)) return false;
|
|
236
|
+
ws.send(encodeClientFrame(0, type, data));
|
|
237
|
+
return true;
|
|
238
|
+
},
|
|
239
|
+
close: () => ws.close(4008),
|
|
240
|
+
bufferedAmount: () => ws.bufferedAmount,
|
|
241
|
+
});
|
|
242
|
+
leg.path.leg = leg;
|
|
243
|
+
const abort = () => ws.close();
|
|
244
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
245
|
+
ws.addEventListener('message', (event) => {
|
|
246
|
+
if (!(event.data instanceof ArrayBuffer) || !this.legs.has(leg)) return;
|
|
247
|
+
let frame;
|
|
248
|
+
try { frame = decodeClientFrame(event.data); } catch { return; }
|
|
249
|
+
if (frame.streamId !== 0) return;
|
|
250
|
+
const { msgType, payload } = frame;
|
|
251
|
+
if (msgType === MSG_E2EE_CTRL || msgType === MSG_E2EE_BOX) {
|
|
252
|
+
this.transport?.receive(msgType, payload, leg.path);
|
|
253
|
+
} else if (msgType === MSG_CONTROL_JSON || msgType === MSG_E2EE_ERROR) {
|
|
254
|
+
let msg;
|
|
255
|
+
try { msg = JSON.parse(textDecoder.decode(payload)); } catch { return; }
|
|
256
|
+
if (msgType === MSG_E2EE_ERROR) {
|
|
257
|
+
const error = Object.assign(new Error('远程主机拒绝当前连接'), { code: msg.code });
|
|
258
|
+
leg.handshake?.reject(error);
|
|
259
|
+
leg.binding?.reject(error);
|
|
260
|
+
} else if (msg.type === 'welcome') {
|
|
261
|
+
leg.welcomeMsg = msg;
|
|
262
|
+
const { challenge, user } = msg;
|
|
263
|
+
if (msg.paired === false) {
|
|
264
|
+
if (allowStandby) {
|
|
265
|
+
leg.challenge = challenge || null;
|
|
266
|
+
welcome.resolve(msg);
|
|
267
|
+
} else {
|
|
268
|
+
welcome.reject(Object.assign(new Error('应用尚未绑定主机'), { code: 'UNPAIRED', welcome: msg }));
|
|
269
|
+
}
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (!/^[A-Za-z0-9_-]{22}$/u.test(challenge) ||
|
|
273
|
+
user?.userId !== this.target.ownerUserId ||
|
|
274
|
+
user?.tenantId !== this.target.tenantId ||
|
|
275
|
+
user?.webId !== this.target.webId) {
|
|
276
|
+
welcome.reject(new Error('远程主机连接身份不匹配'));
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (msg.configuredHost?.hostId) {
|
|
280
|
+
this.target.hostId = msg.configuredHost.hostId;
|
|
281
|
+
this.target.hostName = msg.configuredHost.hostName || msg.configuredHost.hostId;
|
|
282
|
+
if (msg.configuredHost.hostDigest) {
|
|
283
|
+
this.target.hostDigest = msg.configuredHost.hostDigest;
|
|
284
|
+
}
|
|
285
|
+
this.onHostChanged?.(msg.configuredHost);
|
|
286
|
+
}
|
|
287
|
+
if (!msg.selectedHostId || (this.target.hostId && msg.selectedHostId !== this.target.hostId)) {
|
|
288
|
+
if (allowStandby) {
|
|
289
|
+
leg.challenge = challenge;
|
|
290
|
+
welcome.resolve(msg);
|
|
291
|
+
} else {
|
|
292
|
+
welcome.reject(Object.assign(new Error('远程主机离线或连接身份不匹配'), { code: 'HOST_OFFLINE', welcome: msg }));
|
|
293
|
+
}
|
|
294
|
+
} else {
|
|
295
|
+
leg.challenge = challenge;
|
|
296
|
+
welcome.resolve(msg);
|
|
297
|
+
}
|
|
298
|
+
} else if (msg.type === 'host_online') {
|
|
299
|
+
if (msg.hostId) {
|
|
300
|
+
this.target.hostId = msg.hostId;
|
|
301
|
+
this.target.hostName = msg.hostName || msg.hostId;
|
|
302
|
+
} else if (msg.hostName) {
|
|
303
|
+
this.target.hostName = msg.hostName;
|
|
304
|
+
}
|
|
305
|
+
if (msg.hostDigest) {
|
|
306
|
+
this.target.hostDigest = msg.hostDigest;
|
|
307
|
+
}
|
|
308
|
+
this.onHostChanged?.(msg);
|
|
309
|
+
this.onHostOnline?.(msg);
|
|
310
|
+
} else if (msg.type === 'host_disconnected') {
|
|
311
|
+
ws.close();
|
|
312
|
+
}
|
|
313
|
+
} else if (msgType === MSG_E2EE_HOST_HELLO) {
|
|
314
|
+
leg.handshake?.resolve(payload);
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
ws.addEventListener('close', () => {
|
|
318
|
+
this.legs.delete(leg);
|
|
319
|
+
const error = new Error('Relay 连接已断开');
|
|
320
|
+
welcome.reject(error);
|
|
321
|
+
leg.handshake?.reject(error);
|
|
322
|
+
leg.binding?.reject(error);
|
|
323
|
+
if (this.leg === leg) {
|
|
324
|
+
this.leg = null;
|
|
325
|
+
this.transport?.setRelay(null);
|
|
326
|
+
this.onState(this.transport?.p2p ? 'P2P' : '正在重连');
|
|
327
|
+
this.armGrace();
|
|
328
|
+
if (!this.closed) this.scheduleReconnect();
|
|
329
|
+
}
|
|
330
|
+
}, { once: true });
|
|
331
|
+
try {
|
|
332
|
+
await welcome.promise;
|
|
333
|
+
return leg;
|
|
334
|
+
} catch (error) {
|
|
335
|
+
ws.close();
|
|
336
|
+
throw error;
|
|
337
|
+
} finally {
|
|
338
|
+
signal.removeEventListener('abort', abort);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
async exchange(leg, slot, send, timeout = 5000) {
|
|
343
|
+
const pending = leg[slot] = Promise.withResolvers();
|
|
344
|
+
const timer = setTimeout(() => pending.reject(new Error('远程认证响应超时')), timeout);
|
|
345
|
+
try {
|
|
346
|
+
await Promise.all([Promise.resolve().then(send), pending.promise]);
|
|
347
|
+
return await pending.promise;
|
|
348
|
+
} finally {
|
|
349
|
+
clearTimeout(timer);
|
|
350
|
+
leg[slot] = null;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async authenticate(leg, secret) {
|
|
355
|
+
const normalizedSecret = normalizePairingKey(secret);
|
|
356
|
+
let handshake;
|
|
357
|
+
try {
|
|
358
|
+
handshake = await createClientHandshake(normalizedSecret, { ...this.target, logicalSessionId: generateLogicalSessionId() });
|
|
359
|
+
} catch (cause) {
|
|
360
|
+
throw Object.assign(new Error('配对密钥无效', { cause }), { code: 'INVALID_KEY' });
|
|
361
|
+
}
|
|
362
|
+
const payload = await this.exchange(leg, 'handshake', () => leg.path.send(MSG_E2EE_CLIENT_HELLO, handshake.helloPayload));
|
|
363
|
+
const cipher = await handshake.finalize(payload);
|
|
364
|
+
if (!leg.path.ready() || this.closed) throw new Error('加密握手已取消');
|
|
365
|
+
|
|
366
|
+
this.retire(new Error('远程会话已更换,未确认的操作结果未知'));
|
|
367
|
+
const transport = new MultipathSession({
|
|
368
|
+
cipher,
|
|
369
|
+
leaseMs: this.target.leaseMs ?? LEASE_MS,
|
|
370
|
+
onData: (bytes) => {
|
|
371
|
+
if (this.transport === transport) return this.dispatchAppFrame(decodeClientFrame(bytes));
|
|
372
|
+
},
|
|
373
|
+
onControl: (message, path) => this.handleControl(message, path),
|
|
374
|
+
onStall: (path) => path?.close(),
|
|
375
|
+
onClose: (reason) => {
|
|
376
|
+
if (this.transport !== transport) return;
|
|
377
|
+
const hardExpired = Date.now() >= transport.expiresAt;
|
|
378
|
+
this.retire(reason);
|
|
379
|
+
this.onState('远程会话已结束');
|
|
380
|
+
if (hardExpired) {
|
|
381
|
+
this.close(reason);
|
|
382
|
+
void Promise.resolve(this.checkSession?.()).then((valid) => {
|
|
383
|
+
if (valid === false) return this.onRevoked(reason);
|
|
384
|
+
}).catch(() => {});
|
|
385
|
+
} else if (!this.closed) this.scheduleReconnect();
|
|
386
|
+
},
|
|
387
|
+
});
|
|
388
|
+
this.transport = transport;
|
|
389
|
+
this.leg = leg;
|
|
390
|
+
transport.setRelay(leg.path);
|
|
391
|
+
this.secret = normalizedSecret;
|
|
392
|
+
if (this.refreshManifest) await this.refreshManifest();
|
|
393
|
+
this.onState('Relay');
|
|
394
|
+
this.scheduleRenewal();
|
|
395
|
+
this.startRttProbes();
|
|
396
|
+
if (this.p2pEnabled && this.stun) this.startPeer(this.stun);
|
|
397
|
+
return await computeKeyFingerprint(normalizedSecret);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
startRttProbes() {
|
|
401
|
+
clearInterval(this.rttTimer);
|
|
402
|
+
const sendPing = () => {
|
|
403
|
+
if (this.closed || !this.transport) return;
|
|
404
|
+
void this.transport.control({ type: 'rtt_ping', ts: Date.now(), lastRttMs: this.rttMs }).catch(() => {});
|
|
405
|
+
};
|
|
406
|
+
sendPing();
|
|
407
|
+
this.rttTimer = setInterval(sendPing, 10_000);
|
|
408
|
+
this.rttTimer.unref?.();
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
startPeer(stun) {
|
|
412
|
+
if (!this.p2pEnabled) return;
|
|
413
|
+
this.stun = normalizeStun(stun);
|
|
414
|
+
if (typeof RTCPeerConnection !== 'function' || !this.transport || this.peer) return;
|
|
415
|
+
this.peer = new PeerPath(this.transport, {
|
|
416
|
+
createPeer: (config) => new RTCPeerConnection(config),
|
|
417
|
+
sendChannel: (channel, bytes) => channel.send(bytes),
|
|
418
|
+
initiator: true,
|
|
419
|
+
urls: this.stun,
|
|
420
|
+
signalPath: () => this.leg?.path,
|
|
421
|
+
onPath: (available) => {
|
|
422
|
+
this.onState(available ? 'P2P' : this.leg ? 'Relay' : '正在重连');
|
|
423
|
+
this.armGrace();
|
|
424
|
+
},
|
|
425
|
+
});
|
|
426
|
+
void this.peer.start();
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async handleControl(message, path) {
|
|
430
|
+
const leg = path.leg;
|
|
431
|
+
if (message?.type === 'lease_sync' && Number.isFinite(message.leaseMs) && message.leaseMs > 0) {
|
|
432
|
+
this.transport?.renewLease(message.leaseMs);
|
|
433
|
+
this.scheduleRenewal(message.leaseMs);
|
|
434
|
+
} else if (message?.type === 'bound_relay_leg' && leg?.binding && message.challenge === leg.challenge) {
|
|
435
|
+
leg.binding.resolve(message);
|
|
436
|
+
} else if (message?.type === 'rtt_pong' && Number.isFinite(message.ts)) {
|
|
437
|
+
this.rttMs = Math.max(0, Date.now() - message.ts);
|
|
438
|
+
this.onRtt?.(this.rttMs);
|
|
439
|
+
} else if (message?.type === 'session_closed') {
|
|
440
|
+
const code = Number(message.code) || 1000;
|
|
441
|
+
const reason = String(message.reason || '');
|
|
442
|
+
if (code === 4001 || reason === 'key_rotated') {
|
|
443
|
+
const err = Object.assign(new Error('主机已轮换配对密钥'), { code: 'KEY_ROTATED', closeCode: 4001 });
|
|
444
|
+
this.close(err);
|
|
445
|
+
await this.onKeyRotated?.(err);
|
|
446
|
+
} else {
|
|
447
|
+
this.retire(new Error('主机断开了当前会话'));
|
|
448
|
+
if (!this.closed) this.scheduleReconnect();
|
|
449
|
+
}
|
|
450
|
+
} else if (this.p2pEnabled) {
|
|
451
|
+
await this.peer?.handle(message, path);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
armGrace() {
|
|
456
|
+
clearTimeout(this.graceTimer);
|
|
457
|
+
if (this.transport && !this.leg && !this.transport.p2p) {
|
|
458
|
+
const transport = this.transport;
|
|
459
|
+
this.graceTimer = setTimeout(() => transport.close(), RELAY_GRACE_MS);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
scheduleRenewal(grantedMs = this.target.leaseMs ?? LEASE_MS) {
|
|
464
|
+
clearTimeout(this.renewTimer);
|
|
465
|
+
const baseRenew = this.target.renewMs ?? RENEW_MS;
|
|
466
|
+
const proportional = Math.max(1000, Math.floor(grantedMs * (11 / 12)));
|
|
467
|
+
this.renewTimer = setTimeout(() => void this.reconnect(true), Math.min(baseRenew, proportional));
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
scheduleReconnect() {
|
|
471
|
+
if (this.reconnectTimer || this.closed) return;
|
|
472
|
+
this.reconnectTimer = setTimeout(() => {
|
|
473
|
+
this.reconnectTimer = null;
|
|
474
|
+
if (!this.leg) void this.reconnect(false);
|
|
475
|
+
}, 1000);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
async reconnect(renew) {
|
|
479
|
+
if (this.reconnecting || this.closed || !this.secret) return;
|
|
480
|
+
this.reconnecting = true;
|
|
481
|
+
let next;
|
|
482
|
+
try {
|
|
483
|
+
if (this.refreshTarget) {
|
|
484
|
+
try { await this.refreshTarget(); } catch { /* ignore transient poll failure */ }
|
|
485
|
+
}
|
|
486
|
+
const dialedHostId = this.target.hostId;
|
|
487
|
+
try {
|
|
488
|
+
next = await this.connect(renew);
|
|
489
|
+
} catch (err) {
|
|
490
|
+
if (err?.code === 'HOST_OFFLINE' && this.target.hostId && this.target.hostId !== dialedHostId) {
|
|
491
|
+
next = await this.connect(renew);
|
|
492
|
+
} else {
|
|
493
|
+
throw err;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
const transport = this.transport;
|
|
497
|
+
if (transport) {
|
|
498
|
+
try {
|
|
499
|
+
const result = await this.exchange(next, 'binding', () => transport.control({
|
|
500
|
+
type: renew ? 'lease_renew' : 'bind_relay_leg', challenge: next.challenge,
|
|
501
|
+
}, next.path));
|
|
502
|
+
if (this.transport !== transport || !next.path.ready()) throw new Error('远程会话已结束');
|
|
503
|
+
if (renew && !result.renewed) throw new Error('远程续租未获确认');
|
|
504
|
+
const old = this.leg;
|
|
505
|
+
this.leg = next;
|
|
506
|
+
transport.setRelay(next.path);
|
|
507
|
+
clearTimeout(this.graceTimer);
|
|
508
|
+
if (old !== next) old?.ws.close();
|
|
509
|
+
this.onState(transport.p2p ? 'P2P' : 'Relay');
|
|
510
|
+
if (renew) {
|
|
511
|
+
transport.renewLease(result.leaseMs);
|
|
512
|
+
this.scheduleRenewal(result.leaseMs);
|
|
513
|
+
}
|
|
514
|
+
return;
|
|
515
|
+
} catch (error) {
|
|
516
|
+
if (error.code !== 'GENERATION_UNKNOWN') throw error;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
await this.authenticate(next, this.secret);
|
|
520
|
+
} catch (error) {
|
|
521
|
+
next?.ws.close();
|
|
522
|
+
if (error.code === 'AUTH_FAILED' && this.onKeyRotated) {
|
|
523
|
+
this.close(error);
|
|
524
|
+
await this.onKeyRotated(error);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
if ([401, 403].includes(error.status) || error.code === 'AUTH_FAILED' || error.code === 'FORBIDDEN') {
|
|
528
|
+
this.close(error);
|
|
529
|
+
await this.onRevoked(error);
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
const sessionValid = await Promise.resolve(this.checkSession?.()).catch(() => null);
|
|
533
|
+
if (sessionValid === false) {
|
|
534
|
+
this.close(error);
|
|
535
|
+
await this.onRevoked(error);
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
if (renew && !this.closed) {
|
|
539
|
+
clearTimeout(this.renewTimer);
|
|
540
|
+
this.renewTimer = setTimeout(() => void this.reconnect(true), 5000);
|
|
541
|
+
} else {
|
|
542
|
+
this.scheduleReconnect();
|
|
543
|
+
}
|
|
544
|
+
} finally {
|
|
545
|
+
this.reconnecting = false;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
retire(error) {
|
|
550
|
+
const old = this.transport;
|
|
551
|
+
this.transport = null;
|
|
552
|
+
const leg = this.leg;
|
|
553
|
+
this.leg = null;
|
|
554
|
+
leg?.ws.close();
|
|
555
|
+
clearTimeout(this.graceTimer);
|
|
556
|
+
clearInterval(this.rttTimer);
|
|
557
|
+
this.failActiveStreams(error, 1006, 'Remote generation ended');
|
|
558
|
+
void this.peer?.stop().catch(() => {});
|
|
559
|
+
this.peer = null;
|
|
560
|
+
old?.close(error);
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
async lock() {
|
|
564
|
+
await this.transport?.control({ type: 'close_session' }).catch(() => {});
|
|
565
|
+
this.close();
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
close(error = new Error('远程连接已关闭')) {
|
|
569
|
+
if (this.closed) return;
|
|
570
|
+
this.closed = true;
|
|
571
|
+
this.secret = undefined;
|
|
572
|
+
this.lifecycle.abort(error);
|
|
573
|
+
clearTimeout(this.renewTimer);
|
|
574
|
+
clearTimeout(this.reconnectTimer);
|
|
575
|
+
clearInterval(this.rttTimer);
|
|
576
|
+
this.retire(error);
|
|
577
|
+
for (const leg of this.legs) leg.ws.close();
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
sendAppFrame(streamId, msgType, payload, signal, generation = this.transport) {
|
|
581
|
+
if (!generation || this.transport !== generation || this.closed) {
|
|
582
|
+
return Promise.reject(new Error('远程会话已中断,未确认的操作结果未知'));
|
|
583
|
+
}
|
|
584
|
+
return generation.send(encodeClientFrame(streamId, msgType, payload), signal);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
dispatchAppFrame({ streamId, msgType, payload }) {
|
|
588
|
+
if (msgType >= MSG_HTTP_REQ_HEAD && msgType <= MSG_HTTP_RES_WINDOW) {
|
|
589
|
+
const entry = this.httpStreams.get(streamId);
|
|
590
|
+
if (!entry) return;
|
|
591
|
+
if (msgType === MSG_HTTP_RES_HEAD) {
|
|
592
|
+
let meta;
|
|
593
|
+
try {
|
|
594
|
+
meta = JSON.parse(textDecoder.decode(payload));
|
|
595
|
+
} catch (err) {
|
|
596
|
+
entry.fail(err);
|
|
597
|
+
this.httpStreams.delete(streamId);
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
entry.resolveHead(meta);
|
|
601
|
+
} else if (msgType === MSG_HTTP_RES_BODY) {
|
|
602
|
+
entry.pushBody(payload);
|
|
603
|
+
} else if (msgType === MSG_HTTP_RES_END) {
|
|
604
|
+
entry.finishBody();
|
|
605
|
+
this.httpStreams.delete(streamId);
|
|
606
|
+
} else if (msgType === MSG_HTTP_ABORT) {
|
|
607
|
+
const reason = payload.byteLength > 0 ? textDecoder.decode(payload) : 'HTTP stream aborted';
|
|
608
|
+
entry.fail(new Error(reason));
|
|
609
|
+
this.httpStreams.delete(streamId);
|
|
610
|
+
}
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
if (msgType >= MSG_WS_OPEN && msgType <= MSG_WS_CLOSE) {
|
|
615
|
+
const sock = this.wsStreams.get(streamId);
|
|
616
|
+
if (!sock) return;
|
|
617
|
+
if (msgType === MSG_WS_OPENED) {
|
|
618
|
+
let info = {};
|
|
619
|
+
if (payload.byteLength > 0) {
|
|
620
|
+
try { info = JSON.parse(textDecoder.decode(payload)); } catch { /* ignore */ }
|
|
621
|
+
}
|
|
622
|
+
sock._remoteOpen(info);
|
|
623
|
+
} else if (msgType === MSG_WS_DATA_TEXT || msgType === MSG_WS_DATA_BIN) {
|
|
624
|
+
const bytes = sock._fragments.push(msgType, payload);
|
|
625
|
+
if (bytes) sock._remoteMessage(msgType === MSG_WS_DATA_TEXT ? textDecoder.decode(bytes) : bytes.buffer);
|
|
626
|
+
} else if (msgType === MSG_WS_CLOSE) {
|
|
627
|
+
let info = { code: 1000, reason: '', wasClean: true };
|
|
628
|
+
if (payload.byteLength > 0) {
|
|
629
|
+
try { info = { ...info, ...JSON.parse(textDecoder.decode(payload)) }; } catch { /* ignore */ }
|
|
630
|
+
}
|
|
631
|
+
this.wsStreams.delete(streamId);
|
|
632
|
+
sock._remoteClose(info.code, info.reason, Boolean(info.wasClean));
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
async fetch(pathAndQuery, init = {}) {
|
|
638
|
+
const redirectMode = init.redirect || 'follow';
|
|
639
|
+
let currentPath = pathAndQuery;
|
|
640
|
+
let currentMethod = (init.method || 'GET').toUpperCase();
|
|
641
|
+
let currentHeaders = new Headers(init.headers || {});
|
|
642
|
+
let currentBody = init.body;
|
|
643
|
+
let bodyIsUnreplayableStream = false;
|
|
644
|
+
|
|
645
|
+
if (currentMethod !== 'GET' && currentMethod !== 'HEAD') {
|
|
646
|
+
const sourceReq = init._sourceRequest;
|
|
647
|
+
if (sourceReq && currentBody === undefined && sourceReq.body !== null) {
|
|
648
|
+
if (init.signal?.aborted) {
|
|
649
|
+
throw init.signal.reason ?? new DOMException('Aborted', 'AbortError');
|
|
650
|
+
}
|
|
651
|
+
const buf = await sourceReq.arrayBuffer();
|
|
652
|
+
if (buf.byteLength > MAX_REQUEST_BYTES) {
|
|
653
|
+
throw new Error('Remote request body is too large');
|
|
654
|
+
}
|
|
655
|
+
currentBody = new Uint8Array(buf);
|
|
656
|
+
} else if (typeof ReadableStream !== 'undefined' && currentBody instanceof ReadableStream) {
|
|
657
|
+
bodyIsUnreplayableStream = true;
|
|
658
|
+
} else if (currentBody !== undefined && currentBody !== null) {
|
|
659
|
+
const tmpReq = new Request('https://dsh.local/', {
|
|
660
|
+
method: currentMethod,
|
|
661
|
+
headers: currentHeaders,
|
|
662
|
+
body: currentBody,
|
|
663
|
+
});
|
|
664
|
+
tmpReq.headers.forEach((v, k) => {
|
|
665
|
+
if (!currentHeaders.has(k)) currentHeaders.set(k, v);
|
|
666
|
+
});
|
|
667
|
+
const buf = await tmpReq.arrayBuffer();
|
|
668
|
+
if (buf.byteLength > MAX_REQUEST_BYTES) {
|
|
669
|
+
throw new Error('Remote request body is too large');
|
|
670
|
+
}
|
|
671
|
+
currentBody = new Uint8Array(buf);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
const fetchExternal = init._externalFetch || nativeFetch;
|
|
676
|
+
|
|
677
|
+
for (let hop = 0; hop <= MAX_REDIRECT_HOPS; hop += 1) {
|
|
678
|
+
const resp = await this._fetchSingle(currentPath, {
|
|
679
|
+
...init,
|
|
680
|
+
_sourceRequest: undefined,
|
|
681
|
+
method: currentMethod,
|
|
682
|
+
body: currentBody,
|
|
683
|
+
headers: currentHeaders,
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
const isRedirect = resp.status === 301 || resp.status === 302 || resp.status === 303 ||
|
|
687
|
+
resp.status === 307 || resp.status === 308;
|
|
688
|
+
if (!isRedirect) return resp;
|
|
689
|
+
|
|
690
|
+
if (redirectMode === 'error') {
|
|
691
|
+
await resp.body?.cancel().catch(() => {});
|
|
692
|
+
throw new TypeError(`Unexpected redirect response (${resp.status})`);
|
|
693
|
+
}
|
|
694
|
+
if (redirectMode === 'manual') return resp;
|
|
695
|
+
|
|
696
|
+
const loc = resp.headers.get('location');
|
|
697
|
+
if (!loc) return resp;
|
|
698
|
+
|
|
699
|
+
if (hop >= MAX_REDIRECT_HOPS) {
|
|
700
|
+
await resp.body?.cancel().catch(() => {});
|
|
701
|
+
throw new TypeError('Too many redirects');
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
const target = resolveRedirectTarget(currentPath, loc);
|
|
705
|
+
if (!target) return resp;
|
|
706
|
+
await resp.body?.cancel().catch(() => {});
|
|
707
|
+
|
|
708
|
+
const shouldRewriteToGet = (resp.status === 303 && currentMethod !== 'GET' && currentMethod !== 'HEAD') ||
|
|
709
|
+
((resp.status === 301 || resp.status === 302) && currentMethod !== 'GET' && currentMethod !== 'HEAD');
|
|
710
|
+
|
|
711
|
+
if (shouldRewriteToGet) {
|
|
712
|
+
currentMethod = 'GET';
|
|
713
|
+
currentBody = undefined;
|
|
714
|
+
bodyIsUnreplayableStream = false;
|
|
715
|
+
stripBodyHeaders(currentHeaders);
|
|
716
|
+
} else if ((resp.status === 307 || resp.status === 308) && bodyIsUnreplayableStream) {
|
|
717
|
+
throw new TypeError('Cannot follow 307/308 redirect with non-replayable ReadableStream body');
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
if (target.kind === 'external') {
|
|
721
|
+
if (!fetchExternal) throw new Error('External redirect unavailable without native fetch');
|
|
722
|
+
let extUrl = target.url;
|
|
723
|
+
let extHeaders = sanitizeCrossOriginHeaders(currentHeaders);
|
|
724
|
+
let extMethod = currentMethod;
|
|
725
|
+
let extBody = currentBody;
|
|
726
|
+
|
|
727
|
+
if (!init._externalFetch) {
|
|
728
|
+
return await fetchExternal(extUrl, {
|
|
729
|
+
method: extMethod,
|
|
730
|
+
headers: extHeaders,
|
|
731
|
+
body: extMethod === 'GET' || extMethod === 'HEAD' ? undefined : extBody,
|
|
732
|
+
credentials: 'omit',
|
|
733
|
+
signal: init.signal,
|
|
734
|
+
redirect: (MAX_REDIRECT_HOPS - (hop + 1)) === 0 ? 'error' : 'follow',
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
for (let extHop = hop + 1; extHop <= MAX_REDIRECT_HOPS; extHop += 1) {
|
|
739
|
+
const remainingAfterThis = MAX_REDIRECT_HOPS - extHop;
|
|
740
|
+
const extResp = await fetchExternal(extUrl, {
|
|
741
|
+
method: extMethod,
|
|
742
|
+
headers: extHeaders,
|
|
743
|
+
body: extMethod === 'GET' || extMethod === 'HEAD' ? undefined : extBody,
|
|
744
|
+
credentials: 'omit',
|
|
745
|
+
signal: init.signal,
|
|
746
|
+
redirect: remainingAfterThis === 0 ? 'error' : 'manual',
|
|
747
|
+
});
|
|
748
|
+
if (extResp.type === 'opaqueredirect') {
|
|
749
|
+
if (extMethod !== 'GET' && extMethod !== 'HEAD') {
|
|
750
|
+
throw new TypeError('Cannot follow opaque redirect for non-idempotent request');
|
|
751
|
+
}
|
|
752
|
+
return await fetchExternal(extUrl, {
|
|
753
|
+
method: extMethod,
|
|
754
|
+
headers: extHeaders,
|
|
755
|
+
body: undefined,
|
|
756
|
+
credentials: 'omit',
|
|
757
|
+
signal: init.signal,
|
|
758
|
+
redirect: 'follow',
|
|
759
|
+
});
|
|
760
|
+
}
|
|
761
|
+
const isExtRedirect = extResp.status === 301 || extResp.status === 302 || extResp.status === 303 ||
|
|
762
|
+
extResp.status === 307 || extResp.status === 308;
|
|
763
|
+
const extLoc = extResp.headers.get('location');
|
|
764
|
+
if (!isExtRedirect || !extLoc) return extResp;
|
|
765
|
+
if (extHop >= MAX_REDIRECT_HOPS) {
|
|
766
|
+
await extResp.body?.cancel().catch(() => {});
|
|
767
|
+
throw new TypeError('Too many redirects');
|
|
768
|
+
}
|
|
769
|
+
const nextExt = new URL(extLoc, extUrl);
|
|
770
|
+
if (nextExt.protocol !== 'https:') return extResp;
|
|
771
|
+
await extResp.body?.cancel().catch(() => {});
|
|
772
|
+
if ((extResp.status === 303 || extResp.status === 301 || extResp.status === 302) &&
|
|
773
|
+
extMethod !== 'GET' && extMethod !== 'HEAD') {
|
|
774
|
+
extMethod = 'GET';
|
|
775
|
+
extBody = undefined;
|
|
776
|
+
stripBodyHeaders(extHeaders);
|
|
777
|
+
}
|
|
778
|
+
if (nextExt.origin !== new URL(extUrl).origin) {
|
|
779
|
+
extHeaders = sanitizeCrossOriginHeaders(extHeaders);
|
|
780
|
+
}
|
|
781
|
+
extUrl = nextExt.href;
|
|
782
|
+
}
|
|
783
|
+
throw new TypeError('Too many redirects');
|
|
784
|
+
}
|
|
785
|
+
currentPath = target.path;
|
|
786
|
+
}
|
|
787
|
+
throw new TypeError('Too many redirects');
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
async _fetchSingle(pathAndQuery, init = {}) {
|
|
791
|
+
const method = (init.method || 'GET').toUpperCase();
|
|
792
|
+
const signal = init.signal;
|
|
793
|
+
const useSubresourceQueue = Boolean(init.subresource && (method === 'GET' || method === 'HEAD'));
|
|
794
|
+
const releasePermit = useSubresourceQueue ? await this.subresourceSemaphore.acquire(signal) : null;
|
|
795
|
+
|
|
796
|
+
let permitReleased = false;
|
|
797
|
+
const freePermit = () => {
|
|
798
|
+
if (releasePermit && !permitReleased) {
|
|
799
|
+
permitReleased = true;
|
|
800
|
+
releasePermit();
|
|
801
|
+
}
|
|
802
|
+
};
|
|
803
|
+
|
|
804
|
+
try {
|
|
805
|
+
if (this.closed || !this.transport) {
|
|
806
|
+
throw new Error('dsh-remote: tunnel is not connected');
|
|
807
|
+
}
|
|
808
|
+
if (this.nextStreamId > 0xffffffff || this.httpStreams.size + this.wsStreams.size >= MAX_STREAMS) {
|
|
809
|
+
throw new Error('Too many remote streams');
|
|
810
|
+
}
|
|
811
|
+
if (typeof pathAndQuery !== 'string') throw new TypeError('远程请求需要相对路径');
|
|
812
|
+
if (!pathAndQuery.startsWith('/')) pathAndQuery = '/' + pathAndQuery;
|
|
813
|
+
const streamId = this.nextStreamId++;
|
|
814
|
+
const generation = this.transport;
|
|
815
|
+
|
|
816
|
+
const normalizedReq = new Request(new URL(pathAndQuery, 'https://dsh.local').href, {
|
|
817
|
+
method,
|
|
818
|
+
headers: init.headers,
|
|
819
|
+
body: method === 'GET' || method === 'HEAD' ? undefined : init.body,
|
|
820
|
+
duplex: 'half',
|
|
821
|
+
});
|
|
822
|
+
|
|
823
|
+
const headersObj = {};
|
|
824
|
+
normalizedReq.headers.forEach((value, key) => {
|
|
825
|
+
headersObj[key] = value;
|
|
826
|
+
});
|
|
827
|
+
|
|
828
|
+
let bodyBytes = new Uint8Array(0);
|
|
829
|
+
const abortReason = () => signal?.reason ?? new DOMException('Aborted', 'AbortError');
|
|
830
|
+
if (signal?.aborted) {
|
|
831
|
+
normalizedReq.body?.cancel(abortReason()).catch(() => {});
|
|
832
|
+
throw abortReason();
|
|
833
|
+
}
|
|
834
|
+
if (method !== 'GET' && method !== 'HEAD' && normalizedReq.body) {
|
|
835
|
+
const reader = normalizedReq.body.getReader();
|
|
836
|
+
const cancelStreamNonBlocking = (reason) => {
|
|
837
|
+
reader.cancel(reason).catch(() => {});
|
|
838
|
+
};
|
|
839
|
+
const onUploadAbort = () => {
|
|
840
|
+
cancelStreamNonBlocking(abortReason());
|
|
841
|
+
};
|
|
842
|
+
signal?.addEventListener('abort', onUploadAbort, { once: true });
|
|
843
|
+
const chunks = [];
|
|
844
|
+
let size = 0;
|
|
845
|
+
try {
|
|
846
|
+
for (;;) {
|
|
847
|
+
if (signal?.aborted) throw abortReason();
|
|
848
|
+
const { done, value } = await reader.read();
|
|
849
|
+
if (signal?.aborted) throw abortReason();
|
|
850
|
+
if (done) break;
|
|
851
|
+
size += value.byteLength;
|
|
852
|
+
if (size > MAX_REQUEST_BYTES) throw new Error('Remote request body is too large');
|
|
853
|
+
chunks.push(value);
|
|
854
|
+
}
|
|
855
|
+
} catch (err) {
|
|
856
|
+
if (!signal?.aborted) cancelStreamNonBlocking(err);
|
|
857
|
+
throw err;
|
|
858
|
+
} finally {
|
|
859
|
+
signal?.removeEventListener('abort', onUploadAbort);
|
|
860
|
+
try { reader.releaseLock(); } catch { /* ignore */ }
|
|
861
|
+
}
|
|
862
|
+
bodyBytes = new Uint8Array(size);
|
|
863
|
+
let offset = 0;
|
|
864
|
+
for (const chunk of chunks) {
|
|
865
|
+
bodyBytes.set(chunk, offset);
|
|
866
|
+
offset += chunk.byteLength;
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
const tunnel = this;
|
|
871
|
+
if (tunnel.transport !== generation) throw new Error('远程会话已结束,操作未提交');
|
|
872
|
+
const send = (type, payload) => tunnel.sendAppFrame(streamId, type, payload, signal, generation);
|
|
873
|
+
|
|
874
|
+
const requestedWindow = init.windowBytes !== undefined
|
|
875
|
+
? init.windowBytes
|
|
876
|
+
: (tunnel.target.windowBytes ?? DEFAULT_WINDOW_BYTES);
|
|
877
|
+
|
|
878
|
+
return await new Promise((resolveResponse, rejectResponse) => {
|
|
879
|
+
let settled = false;
|
|
880
|
+
let bodyController = null;
|
|
881
|
+
let streamClosed = false;
|
|
882
|
+
let ended = false;
|
|
883
|
+
let bufferedBytes = 0;
|
|
884
|
+
let flowControlEnabled = false;
|
|
885
|
+
let peerWindowRemaining = Number.isInteger(requestedWindow) && requestedWindow > 0 ? requestedWindow : 0;
|
|
886
|
+
let pendingWindowCredit = 0;
|
|
887
|
+
let windowSendInFlight = false;
|
|
888
|
+
let windowRetryTimer = null;
|
|
889
|
+
const pendingChunks = [];
|
|
890
|
+
let idleTimer = null;
|
|
891
|
+
|
|
892
|
+
const isBackpressurePaused = () => {
|
|
893
|
+
if (!flowControlEnabled || streamClosed || ended) return false;
|
|
894
|
+
if (tunnel.closed || tunnel.transport !== generation) return false;
|
|
895
|
+
const consumerFull = bodyController !== null && (bodyController.desiredSize ?? 1) <= 0;
|
|
896
|
+
return consumerFull || peerWindowRemaining <= 0;
|
|
897
|
+
};
|
|
898
|
+
|
|
899
|
+
const refreshIdleTimer = () => {
|
|
900
|
+
clearTimeout(idleTimer);
|
|
901
|
+
idleTimer = null;
|
|
902
|
+
if (streamClosed || ended) return;
|
|
903
|
+
if (isBackpressurePaused()) return;
|
|
904
|
+
idleTimer = setTimeout(() => {
|
|
905
|
+
if (isBackpressurePaused()) return;
|
|
906
|
+
tunnel.httpStreams.delete(streamId);
|
|
907
|
+
void tunnel.sendAppFrame(streamId, MSG_HTTP_ABORT, 'response idle timeout', undefined, generation).catch(() => {});
|
|
908
|
+
fail(new Error('Remote HTTP response timed out'));
|
|
909
|
+
}, tunnel.target.responseIdleMs ?? RESPONSE_IDLE_TIMEOUT_MS);
|
|
910
|
+
};
|
|
911
|
+
|
|
912
|
+
const cleanup = () => {
|
|
913
|
+
clearTimeout(idleTimer);
|
|
914
|
+
idleTimer = null;
|
|
915
|
+
clearTimeout(windowRetryTimer);
|
|
916
|
+
windowRetryTimer = null;
|
|
917
|
+
pendingChunks.length = 0;
|
|
918
|
+
bufferedBytes = 0;
|
|
919
|
+
if (signal && onAbort) {
|
|
920
|
+
signal.removeEventListener('abort', onAbort);
|
|
921
|
+
}
|
|
922
|
+
freePermit();
|
|
923
|
+
};
|
|
924
|
+
|
|
925
|
+
const fail = (err) => {
|
|
926
|
+
cleanup();
|
|
927
|
+
if (!settled) {
|
|
928
|
+
settled = true;
|
|
929
|
+
rejectResponse(err);
|
|
930
|
+
} else if (bodyController && !streamClosed) {
|
|
931
|
+
streamClosed = true;
|
|
932
|
+
try { bodyController.error(err); } catch { /* ignore */ }
|
|
933
|
+
}
|
|
934
|
+
};
|
|
935
|
+
|
|
936
|
+
const maybeSendWindowCredit = () => {
|
|
937
|
+
clearTimeout(windowRetryTimer);
|
|
938
|
+
windowRetryTimer = null;
|
|
939
|
+
if (!flowControlEnabled || streamClosed || ended || windowSendInFlight || pendingWindowCredit <= 0) return;
|
|
940
|
+
const maxRefill = Math.max(0, requestedWindow - peerWindowRemaining);
|
|
941
|
+
if (maxRefill <= 0) return;
|
|
942
|
+
const threshold = Math.min(WINDOW_REFILL_THRESHOLD, Math.max(1, Math.floor(requestedWindow / 2)));
|
|
943
|
+
if (pendingWindowCredit < threshold && pendingChunks.length > 0 && peerWindowRemaining > 0) return;
|
|
944
|
+
const credit = Math.min(pendingWindowCredit, maxRefill);
|
|
945
|
+
if (credit <= 0) return;
|
|
946
|
+
windowSendInFlight = true;
|
|
947
|
+
let enqueued = false;
|
|
948
|
+
void tunnel.sendAppFrame(streamId, MSG_HTTP_RES_WINDOW, encodeWindowUpdate(credit), undefined, generation)
|
|
949
|
+
.then(() => {
|
|
950
|
+
enqueued = true;
|
|
951
|
+
pendingWindowCredit = Math.max(0, pendingWindowCredit - credit);
|
|
952
|
+
peerWindowRemaining = Math.min(requestedWindow, peerWindowRemaining + credit);
|
|
953
|
+
})
|
|
954
|
+
.catch(() => {
|
|
955
|
+
})
|
|
956
|
+
.finally(() => {
|
|
957
|
+
windowSendInFlight = false;
|
|
958
|
+
if (!streamClosed && !ended && pendingWindowCredit > 0) {
|
|
959
|
+
const stillRoom = Math.max(0, requestedWindow - peerWindowRemaining);
|
|
960
|
+
if (stillRoom > 0 && (pendingWindowCredit >= threshold || peerWindowRemaining === 0)) {
|
|
961
|
+
if (enqueued) {
|
|
962
|
+
queueMicrotask(maybeSendWindowCredit);
|
|
963
|
+
} else if (!windowRetryTimer) {
|
|
964
|
+
windowRetryTimer = setTimeout(() => {
|
|
965
|
+
windowRetryTimer = null;
|
|
966
|
+
maybeSendWindowCredit();
|
|
967
|
+
}, 10);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
});
|
|
972
|
+
};
|
|
973
|
+
|
|
974
|
+
const flushToStream = () => {
|
|
975
|
+
while (bodyController && !streamClosed && pendingChunks.length > 0 && (bodyController.desiredSize ?? 1) > 0) {
|
|
976
|
+
const next = pendingChunks.shift();
|
|
977
|
+
bufferedBytes -= next.byteLength;
|
|
978
|
+
bodyController.enqueue(next);
|
|
979
|
+
if (flowControlEnabled) {
|
|
980
|
+
pendingWindowCredit += next.byteLength;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
maybeSendWindowCredit();
|
|
984
|
+
refreshIdleTimer();
|
|
985
|
+
if (ended && pendingChunks.length === 0 && bodyController && !streamClosed) {
|
|
986
|
+
streamClosed = true;
|
|
987
|
+
cleanup();
|
|
988
|
+
try { bodyController.close(); } catch { /* ignore */ }
|
|
989
|
+
}
|
|
990
|
+
};
|
|
991
|
+
|
|
992
|
+
refreshIdleTimer();
|
|
993
|
+
|
|
994
|
+
const maxBuf = tunnel.target.maxResponseBufferBytes ?? MAX_RESPONSE_BUFFER_BYTES;
|
|
995
|
+
const streamHighWater = Math.min(256 * 1024, maxBuf);
|
|
996
|
+
|
|
997
|
+
const entry = {
|
|
998
|
+
resolveHead(meta) {
|
|
999
|
+
if (settled) return;
|
|
1000
|
+
flowControlEnabled = Boolean(meta.flowControl && requestedWindow > 0);
|
|
1001
|
+
refreshIdleTimer();
|
|
1002
|
+
const status = Number(meta.status) || 200;
|
|
1003
|
+
const headers = new Headers(meta.headers || {});
|
|
1004
|
+
const emptyBody = status === 204 || status === 205 || status === 304 || method === 'HEAD';
|
|
1005
|
+
const stream = emptyBody ? null : new ReadableStream({
|
|
1006
|
+
start(controller) {
|
|
1007
|
+
bodyController = controller;
|
|
1008
|
+
flushToStream();
|
|
1009
|
+
},
|
|
1010
|
+
pull() {
|
|
1011
|
+
flushToStream();
|
|
1012
|
+
},
|
|
1013
|
+
cancel: () => {
|
|
1014
|
+
streamClosed = true;
|
|
1015
|
+
cleanup();
|
|
1016
|
+
tunnel.httpStreams.delete(streamId);
|
|
1017
|
+
void tunnel.sendAppFrame(streamId, MSG_HTTP_ABORT, 'cancelled', undefined, generation).catch(() => {});
|
|
1018
|
+
},
|
|
1019
|
+
}, { highWaterMark: streamHighWater, size: (chunk) => chunk.byteLength });
|
|
1020
|
+
if (emptyBody) {
|
|
1021
|
+
streamClosed = true;
|
|
1022
|
+
cleanup();
|
|
1023
|
+
}
|
|
1024
|
+
const response = new Response(stream, {
|
|
1025
|
+
status,
|
|
1026
|
+
statusText: meta.statusText || '',
|
|
1027
|
+
headers,
|
|
1028
|
+
});
|
|
1029
|
+
settled = true;
|
|
1030
|
+
resolveResponse(response);
|
|
1031
|
+
},
|
|
1032
|
+
pushBody(chunk) {
|
|
1033
|
+
if (streamClosed || ended) return;
|
|
1034
|
+
if (flowControlEnabled) {
|
|
1035
|
+
peerWindowRemaining = Math.max(0, peerWindowRemaining - chunk.byteLength);
|
|
1036
|
+
}
|
|
1037
|
+
const inStreamQueue = bodyController ? Math.max(0, streamHighWater - (bodyController.desiredSize ?? 0)) : 0;
|
|
1038
|
+
if (inStreamQueue + bufferedBytes + chunk.byteLength > maxBuf) {
|
|
1039
|
+
tunnel.httpStreams.delete(streamId);
|
|
1040
|
+
void tunnel.sendAppFrame(streamId, MSG_HTTP_ABORT, 'response buffer exceeded', undefined, generation).catch(() => {});
|
|
1041
|
+
fail(new Error('Remote HTTP response buffer exceeded'));
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
const copy = new Uint8Array(chunk);
|
|
1045
|
+
pendingChunks.push(copy);
|
|
1046
|
+
bufferedBytes += copy.byteLength;
|
|
1047
|
+
flushToStream();
|
|
1048
|
+
},
|
|
1049
|
+
finishBody() {
|
|
1050
|
+
if (!settled) { fail(new Error('Remote response was incomplete')); return; }
|
|
1051
|
+
ended = true;
|
|
1052
|
+
flushToStream();
|
|
1053
|
+
},
|
|
1054
|
+
fail,
|
|
1055
|
+
};
|
|
1056
|
+
|
|
1057
|
+
const onAbort = (reason) => {
|
|
1058
|
+
tunnel.httpStreams.delete(streamId);
|
|
1059
|
+
void tunnel.sendAppFrame(streamId, MSG_HTTP_ABORT, 'aborted', undefined, generation).catch(() => {});
|
|
1060
|
+
fail(signal?.reason || (reason instanceof Error ? reason : new DOMException('Aborted', 'AbortError')));
|
|
1061
|
+
};
|
|
1062
|
+
|
|
1063
|
+
if (signal?.aborted) {
|
|
1064
|
+
onAbort();
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
if (signal) {
|
|
1068
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
tunnel.httpStreams.set(streamId, entry);
|
|
1072
|
+
|
|
1073
|
+
void (async () => {
|
|
1074
|
+
try {
|
|
1075
|
+
const reqHead = {
|
|
1076
|
+
method,
|
|
1077
|
+
path: pathAndQuery,
|
|
1078
|
+
headers: headersObj,
|
|
1079
|
+
...(Number.isInteger(requestedWindow) && requestedWindow > 0 ? { windowBytes: requestedWindow } : {}),
|
|
1080
|
+
};
|
|
1081
|
+
await send(MSG_HTTP_REQ_HEAD, JSON.stringify(reqHead));
|
|
1082
|
+
for (let offset = 0; offset < bodyBytes.byteLength; offset += CHUNK_SIZE) {
|
|
1083
|
+
if (tunnel.closed || !tunnel.httpStreams.has(streamId)) return;
|
|
1084
|
+
await send(MSG_HTTP_REQ_BODY, bodyBytes.subarray(offset, offset + CHUNK_SIZE));
|
|
1085
|
+
}
|
|
1086
|
+
if (!tunnel.closed && tunnel.httpStreams.has(streamId)) {
|
|
1087
|
+
await send(MSG_HTTP_REQ_END);
|
|
1088
|
+
}
|
|
1089
|
+
} catch (err) {
|
|
1090
|
+
tunnel.httpStreams.delete(streamId);
|
|
1091
|
+
fail(err instanceof Error ? err : new Error(String(err)));
|
|
1092
|
+
}
|
|
1093
|
+
})();
|
|
1094
|
+
});
|
|
1095
|
+
} catch (err) {
|
|
1096
|
+
freePermit();
|
|
1097
|
+
throw err;
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
createWebSocket(targetUrl) {
|
|
1102
|
+
if (this.nextStreamId > 0xffffffff || this.httpStreams.size + this.wsStreams.size >= MAX_STREAMS) {
|
|
1103
|
+
throw new Error('Too many remote streams');
|
|
1104
|
+
}
|
|
1105
|
+
const streamId = this.nextStreamId++;
|
|
1106
|
+
const parsed = new URL(targetUrl, location.href);
|
|
1107
|
+
let pathAndQuery = `${parsed.pathname}${parsed.search}`;
|
|
1108
|
+
const appBase = new URL('./', location.href).pathname;
|
|
1109
|
+
if (pathAndQuery.startsWith(appBase)) {
|
|
1110
|
+
pathAndQuery = `/${pathAndQuery.slice(appBase.length)}`;
|
|
1111
|
+
}
|
|
1112
|
+
const sock = new TunnelWebSocket(this, streamId, targetUrl, pathAndQuery);
|
|
1113
|
+
this.wsStreams.set(streamId, sock);
|
|
1114
|
+
if (this.closed || !this.transport) {
|
|
1115
|
+
this.wsStreams.delete(streamId);
|
|
1116
|
+
queueMicrotask(() => sock._remoteClose(1006, 'Tunnel disconnected', false));
|
|
1117
|
+
} else {
|
|
1118
|
+
void this.sendAppFrame(streamId, MSG_WS_OPEN, JSON.stringify({ path: pathAndQuery })).catch(() => {
|
|
1119
|
+
this.wsStreams.delete(streamId);
|
|
1120
|
+
sock._remoteClose(1006, 'E2EE send failed', false);
|
|
1121
|
+
});
|
|
1122
|
+
}
|
|
1123
|
+
return sock;
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
export function createTunnelEventSource(tunnelFetch, options = {}) {
|
|
1128
|
+
const baseHref = options.baseHref || (typeof location !== 'undefined' ? location.href : 'https://dsh.local/');
|
|
1129
|
+
const NativeES = options.NativeEventSource !== undefined ? options.NativeEventSource : nativeEventSource;
|
|
1130
|
+
const appBasePath = options.appBasePath ?? new URL('./', baseHref).pathname;
|
|
1131
|
+
|
|
1132
|
+
class TunnelEventSource extends EventTarget {
|
|
1133
|
+
static CONNECTING = 0;
|
|
1134
|
+
static OPEN = 1;
|
|
1135
|
+
static CLOSED = 2;
|
|
1136
|
+
|
|
1137
|
+
constructor(rawUrl, init = {}) {
|
|
1138
|
+
super();
|
|
1139
|
+
const parsed = new URL(String(rawUrl), baseHref);
|
|
1140
|
+
const baseOrigin = new URL(baseHref).origin;
|
|
1141
|
+
const lowerPath = parsed.pathname.toLowerCase();
|
|
1142
|
+
const lowerBase = appBasePath.toLowerCase();
|
|
1143
|
+
const isPlatformReserved = lowerPath.startsWith('/_tiana/') ||
|
|
1144
|
+
lowerPath === '/_tiana' ||
|
|
1145
|
+
lowerPath.startsWith(`${lowerBase}_tiana/`) ||
|
|
1146
|
+
lowerPath === `${lowerBase}_tiana`;
|
|
1147
|
+
|
|
1148
|
+
if (parsed.origin !== baseOrigin || isPlatformReserved) {
|
|
1149
|
+
if (NativeES) {
|
|
1150
|
+
return new NativeES(parsed.href, init);
|
|
1151
|
+
}
|
|
1152
|
+
throw new Error(isPlatformReserved
|
|
1153
|
+
? 'Platform EventSource endpoint requires native EventSource'
|
|
1154
|
+
: 'Cross-origin EventSource is unavailable');
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
this.CONNECTING = 0;
|
|
1158
|
+
this.OPEN = 1;
|
|
1159
|
+
this.CLOSED = 2;
|
|
1160
|
+
this._url = parsed.href;
|
|
1161
|
+
this._withCredentials = Boolean(init?.withCredentials);
|
|
1162
|
+
this._readyState = 0;
|
|
1163
|
+
this._retryMs = 3000;
|
|
1164
|
+
this._lastEventId = '';
|
|
1165
|
+
this._abortController = null;
|
|
1166
|
+
this._reconnectTimer = null;
|
|
1167
|
+
this.onopen = null;
|
|
1168
|
+
this.onmessage = null;
|
|
1169
|
+
this.onerror = null;
|
|
1170
|
+
|
|
1171
|
+
let tunnelPath = `${parsed.pathname}${parsed.search}`;
|
|
1172
|
+
if (appBasePath !== '/' && tunnelPath.startsWith(appBasePath)) {
|
|
1173
|
+
tunnelPath = `/${tunnelPath.slice(appBasePath.length)}`;
|
|
1174
|
+
}
|
|
1175
|
+
this._tunnelPath = tunnelPath;
|
|
1176
|
+
void this._connect();
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
get url() { return this._url; }
|
|
1180
|
+
get withCredentials() { return this._withCredentials; }
|
|
1181
|
+
get readyState() { return this._readyState; }
|
|
1182
|
+
|
|
1183
|
+
_emit(type, event) {
|
|
1184
|
+
this.dispatchEvent(event);
|
|
1185
|
+
const handler = type === 'open' ? this.onopen : type === 'error' ? this.onerror : type === 'message' ? this.onmessage : null;
|
|
1186
|
+
if (typeof handler === 'function') {
|
|
1187
|
+
handler.call(this, event);
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
_failPermanently() {
|
|
1192
|
+
if (this._readyState === 2) return;
|
|
1193
|
+
this._readyState = 2;
|
|
1194
|
+
clearTimeout(this._reconnectTimer);
|
|
1195
|
+
this._reconnectTimer = null;
|
|
1196
|
+
this._abortController?.abort();
|
|
1197
|
+
this._abortController = null;
|
|
1198
|
+
this._emit('error', new Event('error'));
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
_scheduleReconnect() {
|
|
1202
|
+
if (this._readyState === 2) return;
|
|
1203
|
+
this._readyState = 0;
|
|
1204
|
+
this._emit('error', new Event('error'));
|
|
1205
|
+
if (this._readyState === 2) return;
|
|
1206
|
+
clearTimeout(this._reconnectTimer);
|
|
1207
|
+
this._reconnectTimer = setTimeout(() => {
|
|
1208
|
+
this._reconnectTimer = null;
|
|
1209
|
+
if (this._readyState !== 2) void this._connect();
|
|
1210
|
+
}, this._retryMs);
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
async _connect() {
|
|
1214
|
+
if (this._readyState === 2) return;
|
|
1215
|
+
const ac = new AbortController();
|
|
1216
|
+
this._abortController = ac;
|
|
1217
|
+
const headers = {
|
|
1218
|
+
Accept: 'text/event-stream',
|
|
1219
|
+
'Cache-Control': 'no-store',
|
|
1220
|
+
};
|
|
1221
|
+
if (this._lastEventId) {
|
|
1222
|
+
headers['Last-Event-ID'] = this._lastEventId;
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
let resp;
|
|
1226
|
+
try {
|
|
1227
|
+
resp = await tunnelFetch(this._tunnelPath, {
|
|
1228
|
+
method: 'GET',
|
|
1229
|
+
headers,
|
|
1230
|
+
signal: ac.signal,
|
|
1231
|
+
redirect: 'follow',
|
|
1232
|
+
});
|
|
1233
|
+
} catch {
|
|
1234
|
+
if (this._readyState === 2) return;
|
|
1235
|
+
this._scheduleReconnect();
|
|
1236
|
+
return;
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
if (this._readyState === 2) {
|
|
1240
|
+
await resp.body?.cancel().catch(() => {});
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
const contentType = String(resp.headers.get('content-type') || '').split(';', 1)[0].trim().toLowerCase();
|
|
1245
|
+
if (resp.status !== 200 || contentType !== 'text/event-stream' || !resp.body) {
|
|
1246
|
+
await resp.body?.cancel().catch(() => {});
|
|
1247
|
+
this._failPermanently();
|
|
1248
|
+
return;
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
this._readyState = 1;
|
|
1252
|
+
this._emit('open', new Event('open'));
|
|
1253
|
+
if (this._readyState === 2) {
|
|
1254
|
+
await resp.body?.cancel().catch(() => {});
|
|
1255
|
+
return;
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
const reader = resp.body.getReader();
|
|
1259
|
+
const decoder = new TextDecoder('utf-8');
|
|
1260
|
+
let buffer = '';
|
|
1261
|
+
let firstChunk = true;
|
|
1262
|
+
let skipLeadingLF = false;
|
|
1263
|
+
let eventType = '';
|
|
1264
|
+
let dataLines = [];
|
|
1265
|
+
let pendingLastEventId = this._lastEventId;
|
|
1266
|
+
|
|
1267
|
+
const dispatchEventBuffer = () => {
|
|
1268
|
+
if (this._readyState === 2) return;
|
|
1269
|
+
this._lastEventId = pendingLastEventId;
|
|
1270
|
+
if (dataLines.length === 0) {
|
|
1271
|
+
eventType = '';
|
|
1272
|
+
return;
|
|
1273
|
+
}
|
|
1274
|
+
const type = eventType || 'message';
|
|
1275
|
+
const data = dataLines.join('\n');
|
|
1276
|
+
eventType = '';
|
|
1277
|
+
dataLines = [];
|
|
1278
|
+
const ev = new MessageEvent(type, {
|
|
1279
|
+
data,
|
|
1280
|
+
origin: new URL(this._url).origin,
|
|
1281
|
+
lastEventId: this._lastEventId,
|
|
1282
|
+
});
|
|
1283
|
+
if (this._readyState === 2) return;
|
|
1284
|
+
this._emit(type, ev);
|
|
1285
|
+
};
|
|
1286
|
+
|
|
1287
|
+
const processLine = (line) => {
|
|
1288
|
+
if (this._readyState === 2) return;
|
|
1289
|
+
if (line === '') {
|
|
1290
|
+
dispatchEventBuffer();
|
|
1291
|
+
return;
|
|
1292
|
+
}
|
|
1293
|
+
if (line.startsWith(':')) {
|
|
1294
|
+
return; // SSE comment / keepalive
|
|
1295
|
+
}
|
|
1296
|
+
const colon = line.indexOf(':');
|
|
1297
|
+
let field;
|
|
1298
|
+
let value;
|
|
1299
|
+
if (colon === -1) {
|
|
1300
|
+
field = line;
|
|
1301
|
+
value = '';
|
|
1302
|
+
} else {
|
|
1303
|
+
field = line.slice(0, colon);
|
|
1304
|
+
value = line.slice(colon + 1);
|
|
1305
|
+
if (value.startsWith(' ')) value = value.slice(1);
|
|
1306
|
+
}
|
|
1307
|
+
if (field === 'data') {
|
|
1308
|
+
dataLines.push(value);
|
|
1309
|
+
} else if (field === 'event') {
|
|
1310
|
+
eventType = value;
|
|
1311
|
+
} else if (field === 'id') {
|
|
1312
|
+
if (!value.includes('\0')) {
|
|
1313
|
+
pendingLastEventId = value;
|
|
1314
|
+
}
|
|
1315
|
+
} else if (field === 'retry') {
|
|
1316
|
+
if (/^[0-9]+$/u.test(value)) {
|
|
1317
|
+
this._retryMs = Number.parseInt(value, 10);
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
};
|
|
1321
|
+
|
|
1322
|
+
const consumeText = (rawText) => {
|
|
1323
|
+
let text = rawText;
|
|
1324
|
+
if (skipLeadingLF && text.length > 0) {
|
|
1325
|
+
skipLeadingLF = false;
|
|
1326
|
+
if (text.charCodeAt(0) === 10) {
|
|
1327
|
+
text = text.slice(1);
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
if (!text) return;
|
|
1331
|
+
buffer += text;
|
|
1332
|
+
let start = 0;
|
|
1333
|
+
for (let i = 0; i < buffer.length; i += 1) {
|
|
1334
|
+
if (this._readyState === 2) break;
|
|
1335
|
+
const ch = buffer.charCodeAt(i);
|
|
1336
|
+
if (ch === 10) { // \n
|
|
1337
|
+
processLine(buffer.slice(start, i));
|
|
1338
|
+
start = i + 1;
|
|
1339
|
+
} else if (ch === 13) { // \r (standalone CR or start of CRLF)
|
|
1340
|
+
processLine(buffer.slice(start, i));
|
|
1341
|
+
if (this._readyState === 2) {
|
|
1342
|
+
start = i + 1;
|
|
1343
|
+
break;
|
|
1344
|
+
}
|
|
1345
|
+
if (i + 1 < buffer.length) {
|
|
1346
|
+
if (buffer.charCodeAt(i + 1) === 10) i += 1;
|
|
1347
|
+
} else {
|
|
1348
|
+
skipLeadingLF = true;
|
|
1349
|
+
}
|
|
1350
|
+
start = i + 1;
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
buffer = buffer.slice(start);
|
|
1354
|
+
};
|
|
1355
|
+
|
|
1356
|
+
try {
|
|
1357
|
+
while (this._readyState !== 2) {
|
|
1358
|
+
const { done, value } = await reader.read();
|
|
1359
|
+
if (done) {
|
|
1360
|
+
const tail = decoder.decode();
|
|
1361
|
+
if (tail) consumeText(tail);
|
|
1362
|
+
break;
|
|
1363
|
+
}
|
|
1364
|
+
let text = decoder.decode(value, { stream: true });
|
|
1365
|
+
if (firstChunk) {
|
|
1366
|
+
firstChunk = false;
|
|
1367
|
+
if (text.startsWith('\uFEFF')) text = text.slice(1);
|
|
1368
|
+
}
|
|
1369
|
+
consumeText(text);
|
|
1370
|
+
}
|
|
1371
|
+
} catch {
|
|
1372
|
+
} finally {
|
|
1373
|
+
try { await reader.cancel(); } catch { /* ignore */ }
|
|
1374
|
+
try { reader.releaseLock(); } catch { /* ignore */ }
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
if (this._readyState !== 2) {
|
|
1378
|
+
this._scheduleReconnect();
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
close() {
|
|
1383
|
+
if (this._readyState === 2) return;
|
|
1384
|
+
this._readyState = 2;
|
|
1385
|
+
clearTimeout(this._reconnectTimer);
|
|
1386
|
+
this._reconnectTimer = null;
|
|
1387
|
+
this._abortController?.abort();
|
|
1388
|
+
this._abortController = null;
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
return TunnelEventSource;
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
class TunnelWebSocket extends EventTarget {
|
|
1396
|
+
static CONNECTING = 0;
|
|
1397
|
+
static OPEN = 1;
|
|
1398
|
+
static CLOSING = 2;
|
|
1399
|
+
static CLOSED = 3;
|
|
1400
|
+
|
|
1401
|
+
constructor(tunnel, streamId, url, pathAndQuery) {
|
|
1402
|
+
super();
|
|
1403
|
+
this.CONNECTING = 0;
|
|
1404
|
+
this.OPEN = 1;
|
|
1405
|
+
this.CLOSING = 2;
|
|
1406
|
+
this.CLOSED = 3;
|
|
1407
|
+
this._tunnel = tunnel;
|
|
1408
|
+
this._generation = tunnel.transport;
|
|
1409
|
+
this._fragments = new FragmentReader();
|
|
1410
|
+
this._streamId = streamId;
|
|
1411
|
+
this.url = url;
|
|
1412
|
+
this._path = pathAndQuery;
|
|
1413
|
+
this.readyState = 0;
|
|
1414
|
+
this.protocol = '';
|
|
1415
|
+
this.extensions = '';
|
|
1416
|
+
this.bufferedAmount = 0;
|
|
1417
|
+
this._sendQueue = Promise.resolve();
|
|
1418
|
+
this._pendingFrames = 0;
|
|
1419
|
+
this.binaryType = 'blob';
|
|
1420
|
+
this.onopen = null;
|
|
1421
|
+
this.onmessage = null;
|
|
1422
|
+
this.onerror = null;
|
|
1423
|
+
this.onclose = null;
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
_emit(type, event) {
|
|
1427
|
+
this.dispatchEvent(event);
|
|
1428
|
+
const handler = this[`on${type}`];
|
|
1429
|
+
if (typeof handler === 'function') {
|
|
1430
|
+
handler.call(this, event);
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
_remoteOpen(info = {}) {
|
|
1435
|
+
if (this.readyState !== 0) return;
|
|
1436
|
+
this.readyState = 1;
|
|
1437
|
+
if (info.protocol) this.protocol = String(info.protocol);
|
|
1438
|
+
this._emit('open', new Event('open'));
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
_remoteMessage(data) {
|
|
1442
|
+
if (this.readyState !== 1) return;
|
|
1443
|
+
let payload = data;
|
|
1444
|
+
if (data instanceof ArrayBuffer && this.binaryType === 'blob') {
|
|
1445
|
+
payload = new Blob([data]);
|
|
1446
|
+
}
|
|
1447
|
+
this._emit('message', new MessageEvent('message', { data: payload }));
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
_remoteClose(code = 1000, reason = '', wasClean = true) {
|
|
1451
|
+
if (this.readyState === 3) return;
|
|
1452
|
+
const wasConnecting = this.readyState === 0;
|
|
1453
|
+
this.readyState = 3;
|
|
1454
|
+
if (wasConnecting && !wasClean) {
|
|
1455
|
+
this._emit('error', new Event('error'));
|
|
1456
|
+
}
|
|
1457
|
+
this._emit('close', new CloseEvent('close', { code, reason, wasClean }));
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
send(data) {
|
|
1461
|
+
if (this.readyState !== 1) {
|
|
1462
|
+
throw new DOMException('WebSocket is not open', 'InvalidStateError');
|
|
1463
|
+
}
|
|
1464
|
+
const size = typeof data === 'string' ? textEncoder.encode(data).byteLength : data.size ?? data.byteLength;
|
|
1465
|
+
if (!Number.isSafeInteger(size) || size > 16 * 1024 * 1024 ||
|
|
1466
|
+
this.bufferedAmount + size > 16 * 1024 * 1024 || this._pendingFrames >= 256) {
|
|
1467
|
+
this.close(4008, 'Remote socket buffer exceeded');
|
|
1468
|
+
return;
|
|
1469
|
+
}
|
|
1470
|
+
|
|
1471
|
+
this.bufferedAmount += size;
|
|
1472
|
+
this._pendingFrames++;
|
|
1473
|
+
this._sendQueue = this._sendQueue.then(async () => {
|
|
1474
|
+
if (this.readyState === 3) return;
|
|
1475
|
+
const type = typeof data === 'string' ? MSG_WS_DATA_TEXT : MSG_WS_DATA_BIN;
|
|
1476
|
+
const payload = data instanceof Blob ? await data.arrayBuffer() : data;
|
|
1477
|
+
if (this.readyState === 3) return;
|
|
1478
|
+
await sendFragments(payload, (part) => this._tunnel.sendAppFrame(this._streamId, type, part, undefined, this._generation));
|
|
1479
|
+
}).catch(() => {
|
|
1480
|
+
this._tunnel.wsStreams.delete(this._streamId);
|
|
1481
|
+
this._remoteClose(1006, '远程消息发送失败', false);
|
|
1482
|
+
}).finally(() => {
|
|
1483
|
+
this.bufferedAmount -= size;
|
|
1484
|
+
this._pendingFrames--;
|
|
1485
|
+
});
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
close(code = 1000, reason = '') {
|
|
1489
|
+
if (this.readyState === 2 || this.readyState === 3) return;
|
|
1490
|
+
this.readyState = 2;
|
|
1491
|
+
this._sendQueue = this._sendQueue.then(async () => {
|
|
1492
|
+
if (this.readyState === 3) return;
|
|
1493
|
+
await this._tunnel.sendAppFrame(this._streamId, MSG_WS_CLOSE, JSON.stringify({ code, reason }), undefined, this._generation);
|
|
1494
|
+
this._tunnel.wsStreams.delete(this._streamId);
|
|
1495
|
+
this._remoteClose(code, reason, true);
|
|
1496
|
+
}).catch(() => this._remoteClose(1006, '远程会话已结束', false));
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
function installModuleLoaderQueue() {
|
|
1501
|
+
const pendingQueue = [];
|
|
1502
|
+
globalThis.__ModuleLoader__ = {
|
|
1503
|
+
mode: 'queue',
|
|
1504
|
+
pendingQueue,
|
|
1505
|
+
load(registration) {
|
|
1506
|
+
pendingQueue.push(registration);
|
|
1507
|
+
},
|
|
1508
|
+
create(options) {
|
|
1509
|
+
if (this.mode !== 'queue') {
|
|
1510
|
+
throw new Error('client-modules: window.__ModuleLoader__.create called after module-system boot');
|
|
1511
|
+
}
|
|
1512
|
+
const clientModulesId = '@deepseek-ai/dsh-client-modules';
|
|
1513
|
+
const index = pendingQueue.findIndex((r) => r.id === clientModulesId);
|
|
1514
|
+
const registration = pendingQueue[index];
|
|
1515
|
+
if (registration === undefined) {
|
|
1516
|
+
throw new Error(`client-modules: HTML did not preload ${clientModulesId}/client.js`);
|
|
1517
|
+
}
|
|
1518
|
+
pendingQueue.splice(index, 1);
|
|
1519
|
+
const exports = registration.factory((specifier) => {
|
|
1520
|
+
throw new Error(`client-modules: ${clientModulesId}/client.js requested external "${specifier}" before the module system existed`);
|
|
1521
|
+
});
|
|
1522
|
+
if (typeof exports !== 'object' || exports === null || typeof exports.createClientModuleSystem !== 'function' || typeof exports.apply !== 'function') {
|
|
1523
|
+
throw new Error(`client-modules: ${clientModulesId}/client.js did not export the bootstrap module face`);
|
|
1524
|
+
}
|
|
1525
|
+
return exports.createClientModuleSystem(this, { id: registration.id, exports }, options);
|
|
1526
|
+
},
|
|
1527
|
+
};
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
function guardPluginServiceWorkers() {
|
|
1531
|
+
if (typeof navigator === 'undefined' || !navigator.serviceWorker) return;
|
|
1532
|
+
try {
|
|
1533
|
+
Object.defineProperty(navigator.serviceWorker, 'register', {
|
|
1534
|
+
configurable: true,
|
|
1535
|
+
writable: true,
|
|
1536
|
+
value() {
|
|
1537
|
+
return Promise.reject(
|
|
1538
|
+
new DOMException('Plugin Service Worker registration is disabled in dsh-remote', 'NotSupportedError'),
|
|
1539
|
+
);
|
|
1540
|
+
},
|
|
1541
|
+
});
|
|
1542
|
+
} catch {
|
|
1543
|
+
}
|
|
1544
|
+
}
|
|
1545
|
+
|
|
1546
|
+
async function setupServiceWorkerBridge(tunnel, appBasePath, signal) {
|
|
1547
|
+
if (!nativeSwRegister || typeof navigator === 'undefined' || !navigator.serviceWorker) {
|
|
1548
|
+
return { active: false, unbind: () => {}, getNavToken: () => '' };
|
|
1549
|
+
}
|
|
1550
|
+
const swUrl = assetUrl('./dsh-remote-sw.js');
|
|
1551
|
+
const bridgeAbort = new AbortController();
|
|
1552
|
+
const tabNavToken = Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
1553
|
+
let swPort = null;
|
|
1554
|
+
let workerTarget = null;
|
|
1555
|
+
let inFlightAttach = null;
|
|
1556
|
+
let currentNavToken = tabNavToken;
|
|
1557
|
+
let tornDown = false;
|
|
1558
|
+
|
|
1559
|
+
const onParentAbort = () => unbind();
|
|
1560
|
+
signal?.addEventListener('abort', onParentAbort, { once: true });
|
|
1561
|
+
|
|
1562
|
+
const unbind = () => {
|
|
1563
|
+
if (tornDown) return;
|
|
1564
|
+
tornDown = true; currentNavToken = ''; inFlightAttach = null;
|
|
1565
|
+
signal?.removeEventListener('abort', onParentAbort);
|
|
1566
|
+
bridgeAbort.abort();
|
|
1567
|
+
try { workerTarget?.postMessage({ type: 'dsh-remote:sw-unbind' }); } catch { /* ignore */ }
|
|
1568
|
+
try { swPort?.close(); } catch { /* ignore */ }
|
|
1569
|
+
swPort = null; workerTarget = null;
|
|
1570
|
+
};
|
|
1571
|
+
|
|
1572
|
+
const attachWorker = (worker, ackTimeoutMs = SW_READY_TIMEOUT_MS) => {
|
|
1573
|
+
if (!worker || tornDown || signal?.aborted || tunnel.closed) {
|
|
1574
|
+
return Promise.resolve(false);
|
|
1575
|
+
}
|
|
1576
|
+
if (inFlightAttach && workerTarget === worker) {
|
|
1577
|
+
return inFlightAttach;
|
|
1578
|
+
}
|
|
1579
|
+
workerTarget = worker;
|
|
1580
|
+
const channel = new MessageChannel();
|
|
1581
|
+
if (swPort) {
|
|
1582
|
+
try { swPort.close(); } catch { /* ignore */ }
|
|
1583
|
+
}
|
|
1584
|
+
const port = channel.port1;
|
|
1585
|
+
swPort = port;
|
|
1586
|
+
|
|
1587
|
+
const p = new Promise((resolveAck) => {
|
|
1588
|
+
let ackSettled = false;
|
|
1589
|
+
const settleAck = (ok) => {
|
|
1590
|
+
if (ackSettled) return;
|
|
1591
|
+
ackSettled = true;
|
|
1592
|
+
if (inFlightAttach === p) inFlightAttach = null;
|
|
1593
|
+
clearTimeout(ackTimer);
|
|
1594
|
+
bridgeAbort.signal.removeEventListener('abort', onBridgeAbort);
|
|
1595
|
+
resolveAck(ok);
|
|
1596
|
+
};
|
|
1597
|
+
const onBridgeAbort = () => settleAck(false);
|
|
1598
|
+
bridgeAbort.signal.addEventListener('abort', onBridgeAbort, { once: true });
|
|
1599
|
+
const ackTimer = setTimeout(() => settleAck(false), ackTimeoutMs);
|
|
1600
|
+
|
|
1601
|
+
port.onmessageerror = () => {
|
|
1602
|
+
if (swPort === port) {
|
|
1603
|
+
try { port.close(); } catch { /* ignore */ }
|
|
1604
|
+
swPort = null;
|
|
1605
|
+
}
|
|
1606
|
+
settleAck(false);
|
|
1607
|
+
};
|
|
1608
|
+
|
|
1609
|
+
port.onmessage = (event) => {
|
|
1610
|
+
const msg = event.data;
|
|
1611
|
+
if (!msg || typeof msg !== 'object') return;
|
|
1612
|
+
if (msg.type === 'dsh-remote:sw-bound') {
|
|
1613
|
+
if (typeof msg.navToken === 'string' && msg.navToken) currentNavToken = msg.navToken;
|
|
1614
|
+
settleAck(true);
|
|
1615
|
+
return;
|
|
1616
|
+
}
|
|
1617
|
+
if (msg.type !== 'fetch' || !event.ports || !event.ports[0]) return;
|
|
1618
|
+
const reqPort = event.ports[0];
|
|
1619
|
+
const ac = new AbortController();
|
|
1620
|
+
let reader = null;
|
|
1621
|
+
let pullDemand = 0;
|
|
1622
|
+
let reading = false;
|
|
1623
|
+
let aborted = false;
|
|
1624
|
+
|
|
1625
|
+
const finish = () => {
|
|
1626
|
+
aborted = true;
|
|
1627
|
+
ac.abort();
|
|
1628
|
+
try { reader?.cancel().catch(() => {}); } catch { /* ignore */ }
|
|
1629
|
+
try { reqPort.close(); } catch { /* ignore */ }
|
|
1630
|
+
};
|
|
1631
|
+
|
|
1632
|
+
const pump = async () => {
|
|
1633
|
+
if (reading || !reader || aborted) return;
|
|
1634
|
+
reading = true;
|
|
1635
|
+
try {
|
|
1636
|
+
while (pullDemand > 0 && !aborted) {
|
|
1637
|
+
const { done, value } = await reader.read();
|
|
1638
|
+
if (aborted) break;
|
|
1639
|
+
if (done) {
|
|
1640
|
+
reqPort.postMessage({ type: 'end' });
|
|
1641
|
+
finish();
|
|
1642
|
+
return;
|
|
1643
|
+
}
|
|
1644
|
+
pullDemand -= 1;
|
|
1645
|
+
const copy = new Uint8Array(value);
|
|
1646
|
+
reqPort.postMessage({ type: 'chunk', data: copy }, [copy.buffer]);
|
|
1647
|
+
}
|
|
1648
|
+
} catch (err) {
|
|
1649
|
+
if (!aborted) {
|
|
1650
|
+
try { reqPort.postMessage({ type: 'error', message: err instanceof Error ? err.message : String(err) }); } catch { /* ignore */ }
|
|
1651
|
+
finish();
|
|
1652
|
+
}
|
|
1653
|
+
} finally {
|
|
1654
|
+
reading = false;
|
|
1655
|
+
}
|
|
1656
|
+
};
|
|
1657
|
+
|
|
1658
|
+
reqPort.onmessageerror = () => finish();
|
|
1659
|
+
reqPort.onmessage = (ev) => {
|
|
1660
|
+
const sub = ev.data;
|
|
1661
|
+
if (!sub) return;
|
|
1662
|
+
if (sub.type === 'abort') {
|
|
1663
|
+
finish();
|
|
1664
|
+
} else if (sub.type === 'pull') {
|
|
1665
|
+
pullDemand += 1;
|
|
1666
|
+
void pump();
|
|
1667
|
+
}
|
|
1668
|
+
};
|
|
1669
|
+
reqPort.start?.();
|
|
1670
|
+
|
|
1671
|
+
void (async () => {
|
|
1672
|
+
try {
|
|
1673
|
+
const resp = await tunnel.fetch(msg.path, {
|
|
1674
|
+
method: msg.method,
|
|
1675
|
+
headers: msg.headers,
|
|
1676
|
+
body: msg.body && msg.body.byteLength > 0 ? msg.body : undefined,
|
|
1677
|
+
redirect: msg.redirect || 'follow',
|
|
1678
|
+
signal: ac.signal,
|
|
1679
|
+
subresource: msg.method === 'GET' || msg.method === 'HEAD',
|
|
1680
|
+
});
|
|
1681
|
+
if (aborted) {
|
|
1682
|
+
await resp.body?.cancel().catch(() => {});
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
const headersOut = {};
|
|
1686
|
+
resp.headers.forEach((v, k) => { headersOut[k] = v; });
|
|
1687
|
+
reqPort.postMessage({
|
|
1688
|
+
type: 'head',
|
|
1689
|
+
status: resp.status,
|
|
1690
|
+
statusText: resp.statusText,
|
|
1691
|
+
headers: headersOut,
|
|
1692
|
+
});
|
|
1693
|
+
if (!resp.body || msg.method === 'HEAD' || resp.status === 204 || resp.status === 205 || resp.status === 304) {
|
|
1694
|
+
reqPort.postMessage({ type: 'end' });
|
|
1695
|
+
finish();
|
|
1696
|
+
return;
|
|
1697
|
+
}
|
|
1698
|
+
reader = resp.body.getReader();
|
|
1699
|
+
void pump();
|
|
1700
|
+
} catch (err) {
|
|
1701
|
+
if (!aborted) {
|
|
1702
|
+
try { reqPort.postMessage({ type: 'error', message: err instanceof Error ? err.message : String(err) }); } catch { /* ignore */ }
|
|
1703
|
+
finish();
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
})();
|
|
1707
|
+
};
|
|
1708
|
+
port.start?.();
|
|
1709
|
+
try {
|
|
1710
|
+
worker.postMessage({ type: 'dsh-remote:sw-bind', navToken: tabNavToken }, [channel.port2]);
|
|
1711
|
+
} catch {
|
|
1712
|
+
settleAck(false);
|
|
1713
|
+
}
|
|
1714
|
+
});
|
|
1715
|
+
inFlightAttach = p;
|
|
1716
|
+
return p;
|
|
1717
|
+
};
|
|
1718
|
+
|
|
1719
|
+
let raceTimer = null;
|
|
1720
|
+
const setupAbort = new AbortController();
|
|
1721
|
+
const onParentOrBridgeAbort = () => setupAbort.abort();
|
|
1722
|
+
bridgeAbort.signal.addEventListener('abort', onParentOrBridgeAbort, { once: true });
|
|
1723
|
+
|
|
1724
|
+
try {
|
|
1725
|
+
const bound = await Promise.race([
|
|
1726
|
+
(async () => {
|
|
1727
|
+
const reg = await nativeSwRegister(swUrl, { scope: appBasePath, updateViaCache: 'none' });
|
|
1728
|
+
if (setupAbort.signal.aborted || tornDown) return false;
|
|
1729
|
+
if (!navigator.serviceWorker.controller) {
|
|
1730
|
+
await new Promise((resolve) => {
|
|
1731
|
+
const onDone = () => {
|
|
1732
|
+
navigator.serviceWorker.removeEventListener('controllerchange', onDone);
|
|
1733
|
+
setupAbort.signal.removeEventListener('abort', onDone);
|
|
1734
|
+
resolve();
|
|
1735
|
+
};
|
|
1736
|
+
navigator.serviceWorker.addEventListener('controllerchange', onDone, { once: true });
|
|
1737
|
+
setupAbort.signal.addEventListener('abort', onDone, { once: true });
|
|
1738
|
+
if (navigator.serviceWorker.controller || setupAbort.signal.aborted) onDone();
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
if (setupAbort.signal.aborted || tornDown) return false;
|
|
1742
|
+
const controller = navigator.serviceWorker.controller || reg.active;
|
|
1743
|
+
if (!controller) return false;
|
|
1744
|
+
const acked = await attachWorker(controller, SW_READY_TIMEOUT_MS);
|
|
1745
|
+
if (!acked || setupAbort.signal.aborted || tornDown) return false;
|
|
1746
|
+
|
|
1747
|
+
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
|
1748
|
+
if (navigator.serviceWorker.controller && !tornDown && !signal?.aborted) {
|
|
1749
|
+
void attachWorker(navigator.serviceWorker.controller, 2500);
|
|
1750
|
+
}
|
|
1751
|
+
}, { signal: bridgeAbort.signal });
|
|
1752
|
+
navigator.serviceWorker.addEventListener('message', (event) => {
|
|
1753
|
+
if (event.data?.type === 'dsh-remote:sw-request-port' && !tornDown && !signal?.aborted && !tunnel.closed) {
|
|
1754
|
+
const reqTok = event.data.requestedNavToken;
|
|
1755
|
+
if (reqTok && reqTok !== tabNavToken) return;
|
|
1756
|
+
const target = navigator.serviceWorker.controller || event.source || reg.active;
|
|
1757
|
+
if (target && typeof target.postMessage === 'function') {
|
|
1758
|
+
void attachWorker(target, 2500);
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
}, { signal: bridgeAbort.signal });
|
|
1762
|
+
navigator.serviceWorker.startMessages?.();
|
|
1763
|
+
return Boolean(navigator.serviceWorker.controller);
|
|
1764
|
+
})(),
|
|
1765
|
+
new Promise((resolve) => {
|
|
1766
|
+
raceTimer = setTimeout(() => {
|
|
1767
|
+
setupAbort.abort();
|
|
1768
|
+
resolve(false);
|
|
1769
|
+
}, SW_READY_TIMEOUT_MS);
|
|
1770
|
+
}),
|
|
1771
|
+
]);
|
|
1772
|
+
clearTimeout(raceTimer);
|
|
1773
|
+
raceTimer = null;
|
|
1774
|
+
bridgeAbort.signal.removeEventListener('abort', onParentOrBridgeAbort);
|
|
1775
|
+
if (!bound) {
|
|
1776
|
+
unbind();
|
|
1777
|
+
return { active: false, unbind: () => {}, getNavToken: () => '' };
|
|
1778
|
+
}
|
|
1779
|
+
return { active: true, unbind, getNavToken: () => (tornDown ? '' : currentNavToken) };
|
|
1780
|
+
} catch {
|
|
1781
|
+
clearTimeout(raceTimer);
|
|
1782
|
+
bridgeAbort.signal.removeEventListener('abort', onParentOrBridgeAbort);
|
|
1783
|
+
unbind();
|
|
1784
|
+
return { active: false, unbind: () => {}, getNavToken: () => '' };
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
let activeSwNavRewriter = null;
|
|
1789
|
+
let activeWorkerContext = null;
|
|
1790
|
+
let iframeNavHooksInstalled = false;
|
|
1791
|
+
let workerHooksInstalled = false;
|
|
1792
|
+
const blobRegistry = new Map();
|
|
1793
|
+
const nativeCreateObjectURL = typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function'
|
|
1794
|
+
? URL.createObjectURL.bind(URL)
|
|
1795
|
+
: null;
|
|
1796
|
+
const nativeRevokeObjectURL = typeof URL !== 'undefined' && typeof URL.revokeObjectURL === 'function'
|
|
1797
|
+
? URL.revokeObjectURL.bind(URL)
|
|
1798
|
+
: null;
|
|
1799
|
+
const NativeWorker = typeof globalThis.Worker === 'function' ? globalThis.Worker : null;
|
|
1800
|
+
|
|
1801
|
+
function buildWorkerPrelude(navToken, origin, appBasePath) {
|
|
1802
|
+
const baseNoSlash = appBasePath.length > 1 && appBasePath.endsWith('/') ? appBasePath.slice(0, -1) : appBasePath;
|
|
1803
|
+
return `(()=>{const T=${JSON.stringify(navToken)},O=${JSON.stringify(origin)},B=${JSON.stringify(appBasePath)},BN=${JSON.stringify(baseNoSlash)},BH=O+B;` +
|
|
1804
|
+
'const skip=(p)=>p.startsWith("/_tiana/")||p.startsWith(B+"_tiana/")||p.startsWith(B+"assets/")||p.startsWith("/brand/")||p==="/favicon.ico";' +
|
|
1805
|
+
'const rw=(r)=>{try{const u=new URL(String(r),BH);if((u.protocol!=="http:"&&u.protocol!=="https:")||u.origin!==O||skip(u.pathname))return r;' +
|
|
1806
|
+
'if(B!=="/"&&!u.pathname.startsWith(B)&&u.pathname!==BN){const np=BN+(u.pathname.startsWith("/")?u.pathname:"/"+u.pathname);if(skip(np))return r;u.pathname=np;}' +
|
|
1807
|
+
'u.searchParams.set("__dsh_nav",T);return u.href;}catch{return r;}};' +
|
|
1808
|
+
'if(typeof self.fetch==="function"){const nf=self.fetch.bind(self);self.fetch=(i,n)=>{' +
|
|
1809
|
+
'if(typeof i==="string"||i instanceof URL)return nf(rw(i),n);' +
|
|
1810
|
+
'if(i instanceof Request){const next=rw(i.url);return next===i.url?nf(i,n):nf(new Request(next,i),n);}return nf(i,n);};}' +
|
|
1811
|
+
'if(typeof self.XMLHttpRequest==="function"){const po=self.XMLHttpRequest.prototype.open;self.XMLHttpRequest.prototype.open=function(m,u,...a){return po.call(this,m,rw(u),...a);};}' +
|
|
1812
|
+
'})();';
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
function installSwScopeAlignment(appBasePath, signal, getNavToken) {
|
|
1816
|
+
if (typeof document === 'undefined') return;
|
|
1817
|
+
const appBaseNoSlash = appBasePath.length > 1 && appBasePath.endsWith('/') ? appBasePath.slice(0, -1) : appBasePath;
|
|
1818
|
+
|
|
1819
|
+
const isPlatformOrPassthroughPath = (pathname) => (
|
|
1820
|
+
pathname === appBasePath ||
|
|
1821
|
+
pathname === appBaseNoSlash ||
|
|
1822
|
+
pathname.startsWith(`${appBasePath}_tiana/`) ||
|
|
1823
|
+
pathname.startsWith('/_tiana/') ||
|
|
1824
|
+
pathname.startsWith(`${appBasePath}assets/`) ||
|
|
1825
|
+
pathname.startsWith('/brand/') ||
|
|
1826
|
+
pathname === '/favicon.ico'
|
|
1827
|
+
);
|
|
1828
|
+
|
|
1829
|
+
const rewriteIfNeeded = (rawUrl) => {
|
|
1830
|
+
if (typeof rawUrl !== 'string' || !rawUrl) return rawUrl;
|
|
1831
|
+
let parsed;
|
|
1832
|
+
try {
|
|
1833
|
+
parsed = new URL(rawUrl, location.href);
|
|
1834
|
+
} catch {
|
|
1835
|
+
return rawUrl;
|
|
1836
|
+
}
|
|
1837
|
+
if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:') || parsed.origin !== location.origin) {
|
|
1838
|
+
return rawUrl;
|
|
1839
|
+
}
|
|
1840
|
+
let pathname = parsed.pathname;
|
|
1841
|
+
if (isPlatformOrPassthroughPath(pathname)) {
|
|
1842
|
+
return rawUrl;
|
|
1843
|
+
}
|
|
1844
|
+
if (appBasePath !== '/' && !pathname.startsWith(appBasePath) && pathname !== appBaseNoSlash) {
|
|
1845
|
+
pathname = `${appBaseNoSlash}${pathname.startsWith('/') ? pathname : `/${pathname}`}`;
|
|
1846
|
+
if (isPlatformOrPassthroughPath(pathname)) {
|
|
1847
|
+
return rawUrl;
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
const navToken = typeof getNavToken === 'function' ? getNavToken() : '';
|
|
1851
|
+
const params = new URLSearchParams(parsed.search);
|
|
1852
|
+
if (navToken) {
|
|
1853
|
+
params.set('__dsh_nav', navToken);
|
|
1854
|
+
}
|
|
1855
|
+
const qs = params.toString();
|
|
1856
|
+
return `${pathname}${qs ? `?${qs}` : ''}${parsed.hash}`;
|
|
1857
|
+
};
|
|
1858
|
+
|
|
1859
|
+
activeSwNavRewriter = rewriteIfNeeded;
|
|
1860
|
+
activeWorkerContext = { appBasePath, getNavToken, rewriteIfNeeded };
|
|
1861
|
+
signal?.addEventListener('abort', () => {
|
|
1862
|
+
if (activeSwNavRewriter === rewriteIfNeeded) activeSwNavRewriter = null;
|
|
1863
|
+
if (activeWorkerContext?.getNavToken === getNavToken) activeWorkerContext = null;
|
|
1864
|
+
}, { once: true });
|
|
1865
|
+
|
|
1866
|
+
document.addEventListener('click', (ev) => {
|
|
1867
|
+
const anchor = ev.target?.closest?.('a[download]');
|
|
1868
|
+
if (!anchor) return;
|
|
1869
|
+
const rawHref = anchor.getAttribute('href');
|
|
1870
|
+
if (!rawHref || rawHref.startsWith('blob:') || rawHref.startsWith('data:')) return;
|
|
1871
|
+
const next = rewriteIfNeeded(rawHref);
|
|
1872
|
+
if (!next || next === rawHref) return;
|
|
1873
|
+
ev.preventDefault();
|
|
1874
|
+
const dlUrl = new URL(next, location.href);
|
|
1875
|
+
dlUrl.searchParams.set('__dsh_dl', (anchor.getAttribute('download') || '').trim() || '1');
|
|
1876
|
+
const f = document.createElement('iframe');
|
|
1877
|
+
f.style.display = 'none';
|
|
1878
|
+
f.setAttribute('aria-hidden', 'true');
|
|
1879
|
+
f.src = dlUrl.href;
|
|
1880
|
+
document.body.appendChild(f);
|
|
1881
|
+
setTimeout(() => f.remove(), 60_000);
|
|
1882
|
+
}, { capture: true, signal });
|
|
1883
|
+
|
|
1884
|
+
if (!iframeNavHooksInstalled && typeof HTMLIFrameElement !== 'undefined') {
|
|
1885
|
+
iframeNavHooksInstalled = true;
|
|
1886
|
+
const desc = Object.getOwnPropertyDescriptor(HTMLIFrameElement.prototype, 'src');
|
|
1887
|
+
if (desc?.set && desc.configurable) {
|
|
1888
|
+
Object.defineProperty(HTMLIFrameElement.prototype, 'src', {
|
|
1889
|
+
configurable: true,
|
|
1890
|
+
enumerable: desc.enumerable,
|
|
1891
|
+
get: desc.get,
|
|
1892
|
+
set(val) {
|
|
1893
|
+
const next = activeSwNavRewriter ? activeSwNavRewriter(String(val)) : String(val);
|
|
1894
|
+
return desc.set.call(this, next);
|
|
1895
|
+
},
|
|
1896
|
+
});
|
|
1897
|
+
}
|
|
1898
|
+
const origSetAttr = HTMLIFrameElement.prototype.setAttribute;
|
|
1899
|
+
HTMLIFrameElement.prototype.setAttribute = function setAttribute(name, value) {
|
|
1900
|
+
if (String(name).toLowerCase() === 'src') {
|
|
1901
|
+
const next = activeSwNavRewriter ? activeSwNavRewriter(String(value)) : String(value);
|
|
1902
|
+
return origSetAttr.call(this, name, next);
|
|
1903
|
+
}
|
|
1904
|
+
return origSetAttr.call(this, name, value);
|
|
1905
|
+
};
|
|
1906
|
+
}
|
|
1907
|
+
|
|
1908
|
+
if (!workerHooksInstalled && NativeWorker && nativeCreateObjectURL && nativeRevokeObjectURL) {
|
|
1909
|
+
workerHooksInstalled = true;
|
|
1910
|
+
URL.createObjectURL = function createObjectURL(obj) {
|
|
1911
|
+
const url = nativeCreateObjectURL(obj);
|
|
1912
|
+
if (obj instanceof Blob) {
|
|
1913
|
+
if (blobRegistry.size > 256) {
|
|
1914
|
+
const oldest = blobRegistry.keys().next().value;
|
|
1915
|
+
if (oldest) blobRegistry.delete(oldest);
|
|
1916
|
+
}
|
|
1917
|
+
blobRegistry.set(url, obj);
|
|
1918
|
+
}
|
|
1919
|
+
return url;
|
|
1920
|
+
};
|
|
1921
|
+
URL.revokeObjectURL = function revokeObjectURL(url) {
|
|
1922
|
+
blobRegistry.delete(String(url));
|
|
1923
|
+
return nativeRevokeObjectURL(url);
|
|
1924
|
+
};
|
|
1925
|
+
globalThis.Worker = function DshRemoteWorker(scriptURL, options) {
|
|
1926
|
+
const ctx = activeWorkerContext;
|
|
1927
|
+
const navToken = ctx?.getNavToken?.() || '';
|
|
1928
|
+
if (!navToken) return new NativeWorker(scriptURL, options);
|
|
1929
|
+
const raw = scriptURL instanceof URL ? scriptURL.href : String(scriptURL);
|
|
1930
|
+
const prelude = buildWorkerPrelude(navToken, location.origin, ctx.appBasePath);
|
|
1931
|
+
const origBlob = blobRegistry.get(raw);
|
|
1932
|
+
if (origBlob) {
|
|
1933
|
+
const wrappedBlob = new Blob([prelude, '\n', origBlob], { type: origBlob.type || 'text/javascript' });
|
|
1934
|
+
const wrappedUrl = nativeCreateObjectURL(wrappedBlob);
|
|
1935
|
+
const w = new NativeWorker(wrappedUrl, options);
|
|
1936
|
+
const t = setTimeout(() => { try { nativeRevokeObjectURL(wrappedUrl); } catch { /* ignore */ } }, 10_000);
|
|
1937
|
+
t.unref?.();
|
|
1938
|
+
return w;
|
|
1939
|
+
}
|
|
1940
|
+
try {
|
|
1941
|
+
const parsed = new URL(raw, location.href);
|
|
1942
|
+
if ((parsed.protocol === 'http:' || parsed.protocol === 'https:') && parsed.origin === location.origin) {
|
|
1943
|
+
const rewritten = ctx.rewriteIfNeeded(parsed.href);
|
|
1944
|
+
const abs = new URL(rewritten, location.href).href;
|
|
1945
|
+
const loaderLine = options?.type === 'module'
|
|
1946
|
+
? `import ${JSON.stringify(abs)};`
|
|
1947
|
+
: `importScripts(${JSON.stringify(abs)});`;
|
|
1948
|
+
const wrappedBlob = new Blob([prelude, '\n', loaderLine], { type: 'text/javascript' });
|
|
1949
|
+
const wrappedUrl = nativeCreateObjectURL(wrappedBlob);
|
|
1950
|
+
const w = new NativeWorker(wrappedUrl, options);
|
|
1951
|
+
const t = setTimeout(() => { try { nativeRevokeObjectURL(wrappedUrl); } catch { /* ignore */ } }, 10_000);
|
|
1952
|
+
t.unref?.();
|
|
1953
|
+
return w;
|
|
1954
|
+
}
|
|
1955
|
+
} catch {
|
|
1956
|
+
}
|
|
1957
|
+
return new NativeWorker(scriptURL, options);
|
|
1958
|
+
};
|
|
1959
|
+
globalThis.Worker.prototype = NativeWorker.prototype;
|
|
1960
|
+
}
|
|
1961
|
+
}
|
|
1962
|
+
|
|
1963
|
+
let bypassWrappedFetch = 0;
|
|
1964
|
+
|
|
1965
|
+
function wrapGlobalFetch(tunnelFetch, loadAsset) {
|
|
1966
|
+
const appBasePath = new URL('./', location.href).pathname;
|
|
1967
|
+
const appRootNoSlash = appBasePath.length > 1 && appBasePath.endsWith('/') ? appBasePath.slice(0, -1) : appBasePath;
|
|
1968
|
+
const assetsBase = new URL('./', import.meta.url).pathname;
|
|
1969
|
+
|
|
1970
|
+
globalThis.fetch = (input, init) => {
|
|
1971
|
+
if (bypassWrappedFetch > 0) return nativeFetch(input, init);
|
|
1972
|
+
const rawUrl = typeof input === 'string'
|
|
1973
|
+
? input
|
|
1974
|
+
: input instanceof URL
|
|
1975
|
+
? input.href
|
|
1976
|
+
: input instanceof Request
|
|
1977
|
+
? input.url
|
|
1978
|
+
: String(input);
|
|
1979
|
+
|
|
1980
|
+
let parsed;
|
|
1981
|
+
try {
|
|
1982
|
+
parsed = new URL(rawUrl, location.href);
|
|
1983
|
+
} catch {
|
|
1984
|
+
return nativeFetch(input, init);
|
|
1985
|
+
}
|
|
1986
|
+
|
|
1987
|
+
if (parsed.protocol === 'blob:' && parsed.origin === location.origin) {
|
|
1988
|
+
const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();
|
|
1989
|
+
const requestSignal = init?.signal ?? (input instanceof Request ? input.signal : undefined);
|
|
1990
|
+
const asset = loadAsset(parsed.href, method, requestSignal);
|
|
1991
|
+
if (asset) return asset;
|
|
1992
|
+
}
|
|
1993
|
+
if (parsed.protocol !== 'blob:' && parsed.origin === location.origin) {
|
|
1994
|
+
let path = parsed.pathname;
|
|
1995
|
+
const isTianaAsset = path.startsWith(assetsBase);
|
|
1996
|
+
const isTianaInternal = path.startsWith(`${appBasePath}_tiana/`) || path.startsWith('/_tiana/') || path === appBasePath || path === appRootNoSlash;
|
|
1997
|
+
if (!isTianaAsset && !isTianaInternal) {
|
|
1998
|
+
if (appBasePath.endsWith('/') && path.startsWith(appBasePath)) {
|
|
1999
|
+
path = `/${path.slice(appBasePath.length)}`;
|
|
2000
|
+
}
|
|
2001
|
+
const mergedInit = input instanceof Request
|
|
2002
|
+
? {
|
|
2003
|
+
method: init?.method || input.method,
|
|
2004
|
+
headers: init?.headers || input.headers,
|
|
2005
|
+
body: init?.body !== undefined ? init.body : undefined,
|
|
2006
|
+
_sourceRequest: init?.body === undefined ? input : undefined,
|
|
2007
|
+
signal: init?.signal || input.signal,
|
|
2008
|
+
redirect: init?.redirect || input.redirect,
|
|
2009
|
+
}
|
|
2010
|
+
: init;
|
|
2011
|
+
return tunnelFetch(`${path}${parsed.search}`, mergedInit);
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
|
|
2015
|
+
return nativeFetch(input, init);
|
|
2016
|
+
};
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
function endpoint(name) {
|
|
2020
|
+
return new URL('_tiana/' + name, new URL('./', location.href));
|
|
2021
|
+
}
|
|
2022
|
+
|
|
2023
|
+
async function verifyOwner(config, signal) {
|
|
2024
|
+
const reply = await nativeFetch(endpoint('session'), {
|
|
2025
|
+
credentials: 'same-origin', cache: 'no-store', signal,
|
|
2026
|
+
});
|
|
2027
|
+
if (!reply.ok) throw Object.assign(new Error('无法确认 Tiana 应用身份'), { status: reply.status });
|
|
2028
|
+
const session = await reply.json();
|
|
2029
|
+
if (session.is_app_owner !== true ||
|
|
2030
|
+
(session.web_id !== undefined && session.web_id !== config.webId) ||
|
|
2031
|
+
typeof session.user?.user_id !== 'string' || !session.user.user_id ||
|
|
2032
|
+
typeof session.tenant_id !== 'string' || !session.tenant_id ||
|
|
2033
|
+
(typeof session.app_tenant_id === 'string' && session.app_tenant_id !== '' && session.app_tenant_id !== session.tenant_id)) {
|
|
2034
|
+
throw Object.assign(new Error('仅应用所有者可以连接 DSH'), { status: 403 });
|
|
2035
|
+
}
|
|
2036
|
+
return {
|
|
2037
|
+
webId: config.webId,
|
|
2038
|
+
hostId: config.defaultHostId || '',
|
|
2039
|
+
ownerUserId: session.user.user_id,
|
|
2040
|
+
tenantId: session.tenant_id,
|
|
2041
|
+
};
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
async function waitForSocket(ws, signal) {
|
|
2045
|
+
return new Promise((resolve, reject) => {
|
|
2046
|
+
const finish = (error) => {
|
|
2047
|
+
ws.removeEventListener('open', open);
|
|
2048
|
+
ws.removeEventListener('error', failed);
|
|
2049
|
+
ws.removeEventListener('close', failed);
|
|
2050
|
+
signal.removeEventListener('abort', abort);
|
|
2051
|
+
if (error) {
|
|
2052
|
+
ws.close();
|
|
2053
|
+
reject(error);
|
|
2054
|
+
} else resolve(ws);
|
|
2055
|
+
};
|
|
2056
|
+
const open = () => finish();
|
|
2057
|
+
const failed = () => finish(new Error('无法连接 Relay'));
|
|
2058
|
+
const abort = () => finish(signal.reason);
|
|
2059
|
+
ws.addEventListener('open', open, { once: true });
|
|
2060
|
+
ws.addEventListener('error', failed, { once: true });
|
|
2061
|
+
ws.addEventListener('close', failed, { once: true });
|
|
2062
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
2063
|
+
if (signal.aborted) abort();
|
|
2064
|
+
});
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
async function openRelaySocket(tianaContext, config, hostId, renew, signal) {
|
|
2068
|
+
const clientPath = hostId ? '/client?' + new URLSearchParams({ host_id: hostId }) : '/client';
|
|
2069
|
+
if (tianaContext?.functions?.websocket && config.functionId && !renew) {
|
|
2070
|
+
return tianaContext.functions.websocket(config.functionId, clientPath, { signal });
|
|
2071
|
+
}
|
|
2072
|
+
if (config.functionId && tianaContext?.functions?.websocket) {
|
|
2073
|
+
const headers = { 'X-Tiana-Bootstrap': '1', 'X-Request-ID': 'req-' + crypto.randomUUID(), 'Content-Type': 'application/json' };
|
|
2074
|
+
const proof = document.cookie.split('; ').find((item) => item.startsWith('__Host-tiana_site_csrf='));
|
|
2075
|
+
if (proof) headers['X-CSRF-Token'] = decodeURIComponent(proof.slice(proof.indexOf('=') + 1));
|
|
2076
|
+
const reply = await nativeFetch(endpoint('function-connection'), {
|
|
2077
|
+
method: 'POST', credentials: 'same-origin', cache: 'no-store', headers, signal,
|
|
2078
|
+
body: JSON.stringify({ instance_id: config.functionId }),
|
|
2079
|
+
});
|
|
2080
|
+
if (!reply.ok) throw Object.assign(new Error('应用续租未获授权'), { status: reply.status });
|
|
2081
|
+
const grant = await reply.json();
|
|
2082
|
+
const origin = new URL(grant.origin);
|
|
2083
|
+
if (origin.protocol !== 'https:' || origin.username || origin.password || origin.pathname !== '/' ||
|
|
2084
|
+
origin.search || origin.hash || typeof grant.token !== 'string' || !grant.token) {
|
|
2085
|
+
throw new Error('后端授权响应无效');
|
|
2086
|
+
}
|
|
2087
|
+
const url = new URL(clientPath, origin);
|
|
2088
|
+
url.protocol = 'wss:';
|
|
2089
|
+
url.searchParams.set('access_token', grant.token);
|
|
2090
|
+
return waitForSocket(new WebSocket(url), signal);
|
|
2091
|
+
}
|
|
2092
|
+
if (config.localRelayUrl) {
|
|
2093
|
+
const url = new URL(clientPath, config.localRelayUrl);
|
|
2094
|
+
if (!['127.0.0.1', '[::1]', 'localhost'].includes(url.hostname)) throw new Error('测试 Relay 必须使用回环地址');
|
|
2095
|
+
url.protocol = url.protocol === 'https:' ? 'wss:' : url.protocol === 'http:' ? 'ws:' : url.protocol;
|
|
2096
|
+
return waitForSocket(new WebSocket(url), signal);
|
|
2097
|
+
}
|
|
2098
|
+
throw new Error('应用缺少 Relay 配置');
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
async function pollRelayInfo(tianaContext, config, signal) {
|
|
2102
|
+
const pollSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(3000)]) : AbortSignal.timeout(3000);
|
|
2103
|
+
try {
|
|
2104
|
+
if (typeof tianaContext?.functions?.fetch === 'function' && config.functionId) {
|
|
2105
|
+
for (const ep of ['/status', '/info']) {
|
|
2106
|
+
let pending;
|
|
2107
|
+
bypassWrappedFetch += 1;
|
|
2108
|
+
try {
|
|
2109
|
+
pending = tianaContext.functions.fetch(config.functionId, ep, { cache: 'no-store', signal: pollSignal });
|
|
2110
|
+
} finally {
|
|
2111
|
+
bypassWrappedFetch -= 1;
|
|
2112
|
+
}
|
|
2113
|
+
const resp = await pending;
|
|
2114
|
+
if (resp.ok) return await resp.json();
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
if (config.localRelayUrl) {
|
|
2118
|
+
for (const ep of ['/status', '/info']) {
|
|
2119
|
+
const url = new URL(ep, config.localRelayUrl);
|
|
2120
|
+
const resp = await nativeFetch(url, { cache: 'no-store', signal: pollSignal });
|
|
2121
|
+
if (resp.ok) return await resp.json();
|
|
2122
|
+
}
|
|
2123
|
+
}
|
|
2124
|
+
} catch {
|
|
2125
|
+
}
|
|
2126
|
+
return null;
|
|
2127
|
+
}
|
|
2128
|
+
|
|
2129
|
+
function ensureRootElement() {
|
|
2130
|
+
const existingApp = document.getElementById('app');
|
|
2131
|
+
if (existingApp) {
|
|
2132
|
+
existingApp.remove();
|
|
2133
|
+
}
|
|
2134
|
+
let root = document.getElementById('root');
|
|
2135
|
+
if (!root) {
|
|
2136
|
+
root = document.createElement('div');
|
|
2137
|
+
root.id = 'root';
|
|
2138
|
+
document.body.prepend(root);
|
|
2139
|
+
}
|
|
2140
|
+
return root;
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2143
|
+
export function keyName(identity) {
|
|
2144
|
+
return 'dsh-remote:v2:key:' + [identity.webId, identity.ownerUserId, identity.hostId].join(':');
|
|
2145
|
+
}
|
|
2146
|
+
|
|
2147
|
+
export function purgeWebKeys(webId, keepKey = null, storage = globalThis.localStorage) {
|
|
2148
|
+
if (!webId || !storage) return 0;
|
|
2149
|
+
let removed = 0;
|
|
2150
|
+
try {
|
|
2151
|
+
const prefix = `dsh-remote:v2:key:${webId}:`;
|
|
2152
|
+
const toRemove = [];
|
|
2153
|
+
for (let i = 0; i < storage.length; i++) {
|
|
2154
|
+
const k = storage.key(i);
|
|
2155
|
+
if (k && k.startsWith(prefix) && k !== keepKey) toRemove.push(k);
|
|
2156
|
+
}
|
|
2157
|
+
for (const k of toRemove) {
|
|
2158
|
+
storage.removeItem(k);
|
|
2159
|
+
removed++;
|
|
2160
|
+
}
|
|
2161
|
+
} catch {
|
|
2162
|
+
}
|
|
2163
|
+
return removed;
|
|
2164
|
+
}
|
|
2165
|
+
|
|
2166
|
+
export function readStoredKey(key, { local = globalThis.localStorage } = {}) {
|
|
2167
|
+
try {
|
|
2168
|
+
const loc = local?.getItem(key);
|
|
2169
|
+
if (loc) return { secret: loc, remembered: true };
|
|
2170
|
+
} catch { /* ignore */ }
|
|
2171
|
+
return { secret: null, remembered: false };
|
|
2172
|
+
}
|
|
2173
|
+
|
|
2174
|
+
export function writeStoredKey(key, value, { remember = false, session = globalThis.sessionStorage, local = globalThis.localStorage } = {}) {
|
|
2175
|
+
try { session?.removeItem(key); } catch { /* ignore */ }
|
|
2176
|
+
try { local?.removeItem(key); } catch { /* ignore */ }
|
|
2177
|
+
if (!value || !remember) return;
|
|
2178
|
+
try {
|
|
2179
|
+
local?.setItem(key, value);
|
|
2180
|
+
} catch {
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2184
|
+
async function runRemoteSession(container, tianaContext, shellUI, options = {}) {
|
|
2185
|
+
const lifetime = new AbortController();
|
|
2186
|
+
const signal = lifetime.signal;
|
|
2187
|
+
const oneTimeHashKey = options._skipHashConsume ? null : consumeLegacyPairingHash();
|
|
2188
|
+
let loader;
|
|
2189
|
+
let tunnel;
|
|
2190
|
+
let identity;
|
|
2191
|
+
let channel;
|
|
2192
|
+
let swBridge = { active: false, unbind: () => {} };
|
|
2193
|
+
let reconnectBanner = null;
|
|
2194
|
+
let reconnectDelayTimer = null;
|
|
2195
|
+
let currentStateLabel = '连接中';
|
|
2196
|
+
let currentFingerprint = '';
|
|
2197
|
+
let currentRemembered = false;
|
|
2198
|
+
let inMemorySecret = null;
|
|
2199
|
+
let lockedOut = false;
|
|
2200
|
+
const subscribers = new Set();
|
|
2201
|
+
|
|
2202
|
+
const emitSnapshot = () => {
|
|
2203
|
+
const snap = getStatusSnapshot();
|
|
2204
|
+
for (const fn of subscribers) {
|
|
2205
|
+
try { fn(snap); } catch { /* ignore */ }
|
|
2206
|
+
}
|
|
2207
|
+
};
|
|
2208
|
+
|
|
2209
|
+
const getStatusSnapshot = () => ({
|
|
2210
|
+
isRemote: true,
|
|
2211
|
+
transportState: currentStateLabel,
|
|
2212
|
+
transport: currentStateLabel === 'P2P' ? 'p2p' : 'relay',
|
|
2213
|
+
rttMs: tunnel?.rttMs ?? null,
|
|
2214
|
+
hostId: identity?.hostId || '',
|
|
2215
|
+
hostName: identity?.hostName || identity?.hostId || '',
|
|
2216
|
+
webId: identity?.webId || '',
|
|
2217
|
+
fingerprint: currentFingerprint,
|
|
2218
|
+
remembered: currentRemembered,
|
|
2219
|
+
swActive: Boolean(swBridge.active),
|
|
2220
|
+
});
|
|
2221
|
+
|
|
2222
|
+
const applyAuthoritativeHost = (info) => {
|
|
2223
|
+
if (!info || !identity) return;
|
|
2224
|
+
if (info.hostId) {
|
|
2225
|
+
identity.hostId = info.hostId;
|
|
2226
|
+
identity.hostName = info.hostName || info.hostId;
|
|
2227
|
+
} else if (info.hostName) {
|
|
2228
|
+
identity.hostName = info.hostName;
|
|
2229
|
+
}
|
|
2230
|
+
if (info.hostDigest) {
|
|
2231
|
+
identity.hostDigest = info.hostDigest;
|
|
2232
|
+
}
|
|
2233
|
+
if (tunnel?.target) {
|
|
2234
|
+
if (identity.hostId) tunnel.target.hostId = identity.hostId;
|
|
2235
|
+
if (identity.hostName) tunnel.target.hostName = identity.hostName;
|
|
2236
|
+
if (identity.hostDigest) tunnel.target.hostDigest = identity.hostDigest;
|
|
2237
|
+
}
|
|
2238
|
+
};
|
|
2239
|
+
|
|
2240
|
+
const close = () => {
|
|
2241
|
+
lifetime.abort(new Error('远程工作台已关闭'));
|
|
2242
|
+
clearTimeout(reconnectDelayTimer);
|
|
2243
|
+
inMemorySecret = null;
|
|
2244
|
+
swBridge.unbind();
|
|
2245
|
+
tunnel?.close();
|
|
2246
|
+
loader?.close();
|
|
2247
|
+
reconnectBanner?.remove();
|
|
2248
|
+
try { channel?.close(); } catch { /* ignore */ }
|
|
2249
|
+
};
|
|
2250
|
+
|
|
2251
|
+
addEventListener('pagehide', close, { once: true });
|
|
2252
|
+
addEventListener('pageshow', (event) => {
|
|
2253
|
+
if (event.persisted && signal.aborted) location.reload();
|
|
2254
|
+
});
|
|
2255
|
+
|
|
2256
|
+
try {
|
|
2257
|
+
shellUI.showLoading('正在连接本地 DSH 主机…', '正在核验 Tiana 应用归属与端到端加密通道。');
|
|
2258
|
+
const config = await fetchConfig();
|
|
2259
|
+
const { webId } = config;
|
|
2260
|
+
if (!webId || (tianaContext?.appId && tianaContext.appId !== webId)) {
|
|
2261
|
+
throw new Error('缺少当前应用标识配置');
|
|
2262
|
+
}
|
|
2263
|
+
try {
|
|
2264
|
+
identity = await verifyOwner(config, signal);
|
|
2265
|
+
} catch (error) {
|
|
2266
|
+
if ([401, 403].includes(error.status)) {
|
|
2267
|
+
purgeWebKeys(webId, null, globalThis.localStorage);
|
|
2268
|
+
purgeWebKeys(webId, null, globalThis.sessionStorage);
|
|
2269
|
+
await clearWebFrontendCache(webId);
|
|
2270
|
+
}
|
|
2271
|
+
throw error;
|
|
2272
|
+
}
|
|
2273
|
+
|
|
2274
|
+
const lockPulseStorageKey = `dsh-remote:v2:lock-pulse:${webId}`;
|
|
2275
|
+
|
|
2276
|
+
const lockAndReturnToUnlock = async ({ broadcast = false, sendHostLock = false, notice = '' } = {}) => {
|
|
2277
|
+
if (lockedOut) return;
|
|
2278
|
+
lockedOut = true;
|
|
2279
|
+
inMemorySecret = null;
|
|
2280
|
+
currentRemembered = false;
|
|
2281
|
+
purgeWebKeys(webId, null, globalThis.localStorage);
|
|
2282
|
+
purgeWebKeys(webId, null, globalThis.sessionStorage);
|
|
2283
|
+
|
|
2284
|
+
if (broadcast) {
|
|
2285
|
+
try { channel?.postMessage({ type: 'dsh-remote:lock', appId: webId }); } catch { /* ignore */ }
|
|
2286
|
+
try {
|
|
2287
|
+
globalThis.localStorage?.setItem(lockPulseStorageKey, String(Date.now()));
|
|
2288
|
+
globalThis.localStorage?.removeItem(lockPulseStorageKey);
|
|
2289
|
+
} catch { /* ignore */ }
|
|
2290
|
+
}
|
|
2291
|
+
|
|
2292
|
+
swBridge.unbind();
|
|
2293
|
+
if (sendHostLock && tunnel) {
|
|
2294
|
+
await tunnel.lock().catch(() => {});
|
|
2295
|
+
}
|
|
2296
|
+
close();
|
|
2297
|
+
shellUI.destroyAll();
|
|
2298
|
+
await clearWebFrontendCache(webId).catch(() => {});
|
|
2299
|
+
const rootNode = document.getElementById('root');
|
|
2300
|
+
if (rootNode) rootNode.replaceChildren();
|
|
2301
|
+
|
|
2302
|
+
void shellUI.promptUnlock({
|
|
2303
|
+
hostId: identity?.hostId,
|
|
2304
|
+
hostName: identity?.hostName,
|
|
2305
|
+
errorMessage: notice,
|
|
2306
|
+
defaultRemember: true,
|
|
2307
|
+
}).then((nextUnlock) => {
|
|
2308
|
+
void runRemoteSession(container, tianaContext, shellUI, {
|
|
2309
|
+
...options,
|
|
2310
|
+
_skipHashConsume: true,
|
|
2311
|
+
_initialSecret: nextUnlock.secret,
|
|
2312
|
+
_initialRemember: nextUnlock.remember,
|
|
2313
|
+
});
|
|
2314
|
+
});
|
|
2315
|
+
};
|
|
2316
|
+
|
|
2317
|
+
try {
|
|
2318
|
+
if (typeof BroadcastChannel === 'function') {
|
|
2319
|
+
channel = new BroadcastChannel('dsh-remote:v2:' + webId);
|
|
2320
|
+
channel.addEventListener('message', (event) => {
|
|
2321
|
+
const msg = event.data;
|
|
2322
|
+
if (!msg || typeof msg !== 'object') return;
|
|
2323
|
+
if ((msg.type === 'dsh-remote:lock' && (!msg.appId || msg.appId === webId)) ||
|
|
2324
|
+
msg.type === 'purge' || msg.type === 'rotate') {
|
|
2325
|
+
void lockAndReturnToUnlock({
|
|
2326
|
+
broadcast: false,
|
|
2327
|
+
sendHostLock: false,
|
|
2328
|
+
notice: msg.notice || '工作台已在其他标签页锁定,请重新输入配对密钥解锁。',
|
|
2329
|
+
});
|
|
2330
|
+
}
|
|
2331
|
+
}, { signal });
|
|
2332
|
+
}
|
|
2333
|
+
} catch {
|
|
2334
|
+
channel = null;
|
|
2335
|
+
}
|
|
2336
|
+
|
|
2337
|
+
const forget = () => lockAndReturnToUnlock({
|
|
2338
|
+
broadcast: true,
|
|
2339
|
+
sendHostLock: true,
|
|
2340
|
+
notice: '',
|
|
2341
|
+
});
|
|
2342
|
+
|
|
2343
|
+
const clearCacheAndReload = async () => {
|
|
2344
|
+
swBridge.unbind();
|
|
2345
|
+
await clearWebFrontendCache(webId);
|
|
2346
|
+
location.reload();
|
|
2347
|
+
};
|
|
2348
|
+
|
|
2349
|
+
const handleKeyRotated = () => lockAndReturnToUnlock({
|
|
2350
|
+
broadcast: true,
|
|
2351
|
+
sendHostLock: false,
|
|
2352
|
+
notice: '主机已轮换配对密钥,请输入新的配对密钥重新解锁。',
|
|
2353
|
+
});
|
|
2354
|
+
|
|
2355
|
+
const revoked = () => lockAndReturnToUnlock({
|
|
2356
|
+
broadcast: true,
|
|
2357
|
+
sendHostLock: false,
|
|
2358
|
+
notice: 'Tiana 应用会话已失效,请重新验证后解锁。',
|
|
2359
|
+
});
|
|
2360
|
+
|
|
2361
|
+
const checkSession = async () => {
|
|
2362
|
+
try {
|
|
2363
|
+
const current = await verifyOwner(config, AbortSignal.any([signal, AbortSignal.timeout(5000)]));
|
|
2364
|
+
return current.ownerUserId === identity.ownerUserId && current.tenantId === identity.tenantId;
|
|
2365
|
+
} catch (error) {
|
|
2366
|
+
if ([401, 403].includes(error?.status)) return false;
|
|
2367
|
+
return null;
|
|
2368
|
+
}
|
|
2369
|
+
};
|
|
2370
|
+
|
|
2371
|
+
document.addEventListener('visibilitychange', () => {
|
|
2372
|
+
if (document.visibilityState !== 'visible') return;
|
|
2373
|
+
void checkSession().then((valid) => {
|
|
2374
|
+
if (valid === false) return revoked();
|
|
2375
|
+
});
|
|
2376
|
+
}, { signal });
|
|
2377
|
+
|
|
2378
|
+
let hostOnlineResolver = null;
|
|
2379
|
+
const onStateChange = (label) => {
|
|
2380
|
+
const prev = currentStateLabel;
|
|
2381
|
+
currentStateLabel = label;
|
|
2382
|
+
emitSnapshot();
|
|
2383
|
+
if (!reconnectBanner) return;
|
|
2384
|
+
if (label === '正在重连') {
|
|
2385
|
+
clearTimeout(reconnectDelayTimer);
|
|
2386
|
+
reconnectDelayTimer = setTimeout(() => {
|
|
2387
|
+
if (currentStateLabel === '正在重连') reconnectBanner?.showReconnecting();
|
|
2388
|
+
}, RECONNECT_BANNER_DELAY_MS);
|
|
2389
|
+
} else if (label === 'P2P' || label === 'Relay') {
|
|
2390
|
+
clearTimeout(reconnectDelayTimer);
|
|
2391
|
+
if (prev === '正在重连') reconnectBanner.showRecovered();
|
|
2392
|
+
else reconnectBanner.hide();
|
|
2393
|
+
}
|
|
2394
|
+
};
|
|
2395
|
+
|
|
2396
|
+
const initialInfo = await pollRelayInfo(tianaContext, config, signal);
|
|
2397
|
+
if (initialInfo?.paired && initialInfo?.hostId) {
|
|
2398
|
+
applyAuthoritativeHost(initialInfo);
|
|
2399
|
+
}
|
|
2400
|
+
|
|
2401
|
+
tunnel = new TunnelClient(
|
|
2402
|
+
(renew, relaySignal, targetHostId) => openRelaySocket(tianaContext, config, targetHostId || identity.hostId, renew, relaySignal),
|
|
2403
|
+
{ ...identity, renewMs: options?.renewalMs, leaseMs: options?.leaseMs },
|
|
2404
|
+
onStateChange,
|
|
2405
|
+
revoked,
|
|
2406
|
+
checkSession,
|
|
2407
|
+
{
|
|
2408
|
+
onHostChanged: (info) => {
|
|
2409
|
+
applyAuthoritativeHost(info);
|
|
2410
|
+
emitSnapshot();
|
|
2411
|
+
},
|
|
2412
|
+
onHostOnline: (msg) => {
|
|
2413
|
+
applyAuthoritativeHost(msg);
|
|
2414
|
+
emitSnapshot();
|
|
2415
|
+
hostOnlineResolver?.(msg);
|
|
2416
|
+
},
|
|
2417
|
+
refreshTarget: async () => {
|
|
2418
|
+
try {
|
|
2419
|
+
const latestInfo = await pollRelayInfo(tianaContext, config, signal);
|
|
2420
|
+
if (latestInfo?.paired && latestInfo?.hostId) {
|
|
2421
|
+
applyAuthoritativeHost(latestInfo);
|
|
2422
|
+
emitSnapshot();
|
|
2423
|
+
}
|
|
2424
|
+
} catch {
|
|
2425
|
+
}
|
|
2426
|
+
},
|
|
2427
|
+
onKeyRotated: handleKeyRotated,
|
|
2428
|
+
onRtt: () => emitSnapshot(),
|
|
2429
|
+
},
|
|
2430
|
+
);
|
|
2431
|
+
|
|
2432
|
+
const OFFLINE_BACKOFF_STEPS = [2000, 5000, 10_000];
|
|
2433
|
+
let offlineBackoffIdx = 0;
|
|
2434
|
+
let leg = null;
|
|
2435
|
+
|
|
2436
|
+
while (!signal.aborted) {
|
|
2437
|
+
leg = await tunnel.connect(false, { allowStandby: true });
|
|
2438
|
+
const w = leg.welcomeMsg || {};
|
|
2439
|
+
|
|
2440
|
+
if (w.paired === false) {
|
|
2441
|
+
offlineBackoffIdx = 0;
|
|
2442
|
+
shellUI.showOnboarding({ webId, tenantId: identity.tenantId });
|
|
2443
|
+
const detected = await new Promise((resolve) => {
|
|
2444
|
+
let done = false;
|
|
2445
|
+
const finish = (info) => {
|
|
2446
|
+
if (done) return;
|
|
2447
|
+
done = true;
|
|
2448
|
+
clearInterval(pollTimer);
|
|
2449
|
+
hostOnlineResolver = null;
|
|
2450
|
+
resolve(info);
|
|
2451
|
+
};
|
|
2452
|
+
hostOnlineResolver = (msg) => finish(msg);
|
|
2453
|
+
const pollTimer = setInterval(async () => {
|
|
2454
|
+
if (signal.aborted) { finish(null); return; }
|
|
2455
|
+
const info = await pollRelayInfo(tianaContext, config, signal);
|
|
2456
|
+
if (info?.paired && info?.hostId) {
|
|
2457
|
+
applyAuthoritativeHost(info);
|
|
2458
|
+
if (info.hostConnected) {
|
|
2459
|
+
finish(info);
|
|
2460
|
+
}
|
|
2461
|
+
}
|
|
2462
|
+
}, 3000);
|
|
2463
|
+
leg.ws.addEventListener('close', () => setTimeout(() => finish({ reconnect: true }), 1500), { once: true });
|
|
2464
|
+
signal.addEventListener('abort', () => finish(null), { once: true });
|
|
2465
|
+
});
|
|
2466
|
+
leg.ws.close();
|
|
2467
|
+
if (signal.aborted) return;
|
|
2468
|
+
if (detected?.hostId) {
|
|
2469
|
+
applyAuthoritativeHost(detected);
|
|
2470
|
+
shellUI.markHostOnlineDetected(identity.hostName);
|
|
2471
|
+
await new Promise((r) => setTimeout(r, 450));
|
|
2472
|
+
}
|
|
2473
|
+
continue;
|
|
2474
|
+
}
|
|
2475
|
+
|
|
2476
|
+
if (w.configuredHost?.hostId) {
|
|
2477
|
+
const previousHostId = identity.hostId;
|
|
2478
|
+
applyAuthoritativeHost(w.configuredHost);
|
|
2479
|
+
if (!w.selectedHostId && w.hostConnected && previousHostId && previousHostId !== identity.hostId) {
|
|
2480
|
+
leg.ws.close();
|
|
2481
|
+
continue;
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
|
|
2485
|
+
if (!w.selectedHostId) {
|
|
2486
|
+
shellUI.showHostOffline({
|
|
2487
|
+
webId,
|
|
2488
|
+
tenantId: identity.tenantId,
|
|
2489
|
+
hostId: identity.hostId,
|
|
2490
|
+
hostName: identity.hostName,
|
|
2491
|
+
});
|
|
2492
|
+
const delayMs = OFFLINE_BACKOFF_STEPS[Math.min(offlineBackoffIdx, OFFLINE_BACKOFF_STEPS.length - 1)];
|
|
2493
|
+
offlineBackoffIdx = Math.min(offlineBackoffIdx + 1, OFFLINE_BACKOFF_STEPS.length - 1);
|
|
2494
|
+
await new Promise((resolve) => {
|
|
2495
|
+
let done = false;
|
|
2496
|
+
const finish = () => {
|
|
2497
|
+
if (done) return;
|
|
2498
|
+
done = true;
|
|
2499
|
+
clearTimeout(timer);
|
|
2500
|
+
document.removeEventListener('visibilitychange', onVisible);
|
|
2501
|
+
hostOnlineResolver = null;
|
|
2502
|
+
resolve();
|
|
2503
|
+
};
|
|
2504
|
+
const onVisible = () => {
|
|
2505
|
+
if (document.visibilityState === 'visible') finish();
|
|
2506
|
+
};
|
|
2507
|
+
hostOnlineResolver = finish;
|
|
2508
|
+
const timer = setTimeout(finish, delayMs);
|
|
2509
|
+
document.addEventListener('visibilitychange', onVisible);
|
|
2510
|
+
leg.ws.addEventListener('close', finish, { once: true });
|
|
2511
|
+
signal.addEventListener('abort', finish, { once: true });
|
|
2512
|
+
});
|
|
2513
|
+
leg.ws.close();
|
|
2514
|
+
if (signal.aborted) return;
|
|
2515
|
+
const latestInfo = await pollRelayInfo(tianaContext, config, signal);
|
|
2516
|
+
if (latestInfo?.paired && latestInfo?.hostId) {
|
|
2517
|
+
applyAuthoritativeHost(latestInfo);
|
|
2518
|
+
}
|
|
2519
|
+
continue;
|
|
2520
|
+
}
|
|
2521
|
+
|
|
2522
|
+
offlineBackoffIdx = 0;
|
|
2523
|
+
break;
|
|
2524
|
+
}
|
|
2525
|
+
|
|
2526
|
+
const key = keyName(identity);
|
|
2527
|
+
purgeWebKeys(webId, key, globalThis.localStorage);
|
|
2528
|
+
purgeWebKeys(webId, null, globalThis.sessionStorage);
|
|
2529
|
+
|
|
2530
|
+
let saved = readStoredKey(key);
|
|
2531
|
+
let secret = options._initialSecret || oneTimeHashKey || saved.secret;
|
|
2532
|
+
let remember = options._initialSecret !== undefined
|
|
2533
|
+
? Boolean(options._initialRemember)
|
|
2534
|
+
: (saved.remembered || true);
|
|
2535
|
+
let noticeMsg = '';
|
|
2536
|
+
|
|
2537
|
+
addEventListener('storage', (event) => {
|
|
2538
|
+
if (event.key === null || event.key === lockPulseStorageKey) {
|
|
2539
|
+
void lockAndReturnToUnlock({
|
|
2540
|
+
broadcast: false,
|
|
2541
|
+
sendHostLock: false,
|
|
2542
|
+
notice: '工作台已在其他标签页锁定,请重新输入配对密钥解锁。',
|
|
2543
|
+
});
|
|
2544
|
+
return;
|
|
2545
|
+
}
|
|
2546
|
+
if (event.key === key && event.newValue === null && currentRemembered) {
|
|
2547
|
+
if (keyName(identity) !== event.key) return;
|
|
2548
|
+
void pollRelayInfo(tianaContext, config, signal).then((latest) => {
|
|
2549
|
+
const latestKey = latest?.paired && latest?.hostId ? keyName({ ...identity, hostId: latest.hostId }) : '';
|
|
2550
|
+
if (latestKey && latestKey !== event.key) {
|
|
2551
|
+
applyAuthoritativeHost(latest);
|
|
2552
|
+
emitSnapshot();
|
|
2553
|
+
return;
|
|
2554
|
+
}
|
|
2555
|
+
void lockAndReturnToUnlock({
|
|
2556
|
+
broadcast: false,
|
|
2557
|
+
sendHostLock: false,
|
|
2558
|
+
notice: '工作台已在其他标签页锁定,请重新输入配对密钥解锁。',
|
|
2559
|
+
});
|
|
2560
|
+
});
|
|
2561
|
+
}
|
|
2562
|
+
}, { signal });
|
|
2563
|
+
addEventListener('online', () => {
|
|
2564
|
+
if (tunnel?.p2pEnabled && tunnel.stun && tunnel.leg) void tunnel.peer?.start();
|
|
2565
|
+
}, { signal });
|
|
2566
|
+
|
|
2567
|
+
for (;;) {
|
|
2568
|
+
if (!secret) {
|
|
2569
|
+
const res = await shellUI.promptUnlock({
|
|
2570
|
+
hostId: identity.hostId,
|
|
2571
|
+
hostName: identity.hostName,
|
|
2572
|
+
errorMessage: noticeMsg,
|
|
2573
|
+
defaultRemember: true,
|
|
2574
|
+
});
|
|
2575
|
+
secret = res.secret;
|
|
2576
|
+
remember = res.remember;
|
|
2577
|
+
}
|
|
2578
|
+
shellUI.showLoading('正在建立端到端加密隧道…', `正在验证本地主机 "${identity.hostName || identity.hostId}"。`);
|
|
2579
|
+
try {
|
|
2580
|
+
if (!leg.path.ready()) leg = await tunnel.connect();
|
|
2581
|
+
currentFingerprint = await tunnel.authenticate(leg, secret);
|
|
2582
|
+
break;
|
|
2583
|
+
} catch (error) {
|
|
2584
|
+
if (!['AUTH_FAILED', 'INVALID_KEY'].includes(error.code)) throw error;
|
|
2585
|
+
writeStoredKey(key, null);
|
|
2586
|
+
await clearFrontendCache(identity);
|
|
2587
|
+
noticeMsg = '配对密钥无效或主机已轮换密钥,请核对后重新输入。';
|
|
2588
|
+
secret = null;
|
|
2589
|
+
}
|
|
2590
|
+
}
|
|
2591
|
+
|
|
2592
|
+
signal.throwIfAborted();
|
|
2593
|
+
const normalizedSecret = normalizePairingKey(secret);
|
|
2594
|
+
currentRemembered = Boolean(remember);
|
|
2595
|
+
inMemorySecret = normalizedSecret;
|
|
2596
|
+
writeStoredKey(key, normalizedSecret, { remember: currentRemembered });
|
|
2597
|
+
secret = null;
|
|
2598
|
+
|
|
2599
|
+
shellUI.showLoading('正在同步工作台组件…', '正在加载 DSH 前端与已启用的客户端插件。');
|
|
2600
|
+
|
|
2601
|
+
const tunnelFetch = (url, init) => tunnel.fetch(url, init);
|
|
2602
|
+
const frontend = await requestFrontend(tunnelFetch, signal);
|
|
2603
|
+
tunnel.refreshManifest = () => requestFrontend(tunnelFetch, signal);
|
|
2604
|
+
if (frontend.session?.userId !== identity.ownerUserId || frontend.session?.tenantId !== identity.tenantId) {
|
|
2605
|
+
throw new Error('远程前端清单与应用身份不匹配');
|
|
2606
|
+
}
|
|
2607
|
+
if (frontend.host?.hostName) identity.hostName = frontend.host.hostName;
|
|
2608
|
+
tunnel.p2pEnabled = frontend.p2pEnabled !== false;
|
|
2609
|
+
if (tunnel.p2pEnabled) tunnel.startPeer(frontend.iceServers);
|
|
2610
|
+
|
|
2611
|
+
loader = await createFrontendLoader(frontend, identity, tunnelFetch, signal);
|
|
2612
|
+
await loader.prepare();
|
|
2613
|
+
|
|
2614
|
+
const appBasePath = new URL('./', location.href).pathname;
|
|
2615
|
+
swBridge = await setupServiceWorkerBridge(tunnel, appBasePath, signal);
|
|
2616
|
+
if (swBridge.active) {
|
|
2617
|
+
installSwScopeAlignment(appBasePath, signal, swBridge.getNavToken);
|
|
2618
|
+
}
|
|
2619
|
+
|
|
2620
|
+
wrapGlobalFetch(tunnelFetch, loader.fetchAssetUrl);
|
|
2621
|
+
globalThis.__DSH_FILE_UPLOAD__ = { fetch: globalThis.fetch };
|
|
2622
|
+
globalThis.EventSource = createTunnelEventSource(tunnelFetch, { appBasePath });
|
|
2623
|
+
guardPluginServiceWorkers();
|
|
2624
|
+
installModuleLoaderQueue();
|
|
2625
|
+
|
|
2626
|
+
globalThis.__DSH_BOOT__ = frontend.boot;
|
|
2627
|
+
globalThis.__DSH_IMPORT_CORE__ = loader.importCore;
|
|
2628
|
+
globalThis.__DSH_TRANSPORT__ = {
|
|
2629
|
+
ownsHost: true,
|
|
2630
|
+
streamBaseUrl: new URL('./', location.href).href,
|
|
2631
|
+
fetch: tunnelFetch,
|
|
2632
|
+
createWebSocket: (url) => tunnel.createWebSocket(url),
|
|
2633
|
+
loadBundle: loader.loadBundle,
|
|
2634
|
+
resolveAsset: loader.resolveAsset,
|
|
2635
|
+
};
|
|
2636
|
+
globalThis.__DSH_REMOTE_SHELL__ = {
|
|
2637
|
+
isRemote: true,
|
|
2638
|
+
getStatusSnapshot,
|
|
2639
|
+
getSnapshot: getStatusSnapshot,
|
|
2640
|
+
subscribe(fn) {
|
|
2641
|
+
subscribers.add(fn);
|
|
2642
|
+
return () => subscribers.delete(fn);
|
|
2643
|
+
},
|
|
2644
|
+
clearFrontendCache: clearCacheAndReload,
|
|
2645
|
+
lockAndForget: forget,
|
|
2646
|
+
};
|
|
2647
|
+
|
|
2648
|
+
document.title = config.appTitle || 'DSH Remote';
|
|
2649
|
+
const theme = frontend.theme;
|
|
2650
|
+
if (['light', 'dark', 'system'].includes(theme?.preference)) {
|
|
2651
|
+
document.documentElement.dataset.dsThemeSource = theme.preference;
|
|
2652
|
+
const mq = matchMedia('(prefers-color-scheme: dark)');
|
|
2653
|
+
const applyDark = () => {
|
|
2654
|
+
document.body.toggleAttribute('data-ds-dark-theme', theme.preference === 'dark' ||
|
|
2655
|
+
(theme.preference === 'system' && mq.matches));
|
|
2656
|
+
};
|
|
2657
|
+
applyDark();
|
|
2658
|
+
mq.addEventListener?.('change', applyDark, { signal });
|
|
2659
|
+
for (const [name, value] of Object.entries(theme.cssVars ?? {})) {
|
|
2660
|
+
if (/^--[a-z0-9_-]{1,120}$/iu.test(name) && typeof value === 'string' && value.length <= 4096) {
|
|
2661
|
+
document.body.style.setProperty(name, value);
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
}
|
|
2665
|
+
|
|
2666
|
+
await loader.install();
|
|
2667
|
+
shellUI.destroy();
|
|
2668
|
+
ensureRootElement();
|
|
2669
|
+
reconnectBanner = shellUI.mountReconnectBanner({
|
|
2670
|
+
hostName: identity.hostName || identity.hostId,
|
|
2671
|
+
onLock: forget,
|
|
2672
|
+
});
|
|
2673
|
+
if (!swBridge.active) {
|
|
2674
|
+
shellUI.mountNoSwBanner();
|
|
2675
|
+
}
|
|
2676
|
+
emitSnapshot();
|
|
2677
|
+
await loader.importCore(frontend.entry);
|
|
2678
|
+
} catch (error) {
|
|
2679
|
+
close();
|
|
2680
|
+
shellUI.showError('DSH 远程工作台无法启动', error instanceof Error ? error.message : String(error));
|
|
2681
|
+
}
|
|
2682
|
+
}
|
|
2683
|
+
|
|
2684
|
+
export function mount(appContainer, tianaContext, options) {
|
|
2685
|
+
const container = appContainer || document.getElementById('app') || document.body;
|
|
2686
|
+
const shellUI = createShellUI(container);
|
|
2687
|
+
void runRemoteSession(container, tianaContext, shellUI, options);
|
|
2688
|
+
}
|
|
2689
|
+
|
|
2690
|
+
if (typeof window !== 'undefined' && !window.tiana && document.getElementById('app')) {
|
|
2691
|
+
mount(document.getElementById('app'), null);
|
|
2692
|
+
}
|