dsh-quay-bot 1.0.2 → 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -105
- package/botscreen/requirements.txt +1 -1
- package/client.js +3 -2
- 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 +35 -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
|
@@ -0,0 +1,1028 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 边缘代理:Cloudflare 隧道唯一入口。
|
|
3
|
+
*
|
|
4
|
+
* 三条通道:
|
|
5
|
+
* 1) /__dsh/* —— 握手、绑定、端到端加密数据面、shim 分发;
|
|
6
|
+
* 2) 已认证静态通道 —— SPA 外壳与静态资源(经 relay 注入上游 cookie 后转发);
|
|
7
|
+
* 3) /__dsh/ws —— 加密 WebSocket 桥,承载 DSH 实时流。
|
|
8
|
+
*
|
|
9
|
+
* 安全边界:Cloudflare 只能看到 path 前缀、密文与体积;Access 凭证 / DSH launch token /
|
|
10
|
+
* 上游会话 cookie 全部只在浏览器↔relay 的加密通道内,或以 fragment(#k=)形式从不离开浏览器。
|
|
11
|
+
*/
|
|
12
|
+
import http from 'node:http'
|
|
13
|
+
import { createHash } from 'node:crypto'
|
|
14
|
+
import { readFileSync } from 'node:fs'
|
|
15
|
+
import { dirname, join } from 'node:path'
|
|
16
|
+
import { fileURLToPath } from 'node:url'
|
|
17
|
+
import {
|
|
18
|
+
FRAME_CLOSE,
|
|
19
|
+
FRAME_CONTROL,
|
|
20
|
+
FRAME_DATA,
|
|
21
|
+
FrameDecoder,
|
|
22
|
+
deriveKeys,
|
|
23
|
+
encodeLengthPrefixed,
|
|
24
|
+
newSessionId,
|
|
25
|
+
openFrame,
|
|
26
|
+
sealFrame,
|
|
27
|
+
sharedSecret,
|
|
28
|
+
verifyBindProof,
|
|
29
|
+
} from './crypto.mjs'
|
|
30
|
+
import { b64u, unb64u } from './util.mjs'
|
|
31
|
+
import { acceptUpgrade, connectWebSocket } from './ws.mjs'
|
|
32
|
+
|
|
33
|
+
const __dirname = dirname(fileURLToPath(import.meta.url))
|
|
34
|
+
const SHIM_PATH = join(__dirname, 'shim.js')
|
|
35
|
+
|
|
36
|
+
const HOP_BY_HOP = new Set([
|
|
37
|
+
'connection',
|
|
38
|
+
'keep-alive',
|
|
39
|
+
'proxy-authenticate',
|
|
40
|
+
'proxy-authorization',
|
|
41
|
+
'te',
|
|
42
|
+
'trailer',
|
|
43
|
+
'transfer-encoding',
|
|
44
|
+
'upgrade',
|
|
45
|
+
'content-length',
|
|
46
|
+
'accept-encoding',
|
|
47
|
+
])
|
|
48
|
+
|
|
49
|
+
const STRIP_RESPONSE = new Set(['set-cookie', 'content-length', 'content-encoding', 'transfer-encoding', 'connection'])
|
|
50
|
+
|
|
51
|
+
const DROP_REQUEST = new Set([
|
|
52
|
+
'x-forwarded-for',
|
|
53
|
+
'x-forwarded-proto',
|
|
54
|
+
'x-forwarded-host',
|
|
55
|
+
'x-forwarded-port',
|
|
56
|
+
'x-real-ip',
|
|
57
|
+
'forwarded',
|
|
58
|
+
'cf-connecting-ip',
|
|
59
|
+
'cf-ipcountry',
|
|
60
|
+
'cf-ray',
|
|
61
|
+
'cf-visitor',
|
|
62
|
+
'cf-warp-tag-id',
|
|
63
|
+
'cdn-loop',
|
|
64
|
+
'true-client-ip',
|
|
65
|
+
'cf-access-jwt-assertion',
|
|
66
|
+
'cf-access-authenticated-user-email',
|
|
67
|
+
])
|
|
68
|
+
|
|
69
|
+
const E2E_PREFIX = '/__dsh'
|
|
70
|
+
const SESSION_COOKIE = 'dshr_sid'
|
|
71
|
+
// App 直连通道的 cookie 必须用 dsh-auth- 前缀:Android 客户端的 CookieJar 只持久化该前缀
|
|
72
|
+
const PLAIN_COOKIE = 'dsh-auth-relay'
|
|
73
|
+
const PLAIN_COOKIE_ALIASES = ['dsh-auth-relay', 'dshr_plain']
|
|
74
|
+
|
|
75
|
+
const nullLogger = { info() {}, warn() {}, error() {} }
|
|
76
|
+
|
|
77
|
+
export function createEdge({ config, keys, sessions, upstream, logger = nullLogger, shimSource = null }) {
|
|
78
|
+
const stats = { startedAt: Date.now(), requests: 0, e2e: 0, ws: 0, bytesIn: 0, bytesOut: 0, errors: 0, rejected: 0 }
|
|
79
|
+
const shim = shimSource ?? readFileSync(SHIM_PATH, 'utf8')
|
|
80
|
+
const shimBuild = createHash('sha256').update(shim).digest('hex').slice(0, 12)
|
|
81
|
+
const plainSessions = new Map()
|
|
82
|
+
const sessions_ttl = config.e2e.sessionTtlHours * 3_600_000
|
|
83
|
+
|
|
84
|
+
const server = http.createServer((req, res) => {
|
|
85
|
+
stats.requests += 1
|
|
86
|
+
route(req, res).catch((error) => {
|
|
87
|
+
stats.errors += 1
|
|
88
|
+
logger.error('request failed', { url: req.url, error: String(error?.message ?? error) })
|
|
89
|
+
if (!res.headersSent) {
|
|
90
|
+
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' })
|
|
91
|
+
}
|
|
92
|
+
if (!res.writableEnded) res.end('relay error\n')
|
|
93
|
+
})
|
|
94
|
+
})
|
|
95
|
+
|
|
96
|
+
server.on('upgrade', (req, socket, head) => {
|
|
97
|
+
handleUpgrade(req, socket, head).catch((error) => {
|
|
98
|
+
stats.errors += 1
|
|
99
|
+
logger.error('upgrade failed', { url: req.url, error: String(error?.message ?? error) })
|
|
100
|
+
try {
|
|
101
|
+
socket.end('HTTP/1.1 502 Bad Gateway\r\n\r\n')
|
|
102
|
+
} catch {}
|
|
103
|
+
})
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
// ───────────────────────────── 路由 ─────────────────────────────
|
|
107
|
+
|
|
108
|
+
async function route(req, res) {
|
|
109
|
+
const url = new URL(normalizePath(req.url), 'http://relay.invalid')
|
|
110
|
+
if (url.pathname === `${E2E_PREFIX}/health`) return sendJson(res, 200, healthPayload())
|
|
111
|
+
if (url.pathname === `${E2E_PREFIX}/shim.js`) return sendShim(req, res)
|
|
112
|
+
|
|
113
|
+
if (config.e2e.enabled) {
|
|
114
|
+
if (url.pathname === `${E2E_PREFIX}/handshake`) return handleHandshake(req, res)
|
|
115
|
+
if (url.pathname === `${E2E_PREFIX}/bind`) return handleBind(req, res)
|
|
116
|
+
if (url.pathname === `${E2E_PREFIX}/e2e`) return handleE2E(req, res)
|
|
117
|
+
if (url.pathname === `${E2E_PREFIX}/link`) return handleLink(req, res)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// 旧式 ?token= 链接(兼容 / 备用通道,默认关闭)
|
|
121
|
+
if ((config.proxy.legacyToken || config.proxy.appBridge) && url.searchParams.has('token')) {
|
|
122
|
+
return handleLegacyToken(req, res, url)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const session = sessionFromRequest(req)
|
|
126
|
+
const plain = plainSessionFromRequest(req)
|
|
127
|
+
if (!session && !plain) {
|
|
128
|
+
if (wantsHtml(req)) return sendUnlockPage(req, res)
|
|
129
|
+
stats.rejected += 1
|
|
130
|
+
return sendJson(res, 401, { error: 'unauthorized', hint: 'open the link that contains #k=<key>' })
|
|
131
|
+
}
|
|
132
|
+
// 只有 E2E 加密会话(dshr_sid)才注入 shim.js;明文/App 直连通道(?token=)直接走普通 cookie,
|
|
133
|
+
// 否则浏览器打开 App 链接时会被 shim.js 劫持 fetch 并报错「地址缺少 #k=<key> 访问密钥」。
|
|
134
|
+
return proxyStatic(req, res, url, { injectE2eShim: Boolean(session && config.e2e.enabled) })
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ───────────────────────────── 会话 ─────────────────────────────
|
|
138
|
+
|
|
139
|
+
function sessionFromRequest(req) {
|
|
140
|
+
const cookies = parseCookies(req.headers.cookie)
|
|
141
|
+
const sid = cookies[SESSION_COOKIE]
|
|
142
|
+
if (!sid) return null
|
|
143
|
+
return sessions.get(sid)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function plainSessionFromRequest(req) {
|
|
147
|
+
const cookies = parseCookies(req.headers.cookie)
|
|
148
|
+
for (const name of PLAIN_COOKIE_ALIASES) {
|
|
149
|
+
const token = cookies[name]
|
|
150
|
+
if (!token) continue
|
|
151
|
+
const entry = plainSessions.get(token)
|
|
152
|
+
if (entry && entry.expiresAt >= Date.now()) return entry
|
|
153
|
+
plainSessions.delete(token)
|
|
154
|
+
}
|
|
155
|
+
return null
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function cookieAttributes(req, maxAgeSeconds) {
|
|
159
|
+
const secure = isSecureRequest(req)
|
|
160
|
+
return `Path=/; HttpOnly; SameSite=Lax; Max-Age=${String(maxAgeSeconds)}${secure ? '; Secure' : ''}`
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function isSecureRequest(req) {
|
|
164
|
+
const proto = String(req.headers['x-forwarded-proto'] ?? '').split(',')[0].trim()
|
|
165
|
+
if (proto === 'https') return true
|
|
166
|
+
if (req.headers['cf-visitor']) {
|
|
167
|
+
try {
|
|
168
|
+
if (JSON.parse(String(req.headers['cf-visitor'])).scheme === 'https') return true
|
|
169
|
+
} catch {}
|
|
170
|
+
}
|
|
171
|
+
return false
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function bindSessionCookie(res, req, sid, ttlSeconds) {
|
|
175
|
+
res.setHeader('set-cookie', `${SESSION_COOKIE}=${sid}; ${cookieAttributes(req, ttlSeconds)}`)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function healthPayload() {
|
|
179
|
+
return {
|
|
180
|
+
ok: true,
|
|
181
|
+
service: 'dsh-remote',
|
|
182
|
+
e2e: config.e2e.enabled,
|
|
183
|
+
version: 1,
|
|
184
|
+
upstream: upstream.ready,
|
|
185
|
+
sessions: sessions.size,
|
|
186
|
+
ws: stats.ws,
|
|
187
|
+
pskKid: keys.activePsk()?.kid ?? null,
|
|
188
|
+
now: new Date().toISOString(),
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// ───────────────────────────── 握手 / 绑定 ─────────────────────────────
|
|
193
|
+
|
|
194
|
+
function handleHandshake(req, res) {
|
|
195
|
+
if (req.method !== 'GET') return sendJson(res, 405, { error: 'method_not_allowed' })
|
|
196
|
+
const identity = keys.identity
|
|
197
|
+
const challenge = sessions.issueChallenge(identity)
|
|
198
|
+
sendJson(
|
|
199
|
+
res,
|
|
200
|
+
200,
|
|
201
|
+
{
|
|
202
|
+
v: 1,
|
|
203
|
+
kid: challenge.kid,
|
|
204
|
+
spk: challenge.spk,
|
|
205
|
+
nonce: challenge.nonce,
|
|
206
|
+
exp: challenge.expiresAt,
|
|
207
|
+
algo: 'ECDH-P256+HKDF-SHA256+AES-256-GCM',
|
|
208
|
+
sid_len: 16,
|
|
209
|
+
},
|
|
210
|
+
{ 'cache-control': 'no-store' },
|
|
211
|
+
)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function handleBind(req, res) {
|
|
215
|
+
if (req.method !== 'POST') return sendJson(res, 405, { error: 'method_not_allowed' })
|
|
216
|
+
if (!sameOrigin(req)) return deny(res, 403, 'bad_origin')
|
|
217
|
+
const body = await readJsonBody(req, 8 * 1024)
|
|
218
|
+
if (!body || body.v !== 1) return sendJson(res, 400, { error: 'bad_request' })
|
|
219
|
+
const { kid, cpk, nonce, proof } = body
|
|
220
|
+
if (typeof kid !== 'string' || typeof cpk !== 'string' || typeof nonce !== 'string' || typeof proof !== 'string') {
|
|
221
|
+
return sendJson(res, 400, { error: 'bad_request' })
|
|
222
|
+
}
|
|
223
|
+
const challenge = sessions.consumeChallenge(nonce, kid)
|
|
224
|
+
if (!challenge) return deny(res, 401, 'challenge_expired')
|
|
225
|
+
const identity = keys.identityById(kid) ?? keys.identity
|
|
226
|
+
const proofBuffer = unb64u(proof)
|
|
227
|
+
let matched = null
|
|
228
|
+
for (const candidate of keys.candidates()) {
|
|
229
|
+
if (verifyBindProof(candidate.psk, { kid, spk: identity.spki, cpk, nonce: challenge.nonce, proof: proofBuffer })) {
|
|
230
|
+
matched = candidate
|
|
231
|
+
break
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (!matched) {
|
|
235
|
+
stats.rejected += 1
|
|
236
|
+
logger.warn('bind rejected: bad proof', { kid, remote: clientAddr(req) })
|
|
237
|
+
return deny(res, 401, 'bad_proof')
|
|
238
|
+
}
|
|
239
|
+
let secret
|
|
240
|
+
try {
|
|
241
|
+
secret = sharedSecret(identity.privateJwk, cpk)
|
|
242
|
+
} catch (error) {
|
|
243
|
+
return sendJson(res, 400, { error: 'bad_public_key', detail: String(error?.message ?? error) })
|
|
244
|
+
}
|
|
245
|
+
const sidBuffer = newSessionId()
|
|
246
|
+
const sid = b64u(sidBuffer)
|
|
247
|
+
const derived = deriveKeys({
|
|
248
|
+
secret,
|
|
249
|
+
salt: unb64u(challenge.nonce),
|
|
250
|
+
kid,
|
|
251
|
+
spk: identity.spki,
|
|
252
|
+
cpk,
|
|
253
|
+
sessionId: sidBuffer,
|
|
254
|
+
})
|
|
255
|
+
const session = sessions.create({
|
|
256
|
+
sid: sidBuffer,
|
|
257
|
+
kid,
|
|
258
|
+
keys: derived,
|
|
259
|
+
pskKid: matched.kid,
|
|
260
|
+
remote: clientAddr(req),
|
|
261
|
+
userAgent: req.headers['user-agent'] ?? null,
|
|
262
|
+
})
|
|
263
|
+
bindSessionCookie(res, req, sid, Math.floor(sessions_ttl / 1000))
|
|
264
|
+
logger.info('session bound', { sid: `${sid.slice(0, 8)}…`, kid, pskKid: matched.kid, remote: session.remote })
|
|
265
|
+
sendJson(
|
|
266
|
+
res,
|
|
267
|
+
200,
|
|
268
|
+
{
|
|
269
|
+
v: 1,
|
|
270
|
+
sid,
|
|
271
|
+
ttl: Math.floor(sessions_ttl / 1000),
|
|
272
|
+
renewAfter: Math.floor((sessions_ttl * 0.7) / 1000),
|
|
273
|
+
pskKid: matched.kid,
|
|
274
|
+
},
|
|
275
|
+
{ 'cache-control': 'no-store' },
|
|
276
|
+
)
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// ───────────────────────────── 加密数据面 ─────────────────────────────
|
|
280
|
+
|
|
281
|
+
async function handleE2E(req, res) {
|
|
282
|
+
if (req.method !== 'POST') return sendJson(res, 405, { error: 'method_not_allowed' })
|
|
283
|
+
const session = sessionFromRequest(req)
|
|
284
|
+
if (!session) return deny(res, 401, 'no_session')
|
|
285
|
+
if (!sameOrigin(req)) return deny(res, 403, 'bad_origin')
|
|
286
|
+
stats.e2e += 1
|
|
287
|
+
|
|
288
|
+
const body = await readBody(req, config.proxy.maxBodyBytes)
|
|
289
|
+
stats.bytesIn += body.length
|
|
290
|
+
const decoder = new FrameDecoder({ maxFrameBytes: config.e2e.maxFrameBytes })
|
|
291
|
+
let frames
|
|
292
|
+
try {
|
|
293
|
+
frames = decoder.push(body)
|
|
294
|
+
} catch (error) {
|
|
295
|
+
return deny(res, 400, 'bad_frame', String(error?.message ?? error))
|
|
296
|
+
}
|
|
297
|
+
if (frames.length === 0) return deny(res, 400, 'empty_body')
|
|
298
|
+
|
|
299
|
+
const requests = []
|
|
300
|
+
for (const frame of frames) {
|
|
301
|
+
if (!session.c2sWindow.allows(frame.readUInt32BE(2))) continue
|
|
302
|
+
let opened
|
|
303
|
+
try {
|
|
304
|
+
opened = openFrame({ key: session.keys.c2s, sid: session.sid, frame, aadExtra: Buffer.from('c2s') })
|
|
305
|
+
} catch (error) {
|
|
306
|
+
stats.rejected += 1
|
|
307
|
+
return deny(res, 400, 'decrypt_failed', String(error?.message ?? error))
|
|
308
|
+
}
|
|
309
|
+
if (!session.c2sWindow.accept(opened.seq)) continue
|
|
310
|
+
if (opened.type !== FRAME_DATA) continue
|
|
311
|
+
requests.push(opened.plaintext)
|
|
312
|
+
}
|
|
313
|
+
if (requests.length === 0) return deny(res, 400, 'no_data_frame')
|
|
314
|
+
|
|
315
|
+
let envelope
|
|
316
|
+
try {
|
|
317
|
+
envelope = JSON.parse(Buffer.concat(requests).toString('utf8'))
|
|
318
|
+
} catch {
|
|
319
|
+
return deny(res, 400, 'bad_envelope')
|
|
320
|
+
}
|
|
321
|
+
if (!validateEnvelope(envelope)) return deny(res, 400, 'bad_envelope')
|
|
322
|
+
|
|
323
|
+
res.writeHead(200, {
|
|
324
|
+
'content-type': 'application/octet-stream',
|
|
325
|
+
'cache-control': 'no-store',
|
|
326
|
+
'x-content-type-options': 'nosniff',
|
|
327
|
+
})
|
|
328
|
+
const crypto = { session, seq: () => sessions.nextSeq(session), closed: false }
|
|
329
|
+
const writeFrame = (type, plaintext) => {
|
|
330
|
+
if (crypto.closed || res.writableEnded) return false
|
|
331
|
+
const frame = sealFrame({
|
|
332
|
+
key: session.keys.s2c,
|
|
333
|
+
sid: session.sid,
|
|
334
|
+
seq: crypto.seq(),
|
|
335
|
+
type,
|
|
336
|
+
plaintext,
|
|
337
|
+
aadExtra: Buffer.from('s2c'),
|
|
338
|
+
})
|
|
339
|
+
const wire = encodeLengthPrefixed(frame)
|
|
340
|
+
const ok = res.write(wire)
|
|
341
|
+
stats.bytesOut += frame.length
|
|
342
|
+
session.bytesOut += frame.length
|
|
343
|
+
return ok
|
|
344
|
+
}
|
|
345
|
+
const finish = (control) => {
|
|
346
|
+
if (crypto.closed) return
|
|
347
|
+
try {
|
|
348
|
+
if (control) writeFrame(FRAME_CLOSE, Buffer.from(JSON.stringify(control)))
|
|
349
|
+
} finally {
|
|
350
|
+
crypto.closed = true
|
|
351
|
+
if (!res.writableEnded) res.end()
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
res.on('close', () => {
|
|
355
|
+
crypto.closed = true
|
|
356
|
+
})
|
|
357
|
+
|
|
358
|
+
await forwardToUpstream(envelope, {
|
|
359
|
+
session,
|
|
360
|
+
writeFrame,
|
|
361
|
+
finish,
|
|
362
|
+
res,
|
|
363
|
+
})
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function validateEnvelope(envelope) {
|
|
367
|
+
if (!envelope || typeof envelope !== 'object') return false
|
|
368
|
+
const { m, p, h, b } = envelope
|
|
369
|
+
if (typeof m !== 'string' || !/^[A-Z]+$/u.test(m)) return false
|
|
370
|
+
if (typeof p !== 'string' || !p.startsWith('/') || p.length > 8192) return false
|
|
371
|
+
if (p.startsWith('//')) return false
|
|
372
|
+
if (h !== undefined && (typeof h !== 'object' || h === null || Array.isArray(h))) return false
|
|
373
|
+
if (h) {
|
|
374
|
+
const names = Object.keys(h)
|
|
375
|
+
if (names.length > 64) return false
|
|
376
|
+
for (const name of names) {
|
|
377
|
+
if (name.length > 128 || !/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/u.test(name)) return false
|
|
378
|
+
const value = h[name]
|
|
379
|
+
if (typeof value !== 'string' && !Array.isArray(value)) return false
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
if (b !== undefined && b !== null && typeof b !== 'string') return false
|
|
383
|
+
if (typeof b === 'string' && b.length > Math.ceil((config.proxy.maxBodyBytes * 4) / 3) + 8) return false
|
|
384
|
+
return true
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async function forwardToUpstream(envelope, { session, writeFrame, finish, res }) {
|
|
388
|
+
const method = envelope.m
|
|
389
|
+
const path = envelope.p
|
|
390
|
+
const headers = scrubUpstreamHeaders(envelope.h ?? {}, { method })
|
|
391
|
+
const bodyBuffer = typeof envelope.b === 'string' && envelope.b.length > 0 ? unb64u(envelope.b) : null
|
|
392
|
+
|
|
393
|
+
const upstreamReq = http.request(
|
|
394
|
+
{
|
|
395
|
+
host: upstream.info.host,
|
|
396
|
+
port: upstream.info.port,
|
|
397
|
+
method,
|
|
398
|
+
path,
|
|
399
|
+
headers,
|
|
400
|
+
},
|
|
401
|
+
(upstreamRes) => {
|
|
402
|
+
const responseHeaders = cleanResponseHeaders(upstreamRes.headers)
|
|
403
|
+
const meta = { s: upstreamRes.statusCode ?? 502, h: responseHeaders }
|
|
404
|
+
const renewal = sessions.takeRenewal(session, session.pskKid)
|
|
405
|
+
if (renewal) meta.renew = renewal
|
|
406
|
+
const primary = writeFrame(FRAME_CONTROL, Buffer.from(JSON.stringify(meta)))
|
|
407
|
+
let closed = false
|
|
408
|
+
const abort = () => {
|
|
409
|
+
closed = true
|
|
410
|
+
upstreamRes.destroy()
|
|
411
|
+
}
|
|
412
|
+
res.on('close', abort)
|
|
413
|
+
if (upstreamRes.statusCode === 401 || upstreamRes.statusCode === 403) {
|
|
414
|
+
upstream.onUnauthorized().catch((error) => logger.warn('upstream rebootstrap failed', { error: String(error?.message ?? error) }))
|
|
415
|
+
}
|
|
416
|
+
upstreamRes.on('data', (chunk) => {
|
|
417
|
+
if (closed) return
|
|
418
|
+
if (!writeFrame(FRAME_DATA, chunk)) {
|
|
419
|
+
upstreamRes.pause()
|
|
420
|
+
res.once('drain', () => upstreamRes.resume())
|
|
421
|
+
}
|
|
422
|
+
session.bytesIn += chunk.length
|
|
423
|
+
})
|
|
424
|
+
upstreamRes.on('end', () => {
|
|
425
|
+
finish({ t: 'end' })
|
|
426
|
+
})
|
|
427
|
+
upstreamRes.on('error', (error) => {
|
|
428
|
+
finish({ t: 'error', message: String(error?.message ?? error) })
|
|
429
|
+
})
|
|
430
|
+
if (!primary) upstreamRes.pause()
|
|
431
|
+
},
|
|
432
|
+
)
|
|
433
|
+
upstreamReq.on('error', (error) => {
|
|
434
|
+
stats.errors += 1
|
|
435
|
+
writeFrame(FRAME_CONTROL, Buffer.from(JSON.stringify({ s: 502, h: { 'content-type': 'text/plain; charset=utf-8' } })))
|
|
436
|
+
writeFrame(FRAME_DATA, Buffer.from(`upstream error: ${String(error?.message ?? error)}\n`))
|
|
437
|
+
finish({ t: 'error', message: `upstream: ${String(error?.message ?? error)}` })
|
|
438
|
+
})
|
|
439
|
+
if (bodyBuffer) upstreamReq.end(bodyBuffer)
|
|
440
|
+
else upstreamReq.end()
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function handleLink(req, res) {
|
|
444
|
+
const session = sessionFromRequest(req)
|
|
445
|
+
if (!session) return deny(res, 401, 'no_session')
|
|
446
|
+
const base = publicBaseUrl(req)
|
|
447
|
+
const active = keys.activePsk()
|
|
448
|
+
sendJson(res, 200, {
|
|
449
|
+
link: keys.link(base),
|
|
450
|
+
kid: active?.kid ?? null,
|
|
451
|
+
expiresAt: active ? new Date(active.expiresAt).toISOString() : null,
|
|
452
|
+
session: { sid: `${session.sidB64.slice(0, 8)}…`, kid: session.pskKid },
|
|
453
|
+
})
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// ───────────────────────────── 静态转发 ─────────────────────────────
|
|
457
|
+
|
|
458
|
+
function proxyStatic(req, res, url, { retried = false, injectE2eShim = true } = {}) {
|
|
459
|
+
const headers = scrubUpstreamHeaders(req.headers, { method: req.method, raw: true })
|
|
460
|
+
const upstreamReq = http.request(
|
|
461
|
+
{
|
|
462
|
+
host: upstream.info.host,
|
|
463
|
+
port: upstream.info.port,
|
|
464
|
+
method: req.method,
|
|
465
|
+
path: `${url.pathname}${url.search}`,
|
|
466
|
+
headers,
|
|
467
|
+
},
|
|
468
|
+
(upstreamRes) => {
|
|
469
|
+
const status = upstreamRes.statusCode ?? 502
|
|
470
|
+
if ((status === 401 || status === 403) && !retried && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
471
|
+
upstreamRes.resume()
|
|
472
|
+
upstream
|
|
473
|
+
.onUnauthorized()
|
|
474
|
+
.then(() => proxyStatic(req, res, url, { retried: true, injectE2eShim }))
|
|
475
|
+
.catch((error) => {
|
|
476
|
+
stats.errors += 1
|
|
477
|
+
if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' })
|
|
478
|
+
if (!res.writableEnded) res.end(`upstream auth refresh failed: ${String(error?.message ?? error)}\n`)
|
|
479
|
+
})
|
|
480
|
+
return
|
|
481
|
+
}
|
|
482
|
+
if (status === 401 || status === 403) {
|
|
483
|
+
upstream.onUnauthorized().catch((error) => logger.warn('upstream rebootstrap failed', { error: String(error?.message ?? error) }))
|
|
484
|
+
}
|
|
485
|
+
const outHeaders = cleanResponseHeaders(upstreamRes.headers)
|
|
486
|
+
const contentType = String(outHeaders['content-type'] ?? '')
|
|
487
|
+
const isHtml = contentType.includes('text/html')
|
|
488
|
+
if (!isHtml || !injectE2eShim) {
|
|
489
|
+
if (isHtml) outHeaders['cache-control'] = 'no-store'
|
|
490
|
+
res.writeHead(status, outHeaders)
|
|
491
|
+
upstreamRes.pipe(res)
|
|
492
|
+
return
|
|
493
|
+
}
|
|
494
|
+
const chunks = []
|
|
495
|
+
let size = 0
|
|
496
|
+
upstreamRes.on('data', (chunk) => {
|
|
497
|
+
size += chunk.length
|
|
498
|
+
if (size > 8 * 1024 * 1024) {
|
|
499
|
+
req.destroy()
|
|
500
|
+
return
|
|
501
|
+
}
|
|
502
|
+
chunks.push(chunk)
|
|
503
|
+
})
|
|
504
|
+
upstreamRes.on('end', () => {
|
|
505
|
+
const html = injectShim(Buffer.concat(chunks).toString('utf8'))
|
|
506
|
+
delete outHeaders['content-length']
|
|
507
|
+
outHeaders['cache-control'] = 'no-store'
|
|
508
|
+
res.writeHead(status, outHeaders)
|
|
509
|
+
res.end(html)
|
|
510
|
+
})
|
|
511
|
+
},
|
|
512
|
+
)
|
|
513
|
+
upstreamReq.on('error', (error) => {
|
|
514
|
+
stats.errors += 1
|
|
515
|
+
if (!res.headersSent) res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' })
|
|
516
|
+
if (!res.writableEnded) res.end(`upstream error: ${String(error?.message ?? error)}\n`)
|
|
517
|
+
})
|
|
518
|
+
res.on('close', () => {
|
|
519
|
+
if (!upstreamReq.destroyed && !res.writableEnded) upstreamReq.destroy()
|
|
520
|
+
})
|
|
521
|
+
req.pipe(upstreamReq)
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function injectShim(html) {
|
|
525
|
+
if (!config.e2e.enabled || html.includes(E2E_PREFIX + '/shim.js')) return html
|
|
526
|
+
const tag = `<script src="${E2E_PREFIX}/shim.js?v=${shimBuild}" data-dsh-remote="e2e"></script>`
|
|
527
|
+
if (/<head[^>]*>/iu.test(html)) return html.replace(/<head[^>]*>/iu, (match) => `${match}${tag}`)
|
|
528
|
+
return `${tag}${html}`
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// ───────────────────────────── WebSocket 桥 ─────────────────────────────
|
|
532
|
+
|
|
533
|
+
async function handleUpgrade(req, socket, head) {
|
|
534
|
+
const url = new URL(normalizePath(req.url), 'http://relay.invalid')
|
|
535
|
+
if (!url.pathname.startsWith(`${E2E_PREFIX}/`)) {
|
|
536
|
+
// App / 明文通道:直通上游 WS(cookie 由 relay 注入)
|
|
537
|
+
const plain = plainSessionFromRequest(req)
|
|
538
|
+
if (!plain) {
|
|
539
|
+
socket.end('HTTP/1.1 401 Unauthorized\r\n\r\n')
|
|
540
|
+
return
|
|
541
|
+
}
|
|
542
|
+
if (!sameOrigin(req)) {
|
|
543
|
+
socket.end('HTTP/1.1 403 Forbidden\r\n\r\n')
|
|
544
|
+
return
|
|
545
|
+
}
|
|
546
|
+
await bridgePlainWebSocket(req, socket, head, `${url.pathname}${url.search}`)
|
|
547
|
+
return
|
|
548
|
+
}
|
|
549
|
+
if (url.pathname !== `${E2E_PREFIX}/ws`) {
|
|
550
|
+
socket.end('HTTP/1.1 404 Not Found\r\n\r\n')
|
|
551
|
+
return
|
|
552
|
+
}
|
|
553
|
+
const session = sessionFromRequest(req)
|
|
554
|
+
if (!session) {
|
|
555
|
+
socket.end('HTTP/1.1 401 Unauthorized\r\n\r\n')
|
|
556
|
+
return
|
|
557
|
+
}
|
|
558
|
+
if (!sameOrigin(req)) {
|
|
559
|
+
socket.end('HTTP/1.1 403 Forbidden\r\n\r\n')
|
|
560
|
+
return
|
|
561
|
+
}
|
|
562
|
+
const client = acceptUpgrade(req, socket, head, { maxPayload: config.e2e.maxFrameBytes })
|
|
563
|
+
if (!client) return
|
|
564
|
+
stats.ws += 1
|
|
565
|
+
session.ws = client
|
|
566
|
+
client.on('close', () => {
|
|
567
|
+
if (session.ws === client) session.ws = null
|
|
568
|
+
})
|
|
569
|
+
bridgeWebSocket(session, client)
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
function bridgeWebSocket(session, client) {
|
|
573
|
+
const decoder = new FrameDecoder({ maxFrameBytes: config.e2e.maxFrameBytes })
|
|
574
|
+
let upstreamWs = null
|
|
575
|
+
const queue = []
|
|
576
|
+
let closed = false
|
|
577
|
+
|
|
578
|
+
const sendControl = (obj) => {
|
|
579
|
+
const frame = sealFrame({
|
|
580
|
+
key: session.keys.s2c,
|
|
581
|
+
sid: session.sid,
|
|
582
|
+
seq: sessions.nextSeq(session),
|
|
583
|
+
type: FRAME_CONTROL,
|
|
584
|
+
plaintext: Buffer.from(JSON.stringify(obj)),
|
|
585
|
+
aadExtra: Buffer.from('s2c'),
|
|
586
|
+
})
|
|
587
|
+
client.sendBinary(encodeLengthPrefixed(frame))
|
|
588
|
+
}
|
|
589
|
+
const sendData = (opcode, payload, type = FRAME_DATA) => {
|
|
590
|
+
const plaintext = Buffer.concat([Buffer.from([opcode]), payload])
|
|
591
|
+
const frame = sealFrame({
|
|
592
|
+
key: session.keys.s2c,
|
|
593
|
+
sid: session.sid,
|
|
594
|
+
seq: sessions.nextSeq(session),
|
|
595
|
+
type,
|
|
596
|
+
plaintext,
|
|
597
|
+
aadExtra: Buffer.from('s2c'),
|
|
598
|
+
})
|
|
599
|
+
client.sendBinary(encodeLengthPrefixed(frame))
|
|
600
|
+
}
|
|
601
|
+
const shutdown = (code = 1000, reason = 'relay closed') => {
|
|
602
|
+
if (closed) return
|
|
603
|
+
closed = true
|
|
604
|
+
try {
|
|
605
|
+
upstreamWs?.close(code, reason)
|
|
606
|
+
} catch {}
|
|
607
|
+
try {
|
|
608
|
+
client.close(code, reason)
|
|
609
|
+
} catch {}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const openUpstream = async (init) => {
|
|
613
|
+
const targetPath = typeof init?.p === 'string' && init.p.startsWith('/') ? init.p : '/'
|
|
614
|
+
const headers = scrubUpstreamHeaders(init?.h ?? {}, { method: 'GET', ws: true })
|
|
615
|
+
const renewal = sessions.takeRenewal(session, session.pskKid)
|
|
616
|
+
if (renewal) sendControl({ t: 'rotate', renew: renewal })
|
|
617
|
+
const target = `ws://${upstream.info.host}:${upstream.info.port}${targetPath}`
|
|
618
|
+
try {
|
|
619
|
+
upstreamWs = await connectWebSocket(target, { headers, maxPayload: config.e2e.maxFrameBytes })
|
|
620
|
+
} catch (error) {
|
|
621
|
+
const msg = String(error?.message ?? error)
|
|
622
|
+
if (/\b(401|403)\b/.test(msg)) {
|
|
623
|
+
await upstream.onUnauthorized().catch(() => {})
|
|
624
|
+
const retryHeaders = scrubUpstreamHeaders(init?.h ?? {}, { method: 'GET', ws: true })
|
|
625
|
+
try {
|
|
626
|
+
upstreamWs = await connectWebSocket(target, { headers: retryHeaders, maxPayload: config.e2e.maxFrameBytes })
|
|
627
|
+
} catch (retryError) {
|
|
628
|
+
logger.warn('upstream ws failed after reauth', { error: String(retryError?.message ?? retryError), target })
|
|
629
|
+
sendControl({ t: 'error', message: `upstream ws: ${String(retryError?.message ?? retryError)}` })
|
|
630
|
+
shutdown(1011, 'upstream failed')
|
|
631
|
+
return
|
|
632
|
+
}
|
|
633
|
+
} else {
|
|
634
|
+
logger.warn('upstream ws failed', { error: msg, target })
|
|
635
|
+
sendControl({ t: 'error', message: `upstream ws: ${msg}` })
|
|
636
|
+
shutdown(1011, 'upstream failed')
|
|
637
|
+
return
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
upstreamWs.on('message', (payload, isText) => {
|
|
641
|
+
if (closed) return
|
|
642
|
+
sendData(isText ? 0x1 : 0x2, payload)
|
|
643
|
+
})
|
|
644
|
+
upstreamWs.on('close', (code, reason) => {
|
|
645
|
+
sendControl({ t: 'close', code, reason: String(reason ?? '') })
|
|
646
|
+
shutdown(code === 1005 ? 1000 : code, String(reason ?? ''))
|
|
647
|
+
})
|
|
648
|
+
upstreamWs.on('error', (error) => {
|
|
649
|
+
sendControl({ t: 'error', message: String(error?.message ?? error) })
|
|
650
|
+
})
|
|
651
|
+
upstreamWs.on('ping', (payload) => client.ping(payload))
|
|
652
|
+
for (const item of queue.splice(0)) deliverUpstream(item)
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
const deliverUpstream = (message) => {
|
|
656
|
+
if (!upstreamWs) {
|
|
657
|
+
queue.push(message)
|
|
658
|
+
return
|
|
659
|
+
}
|
|
660
|
+
if (message.opcode === 0x1) upstreamWs.sendText(message.payload)
|
|
661
|
+
else upstreamWs.sendBinary(message.payload)
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
client.on('message', (payload, isText) => {
|
|
665
|
+
if (closed) return
|
|
666
|
+
if (isText) {
|
|
667
|
+
// 明文控制帧只允许出现在上游就绪前;其它一律拒绝,避免绕过加密
|
|
668
|
+
return
|
|
669
|
+
}
|
|
670
|
+
let frames
|
|
671
|
+
try {
|
|
672
|
+
frames = decoder.push(payload)
|
|
673
|
+
} catch (error) {
|
|
674
|
+
sendControl({ t: 'error', message: String(error?.message ?? error) })
|
|
675
|
+
shutdown(1002, 'bad frame')
|
|
676
|
+
return
|
|
677
|
+
}
|
|
678
|
+
for (const frame of frames) {
|
|
679
|
+
if (!session.c2sWindow.allows(frame.readUInt32BE(2))) continue
|
|
680
|
+
let opened
|
|
681
|
+
try {
|
|
682
|
+
opened = openFrame({ key: session.keys.c2s, sid: session.sid, frame, aadExtra: Buffer.from('c2s') })
|
|
683
|
+
} catch (error) {
|
|
684
|
+
sendControl({ t: 'error', message: 'decrypt failed' })
|
|
685
|
+
shutdown(1002, 'decrypt failed')
|
|
686
|
+
return
|
|
687
|
+
}
|
|
688
|
+
if (!session.c2sWindow.accept(opened.seq)) continue
|
|
689
|
+
if (opened.type === FRAME_CONTROL) {
|
|
690
|
+
let init
|
|
691
|
+
try {
|
|
692
|
+
init = JSON.parse(opened.plaintext.toString('utf8'))
|
|
693
|
+
} catch {
|
|
694
|
+
continue
|
|
695
|
+
}
|
|
696
|
+
if (init?.t === 'init' && !upstreamWs) openUpstream(init)
|
|
697
|
+
else if (init?.t === 'ping') sendControl({ t: 'pong' })
|
|
698
|
+
else if (init?.t === 'close') shutdown(1000, 'client closed')
|
|
699
|
+
continue
|
|
700
|
+
}
|
|
701
|
+
if (opened.type === FRAME_DATA) {
|
|
702
|
+
const opcode = opened.plaintext[0]
|
|
703
|
+
deliverUpstream({ opcode, payload: opened.plaintext.subarray(1) })
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
})
|
|
707
|
+
|
|
708
|
+
client.on('close', () => shutdown(1000, 'client closed'))
|
|
709
|
+
client.on('error', () => shutdown(1011, 'client error'))
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/** App / 明文通道的 WS 直通:cookie 注入后把帧原样搬运,不做 L7 解析。 */
|
|
713
|
+
async function bridgePlainWebSocket(req, socket, head, pathQuery) {
|
|
714
|
+
const plainMaxPayload = Math.max(config.proxy.maxBodyBytes ?? 64 * 1024 * 1024, config.e2e.maxFrameBytes)
|
|
715
|
+
const client = acceptUpgrade(req, socket, head, { maxPayload: plainMaxPayload })
|
|
716
|
+
if (!client) return
|
|
717
|
+
const headers = scrubUpstreamHeaders(req.headers, { method: 'GET', ws: true })
|
|
718
|
+
const target = `ws://${upstream.info.host}:${String(upstream.info.port)}${pathQuery}`
|
|
719
|
+
const queue = []
|
|
720
|
+
let upstreamWs = null
|
|
721
|
+
let closed = false
|
|
722
|
+
const shutdown = (code = 1000, reason = 'relay closed') => {
|
|
723
|
+
if (closed) return
|
|
724
|
+
closed = true
|
|
725
|
+
try {
|
|
726
|
+
upstreamWs?.close(code, reason)
|
|
727
|
+
} catch {}
|
|
728
|
+
try {
|
|
729
|
+
client.close(code, reason)
|
|
730
|
+
} catch {}
|
|
731
|
+
}
|
|
732
|
+
client.on('message', (payload, isText) => {
|
|
733
|
+
if (closed) return
|
|
734
|
+
if (!upstreamWs) {
|
|
735
|
+
queue.push({ payload, isText })
|
|
736
|
+
return
|
|
737
|
+
}
|
|
738
|
+
if (isText) upstreamWs.sendText(payload)
|
|
739
|
+
else upstreamWs.sendBinary(payload)
|
|
740
|
+
})
|
|
741
|
+
client.on('ping', (payload) => upstreamWs?.ping(payload))
|
|
742
|
+
client.on('close', () => shutdown(1000, 'client closed'))
|
|
743
|
+
client.on('error', (error) => {
|
|
744
|
+
logger.warn('plain ws client error', { error: String(error?.message ?? error) })
|
|
745
|
+
shutdown(1011, 'client error')
|
|
746
|
+
})
|
|
747
|
+
try {
|
|
748
|
+
upstreamWs = await connectWebSocket(target, { headers, maxPayload: plainMaxPayload })
|
|
749
|
+
} catch (error) {
|
|
750
|
+
const msg = String(error?.message ?? error)
|
|
751
|
+
if (/\b(401|403)\b/.test(msg)) {
|
|
752
|
+
await upstream.onUnauthorized().catch(() => {})
|
|
753
|
+
const retryHeaders = scrubUpstreamHeaders(req.headers, { method: 'GET', ws: true })
|
|
754
|
+
const retryTarget = `ws://${upstream.info.host}:${String(upstream.info.port)}${pathQuery}`
|
|
755
|
+
try {
|
|
756
|
+
upstreamWs = await connectWebSocket(retryTarget, { headers: retryHeaders, maxPayload: plainMaxPayload })
|
|
757
|
+
} catch (retryError) {
|
|
758
|
+
stats.errors += 1
|
|
759
|
+
logger.warn('plain ws upstream failed after reauth', { error: String(retryError?.message ?? retryError), target: retryTarget })
|
|
760
|
+
shutdown(1011, 'upstream failed')
|
|
761
|
+
return
|
|
762
|
+
}
|
|
763
|
+
} else {
|
|
764
|
+
stats.errors += 1
|
|
765
|
+
logger.warn('plain ws upstream failed', { error: msg, target })
|
|
766
|
+
shutdown(1011, 'upstream failed')
|
|
767
|
+
return
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
stats.ws += 1
|
|
771
|
+
upstreamWs.on('message', (payload, isText) => {
|
|
772
|
+
if (closed) return
|
|
773
|
+
if (isText) client.sendText(payload)
|
|
774
|
+
else client.sendBinary(payload)
|
|
775
|
+
})
|
|
776
|
+
upstreamWs.on('close', (code, reason) => shutdown(code === 1005 ? 1000 : code, String(reason ?? '')))
|
|
777
|
+
upstreamWs.on('error', (error) => {
|
|
778
|
+
logger.warn('plain ws upstream error', { error: String(error?.message ?? error), target })
|
|
779
|
+
shutdown(1011, 'upstream error')
|
|
780
|
+
})
|
|
781
|
+
upstreamWs.on('ping', (payload) => client.ping(payload))
|
|
782
|
+
for (const item of queue.splice(0)) {
|
|
783
|
+
if (item.isText) upstreamWs.sendText(item.payload)
|
|
784
|
+
else upstreamWs.sendBinary(item.payload)
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// ───────────────────────────── 辅助 ─────────────────────────────
|
|
789
|
+
|
|
790
|
+
function scrubUpstreamHeaders(input, { method, raw = false, ws = false } = {}) {
|
|
791
|
+
const out = {}
|
|
792
|
+
for (const [name, value] of Object.entries(input ?? {})) {
|
|
793
|
+
const key = name.toLowerCase()
|
|
794
|
+
if (HOP_BY_HOP.has(key) || DROP_REQUEST.has(key)) continue
|
|
795
|
+
if (key === 'cookie' || key === 'authorization') continue
|
|
796
|
+
if (value === undefined || value === null) continue
|
|
797
|
+
out[key] = value
|
|
798
|
+
}
|
|
799
|
+
if (upstream.info.cookie) out.cookie = upstream.info.cookie
|
|
800
|
+
out.host = `${upstream.info.host}:${String(upstream.info.port)}`
|
|
801
|
+
out.origin = `http://${upstream.info.host}:${String(upstream.info.port)}`
|
|
802
|
+
if (out.referer !== undefined) {
|
|
803
|
+
try {
|
|
804
|
+
const parsed = new URL(String(out.referer))
|
|
805
|
+
out.referer = `http://${upstream.info.host}:${String(upstream.info.port)}${parsed.pathname}${parsed.search}`
|
|
806
|
+
} catch {
|
|
807
|
+
delete out.referer
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
if (ws) {
|
|
811
|
+
out.connection = 'Upgrade'
|
|
812
|
+
out.upgrade = 'websocket'
|
|
813
|
+
}
|
|
814
|
+
if (!raw) delete out['accept-encoding']
|
|
815
|
+
return out
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
function cleanResponseHeaders(headers) {
|
|
819
|
+
const out = {}
|
|
820
|
+
for (const [name, value] of Object.entries(headers ?? {})) {
|
|
821
|
+
const key = name.toLowerCase()
|
|
822
|
+
if (STRIP_RESPONSE.has(key)) continue
|
|
823
|
+
if (value === undefined) continue
|
|
824
|
+
out[key] = value
|
|
825
|
+
}
|
|
826
|
+
out['x-frame-options'] = 'DENY'
|
|
827
|
+
out['referrer-policy'] = 'no-referrer'
|
|
828
|
+
return out
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
function sameOrigin(req) {
|
|
832
|
+
const origin = req.headers.origin
|
|
833
|
+
if (!origin) return true
|
|
834
|
+
try {
|
|
835
|
+
const parsed = new URL(String(origin))
|
|
836
|
+
const host = String(req.headers['x-forwarded-host'] ?? req.headers.host ?? '')
|
|
837
|
+
return parsed.host === host
|
|
838
|
+
} catch {
|
|
839
|
+
return false
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
function publicBaseUrl(req) {
|
|
844
|
+
if (config.proxy.publicUrl) return config.proxy.publicUrl.replace(/\/+$/, '')
|
|
845
|
+
const host = String(req.headers['x-forwarded-host'] ?? req.headers.host ?? `127.0.0.1:${String(config.listen.port)}`)
|
|
846
|
+
const proto = isSecureRequest(req) ? 'https' : 'http'
|
|
847
|
+
return `${proto}://${host}`
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
function wantsHtml(req) {
|
|
851
|
+
const accept = String(req.headers.accept ?? '')
|
|
852
|
+
return req.method === 'GET' && (accept.includes('text/html') || req.headers['sec-fetch-mode'] === 'navigate')
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
function clientAddr(req) {
|
|
856
|
+
return String(req.headers['cf-connecting-ip'] ?? req.socket.remoteAddress ?? '')
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// ───────────────────────────── 页面 / 响应 ─────────────────────────────
|
|
860
|
+
|
|
861
|
+
function sendShim(req, res) {
|
|
862
|
+
// 不协商缓存:shim 是安全边界的一部分,升级后必须立即生效
|
|
863
|
+
res.writeHead(200, {
|
|
864
|
+
'content-type': 'text/javascript; charset=utf-8',
|
|
865
|
+
'content-length': Buffer.byteLength(shim),
|
|
866
|
+
'cache-control': 'no-store, max-age=0',
|
|
867
|
+
'x-shim-build': shimBuild,
|
|
868
|
+
'x-content-type-options': 'nosniff',
|
|
869
|
+
})
|
|
870
|
+
res.end(shim)
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
function sendUnlockPage(req, res) {
|
|
874
|
+
const html = `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
|
|
875
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
876
|
+
<title>DSH Remote · 解锁</title>
|
|
877
|
+
<style>
|
|
878
|
+
:root{color-scheme:dark}
|
|
879
|
+
body{margin:0;min-height:100vh;display:grid;place-items:center;background:#111114;color:#e7e7ea;
|
|
880
|
+
font:15px/1.6 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
881
|
+
.card{max-width:520px;padding:32px;border:1px solid #2a2a31;border-radius:16px;background:#17171c}
|
|
882
|
+
h1{margin:0 0 8px;font-size:18px;letter-spacing:.2px}
|
|
883
|
+
p{margin:0 0 12px;color:#9b9ba4}
|
|
884
|
+
code{background:#22222a;padding:2px 6px;border-radius:6px;color:#cfcfe6}
|
|
885
|
+
#state{margin-top:14px;font-size:13px;color:#8fb7ff;min-height:20px}
|
|
886
|
+
.fail{color:#ff9a9a !important}
|
|
887
|
+
</style></head>
|
|
888
|
+
<body><div class="card">
|
|
889
|
+
<h1>需要端到端加密密钥</h1>
|
|
890
|
+
<p>这个地址本身不含访问密钥。请使用完整链接打开:<code>https://…/#k=<key></code></p>
|
|
891
|
+
<p>密钥只存在于地址的 <code>#</code> 片段中,浏览器不会把它发送给 Cloudflare。</p>
|
|
892
|
+
<div id="state">等待握手…</div>
|
|
893
|
+
</div>
|
|
894
|
+
<script src="/__dsh/shim.js" data-dsh-remote="unlock"></script>
|
|
895
|
+
</body></html>`
|
|
896
|
+
res.writeHead(401, {
|
|
897
|
+
'content-type': 'text/html; charset=utf-8',
|
|
898
|
+
'cache-control': 'no-store',
|
|
899
|
+
'referrer-policy': 'no-referrer',
|
|
900
|
+
'x-frame-options': 'DENY',
|
|
901
|
+
})
|
|
902
|
+
res.end(html)
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
function sendJson(res, status, payload, extraHeaders = {}) {
|
|
906
|
+
const body = Buffer.from(`${JSON.stringify(payload)}\n`)
|
|
907
|
+
res.writeHead(status, {
|
|
908
|
+
'content-type': 'application/json; charset=utf-8',
|
|
909
|
+
'content-length': body.length,
|
|
910
|
+
'cache-control': 'no-store',
|
|
911
|
+
...extraHeaders,
|
|
912
|
+
})
|
|
913
|
+
res.end(body)
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
function deny(res, status, code, detail = null) {
|
|
917
|
+
sendJson(res, status, detail ? { error: code, detail } : { error: code })
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
async function readBody(req, limit) {
|
|
921
|
+
return new Promise((resolve, reject) => {
|
|
922
|
+
const chunks = []
|
|
923
|
+
let size = 0
|
|
924
|
+
req.on('data', (chunk) => {
|
|
925
|
+
size += chunk.length
|
|
926
|
+
if (size > limit) {
|
|
927
|
+
reject(new Error(`请求体超过上限 ${limit}`))
|
|
928
|
+
req.destroy()
|
|
929
|
+
return
|
|
930
|
+
}
|
|
931
|
+
chunks.push(chunk)
|
|
932
|
+
})
|
|
933
|
+
req.on('end', () => resolve(Buffer.concat(chunks)))
|
|
934
|
+
req.on('error', reject)
|
|
935
|
+
})
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
async function readJsonBody(req, limit) {
|
|
939
|
+
try {
|
|
940
|
+
const raw = await readBody(req, limit)
|
|
941
|
+
return JSON.parse(raw.toString('utf8'))
|
|
942
|
+
} catch {
|
|
943
|
+
return null
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
async function handleLegacyToken(req, res, url) {
|
|
948
|
+
const token = url.searchParams.get('token')
|
|
949
|
+
keys.reload()
|
|
950
|
+
const viaApp = config.proxy.appBridge && keys.verifyAppToken(token)
|
|
951
|
+
const viaLegacy = config.proxy.legacyToken && keys.verifyLegacyToken(token)
|
|
952
|
+
if (!viaApp && !viaLegacy) {
|
|
953
|
+
stats.rejected += 1
|
|
954
|
+
// 加密链接是 PSK 不是 token:给出可操作的原因,避免客户端只看到 401
|
|
955
|
+
const looksEncrypted = keys.findPskByValue(token)
|
|
956
|
+
return deny(res, 401, looksEncrypted ? 'e2e_link_requires_browser' : 'bad_token')
|
|
957
|
+
}
|
|
958
|
+
const sid = b64u(newSessionId())
|
|
959
|
+
plainSessions.set(sid, { sid, createdAt: Date.now(), expiresAt: Date.now() + sessions_ttl, channel: viaApp ? 'app' : 'legacy' })
|
|
960
|
+
res.setHeader('set-cookie', [
|
|
961
|
+
`${PLAIN_COOKIE}=${sid}; ${cookieAttributes(req, Math.floor(sessions_ttl / 1000))}`,
|
|
962
|
+
// 清除可能残留的旧 E2E 会话 cookie,避免浏览器切到明文 ?token= 通道后仍被注入 shim.js
|
|
963
|
+
`${SESSION_COOKIE}=; ${cookieAttributes(req, 0)}`,
|
|
964
|
+
])
|
|
965
|
+
res.writeHead(303, { location: './', 'cache-control': 'no-store' })
|
|
966
|
+
res.end()
|
|
967
|
+
if (viaApp) logger.info('app bridge session', { sid: sid.slice(0, 8), remote: clientAddr(req) })
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
return {
|
|
971
|
+
server,
|
|
972
|
+
stats,
|
|
973
|
+
listen() {
|
|
974
|
+
return new Promise((resolve, reject) => {
|
|
975
|
+
server.once('error', reject)
|
|
976
|
+
server.listen(config.listen.port, config.listen.host, () => {
|
|
977
|
+
server.removeListener('error', reject)
|
|
978
|
+
resolve(server.address())
|
|
979
|
+
})
|
|
980
|
+
})
|
|
981
|
+
},
|
|
982
|
+
/** 主动向在线会话推送新 PSK(WS 控制帧)。 */
|
|
983
|
+
pushRenewal(session, payload) {
|
|
984
|
+
if (!session?.ws) return false
|
|
985
|
+
const frame = sealFrame({
|
|
986
|
+
key: session.keys.s2c,
|
|
987
|
+
sid: session.sid,
|
|
988
|
+
seq: sessions.nextSeq(session),
|
|
989
|
+
type: FRAME_CONTROL,
|
|
990
|
+
plaintext: Buffer.from(JSON.stringify({ t: 'rotate', renew: payload })),
|
|
991
|
+
aadExtra: Buffer.from('s2c'),
|
|
992
|
+
})
|
|
993
|
+
return session.ws.sendBinary(frame)
|
|
994
|
+
},
|
|
995
|
+
close() {
|
|
996
|
+
return new Promise((resolve) => server.close(() => resolve()))
|
|
997
|
+
},
|
|
998
|
+
describe() {
|
|
999
|
+
return {
|
|
1000
|
+
listen: server.address(),
|
|
1001
|
+
...stats,
|
|
1002
|
+
sessions: sessions.size,
|
|
1003
|
+
plainSessions: plainSessions.size,
|
|
1004
|
+
e2e: config.e2e.enabled,
|
|
1005
|
+
}
|
|
1006
|
+
},
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
/** Cloudflare/代理可能给出 `//path` 形式,统一成绝对路径。 */
|
|
1011
|
+
function normalizePath(raw) {
|
|
1012
|
+
const value = typeof raw === 'string' && raw.length > 0 ? raw : '/'
|
|
1013
|
+
if (!value.startsWith('//')) return value
|
|
1014
|
+
return `/${value.slice(2)}`
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
function parseCookies(header) {
|
|
1018
|
+
const out = {}
|
|
1019
|
+
if (typeof header !== 'string' || header === '') return out
|
|
1020
|
+
for (const segment of header.split(';')) {
|
|
1021
|
+
const at = segment.indexOf('=')
|
|
1022
|
+
if (at === -1) continue
|
|
1023
|
+
const name = segment.slice(0, at).trim()
|
|
1024
|
+
const value = segment.slice(at + 1).trim()
|
|
1025
|
+
if (name) out[name] = value
|
|
1026
|
+
}
|
|
1027
|
+
return out
|
|
1028
|
+
}
|