@floegence/flowersec-core 7.1.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.
- package/README.md +2 -1
- package/THIRD_PARTY_NOTICES.md +5 -5
- package/dist/node/acceptorV3.js +7 -3
- package/dist/node/connectionPath.js +49 -37
- package/dist/node/listenerIngress.d.ts +7 -0
- package/dist/node/listenerIngress.js +21 -0
- package/dist/node/proxyServer.d.ts +1 -0
- package/dist/node/proxyServer.js +173 -78
- package/dist/node/proxyTarget.d.ts +1 -0
- package/dist/node/proxyTarget.js +13 -0
- package/dist/node/rawQuicAdapterV3.js +2 -2
- package/dist/node/rawQuicServerV3.js +12 -1
- package/dist/node/tunnelRuntimeV3.js +40 -7
- package/dist/node/webSocketServerV3.js +24 -2
- package/dist/proxy/bodyIntake.d.ts +13 -0
- package/dist/proxy/bodyIntake.js +55 -0
- package/dist/proxy/controllerGuard.d.ts +4 -0
- package/dist/proxy/controllerGuard.js +79 -37
- package/dist/proxy/fetch.d.ts +2 -1
- package/dist/proxy/fetch.js +55 -27
- package/dist/proxy/integration.d.ts +1 -1
- package/dist/proxy/integration.js +25 -5
- package/dist/proxy/registerServiceWorker.d.ts +5 -0
- package/dist/proxy/registerServiceWorker.js +30 -21
- package/dist/proxy/runtime.d.ts +7 -1
- package/dist/proxy/runtime.js +129 -39
- package/dist/proxy/scope.js +1 -1
- package/dist/proxy/serviceWorker.js +286 -43
- package/dist/proxy/serviceWorkerRuntime.d.ts +5 -2
- package/dist/proxy/serviceWorkerRuntime.js +58 -3
- package/dist/proxy/stream.d.ts +1 -0
- package/dist/proxy/stream.js +6 -3
- package/dist/proxy/types.d.ts +1 -1
- package/dist/proxy/windowBridge.d.ts +3 -1
- package/dist/proxy/windowBridge.js +64 -19
- package/dist/proxy/wsPatch.js +70 -52
- package/dist/public/sessionHandlers.js +3 -2
- package/dist/utils/abort.d.ts +1 -0
- package/dist/utils/abort.js +13 -0
- package/dist/v3/artifactLease.d.ts +6 -0
- package/dist/v3/artifactLease.js +6 -0
- package/dist/v3/contract.d.ts +1 -0
- package/dist/v3/nodeRuntime.js +10 -25
- package/dist/v3/publicSession.d.ts +2 -1
- package/dist/v3/publicSession.js +11 -15
- package/dist/v3/session.d.ts +7 -1
- package/dist/v3/session.js +110 -25
- package/dist/v3/unreliableMessage.d.ts +1 -0
- package/dist/v3/unreliableMessage.js +5 -1
- package/dist/v3/webSocketCarrier.js +24 -11
- package/dist/v3/webTransportCarrier.js +6 -0
- package/dist/ws-client/binaryTransport.d.ts +2 -0
- package/dist/ws-client/binaryTransport.js +8 -2
- package/dist/yamux/byteReader.js +1 -0
- package/dist/yamux/session.d.ts +2 -0
- package/dist/yamux/session.js +4 -1
- package/package.json +3 -3
- package/sbom/cyclonedx.json +31 -31
- package/sbom/spdx.json +38 -38
package/dist/node/proxyServer.js
CHANGED
|
@@ -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) {
|
|
157
|
-
|
|
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
|
|
165
|
-
const 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
|
|
191
|
-
if (meta.v !== WIRE_VERSION || requestID === "" || meta.method.trim() === "" ||
|
|
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 =
|
|
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 =
|
|
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
|
-
|
|
254
|
+
headers["x-forwarded-proto"] = origin.protocol.slice(0, -1);
|
|
246
255
|
}
|
|
247
|
-
const
|
|
248
|
-
|
|
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,
|
|
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
|
-
|
|
390
|
+
if (!signal.aborted)
|
|
391
|
+
await writeWSError(stream, "unknown", "invalid_ws_open_meta", signal);
|
|
325
392
|
return;
|
|
326
393
|
}
|
|
327
|
-
const
|
|
328
|
-
if (open.v !== WIRE_VERSION || open.conn_id.trim() === "" ||
|
|
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
|
-
|
|
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 =
|
|
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,
|
|
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
|
-
|
|
436
|
+
if (signal.aborted || !opened)
|
|
437
|
+
socket.terminate();
|
|
438
|
+
else
|
|
362
439
|
socket.close();
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
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
|
|
384
|
-
|
|
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
|
|
438
|
-
const headers = filterHeaders(input,
|
|
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
|
-
|
|
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
|
-
|
|
508
|
-
|
|
509
|
-
return
|
|
510
|
-
|
|
511
|
-
|
|
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
|
|
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
|
-
|
|
635
|
-
|
|
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 {
|
|
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 ?
|
|
42
|
+
trustRootsDer: options.roots === undefined ? getCACertificates("default").map((cert) => normalizeCertificateChain(cert)[0]) : normalizeCertificateChain(options.roots),
|
|
43
43
|
}
|
|
44
44
|
: {
|
|
45
45
|
...common,
|
|
@@ -23,7 +23,18 @@ export async function startNodeRawQuicListenerV3(driver, options) {
|
|
|
23
23
|
}
|
|
24
24
|
return Object.freeze({
|
|
25
25
|
address: () => listener.address(),
|
|
26
|
-
accept: async (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
|
}
|
|
@@ -2,7 +2,8 @@ import { createAdmissionReasonRegistryV3, receiveSessionAdmissionV3, rejectSessi
|
|
|
2
2
|
import { configureServerWebSocketCarrierRoleV3 } from "../v3/webSocketCarrier.js";
|
|
3
3
|
import { AdmissionStatusV3, encodeFSA3ResponseV3, } from "../v3/artifact.js";
|
|
4
4
|
import { CarrierError, } from "../v3/carrier.js";
|
|
5
|
-
import {
|
|
5
|
+
import { X509Certificate } from "node:crypto";
|
|
6
|
+
import { boundIngressURL, matchesIngress } from "./listenerIngress.js";
|
|
6
7
|
import { startNodeWebSocketListenerV3 } from "./webSocketServerV3.js";
|
|
7
8
|
import { createNativeRawQuicDriver } from "./nativeTransportAddon.js";
|
|
8
9
|
import { startNodeRawQuicListenerV3, startNodeWebTransportListener, validateWebTransportListeners } from "./rawQuicServerV3.js";
|
|
@@ -49,6 +50,8 @@ export class TunnelRuntimeV3 {
|
|
|
49
50
|
await Promise.allSettled([starting]);
|
|
50
51
|
await Promise.allSettled(state.listeners.map(async (listener) => await listener.close()));
|
|
51
52
|
await drainTasks(state.tasks);
|
|
53
|
+
state.usedCredentials.clear();
|
|
54
|
+
state.expirations.length = 0;
|
|
52
55
|
})();
|
|
53
56
|
closes.set(state, closing);
|
|
54
57
|
return await closing;
|
|
@@ -73,7 +76,8 @@ export function createTunnelRuntimeV3(options) {
|
|
|
73
76
|
limits,
|
|
74
77
|
abort: new AbortController(),
|
|
75
78
|
generations: new Map(),
|
|
76
|
-
usedCredentials: new
|
|
79
|
+
usedCredentials: new Set(),
|
|
80
|
+
expirations: [],
|
|
77
81
|
legGenerations: new WeakMap(),
|
|
78
82
|
admissionSlots: new AdmissionSlots(limits.maxConcurrentAdmissions),
|
|
79
83
|
authorizerSlots: new Slots(limits.maxConcurrentAdmissions),
|
|
@@ -94,6 +98,7 @@ async function startTunnelRuntimeV3(state) {
|
|
|
94
98
|
let rawQuicDriver;
|
|
95
99
|
try {
|
|
96
100
|
for (const listener of state.options.listeners) {
|
|
101
|
+
const leaf = new X509Certificate(listener.tls.certificate);
|
|
97
102
|
if (state.abort.signal.aborted)
|
|
98
103
|
throw new Error("Flowersec tunnel runtime is closed");
|
|
99
104
|
const running = listener.carrier === "websocket"
|
|
@@ -117,6 +122,7 @@ async function startTunnelRuntimeV3(state) {
|
|
|
117
122
|
}
|
|
118
123
|
state.listeners.push(running);
|
|
119
124
|
state.ingress.set(running, {
|
|
125
|
+
leaf,
|
|
120
126
|
url: boundIngressURL("tunnel", listener.carrier, running.address(), listener.publicURL),
|
|
121
127
|
});
|
|
122
128
|
}
|
|
@@ -161,7 +167,7 @@ async function processCarrier(state, carrier, ingress) {
|
|
|
161
167
|
const authorizationRequest = runtimeAuthorizationRequestV3FromDecoded(decoded);
|
|
162
168
|
const selected = decoded.request.candidates.find(candidate => candidate.id === decoded.request.chosen_candidate_id);
|
|
163
169
|
if (carrier.path !== "tunnel" || decoded.request.pathKind !== "tunnel" ||
|
|
164
|
-
selected?.carrier !== carrier.kind || selected
|
|
170
|
+
selected?.carrier !== carrier.kind || !matchesIngress(selected, ingress)) {
|
|
165
171
|
await reject(received, "invalid_credential", false, state.admissionReasons, admission.signal);
|
|
166
172
|
return;
|
|
167
173
|
}
|
|
@@ -256,7 +262,7 @@ function registerLeg(state, leg) {
|
|
|
256
262
|
track(state, reject(leg.received, "credential_replay", false, state.admissionReasons, state.abort.signal));
|
|
257
263
|
return;
|
|
258
264
|
}
|
|
259
|
-
state
|
|
265
|
+
rememberCredential(state, leg.authorization.credentialId, leg.authorization.expiresAtUnixSeconds);
|
|
260
266
|
const key = pairKey(leg.request, leg.authorization.authorityScope);
|
|
261
267
|
let generation = state.generations.get(key);
|
|
262
268
|
if (generation !== undefined && !generation.finished &&
|
|
@@ -663,11 +669,38 @@ function validateOptions(options) {
|
|
|
663
669
|
function boundedInteger(value, minimum, maximum) {
|
|
664
670
|
return Number.isSafeInteger(value) && value >= minimum && value <= maximum;
|
|
665
671
|
}
|
|
672
|
+
function rememberCredential(state, credential, expiry) {
|
|
673
|
+
state.usedCredentials.add(credential);
|
|
674
|
+
const heap = state.expirations;
|
|
675
|
+
let index = heap.length;
|
|
676
|
+
while (index > 0) {
|
|
677
|
+
const parent = Math.floor((index - 1) / 2);
|
|
678
|
+
if (heap[parent].expiry <= expiry)
|
|
679
|
+
break;
|
|
680
|
+
heap[index] = heap[parent];
|
|
681
|
+
index = parent;
|
|
682
|
+
}
|
|
683
|
+
heap[index] = { credential, expiry };
|
|
684
|
+
}
|
|
666
685
|
function pruneCredentials(state) {
|
|
667
686
|
const now = Math.floor(Date.now() / 1_000);
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
687
|
+
const heap = state.expirations;
|
|
688
|
+
while (heap.length && heap[0].expiry <= now) {
|
|
689
|
+
state.usedCredentials.delete(heap[0].credential);
|
|
690
|
+
const last = heap.pop();
|
|
691
|
+
if (!heap.length)
|
|
692
|
+
break;
|
|
693
|
+
let index = 0;
|
|
694
|
+
while (2 * index + 1 < heap.length) {
|
|
695
|
+
let child = 2 * index + 1;
|
|
696
|
+
if (child + 1 < heap.length && heap[child + 1].expiry < heap[child].expiry)
|
|
697
|
+
child++;
|
|
698
|
+
if (last.expiry <= heap[child].expiry)
|
|
699
|
+
break;
|
|
700
|
+
heap[index] = heap[child];
|
|
701
|
+
index = child;
|
|
702
|
+
}
|
|
703
|
+
heap[index] = last;
|
|
671
704
|
}
|
|
672
705
|
}
|
|
673
706
|
function releaseDecision(state, decision) {
|