@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,3 +1,7 @@
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ import { bytesToHex } from "@noble/hashes/utils.js";
3
+ import { BodyIntake } from "./bodyIntake.js";
4
+ import { FORBIDDEN_HEADERS } from "./policy.js";
1
5
  function strings(name, values, max = 64) {
2
6
  if ((values?.length ?? 0) > max)
3
7
  throw new TypeError(`${name} contains too many entries`);
@@ -30,6 +34,7 @@ function token(name, value, fallback = "") {
30
34
  return result;
31
35
  }
32
36
  function normalizeOptions(options) {
37
+ const registrationToken = token("runtimeRegistrationToken", options.runtimeRegistrationToken);
33
38
  const proxyPathPrefix = token("proxyPathPrefix", options.proxyPathPrefix, "");
34
39
  if (proxyPathPrefix !== "" && (!proxyPathPrefix.startsWith("/") || proxyPathPrefix.startsWith("//"))) {
35
40
  throw new TypeError("proxyPathPrefix must be an origin-relative prefix");
@@ -45,6 +50,7 @@ function normalizeOptions(options) {
45
50
  }
46
51
  }
47
52
  return Object.freeze({
53
+ forbiddenHeaders: [...FORBIDDEN_HEADERS],
48
54
  sameOriginOnly: options.sameOriginOnly ?? true,
49
55
  maxRequestBodyBytes: bounded("maxRequestBodyBytes", options.maxRequestBodyBytes, 64 * 1024 * 1024, 256 * 1024 * 1024),
50
56
  maxInjectHTMLBytes: bounded("maxInjectHTMLBytes", options.maxInjectHTMLBytes, 8 * 1024 * 1024, 32 * 1024 * 1024),
@@ -60,16 +66,160 @@ function normalizeOptions(options) {
60
66
  excludePathPrefixes: strings("injectHTML.excludePathPrefixes", inject.excludePathPrefixes),
61
67
  }),
62
68
  forwardFetchMessageTypes: strings("forwardFetchMessageTypes", options.forwardFetchMessageTypes),
63
- windowTarget: options.windowTarget ?? "registered_runtime",
69
+ windowTarget: options.windowTarget ?? "request_client",
64
70
  windowClientMessageType: token("windowClientMessageType", options.windowClientMessageType, "flowersec-proxy:fetch"),
65
- runtimeRegistrationToken: token("runtimeRegistrationToken", options.runtimeRegistrationToken),
71
+ runtimeRegistrationDigest: registrationToken && bytesToHex(sha256(new TextEncoder().encode(registrationToken))),
66
72
  runtimeClientPathPrefix: token("runtimeClientPathPrefix", options.runtimeClientPathPrefix),
67
73
  conflictHints: strings("conflictHints.keepScriptPathSuffixes", options.conflictHints?.keepScriptPathSuffixes),
68
74
  });
69
75
  }
