@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.
Files changed (59) hide show
  1. package/README.md +2 -1
  2. package/THIRD_PARTY_NOTICES.md +5 -5
  3. package/dist/node/acceptorV3.js +7 -3
  4. package/dist/node/connectionPath.js +49 -37
  5. package/dist/node/listenerIngress.d.ts +7 -0
  6. package/dist/node/listenerIngress.js +21 -0
  7. package/dist/node/proxyServer.d.ts +1 -0
  8. package/dist/node/proxyServer.js +173 -78
  9. package/dist/node/proxyTarget.d.ts +1 -0
  10. package/dist/node/proxyTarget.js +13 -0
  11. package/dist/node/rawQuicAdapterV3.js +2 -2
  12. package/dist/node/rawQuicServerV3.js +12 -1
  13. package/dist/node/tunnelRuntimeV3.js +40 -7
  14. package/dist/node/webSocketServerV3.js +24 -2
  15. package/dist/proxy/bodyIntake.d.ts +13 -0
  16. package/dist/proxy/bodyIntake.js +55 -0
  17. package/dist/proxy/controllerGuard.d.ts +4 -0
  18. package/dist/proxy/controllerGuard.js +79 -37
  19. package/dist/proxy/fetch.d.ts +2 -1
  20. package/dist/proxy/fetch.js +55 -27
  21. package/dist/proxy/integration.d.ts +1 -1
  22. package/dist/proxy/integration.js +25 -5
  23. package/dist/proxy/registerServiceWorker.d.ts +5 -0
  24. package/dist/proxy/registerServiceWorker.js +30 -21
  25. package/dist/proxy/runtime.d.ts +7 -1
  26. package/dist/proxy/runtime.js +129 -39
  27. package/dist/proxy/scope.js +1 -1
  28. package/dist/proxy/serviceWorker.js +286 -43
  29. package/dist/proxy/serviceWorkerRuntime.d.ts +5 -2
  30. package/dist/proxy/serviceWorkerRuntime.js +58 -3
  31. package/dist/proxy/stream.d.ts +1 -0
  32. package/dist/proxy/stream.js +6 -3
  33. package/dist/proxy/types.d.ts +1 -1
  34. package/dist/proxy/windowBridge.d.ts +3 -1
  35. package/dist/proxy/windowBridge.js +64 -19
  36. package/dist/proxy/wsPatch.js +70 -52
  37. package/dist/public/sessionHandlers.js +3 -2
  38. package/dist/utils/abort.d.ts +1 -0
  39. package/dist/utils/abort.js +13 -0
  40. package/dist/v3/artifactLease.d.ts +6 -0
  41. package/dist/v3/artifactLease.js +6 -0
  42. package/dist/v3/contract.d.ts +1 -0
  43. package/dist/v3/nodeRuntime.js +10 -25
  44. package/dist/v3/publicSession.d.ts +2 -1
  45. package/dist/v3/publicSession.js +11 -15
  46. package/dist/v3/session.d.ts +7 -1
  47. package/dist/v3/session.js +110 -25
  48. package/dist/v3/unreliableMessage.d.ts +1 -0
  49. package/dist/v3/unreliableMessage.js +5 -1
  50. package/dist/v3/webSocketCarrier.js +24 -11
  51. package/dist/v3/webTransportCarrier.js +6 -0
  52. package/dist/ws-client/binaryTransport.d.ts +2 -0
  53. package/dist/ws-client/binaryTransport.js +8 -2
  54. package/dist/yamux/byteReader.js +1 -0
  55. package/dist/yamux/session.d.ts +2 -0
  56. package/dist/yamux/session.js +4 -1
  57. package/package.json +3 -3
  58. package/sbom/cyclonedx.json +31 -31
  59. package/sbom/spdx.json +38 -38
@@ -1,4 +1,7 @@
1
1
  import { prepareProxyFetch } from "./fetch.js";
2
+ import { raceWithSignal } from "../utils/abort.js";
3
+ import { BodyIntake } from "./bodyIntake.js";
4
+ import { matchesServiceWorkerRegistration } from "./registerServiceWorker.js";
2
5
  import { SDK_DEFAULTS } from "../defaults.js";
