@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,10 +2,11 @@ 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 { boundIngressURL } from "./listenerIngress.js";
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
- import { startNodeRawQuicListenerV3, startNodeWebTransportListener } from "./rawQuicServerV3.js";
9
+ import { startNodeRawQuicListenerV3, startNodeWebTransportListener, validateWebTransportListeners } from "./rawQuicServerV3.js";
9
10
  import { consumeTunnelAuthorizationGrantV3, inspectTunnelAuthorizationGrantV3, retireTunnelAuthorizationGrantV3, runtimeAuthorizationRequestV3FromDecoded, validateTunnelAuthorizationGrantV3, } from "./runtimeAuthorizationV3.js";
10
11
  const DEFAULT_PAIR_TIMEOUT_MS = 10_000;
11
12
  const DEFAULT_ADMISSION_TIMEOUT_MS = 10_000;
@@ -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 Map(),
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.normalized_url !== ingress.url) {
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.usedCredentials.set(leg.authorization.credentialId, leg.authorization.expiresAtUnixSeconds);
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 &&
@@ -636,6 +642,7 @@ async function reject(received, reason, retryable, admissionReasons, signal) {
636
642
  }
637
643
  }
638
644
  function validateOptions(options) {
645
+ validateWebTransportListeners(options.listeners);
639
646
  const limits = {
640
647
  maxPendingLegs: options.maxPendingLegs ?? DEFAULT_MAX_PENDING_LEGS,
641
648
  maxActivePairs: options.maxActivePairs ?? DEFAULT_MAX_ACTIVE_PAIRS,
@@ -662,11 +669,38 @@ function validateOptions(options) {
662
669
  function boundedInteger(value, minimum, maximum) {
663
670
  return Number.isSafeInteger(value) && value >= minimum && value <= maximum;
664
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
+ }
665
685
  function pruneCredentials(state) {
666
686
  const now = Math.floor(Date.now() / 1_000);
667
- for (const [credential, expiry] of state.usedCredentials) {
668
- if (expiry <= now)
669
- state.usedCredentials.delete(credential);
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;
670
704
  }
671
705
  }
672
706
  function releaseDecision(state, decision) {
@@ -21,10 +21,14 @@ export async function startNodeWebSocketListenerV3(options) {
21
21
  minVersion: "TLSv1.3",
22
22
  maxVersion: "TLSv1.3",
23
23
  secureOptions: constants.SSL_OP_NO_TICKET,
24
+ }, (_request, response) => {
25
+ response.writeHead(404, { Connection: "close", "Content-Length": "0" });
26
+ response.end();
24
27
  });
25
28
  const sessions = new SessionQueueV3(maxPendingSessions, pendingSessionTimeoutMs);
26
29
  const sockets = new Set();
27
30
  const networkSockets = new Set();
31
+ const pendingUpgrades = new Map();
28
32
  const wss = new WebSocketServer({
29
33
  noServer: true,
30
34
  perMessageDeflate: false,
@@ -32,8 +36,21 @@ export async function startNodeWebSocketListenerV3(options) {
32
36
  handleProtocols(protocols) { return protocols.size === 1 && protocols.has(protocol) ? protocol : false; },
33
37
  });
34
38
  server.on("connection", (socket) => {
39
+ if (pendingUpgrades.size >= maxPendingSessions) {
40
+ socket.destroy();
41
+ return;
42
+ }
43
+ const key = connectionKey(socket);
44
+ const timer = setTimeout(() => socket.destroy(), pendingSessionTimeoutMs);
45
+ timer.unref();
46
+ pendingUpgrades.set(key, timer);
35
47
  networkSockets.add(socket);
36
- socket.once("close", () => networkSockets.delete(socket));
48
+ socket.once("close", () => {
49
+ clearTimeout(timer);
50
+ if (pendingUpgrades.get(key) === timer)
51
+ pendingUpgrades.delete(key);
52
+ networkSockets.delete(socket);
53
+ });
37
54
  });
38
55
  server.on("upgrade", (request, socket, head) => {
39
56
  const origin = request.headers.origin;
@@ -44,7 +61,12 @@ export async function startNodeWebSocketListenerV3(options) {
44
61
  socket.destroy();
45
62
  return;
46
63
  }
47
- wss.handleUpgrade(request, socket, head, (webSocket) => wss.emit("connection", webSocket));
64
+ const key = connectionKey(request.socket);
65
+ wss.handleUpgrade(request, socket, head, (webSocket) => {
66
+ clearTimeout(pendingUpgrades.get(key));
67
+ pendingUpgrades.delete(key);
68
+ wss.emit("connection", webSocket);
69
+ });
48
70
  });
49
71
  wss.on("connection", (socket) => {
50
72
  sockets.add(socket);
@@ -112,6 +134,9 @@ export async function startNodeWebSocketListenerV3(options) {
112
134
  await graceful;
113
135
  }
114
136
  }
137
+ function connectionKey(socket) {
138
+ return `${socket.localAddress}/${socket.localPort}/${socket.remoteAddress}/${socket.remotePort}`;
139
+ }
115
140
  function validateOptions(options) {
116
141
  if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65_535 ||
117
142
  options.allowedOrigins.length === 0 || new Set(options.allowedOrigins).size !== options.allowedOrigins.length ||
@@ -0,0 +1,13 @@
1
+ export declare class BodyIntake {
2
+ private readonly slots;
3
+ private readonly limit;
4
+ private count;
5
+ private bytes;
6
+ private readonly waiters;
7
+ constructor(slots: number, limit: number);
8
+ begin(): {
9
+ grow: (size: number) => boolean;
10
+ waitForBudget: (size: number, signal: AbortSignal) => Promise<boolean>;
11
+ release: () => void;
12
+ } | undefined;
13
+ }
@@ -0,0 +1,55 @@
1
+ export class BodyIntake {
2
+ slots;
3
+ limit;
4
+ count = 0;
5
+ bytes = 0;
6
+ waiters = new Set();
7
+ constructor(slots, limit) {
8
+ this.slots = slots;
9
+ this.limit = limit;
10
+ }
11
+ begin() {
12
+ if (this.count >= this.slots)
13
+ return undefined;
14
+ this.count++;
15
+ let held = 0;
16
+ const grow = (size) => {
17
+ if (this.bytes + size > this.limit)
18
+ return false;
19
+ this.bytes += size;
20
+ held += size;
21
+ return true;
22
+ };
23
+ return {
24
+ grow,
25
+ waitForBudget: async (size, signal) => {
26
+ if (size > this.limit)
27
+ return false;
28
+ signal.throwIfAborted();
29
+ if (grow(size))
30
+ return true;
31
+ return await new Promise((resolve, reject) => {
32
+ const cleanup = () => {
33
+ this.waiters.delete(wake);
34
+ signal.removeEventListener("abort", abort);
35
+ };
36
+ const wake = () => {
37
+ if (grow(size)) {
38
+ cleanup();
39
+ resolve(true);
40
+ }
41
+ };
42
+ const abort = () => { cleanup(); reject(signal.reason); };
43
+ this.waiters.add(wake);
44
+ signal.addEventListener("abort", abort, { once: true });
45
+ });
46
+ },
47
+ release: () => {
48
+ this.count--;
49
+ this.bytes -= held;
50
+ for (const wake of this.waiters)
51
+ wake();
52
+ },
53
+ };
54
+ }
55
+ }
@@ -22,6 +22,10 @@ export type ServiceWorkerControllerGuardOptions = Readonly<{
22
22
  navigationWindow?: Window;
23
23
  expectedScriptPathSuffix: string;
24
24
  repair?: ServiceWorkerControllerGuardRepairOptions;
25
+ registration?: Readonly<{
26
+ scriptUrl: string;
27
+ scope: string;
28
+ }>;
25
29
  monitor?: ServiceWorkerControllerGuardMonitorOptions;
26
30
  conflicts?: ServiceWorkerControllerGuardConflictPolicy;
27
31
  onControllerMismatch?: (context: ServiceWorkerControllerGuardMismatchContext) => "repair" | "ignore" | void;
@@ -1,3 +1,4 @@
1
+ import { matchesServiceWorkerRegistration } from "./registerServiceWorker.js";
1
2
  function serviceWorkerContainer(target) {
2
3
  try {
3
4
  return target.navigator?.serviceWorker;
@@ -16,20 +17,11 @@ function scriptMatches(scriptURL, suffix) {
16
17
  return scriptURL.endsWith(suffix);
17
18
  }
18
19
  }
19
- async function removeConflicts(container, expected, policy) {
20
- if (policy?.uninstallOnMismatch === false || typeof container.getRegistrations !== "function")
21
- return;
22
- const keep = [expected, ...(policy?.keepScriptPathSuffixes ?? [])];
23
- for (const registration of await container.getRegistrations()) {
24
- const script = registration.active?.scriptURL ?? registration.waiting?.scriptURL ?? registration.installing?.scriptURL;
25
- if (script !== undefined && !keep.some((suffix) => scriptMatches(script, suffix))) {
26
- await registration.unregister().catch(() => false);
27
- }
28
- }
29
- }
30
- function repair(target, options) {
20
+ function nextRepairURL(target, options) {
31
21
  const key = options?.queryKey?.trim() || "_flowersec_sw_repair";
32
22
  const maxAttempts = options?.maxAttempts ?? 2;
23
+ if (!Number.isSafeInteger(maxAttempts) || maxAttempts < 0 || maxAttempts > 5)
24
+ throw new TypeError("invalid service worker repair limit");
33
25
  let url;
34
26
  try {
35
27
  url = new URL(target.location.href);
@@ -41,14 +33,8 @@ function repair(target, options) {
41
33
  const attempt = Number.isSafeInteger(current) && current >= 0 ? current : 0;
42
34
  if (attempt >= maxAttempts)
43
35
  throw new Error("service worker controller mismatch persists");
44
- if (options?.strategy === "reload") {
45
- target.location.reload();
46
- }
47
- else {
48
- url.searchParams.set(key, String(attempt + 1));
49
- target.location.replace(url.toString());
50
- }
51
- throw new Error("service worker controller repair navigation started");
36
+ url.searchParams.set(key, String(attempt + 1));
37
+ return url;
52
38
  }
53
39
  export function createServiceWorkerControllerGuard(options) {
54
40
  const target = options.targetWindow ?? globalThis.window;
@@ -59,6 +45,28 @@ export function createServiceWorkerControllerGuard(options) {
59
45
  const container = serviceWorkerContainer(target);
60
46
  let disposed = false;
61
47
  let lastRepairAt = 0;
48
+ let pendingRepair;
49
+ let navigating = false;
50
+ const grant = options.registration && {
51
+ scope: new URL(options.registration.scope, target.location.href).href,
52
+ scriptUrl: new URL(options.registration.scriptUrl, target.location.href).href,
53
+ };
54
+ const matches = async () => {
55
+ if (!grant || !container)
56
+ return scriptMatches(container?.controller?.scriptURL, expected);
57
+ const current = await container.getRegistration(target.location.href);
58
+ return matchesServiceWorkerRegistration(current, container.controller, grant, target.location.href);
59
+ };
60
+ const clearAttempt = () => {
61
+ if (disposed || navigating)
62
+ return;
63
+ const url = new URL(navigation.location.href);
64
+ const key = options.repair?.queryKey?.trim() || "_flowersec_sw_repair";
65
+ if (url.searchParams.has(key)) {
66
+ url.searchParams.delete(key);
67
+ navigation.history.replaceState(navigation.history.state, "", url);
68
+ }
69
+ };
62
70
  const handleMismatch = async (stage) => {
63
71
  if (disposed || container === undefined)
64
72
  throw new Error("service worker controller is unavailable");
@@ -66,18 +74,48 @@ export function createServiceWorkerControllerGuard(options) {
66
74
  const context = { expectedScriptPathSuffix: expected, actualScriptURL: actual, stage };
67
75
  if (options.onControllerMismatch?.(context) === "ignore")
68
76
  return;
69
- await removeConflicts(container, expected, options.conflicts);
70
- repair(navigation, options.repair);
77
+ if (navigating)
78
+ throw new Error("service worker controller repair navigation started");
79
+ const destination = nextRepairURL(navigation, options.repair);
80
+ if (grant && options.conflicts?.uninstallOnMismatch !== false) {
81
+ const current = await container.getRegistration(target.location.href);
82
+ if (disposed)
83
+ return;
84
+ if (matchesServiceWorkerRegistration(current, container.controller, grant, target.location.href)) {
85
+ clearAttempt();
86
+ return;
87
+ }
88
+ if (current?.scope === grant.scope && current.active && current.active === container.controller &&
89
+ !current.waiting && !current.installing && !options.conflicts?.keepScriptPathSuffixes?.some(suffix => scriptMatches(current.active?.scriptURL, suffix))) {
90
+ await current.unregister();
91
+ }
92
+ }
93
+ if (disposed)
94
+ return;
95
+ if (options.repair?.strategy === "reload") {
96
+ navigation.history.replaceState(navigation.history.state, "", destination);
97
+ navigation.location.reload();
98
+ }
99
+ else
100
+ navigation.location.replace(destination.href);
101
+ navigating = true;
102
+ throw new Error("service worker controller repair navigation started");
71
103
  };
104
+ const repair = (stage) => pendingRepair ??= handleMismatch(stage).finally(() => { pendingRepair = undefined; });
72
105
  const onControllerChange = () => {
73
- if (disposed || options.monitor?.enabled === false || scriptMatches(container?.controller?.scriptURL, expected))
74
- return;
75
- const now = Date.now();
76
- const throttle = options.monitor?.throttleMs ?? 10_000;
77
- if (now - lastRepairAt < throttle)
106
+ if (disposed || options.monitor?.enabled === false)
78
107
  return;
79
- lastRepairAt = now;
80
- void handleMismatch("monitor").catch(() => undefined);
108
+ void matches().then(async (ok) => {
109
+ if (ok) {
110
+ clearAttempt();
111
+ return;
112
+ }
113
+ const now = Date.now();
114
+ if (now - lastRepairAt < (options.monitor?.throttleMs ?? 10_000))
115
+ return;
116
+ lastRepairAt = now;
117
+ await repair("monitor");
118
+ }).catch(() => undefined);
81
119
  };
82
120
  container?.addEventListener("controllerchange", onControllerChange);
83
121
  return Object.freeze({
@@ -86,25 +124,29 @@ export function createServiceWorkerControllerGuard(options) {
86
124
  throw new Error("service worker controller guard is disposed");
87
125
  if (container === undefined)
88
126
  throw new Error("service worker controller is unavailable");
89
- if (scriptMatches(container.controller?.scriptURL, expected))
127
+ if (await matches()) {
128
+ clearAttempt();
90
129
  return;
130
+ }
91
131
  const timeoutMs = options.repair?.controllerTimeoutMs ?? 8_000;
92
132
  const matched = await new Promise((resolve) => {
93
133
  const onChange = () => {
94
- if (!scriptMatches(container.controller?.scriptURL, expected))
95
- return;
96
- cleanup();
97
- resolve(true);
134
+ void matches().then(ok => { if (ok) {
135
+ cleanup();
136
+ resolve(true);
137
+ } }).catch(() => undefined);
98
138
  };
99
139
  const cleanup = () => {
100
140
  clearTimeout(timer);
101
141
  container.removeEventListener("controllerchange", onChange);
102
142
  };
103
143
  container.addEventListener("controllerchange", onChange);
104
- const timer = setTimeout(() => { cleanup(); resolve(scriptMatches(container.controller?.scriptURL, expected)); }, timeoutMs);
144
+ const timer = setTimeout(() => { cleanup(); resolve(false); }, timeoutMs);
105
145
  });
106
- if (!matched)
107
- await handleMismatch("ensure");
146
+ if (matched || await matches())
147
+ clearAttempt();
148
+ else
149
+ await repair("ensure");
108
150
  },
109
151
  dispose: () => {
110
152
  if (disposed)
@@ -1,5 +1,6 @@
1
+ import type { BodyIntake } from "./bodyIntake.js";
1
2
  import type { ProxyFetchRequest, ProxyRuntime } from "./types.js";
2
- export declare function prepareProxyFetch(input: RequestInfo | URL, init?: RequestInit, externalOrigin?: string, maxBodyBytes?: number): Promise<{
3
+ export declare function prepareProxyFetch(input: RequestInfo | URL, init?: RequestInit, externalOrigin?: string, maxBodyBytes?: number, intake?: BodyIntake): Promise<{
3
4
  request: ProxyFetchRequest;
4
5
  signal: AbortSignal;
5
6
  }>;
@@ -1,7 +1,7 @@
1
1
  import { enableResponseFlowControl } from "./serviceWorkerRuntime.js";
2
2
  import { SessionError } from "../public/contract.js";
3
3
  import { InvalidProxyPathError, normalizePath } from "./policy.js";
4
- export async function prepareProxyFetch(input, init, externalOrigin, maxBodyBytes = 64 * 1024 * 1024) {
4
+ export async function prepareProxyFetch(input, init, externalOrigin, maxBodyBytes = 64 * 1024 * 1024, intake) {
5
5
  const raw = input instanceof Request ? input.url : String(input);
6
6
  let path = raw;
7
7
  if (!raw.startsWith("/")) {
@@ -14,23 +14,43 @@ export async function prepareProxyFetch(input, init, externalOrigin, maxBodyByte
14
14
  path = normalizePath(path);
15
15
  const request = new Request(input instanceof Request ? input : `https://flowersec.invalid${path}`, init);
16
16
  request.signal.throwIfAborted();
17
- let body;
18
- let source = request.body;
17
+ const body = await readRequestBody(request, maxBodyBytes, intake);
18
+ return { request: enableResponseFlowControl({ id: "", method: request.method, path,
19
+ headers: Array.from(request.headers, ([name, value]) => ({ name, value })),
20
+ ...(body === undefined ? {} : { body }),
21
+ }), signal: request.signal };
22
+ }
23
+ async function readRequestBody(request, maxBodyBytes, intake) {
24
+ const source = request.body;
25
+ if (source === null || ["GET", "HEAD"].includes(request.method))
26
+ return undefined;
27
+ const reservation = intake?.begin();
28
+ if (intake && !reservation)
29
+ throw new SessionError("resource_exhausted");
19
30
  if (source === undefined) {
20
31
  // Some current browser engines implement Body consumption without exposing
21
32
  // Request.body. Blob size is checked before copying bytes into the carrier;
22
33
  // the ordinary streaming path retains its incremental budget enforcement.
23
- const blob = await request.blob();
24
- request.signal.throwIfAborted();
25
- if (blob.size > maxBodyBytes)
26
- throw new SessionError("resource_exhausted");
27
- source = blob.size ? blob.stream() : null;
34
+ try {
35
+ if (reservation && !await reservation.waitForBudget(maxBodyBytes, request.signal))
36
+ throw new SessionError("resource_exhausted");
37
+ const blob = await request.blob();
38
+ request.signal.throwIfAborted();
39
+ if (blob.size > maxBodyBytes)
40
+ throw new SessionError("resource_exhausted");
41
+ const body = blob.size ? await blob.arrayBuffer() : undefined;
42
+ request.signal.throwIfAborted();
43
+ return body;
44
+ }
45
+ finally {
46
+ reservation?.release();
47
+ }
28
48
  }
29
- if (source !== null) {
49
+ try {
30
50
  const reader = source.getReader();
31
51
  const abort = () => { void reader.cancel().catch(() => undefined); };
32
52
  request.signal.addEventListener("abort", abort, { once: true });
33
- const chunks = [];
53
+ let bytes = new Uint8Array(0);
34
54
  let total = 0;
35
55
  try {
36
56
  for (;;) {
@@ -39,18 +59,21 @@ export async function prepareProxyFetch(input, init, externalOrigin, maxBodyByte
39
59
  request.signal.throwIfAborted();
40
60
  if (next.done)
41
61
  break;
42
- total += next.value.byteLength;
43
- if (total > maxBodyBytes)
62
+ const required = total + next.value.byteLength;
63
+ if (required > maxBodyBytes)
44
64
  throw new SessionError("resource_exhausted");
45
- chunks.push(next.value);
46
- }
47
- const bytes = new Uint8Array(total);
48
- let offset = 0;
49
- for (const chunk of chunks) {
50
- bytes.set(chunk, offset);
51
- offset += chunk.length;
65
+ if (required > bytes.length) {
66
+ const capacity = Math.min(maxBodyBytes, Math.max(required, bytes.length * 2));
67
+ if (reservation && !reservation.grow(capacity - bytes.length))
68
+ throw new SessionError("resource_exhausted");
69
+ const grown = new Uint8Array(capacity);
70
+ grown.set(bytes);
71
+ bytes = grown;
72
+ }
73
+ bytes.set(next.value, total);
74
+ total = required;
52
75
  }
53
- body = bytes.buffer;
76
+ return total === bytes.length ? bytes.buffer : bytes.buffer.slice(0, total);
54
77
  }
55
78
  finally {
56
79
  request.signal.removeEventListener("abort", abort);
@@ -58,10 +81,9 @@ export async function prepareProxyFetch(input, init, externalOrigin, maxBodyByte
58
81
  reader.releaseLock();
59
82
  }
60
83
  }
61
- return { request: enableResponseFlowControl({ id: "", method: request.method, path,
62
- headers: Array.from(request.headers, ([name, value]) => ({ name, value })),
63
- ...(body === undefined ? {} : { body }),
64
- }), signal: request.signal };
84
+ finally {
85
+ reservation?.release();
86
+ }
65
87
  }
66
88
  // Window applications use the same controller-owned transaction through a
67
89
  // credited port. At most one body chunk may be in flight across the bridge.
@@ -87,10 +109,16 @@ export function fetchProxyPort(dispatch, request, signal, maxChunkBytes = 256 *
87
109
  else
88
110
  output?.close();
89
111
  };
90
- const abort = () => {
91
- port.postMessage({ type: "flowersec-proxy:abort" });
92
- finish(new SessionError("canceled"));
112
+ const cancel = (error) => {
113
+ try {
114
+ port.postMessage({ type: "flowersec-proxy:abort" });
115
+ }
116
+ finally {
117
+ finish(error);
118
+ }
93
119
  };
120
+ const abort = () => cancel(signal.reason instanceof SessionError ? signal.reason : new SessionError("canceled"));
121
+ port.onmessageerror = () => cancel(new SessionError("operation_failed"));
94
122
  signal.addEventListener("abort", abort, { once: true });
95
123
  port.onmessage = (event) => {
96
124
  if (finished)
@@ -1,5 +1,5 @@
1
1
  import { type SessionOptionsV3 } from "../browser/connectSessionV3.js";
2
- import type { ArtifactLeaseV3 } from "../v3/artifactLease.js";
2
+ import { type ArtifactLeaseV3 } from "../v3/artifactLease.js";
3
3
  import type { Session } from "../public/contract.js";
4
4
  import type { ProxyRuntime, ProxyRuntimeOptions } from "./types.js";
5
5
  import { type ProxyControllerWindowHandle, type RegisterProxyControllerWindowOptions } from "./windowBridge.js";
@@ -1,14 +1,29 @@
1
1
  import { connectV3 } from "../browser/connectSessionV3.js";
2
- import { createProxyRuntime } from "./runtime.js";
2
+ import { leaseScopeV3 } from "../v3/artifactLease.js";
3
+ import { createScopedProxyRuntime } from "./runtime.js";
4
+ import { assertProxyRuntimeScope, PROXY_RUNTIME_SCOPE } from "./scope.js";
3
5
  import { registerServiceWorkerAndEnsureControl } from "./registerServiceWorker.js";
4
6
  import { registerProxyControllerWindow, } from "./windowBridge.js";
7
+ function proxyAuthority(lease) {
8
+ const entry = leaseScopeV3(lease, PROXY_RUNTIME_SCOPE.name);
9
+ if (!entry)
10
+ return undefined;
11
+ if (entry.scope_version !== PROXY_RUNTIME_SCOPE.version)
12
+ throw new TypeError("unsupported proxy scope version");
13
+ return assertProxyRuntimeScope(entry.payload);
14
+ }
5
15
  export async function connectProxyBrowser(lease, options = {}) {
16
+ const authority = proxyAuthority(lease);
17
+ if (authority && options.serviceWorker && (authority.mode !== "service_worker" ||
18
+ options.serviceWorker.scriptUrl !== authority.serviceWorker.scriptUrl || options.serviceWorker.scope !== authority.serviceWorker.scope)) {
19
+ throw new TypeError("service worker does not match the proxy scope");
20
+ }
21
+ if (options.serviceWorker !== undefined)
22
+ await registerServiceWorkerAndEnsureControl(options.serviceWorker);
6
23
  const session = await connectV3(lease, options.connect);
7
24
  let runtime;
8
25
  try {
9
- if (options.serviceWorker !== undefined)
10
- await registerServiceWorkerAndEnsureControl(options.serviceWorker);
11
- runtime = createProxyRuntime({ session, ...options.runtime });
26
+ runtime = createScopedProxyRuntime({ ...options.runtime, session }, authority);
12
27
  return Object.freeze({
13
28
  session,
14
29
  runtime,
@@ -25,10 +40,15 @@ export async function connectProxyBrowser(lease, options = {}) {
25
40
  }
26
41
  }
27
42
  export async function connectProxyControllerBrowser(lease, options) {
43
+ const authority = proxyAuthority(lease);
44
+ const allowedOrigins = Object.freeze([...options.controller.allowedOrigins]);
45
+ if (authority && (authority.mode !== "controller_bridge" || allowedOrigins.some(origin => !authority.controllerBridge.allowedOrigins.includes(origin)))) {
46
+ throw new TypeError("controller origins do not match the proxy scope");
47
+ }
28
48
  const base = await connectProxyBrowser(lease, options);
29
49
  let controller;
30
50
  try {
31
- controller = registerProxyControllerWindow({ runtime: base.runtime, ...options.controller });
51
+ controller = registerProxyControllerWindow({ ...options.controller, allowedOrigins, runtime: base.runtime });
32
52
  return Object.freeze({
33
53
  session: base.session,
34
54
  runtime: base.runtime,
@@ -5,4 +5,9 @@ export type RegisterServiceWorkerOptions = Readonly<{
5
5
  maxRepairAttempts?: number;
6
6
  controllerTimeoutMs?: number;
7
7
  }>;
8
+ export declare function matchesServiceWorkerRegistration(registration: ServiceWorkerRegistration | undefined, controller: ServiceWorker | null, expected: Readonly<{
9
+ scriptUrl: string;
10
+ scope: string;
11
+ }>, base?: string): boolean;
8
12
  export declare function registerServiceWorkerAndEnsureControl(options: RegisterServiceWorkerOptions): Promise<void>;
13
+ export declare function registerWindowWorker(options: RegisterServiceWorkerOptions, target: Pick<Window, "navigator" | "location">): Promise<void>;