@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
@@ -28,6 +28,7 @@ export async function startNodeWebSocketListenerV3(options) {
28
28
  const sessions = new SessionQueueV3(maxPendingSessions, pendingSessionTimeoutMs);
29
29
  const sockets = new Set();
30
30
  const networkSockets = new Set();
31
+ const pendingUpgrades = new Map();
31
32
  const wss = new WebSocketServer({
32
33
  noServer: true,
33
34
  perMessageDeflate: false,
@@ -35,8 +36,21 @@ export async function startNodeWebSocketListenerV3(options) {
35
36
  handleProtocols(protocols) { return protocols.size === 1 && protocols.has(protocol) ? protocol : false; },
36
37
  });
37
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);
38
47
  networkSockets.add(socket);
39
- 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
+ });
40
54
  });
41
55
  server.on("upgrade", (request, socket, head) => {
42
56
  const origin = request.headers.origin;
@@ -47,7 +61,12 @@ export async function startNodeWebSocketListenerV3(options) {
47
61
  socket.destroy();
48
62
  return;
49
63
  }
50
- 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
+ });
51
70
  });
52
71
  wss.on("connection", (socket) => {
53
72
  sockets.add(socket);
@@ -115,6 +134,9 @@ export async function startNodeWebSocketListenerV3(options) {
115
134
  await graceful;
116
135
  }
117
136
  }
137
+ function connectionKey(socket) {
138
+ return `${socket.localAddress}/${socket.localPort}/${socket.remoteAddress}/${socket.remotePort}`;
139
+ }
118
140
  function validateOptions(options) {
119
141
  if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65_535 ||
120
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>;
@@ -1,20 +1,28 @@
1
- function currentAttempt(key) {
1
+ function currentAttempt(key, location) {
2
2
  try {
3
- const value = Number(new URL(globalThis.location.href).searchParams.get(key) ?? "0");
3
+ const value = Number(new URL(location.href).searchParams.get(key) ?? "0");
4
4
  return Number.isSafeInteger(value) && value >= 0 ? value : 0;
5
5
  }
6
6
  catch {
7
7
  return 0;
8
8
  }
9
9
  }
10
- function repairNavigation(key, attempt) {
11
- const target = new URL(globalThis.location.href);
10
+ function repairNavigation(key, attempt, location) {
11
+ const target = new URL(location.href);
12
12
  target.searchParams.set(key, String(attempt));
13
- globalThis.location.replace(target.toString());
13
+ location.replace(target.toString());
14
14
  throw new Error("service worker controller navigation started");
15
15
  }
16
+ export function matchesServiceWorkerRegistration(registration, controller, expected, base = globalThis.location.href) {
17
+ return controller !== null && registration?.active === controller &&
18
+ controller.scriptURL === new URL(expected.scriptUrl, base).href &&
19
+ registration.scope === new URL(expected.scope, base).href;
20
+ }
16
21
  export async function registerServiceWorkerAndEnsureControl(options) {
17
- const serviceWorker = globalThis.navigator?.serviceWorker;
22
+ return registerWindowWorker(options, globalThis);
23
+ }
24
+ export async function registerWindowWorker(options, target) {
25
+ const serviceWorker = target.navigator?.serviceWorker;
18
26
  if (serviceWorker === undefined)
19
27
  throw new Error("service workers are unavailable");
20
28
  const scriptUrl = options.scriptUrl.trim();
@@ -26,29 +34,30 @@ export async function registerServiceWorkerAndEnsureControl(options) {
26
34
  if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 60_000 || !Number.isSafeInteger(maxAttempts) || maxAttempts < 0 || maxAttempts > 5) {
27
35
  throw new TypeError("invalid service worker control policy");
28
36
  }
29
- await serviceWorker.register(scriptUrl, { scope });
30
- await serviceWorker.ready;
31
- if (serviceWorker.controller !== null)
32
- return;
33
- const controlled = await new Promise((resolve) => {
34
- let settled = false;
35
- const finish = (value) => {
36
- if (settled)
37
- return;
38
- settled = true;
37
+ const controlled = await new Promise((resolve, reject) => {
38
+ let registration;
39
+ const cleanup = () => {
39
40
  clearTimeout(timer);
40
41
  serviceWorker.removeEventListener("controllerchange", onChange);
41
- resolve(value);
42
42
  };
43
- const onChange = () => finish(serviceWorker.controller !== null);
43
+ const onChange = () => {
44
+ if (matchesServiceWorkerRegistration(registration, serviceWorker.controller, { scriptUrl, scope }, target.location.href)) {
45
+ cleanup();
46
+ resolve(true);
47
+ }
48
+ };
49
+ const timer = setTimeout(() => { cleanup(); resolve(false); }, timeoutMs);
44
50
  serviceWorker.addEventListener("controllerchange", onChange);
45
- const timer = setTimeout(() => finish(serviceWorker.controller !== null), timeoutMs);
51
+ void serviceWorker.register(scriptUrl, { scope }).then(result => {
52
+ registration = result;
53
+ onChange();
54
+ }).catch(error => { cleanup(); reject(error); });
46
55
  });
47
56
  if (controlled)
48
57
  return;
49
58
  const key = options.repairQueryKey?.trim() || "_flowersec_sw_repair";
50
- const attempt = currentAttempt(key);
59
+ const attempt = currentAttempt(key, target.location);
51
60
  if (attempt >= maxAttempts)
52
61
  throw new Error("service worker did not take control");
53
- repairNavigation(key, attempt + 1);
62
+ repairNavigation(key, attempt + 1, target.location);
54
63
  }
@@ -1,7 +1,13 @@
1
- import type { ProxyRuntime, ProxyRuntimeOptions } from "./types.js";
1
+ import type { ProxyRuntime, ProxyRuntimeOptions, ProxyRuntimeScope } from "./types.js";
2
2
  export declare function createProxyRuntime(options: ProxyRuntimeOptions): ProxyRuntime;
3
+ export declare function createScopedProxyRuntime(options: ProxyRuntimeOptions, authority?: ProxyRuntimeScope): ProxyRuntime;
3
4
  export type EnsureServiceWorkerRuntimeRegisteredOptions = Readonly<{
4
5
  timeoutMs?: number;
5
6
  runtimeRegistrationToken?: string;
6
7
  }>;
7
8
  export declare function ensureServiceWorkerRuntimeRegistered(options?: EnsureServiceWorkerRuntimeRegisteredOptions): Promise<void>;
9
+ export declare function registerRuntimeInContainer(container: ServiceWorkerContainer | undefined, options: EnsureServiceWorkerRuntimeRegisteredOptions, expected?: {
10
+ scriptUrl: string;
11
+ scope: string;
12
+ href: string;
13
+ }): Promise<void>;