dsh-quay-bot 1.0.2 → 1.0.6
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/README.md +28 -105
- package/botscreen/requirements.txt +1 -1
- package/client.js +123 -53
- package/cordis.patch.yml +1 -1
- package/host/api.js +4 -0
- package/host/remote.js +285 -8
- package/host/screen.js +22 -86
- package/package.json +34 -32
- package/remote/bin/dsh-remote.mjs +435 -0
- package/remote/package.json +27 -0
- package/remote/src/config.mjs +183 -0
- package/remote/src/crypto.mjs +220 -0
- package/remote/src/keys.mjs +226 -0
- package/remote/src/proxy.mjs +1028 -0
- package/remote/src/sessions.mjs +163 -0
- package/remote/src/shim.js +838 -0
- package/remote/src/supervisor.mjs +207 -0
- package/remote/src/tunnel.mjs +533 -0
- package/remote/src/upstream.mjs +403 -0
- package/remote/src/util.mjs +149 -0
- package/remote/src/ws.mjs +313 -0
- package/LICENSE +0 -21
- package/avatar/build.mjs +0 -81
- package/avatar/gallery/droid.json +0 -14
- package/avatar/gallery/ghost.json +0 -14
- package/avatar/gallery/grok-pod.json +0 -14
- package/avatar/gallery/guardian.json +0 -14
- package/avatar/gallery/mecha.json +0 -14
- package/avatar/gallery/mochi.json +0 -14
- package/avatar/gallery/neko.json +0 -14
- package/avatar/gallery/orbiter.json +0 -14
- package/avatar/gallery/relay.json +0 -14
- package/avatar/gallery/spark.json +0 -14
- package/avatar/src/bot/clay.ts +0 -135
- package/avatar/src/bot/effects.ts +0 -100
- package/avatar/src/bot/grok-bot.ts +0 -626
- package/avatar/src/bot/index.ts +0 -15
- package/avatar/src/bot/palettes.ts +0 -62
- package/avatar/src/bot/ring.ts +0 -219
- package/avatar/src/bot/scheduler.ts +0 -239
- package/avatar/src/bot/shapes.ts +0 -277
- package/avatar/src/bot/spring.ts +0 -196
- package/avatar/src/core/color.ts +0 -92
- package/avatar/src/core/eyes.ts +0 -297
- package/avatar/src/core/field.ts +0 -482
- package/avatar/src/core/frame.ts +0 -655
- package/avatar/src/core/fx.ts +0 -375
- package/avatar/src/core/index.ts +0 -49
- package/avatar/src/core/paint.ts +0 -331
- package/avatar/src/core/path.ts +0 -495
- package/avatar/src/core/pose.ts +0 -581
- package/avatar/src/core/svg.ts +0 -98
- package/avatar/src/core/types.ts +0 -153
- package/avatar/src/core/validate.ts +0 -296
- package/avatar/src/core/volume.ts +0 -681
- package/avatar/src/entry.ts +0 -260
- package/bin/doctor.mjs +0 -148
- package/botscreen/requirements-offline.txt +0 -11
- package/market/index.json +0 -41
- package/vendor/pip/pip-25.1.1-py3-none-any.whl +0 -0
- package/vendor/pip/setuptools-78.1.1-py3-none-any.whl +0 -0
|
@@ -0,0 +1,838 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* dsh-remote 浏览器端 shim(classic script,必须先于应用模块执行)。
|
|
3
|
+
*
|
|
4
|
+
* 职责:
|
|
5
|
+
* 1) 从 URL fragment(#k=…,不会发送给 Cloudflare)读取 PSK;
|
|
6
|
+
* 2) ECDH P-256 握手 + HMAC 证明 → 建立 relay 会话;
|
|
7
|
+
* 3) 劫持同源 fetch / WebSocket / EventSource,把业务数据封装为 AES-256-GCM 密文帧;
|
|
8
|
+
* 4) 处理密钥轮换(响应元数据或 WS 控制帧回传新 PSK)。
|
|
9
|
+
*
|
|
10
|
+
* 不拦截:静态资源(由 SPA 自行按普通方式加载)与 /__dsh/* 自身的控制面请求。
|
|
11
|
+
*/
|
|
12
|
+
(() => {
|
|
13
|
+
'use strict'
|
|
14
|
+
if (window.__DSH_REMOTE_SHIM__) return
|
|
15
|
+
window.__DSH_REMOTE_SHIM__ = { version: 1 }
|
|
16
|
+
|
|
17
|
+
const E2E_PREFIX = '/__dsh'
|
|
18
|
+
const E2E_ENDPOINT = `${E2E_PREFIX}/e2e`
|
|
19
|
+
const WS_ENDPOINT = `${E2E_PREFIX}/ws`
|
|
20
|
+
const HANDSHAKE_ENDPOINT = `${E2E_PREFIX}/handshake`
|
|
21
|
+
const BIND_ENDPOINT = `${E2E_PREFIX}/bind`
|
|
22
|
+
const PSK_STORAGE = 'dshr.psk'
|
|
23
|
+
const SID_STORAGE = 'dshr.sid'
|
|
24
|
+
const FRAME_DATA = 1
|
|
25
|
+
const FRAME_CONTROL = 2
|
|
26
|
+
const FRAME_CLOSE = 3
|
|
27
|
+
const encoder = new TextEncoder()
|
|
28
|
+
const decoder = new TextDecoder()
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
if (new URLSearchParams(location.search).has('dsh_debug')) sessionStorage.setItem('dshr.debug', '1')
|
|
32
|
+
window.__DSH_REMOTE_DEBUG__ = sessionStorage.getItem('dshr.debug') === '1'
|
|
33
|
+
} catch {}
|
|
34
|
+
|
|
35
|
+
const state = {
|
|
36
|
+
psk: null,
|
|
37
|
+
pskKid: null,
|
|
38
|
+
sid: null,
|
|
39
|
+
keys: null,
|
|
40
|
+
bindReady: null,
|
|
41
|
+
seq: 0,
|
|
42
|
+
handshakes: 0,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ───────────────────────── base64url ─────────────────────────
|
|
46
|
+
|
|
47
|
+
function b64u(bytes) {
|
|
48
|
+
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes)
|
|
49
|
+
let binary = ''
|
|
50
|
+
const chunk = 0x8000
|
|
51
|
+
for (let i = 0; i < view.length; i += chunk) {
|
|
52
|
+
binary += String.fromCharCode.apply(null, view.subarray(i, i + chunk))
|
|
53
|
+
}
|
|
54
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/u, '')
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function unb64u(text) {
|
|
58
|
+
const normalized = String(text).replace(/-/g, '+').replace(/_/g, '/')
|
|
59
|
+
const padded = normalized + '==='.slice((normalized.length + 3) % 4)
|
|
60
|
+
const binary = atob(padded)
|
|
61
|
+
const out = new Uint8Array(binary.length)
|
|
62
|
+
for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i)
|
|
63
|
+
return out
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function concatBytes(...parts) {
|
|
67
|
+
const total = parts.reduce((sum, part) => sum + part.length, 0)
|
|
68
|
+
const out = new Uint8Array(total)
|
|
69
|
+
let offset = 0
|
|
70
|
+
for (const part of parts) {
|
|
71
|
+
out.set(part, offset)
|
|
72
|
+
offset += part.length
|
|
73
|
+
}
|
|
74
|
+
return out
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function textBytes(text) {
|
|
78
|
+
return encoder.encode(String(text))
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function readHashPsk() {
|
|
82
|
+
const hash = String(location.hash || '').replace(/^#/u, '')
|
|
83
|
+
if (!hash) return null
|
|
84
|
+
for (const part of hash.split('&')) {
|
|
85
|
+
const at = part.indexOf('=')
|
|
86
|
+
if (at === -1) continue
|
|
87
|
+
const name = part.slice(0, at)
|
|
88
|
+
if (name !== 'k' && name !== 'key' && name !== 'psk') continue
|
|
89
|
+
const value = decodeURIComponent(part.slice(at + 1))
|
|
90
|
+
if (/^[A-Za-z0-9_-]{20,}$/u.test(value)) return value
|
|
91
|
+
}
|
|
92
|
+
return null
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function currentPsk() {
|
|
96
|
+
if (state.psk) return state.psk
|
|
97
|
+
const fromHash = readHashPsk()
|
|
98
|
+
if (fromHash) {
|
|
99
|
+
state.psk = fromHash
|
|
100
|
+
try { sessionStorage.setItem(PSK_STORAGE, fromHash) } catch {}
|
|
101
|
+
try { localStorage.setItem(PSK_STORAGE, fromHash) } catch {}
|
|
102
|
+
return fromHash
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
const stored = sessionStorage.getItem(PSK_STORAGE) || localStorage.getItem(PSK_STORAGE)
|
|
106
|
+
if (stored) {
|
|
107
|
+
state.psk = stored
|
|
108
|
+
try { sessionStorage.setItem(PSK_STORAGE, stored) } catch {}
|
|
109
|
+
return stored
|
|
110
|
+
}
|
|
111
|
+
} catch {}
|
|
112
|
+
return null
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function storePsk(psk, kid) {
|
|
116
|
+
state.psk = psk
|
|
117
|
+
if (kid) state.pskKid = kid
|
|
118
|
+
try { sessionStorage.setItem(PSK_STORAGE, psk) } catch {}
|
|
119
|
+
try { localStorage.setItem(PSK_STORAGE, psk) } catch {}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function report(message, isError = false) {
|
|
123
|
+
const el = document.getElementById('state')
|
|
124
|
+
if (!el) return
|
|
125
|
+
el.textContent = message
|
|
126
|
+
el.classList.toggle('fail', isError)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// ───────────────────────── 帧编解码 ─────────────────────────
|
|
130
|
+
|
|
131
|
+
let cachedAes = { c2s: null, s2c: null }
|
|
132
|
+
|
|
133
|
+
async function aesKey(raw) {
|
|
134
|
+
return crypto.subtle.importKey('raw', raw, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt'])
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function loadKeys(c2sRaw, s2cRaw) {
|
|
138
|
+
cachedAes = { c2s: await aesKey(c2sRaw), s2c: await aesKey(s2cRaw) }
|
|
139
|
+
state.keys = { c2s: c2sRaw, s2c: s2cRaw }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function counterNonce(seq) {
|
|
143
|
+
const nonce = new Uint8Array(12)
|
|
144
|
+
const view = new DataView(nonce.buffer)
|
|
145
|
+
view.setUint32(0, 0)
|
|
146
|
+
view.setBigUint64(4, BigInt(seq))
|
|
147
|
+
return nonce
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function seal(type, plaintext, direction = 'c2s') {
|
|
151
|
+
const seq = state.seq
|
|
152
|
+
state.seq += 1
|
|
153
|
+
const header = new Uint8Array(6)
|
|
154
|
+
header[0] = 1
|
|
155
|
+
header[1] = type
|
|
156
|
+
new DataView(header.buffer).setUint32(2, seq)
|
|
157
|
+
const aad = concatBytes(header, unb64u(state.sid), textBytes(direction))
|
|
158
|
+
const key = direction === 'c2s' ? cachedAes.c2s : cachedAes.s2c
|
|
159
|
+
const ciphertext = await crypto.subtle.encrypt(
|
|
160
|
+
{ name: 'AES-GCM', iv: counterNonce(seq), additionalData: aad, tagLength: 128 },
|
|
161
|
+
key,
|
|
162
|
+
plaintext,
|
|
163
|
+
)
|
|
164
|
+
return concatBytes(header, new Uint8Array(ciphertext))
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function open(frame) {
|
|
168
|
+
if (frame.length < 6 + 16) throw new Error('帧过短')
|
|
169
|
+
if (frame[0] !== 1) throw new Error(`帧版本不支持: ${frame[0]}`)
|
|
170
|
+
const type = frame[1]
|
|
171
|
+
const seq = new DataView(frame.buffer, frame.byteOffset, frame.byteLength).getUint32(2)
|
|
172
|
+
const header = frame.subarray(0, 6)
|
|
173
|
+
const aad = concatBytes(header, unb64u(state.sid), textBytes('s2c'))
|
|
174
|
+
const ciphertext = frame.subarray(6)
|
|
175
|
+
const plaintext = await crypto.subtle.decrypt(
|
|
176
|
+
{ name: 'AES-GCM', iv: counterNonce(seq), additionalData: aad, tagLength: 128 },
|
|
177
|
+
cachedAes.s2c,
|
|
178
|
+
ciphertext,
|
|
179
|
+
)
|
|
180
|
+
return { type, seq, plaintext: new Uint8Array(plaintext) }
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function lengthPrefixed(frame) {
|
|
184
|
+
const out = new Uint8Array(4 + frame.length)
|
|
185
|
+
new DataView(out.buffer).setUint32(0, frame.length)
|
|
186
|
+
out.set(frame, 4)
|
|
187
|
+
return out
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
class FrameReader {
|
|
191
|
+
constructor() {
|
|
192
|
+
this.buffer = new Uint8Array(0)
|
|
193
|
+
this.consumed = 0
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
push(chunk) {
|
|
197
|
+
if (chunk && chunk.length) {
|
|
198
|
+
const merged = new Uint8Array(this.buffer.length + chunk.length)
|
|
199
|
+
merged.set(this.buffer)
|
|
200
|
+
merged.set(chunk, this.buffer.length)
|
|
201
|
+
this.buffer = merged
|
|
202
|
+
}
|
|
203
|
+
if (this.buffer.length < 4) return null
|
|
204
|
+
const length = new DataView(this.buffer.buffer, this.buffer.byteOffset, 4).getUint32(0)
|
|
205
|
+
if (length > 8 * 1024 * 1024) throw new Error(`帧过大: ${length}`)
|
|
206
|
+
if (this.buffer.length < 4 + length) return null
|
|
207
|
+
const frame = this.buffer.slice(4, 4 + length)
|
|
208
|
+
this.buffer = this.buffer.subarray(4 + length)
|
|
209
|
+
return frame
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
get pending() {
|
|
213
|
+
return this.buffer.length
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// ───────────────────────── 握手 / 绑定 ─────────────────────────
|
|
218
|
+
|
|
219
|
+
async function bind() {
|
|
220
|
+
const psk = currentPsk()
|
|
221
|
+
if (!psk) throw new Error('地址缺少 #k=<key> 访问密钥')
|
|
222
|
+
const handshake = await rawFetch(HANDSHAKE_ENDPOINT, { method: 'GET', credentials: 'same-origin', cache: 'no-store' })
|
|
223
|
+
if (!handshake.ok) throw new Error(`握手失败: HTTP ${String(handshake.status)}`)
|
|
224
|
+
const challenge = await handshake.json()
|
|
225
|
+
const keyPair = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits'])
|
|
226
|
+
const clientPub = new Uint8Array(await crypto.subtle.exportKey('spki', keyPair.publicKey))
|
|
227
|
+
const serverPub = await crypto.subtle.importKey(
|
|
228
|
+
'spki',
|
|
229
|
+
unb64u(challenge.spk),
|
|
230
|
+
{ name: 'ECDH', namedCurve: 'P-256' },
|
|
231
|
+
false,
|
|
232
|
+
[],
|
|
233
|
+
)
|
|
234
|
+
const shared = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: serverPub }, keyPair.privateKey, 256))
|
|
235
|
+
const pskBytes = unb64u(psk)
|
|
236
|
+
const hmacKey = await crypto.subtle.importKey('raw', pskBytes, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
|
|
237
|
+
const proofInput = concatBytes(
|
|
238
|
+
textBytes('dsh-remote/v1/bind'),
|
|
239
|
+
new Uint8Array([0]),
|
|
240
|
+
textBytes(challenge.kid),
|
|
241
|
+
new Uint8Array([0]),
|
|
242
|
+
textBytes(challenge.spk),
|
|
243
|
+
new Uint8Array([0]),
|
|
244
|
+
textBytes(b64u(clientPub)),
|
|
245
|
+
new Uint8Array([0]),
|
|
246
|
+
unb64u(challenge.nonce),
|
|
247
|
+
)
|
|
248
|
+
const proof = new Uint8Array(await crypto.subtle.sign('HMAC', hmacKey, proofInput))
|
|
249
|
+
|
|
250
|
+
const response = await rawFetch(BIND_ENDPOINT, {
|
|
251
|
+
method: 'POST',
|
|
252
|
+
credentials: 'same-origin',
|
|
253
|
+
cache: 'no-store',
|
|
254
|
+
headers: { 'content-type': 'application/json' },
|
|
255
|
+
body: JSON.stringify({
|
|
256
|
+
v: 1,
|
|
257
|
+
kid: challenge.kid,
|
|
258
|
+
cpk: b64u(clientPub),
|
|
259
|
+
nonce: challenge.nonce,
|
|
260
|
+
proof: b64u(proof),
|
|
261
|
+
}),
|
|
262
|
+
})
|
|
263
|
+
if (response.status === 401) throw new Error('访问密钥被拒绝(可能已轮换,请使用最新链接)')
|
|
264
|
+
if (!response.ok) throw new Error(`绑定失败: HTTP ${String(response.status)}`)
|
|
265
|
+
const result = await response.json()
|
|
266
|
+
state.sid = result.sid
|
|
267
|
+
state.pskKid = result.pskKid ?? null
|
|
268
|
+
try {
|
|
269
|
+
sessionStorage.setItem(SID_STORAGE, result.sid)
|
|
270
|
+
} catch {}
|
|
271
|
+
|
|
272
|
+
const sidBytes = unb64u(result.sid)
|
|
273
|
+
const info = concatBytes(
|
|
274
|
+
textBytes('dsh-remote/v1/keys'),
|
|
275
|
+
new Uint8Array([0]),
|
|
276
|
+
textBytes(challenge.kid),
|
|
277
|
+
unb64u(challenge.spk),
|
|
278
|
+
clientPub,
|
|
279
|
+
sidBytes,
|
|
280
|
+
)
|
|
281
|
+
const hkdfKey = await crypto.subtle.importKey('raw', shared, { name: 'HKDF' }, false, ['deriveBits'])
|
|
282
|
+
const okm = new Uint8Array(
|
|
283
|
+
await crypto.subtle.deriveBits(
|
|
284
|
+
{ name: 'HKDF', hash: 'SHA-256', salt: unb64u(challenge.nonce), info },
|
|
285
|
+
hkdfKey,
|
|
286
|
+
512,
|
|
287
|
+
),
|
|
288
|
+
)
|
|
289
|
+
await loadKeys(okm.slice(0, 32), okm.slice(32, 64))
|
|
290
|
+
state.handshakes += 1
|
|
291
|
+
return result
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function ensureSession() {
|
|
295
|
+
if (state.keys && state.sid) return Promise.resolve()
|
|
296
|
+
if (state.bindReady) return state.bindReady
|
|
297
|
+
state.bindReady = bind()
|
|
298
|
+
.catch((error) => {
|
|
299
|
+
state.bindReady = null
|
|
300
|
+
throw error
|
|
301
|
+
})
|
|
302
|
+
.then((result) => {
|
|
303
|
+
state.bindReady = null
|
|
304
|
+
return result
|
|
305
|
+
})
|
|
306
|
+
return state.bindReady
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function rawFetch(input, init) {
|
|
310
|
+
return originalFetch(input, init)
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** 401 → 重新绑定一次并重试。 */
|
|
314
|
+
async function withSession(fn) {
|
|
315
|
+
await ensureSession()
|
|
316
|
+
try {
|
|
317
|
+
return await fn()
|
|
318
|
+
} catch (error) {
|
|
319
|
+
if (error && error.__dshUnauthorized) {
|
|
320
|
+
state.keys = null
|
|
321
|
+
state.sid = null
|
|
322
|
+
await ensureSession()
|
|
323
|
+
return fn()
|
|
324
|
+
}
|
|
325
|
+
throw error
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// ───────────────────────── fetch ─────────────────────────
|
|
330
|
+
|
|
331
|
+
const originalFetch = window.fetch.bind(window)
|
|
332
|
+
const originalWebSocket = window.WebSocket
|
|
333
|
+
const originalEventSource = window.EventSource
|
|
334
|
+
|
|
335
|
+
function applyRenew(payload) {
|
|
336
|
+
if (!payload || typeof payload.psk !== 'string') return
|
|
337
|
+
storePsk(payload.psk, payload.kid)
|
|
338
|
+
state.pskKid = payload.kid ?? state.pskKid
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async function readRequestBody(request) {
|
|
342
|
+
if (request.method === 'GET' || request.method === 'HEAD') return { bytes: null, contentType: null }
|
|
343
|
+
if (!request.body) return { bytes: null, contentType: request.headers.get('content-type') }
|
|
344
|
+
const buffer = await request.arrayBuffer()
|
|
345
|
+
return { bytes: new Uint8Array(buffer), contentType: request.headers.get('content-type') }
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function headersToObject(headers) {
|
|
349
|
+
const out = {}
|
|
350
|
+
headers.forEach((value, name) => {
|
|
351
|
+
const key = name.toLowerCase()
|
|
352
|
+
if (key === 'content-length' || key === 'connection' || key === 'host' || key === 'cookie') return
|
|
353
|
+
if (key.startsWith('x-dsh-')) return
|
|
354
|
+
out[key] = value
|
|
355
|
+
})
|
|
356
|
+
return out
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async function e2eFetch(request) {
|
|
360
|
+
const url = new URL(request.url)
|
|
361
|
+
return withSession(async () => {
|
|
362
|
+
const { bytes, contentType } = await readRequestBody(request)
|
|
363
|
+
const headers = headersToObject(request.headers)
|
|
364
|
+
if (contentType) headers['content-type'] = contentType
|
|
365
|
+
const envelope = {
|
|
366
|
+
v: 1,
|
|
367
|
+
m: request.method,
|
|
368
|
+
p: `${url.pathname}${url.search}`,
|
|
369
|
+
h: headers,
|
|
370
|
+
b: bytes && bytes.length > 0 ? b64u(bytes) : null,
|
|
371
|
+
}
|
|
372
|
+
const frame = await seal(FRAME_DATA, textBytes(JSON.stringify(envelope)), 'c2s')
|
|
373
|
+
const response = await rawFetch(E2E_ENDPOINT, {
|
|
374
|
+
method: 'POST',
|
|
375
|
+
credentials: 'same-origin',
|
|
376
|
+
cache: 'no-store',
|
|
377
|
+
headers: { 'content-type': 'application/octet-stream' },
|
|
378
|
+
body: lengthPrefixed(frame),
|
|
379
|
+
signal: request.signal,
|
|
380
|
+
})
|
|
381
|
+
if (response.status === 401) {
|
|
382
|
+
const error = new Error('relay session expired')
|
|
383
|
+
error.__dshUnauthorized = true
|
|
384
|
+
throw error
|
|
385
|
+
}
|
|
386
|
+
if (!response.ok || !response.body) throw new Error(`relay HTTP ${String(response.status)}`)
|
|
387
|
+
|
|
388
|
+
const reader = response.body.getReader()
|
|
389
|
+
const frames = new FrameReader()
|
|
390
|
+
let meta = null
|
|
391
|
+
let closed = false
|
|
392
|
+
|
|
393
|
+
const pullFrame = async () => {
|
|
394
|
+
for (;;) {
|
|
395
|
+
const ready = frames.push(null)
|
|
396
|
+
if (ready) return ready
|
|
397
|
+
const { value, done } = await reader.read()
|
|
398
|
+
if (done) return null
|
|
399
|
+
const parsed = frames.push(value)
|
|
400
|
+
if (parsed) return parsed
|
|
401
|
+
const frame = frames.push(null)
|
|
402
|
+
if (frame) return frame
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const first = await pullFrame()
|
|
407
|
+
if (!first) throw new Error('relay 未返回响应帧')
|
|
408
|
+
const opened = await open(first)
|
|
409
|
+
if (opened.type !== FRAME_CONTROL) throw new Error('响应缺少元数据帧')
|
|
410
|
+
meta = JSON.parse(decoder.decode(opened.plaintext))
|
|
411
|
+
if (meta.renew) applyRenew(meta.renew)
|
|
412
|
+
if (meta.t === 'error') throw new Error(meta.message || 'relay error')
|
|
413
|
+
|
|
414
|
+
const stream = new ReadableStream({
|
|
415
|
+
async pull(controller) {
|
|
416
|
+
if (closed) return
|
|
417
|
+
for (;;) {
|
|
418
|
+
const frame = await pullFrame()
|
|
419
|
+
if (!frame) {
|
|
420
|
+
closed = true
|
|
421
|
+
controller.close()
|
|
422
|
+
return
|
|
423
|
+
}
|
|
424
|
+
const item = await open(frame)
|
|
425
|
+
if (item.type === FRAME_DATA) {
|
|
426
|
+
controller.enqueue(item.plaintext)
|
|
427
|
+
return
|
|
428
|
+
}
|
|
429
|
+
if (item.type === FRAME_CONTROL) {
|
|
430
|
+
try {
|
|
431
|
+
const control = JSON.parse(decoder.decode(item.plaintext))
|
|
432
|
+
if (control.renew) applyRenew(control.renew)
|
|
433
|
+
if (control.t === 'error') {
|
|
434
|
+
closed = true
|
|
435
|
+
controller.error(new Error(control.message || 'relay error'))
|
|
436
|
+
return
|
|
437
|
+
}
|
|
438
|
+
} catch {}
|
|
439
|
+
continue
|
|
440
|
+
}
|
|
441
|
+
if (item.type === FRAME_CLOSE) {
|
|
442
|
+
closed = true
|
|
443
|
+
controller.close()
|
|
444
|
+
return
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
},
|
|
448
|
+
cancel(reason) {
|
|
449
|
+
closed = true
|
|
450
|
+
try {
|
|
451
|
+
reader.cancel(reason)
|
|
452
|
+
} catch {}
|
|
453
|
+
},
|
|
454
|
+
})
|
|
455
|
+
|
|
456
|
+
const responseHeaders = new Headers()
|
|
457
|
+
for (const [name, value] of Object.entries(meta.h || {})) {
|
|
458
|
+
if (Array.isArray(value)) for (const item of value) responseHeaders.append(name, item)
|
|
459
|
+
else if (value !== undefined && value !== null) responseHeaders.set(name, String(value))
|
|
460
|
+
}
|
|
461
|
+
return new Response(request.method === 'HEAD' ? null : stream, {
|
|
462
|
+
status: meta.s,
|
|
463
|
+
statusText: '',
|
|
464
|
+
headers: responseHeaders,
|
|
465
|
+
})
|
|
466
|
+
})
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
window.fetch = function shimFetch(input, init) {
|
|
470
|
+
let request
|
|
471
|
+
try {
|
|
472
|
+
request = new Request(input, init)
|
|
473
|
+
} catch {
|
|
474
|
+
return originalFetch(input, init)
|
|
475
|
+
}
|
|
476
|
+
let url
|
|
477
|
+
try {
|
|
478
|
+
url = new URL(request.url, location.href)
|
|
479
|
+
} catch {
|
|
480
|
+
return originalFetch(input, init)
|
|
481
|
+
}
|
|
482
|
+
if (url.origin !== location.origin) return originalFetch(input, init)
|
|
483
|
+
if (url.pathname.startsWith(E2E_PREFIX) || request.method === 'OPTIONS') return originalFetch(input, init)
|
|
484
|
+
return e2eFetch(request)
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// ───────────────────────── WebSocket ─────────────────────────
|
|
488
|
+
|
|
489
|
+
class RemoteWebSocket extends EventTarget {
|
|
490
|
+
static CONNECTING = 0
|
|
491
|
+
static OPEN = 1
|
|
492
|
+
static CLOSING = 2
|
|
493
|
+
static CLOSED = 3
|
|
494
|
+
|
|
495
|
+
constructor(url, protocols) {
|
|
496
|
+
super()
|
|
497
|
+
this.url = String(url)
|
|
498
|
+
this.protocol = ''
|
|
499
|
+
this.readyState = RemoteWebSocket.CONNECTING
|
|
500
|
+
this.binaryType = 'blob'
|
|
501
|
+
this.onopen = null
|
|
502
|
+
this.onmessage = null
|
|
503
|
+
this.onerror = null
|
|
504
|
+
this.onclose = null
|
|
505
|
+
this.#target = new URL(this.url, location.href)
|
|
506
|
+
this.#protocols = protocols
|
|
507
|
+
this.#queue = []
|
|
508
|
+
this.#init()
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
#target
|
|
512
|
+
#socket = null
|
|
513
|
+
#queue = []
|
|
514
|
+
#ready = false
|
|
515
|
+
#reader = new FrameReader()
|
|
516
|
+
#closed = false
|
|
517
|
+
#chain = Promise.resolve()
|
|
518
|
+
#protocols
|
|
519
|
+
|
|
520
|
+
async #init() {
|
|
521
|
+
try {
|
|
522
|
+
await ensureSession()
|
|
523
|
+
} catch (error) {
|
|
524
|
+
this.#fail(error)
|
|
525
|
+
return
|
|
526
|
+
}
|
|
527
|
+
const wsUrl = new URL(WS_ENDPOINT, location.href)
|
|
528
|
+
wsUrl.protocol = wsUrl.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
529
|
+
const socket = new originalWebSocket(wsUrl.href, this.#protocols)
|
|
530
|
+
this.#socket = socket
|
|
531
|
+
socket.binaryType = 'arraybuffer'
|
|
532
|
+
socket.onopen = async () => {
|
|
533
|
+
try {
|
|
534
|
+
const init = {
|
|
535
|
+
t: 'init',
|
|
536
|
+
p: `${this.#target.pathname}${this.#target.search}`,
|
|
537
|
+
h: { origin: location.origin },
|
|
538
|
+
}
|
|
539
|
+
const frame = await seal(FRAME_CONTROL, textBytes(JSON.stringify(init)), 'c2s')
|
|
540
|
+
socket.send(lengthPrefixed(frame))
|
|
541
|
+
this.#ready = true
|
|
542
|
+
this.readyState = RemoteWebSocket.OPEN
|
|
543
|
+
this.#emit('open', new Event('open'))
|
|
544
|
+
for (const item of this.#queue.splice(0)) this.send(item.data)
|
|
545
|
+
} catch (error) {
|
|
546
|
+
this.#fail(error)
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
socket.onmessage = (event) => {
|
|
550
|
+
this.#chain = this.#chain.then(() => this.#onData(event.data)).catch((error) => this.#fail(error))
|
|
551
|
+
}
|
|
552
|
+
socket.onerror = () => this.#fail(new Error('relay WebSocket error'))
|
|
553
|
+
socket.onclose = (event) => this.#finish(event.code, event.reason)
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
#emit(type, event) {
|
|
557
|
+
const handler = this[`on${type}`]
|
|
558
|
+
if (typeof handler === 'function') {
|
|
559
|
+
try {
|
|
560
|
+
handler.call(this, event)
|
|
561
|
+
} catch (error) {
|
|
562
|
+
console.error('[dsh-remote] ws handler error', error)
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
this.dispatchEvent(event)
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
#fail(error) {
|
|
569
|
+
if (this.#closed) return
|
|
570
|
+
this.#closed = true
|
|
571
|
+
this.readyState = RemoteWebSocket.CLOSED
|
|
572
|
+
const event = new Event('error')
|
|
573
|
+
event.error = error
|
|
574
|
+
event.message = String(error?.message ?? error)
|
|
575
|
+
this.#emit('error', event)
|
|
576
|
+
this.#finish(1006, 'relay error')
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
#finish(code, reason) {
|
|
580
|
+
if (this.readyState === RemoteWebSocket.CLOSED) return
|
|
581
|
+
this.#closed = true
|
|
582
|
+
this.readyState = RemoteWebSocket.CLOSED
|
|
583
|
+
const event = new CloseEvent('close', { code, reason: String(reason ?? ''), wasClean: code !== 1006 })
|
|
584
|
+
this.#emit('close', event)
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
async #onData(data) {
|
|
588
|
+
const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(await data.arrayBuffer())
|
|
589
|
+
const queue = []
|
|
590
|
+
try {
|
|
591
|
+
const first = this.#reader.push(bytes)
|
|
592
|
+
if (first) queue.push(first)
|
|
593
|
+
for (;;) {
|
|
594
|
+
const next = this.#reader.push(null)
|
|
595
|
+
if (!next) break
|
|
596
|
+
queue.push(next)
|
|
597
|
+
}
|
|
598
|
+
} catch (error) {
|
|
599
|
+
this.#fail(error)
|
|
600
|
+
return
|
|
601
|
+
}
|
|
602
|
+
for (const frame of queue) {
|
|
603
|
+
await this.#handleFrame(frame)
|
|
604
|
+
if (this.#closed) return
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
async #handleFrame(frame) {
|
|
609
|
+
let opened
|
|
610
|
+
try {
|
|
611
|
+
opened = await open(frame)
|
|
612
|
+
} catch (error) {
|
|
613
|
+
this.#fail(error)
|
|
614
|
+
return
|
|
615
|
+
}
|
|
616
|
+
if (opened.type === FRAME_CONTROL) {
|
|
617
|
+
try {
|
|
618
|
+
const control = JSON.parse(decoder.decode(opened.plaintext))
|
|
619
|
+
if (control.renew) applyRenew(control.renew)
|
|
620
|
+
if (control.t === 'close') this.#finish(control.code ?? 1000, control.reason ?? '')
|
|
621
|
+
if (control.t === 'error') this.#fail(new Error(control.message || 'relay error'))
|
|
622
|
+
} catch {}
|
|
623
|
+
return
|
|
624
|
+
}
|
|
625
|
+
if (opened.type !== FRAME_DATA) return
|
|
626
|
+
const opcode = opened.plaintext[0]
|
|
627
|
+
const payload = opened.plaintext.slice(1)
|
|
628
|
+
let value
|
|
629
|
+
if (opcode === 0x1) value = decoder.decode(payload)
|
|
630
|
+
else if (this.binaryType === 'arraybuffer') value = payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.byteLength)
|
|
631
|
+
else value = new Blob([payload])
|
|
632
|
+
this.#emit('message', new MessageEvent('message', { data: value }))
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
send(data) {
|
|
636
|
+
if (this.readyState === RemoteWebSocket.CONNECTING || !this.#ready) {
|
|
637
|
+
this.#queue.push({ data })
|
|
638
|
+
return
|
|
639
|
+
}
|
|
640
|
+
if (this.readyState !== RemoteWebSocket.OPEN) throw new Error('WebSocket 已关闭')
|
|
641
|
+
let opcode = 0x1
|
|
642
|
+
let payload
|
|
643
|
+
if (typeof data === 'string') {
|
|
644
|
+
payload = textBytes(data)
|
|
645
|
+
} else if (data instanceof Blob) {
|
|
646
|
+
opcode = 0x2
|
|
647
|
+
data.arrayBuffer().then((buffer) => this.#sendBinary(new Uint8Array(buffer)))
|
|
648
|
+
return
|
|
649
|
+
} else if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
|
|
650
|
+
opcode = 0x2
|
|
651
|
+
payload = data instanceof ArrayBuffer ? new Uint8Array(data) : new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
|
|
652
|
+
} else {
|
|
653
|
+
opcode = 0x1
|
|
654
|
+
payload = textBytes(String(data))
|
|
655
|
+
}
|
|
656
|
+
this.#sendBinary(payload, opcode)
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
#sendBinary(payload, opcode = 0x2) {
|
|
660
|
+
const plaintext = concatBytes(new Uint8Array([opcode]), payload)
|
|
661
|
+
seal(FRAME_DATA, plaintext, 'c2s')
|
|
662
|
+
.then((frame) => this.#socket && this.#socket.readyState === 1 && this.#socket.send(lengthPrefixed(frame)))
|
|
663
|
+
.catch((error) => this.#fail(error))
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
close(code = 1000, reason = '') {
|
|
667
|
+
if (this.readyState === RemoteWebSocket.CLOSED || this.readyState === RemoteWebSocket.CLOSING) return
|
|
668
|
+
this.readyState = RemoteWebSocket.CLOSING
|
|
669
|
+
const socket = this.#socket
|
|
670
|
+
if (socket && socket.readyState === 1) {
|
|
671
|
+
seal(FRAME_CONTROL, textBytes(JSON.stringify({ t: 'close' })), 'c2s')
|
|
672
|
+
.then((frame) => socket.send(lengthPrefixed(frame)))
|
|
673
|
+
.catch(() => {})
|
|
674
|
+
}
|
|
675
|
+
setTimeout(() => {
|
|
676
|
+
try {
|
|
677
|
+
socket?.close(code, reason)
|
|
678
|
+
} catch {}
|
|
679
|
+
this.#finish(code, reason)
|
|
680
|
+
}, 50)
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
RemoteWebSocket.prototype.CONNECTING = 0
|
|
685
|
+
RemoteWebSocket.prototype.OPEN = 1
|
|
686
|
+
RemoteWebSocket.prototype.CLOSING = 2
|
|
687
|
+
RemoteWebSocket.prototype.CLOSED = 3
|
|
688
|
+
|
|
689
|
+
const wsStats = { shimmed: 0, passthrough: 0, lastUrl: null, lastError: null }
|
|
690
|
+
window.WebSocket = function shimWebSocket(url, protocols) {
|
|
691
|
+
try {
|
|
692
|
+
const target = new URL(String(url), location.href)
|
|
693
|
+
wsStats.lastUrl = target.href
|
|
694
|
+
// ws:/wss: 与 http:/https: 的 origin 不同,需按 host 比较
|
|
695
|
+
const sameHost = target.host === location.host
|
|
696
|
+
const httpish = ['http:', 'https:', 'ws:', 'wss:'].includes(target.protocol)
|
|
697
|
+
if (sameHost && httpish && !target.pathname.startsWith(E2E_PREFIX)) {
|
|
698
|
+
wsStats.shimmed += 1
|
|
699
|
+
return new RemoteWebSocket(url, protocols)
|
|
700
|
+
}
|
|
701
|
+
} catch (error) {
|
|
702
|
+
wsStats.lastError = String(error?.message ?? error)
|
|
703
|
+
}
|
|
704
|
+
wsStats.passthrough += 1
|
|
705
|
+
return new originalWebSocket(url, protocols)
|
|
706
|
+
}
|
|
707
|
+
window.WebSocket.prototype = originalWebSocket.prototype
|
|
708
|
+
Object.assign(window.WebSocket, {
|
|
709
|
+
CONNECTING: 0,
|
|
710
|
+
OPEN: 1,
|
|
711
|
+
CLOSING: 2,
|
|
712
|
+
CLOSED: 3,
|
|
713
|
+
})
|
|
714
|
+
|
|
715
|
+
// ───────────────────────── EventSource ─────────────────────────
|
|
716
|
+
|
|
717
|
+
class RemoteEventSource extends EventTarget {
|
|
718
|
+
constructor(url, options = {}) {
|
|
719
|
+
super()
|
|
720
|
+
this.url = String(url)
|
|
721
|
+
this.readyState = 0
|
|
722
|
+
this.onmessage = null
|
|
723
|
+
this.onerror = null
|
|
724
|
+
this.onopen = null
|
|
725
|
+
this.#options = options
|
|
726
|
+
this.#start()
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
#options
|
|
730
|
+
#controller = null
|
|
731
|
+
#buffer = ''
|
|
732
|
+
|
|
733
|
+
async #start() {
|
|
734
|
+
const target = new URL(this.url, location.href)
|
|
735
|
+
try {
|
|
736
|
+
this.#controller = new AbortController()
|
|
737
|
+
const response = await window.fetch(target.href, {
|
|
738
|
+
method: 'GET',
|
|
739
|
+
headers: { accept: 'text/event-stream', ...(this.#options.headers || {}) },
|
|
740
|
+
signal: this.#controller.signal,
|
|
741
|
+
cache: 'no-store',
|
|
742
|
+
})
|
|
743
|
+
if (!response.ok || !response.body) throw new Error(`EventSource HTTP ${String(response.status)}`)
|
|
744
|
+
this.readyState = 1
|
|
745
|
+
this.dispatchEvent(new Event('open'))
|
|
746
|
+
const reader = response.body.getReader()
|
|
747
|
+
const textDecoder = new TextDecoder()
|
|
748
|
+
for (;;) {
|
|
749
|
+
const { value, done } = await reader.read()
|
|
750
|
+
if (done) break
|
|
751
|
+
this.#buffer += textDecoder.decode(value, { stream: true })
|
|
752
|
+
let index
|
|
753
|
+
while ((index = this.#buffer.indexOf('\n\n')) !== -1) {
|
|
754
|
+
const chunk = this.#buffer.slice(0, index)
|
|
755
|
+
this.#buffer = this.#buffer.slice(index + 2)
|
|
756
|
+
this.#dispatchChunk(chunk)
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
this.readyState = 2
|
|
760
|
+
} catch (error) {
|
|
761
|
+
if (this.#controller?.signal.aborted) return
|
|
762
|
+
this.readyState = 2
|
|
763
|
+
const event = new Event('error')
|
|
764
|
+
event.message = String(error?.message ?? error)
|
|
765
|
+
this.dispatchEvent(event)
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
#dispatchChunk(chunk) {
|
|
770
|
+
let event = 'message'
|
|
771
|
+
let data = ''
|
|
772
|
+
for (const line of chunk.split('\n')) {
|
|
773
|
+
if (line.startsWith('event:')) event = line.slice(6).trim()
|
|
774
|
+
else if (line.startsWith('data:')) data += `${line.slice(5).trim()}\n`
|
|
775
|
+
}
|
|
776
|
+
if (data.endsWith('\n')) data = data.slice(0, -1)
|
|
777
|
+
const message = new MessageEvent(event, { data })
|
|
778
|
+
const handler = this[`on${event}`]
|
|
779
|
+
if (typeof handler === 'function') handler.call(this, message)
|
|
780
|
+
this.dispatchEvent(message)
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
close() {
|
|
784
|
+
this.readyState = 2
|
|
785
|
+
this.#controller?.abort()
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
if (originalEventSource) {
|
|
790
|
+
window.EventSource = function shimEventSource(url, options) {
|
|
791
|
+
try {
|
|
792
|
+
const target = new URL(String(url), location.href)
|
|
793
|
+
if (target.origin === location.origin && !target.pathname.startsWith(E2E_PREFIX)) {
|
|
794
|
+
return new RemoteEventSource(url, options)
|
|
795
|
+
}
|
|
796
|
+
} catch {}
|
|
797
|
+
return new originalEventSource(url, options)
|
|
798
|
+
}
|
|
799
|
+
window.EventSource.prototype = originalEventSource.prototype
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// ───────────────────────── 启动 ─────────────────────────
|
|
803
|
+
|
|
804
|
+
async function boot() {
|
|
805
|
+
const psk = currentPsk()
|
|
806
|
+
if (document.getElementById('state')) {
|
|
807
|
+
if (!psk) {
|
|
808
|
+
report('缺少 #k=<key> 访问密钥,请用完整链接打开。', true)
|
|
809
|
+
return
|
|
810
|
+
}
|
|
811
|
+
report('正在建立端到端加密会话…')
|
|
812
|
+
try {
|
|
813
|
+
await ensureSession()
|
|
814
|
+
report('已解锁,正在进入…')
|
|
815
|
+
location.replace('/')
|
|
816
|
+
} catch (error) {
|
|
817
|
+
report(`解锁失败:${String(error?.message ?? error)}`, true)
|
|
818
|
+
}
|
|
819
|
+
return
|
|
820
|
+
}
|
|
821
|
+
if (!psk) return
|
|
822
|
+
ensureSession().catch((error) => {
|
|
823
|
+
console.warn('[dsh-remote] session failed', error)
|
|
824
|
+
})
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
window.__DSH_REMOTE__ = {
|
|
828
|
+
state,
|
|
829
|
+
version: 1,
|
|
830
|
+
wsStats,
|
|
831
|
+
bind: ensureSession,
|
|
832
|
+
pskKid: () => state.pskKid,
|
|
833
|
+
handshakes: () => state.handshakes,
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot, { once: true })
|
|
837
|
+
else boot()
|
|
838
|
+
})()
|