@floegence/flowersec-core 7.0.0 → 7.2.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.
Files changed (65) hide show
  1. package/README.md +6 -5
  2. package/THIRD_PARTY_NOTICES.md +8 -8
  3. package/dist/node/acceptorV3.js +9 -4
  4. package/dist/node/connectSessionV3.d.ts +2 -2
  5. package/dist/node/connectSessionV3.js +9 -3
  6. package/dist/node/connectionPath.js +49 -37
  7. package/dist/node/listenerIngress.d.ts +7 -0
  8. package/dist/node/listenerIngress.js +21 -0
  9. package/dist/node/nativeTransportAddon.d.ts +1 -5
  10. package/dist/node/nativeTransportAddon.js +3 -5
  11. package/dist/node/proxyServer.d.ts +1 -0
  12. package/dist/node/proxyServer.js +173 -78
  13. package/dist/node/proxyTarget.d.ts +1 -0
  14. package/dist/node/proxyTarget.js +13 -0
  15. package/dist/node/rawQuicAdapterV3.js +2 -2
  16. package/dist/node/rawQuicServerV3.d.ts +3 -1
  17. package/dist/node/rawQuicServerV3.js +18 -3
  18. package/dist/node/tunnelRuntimeV3.js +42 -8
  19. package/dist/node/webSocketServerV3.js +27 -2
  20. package/dist/proxy/bodyIntake.d.ts +13 -0
  21. package/dist/proxy/bodyIntake.js +55 -0
  22. package/dist/proxy/controllerGuard.d.ts +4 -0
  23. package/dist/proxy/controllerGuard.js +79 -37
  24. package/dist/proxy/fetch.d.ts +2 -1
  25. package/dist/proxy/fetch.js +55 -27
  26. package/dist/proxy/integration.d.ts +1 -1
  27. package/dist/proxy/integration.js +25 -5
  28. package/dist/proxy/registerServiceWorker.d.ts +5 -0
  29. package/dist/proxy/registerServiceWorker.js +30 -21
  30. package/dist/proxy/runtime.d.ts +7 -1
  31. package/dist/proxy/runtime.js +129 -39
  32. package/dist/proxy/scope.js +1 -1
  33. package/dist/proxy/serviceWorker.js +286 -43
  34. package/dist/proxy/serviceWorkerRuntime.d.ts +5 -2
  35. package/dist/proxy/serviceWorkerRuntime.js +58 -3
  36. package/dist/proxy/stream.d.ts +1 -0
  37. package/dist/proxy/stream.js +6 -3
  38. package/dist/proxy/types.d.ts +1 -1
  39. package/dist/proxy/windowBridge.d.ts +3 -1
  40. package/dist/proxy/windowBridge.js +64 -19
  41. package/dist/proxy/wsPatch.js +70 -52
  42. package/dist/public/sessionHandlers.js +3 -2
  43. package/dist/utils/abort.d.ts +1 -0
  44. package/dist/utils/abort.js +13 -0
  45. package/dist/v3/artifactLease.d.ts +6 -0
  46. package/dist/v3/artifactLease.js +6 -0
  47. package/dist/v3/contract.d.ts +1 -0
  48. package/dist/v3/nodeRuntime.js +10 -25
  49. package/dist/v3/publicSession.d.ts +2 -1
  50. package/dist/v3/publicSession.js +11 -15
  51. package/dist/v3/session.d.ts +7 -1
  52. package/dist/v3/session.js +110 -25
  53. package/dist/v3/unreliableMessage.d.ts +1 -0
  54. package/dist/v3/unreliableMessage.js +5 -1
  55. package/dist/v3/webSocketCarrier.js +24 -11
  56. package/dist/v3/webTransportCarrier.js +6 -0
  57. package/dist/vendor/tr46.js +17 -23
  58. package/dist/ws-client/binaryTransport.d.ts +2 -0
  59. package/dist/ws-client/binaryTransport.js +8 -2
  60. package/dist/yamux/byteReader.js +1 -0
  61. package/dist/yamux/session.d.ts +2 -0
  62. package/dist/yamux/session.js +4 -1
  63. package/package.json +12 -12
  64. package/sbom/cyclonedx.json +43 -43
  65. package/sbom/spdx.json +49 -49
@@ -2,6 +2,8 @@ import { createRequire } from "node:module";
2
2
  import { SessionError } from "../public/contract.js";
3
3
  import { writeJsonFrame } from "../framing/jsonframe.js";
4
4
  import { ProxyByteReader, writeAll, writeProxyWebSocketFrame } from "../proxy/stream.js";
5
+ import { resolveProxyTarget } from "./proxyTarget.js";
6
+ import { incomingResetSignal } from "../v3/publicSession.js";
5
7
  import { StreamHandlers, registerStreamHandlersAtomically, } from "../public/streamHandlers.js";
