@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/dist/tunnel.js CHANGED
@@ -1,13 +1,12 @@
1
1
  /**
2
- * [INPUT]: 依赖 ws 的 WebSocket 客户端,依赖 ./protocol.js 的帧定义及可选本地上游鉴权 headers
3
- * [OUTPUT]: 对外提供 TunnelClient 类 (start/close/connect/send/handleFrame/reconnect/schedule 私有方法),被 src/index.ts 实例化
4
- * CLI 端 WS 客户端连 wss://relay/host/{tunnelId},发 host-hello + 自动心跳/重连 + SSE/req 转发并向本地 fetch 注入可信 headers
5
- * 严格禁掉 permessage-deflate 协商 (perMessageDeflate: false),避免 caddy 透明代理吞 pong 帧
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 { PROTOCOL_VERSION, } from "./protocol.js";
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 but keeps the header.
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
- * 把隧道帧里的 path 解析成本地上游 URL;跨 origin 时返回 null。
29
- *
30
- * `new URL("//evil.com/x", "http://127.0.0.1:4096")` 会得到 `http://evil.com/x`
31
- * —— `//` 开头是**协议相对 URL**,会被解析到任意主机。而调用方会把
32
- * localHeaders(含本地 Bridge token)注入这次 fetch,等于让用户自己的电脑
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
- const url = new URL(`/host/${this.opts.tunnelId}`, this.opts.relayUrl).toString();
66
- const ws = new WebSocket(url, { perMessageDeflate: false });
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.send({
70
- type: "host-hello",
71
- version: PROTOCOL_VERSION,
72
- secret: this.opts.secret,
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.send({ type: "ping" });
76
- this.pongDeadline = Date.now() + 5000;
77
- }, 15000);
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
- this.ws?.close();
163
+ ws.terminate();
83
164
  }
84
165
  catch { }
85
166
  }
86
- }, 1000);
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 = JSON.parse(raw.toString());
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
- if (this.pingTimer)
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 (!this.closed) {
111
- const err = new Error(`tunnel closed (code=${code}${reasonStr ? `, ${reasonStr}` : ""})`);
112
- this.opts.onError?.(err);
113
- this.scheduleReconnect();
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
- close() {
122
- this.closed = true;
123
- if (this.pingTimer)
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
- send(frame) {
136
- if (this.ws && this.ws.readyState === WebSocket.OPEN) {
137
- this.ws.send(JSON.stringify(frame));
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(1000 * 2 ** this.reconnectAttempt, 10_000);
144
- const jitter = Math.floor(Math.random() * 1000);
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 inflight of this.inflight.values()) {
251
+ for (const stream of this.inflight.values()) {
156
252
  try {
157
- inflight.controller.abort();
253
+ stream.controller.abort();
158
254
  }
159
255
  catch { }
160
256
  try {
161
- inflight.bodyController?.error(new Error("tunnel closed"));
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 "host-hello-ack": {
170
- const ack = frame;
171
- const relayPublicUrl = this.opts.relayUrl
172
- .replace(/^wss:\/\//, "https://")
173
- .replace(/^ws:\/\//, "http://")
174
- .replace(/\/$/, "");
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?.(ack, relayPublicUrl);
280
+ await this.opts.onReady?.(hostId);
177
281
  return;
178
282
  }
179
- case "ping":
180
- this.send({ type: "pong" });
283
+ case FrameType.Ping:
284
+ this.sendRaw(ws, encodeControlFrame(FrameType.Pong));
181
285
  return;
182
- case "pong":
286
+ case FrameType.Pong:
183
287
  this.pongDeadline = null;
184
288
  return;
185
- case "req-head":
186
- await this.handleReqHead(frame);
289
+ case FrameType.StreamOpen:
290
+ this.handleStreamOpen(ws, frame);
187
291
  return;
188
- case "req-chunk":
189
- this.handleReqChunk(frame);
292
+ case FrameType.StreamData:
293
+ this.handleStreamData(ws, frame);
190
294
  return;
191
- case "req-end":
192
- this.handleReqEnd(frame);
295
+ case FrameType.StreamEnd:
296
+ this.handleStreamEnd(ws, frame);
193
297
  return;
194
- case "req-abort":
195
- this.handleReqAbort(frame);
298
+ case FrameType.StreamAbort:
299
+ this.handleStreamAbort(frame);
196
300
  return;
197
301
  default:
198
302
  return;
199
303
  }
200
304
  }
201
- async handleReqHead(frame) {
202
- const controller = new AbortController();
203
- const inflight = {
204
- id: frame.id,
205
- controller,
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
- if (frame.hasBody) {
210
- inflight.bodyStream = new ReadableStream({
211
- start: (c) => {
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
- this.inflight.set(frame.id, inflight);
217
- const headers = new Headers();
218
- for (const [k, v] of Object.entries(frame.headers)) {
219
- if (HOP_BY_HOP.has(k.toLowerCase()))
220
- continue;
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
- const init = {
246
- method: frame.method,
247
- headers,
248
- signal: controller.signal,
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
- const resHeaders = {};
268
- res.headers.forEach((value, key) => {
269
- if (HOP_BY_HOP.has(key.toLowerCase()))
270
- return;
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
- const reader = res.body.getReader();
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
- handleReqChunk(frame) {
312
- const inflight = this.inflight.get(frame.id);
313
- if (!inflight || !inflight.bodyController)
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
- inflight.bodyController.enqueue(Buffer.from(frame.data, "base64"));
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
- handleReqEnd(frame) {
321
- const inflight = this.inflight.get(frame.id);
322
- if (!inflight || !inflight.bodyController || inflight.bodyClosed)
364
+ closeRequestBody(stream) {
365
+ if (!stream.bodyController || stream.bodyClosed)
323
366
  return;
324
- inflight.bodyClosed = true;
367
+ stream.bodyClosed = true;
325
368
  try {
326
- inflight.bodyController.close();
369
+ stream.bodyController.close();
327
370
  }
328
371
  catch { }
329
372
  }
330
- handleReqAbort(frame) {
331
- const inflight = this.inflight.get(frame.id);
332
- if (!inflight)
333
- return;
373
+ abortStream(ws, stream, reason) {
374
+ if (this.inflight.get(stream.key) === stream) {
375
+ this.inflight.delete(stream.key);
376
+ }
334
377
  try {
335
- inflight.controller.abort();
378
+ stream.controller.abort();
336
379
  }
337
380
  catch { }
338
381
  try {
339
- inflight.bodyController?.error(new Error("client aborted"));
382
+ stream.bodyController?.error(new Error(reason));
340
383
  }
341
384
  catch { }
342
- this.inflight.delete(frame.id);
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