@kkcode-app/agent 1.1.3 → 2.0.0
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 +40 -99
- package/dist/agent-link.js +55 -93
- package/dist/agent-link.js.map +1 -1
- package/dist/config.js +101 -69
- package/dist/config.js.map +1 -1
- package/dist/crypto.js +151 -0
- package/dist/crypto.js.map +1 -0
- package/dist/entry.js +5 -9
- package/dist/entry.js.map +1 -1
- package/dist/index.js +71 -83
- package/dist/index.js.map +1 -1
- package/dist/local-server.js +58 -27
- package/dist/local-server.js.map +1 -1
- package/dist/notification-core.js +131 -59
- package/dist/notification-core.js.map +1 -1
- package/dist/plugin.js +183 -67
- package/dist/plugin.js.map +1 -1
- package/dist/protocol.js +62 -6
- package/dist/protocol.js.map +1 -1
- package/dist/qr.js +31 -20
- package/dist/qr.js.map +1 -1
- package/dist/service.js +24 -8
- package/dist/service.js.map +1 -1
- package/dist/tunnel.js +406 -200
- package/dist/tunnel.js.map +1 -1
- package/dist/update.js +13 -5
- package/dist/update.js.map +1 -1
- package/package.json +4 -3
- package/src/config.ts +144 -0
- package/src/crypto.ts +193 -0
- package/src/entry.ts +5 -11
- package/src/notification-core.ts +139 -71
- package/src/plugin.ts +161 -71
- package/dist/plugin-v1.js +0 -136
- package/dist/plugin-v1.js.map +0 -1
- package/src/plugin-v1.ts +0 -189
package/dist/tunnel.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* [INPUT]: 依赖 ws
|
|
3
|
-
* [OUTPUT]:
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* [POS]: cli/ 隧道核心,被 index.ts 在默认 / --attach 模式下 spawn 后调用; 通过 QR secret 复用相同 tunnelId,自动重连不需手机重扫
|
|
7
|
-
* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md
|
|
2
|
+
* [INPUT]: 依赖 ws、./crypto.ts(E2EE 密钥派生与流式加解密)与 ./protocol.ts(Tunnel v4 二进制帧)
|
|
3
|
+
* [OUTPUT]: 提供 TunnelClient、resolveLocalUrl、toRelayWebSocketUrl 与 toRelayPublicHttpUrl
|
|
4
|
+
* [POS]: CLI Tunnel v4 二进制 + E2EE HTTP/SSE 转发边界;连接与流独立持有生命周期,强制本地鉴权注入、拒绝跨源与重定向、逐帧背压与取消回收
|
|
5
|
+
* [PROTOCOL]: Update this header on change, then check CLAUDE.md
|
|
8
6
|
*/
|
|
9
7
|
import WebSocket from "ws";
|
|
10
|
-
import {
|
|
8
|
+
import { deriveKeys, E2EEFrameDecoder, E2EEFrameEncoder, } from "./crypto.js";
|
|
9
|
+
import { decodeFrame, encodeControlFrame, encodeFrame, FrameType, streamIdKey, } from "./protocol.js";
|
|
11
10
|
const HOP_BY_HOP = new Set([
|
|
12
11
|
"connection",
|
|
13
12
|
"keep-alive",
|
|
@@ -19,21 +18,52 @@ const HOP_BY_HOP = new Set([
|
|
|
19
18
|
"upgrade",
|
|
20
19
|
"host",
|
|
21
20
|
"content-length",
|
|
22
|
-
// fetch() auto-decompresses gzip/deflate/br
|
|
23
|
-
// The tunneled body is already decompressed, so forwarding this header
|
|
24
|
-
// makes Caddy/clients try to decompress plain bytes → "gzip: invalid header".
|
|
21
|
+
// fetch() auto-decompresses gzip/deflate/br while keeping the header.
|
|
25
22
|
"content-encoding",
|
|
26
23
|
]);
|
|
24
|
+
const MAX_RESPONSE_CHUNK_BYTES = 200 * 1024;
|
|
25
|
+
const HANDSHAKE_TIMEOUT_MS = 10_000;
|
|
26
|
+
const PING_INTERVAL_MS = 15_000;
|
|
27
|
+
const PONG_TIMEOUT_MS = 5_000;
|
|
28
|
+
const CONTROL_CHAR_RE = /[\u0000-\u001f\u007f]/u;
|
|
27
29
|
/**
|
|
28
|
-
*
|
|
29
|
-
*
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
30
|
+
* 将用户输入的中继地址规范化为 WebSocket 基础地址(不含路径末尾斜杠):
|
|
31
|
+
* https:// -> wss://,http:// -> ws://。
|
|
32
|
+
*/
|
|
33
|
+
export function toRelayWebSocketUrl(relayUrl) {
|
|
34
|
+
const parsed = new URL(relayUrl);
|
|
35
|
+
if (parsed.protocol === "https:") {
|
|
36
|
+
parsed.protocol = "wss:";
|
|
37
|
+
}
|
|
38
|
+
else if (parsed.protocol === "http:") {
|
|
39
|
+
parsed.protocol = "ws:";
|
|
40
|
+
}
|
|
41
|
+
else if (parsed.protocol !== "wss:" && parsed.protocol !== "ws:") {
|
|
42
|
+
throw new Error(`relay URL must use ws://, wss://, http://, or https://, got ${parsed.protocol}`);
|
|
43
|
+
}
|
|
44
|
+
return parsed.toString().replace(/\/$/u, "");
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* 将中继地址规范化为公开 HTTP(S) 基础地址(供 QR payload 使用)。
|
|
48
|
+
*/
|
|
49
|
+
export function toRelayPublicHttpUrl(relayUrl) {
|
|
50
|
+
const parsed = new URL(toRelayWebSocketUrl(relayUrl));
|
|
51
|
+
parsed.protocol = parsed.protocol === "wss:" ? "https:" : "http:";
|
|
52
|
+
return parsed.toString().replace(/\/$/u, "");
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 将解密后的请求 path 解析为本地上游 URL。
|
|
56
|
+
* 拒绝非 `/` 起始、protocol-relative `//`、反斜杠 `\`、控制字符及任何跨 origin 目标。
|
|
35
57
|
*/
|
|
36
58
|
export function resolveLocalUrl(localOrigin, path) {
|
|
59
|
+
if (typeof path !== "string" ||
|
|
60
|
+
path.length === 0 ||
|
|
61
|
+
!path.startsWith("/") ||
|
|
62
|
+
path.startsWith("//") ||
|
|
63
|
+
path.includes("\\") ||
|
|
64
|
+
CONTROL_CHAR_RE.test(path)) {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
37
67
|
let origin;
|
|
38
68
|
let resolved;
|
|
39
69
|
try {
|
|
@@ -45,11 +75,22 @@ export function resolveLocalUrl(localOrigin, path) {
|
|
|
45
75
|
}
|
|
46
76
|
return resolved.origin === origin.origin ? resolved.toString() : null;
|
|
47
77
|
}
|
|
78
|
+
function toBuffer(raw) {
|
|
79
|
+
if (Buffer.isBuffer(raw))
|
|
80
|
+
return raw;
|
|
81
|
+
if (Array.isArray(raw))
|
|
82
|
+
return Buffer.concat(raw);
|
|
83
|
+
return Buffer.from(raw);
|
|
84
|
+
}
|
|
48
85
|
export class TunnelClient {
|
|
49
86
|
ws;
|
|
50
87
|
inflight = new Map();
|
|
51
88
|
opts;
|
|
89
|
+
keys;
|
|
90
|
+
wsBaseUrl;
|
|
52
91
|
closed = false;
|
|
92
|
+
ready = false;
|
|
93
|
+
handshakeTimer;
|
|
53
94
|
pingTimer;
|
|
54
95
|
pongCheckTimer;
|
|
55
96
|
pongDeadline = null;
|
|
@@ -57,91 +98,134 @@ export class TunnelClient {
|
|
|
57
98
|
reconnectAttempt = 0;
|
|
58
99
|
constructor(opts) {
|
|
59
100
|
this.opts = opts;
|
|
101
|
+
this.keys = deriveKeys(opts.secret);
|
|
102
|
+
this.wsBaseUrl = toRelayWebSocketUrl(opts.relayUrl);
|
|
103
|
+
}
|
|
104
|
+
get hostId() {
|
|
105
|
+
return this.keys.hostId;
|
|
60
106
|
}
|
|
61
107
|
start() {
|
|
108
|
+
if (this.closed || this.ws || this.reconnectTimer)
|
|
109
|
+
return;
|
|
62
110
|
this.connect();
|
|
63
111
|
}
|
|
112
|
+
close() {
|
|
113
|
+
this.closed = true;
|
|
114
|
+
this.ready = false;
|
|
115
|
+
this.cleanupConnectionTimers();
|
|
116
|
+
if (this.reconnectTimer) {
|
|
117
|
+
clearTimeout(this.reconnectTimer);
|
|
118
|
+
this.reconnectTimer = undefined;
|
|
119
|
+
}
|
|
120
|
+
this.cleanupInflight();
|
|
121
|
+
try {
|
|
122
|
+
this.ws?.terminate();
|
|
123
|
+
}
|
|
124
|
+
catch { }
|
|
125
|
+
this.ws = undefined;
|
|
126
|
+
}
|
|
64
127
|
connect() {
|
|
65
|
-
|
|
66
|
-
|
|
128
|
+
if (this.closed)
|
|
129
|
+
return;
|
|
130
|
+
const url = new URL("/v4/host", this.wsBaseUrl).toString();
|
|
131
|
+
const ws = new WebSocket(url, {
|
|
132
|
+
perMessageDeflate: false,
|
|
133
|
+
handshakeTimeout: HANDSHAKE_TIMEOUT_MS,
|
|
134
|
+
});
|
|
67
135
|
this.ws = ws;
|
|
136
|
+
this.ready = false;
|
|
68
137
|
ws.on("open", () => {
|
|
69
|
-
this.
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
138
|
+
if (this.closed || this.ws !== ws)
|
|
139
|
+
return;
|
|
140
|
+
this.sendRaw(ws, encodeControlFrame(FrameType.HostHello, {
|
|
141
|
+
hostId: this.keys.hostId,
|
|
142
|
+
relayAuth: this.keys.relayAuth,
|
|
143
|
+
}));
|
|
144
|
+
this.handshakeTimer = setTimeout(() => {
|
|
145
|
+
if (this.ws === ws && !this.ready && !this.closed) {
|
|
146
|
+
console.warn("[tunnel] handshake timeout, closing to trigger reconnect");
|
|
147
|
+
try {
|
|
148
|
+
ws.terminate();
|
|
149
|
+
}
|
|
150
|
+
catch { }
|
|
151
|
+
}
|
|
152
|
+
}, HANDSHAKE_TIMEOUT_MS);
|
|
74
153
|
this.pingTimer = setInterval(() => {
|
|
75
|
-
this.
|
|
76
|
-
|
|
77
|
-
|
|
154
|
+
if (this.ws !== ws || ws.readyState !== WebSocket.OPEN)
|
|
155
|
+
return;
|
|
156
|
+
this.sendRaw(ws, encodeControlFrame(FrameType.Ping));
|
|
157
|
+
this.pongDeadline = Date.now() + PONG_TIMEOUT_MS;
|
|
158
|
+
}, PING_INTERVAL_MS);
|
|
78
159
|
this.pongCheckTimer = setInterval(() => {
|
|
79
160
|
if (this.pongDeadline !== null && Date.now() > this.pongDeadline) {
|
|
80
161
|
console.warn("[tunnel] pong timeout, closing to trigger reconnect");
|
|
81
162
|
try {
|
|
82
|
-
|
|
163
|
+
ws.terminate();
|
|
83
164
|
}
|
|
84
165
|
catch { }
|
|
85
166
|
}
|
|
86
|
-
},
|
|
167
|
+
}, 1_000);
|
|
87
168
|
});
|
|
88
169
|
ws.on("message", (raw) => {
|
|
170
|
+
if (this.closed || this.ws !== ws)
|
|
171
|
+
return;
|
|
89
172
|
let frame;
|
|
90
173
|
try {
|
|
91
|
-
frame =
|
|
174
|
+
frame = decodeFrame(toBuffer(raw));
|
|
92
175
|
}
|
|
93
|
-
catch {
|
|
176
|
+
catch (err) {
|
|
177
|
+
console.warn("[tunnel] ignored malformed binary frame:", err instanceof Error ? err.message : String(err));
|
|
94
178
|
return;
|
|
95
179
|
}
|
|
96
|
-
this.handleFrame(frame).catch((err) => {
|
|
180
|
+
this.handleFrame(ws, frame).catch((err) => {
|
|
97
181
|
console.error("[tunnel] frame handler failed:", err);
|
|
98
182
|
});
|
|
99
183
|
});
|
|
100
184
|
ws.on("close", (code, reason) => {
|
|
185
|
+
if (this.ws !== ws)
|
|
186
|
+
return;
|
|
187
|
+
this.ws = undefined;
|
|
188
|
+
this.ready = false;
|
|
101
189
|
this.cleanupInflight();
|
|
102
|
-
|
|
103
|
-
clearInterval(this.pingTimer);
|
|
104
|
-
this.pingTimer = undefined;
|
|
105
|
-
if (this.pongCheckTimer)
|
|
106
|
-
clearInterval(this.pongCheckTimer);
|
|
107
|
-
this.pongCheckTimer = undefined;
|
|
108
|
-
this.pongDeadline = null;
|
|
190
|
+
this.cleanupConnectionTimers();
|
|
109
191
|
const reasonStr = reason?.toString() || "";
|
|
110
|
-
if (
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
this.
|
|
192
|
+
if (this.closed)
|
|
193
|
+
return;
|
|
194
|
+
if (code === 1008) {
|
|
195
|
+
this.closed = true;
|
|
196
|
+
const message = `tunnel rejected by relay (code=1008${reasonStr ? `, ${reasonStr}` : ""}). ` +
|
|
197
|
+
`Check your host secret or run with --reset-tunnel to generate a new secret.`;
|
|
198
|
+
console.error(`[tunnel] ${message}`);
|
|
199
|
+
this.opts.onFatalClose?.(code, reasonStr);
|
|
200
|
+
this.opts.onError?.(new Error(message));
|
|
201
|
+
return;
|
|
114
202
|
}
|
|
203
|
+
const err = new Error(`tunnel closed (code=${code}${reasonStr ? `, ${reasonStr}` : ""})`);
|
|
204
|
+
this.opts.onError?.(err);
|
|
205
|
+
this.scheduleReconnect();
|
|
115
206
|
});
|
|
116
207
|
ws.on("error", (err) => {
|
|
117
|
-
if (!this.closed)
|
|
208
|
+
if (!this.closed && this.ws === ws)
|
|
118
209
|
this.opts.onError?.(err);
|
|
119
210
|
});
|
|
120
211
|
}
|
|
121
|
-
|
|
122
|
-
this.closed
|
|
123
|
-
|
|
124
|
-
clearInterval(this.pingTimer);
|
|
125
|
-
if (this.pongCheckTimer)
|
|
126
|
-
clearInterval(this.pongCheckTimer);
|
|
127
|
-
if (this.reconnectTimer)
|
|
128
|
-
clearTimeout(this.reconnectTimer);
|
|
129
|
-
this.cleanupInflight();
|
|
130
|
-
try {
|
|
131
|
-
this.ws?.close();
|
|
212
|
+
sendRaw(ws, data) {
|
|
213
|
+
if (!this.closed && this.ws === ws && ws.readyState === WebSocket.OPEN) {
|
|
214
|
+
ws.send(data);
|
|
132
215
|
}
|
|
133
|
-
catch { }
|
|
134
216
|
}
|
|
135
|
-
|
|
136
|
-
if (
|
|
137
|
-
|
|
138
|
-
|
|
217
|
+
sendWithBackpressure(ws, data, active) {
|
|
218
|
+
if (!active() || ws.readyState !== WebSocket.OPEN)
|
|
219
|
+
return Promise.resolve();
|
|
220
|
+
return new Promise((resolve, reject) => {
|
|
221
|
+
ws.send(data, (error) => (error ? reject(error) : resolve()));
|
|
222
|
+
});
|
|
139
223
|
}
|
|
140
224
|
scheduleReconnect() {
|
|
141
225
|
if (this.closed || this.reconnectTimer)
|
|
142
226
|
return;
|
|
143
|
-
const base = Math.min(
|
|
144
|
-
const jitter = Math.floor(Math.random() *
|
|
227
|
+
const base = Math.min(1_000 * 2 ** this.reconnectAttempt, 10_000);
|
|
228
|
+
const jitter = Math.floor(Math.random() * 1_000);
|
|
145
229
|
const delay = base + jitter;
|
|
146
230
|
this.reconnectAttempt += 1;
|
|
147
231
|
console.warn(`[tunnel] reconnecting in ${Math.round(delay / 1000)}s…`);
|
|
@@ -151,195 +235,317 @@ export class TunnelClient {
|
|
|
151
235
|
this.connect();
|
|
152
236
|
}, delay);
|
|
153
237
|
}
|
|
238
|
+
cleanupConnectionTimers() {
|
|
239
|
+
if (this.handshakeTimer)
|
|
240
|
+
clearTimeout(this.handshakeTimer);
|
|
241
|
+
if (this.pingTimer)
|
|
242
|
+
clearInterval(this.pingTimer);
|
|
243
|
+
if (this.pongCheckTimer)
|
|
244
|
+
clearInterval(this.pongCheckTimer);
|
|
245
|
+
this.handshakeTimer = undefined;
|
|
246
|
+
this.pingTimer = undefined;
|
|
247
|
+
this.pongCheckTimer = undefined;
|
|
248
|
+
this.pongDeadline = null;
|
|
249
|
+
}
|
|
154
250
|
cleanupInflight() {
|
|
155
|
-
for (const
|
|
251
|
+
for (const stream of this.inflight.values()) {
|
|
156
252
|
try {
|
|
157
|
-
|
|
253
|
+
stream.controller.abort();
|
|
158
254
|
}
|
|
159
255
|
catch { }
|
|
160
256
|
try {
|
|
161
|
-
|
|
257
|
+
stream.bodyController?.error(new Error("tunnel closed"));
|
|
162
258
|
}
|
|
163
259
|
catch { }
|
|
260
|
+
void stream.reader?.cancel().catch(() => undefined);
|
|
164
261
|
}
|
|
165
262
|
this.inflight.clear();
|
|
166
263
|
}
|
|
167
|
-
async handleFrame(frame) {
|
|
264
|
+
async handleFrame(ws, frame) {
|
|
168
265
|
switch (frame.type) {
|
|
169
|
-
case
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
.
|
|
173
|
-
|
|
174
|
-
|
|
266
|
+
case FrameType.HostReady: {
|
|
267
|
+
if (this.handshakeTimer) {
|
|
268
|
+
clearTimeout(this.handshakeTimer);
|
|
269
|
+
this.handshakeTimer = undefined;
|
|
270
|
+
}
|
|
271
|
+
let hostId = this.keys.hostId;
|
|
272
|
+
if (frame.payload.length > 0) {
|
|
273
|
+
const parsed = JSON.parse(frame.payload.toString("utf8"));
|
|
274
|
+
if (typeof parsed.hostId === "string" && parsed.hostId.length > 0) {
|
|
275
|
+
hostId = parsed.hostId;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
this.ready = true;
|
|
175
279
|
this.reconnectAttempt = 0;
|
|
176
|
-
this.opts.onReady?.(
|
|
280
|
+
await this.opts.onReady?.(hostId);
|
|
177
281
|
return;
|
|
178
282
|
}
|
|
179
|
-
case
|
|
180
|
-
this.
|
|
283
|
+
case FrameType.Ping:
|
|
284
|
+
this.sendRaw(ws, encodeControlFrame(FrameType.Pong));
|
|
181
285
|
return;
|
|
182
|
-
case
|
|
286
|
+
case FrameType.Pong:
|
|
183
287
|
this.pongDeadline = null;
|
|
184
288
|
return;
|
|
185
|
-
case
|
|
186
|
-
|
|
289
|
+
case FrameType.StreamOpen:
|
|
290
|
+
this.handleStreamOpen(ws, frame);
|
|
187
291
|
return;
|
|
188
|
-
case
|
|
189
|
-
this.
|
|
292
|
+
case FrameType.StreamData:
|
|
293
|
+
this.handleStreamData(ws, frame);
|
|
190
294
|
return;
|
|
191
|
-
case
|
|
192
|
-
this.
|
|
295
|
+
case FrameType.StreamEnd:
|
|
296
|
+
this.handleStreamEnd(ws, frame);
|
|
193
297
|
return;
|
|
194
|
-
case
|
|
195
|
-
this.
|
|
298
|
+
case FrameType.StreamAbort:
|
|
299
|
+
this.handleStreamAbort(frame);
|
|
196
300
|
return;
|
|
197
301
|
default:
|
|
198
302
|
return;
|
|
199
303
|
}
|
|
200
304
|
}
|
|
201
|
-
|
|
202
|
-
const
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
305
|
+
handleStreamOpen(ws, frame) {
|
|
306
|
+
const key = streamIdKey(frame.streamId);
|
|
307
|
+
if (this.inflight.has(key))
|
|
308
|
+
return;
|
|
309
|
+
const stream = {
|
|
310
|
+
key,
|
|
311
|
+
streamId: Buffer.from(frame.streamId),
|
|
312
|
+
decoder: new E2EEFrameDecoder(this.keys.e2eeKey, this.keys.hostId, "c2h"),
|
|
313
|
+
encoder: new E2EEFrameEncoder(this.keys.e2eeKey, this.keys.hostId, "h2c"),
|
|
314
|
+
controller: new AbortController(),
|
|
315
|
+
headReceived: false,
|
|
206
316
|
bodyClosed: false,
|
|
207
|
-
hasBody: frame.hasBody,
|
|
208
317
|
};
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
inflight.bodyController = c;
|
|
213
|
-
},
|
|
214
|
-
});
|
|
318
|
+
this.inflight.set(key, stream);
|
|
319
|
+
if (frame.payload.length > 0) {
|
|
320
|
+
this.consumeEncryptedPayload(ws, stream, frame.payload);
|
|
215
321
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
try {
|
|
222
|
-
headers.set(k, v);
|
|
223
|
-
}
|
|
224
|
-
catch { }
|
|
225
|
-
}
|
|
226
|
-
for (const [k, v] of Object.entries(this.opts.localHeaders ?? {})) {
|
|
227
|
-
if (HOP_BY_HOP.has(k.toLowerCase()))
|
|
228
|
-
continue;
|
|
229
|
-
headers.set(k, v);
|
|
230
|
-
}
|
|
231
|
-
// `new URL(path, localOrigin)` 会把 `//evil.com/x` 当作**协议相对 URL**
|
|
232
|
-
// 解析到任意主机,而上面刚注入的 localHeaders(含本地 Bridge token)会随
|
|
233
|
-
// fetch 一起发过去 —— 等于用用户的凭据去打攻击者的域名。
|
|
234
|
-
// 服务端已拦这一形态,这里必须再挡一次:真正发起请求的是本进程。
|
|
235
|
-
const localUrl = resolveLocalUrl(this.opts.localOrigin, frame.path);
|
|
236
|
-
if (localUrl === null) {
|
|
237
|
-
this.send({
|
|
238
|
-
type: "res-error",
|
|
239
|
-
id: frame.id,
|
|
240
|
-
message: `refusing cross-origin tunnel path: ${frame.path}`,
|
|
241
|
-
});
|
|
242
|
-
this.inflight.delete(frame.id);
|
|
322
|
+
}
|
|
323
|
+
handleStreamData(ws, frame) {
|
|
324
|
+
const key = streamIdKey(frame.streamId);
|
|
325
|
+
const stream = this.inflight.get(key);
|
|
326
|
+
if (!stream)
|
|
243
327
|
return;
|
|
328
|
+
if (frame.payload.length > 0) {
|
|
329
|
+
this.consumeEncryptedPayload(ws, stream, frame.payload);
|
|
244
330
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
if (frame.hasBody && inflight.bodyStream) {
|
|
251
|
-
init.duplex = "half";
|
|
252
|
-
init.body = inflight.bodyStream;
|
|
253
|
-
}
|
|
254
|
-
let res;
|
|
255
|
-
try {
|
|
256
|
-
res = await fetch(localUrl, init);
|
|
257
|
-
}
|
|
258
|
-
catch (err) {
|
|
259
|
-
this.send({
|
|
260
|
-
type: "res-error",
|
|
261
|
-
id: frame.id,
|
|
262
|
-
message: `local fetch failed: ${err.message}`,
|
|
263
|
-
});
|
|
264
|
-
this.inflight.delete(frame.id);
|
|
331
|
+
}
|
|
332
|
+
handleStreamEnd(ws, frame) {
|
|
333
|
+
const key = streamIdKey(frame.streamId);
|
|
334
|
+
const stream = this.inflight.get(key);
|
|
335
|
+
if (!stream)
|
|
265
336
|
return;
|
|
337
|
+
if (frame.payload.length > 0) {
|
|
338
|
+
this.consumeEncryptedPayload(ws, stream, frame.payload);
|
|
266
339
|
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
resHeaders[key] = value;
|
|
272
|
-
});
|
|
273
|
-
this.send({
|
|
274
|
-
type: "res-head",
|
|
275
|
-
id: frame.id,
|
|
276
|
-
status: res.status,
|
|
277
|
-
headers: resHeaders,
|
|
278
|
-
});
|
|
279
|
-
if (!res.body) {
|
|
280
|
-
this.send({ type: "res-end", id: frame.id });
|
|
281
|
-
this.inflight.delete(frame.id);
|
|
340
|
+
if (!this.inflight.has(key))
|
|
341
|
+
return;
|
|
342
|
+
if (!stream.headReceived || stream.decoder.hasPendingBytes()) {
|
|
343
|
+
this.abortStream(ws, stream, "truncated encrypted request stream");
|
|
282
344
|
return;
|
|
283
345
|
}
|
|
284
|
-
|
|
285
|
-
try {
|
|
286
|
-
while (true) {
|
|
287
|
-
const { value, done } = await reader.read();
|
|
288
|
-
if (done)
|
|
289
|
-
break;
|
|
290
|
-
if (value && value.byteLength > 0) {
|
|
291
|
-
this.send({
|
|
292
|
-
type: "res-chunk",
|
|
293
|
-
id: frame.id,
|
|
294
|
-
data: Buffer.from(value).toString("base64"),
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
this.send({ type: "res-end", id: frame.id });
|
|
299
|
-
}
|
|
300
|
-
catch (err) {
|
|
301
|
-
this.send({
|
|
302
|
-
type: "res-error",
|
|
303
|
-
id: frame.id,
|
|
304
|
-
message: `stream error: ${err.message}`,
|
|
305
|
-
});
|
|
306
|
-
}
|
|
307
|
-
finally {
|
|
308
|
-
this.inflight.delete(frame.id);
|
|
309
|
-
}
|
|
346
|
+
this.closeRequestBody(stream);
|
|
310
347
|
}
|
|
311
|
-
|
|
312
|
-
const
|
|
313
|
-
|
|
348
|
+
handleStreamAbort(frame) {
|
|
349
|
+
const key = streamIdKey(frame.streamId);
|
|
350
|
+
const stream = this.inflight.get(key);
|
|
351
|
+
if (!stream)
|
|
314
352
|
return;
|
|
353
|
+
this.inflight.delete(key);
|
|
315
354
|
try {
|
|
316
|
-
|
|
355
|
+
stream.controller.abort();
|
|
356
|
+
}
|
|
357
|
+
catch { }
|
|
358
|
+
void stream.reader?.cancel().catch(() => undefined);
|
|
359
|
+
try {
|
|
360
|
+
stream.bodyController?.error(new Error("client aborted"));
|
|
317
361
|
}
|
|
318
362
|
catch { }
|
|
319
363
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
if (!inflight || !inflight.bodyController || inflight.bodyClosed)
|
|
364
|
+
closeRequestBody(stream) {
|
|
365
|
+
if (!stream.bodyController || stream.bodyClosed)
|
|
323
366
|
return;
|
|
324
|
-
|
|
367
|
+
stream.bodyClosed = true;
|
|
325
368
|
try {
|
|
326
|
-
|
|
369
|
+
stream.bodyController.close();
|
|
327
370
|
}
|
|
328
371
|
catch { }
|
|
329
372
|
}
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
373
|
+
abortStream(ws, stream, reason) {
|
|
374
|
+
if (this.inflight.get(stream.key) === stream) {
|
|
375
|
+
this.inflight.delete(stream.key);
|
|
376
|
+
}
|
|
334
377
|
try {
|
|
335
|
-
|
|
378
|
+
stream.controller.abort();
|
|
336
379
|
}
|
|
337
380
|
catch { }
|
|
338
381
|
try {
|
|
339
|
-
|
|
382
|
+
stream.bodyController?.error(new Error(reason));
|
|
340
383
|
}
|
|
341
384
|
catch { }
|
|
342
|
-
|
|
385
|
+
void stream.reader?.cancel().catch(() => undefined);
|
|
386
|
+
this.sendRaw(ws, encodeFrame(FrameType.StreamAbort, stream.streamId));
|
|
387
|
+
}
|
|
388
|
+
consumeEncryptedPayload(ws, stream, payload) {
|
|
389
|
+
let records;
|
|
390
|
+
try {
|
|
391
|
+
records = stream.decoder.push(payload);
|
|
392
|
+
}
|
|
393
|
+
catch (err) {
|
|
394
|
+
this.abortStream(ws, stream, `E2EE decrypt failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
for (const plaintext of records) {
|
|
398
|
+
if (!stream.headReceived) {
|
|
399
|
+
let head;
|
|
400
|
+
try {
|
|
401
|
+
const parsed = JSON.parse(plaintext.toString("utf8"));
|
|
402
|
+
if (typeof parsed.method !== "string" || typeof parsed.path !== "string") {
|
|
403
|
+
throw new Error("missing method or path");
|
|
404
|
+
}
|
|
405
|
+
head = {
|
|
406
|
+
method: parsed.method,
|
|
407
|
+
path: parsed.path,
|
|
408
|
+
headers: parsed.headers,
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
catch (err) {
|
|
412
|
+
this.abortStream(ws, stream, `invalid request head: ${err instanceof Error ? err.message : String(err)}`);
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
stream.headReceived = true;
|
|
416
|
+
const upperMethod = head.method.toUpperCase();
|
|
417
|
+
if (upperMethod !== "GET" && upperMethod !== "HEAD") {
|
|
418
|
+
stream.bodyStream = new ReadableStream({
|
|
419
|
+
start: (controller) => {
|
|
420
|
+
stream.bodyController = controller;
|
|
421
|
+
},
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
void this.executeRequest(ws, stream, head);
|
|
425
|
+
}
|
|
426
|
+
else if (plaintext.length === 0) {
|
|
427
|
+
this.closeRequestBody(stream);
|
|
428
|
+
}
|
|
429
|
+
else if (stream.bodyController && !stream.bodyClosed) {
|
|
430
|
+
try {
|
|
431
|
+
stream.bodyController.enqueue(plaintext);
|
|
432
|
+
}
|
|
433
|
+
catch { }
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async executeRequest(ws, stream, head) {
|
|
438
|
+
const active = () => !this.closed &&
|
|
439
|
+
this.ws === ws &&
|
|
440
|
+
this.inflight.get(stream.key) === stream &&
|
|
441
|
+
!stream.controller.signal.aborted;
|
|
442
|
+
let reader;
|
|
443
|
+
try {
|
|
444
|
+
const localUrl = resolveLocalUrl(this.opts.localOrigin, head.path);
|
|
445
|
+
if (localUrl === null) {
|
|
446
|
+
throw new Error("rejected local request path");
|
|
447
|
+
}
|
|
448
|
+
const headers = new Headers();
|
|
449
|
+
if (head.headers) {
|
|
450
|
+
for (const [key, value] of Object.entries(head.headers)) {
|
|
451
|
+
if (HOP_BY_HOP.has(key.toLowerCase()))
|
|
452
|
+
continue;
|
|
453
|
+
if (Array.isArray(value)) {
|
|
454
|
+
for (const item of value) {
|
|
455
|
+
if (typeof item === "string")
|
|
456
|
+
headers.append(key, item);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
else if (typeof value === "string") {
|
|
460
|
+
headers.set(key, value);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
// Host 注入的本地鉴权头(如 Basic Auth)始终覆盖不可信的客户端同名头。
|
|
465
|
+
for (const [key, value] of Object.entries(this.opts.localHeaders ?? {})) {
|
|
466
|
+
if (!HOP_BY_HOP.has(key.toLowerCase())) {
|
|
467
|
+
headers.set(key, value);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
const init = {
|
|
471
|
+
method: head.method,
|
|
472
|
+
headers,
|
|
473
|
+
signal: stream.controller.signal,
|
|
474
|
+
redirect: "error",
|
|
475
|
+
};
|
|
476
|
+
if (stream.bodyStream) {
|
|
477
|
+
init.duplex = "half";
|
|
478
|
+
init.body = stream.bodyStream;
|
|
479
|
+
}
|
|
480
|
+
const response = await fetch(localUrl, init);
|
|
481
|
+
if (!active()) {
|
|
482
|
+
await response.body?.cancel();
|
|
483
|
+
return;
|
|
484
|
+
}
|
|
485
|
+
const responseHeaders = {};
|
|
486
|
+
const setCookies = typeof response.headers.getSetCookie === "function"
|
|
487
|
+
? response.headers.getSetCookie()
|
|
488
|
+
: [];
|
|
489
|
+
response.headers.forEach((value, key) => {
|
|
490
|
+
const lower = key.toLowerCase();
|
|
491
|
+
if (HOP_BY_HOP.has(lower))
|
|
492
|
+
return;
|
|
493
|
+
if (lower === "set-cookie" && setCookies.length > 0)
|
|
494
|
+
return;
|
|
495
|
+
responseHeaders[key] = value;
|
|
496
|
+
});
|
|
497
|
+
if (setCookies.length === 1) {
|
|
498
|
+
responseHeaders["set-cookie"] = setCookies[0];
|
|
499
|
+
}
|
|
500
|
+
else if (setCookies.length > 1) {
|
|
501
|
+
responseHeaders["set-cookie"] = setCookies;
|
|
502
|
+
}
|
|
503
|
+
const resHead = {
|
|
504
|
+
status: response.status,
|
|
505
|
+
headers: responseHeaders,
|
|
506
|
+
};
|
|
507
|
+
const encryptedHead = stream.encoder.encode(Buffer.from(JSON.stringify(resHead), "utf8"));
|
|
508
|
+
await this.sendWithBackpressure(ws, encodeFrame(FrameType.StreamData, stream.streamId, encryptedHead), active);
|
|
509
|
+
if (response.body) {
|
|
510
|
+
reader = response.body.getReader();
|
|
511
|
+
stream.reader = reader;
|
|
512
|
+
while (active()) {
|
|
513
|
+
const { value, done } = await reader.read();
|
|
514
|
+
if (!active())
|
|
515
|
+
return;
|
|
516
|
+
if (done)
|
|
517
|
+
break;
|
|
518
|
+
if (value?.byteLength) {
|
|
519
|
+
for (let offset = 0; offset < value.byteLength && active(); offset += MAX_RESPONSE_CHUNK_BYTES) {
|
|
520
|
+
const slice = value.subarray(offset, Math.min(offset + MAX_RESPONSE_CHUNK_BYTES, value.byteLength));
|
|
521
|
+
const encryptedChunk = stream.encoder.encode(slice);
|
|
522
|
+
await this.sendWithBackpressure(ws, encodeFrame(FrameType.StreamData, stream.streamId, encryptedChunk), active);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
await this.sendWithBackpressure(ws, encodeFrame(FrameType.StreamEnd, stream.streamId), active);
|
|
528
|
+
}
|
|
529
|
+
catch {
|
|
530
|
+
if (active()) {
|
|
531
|
+
this.sendRaw(ws, encodeFrame(FrameType.StreamAbort, stream.streamId));
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
finally {
|
|
535
|
+
if (this.inflight.get(stream.key) === stream) {
|
|
536
|
+
this.inflight.delete(stream.key);
|
|
537
|
+
}
|
|
538
|
+
stream.controller.abort();
|
|
539
|
+
try {
|
|
540
|
+
stream.bodyController?.error(new Error("request finished"));
|
|
541
|
+
}
|
|
542
|
+
catch { }
|
|
543
|
+
try {
|
|
544
|
+
await reader?.cancel();
|
|
545
|
+
}
|
|
546
|
+
catch { }
|
|
547
|
+
reader?.releaseLock();
|
|
548
|
+
}
|
|
343
549
|
}
|
|
344
550
|
}
|
|
345
551
|
//# sourceMappingURL=tunnel.js.map
|