70
- function serviceWorkerMain(config) {
76
+ function serviceWorkerMain(config, Intake) {
71
77
  const worker = self;
78
+ const forbiddenHeaders = new Set(config.forbiddenHeaders);
72
79
  let runtimeClientId = "";
80
+ const registrations = new Set();
81
+ const watches = new Map();
82
+ const watchClient = (id, onLost) => {
83
+ let watch = watches.get(id);
84
+ if (!watch) {
85
+ const lost = new Set();
86
+ let checking = false;
87
+ const timer = setInterval(async () => {
88
+ if (checking)
89
+ return;
90
+ checking = true;
91
+ try {
92
+ if (await worker.clients.get(id))
93
+ return;
94
+ }
95
+ catch { /* Unreachable client. */ }
96
+ finally {
97
+ checking = false;
98
+ }
99
+ for (const notify of lost)
100
+ notify();
101
+ }, 250);
102
+ watch = { lost, timer };
103
+ watches.set(id, watch);
104
+ }
105
+ watch.lost.add(onLost);
106
+ return () => {
107
+ if (watch.lost.delete(onLost) && !watch.lost.size) {
108
+ clearInterval(watch.timer);
109
+ watches.delete(id);
110
+ }
111
+ };
112
+ };
113
+ const restricted = !!(config.runtimeRegistrationDigest || config.runtimeClientPathPrefix);
114
+ const matchesToken = async (value) => {
115
+ if (!config.runtimeRegistrationDigest)
116
+ return true;
117
+ if (typeof value !== "string" || !value.length || value.length > 512)
118
+ return false;
119
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
120
+ return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, "0")).join("") === config.runtimeRegistrationDigest;
121
+ };
122
+ const intake = new Intake(24, Math.max(config.maxRequestBodyBytes, 64 * 1024 * 1024));
123
+ const shared = config.windowTarget === "registered_runtime";
124
+ const cacheName = `flowersec-proxy-owner-v2:${worker.registration?.scope ?? worker.location.href}`;
125
+ const ownerKey = worker.location.href;
126
+ const ownerCache = () => worker.caches.open(cacheName);
127
+ let mutation = Promise.resolve();
128
+ const serialize = (operation) => {
129
+ const result = mutation.then(operation);
130
+ mutation = result.catch(() => undefined);
131
+ return result;
132
+ };
133
+ const storedOwner = async () => (await (await ownerCache()).match(ownerKey))?.text();
134
+ const eligible = (client) => !!client?.id && (!config.runtimeClientPathPrefix || new URL(client.url).pathname.startsWith(config.runtimeClientPathPrefix));
135
+ const confirmations = new Map();
136
+ const confirm = (client) => {
137
+ if (!eligible(client))
138
+ return Promise.resolve(false);
139
+ const existing = confirmations.get(client.id);
140
+ if (existing)
141
+ return existing;
142
+ if (confirmations.size >= 256)
143
+ return Promise.resolve(false);
144
+ const confirmation = new Promise(resolve => {
145
+ const channel = new MessageChannel();
146
+ const finish = (ok) => { clearTimeout(timer); channel.port1.close(); resolve(ok); };
147
+ const timer = setTimeout(() => finish(false), 2_000);
148
+ channel.port1.onmessage = event => {
149
+ if (event.data?.registered !== true)
150
+ return finish(false);
151
+ void matchesToken(event.data.token).then(finish, () => finish(false));
152
+ };
153
+ channel.port1.onmessageerror = () => finish(false);
154
+ try {
155
+ client.postMessage({ type: "flowersec-proxy:confirm-registration" }, [channel.port2]);
156
+ }
157
+ catch {
158
+ finish(false);
159
+ }
160
+ }).finally(() => confirmations.delete(client.id));
161
+ confirmations.set(client.id, confirmation);
162
+ return confirmation;
163
+ };
164
+ const resolveTarget = async (source) => {
165
+ await mutation;
166
+ if (!shared) {
167
+ if (!restricted || registrations.has(source?.id))
168
+ return source;
169
+ const before = mutation;
170
+ if (!await confirm(source) || before !== mutation || registrations.size >= 256)
171
+ return null;
172
+ registrations.add(source.id);
173
+ return source;
174
+ }
175
+ const id = runtimeClientId || await storedOwner();
176
+ if (!id)
177
+ return null;
178
+ const client = await worker.clients.get(id);
179
+ if (client && (runtimeClientId === id || await confirm(client)) && (runtimeClientId || await storedOwner()) === id) {
180
+ runtimeClientId = id;
181
+ return client;
182
+ }
183
+ return null;
184
+ };
185
+ const boundedBody = async (body, limit, reserve, signal) => {
186
+ let buffer = new Uint8Array(0);
187
+ let used = 0;
188
+ if (body === null)
189
+ return buffer.buffer;
190
+ const reader = body.getReader();
191
+ const cancel = () => { void reader.cancel().catch(() => undefined); };
192
+ signal?.addEventListener("abort", cancel, { once: true });
193
+ try {
194
+ while (true) {
195
+ signal?.throwIfAborted();
196
+ const next = await reader.read();
197
+ if (next.done)
198
+ return used === buffer.length ? buffer.buffer : buffer.buffer.slice(0, used);
199
+ const required = used + next.value.byteLength;
200
+ if (required > limit) {
201
+ void reader.cancel().catch(() => undefined);
202
+ return null;
203
+ }
204
+ if (required > buffer.length) {
205
+ const capacity = Math.min(limit, Math.max(required, buffer.length * 2));
206
+ if (reserve && !reserve(capacity - buffer.length)) {
207
+ void reader.cancel().catch(() => undefined);
208
+ return null;
209
+ }
210
+ const grown = new Uint8Array(capacity);
211
+ grown.set(buffer);
212
+ buffer = grown;
213
+ }
214
+ buffer.set(next.value, used);
215
+ used = required;
216
+ }
217
+ }
218
+ finally {
219
+ signal?.removeEventListener("abort", cancel);
220
+ reader.releaseLock();
221
+ }
222
+ };
73
223
  const pathMatches = (path, values) => values.some((value) => path.startsWith(value));