6
8
  import { SessionHandlersV3, registerSessionStreamHandlersAtomically, } from "./acceptor.js";
7
9
  const HTTP_KIND = "flowersec-proxy/http1";
@@ -15,7 +17,7 @@ const DEFAULT_TIMEOUT = 30_000;
15
17
  const MAX_TIMEOUT = 300_000;
16
18
  const FORBIDDEN_HEADERS = new Set(["authorization", "connection", "host", "keep-alive", "proxy-authorization", "set-cookie", "transfer-encoding", "upgrade"]);
17
19
  const REQUEST_HEADERS = new Set(["accept", "accept-language", "content-type", "if-match", "if-none-match", "range"]);
18
- const RESPONSE_HEADERS = new Set(["accept-ranges", "cache-control", "content-disposition", "content-language", "content-range", "content-type", "etag", "expires", "last-modified", "location"]);
20
+ const RESPONSE_HEADERS = new Set(["accept-ranges", "cache-control", "content-disposition", "content-language", "content-range", "content-security-policy", "content-type", "etag", "expires", "last-modified", "location", "x-content-type-options", "x-frame-options"]);
19
21
  const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u;
20
22
  export class ProxyServerError extends Error {
21
23
  code;
@@ -34,6 +36,7 @@ export class ProxyServer {
34
36
  #resolveCompletion;
35
37
  #closed = false;
36
38
  #httpCount = 0;
39
+ #bufferedBodyBytes = 0;
37
40
  #eventCount = 0;
38
41
  constructor(options) {
39
42
  this.#config = compileConfig(options);
@@ -153,20 +156,31 @@ export class ProxyServer {
153
156
  if (this.#closed && this.#active.size === 0)
154
157
  this.#resolveCompletion();
155
158
  }
156
- #report(error) { try {
157
- this.#config.report?.(error);
159
+ #report(error) {
160
+ const diagnostic = error instanceof ProxyServerError ? new ProxyServerError(error.code)
161
+ : new SessionError(error instanceof SessionError ? error.code : "operation_failed");
162
+ try {
163
+ this.#config.report?.(diagnostic);
164
+ }
165
+ catch { /* reporting is isolated */ }
158
166
  }
159
- catch { /* reporting is isolated */ } }
160
167
  async #serveHTTP(stream, parentSignal) {
161
168
  const started = performance.now();
162
169
  const timeoutController = new AbortController();
163
170
  let timer = setTimeout(() => timeoutController.abort(), this.#config.maxTimeout);
164
- const linked = linkSignals(parentSignal, timeoutController.signal);
165
- const signal = linked.signal;
171
+ const resetSignal = incomingResetSignal(stream);
172
+ const signal = AbortSignal.any(resetSignal ? [parentSignal, timeoutController.signal, resetSignal] : [parentSignal, timeoutController.signal]);
166
173
  let reset;
167
174
  let peerWatch;
168
175
  let responseReader;
169
176
  let httpPermit = false;
177
+ let reservedBytes = 0;
178
+ const upload = [];
179
+ const releaseUpload = () => {
180
+ upload.length = 0;
181
+ this.#bufferedBodyBytes -= reservedBytes;
182
+ reservedBytes = 0;
183
+ };
170
184
  let eventPermit = false;
171
185
  const releaseEvent = () => { if (eventPermit) {
172
186
  eventPermit = false;
@@ -187,8 +201,8 @@ export class ProxyServer {
187
201
  return;
188
202
  }
189
203
  const requestID = meta.request_id.trim();
190
- const path = normalizePath(meta.path);
191
- if (meta.v !== WIRE_VERSION || requestID === "" || meta.method.trim() === "" || path === undefined) {
204
+ const target = resolveProxyTarget(this.#config.upstream, meta.path);
205
+ if (meta.v !== WIRE_VERSION || requestID === "" || meta.method.trim() === "" || target === undefined) {
192
206
  await writeHTTPError(stream, requestID, "invalid_request_meta");
193
207
  return;
194
208
  }
@@ -203,17 +217,6 @@ export class ProxyServer {
203
217
  timeoutController.abort();
204
218
  else
205
219
  timer = setTimeout(() => timeoutController.abort(), remaining);
206
- const body = await readBody(reader, this.#config.maxChunk, this.#config.maxBody);
207
- if (body === undefined) {
208
- await writeHTTPError(stream, requestID, "request_body_invalid");
209
- return;
210
- }
211
- // A peer reset cancels the upstream even when it has no next event to write.
212
- // A FIN only closes request writes and is valid during response streaming.
213
- peerWatch = stream.read({ signal }).then((chunk) => {
214
- if (chunk !== null)
215
- timeoutController.abort(new SessionError("canceled"));
216
- }, () => { timeoutController.abort(new SessionError("canceled")); });
217
220
  if (this.#httpCount >= this.#config.maxHTTP) {
218
221
  await writeHTTPError(stream, requestID, "resource_exhausted");
219
222
  return;
@@ -234,22 +237,63 @@ export class ProxyServer {
234
237
  await writeHTTPError(stream, requestID, "invalid_request_meta");
235
238
  return;
236
239
  }
237
- const requestHeaders = filterRequestHeaders(meta.headers, this.#config);
240
+ const requestHeaders = filterUpstreamHeaders(meta.headers, REQUEST_HEADERS, this.#config.requestHeaders, this.#config);
241
+ const headers = Object.fromEntries(requestHeaders.map((header) => [header.name, header.value]));
242
+ delete headers["x-forwarded-proto"];
243
+ if (requestHeaders.filter(header => header.name === "origin").length > 1) {
244
+ await writeHTTPError(stream, requestID, "invalid_request_meta");
245
+ return;
246
+ }
238
247
  if (externalOrigin !== undefined) {
239
- const explicitOrigin = requestHeaders.find((header) => header.name === "origin")?.value;
248
+ const explicitOrigin = headers.origin;
240
249
  if (explicitOrigin !== undefined && explicitOrigin !== externalOrigin) {
241
250
  await writeHTTPError(stream, requestID, "invalid_request_meta");
242
251
  return;
243
252
  }
244
253
  const origin = new URL(externalOrigin);
245
- requestHeaders.push({ name: "x-forwarded-proto", value: origin.protocol.slice(0, -1) });
254
+ headers["x-forwarded-proto"] = origin.protocol.slice(0, -1);
246
255
  }
247
- const headers = Object.fromEntries(requestHeaders.map((header) => [header.name, header.value]));
248
- const target = new URL(path, this.#config.upstream);
256
+ const bodyLength = await readBody(reader, upload, this.#config.maxChunk, this.#config.maxBody, (minimum, preferred) => {
257
+ const available = this.#config.maxBufferedBody - this.#bufferedBodyBytes;
258
+ const growth = Math.min(preferred, available);
259
+ if (growth < minimum)
260
+ return 0;
261
+ reservedBytes += growth;
262
+ this.#bufferedBodyBytes += growth;
263
+ return growth;
264
+ });
265
+ if (typeof bodyLength === "string") {
266
+ await writeHTTPError(stream, requestID, bodyLength);
267
+ return;
268
+ }
269
+ // A peer reset cancels the upstream even when it has no next event to write.
270
+ // A FIN only closes request writes and is valid during response streaming.
271
+ peerWatch = reader.remainingStream().read({ signal }).then((chunk) => {
272
+ if (chunk !== null)
273
+ timeoutController.abort(new SessionError("canceled"));
274
+ }, () => { timeoutController.abort(new SessionError("canceled")); });
249
275
  const requestInit = {
250
276
  method: meta.method.trim().toUpperCase(), headers, redirect: "manual", signal,
251
- ...(body.byteLength === 0 ? {} : { body: body.slice().buffer, duplex: "half" }),
252
277
  };
278
+ if (bodyLength > 0) {
279
+ headers["content-length"] = String(bodyLength);
280
+ upload.reverse();
281
+ requestInit.duplex = "half";
282
+ requestInit.body = new ReadableStream({
283
+ pull(controller) {
284
+ const block = upload.pop();
285
+ if (block) {
286
+ controller.enqueue(block);
287
+ }
288
+ else {
289
+ controller.close();
290
+ releaseUpload();
291
+ }
292
+ },
293
+ cancel: releaseUpload,
294
+ }, { highWaterMark: 0 });
295
+ }
296
+ let responseStarted = false;
253
297
  try {
254
298
  const response = await fetch(target, requestInit);
255
299
  const persistent = eventRequested && isEventStream(response.headers.get("content-type") ?? "");
@@ -264,10 +308,11 @@ export class ProxyServer {
264
308
  else
265
309
  releaseEvent();
266
310
  const contentLength = response.headers.get("content-length");
267
- if (!persistent && contentLength !== null && Number(contentLength) > this.#config.maxBody) {
311
+ if (response.body !== null && !persistent && contentLength !== null && Number(contentLength) > this.#config.maxBody) {
268
312
  await writeHTTPError(stream, requestID, "response_body_too_large");
269
313
  return;
270
314
  }
315
+ responseStarted = true;
271
316
  await writeFrame(stream, {
272
317
  v: WIRE_VERSION, request_id: requestID, ok: true, status: response.status,
273
318
  headers: filterHeaders(responseHeaderList(response.headers), RESPONSE_HEADERS, this.#config.responseHeaders, this.#config.blockedResponseHeaders),
@@ -293,7 +338,7 @@ export class ProxyServer {
293
338
  await writeChunk(stream, new Uint8Array(), signal);
294
339
  }
295
340
  catch (error) {
296
- if (signal.aborted)
341
+ if (responseStarted || signal.aborted)
297
342
  throw error;
298
343
  const code = timeoutController.signal.aborted ? "timeout" : signal.aborted ? "canceled" : "upstream_request_failed";
299
344
  await writeHTTPError(stream, requestID, code);
@@ -302,10 +347,10 @@ export class ProxyServer {
302
347
  }
303
348
  finally {
304
349
  clearTimeout(timer);
350
+ releaseUpload();
305
351
  releaseEvent();
306
352
  if (httpPermit)
307
353
  this.#httpCount--;
308
- linked.dispose();
309
354
  signal.removeEventListener("abort", abort);
310
355
  timeoutController.abort();
311
356
  await responseReader?.cancel().catch(() => undefined);
@@ -314,28 +359,50 @@ export class ProxyServer {
314
359
  await reset;
315
360
  }
316
361
  }
317
- async #serveWebSocket(stream, signal) {
362
+ async #serveWebSocket(stream, parent) {
363
+ const deadline = new AbortController();
364
+ const timer = setTimeout(() => deadline.abort(new SessionError("timeout")), this.#config.maxTimeout);
365
+ const resetSignal = incomingResetSignal(stream);
366
+ const signal = AbortSignal.any(resetSignal ? [parent, deadline.signal, resetSignal] : [parent, deadline.signal]);
367
+ let resetting;
368
+ const abort = () => { resetting ??= stream.reset().catch(() => undefined); };
369
+ signal.addEventListener("abort", abort, { once: true });
370
+ try {
371
+ if (signal.aborted) {
372
+ abort();
373
+ return;
374
+ }
375
+ await this.#runWebSocket(stream, signal, () => clearTimeout(timer));
376
+ }
377
+ finally {
378
+ clearTimeout(timer);
379
+ signal.removeEventListener("abort", abort);
380
+ await resetting;
381
+ }
382
+ }
383
+ async #runWebSocket(stream, signal, established) {
318
384
  const reader = new ProxyByteReader(stream, { signal });
319
385
  let open;
320
386
  try {
321
387
  open = decodeWSOpen(await readFrame(reader, this.#config.maxJSON));
322
388
  }
323
389
  catch {
324
- await writeWSError(stream, "unknown", "invalid_ws_open_meta");
390
+ if (!signal.aborted)
391
+ await writeWSError(stream, "unknown", "invalid_ws_open_meta", signal);
325
392
  return;
326
393
  }
327
- const path = normalizePath(open.path);
328
- if (open.v !== WIRE_VERSION || open.conn_id.trim() === "" || path === undefined) {
329
- await writeWSError(stream, open.conn_id, "invalid_ws_open_meta");
394
+ const upstreamURL = resolveProxyTarget(this.#config.upstream, open.path);
395
+ if (open.v !== WIRE_VERSION || open.conn_id.trim() === "" || upstreamURL === undefined) {
396
+ await writeWSError(stream, open.conn_id, "invalid_ws_open_meta", signal);
330
397
  return;
331
398
  }
332
- const upstreamURL = new URL(path, this.#config.upstream);
399
+ signal.throwIfAborted();
333
400
  upstreamURL.protocol = upstreamURL.protocol === "https:" ? "wss:" : "ws:";
334
401
  const require = createRequire(import.meta.url);
335
402
  const wsModule = require("ws");
336
403
  const WebSocketCtor = wsModule?.WebSocket ?? wsModule;
337
404
  const protocols = open.headers.find((header) => header.name.toLowerCase() === "sec-websocket-protocol")?.value;
338
- const headers = filterHeaders(open.headers, new Set(["sec-websocket-protocol"]), this.#config.websocketHeaders)
405
+ const headers = filterUpstreamHeaders(open.headers, new Set(["sec-websocket-protocol"]), this.#config.websocketHeaders, this.#config)
339
406
  .filter((header) => header.name !== "origin");
340
407
  const socket = new WebSocketCtor(upstreamURL.toString(), protocols === undefined ? undefined : protocols.split(",").map((item) => item.trim()), {
341
408
  headers: {
@@ -346,23 +413,34 @@ export class ProxyServer {
346
413
  perMessageDeflate: false,
347
414
  });
348
415
  let opened = false;
416
+ const socketClosed = new Promise((resolve) => socket.once("close", resolve));
417
+ socket.on("error", () => { });
418
+ const terminate = () => socket.terminate();
419
+ signal.addEventListener("abort", terminate, { once: true });
349
420
  try {
421
+ socket.once("open", () => socket.pause());
350
422
  await onceEvent(socket, "open", signal);
351
423
  await writeFrame(stream, { v: WIRE_VERSION, conn_id: open.conn_id.trim(), ok: true, protocol: socket.protocol ?? "" }, signal);
352
424
  opened = true;
425
+ if (socket.readyState !== WebSocketCtor.OPEN)
426
+ return;
427
+ established();
353
428
  await relayWebSocket(socket, stream, reader, this.#config.maxWS, signal);
354
429
  }
355
430
  catch (error) {
356
- if (!opened)
357
- await writeWSError(stream, open.conn_id, signal.aborted ? "canceled" : "upstream_ws_dial_failed");
431
+ if (!opened && !signal.aborted)
432
+ await writeWSError(stream, open.conn_id, "upstream_ws_dial_failed", signal);
358
433
  this.#report(error);
359
434
  }
360
435
  finally {
361
- try {
436
+ if (signal.aborted || !opened)
437
+ socket.terminate();
438
+ else
362
439
  socket.close();
363
- }
364
- catch { /* cleanup */ }
365
- await stream.close().catch(() => undefined);
440
+ await socketClosed;
441
+ signal.removeEventListener("abort", terminate);
442
+ if (!opened || signal.aborted)
443
+ await stream.close().catch(() => undefined);
366
444
  }
367
445
  }
368
446
  }
@@ -380,8 +458,9 @@ function compileConfig(options) {
380
458
  throw new ProxyServerError("invalid_options");
381
459
  if ((origin.protocol !== "http:" && origin.protocol !== "https:") || origin.pathname !== "/" || origin.search || origin.hash || origin.username || origin.origin !== origin.toString().replace(/\/$/u, ""))
382
460
  throw new ProxyServerError("invalid_options");
383
- const allowedHosts = new Set((options.allowedUpstreamHosts ?? ["127.0.0.1", "::1"]).map((value) => value.trim().toLowerCase()));
384
- if (!allowedHosts.has(upstream.hostname.toLowerCase()))
461
+ const hostKey = (host) => host.toLowerCase().replace(/^\[([^\]]+)\]$/u, "$1");
462
+ const allowedHosts = new Set((options.allowedUpstreamHosts ?? ["127.0.0.1", "::1"]).map((value) => hostKey(value.trim())));
463
+ if (!allowedHosts.has(hostKey(upstream.hostname)))
385
464
  throw new ProxyServerError("invalid_options");
386
465
  const allowedOrigins = new Set(options.allowedOrigins ?? [origin.origin]);
387
466
  for (const allowed of allowedOrigins) {
@@ -403,10 +482,11 @@ function compileConfig(options) {
403
482
  const maxJSON = positive(options.maxJsonFrameBytes, DEFAULT_MAX_JSON);
404
483
  const maxChunk = positive(options.maxChunkBytes, DEFAULT_MAX_CHUNK);
405
484
  const maxBody = positive(options.maxBodyBytes, DEFAULT_MAX_BODY);
485
+ const maxBufferedBody = positive(options.maxBufferedRequestBodyBytes, Math.max(DEFAULT_MAX_BODY, maxBody));
406
486
  const maxWS = positive(options.maxWebSocketFrameBytes, DEFAULT_MAX_WS);
407
487
  const defaultTimeout = positive(options.defaultHTTPRequestTimeoutMs, DEFAULT_TIMEOUT);
408
488
  const maxTimeout = positive(options.maxHTTPRequestTimeoutMs, MAX_TIMEOUT);
409
- if ([maxConcurrent, maxHTTP, maxEvents, eventIdleTimeout, maxJSON, maxChunk, maxBody, maxWS, defaultTimeout, maxTimeout].some((value) => !Number.isSafeInteger(value) || value < 1) || defaultTimeout > maxTimeout)
489
+ if ([maxConcurrent, maxHTTP, maxEvents, eventIdleTimeout, maxJSON, maxChunk, maxBody, maxBufferedBody, maxWS, defaultTimeout, maxTimeout].some((value) => !Number.isSafeInteger(value) || value < 1) || defaultTimeout > maxTimeout)
410
490
  throw new ProxyServerError("invalid_options");
411
491
  const normalizeHeaders = (values) => new Set((values ?? []).map((name) => {
412
492
  const lower = name.trim().toLowerCase();
@@ -430,12 +510,12 @@ function compileConfig(options) {
430
510
  websocketHeaders: normalizeHeaders(options.extraWebSocketHeaders),
431
511
  forbiddenCookies: new Set(normalizeCookieValues(options.forbiddenCookieNames)),
432
512
  forbiddenCookiePrefixes: normalizeCookieValues(options.forbiddenCookieNamePrefixes),
433
- maxConcurrent, maxHTTP, maxEvents, eventIdleTimeout, maxJSON, maxChunk, maxBody, maxWS, defaultTimeout, maxTimeout,
513
+ maxConcurrent, maxHTTP, maxEvents, eventIdleTimeout, maxJSON, maxChunk, maxBody, maxBufferedBody, maxWS, defaultTimeout, maxTimeout,
434
514
  ...(options.onError === undefined ? {} : { report: options.onError }),
435
515
  };
436
516
  }
437
- function filterRequestHeaders(input, config) {
438
- const headers = filterHeaders(input, REQUEST_HEADERS, config.requestHeaders);
517
+ function filterUpstreamHeaders(input, base, extra, config) {
518
+ const headers = filterHeaders(input, base, extra);
439
519
  return headers.flatMap((header) => {
440
520
  if (header.name !== "cookie")
441
521
  return [header];
@@ -481,8 +561,8 @@ async function writeHTTPError(stream, requestID, code) {
481
561
  await writeFrame(stream, { v: WIRE_VERSION, request_id: requestID.trim() || "unknown", ok: false, error: { code, message: "proxy operation failed" } }).catch(() => undefined);
482
562
  await writeChunks(stream, new Uint8Array(), 1, undefined).catch(() => undefined);
483
563
  }
484
- async function writeWSError(stream, connID, code) {
485
- await writeFrame(stream, { v: WIRE_VERSION, conn_id: connID.trim() || "unknown", ok: false, error: { code, message: "proxy operation failed" } }).catch(() => undefined);
564
+ async function writeWSError(stream, connID, code, signal) {
565
+ await writeFrame(stream, { v: WIRE_VERSION, conn_id: connID.trim() || "unknown", ok: false, error: { code, message: "proxy operation failed" } }, signal).catch(() => undefined);
486
566
  }
487
567
  async function writeChunks(stream, body, chunkSize, signal) {
488
568
  for (let offset = 0; offset < body.length; offset += chunkSize) {
@@ -496,38 +576,45 @@ async function writeChunk(stream, chunk, signal) {
496
576
  bytes.set(chunk, 4);
497
577
  await writeAll(stream, bytes, signal === undefined ? {} : { signal });
498
578
  }
499
- async function readBody(reader, maxChunk, maxBody) {
500
- const chunks = [];
579
+ async function readBody(reader, blocks, maxChunk, maxBody, reserve) {
580
+ let block = new Uint8Array(0);
581
+ let used = 0;
501
582
  let total = 0;
502
583
  try {
503
584
  while (true) {
504
585
  const header = await reader.readExactly(4);
505
586
  const length = new DataView(header.buffer, header.byteOffset, 4).getUint32(0, false);
506
- if (length === 0)
507
- return concat(chunks);
508
- if (length > maxChunk || total + length > maxBody)
509
- return undefined;
510
- const chunk = await reader.readExactly(length);
511
- chunks.push(chunk);
587
+ if (length === 0) {
588
+ if (used > 0)
589
+ blocks.push(block.subarray(0, used));
590
+ return total;
591
+ }
592
+ if (length > maxChunk || length > maxBody - total)
593
+ return "request_body_invalid";
594
+ const fit = Math.min(length, block.length - used);
595
+ const required = length - fit;
596
+ if (required > 0) {
597
+ const preferred = Math.max(required, Math.min(64 * 1024, 2 * block.length));
598
+ const capacity = reserve(required, Math.min(maxBody - total - fit, preferred));
599
+ if (capacity === 0)
600
+ return "resource_exhausted";
601
+ if (fit > 0)
602
+ await reader.readInto(block.subarray(used));
603
+ if (block.length > 0)
604
+ blocks.push(block);
605
+ block = new Uint8Array(capacity);
606
+ used = 0;
607
+ }
608
+ const count = required || length;
609
+ await reader.readInto(block.subarray(used, used + count));
610
+ used += count;
512
611
  total += length;
513
612
  }
514
613
  }
515
614
  catch {
516
- return undefined;
615
+ return "request_body_invalid";
517
616
  }
518
617
  }
519
- function concat(chunks) { const out = new Uint8Array(chunks.reduce((sum, item) => sum + item.length, 0)); let offset = 0; for (const chunk of chunks) {
520
- out.set(chunk, offset);
521
- offset += chunk.length;
522
- } return out; }
523
- function normalizePath(value) { if (value.trim() !== value || !value.startsWith("/") || value.startsWith("//") || value.includes("://") || /[\u0000-\u0020\u007f]/u.test(value))
524
- return undefined; try {
525
- const parsed = new URL(value, "http://flowersec.invalid");
526
- return parsed.origin === "http://flowersec.invalid" && !parsed.hash ? `${parsed.pathname}${parsed.search}` : undefined;
527
- }
528
- catch {
529
- return undefined;
530
- } }
531
618
  function normalizeTimeout(value, fallback, maximum) { if (value !== undefined && (!Number.isSafeInteger(value) || value < 0))
532
619
  return undefined; return Math.min(value === undefined || value === 0 ? fallback : value, maximum); }
533
620
  function validateOrigin(value, allowed) { if (value === undefined || value === "")
@@ -538,10 +625,6 @@ function validateOrigin(value, allowed) { if (value === undefined || value === "
538
625
  catch {
539
626
  return undefined;
540
627
  } }
541
- function linkSignals(parent, timeout) { const controller = new AbortController(); const abort = (event) => controller.abort(event.target.reason); parent.addEventListener("abort", abort, { once: true }); timeout.addEventListener("abort", abort, { once: true }); if (parent.aborted)
542
- controller.abort(parent.reason);
543
- else if (timeout.aborted)
544
- controller.abort(timeout.reason); return { signal: controller.signal, dispose: () => { parent.removeEventListener("abort", abort); timeout.removeEventListener("abort", abort); } }; }
545
628
  function decodeHTTPMeta(value) { if (!isRecord(value) || value.v !== WIRE_VERSION || typeof value.request_id !== "string" || typeof value.method !== "string" || typeof value.path !== "string" || !Array.isArray(value.headers) || (value.external_origin !== undefined && typeof value.external_origin !== "string") || (value.timeout_ms !== undefined && typeof value.timeout_ms !== "number"))
546
629
  throw new Error("invalid HTTP metadata"); return { v: value.v, request_id: value.request_id, method: value.method, path: value.path, headers: value.headers.filter(isHeader), ...(value.external_origin === undefined ? {} : { external_origin: value.external_origin }), ...(value.timeout_ms === undefined ? {} : { timeout_ms: value.timeout_ms }) }; }
547
630
  function decodeWSOpen(value) { if (!isRecord(value) || value.v !== WIRE_VERSION || typeof value.conn_id !== "string" || typeof value.path !== "string" || !Array.isArray(value.headers))
@@ -587,6 +670,10 @@ async function relayWebSocket(socket, stream, reader, maximum, signal) {
587
670
  socket.once("close", (code, reason) => {
588
671
  if (done)
589
672
  return;
673
+ if (code === 1006) {
674
+ reject(new SessionError("operation_failed"));
675
+ return;
676
+ }
590
677
  const closePayload = encodeWebSocketClose(code, reason);
591
678
  void enqueue(async () => {
592
679
  const frame = new Uint8Array(5 + closePayload.length);
@@ -598,6 +685,7 @@ async function relayWebSocket(socket, stream, reader, maximum, signal) {
598
685
  });
599
686
  socket.once("error", reject);
600
687
  });
688
+ socket.resume();
601
689
  const downstream = (async () => {
602
690
  while (!done) {
603
691
  const frame = await reader.readExactly(5);
@@ -629,19 +717,26 @@ async function relayWebSocket(socket, stream, reader, maximum, signal) {
629
717
  }
630
718
  return "downstream_close";
631
719
  })();
720
+ let timer;
632
721
  try {
633
722
  const winner = await Promise.race([upstream, downstream]);
634
- if (winner === "downstream_close") {
635
- await Promise.race([upstream, new Promise((resolve) => setTimeout(resolve, 1_000))]);
636
- }
723
+ await Promise.race([
724
+ winner === "downstream_close" ? upstream : downstream,
725
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("WebSocket close timed out")), 1_000); }),
726
+ ]);
727
+ await stream.closeWrite();
728
+ }
729
+ catch (error) {
730
+ await stream.reset().catch(() => undefined);
731
+ throw error;
637
732
  }
638
733
  finally {
734
+ clearTimeout(timer);
639
735
  done = true;
640
736
  try {
641
737
  socket.close();
642
738
  }
643
739
  catch { /* cleanup */ }
644
- await stream.close().catch(() => undefined);
645
740
  await Promise.allSettled([writeChain, downstream]);
646
741
  }
647
742
  }
@@ -0,0 +1 @@
1
+ export declare function resolveProxyTarget(upstream: URL, path: string): URL | undefined;
@@ -0,0 +1,13 @@
1
+ export function resolveProxyTarget(upstream, path) {
2
+ if (!path.startsWith("/") || path.startsWith("//") || path.includes("://") || path.includes("#") || /[\u0000-\u0020\u007f]/u.test(path) || path.trim() !== path)
3
+ return undefined;
4
+ try {
5
+ const target = new URL(path, upstream);
6
+ if (target.origin !== upstream.origin || target.username || target.password || target.pathname.startsWith("//"))
7
+ return undefined;
8
+ return target;
9
+ }
10
+ catch {
11
+ return undefined;
12
+ }
13
+ }
@@ -1,4 +1,4 @@
1
- import { rootCertificates } from "node:tls";
1
+ import { getCACertificates } from "node:tls";
2
2
  import { snapshotTransportSecurityPolicyV3, TransportFailureV3, } from "../v3/security.js";
3
3
  import { normalizeCertificateChain } from "./rawQuicTls.js";
4
4
  import { alpnForPathV3, FLOWERSEC_V3_PATHS } from "../v3/transportConstants.js";
@@ -39,7 +39,7 @@ export async function createNodeRawQuicClientV3(driver, candidate, artifact, att
39
39
  ? {
40
40
  ...common,
41
41
  tlsMode: "ca",
42
- trustRootsDer: options.roots === undefined ? rootCertificates.map((cert) => normalizeCertificateChain(cert)[0]) : normalizeCertificateChain(options.roots),
42
+ trustRootsDer: options.roots === undefined ? getCACertificates("default").map((cert) => normalizeCertificateChain(cert)[0]) : normalizeCertificateChain(options.roots),
43
43
  }
44
44
  : {
45
45
  ...common,
@@ -24,11 +24,13 @@ export type NodeRawQuicListenerV3 = Readonly<{
24
24
  export declare function startNodeRawQuicListenerV3(driver: NativeRawQuicDriver, options: NodeRawQuicListenerOptionsV3): Promise<NodeRawQuicListenerV3>;
25
25
  export type NodeWebTransportListenerConfig = Readonly<{
26
26
  carrier: "webtransport";
27
- profile: "draft02" | "native_h3";
28
27
  host: string;
29
28
  port: number;
30
29
  publicURL?: string;
31
30
  tls: NodeRawQuicListenerOptionsV3["tls"];
32
31
  allowedOrigins: readonly string[];
33
32
  }>;
33
+ export declare function validateWebTransportListeners(listeners: readonly {
34
+ carrier: string;
35
+ }[]): void;
34
36
  export declare function startNodeWebTransportListener(options: NodeWebTransportListenerConfig & NodeRawQuicListenerOptionsV3): Promise<NodeRawQuicListenerV3>;
@@ -23,17 +23,32 @@ export async function startNodeRawQuicListenerV3(driver, options) {
23
23
  }
24
24
  return Object.freeze({
25
25
  address: () => listener.address(),
26
- accept: async (operation = {}) => adaptNativeCarrierSessionV3(await listener.accept(operation)),
26
+ accept: async (operation = {}) => {
27
+ while (true) {
28
+ operation.signal?.throwIfAborted();
29
+ try {
30
+ return adaptNativeCarrierSessionV3(await listener.accept(operation));
31
+ }
32
+ catch (error) {
33
+ if (!(error instanceof Error) || !["handshake_failed", "handshake_timeout", "invalid_alpn"].includes(error.message))
34
+ throw error;
35
+ }
36
+ }
37
+ },
27
38
  close: async () => await listener.close(),
28
39
  });
29
40
  }
41
+ export function validateWebTransportListeners(listeners) {
42
+ if (listeners.some(listener => listener.carrier === "webtransport" && "profile" in listener))
43
+ throw new TypeError("WebTransport listener profile was removed; omit profile for draft02 or configure a raw_quic listener for Go clients");
44
+ }
30
45
  export async function startNodeWebTransportListener(options) {
31
46
  validateOptions(options);
32
- if ((options.profile !== "draft02" && options.profile !== "native_h3") || !Array.isArray(options.allowedOrigins) || options.allowedOrigins.length < 1 || options.allowedOrigins.length > 64 ||
47
+ if (!Array.isArray(options.allowedOrigins) || options.allowedOrigins.length < 1 || options.allowedOrigins.length > 64 ||
33
48
  new Set(options.allowedOrigins).size !== options.allowedOrigins.length || !options.allowedOrigins.every(validOrigin))
34
49
  throw new TypeError("invalid WebTransport Origin policy");
35
50
  const url = new URL(boundIngressURL(options.path, "webtransport", { host: options.host, port: options.port || 443 }, options.publicURL));
36
- const driver = createNativeWebTransportDriver(loadNativeTransportAddon(), options.profile);
51
+ const driver = createNativeWebTransportDriver(loadNativeTransportAddon());
37
52
  if (driver === undefined)
38
53
  throw new NativeTransportUnavailableError();
39
54
  const listener = await driver.bind({ host: options.host, port: options.port, path: options.path, authorityHost: url.hostname,