3
6
  import { readJsonFrame, writeJsonFrame } from "../framing/jsonframe.js";
4
7
  import { base64urlEncode } from "../utils/base64url.js";
@@ -7,7 +10,7 @@ import { SessionError } from "../public/contract.js";
7
10
  import { createStreamMetadata } from "../public/streamMetadata.js";
8
11
  import { InvalidProxyPathError, normalizePath, normalizePrefixes, normalizeHeaderNames, FORBIDDEN_HEADERS } from "./policy.js";
9
12
  import { ProxyByteReader, writeAll } from "./stream.js";
10
- import { registerProxyRuntimeServiceWorkerBridge, usesServiceWorkerResponseFlowControl, } from "./serviceWorkerRuntime.js";
13
+ import { registerWithController, registerProxyRuntimeServiceWorkerBridge, usesServiceWorkerResponseFlowControl, } from "./serviceWorkerRuntime.js";
11
14
  const PROXY_HTTP_STREAM_KIND = "flowersec-proxy/http1";
12
15
  const PROXY_WEBSOCKET_STREAM_KIND = "flowersec-proxy/ws";
13
16
  const PROXY_WIRE_VERSION = 1;
@@ -104,7 +107,7 @@ function normalizeToken(input) {
104
107
  return input;
105
108
  }
106
109
  const BASE_REQUEST_HEADERS = new Set(["accept", "accept-language", "content-type", "if-match", "if-none-match", "range"]);