74
224
  const safeMessage = (error) => error instanceof Error && error.name === "AbortError"
75
225
  ? "proxy request canceled"
@@ -80,12 +230,20 @@ function serviceWorkerMain(config) {
80
230
  const data = event.data;
81
231
  if (data === null || typeof data !== "object")
82
232
  return;
233
+ if (data.type === "flowersec-proxy:release-runtime" && data.version === 2) {
234
+ event.waitUntil(serialize(async () => {
235
+ if (shared && event.source?.id === (runtimeClientId || await storedOwner())) {
236
+ await (await ownerCache()).delete(ownerKey);
237
+ runtimeClientId = "";
238
+ }
239
+ registrations.delete(event.source?.id);
240
+ }));
241
+ return;
242
+ }
83
243
  if (data.type === "flowersec-proxy:register-runtime") {
84
244
  const port = event.ports[0];
85
245
  const source = event.source;
86
- let ok = data.version === 2 && source !== null;
87
- if (config.runtimeRegistrationToken !== "")
88
- ok = ok && data.token === config.runtimeRegistrationToken;
246
+ let ok = data.version === 2 && typeof source?.id === "string" && source.id !== "";
89
247
  if (ok && config.runtimeClientPathPrefix !== "") {
90
248
  try {
91
249
  ok = new URL(source.url).pathname.startsWith(config.runtimeClientPathPrefix);
@@ -94,16 +252,38 @@ function serviceWorkerMain(config) {
94
252
  ok = false;
95
253
  }
96
254
  }
97
- if (ok)
98
- runtimeClientId = source.id;
99
- port?.postMessage({ type: "flowersec-proxy:register-runtime-ack", ok });
100
- port?.close();
255
+ event.waitUntil(serialize(async () => {
256
+ ok = ok && await matchesToken(data.token);
257
+ if (ok && restricted && config.windowTarget === "request_client") {
258
+ if (registrations.size >= 256 && !registrations.has(source.id)) {
259
+ await Promise.all(Array.from(registrations, async (id) => {
260
+ if (!await worker.clients.get(id))
261
+ registrations.delete(id);
262
+ }));
263
+ }
264
+ ok = registrations.has(source.id) || registrations.size < 256;
265
+ if (ok)
266
+ registrations.add(source.id);
267
+ }
268
+ if (ok && config.windowTarget === "registered_runtime") {
269
+ const previous = runtimeClientId || await storedOwner();
270
+ if (previous && previous !== source.id) {
271
+ ok = !(await worker.clients.get(previous));
272
+ }
273
+ if (ok) {
274
+ await (await ownerCache()).put(ownerKey, new Response(source.id));
275
+ runtimeClientId = source.id;
276
+ }
277
+ }
278
+ port?.postMessage({ type: "flowersec-proxy:register-runtime-ack", ok });
279
+ port?.close();
280
+ }).catch(() => { port?.postMessage({ type: "flowersec-proxy:register-runtime-ack", ok: false }); port?.close(); }));
101
281
  return;
102
282
  }
103
283
  if (!config.forwardFetchMessageTypes.includes(String(data.type ?? "")))
104
284
  return;
105
285
  event.waitUntil((async () => {
106
- const target = runtimeClientId === "" ? null : await worker.clients.get(runtimeClientId);
286
+ const target = await resolveTarget(event.source);
107
287
  target?.postMessage(data, event.ports);
108
288
  })());
109
289
  });