107
- const BASE_RESPONSE_HEADERS = new Set(["accept-ranges", "cache-control", "content-disposition", "content-language", "content-range", "content-type", "etag", "expires", "last-modified", "location"]);
110
+ const BASE_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"]);
108
111
  function filterHeaders(input, base, extra) {
109
112
  const result = [];
110
113
  for (const entry of input) {
@@ -237,6 +240,29 @@ function publicFailure(error) {
237
240
  return { status: 502, code: "operation_failed", message: "proxy request failed" };
238
241
  }
239
242
  export function createProxyRuntime(options) {
243
+ return createScopedProxyRuntime(options);
244
+ }
245
+ export function createScopedProxyRuntime(options, authority) {
246
+ if (authority) {
247
+ const grantedHeaders = authority.http?.extraRequestHeaders ?? [];
248
+ const limits = Object.fromEntries(Object.entries(authority.limits ?? {}).map(([key, ceiling]) => {
249
+ const configured = options[key];
250
+ return [key, typeof configured === "number" && configured > 0 ? Math.min(configured, ceiling) : ceiling];
251
+ }));
252
+ options = { ...options, ...limits, extraRequestHeaders: options.extraRequestHeaders === undefined ? grantedHeaders :
253
+ [...normalizeHeaderNames(options.extraRequestHeaders)].filter(name => grantedHeaders.includes(name)) };
254
+ }
255
+ const checkAuthority = (kind, path) => {
256
+ const base = authority?.appBasePath;
257
+ if (!base)
258
+ return;
259
+ const candidate = pathName(path);
260
+ if (candidate === base || candidate.startsWith(base.endsWith("/") ? base : `${base}/`))
261
+ return;
262
+ if (kind === "http" && authority?.http?.additionalPathPrefixes?.some(prefix => candidate.startsWith(prefix)))
263
+ return;
264
+ throw new ProxyPolicyError("proxy path outside acquisition scope");
265
+ };
240
266
  if (options.session === null || typeof options.session !== "object" || typeof options.session.openStream !== "function") {
241
267
  throw new TypeError("proxy runtime requires a Session");
242
268
  }
@@ -260,6 +286,7 @@ export function createProxyRuntime(options) {
260
286
  const responseExtra = normalizeHeaderNames(options.extraResponseHeaders);
261
287
  const webSocketExtra = normalizeHeaderNames(options.extraWebSocketHeaders);
262
288
  const admission = new StreamAdmission(maxConcurrentHttpStreams, maxQueuedHttpRequests, maxQueuedHttpBodyBytes);
289
+ const intake = new BodyIntake(maxConcurrentHttpStreams, Math.max(maxBodyBytes, maxQueuedHttpBodyBytes));
263
290
  let disposed = false;
264
291
  let activeEvents = 0;
265
292
  const active = new Set();
@@ -269,8 +296,6 @@ export function createProxyRuntime(options) {
269
296
  ...(runtimeRegistrationToken === undefined ? {} : { runtimeRegistrationToken }),
270
297
  }).catch(() => undefined);
271
298
  const serviceWorker = globalThis.navigator?.serviceWorker;
272
- serviceWorker?.addEventListener("controllerchange", register);
273
- register();
274
299
  let serviceWorkerBridge;
275
300
  const terminate = () => {
276
301
  admission.close();
@@ -278,15 +303,15 @@ export function createProxyRuntime(options) {
278
303
  controller.abort(new SessionError("closed"));
279
304
  lifetime.abort(new SessionError("closed"));
280
305
  };
281
- void options.session.waitTermination({ signal: lifetime.signal }).then(terminate, () => { if (!disposed)
282
- terminate(); });
283
306
  // One transaction owns admission, framing, cancellation and response backpressure
284
307
  // for direct fetch and both browser bridges. It never reconnects a request.
285
- async function execute(request, signal, sessionBound = false) {
308
+ const requestDuration = timeoutMs || SDK_DEFAULTS.proxy.defaultTimeoutMs;
309
+ async function execute(request, signal, sessionBound = false, deadline = performance.now() + requestDuration) {
286
310
  if (disposed)
287
311
  throw new SessionError("closed");
288
312
  const path = normalizePath(request.path);
289
313
  enforcePathPolicy("http", path, pathPolicy);
314
+ checkAuthority("http", path);
290
315
  const headers = filterHeaders(request.headers, BASE_REQUEST_HEADERS, requestExtra);
291
316
  const eventRequested = headers.some(({ name, value }) => name === "accept" && acceptsEventStream(value));
292
317
  if (eventRequested && activeEvents >= maxConcurrentEventStreams)
@@ -342,9 +367,12 @@ export function createProxyRuntime(options) {
342
367
  if (body.length > maxBodyBytes)
343
368
  throw new SessionError("resource_exhausted");
344
369
  // Persistent requests never queue behind an occupied finite-request slot.
370
+ const remaining = deadline - performance.now();
371
+ if (!sessionBound && remaining <= 0)
372
+ throw new SessionError("timeout");
373
+ arm(remaining);
345
374
  release = await admission.acquire(body.length, controller.signal, eventRequested);
346
375
  controller.signal.throwIfAborted();
347
- arm(timeoutMs || SDK_DEFAULTS.proxy.defaultTimeoutMs);
348
376
  stream = await options.session.openStream(PROXY_HTTP_STREAM_KIND, {
349
377
  signal: controller.signal,
350
378
  metadata: createStreamMetadata({ protocol: "flowersec.proxy.http", version: 2 }),
@@ -357,14 +385,18 @@ export function createProxyRuntime(options) {
357
385
  v: PROXY_WIRE_VERSION, request_id: requestID, method: request.method.toUpperCase(), path, headers,
358
386
  ...(requestOrigin === undefined ? {} : { external_origin: requestOrigin }),
359
387
  ...(timeoutMs === 0 ? {} : { timeout_ms: timeoutMs }),
360
- });
361
- await writeChunks(stream, body, maxChunkBytes, maxBodyBytes, controller.signal);
362
- const response = await readJsonFrame(reader, maxJsonFrameBytes);
363
- if (response.v !== PROXY_WIRE_VERSION || response.request_id !== requestID)
364
- throw new Error("invalid proxy response");
365
- if (response.ok !== true) {
366
- throw new SessionError(response.error?.code === "resource_exhausted" ? "resource_exhausted" : "operation_failed");
367
- }
388
+ }, maxJsonFrameBytes);
389
+ const [response] = await Promise.all([
390
+ readJsonFrame(reader, maxJsonFrameBytes).then((value) => {
391
+ const meta = value;
392
+ if (meta.v !== PROXY_WIRE_VERSION || meta.request_id !== requestID)
393
+ throw new Error("invalid proxy response");
394
+ if (meta.ok !== true)
395
+ throw new SessionError(meta.error?.code === "resource_exhausted" ? "resource_exhausted" : "operation_failed");
396
+ return meta;
397
+ }),
398
+ writeChunks(stream, body, maxChunkBytes, maxBodyBytes, controller.signal),
399
+ ]);
368
400
  if (!Number.isInteger(response.status))
369
401
  throw new Error("invalid proxy response");
370
402
  const headersOut = filterHeaders(response.headers ?? [], BASE_RESPONSE_HEADERS, responseExtra);
@@ -375,6 +407,13 @@ export function createProxyRuntime(options) {
375
407
  releaseEvent();
376
408
  const chunks = readChunks(reader, maxChunkBytes, persistent ? Infinity : maxBodyBytes)[Symbol.asyncIterator]();
377
409
  controller.signal.throwIfAborted();
410
+ const finishResponse = async () => {
411
+ await stream.closeWrite();
412
+ if (await reader.remainingStream().read({ signal: controller.signal }) !== null)
413
+ throw new Error("unexpected data after response terminator");
414
+ controller.signal.throwIfAborted();
415
+ finish();
416
+ };
378
417
  const bodyStream = new ReadableStream({
379
418
  start(value) { output = value; },
380
419
  async pull(value) {
@@ -384,7 +423,7 @@ export function createProxyRuntime(options) {
384
423
  if (finished)
385
424
  return;
386
425
  if (next.done)
387
- finish();
426
+ await finishResponse();
388
427
  else {
389
428
  if (persistent)
390
429
  arm(eventStreamIdleTimeoutMs);
@@ -402,7 +441,7 @@ export function createProxyRuntime(options) {
402
441
  const next = await chunks.next();
403
442
  if (!next.done)
404
443
  throw new Error("unexpected proxy response body");
405
- finish();
444
+ await finishResponse();
406
445
  }
407
446
  return new Response(noBody ? null : bodyStream, {
408
447
  status: response.status, headers: headersOut.map(({ name, value }) => [name, value]),
@@ -423,15 +462,24 @@ export function createProxyRuntime(options) {
423
462
  if (disposed)
424
463
  throw new SessionError("closed");
425
464
  const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);
426
- const prepared = await prepareProxyFetch(input, { ...init,
427
- signal: AbortSignal.any([lifetime.signal, ...(signal ? [signal] : [])]),
428
- }, externalOrigin, maxBodyBytes);
429
465
  if (init?.sessionBound !== undefined && typeof init.sessionBound !== "boolean")
430
466
  throw new TypeError("sessionBound must be a boolean");
431
- return execute(prepared.request, prepared.signal, init?.sessionBound === true);
467
+ const sessionBound = init?.sessionBound === true;
468
+ const deadline = performance.now() + requestDuration;
469
+ const preparation = new AbortController();
470
+ const owner = AbortSignal.any([preparation.signal, lifetime.signal, ...(signal ? [signal] : [])]);
471
+ const timer = sessionBound ? undefined : setTimeout(() => preparation.abort(new SessionError("timeout")), requestDuration);
472
+ try {
473
+ const prepared = await raceWithSignal(prepareProxyFetch(input, { ...init, signal: owner }, externalOrigin, maxBodyBytes, intake), owner);
474
+ return execute(prepared.request, prepared.signal, sessionBound, deadline);
475
+ }
476
+ finally {
477
+ clearTimeout(timer);
478
+ }
432
479
  }
433
- function dispatchFetch(request, port) {
480
+ function dispatchFetch(request, port, owner) {
434
481
  const controller = new AbortController();
482
+ const signal = owner ? AbortSignal.any([controller.signal, owner]) : controller.signal;
435
483
  const flowControlled = usesServiceWorkerResponseFlowControl(request) || request.headers.some(({ name, value }) => name.toLowerCase() === "accept" && acceptsEventStream(value));
436
484
  let credit = !flowControlled;
437
485
  let creditWake;
@@ -445,7 +493,7 @@ export function createProxyRuntime(options) {
445
493
  void (async () => {
446
494
  let reader;
447
495
  try {
448
- const response = await execute(request, controller.signal);
496
+ const response = await execute(request, signal);
449
497
  port.postMessage({ type: "flowersec-proxy:response_meta", status: response.status,
450
498
  headers: Array.from(response.headers, ([name, value]) => ({ name, value })) });
451
499
  reader = response.body?.getReader();
@@ -453,10 +501,10 @@ export function createProxyRuntime(options) {
453
501
  const wake = () => { controller.abort(new SessionError("canceled")); creditWake?.(); };
454
502
  const read = async () => {
455
503
  while (!credit) {
456
- controller.signal.throwIfAborted();
504
+ signal.throwIfAborted();
457
505
  await new Promise((resolve) => { creditWake = resolve; });
458
506
  }
459
- controller.signal.throwIfAborted();
507
+ signal.throwIfAborted();
460
508
  credit = !flowControlled;
461
509
  return reader.read();
462
510
  };
@@ -486,28 +534,52 @@ export function createProxyRuntime(options) {
486
534
  throw new SessionError("closed");
487
535
  const path = normalizePath(input);
488
536
  enforcePathPolicy("websocket", path, pathPolicy);
489
- const stream = await options.session.openStream(PROXY_WEBSOCKET_STREAM_KIND, {
490
- ...(openOptions.signal === undefined ? {} : { signal: openOptions.signal }),
491
- metadata: createStreamMetadata({ protocol: "flowersec.proxy.websocket", version: 2 }),
492
- });
493
- try {
537
+ checkAuthority("websocket", path);
538
+ const signal = openOptions.signal ? AbortSignal.any([lifetime.signal, openOptions.signal]) : lifetime.signal;
539
+ const abortError = () => lifetime.signal.aborted ? new SessionError("closed") : new SessionError("canceled");
540
+ if (signal.aborted)
541
+ throw abortError();
542
+ let pendingStream;
543
+ const resetPending = () => {
544
+ const stream = pendingStream;
545
+ pendingStream = undefined;
546
+ void stream?.reset().catch(() => undefined);
547
+ };
548
+ const establish = async () => {
549
+ const stream = await options.session.openStream(PROXY_WEBSOCKET_STREAM_KIND, {
550
+ signal,
551
+ metadata: createStreamMetadata({ protocol: "flowersec.proxy.websocket", version: 2 }),
552
+ });
553
+ pendingStream = stream;
554
+ if (signal.aborted) {
555
+ resetPending();
556
+ throw abortError();
557
+ }
494
558
  const protocols = (openOptions.protocols ?? []).filter((value) => value.trim() !== "" && value === value.trim());
495
559
  const headers = filterHeaders(protocols.length === 0 ? [] : [{ name: "sec-websocket-protocol", value: protocols.join(", ") }], new Set(["sec-websocket-protocol"]), webSocketExtra);
496
- await writeJsonFrame({ write: async (data) => await writeAll(stream, data, openOptions.signal === undefined ? {} : { signal: openOptions.signal }) }, {
560
+ await writeJsonFrame({ write: async (data) => await writeAll(stream, data, { signal }) }, {
497
561
  v: PROXY_WIRE_VERSION,
498
562
  conn_id: randomID(),
499
563
  path,
500
564
  headers,
501
- });
502
- const reader = new ProxyByteReader(stream, openOptions.signal === undefined ? {} : { signal: openOptions.signal });
565
+ }, maxJsonFrameBytes);
566
+ const reader = new ProxyByteReader(stream, { signal });
503
567
  const response = await readJsonFrame(reader, maxJsonFrameBytes);
504
568
  if (response.v !== PROXY_WIRE_VERSION || response.ok !== true || (response.protocol !== undefined && typeof response.protocol !== "string")) {
505
569
  throw new Error("proxy WebSocket open failed");
506
570
  }
507
571
  return Object.freeze({ stream: reader.remainingStream(), protocol: response.protocol ?? "" });
572
+ };
573
+ try {
574
+ const opened = await raceWithSignal(establish(), signal);
575
+ if (signal.aborted)
576
+ throw abortError();
577
+ return opened;
508
578
  }
509
579
  catch (error) {
510
- await stream.reset().catch(() => undefined);
580
+ resetPending();
581
+ if (signal.aborted)
582
+ throw abortError();
511
583
  throw error instanceof SessionError ? error : new SessionError("operation_failed");
512
584
  }
513
585
  }
@@ -538,19 +610,35 @@ export function createProxyRuntime(options) {
538
610
  serviceWorkerBridge?.dispose();
539
611
  },
540
612
  });
541
- if (serviceWorker !== undefined) {
542
- serviceWorkerBridge = registerProxyRuntimeServiceWorkerBridge(runtime, serviceWorker);
613
+ if (serviceWorker !== undefined && authority?.mode !== "controller_bridge") {
614
+ serviceWorkerBridge = registerProxyRuntimeServiceWorkerBridge(runtime, serviceWorker, authority?.serviceWorker);
615
+ serviceWorker.addEventListener("controllerchange", register);
616
+ register();
543
617
  }
618
+ void options.session.waitTermination({ signal: lifetime.signal }).then(terminate, () => { if (!disposed)
619
+ terminate(); });
544
620
  return runtime;
545
621
  }
546
622
  export async function ensureServiceWorkerRuntimeRegistered(options = {}) {
547
- const controller = globalThis.navigator?.serviceWorker?.controller;
548
- if (controller === null || controller === undefined || typeof controller.postMessage !== "function")
623
+ return registerRuntimeInContainer(globalThis.navigator?.serviceWorker, options);
624
+ }
625
+ export async function registerRuntimeInContainer(container, options, expected) {
626
+ const controller = container?.controller;
627
+ if (expected) {
628
+ const registration = await container?.getRegistration(expected.href);
629
+ if (!controller || container?.controller !== controller || !matchesServiceWorkerRegistration(registration, controller, expected, expected.href)) {
630
+ throw new Error("service worker controller mismatch");
631
+ }
632
+ }
633
+ if (!container || !controller || typeof controller.postMessage !== "function")
549
634
  return;
550
635
  const timeoutMs = options.timeoutMs ?? 2_000;
551
636
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > 60_000)
552
637
  throw new TypeError("invalid runtime registration timeout");
553
638
  const token = normalizeToken(options.runtimeRegistrationToken);
639
+ await registerWithController(container, controller, token, acknowledge => sendRuntimeRegistration(controller, token, timeoutMs, acknowledge));
640
+ }
641
+ async function sendRuntimeRegistration(controller, token, timeoutMs, acknowledge) {
554
642
  const channel = new MessageChannel();
555
643
  await new Promise((resolve, reject) => {
556
644
  let settled = false;
@@ -566,6 +654,8 @@ export async function ensureServiceWorkerRuntimeRegistered(options = {}) {
566
654
  channel.port1.onmessage = (event) => {
567
655
  if (event.data?.type !== "flowersec-proxy:register-runtime-ack")
568
656
  return;
657
+ if (event.data.ok === true)
658
+ acknowledge();
569
659
  finish(event.data.ok === true ? undefined : new Error("service worker runtime registration rejected"));
570
660
  };
571
661
  channel.port1.onmessageerror = () => finish(new Error("service worker runtime registration failed"));
@@ -58,7 +58,7 @@ function optionalAppBasePath(value) {
58
58
  const path = nonEmpty("appBasePath", value);
59
59
  if (!path.startsWith("/") || path.startsWith("//") || /[\u0000-\u0020]/u.test(path))
60
60
  reject("appBasePath");
61
- return path;
61
+ return normalizePrefixes("appBasePath", [path])[0];
62
62
  }
63
63
  function httpStrings(name, value) {
64
64
  if (value === undefined)