@@ -126,23 +306,69 @@ function serviceWorkerMain(config) {
126
306
  }
127
307
  }
128
308
  const source = event.clientId === "" ? null : await worker.clients.get(event.clientId);
129
- const target = config.windowTarget === "request_client"
130
- ? source
131
- : runtimeClientId === "" ? null : await worker.clients.get(runtimeClientId);
132
- if (target === null) {
133
- if (config.windowTarget === "registered_runtime")
309
+ const target = await resolveTarget(source);
310
+ const registered = runtimeClientId;
311
+ const forgetTarget = () => {
312
+ if (config.windowTarget === "registered_runtime" && runtimeClientId === registered)
134
313
  runtimeClientId = "";
314
+ };
315
+ if (target == null) {
135
316
  return new Response("proxy runtime unavailable", { status: 503 });
136
317
  }
137
318
  let body;
319
+ const deadline = performance.now() + config.responseMetadataTimeoutMs;
138
320
  if (request.signal.aborted)
139
321
  return new Response("proxy request canceled", { status: 499 });
140
322
  if (request.method !== "GET" && request.method !== "HEAD") {
141
- const requestBody = await request.clone().arrayBuffer();
142
- if (requestBody.byteLength > config.maxRequestBodyBytes)
143
- return new Response("proxy request too large", { status: 413 });
144
- body = requestBody;
323
+ const reservation = intake.begin();
324
+ if (!reservation)
325
+ return new Response("proxy service unavailable", { status: 503 });
326
+ const timeout = new AbortController();
327
+ const timer = setTimeout(() => timeout.abort(), config.responseMetadataTimeoutMs);
328
+ const signal = AbortSignal.any([request.signal, timeout.signal]);
329
+ const interrupted = () => request.signal.aborted ? new Response("proxy request canceled", { status: 499 }) : new Response("proxy request timed out", { status: 504 });
330
+ const prepare = async () => {
331
+ let busy = false;
332
+ let requestBody;
333
+ if (request.body === undefined) {
334
+ if (!await reservation.waitForBudget(config.maxRequestBodyBytes, signal)) {
335
+ return new Response("proxy service unavailable", { status: 503 });
336
+ }
337
+ const blob = await request.blob();
338
+ signal.throwIfAborted();
339
+ requestBody = blob.size > config.maxRequestBodyBytes ? null : await blob.arrayBuffer();
340
+ }
341
+ else
342
+ requestBody = await boundedBody(request.body, config.maxRequestBodyBytes, bytes => {
343
+ busy = !reservation.grow(bytes);
344
+ return !busy;
345
+ }, signal);
346
+ signal.throwIfAborted();
347
+ if (busy)
348
+ return new Response("proxy service unavailable", { status: 503 });
349
+ if (requestBody === null)
350
+ return new Response("proxy request too large", { status: 413 });
351
+ return requestBody;
352
+ };
353
+ let wake;
354
+ const aborted = new Promise(resolve => { wake = () => resolve(interrupted()); });
355
+ signal.addEventListener("abort", wake, { once: true });
356
+ try {
357
+ const result = await Promise.race([aborted, prepare().finally(() => reservation.release())]);
358
+ if (signal.aborted)
359
+ return interrupted();
360
+ if (result instanceof Response)
361
+ return result;
362
+ body = result;
363
+ }
364
+ finally {
365
+ clearTimeout(timer);
366
+ signal.removeEventListener("abort", wake);
367
+ }
145
368
  }
369
+ const remaining = deadline - performance.now();
370
+ if (remaining <= 0)
371
+ return new Response("proxy request timed out", { status: 504 });
146
372
  const channel = new MessageChannel();
147
373
  const response = await new Promise((resolve) => {
148
374
  let metadata = null;
@@ -162,7 +388,7 @@ function serviceWorkerMain(config) {
162
388
  const cleanup = () => {
163
389
  clearTimeout(metadataTimer);
164
390
  clearTimeout(bodyInactivityTimer);
165
- clearInterval(runtimeWatchdog);
391
+ stopWatching();
166
392
  request.signal.removeEventListener("abort", requestAborted);
167
393
  channel.port1.close();
168
394
  };
@@ -185,23 +411,18 @@ function serviceWorkerMain(config) {
185
411
  return;
186
412
  bodyInactivityTimer = setTimeout(() => finishError(504, "proxy response body timed out", true), config.responseBodyInactivityTimeoutMs);
187
413
  };
188
- const metadataTimer = setTimeout(() => finishError(504, "proxy response timed out", true), config.responseMetadataTimeoutMs);
189
- const runtimeWatchdog = setInterval(() => {
190
- void worker.clients.get(target.id).then((current) => {
191
- if (current !== null || finished)
192
- return;
193
- if (config.windowTarget === "registered_runtime")
194
- runtimeClientId = "";
195
- finishError(503, "proxy runtime unavailable", true);
196
- }).catch(() => finishError(503, "proxy runtime unavailable", true));
197
- }, 250);
414
+ const metadataTimer = setTimeout(() => finishError(504, "proxy response timed out", true), remaining);
415
+ const stopWatching = watchClient(target.id, () => {
416
+ forgetTarget();
417
+ finishError(503, "proxy runtime unavailable", true);
418
+ });
198
419
  request.signal.addEventListener("abort", requestAborted, { once: true });
199
- channel.port1.onmessage = (message) => {
420
+ const handleMessage = (message) => {
200
421
  const value = message.data;
201
422
  if (value === null || typeof value !== "object" || finished)
202
423
  return;
203
424
  if (value.type === "flowersec-proxy:response_meta") {
204
- if (!Number.isInteger(value.status) || metadata !== null)
425
+ if (typeof value.status !== "number" || !Number.isInteger(value.status) || value.status < 200 || value.status > 599 || metadata !== null)
205
426
  return finishError(502, "invalid proxy response");
206
427
  const headers = new Headers();
207
428
  if (Array.isArray(value.headers))
@@ -212,6 +433,8 @@ function serviceWorkerMain(config) {
212
433
  metadata = { status: value.status, headers };
213
434
  clearTimeout(metadataTimer);
214
435
  armBodyInactivityTimer();
436
+ if (request.method === "HEAD" || [204, 205, 304].includes(metadata.status))
437
+ return;
215
438
  const stream = new ReadableStream({
216
439
  start(valueController) {
217
440
  controller = valueController;
@@ -237,6 +460,10 @@ function serviceWorkerMain(config) {
237
460
  return;
238
461
  }
239
462
  if (value.type === "flowersec-proxy:response_end") {
463
+ if (metadata === null)
464
+ return finishError(502, "invalid proxy response");
465
+ if (controller === null)
466
+ resolve(new Response(null, metadata));
240
467
  finished = true;
241
468
  controller?.close();
242
469
  cleanup();
@@ -246,8 +473,16 @@ function serviceWorkerMain(config) {
246
473
  finishError(Number.isInteger(value.status) ? value.status : 502, typeof value.message === "string" ? value.message : "proxy request failed");
247
474
  }
248
475
  };
476
+ channel.port1.onmessage = (message) => {
477
+ try {
478
+ handleMessage(message);
479
+ }
480
+ catch {
481
+ finishError(502, "invalid proxy response", true);
482
+ }
483
+ };
249
484
  channel.port1.onmessageerror = () => finishError(502, "proxy request failed", true);
250
- const headers = Array.from(request.headers.entries()).map(([name, value]) => ({ name, value }));
485
+ const headers = Array.from(request.headers.entries()).filter(([name]) => !forbiddenHeaders.has(name.toLowerCase())).map(([name, value]) => ({ name, value }));
251
486
  try {
252
487
  target.postMessage({
253
488
  type: config.windowClientMessageType,
@@ -262,21 +497,29 @@ function serviceWorkerMain(config) {
262
497
  }, [channel.port2, ...(body === undefined ? [] : [body])]);
263
498
  }
264
499
  catch {
265
- if (config.windowTarget === "registered_runtime")
266
- runtimeClientId = "";
500
+ forgetTarget();
267
501
  finishError(503, "proxy runtime unavailable");
268
502
  }
269
503
  });
270
504
  const injection = config.injectHTML;
271
- if (injection === null || pathMatches(url.pathname, injection.excludePathPrefixes ?? []))
505
+ if (response.body === null || injection === null || pathMatches(url.pathname, injection.excludePathPrefixes ?? []))
506
+ return response;
507
+ const contentType = response.headers.get("content-type") ?? "";
508
+ if (contentType.split(";", 1)[0]?.trim().toLowerCase() !== "text/html")
272
509
  return response;
273
- if (!(response.headers.get("content-type") ?? "").toLowerCase().includes("text/html"))
510
+ const charset = /;\s*charset\s*=\s*(?:"([^"]*)"|([^;\s]*))/iu.exec(contentType);
511
+ if (charset && !/^utf-?8$/iu.test(charset[1] ?? charset[2] ?? ""))
274
512
  return response;
275
- const bytes = await response.arrayBuffer();
276
- if (bytes.byteLength > config.maxInjectHTMLBytes)
513
+ const bytes = await boundedBody(response.body, config.maxInjectHTMLBytes);
514
+ if (bytes === null)
277
515
  return new Response("proxy HTML response too large", { status: 502 });
278
- const decoder = new TextDecoder();
279
- let html = decoder.decode(bytes);
516
+ let html;
517
+ try {
518
+ html = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
519
+ }
520
+ catch {
521
+ return new Response(bytes, response);
522
+ }
280
523
  const runtimeGlobal = injection.runtimeGlobal ?? "__flowersecProxyRuntime";
281
524
  let markup;
282
525
  if ((injection.mode ?? "inline_module") === "inline_module") {
@@ -302,5 +545,5 @@ function serviceWorkerMain(config) {
302
545
  }
303
546
  export function createProxyServiceWorkerScript(options = {}) {
304
547
  const config = normalizeOptions(options);
305
- return `// Generated by @floegence/flowersec-core/proxy v2\n(${serviceWorkerMain.toString()})(${JSON.stringify(config)});\n`;
548
+ return `// Generated by @floegence/flowersec-core/proxy v2\n(${serviceWorkerMain.toString()})(${JSON.stringify(config)}, ${BodyIntake.toString()});\n`;
306
549
  }
@@ -1,8 +1,11 @@
1
- import type { ProxyFetchRequest, ProxyRuntime } from "./types.js";
1
+ import type { ProxyFetchRequest, ProxyRuntime, ProxyRuntimeServiceWorkerScope } from "./types.js";
2
2
  export declare function enableResponseFlowControl(request: ProxyFetchRequest): ProxyFetchRequest;
3
3
  type ProxyRuntimeServiceWorkerBridgeHandle = Readonly<{
4
4
  dispose(): void;
5
5
  }>;
6
+ type WorkerGrant = ProxyRuntimeServiceWorkerScope["serviceWorker"];
7
+ type BridgePolicy = WorkerGrant | "registered" | "app_window";
8
+ export declare function registerWithController(container: ServiceWorkerContainer, controller: ServiceWorker, token: string | undefined, send: (acknowledge: () => void) => Promise<void>): Promise<void>;
6
9
  export declare function usesServiceWorkerResponseFlowControl(request: ProxyFetchRequest): boolean;
7
- export declare function registerProxyRuntimeServiceWorkerBridge(runtime: ProxyRuntime, serviceWorker: ServiceWorkerContainer): ProxyRuntimeServiceWorkerBridgeHandle;
10
+ export declare function registerProxyRuntimeServiceWorkerBridge(runtime: ProxyRuntime, serviceWorker: ServiceWorkerContainer, policy?: BridgePolicy): ProxyRuntimeServiceWorkerBridgeHandle;
8
11
  export {};
@@ -1,8 +1,29 @@
1
+ import { matchesServiceWorkerRegistration } from "./registerServiceWorker.js";
1
2
  const responseFlowControl = new WeakSet();
2
3
  export function enableResponseFlowControl(request) {
3
4
  responseFlowControl.add(request);
4
5
  return request;
5
6
  }
7
+ const ownershipKey = Symbol.for("flowersec.proxy.serviceWorkerBridgeOwners.v2");
8
+ const registryHost = globalThis;
9
+ const bridgeOwners = registryHost[ownershipKey] ??= new WeakMap();
10
+ export async function registerWithController(container, controller, token, send) {
11
+ const owner = bridgeOwners.get(container);
12
+ if (typeof owner?.policy === "object") {
13
+ const registration = await container.getRegistration();
14
+ if (!matchesServiceWorkerRegistration(registration, controller, owner.policy))
15
+ return;
16
+ }
17
+ if (container.controller !== controller || bridgeOwners.get(container) !== owner)
18
+ return;
19
+ if (owner)
20
+ owner.contacted = controller;
21
+ await send(() => {
22
+ if (owner && bridgeOwners.get(container) === owner && container.controller === controller) {
23
+ owner.registration = { controller, ...(token === undefined ? {} : { token }) };
24
+ }
25
+ });
26
+ }
6
27
  function record(value) {
7
28
  return value !== null && typeof value === "object" && !Array.isArray(value)
8
29
  ? value
@@ -45,15 +66,37 @@ function parseRuntimeRequest(value) {
45
66
  export function usesServiceWorkerResponseFlowControl(request) {
46
67
  return responseFlowControl.has(request);
47
68
  }
48
- export function registerProxyRuntimeServiceWorkerBridge(runtime, serviceWorker) {
69
+ export function registerProxyRuntimeServiceWorkerBridge(runtime, serviceWorker, policy = "registered") {
49
70
  let disposed = false;
71
+ const owner = bridgeOwners.get(serviceWorker);
72
+ if (owner !== undefined && owner.runtime !== runtime) {
73
+ throw new Error("dispose the current proxy service worker runtime before registering another");
74
+ }
50
75
  const onMessage = (event) => {
76
+ if (record(event.data)?.type === "flowersec-proxy:confirm-registration") {
77
+ const registered = bridgeOwners.get(serviceWorker)?.registration;
78
+ const port = event.ports?.[0];
79
+ if (port && registered && event.source === registered.controller && serviceWorker.controller === registered.controller) {
80
+ port.postMessage({ registered: true, token: registered.token });
81
+ }
82
+ else if (port)
83
+ port.postMessage({ registered: false });
84
+ port?.close();
85
+ return;
86
+ }
51
87
  const message = record(event.data);
52
88
  if (message?.type !== "flowersec-proxy:fetch")
53
89
  return;
54
90
  const port = event.ports?.[0];
55
91
  if (port === undefined)
56
92
  return;
93
+ const controller = serviceWorker.controller;
94
+ const registered = bridgeOwners.get(serviceWorker)?.registration;
95
+ if (!controller || event.source !== controller ||
96
+ ((policy !== "app_window" || registered) && registered?.controller !== controller)) {
97
+ port.close();
98
+ return;
99
+ }
57
100
  try {
58
101
  runtime.dispatchFetch(parseRuntimeRequest(message.req), port);
59
102
  }
@@ -67,13 +110,25 @@ export function registerProxyRuntimeServiceWorkerBridge(runtime, serviceWorker)
67
110
  port.close();
68
111
  }
69
112
  };
70
- serviceWorker.addEventListener("message", onMessage);
113
+ const entry = owner ?? { runtime, handles: 0, policy, releaseListener: () => serviceWorker.removeEventListener("message", onMessage) };
114
+ if (owner === undefined) {
115
+ serviceWorker.addEventListener("message", onMessage);
116
+ bridgeOwners.set(serviceWorker, entry);
117
+ }
118
+ entry.handles++;
71
119
  return Object.freeze({
72
120
  dispose: () => {
73
121
  if (disposed)
74
122
  return;
75
123
  disposed = true;
76
- serviceWorker.removeEventListener("message", onMessage);
124
+ if (--entry.handles === 0) {
125
+ entry.releaseListener();
126
+ bridgeOwners.delete(serviceWorker);
127
+ try {
128
+ entry.contacted?.postMessage({ type: "flowersec-proxy:release-runtime", version: 2 });
129
+ }
130
+ catch { /* A controller may have gone away during disposal. */ }
131
+ }
77
132
  },
78
133
  });
79
134
  }
@@ -5,6 +5,7 @@ export declare class ProxyByteReader {
5
5
  private buffered;
6
6
  constructor(stream: ByteStream, options?: OperationOptions);
7
7
  readExactly(length: number): Promise<Uint8Array<ArrayBuffer>>;
8
+ readInto(output: Uint8Array): Promise<void>;
8
9
  remainingStream(): ByteStream;
9
10
  }
10
11
  export declare function writeProxyWebSocketFrame(stream: ByteStream, opcode: number, payload: Uint8Array, maximum: number, options?: OperationOptions): Promise<void>;
@@ -10,8 +10,12 @@ export class ProxyByteReader {
10
10
  if (!Number.isSafeInteger(length) || length < 0)
11
11
  throw new TypeError("invalid proxy read length");
12
12
  const output = new Uint8Array(length);
13
+ await this.readInto(output);
14
+ return output;
15
+ }
16
+ async readInto(output) {
13
17
  let offset = 0;
14
- while (offset < length) {
18
+ while (offset < output.length) {
15
19
  if (this.buffered === undefined) {
16
20
  const next = await this.stream.read(this.options);
17
21
  if (next === null)
@@ -20,12 +24,11 @@ export class ProxyByteReader {
20
24
  continue;
21
25
  this.buffered = next;
22
26
  }
23
- const take = Math.min(length - offset, this.buffered.length);
27
+ const take = Math.min(output.length - offset, this.buffered.length);
24
28
  output.set(this.buffered.subarray(0, take), offset);
25
29
  offset += take;
26
30
  this.buffered = take === this.buffered.length ? undefined : this.buffered.subarray(take);
27
31
  }
28
- return output;
29
32
  }
30
33
  remainingStream() {
31
34
  if (this.buffered === undefined)
@@ -55,7 +55,7 @@ export type ProxyRequestInit = RequestInit & Readonly<{
55
55
  export type ProxyRuntime = Readonly<{
56
56
  limits: ProxyRuntimeLimits;
57
57
  fetch(input: RequestInfo | URL, init?: ProxyRequestInit): Promise<Response>;
58
- dispatchFetch(request: ProxyFetchRequest, port: MessagePort): void;
58
+ dispatchFetch(request: ProxyFetchRequest, port: MessagePort, signal?: AbortSignal): void;
59
59
  openWebSocketStream(path: string, options?: Readonly<{
60
60
  protocols?: readonly string[];
61
61
  signal?: AbortSignal;
@@ -3,6 +3,7 @@ import { type ServiceWorkerControllerGuardConflictPolicy, type ServiceWorkerCont
3
3
  import type { ProxyRuntime } from "./types.js";
4
4
  export declare class MessagePortByteStream implements ByteStream {
5
5
  private readonly port;
6
+ private readonly lifetime?;
6
7
  readonly kind = "flowersec.proxy.window.v2";
7
8
  terminalError: SessionError | undefined;
8
9
  private readonly reads;
@@ -14,7 +15,8 @@ export declare class MessagePortByteStream implements ByteStream {
14
15
  private ended;
15
16
  private writeClosed;
16
17
  private closed;
17
- constructor(port: MessagePort);
18
+ private readonly abortLifetime;
19
+ constructor(port: MessagePort, lifetime?: AbortSignal | undefined);
18
20
  read(options?: OperationOptions): Promise<Uint8Array | null>;
19
21
  write(data: Uint8Array, options?: OperationOptions): Promise<number>;
20
22
  closeWrite(): Promise<void>;