@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.
- package/README.md +6 -5
- package/THIRD_PARTY_NOTICES.md +8 -8
- package/dist/node/acceptorV3.js +9 -4
- package/dist/node/connectSessionV3.d.ts +2 -2
- package/dist/node/connectSessionV3.js +9 -3
- package/dist/node/connectionPath.js +49 -37
- package/dist/node/listenerIngress.d.ts +7 -0
- package/dist/node/listenerIngress.js +21 -0
- package/dist/node/nativeTransportAddon.d.ts +1 -5
- package/dist/node/nativeTransportAddon.js +3 -5
- package/dist/node/proxyServer.d.ts +1 -0
- package/dist/node/proxyServer.js +173 -78
- package/dist/node/proxyTarget.d.ts +1 -0
- package/dist/node/proxyTarget.js +13 -0
- package/dist/node/rawQuicAdapterV3.js +2 -2
- package/dist/node/rawQuicServerV3.d.ts +3 -1
- package/dist/node/rawQuicServerV3.js +18 -3
- package/dist/node/tunnelRuntimeV3.js +42 -8
- package/dist/node/webSocketServerV3.js +27 -2
- package/dist/proxy/bodyIntake.d.ts +13 -0
- package/dist/proxy/bodyIntake.js +55 -0
- package/dist/proxy/controllerGuard.d.ts +4 -0
- package/dist/proxy/controllerGuard.js +79 -37
- package/dist/proxy/fetch.d.ts +2 -1
- package/dist/proxy/fetch.js +55 -27
- package/dist/proxy/integration.d.ts +1 -1
- package/dist/proxy/integration.js +25 -5
- package/dist/proxy/registerServiceWorker.d.ts +5 -0
- package/dist/proxy/registerServiceWorker.js +30 -21
- package/dist/proxy/runtime.d.ts +7 -1
- package/dist/proxy/runtime.js +129 -39
- package/dist/proxy/scope.js +1 -1
- package/dist/proxy/serviceWorker.js +286 -43
- package/dist/proxy/serviceWorkerRuntime.d.ts +5 -2
- package/dist/proxy/serviceWorkerRuntime.js +58 -3
- package/dist/proxy/stream.d.ts +1 -0
- package/dist/proxy/stream.js +6 -3
- package/dist/proxy/types.d.ts +1 -1
- package/dist/proxy/windowBridge.d.ts +3 -1
- package/dist/proxy/windowBridge.js +64 -19
- package/dist/proxy/wsPatch.js +70 -52
- package/dist/public/sessionHandlers.js +3 -2
- package/dist/utils/abort.d.ts +1 -0
- package/dist/utils/abort.js +13 -0
- package/dist/v3/artifactLease.d.ts +6 -0
- package/dist/v3/artifactLease.js +6 -0
- package/dist/v3/contract.d.ts +1 -0
- package/dist/v3/nodeRuntime.js +10 -25
- package/dist/v3/publicSession.d.ts +2 -1
- package/dist/v3/publicSession.js +11 -15
- package/dist/v3/session.d.ts +7 -1
- package/dist/v3/session.js +110 -25
- package/dist/v3/unreliableMessage.d.ts +1 -0
- package/dist/v3/unreliableMessage.js +5 -1
- package/dist/v3/webSocketCarrier.js +24 -11
- package/dist/v3/webTransportCarrier.js +6 -0
- package/dist/vendor/tr46.js +17 -23
- package/dist/ws-client/binaryTransport.d.ts +2 -0
- package/dist/ws-client/binaryTransport.js +8 -2
- package/dist/yamux/byteReader.js +1 -0
- package/dist/yamux/session.d.ts +2 -0
- package/dist/yamux/session.js +4 -1
- package/package.json +12 -12
- package/sbom/cyclonedx.json +43 -43
- package/sbom/spdx.json +49 -49
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { enableResponseFlowControl, usesServiceWorkerResponseFlowControl } from "./serviceWorkerRuntime.js";
|
|
2
2
|
import { fetchProxyPort, prepareProxyFetch } from "./fetch.js";
|
|
3
|
+
import { BodyIntake } from "./bodyIntake.js";
|
|
4
|
+
import { FORBIDDEN_HEADERS } from "./policy.js";
|
|
5
|
+
import { raceWithSignal } from "../utils/abort.js";
|
|
3
6
|
import { writeAll } from "./stream.js";
|
|
4
7
|
import { SDK_DEFAULTS } from "../defaults.js";
|
|
5
8
|
import { SessionError } from "../public/contract.js";
|
|
6
9
|
import { createServiceWorkerControllerGuard, } from "./controllerGuard.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
10
|
+
import { registerWindowWorker } from "./registerServiceWorker.js";
|
|
11
|
+
import { registerRuntimeInContainer } from "./runtime.js";
|
|
9
12
|
import { registerProxyRuntimeServiceWorkerBridge } from "./serviceWorkerRuntime.js";
|
|
10
13
|
const FETCH_MESSAGE = "flowersec-proxy:window_fetch_v2";
|
|
11
14
|
const WEBSOCKET_OPEN_MESSAGE = "flowersec-proxy:window_ws_open_v2";
|
|
@@ -14,6 +17,7 @@ const MAX_BRIDGE_CHUNK_BYTES = 1024 * 1024;
|
|
|
14
17
|
const MAX_BRIDGE_BUFFER_BYTES = 4 * 1024 * 1024;
|
|
15
18
|
export class MessagePortByteStream {
|
|
16
19
|
port;
|
|
20
|
+
lifetime;
|
|
17
21
|
kind = "flowersec.proxy.window.v2";
|
|
18
22
|
terminalError;
|
|
19
23
|
reads = [];
|
|
@@ -25,11 +29,14 @@ export class MessagePortByteStream {
|
|
|
25
29
|
ended = false;
|
|
26
30
|
writeClosed = false;
|
|
27
31
|
closed = false;
|
|
28
|
-
|
|
32
|
+
abortLifetime = () => { void this.reset(); };
|
|
33
|
+
constructor(port, lifetime) {
|
|
29
34
|
this.port = port;
|
|
35
|
+
this.lifetime = lifetime;
|
|
30
36
|
port.onmessage = (event) => this.handle(event.data);
|
|
31
37
|
port.onmessageerror = () => this.fail(new SessionError("operation_failed"));
|
|
32
38
|
port.start();
|
|
39
|
+
lifetime?.addEventListener("abort", this.abortLifetime, { once: true });
|
|
33
40
|
}
|
|
34
41
|
async read(options = {}) {
|
|
35
42
|
if (options.signal?.aborted === true)
|
|
@@ -168,6 +175,7 @@ export class MessagePortByteStream {
|
|
|
168
175
|
finish() {
|
|
169
176
|
if (this.closed)
|
|
170
177
|
return;
|
|
178
|
+
this.lifetime?.removeEventListener("abort", this.abortLifetime);
|
|
171
179
|
this.closed = true;
|
|
172
180
|
this.ended = true;
|
|
173
181
|
this.reads.length = 0;
|
|
@@ -181,6 +189,7 @@ export class MessagePortByteStream {
|
|
|
181
189
|
fail(error) {
|
|
182
190
|
if (this.terminalError !== undefined)
|
|
183
191
|
return;
|
|
192
|
+
this.lifetime?.removeEventListener("abort", this.abortLifetime);
|
|
184
193
|
this.terminalError = error;
|
|
185
194
|
this.closed = true;
|
|
186
195
|
this.reads.length = 0;
|
|
@@ -240,6 +249,7 @@ export function registerProxyAppWindow(options) {
|
|
|
240
249
|
throw new TypeError("controllerOrigin must be an origin");
|
|
241
250
|
const nonce = capability(options.capabilityNonce);
|
|
242
251
|
const limits = bridgeLimits(options.maxWsFrameBytes, options.maxWsBufferedAmountBytes);
|
|
252
|
+
const intake = new BodyIntake(limits.maxConcurrentHttpStreams, limits.maxQueuedHttpBodyBytes);
|
|
243
253
|
let disposed = false;
|
|
244
254
|
const dispatchFetch = (request, port) => {
|
|
245
255
|
if (disposed) {
|
|
@@ -247,7 +257,8 @@ export function registerProxyAppWindow(options) {
|
|
|
247
257
|
port.close();
|
|
248
258
|
return;
|
|
249
259
|
}
|
|
250
|
-
|
|
260
|
+
const headers = request.headers.filter(({ name }) => !FORBIDDEN_HEADERS.has(name.trim().toLowerCase()));
|
|
261
|
+
controller.postMessage({ type: FETCH_MESSAGE, version: 2, request: { ...request, headers }, responseFlowControl: usesServiceWorkerResponseFlowControl(request) ? "chunk_credit_v2" : undefined, ...(nonce === undefined ? {} : { capabilityNonce: nonce }) }, origin, [port]);
|
|
251
262
|
};
|
|
252
263
|
const lifetime = new AbortController();
|
|
253
264
|
const dispose = () => { disposed = true; lifetime.abort(); };
|
|
@@ -256,9 +267,20 @@ export function registerProxyAppWindow(options) {
|
|
|
256
267
|
fetch: async (input, init) => {
|
|
257
268
|
if (disposed)
|
|
258
269
|
throw new SessionError("closed");
|
|
270
|
+
if (init?.sessionBound !== undefined && init.sessionBound !== false)
|
|
271
|
+
throw new TypeError("sessionBound requires a controller-owned runtime");
|
|
259
272
|
const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);
|
|
260
|
-
const
|
|
261
|
-
|
|
273
|
+
const establishment = new AbortController();
|
|
274
|
+
const owner = AbortSignal.any([lifetime.signal, establishment.signal, ...(signal ? [signal] : [])]);
|
|
275
|
+
const timer = setTimeout(() => establishment.abort(new SessionError("timeout")), 10_000);
|
|
276
|
+
try {
|
|
277
|
+
const prepared = await raceWithSignal(prepareProxyFetch(input, { ...init, signal: owner }, target.location?.origin, limits.maxBodyBytes, intake), owner);
|
|
278
|
+
owner.throwIfAborted();
|
|
279
|
+
return await fetchProxyPort(dispatchFetch, prepared.request, owner, limits.maxChunkBytes);
|
|
280
|
+
}
|
|
281
|
+
finally {
|
|
282
|
+
clearTimeout(timer);
|
|
283
|
+
}
|
|
262
284
|
},
|
|
263
285
|
dispatchFetch,
|
|
264
286
|
openWebSocketStream: async (path, openOptions = {}) => {
|
|
@@ -275,6 +297,7 @@ export function registerProxyAppWindow(options) {
|
|
|
275
297
|
settled = true;
|
|
276
298
|
clearTimeout(timer);
|
|
277
299
|
openOptions.signal?.removeEventListener("abort", abort);
|
|
300
|
+
lifetime.signal.removeEventListener("abort", close);
|
|
278
301
|
if (error !== undefined) {
|
|
279
302
|
channel.port1.close();
|
|
280
303
|
reject(error);
|
|
@@ -282,11 +305,20 @@ export function registerProxyAppWindow(options) {
|
|
|
282
305
|
else
|
|
283
306
|
resolve(opened);
|
|
284
307
|
};
|
|
285
|
-
const
|
|
286
|
-
|
|
287
|
-
|
|
308
|
+
const cancel = (error) => {
|
|
309
|
+
if (settled)
|
|
310
|
+
return;
|
|
311
|
+
try {
|
|
312
|
+
channel.port1.postMessage({ type: "reset" });
|
|
313
|
+
}
|
|
314
|
+
finally {
|
|
315
|
+
finish(error);
|
|
316
|
+
}
|
|
288
317
|
};
|
|
289
|
-
const
|
|
318
|
+
const abort = () => cancel(new SessionError("canceled"));
|
|
319
|
+
const close = () => cancel(new SessionError("closed"));
|
|
320
|
+
const timer = setTimeout(() => cancel(new SessionError("timeout")), 10_000);
|
|
321
|
+
lifetime.signal.addEventListener("abort", close, { once: true });
|
|
290
322
|
channel.port1.onmessage = (event) => {
|
|
291
323
|
if (event.data?.type !== WEBSOCKET_ACK_MESSAGE)
|
|
292
324
|
return;
|
|
@@ -294,7 +326,7 @@ export function registerProxyAppWindow(options) {
|
|
|
294
326
|
finish(new SessionError("operation_failed"));
|
|
295
327
|
return;
|
|
296
328
|
}
|
|
297
|
-
finish(undefined, Object.freeze({ stream: new MessagePortByteStream(channel.port1), protocol: typeof event.data.protocol === "string" ? event.data.protocol : "" }));
|
|
329
|
+
finish(undefined, Object.freeze({ stream: new MessagePortByteStream(channel.port1, lifetime.signal), protocol: typeof event.data.protocol === "string" ? event.data.protocol : "" }));
|
|
298
330
|
};
|
|
299
331
|
openOptions.signal?.addEventListener("abort", abort, { once: true });
|
|
300
332
|
});
|
|
@@ -321,7 +353,7 @@ export function registerProxyAppWindowWithServiceWorkerRuntime(options) {
|
|
|
321
353
|
throw new Error("proxy service worker is unavailable");
|
|
322
354
|
const app = registerProxyAppWindow(options);
|
|
323
355
|
try {
|
|
324
|
-
const serviceWorkerBridge = registerProxyRuntimeServiceWorkerBridge(app.runtime, serviceWorker);
|
|
356
|
+
const serviceWorkerBridge = registerProxyRuntimeServiceWorkerBridge(app.runtime, serviceWorker, "app_window");
|
|
325
357
|
let disposed = false;
|
|
326
358
|
return Object.freeze({
|
|
327
359
|
runtime: app.runtime,
|
|
@@ -418,7 +450,7 @@ export function registerProxyControllerWindow(options) {
|
|
|
418
450
|
const request = event.data.request;
|
|
419
451
|
if (event.data.responseFlowControl === "chunk_credit_v2")
|
|
420
452
|
enableResponseFlowControl(request);
|
|
421
|
-
options.runtime.dispatchFetch(request, port);
|
|
453
|
+
options.runtime.dispatchFetch(request, port, httpLifetime.signal);
|
|
422
454
|
return;
|
|
423
455
|
}
|
|
424
456
|
if (event.data?.type === WEBSOCKET_OPEN_MESSAGE && event.data.version === 2) {
|
|
@@ -459,10 +491,12 @@ export function registerProxyControllerWindow(options) {
|
|
|
459
491
|
})();
|
|
460
492
|
}
|
|
461
493
|
};
|
|
494
|
+
const httpLifetime = new AbortController();
|
|
462
495
|
target.addEventListener("message", onMessage);
|
|
463
496
|
return Object.freeze({
|
|
464
497
|
dispose: () => {
|
|
465
498
|
disposed = true;
|
|
499
|
+
httpLifetime.abort(new SessionError("canceled"));
|
|
466
500
|
target.removeEventListener("message", onMessage);
|
|
467
501
|
for (const controller of active)
|
|
468
502
|
controller.abort(new SessionError("closed"));
|
|
@@ -470,16 +504,27 @@ export function registerProxyControllerWindow(options) {
|
|
|
470
504
|
});
|
|
471
505
|
}
|
|
472
506
|
export async function registerProxyAppWindowWithServiceWorkerControl(options) {
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
507
|
+
const target = options.targetWindow ?? globalThis.window;
|
|
508
|
+
const href = target.location.href;
|
|
509
|
+
const scriptUrl = options.serviceWorker.scriptUrl.trim();
|
|
510
|
+
if (!scriptUrl)
|
|
511
|
+
throw new TypeError("service worker script and scope are required");
|
|
512
|
+
const expected = {
|
|
513
|
+
scriptUrl: new URL(scriptUrl, href).href,
|
|
514
|
+
scope: new URL(options.serviceWorker.scope?.trim() || "/", href).href,
|
|
515
|
+
href,
|
|
516
|
+
};
|
|
517
|
+
await registerWindowWorker({
|
|
518
|
+
scriptUrl: expected.scriptUrl,
|
|
519
|
+
scope: expected.scope,
|
|
476
520
|
...(options.serviceWorker.repair?.queryKey === undefined ? {} : { repairQueryKey: options.serviceWorker.repair.queryKey }),
|
|
477
521
|
...(options.serviceWorker.repair?.maxAttempts === undefined ? {} : { maxRepairAttempts: options.serviceWorker.repair.maxAttempts }),
|
|
478
522
|
...(options.serviceWorker.repair?.controllerTimeoutMs === undefined ? {} : { controllerTimeoutMs: options.serviceWorker.repair.controllerTimeoutMs }),
|
|
479
|
-
});
|
|
523
|
+
}, target);
|
|
480
524
|
const guard = createServiceWorkerControllerGuard({
|
|
481
525
|
...(options.targetWindow === undefined ? {} : { targetWindow: options.targetWindow, navigationWindow: options.targetWindow }),
|
|
482
526
|
expectedScriptPathSuffix: options.serviceWorker.expectedScriptPathSuffix,
|
|
527
|
+
registration: { scriptUrl: expected.scriptUrl, scope: expected.scope },
|
|
483
528
|
...(options.serviceWorker.repair === undefined ? {} : { repair: options.serviceWorker.repair }),
|
|
484
529
|
...(options.serviceWorker.monitor === undefined ? {} : { monitor: options.serviceWorker.monitor }),
|
|
485
530
|
...(options.serviceWorker.conflicts === undefined ? {} : { conflicts: options.serviceWorker.conflicts }),
|
|
@@ -488,11 +533,11 @@ export async function registerProxyAppWindowWithServiceWorkerControl(options) {
|
|
|
488
533
|
try {
|
|
489
534
|
await guard.ensure();
|
|
490
535
|
app = registerProxyAppWindowWithServiceWorkerRuntime(options);
|
|
491
|
-
await
|
|
536
|
+
await registerRuntimeInContainer(target.navigator.serviceWorker, {
|
|
492
537
|
...(options.serviceWorker.runtimeRegistrationToken === undefined
|
|
493
538
|
? {}
|
|
494
539
|
: { runtimeRegistrationToken: options.serviceWorker.runtimeRegistrationToken }),
|
|
495
|
-
});
|
|
540
|
+
}, expected);
|
|
496
541
|
let disposed = false;
|
|
497
542
|
return Object.freeze({
|
|
498
543
|
runtime: app.runtime,
|
package/dist/proxy/wsPatch.js
CHANGED
|
@@ -19,28 +19,6 @@ async function readFrame(reader, maximum) {
|
|
|
19
19
|
throw new Error("WebSocket frame exceeds the proxy limit");
|
|
20
20
|
return { opcode: header[0], payload: await reader.readExactly(length) };
|
|
21
21
|
}
|
|
22
|
-
class EventListeners {
|
|
23
|
-
values = new Map();
|
|
24
|
-
add(type, listener) {
|
|
25
|
-
const entries = this.values.get(type) ?? new Set();
|
|
26
|
-
entries.add(listener);
|
|
27
|
-
this.values.set(type, entries);
|
|
28
|
-
}
|
|
29
|
-
remove(type, listener) { this.values.get(type)?.delete(listener); }
|
|
30
|
-
dispatch(type, event, target) {
|
|
31
|
-
for (const listener of this.values.get(type) ?? []) {
|
|
32
|
-
try {
|
|
33
|
-
if (typeof listener === "function")
|
|
34
|
-
listener.call(target, event);
|
|
35
|
-
else
|
|
36
|
-
listener.handleEvent(event);
|
|
37
|
-
}
|
|
38
|
-
catch {
|
|
39
|
-
// Event listener failures do not corrupt the transport state.
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
22
|
function limit(name, input, fallback) {
|
|
45
23
|
const value = input ?? fallback;
|
|
46
24
|
if (!Number.isSafeInteger(value) || value <= 0)
|
|
@@ -64,7 +42,7 @@ export function installWebSocketPatch(options) {
|
|
|
64
42
|
const remotePort = url.port || defaultPort(url.protocol);
|
|
65
43
|
return url.hostname === location.hostname && remotePort === localPort;
|
|
66
44
|
});
|
|
67
|
-
class ProxyWebSocket {
|
|
45
|
+
class ProxyWebSocket extends EventTarget {
|
|
68
46
|
static CONNECTING = 0;
|
|
69
47
|
static OPEN = 1;
|
|
70
48
|
static CLOSING = 2;
|
|
@@ -79,28 +57,51 @@ export function installWebSocketPatch(options) {
|
|
|
79
57
|
extensions = "";
|
|
80
58
|
protocol = "";
|
|
81
59
|
binaryType = "blob";
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
60
|
+
properties = new Map();
|
|
61
|
+
notifyProperty = (event) => {
|
|
62
|
+
try {
|
|
63
|
+
this.properties.get(event.type)?.call(this, event);
|
|
64
|
+
}
|
|
65
|
+
catch { /* User handlers are isolated. */ }
|
|
66
|
+
};
|
|
67
|
+
setProperty(type, value) {
|
|
68
|
+
if (typeof value === "function") {
|
|
69
|
+
this.properties.set(type, value);
|
|
70
|
+
this.addEventListener(type, this.notifyProperty);
|
|
71
|
+
}
|
|
72
|
+
else {
|
|
73
|
+
this.properties.delete(type);
|
|
74
|
+
this.removeEventListener(type, this.notifyProperty);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
get onopen() { return this.properties.get("open") ?? null; }
|
|
78
|
+
set onopen(value) { this.setProperty("open", value); }
|
|
79
|
+
get onmessage() { return this.properties.get("message") ?? null; }
|
|
80
|
+
set onmessage(value) { this.setProperty("message", value); }
|
|
81
|
+
get onerror() { return this.properties.get("error") ?? null; }
|
|
82
|
+
set onerror(value) { this.setProperty("error", value); }
|
|
83
|
+
get onclose() { return this.properties.get("close") ?? null; }
|
|
84
|
+
set onclose(value) { this.setProperty("close", value); }
|
|
87
85
|
abort = new AbortController();
|
|
88
86
|
stream;
|
|
89
87
|
writes = Promise.resolve();
|
|
88
|
+
pendingMessages = 0;
|
|
90
89
|
closeTimer;
|
|
91
90
|
constructor(input, protocols) {
|
|
91
|
+
super();
|
|
92
92
|
const url = new URL(String(input), globalThis.location?.href);
|
|
93
93
|
if (!shouldProxy(url))
|
|
94
94
|
return new NativeWebSocket(input, protocols);
|
|
95
95
|
this.url = url.toString();
|
|
96
96
|
void this.connect(url, protocols);
|
|
97
97
|
}
|
|
98
|
-
addEventListener(type, listener) { this.listeners.add(type, listener); }
|
|
99
|
-
removeEventListener(type, listener) { this.listeners.remove(type, listener); }
|
|
100
|
-
dispatchEvent(event) { this.listeners.dispatch(event.type, event, this); return !event.defaultPrevented; }
|
|
101
98
|
send(data) {
|
|
102
99
|
if (this.readyState !== ProxyWebSocket.OPEN || this.stream === undefined)
|
|
103
100
|
throw new DOMException("WebSocket is not open", "InvalidStateError");
|
|
101
|
+
if (this.pendingMessages >= 1024) {
|
|
102
|
+
this.fail();
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
104
105
|
let opcode;
|
|
105
106
|
let bytes;
|
|
106
107
|
let source;
|
|
@@ -133,8 +134,9 @@ export function installWebSocketPatch(options) {
|
|
|
133
134
|
this.fail();
|
|
134
135
|
return;
|
|
135
136
|
}
|
|
136
|
-
this.bufferedAmount += bytes;
|
|
137
137
|
const snapshot = source instanceof Uint8Array && opcode === 2 ? source.slice() : source;
|
|
138
|
+
this.pendingMessages++;
|
|
139
|
+
this.bufferedAmount += bytes;
|
|
138
140
|
const stream = this.stream;
|
|
139
141
|
this.writes = this.writes.then(async () => {
|
|
140
142
|
this.abort.signal.throwIfAborted();
|
|
@@ -142,7 +144,10 @@ export function installWebSocketPatch(options) {
|
|
|
142
144
|
await writeFrame(stream, opcode, payload, maxFrameBytes, { signal: this.abort.signal });
|
|
143
145
|
})
|
|
144
146
|
.catch(() => this.fail())
|
|
145
|
-
.finally(() => {
|
|
147
|
+
.finally(() => {
|
|
148
|
+
this.pendingMessages--;
|
|
149
|
+
this.bufferedAmount = Math.max(0, this.bufferedAmount - bytes);
|
|
150
|
+
});
|
|
146
151
|
}
|
|
147
152
|
close(code, reason = "") {
|
|
148
153
|
if (this.readyState === ProxyWebSocket.CLOSED || this.readyState === ProxyWebSocket.CLOSING)
|
|
@@ -171,10 +176,14 @@ export function installWebSocketPatch(options) {
|
|
|
171
176
|
protocols: typeof protocols === "string" ? [protocols] : protocols ?? [],
|
|
172
177
|
signal: this.abort.signal,
|
|
173
178
|
});
|
|
179
|
+
if (this.readyState !== ProxyWebSocket.CONNECTING) {
|
|
180
|
+
await opened.stream.reset();
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
174
183
|
this.stream = opened.stream;
|
|
175
184
|
this.protocol = opened.protocol;
|
|
176
185
|
this.readyState = ProxyWebSocket.OPEN;
|
|
177
|
-
this.
|
|
186
|
+
this.dispatchEvent(new Event("open"));
|
|
178
187
|
await this.readLoop(opened.stream);
|
|
179
188
|
}
|
|
180
189
|
catch {
|
|
@@ -186,18 +195,18 @@ export function installWebSocketPatch(options) {
|
|
|
186
195
|
while (this.readyState !== ProxyWebSocket.CLOSED) {
|
|
187
196
|
const frame = await readFrame(reader, maxFrameBytes);
|
|
188
197
|
if (frame.opcode === 9) {
|
|
189
|
-
this.writes = this.writes.then(
|
|
198
|
+
this.writes = this.writes.then(() => writeFrame(stream, 10, frame.payload, maxFrameBytes, { signal: this.abort.signal }));
|
|
199
|
+
await this.writes;
|
|
190
200
|
}
|
|
191
201
|
else if (frame.opcode === 8) {
|
|
192
202
|
if (frame.payload.length === 1)
|
|
193
203
|
throw new Error("invalid WebSocket close frame");
|
|
194
|
-
const code = frame.payload.length >= 2 ? readU16(frame.payload) :
|
|
204
|
+
const code = frame.payload.length >= 2 ? readU16(frame.payload) : 1005;
|
|
195
205
|
const reason = frame.payload.length > 2 ? decoder.decode(frame.payload.subarray(2)) : "";
|
|
196
206
|
const peerInitiated = this.readyState === ProxyWebSocket.OPEN;
|
|
197
207
|
this.readyState = ProxyWebSocket.CLOSING;
|
|
198
|
-
if (this.closeTimer !== undefined)
|
|
199
|
-
clearTimeout(this.closeTimer);
|
|
200
208
|
if (peerInitiated) {
|
|
209
|
+
this.closeTimer = setTimeout(() => this.fail(), closeHandshakeTimeoutMs);
|
|
201
210
|
this.writes = this.writes.then(async () => await writeFrame(stream, 8, frame.payload, maxFrameBytes));
|
|
202
211
|
}
|
|
203
212
|
await this.writes;
|
|
@@ -205,24 +214,16 @@ export function installWebSocketPatch(options) {
|
|
|
205
214
|
return;
|
|
206
215
|
}
|
|
207
216
|
else if (frame.opcode === 1) {
|
|
208
|
-
this.
|
|
217
|
+
this.dispatchEvent(new MessageEvent("message", { data: decoder.decode(frame.payload) }));
|
|
209
218
|
}
|
|
210
219
|
else if (frame.opcode === 2) {
|
|
211
220
|
const data = this.binaryType === "arraybuffer"
|
|
212
221
|
? frame.payload.buffer
|
|
213
222
|
: new Blob([frame.payload]);
|
|
214
|
-
this.
|
|
223
|
+
this.dispatchEvent(new MessageEvent("message", { data }));
|
|
215
224
|
}
|
|
216
225
|
}
|
|
217
226
|
}
|
|
218
|
-
emit(type, event) {
|
|
219
|
-
const callback = this[`on${type}`];
|
|
220
|
-
try {
|
|
221
|
-
callback?.call(this, event);
|
|
222
|
-
}
|
|
223
|
-
catch { /* User event handlers are isolated. */ }
|
|
224
|
-
this.listeners.dispatch(type, event, this);
|
|
225
|
-
}
|
|
226
227
|
fail() {
|
|
227
228
|
if (this.readyState === ProxyWebSocket.CLOSED)
|
|
228
229
|
return;
|
|
@@ -230,8 +231,8 @@ export function installWebSocketPatch(options) {
|
|
|
230
231
|
clearTimeout(this.closeTimer);
|
|
231
232
|
this.readyState = ProxyWebSocket.CLOSED;
|
|
232
233
|
this.bufferedAmount = 0;
|
|
233
|
-
this.
|
|
234
|
-
this.
|
|
234
|
+
this.dispatchEvent(new Event("error"));
|
|
235
|
+
this.dispatchEvent(new CloseEvent("close", { code: 1006, reason: "proxy WebSocket failed", wasClean: false }));
|
|
235
236
|
const stream = this.stream;
|
|
236
237
|
this.stream = undefined;
|
|
237
238
|
this.abort.abort();
|
|
@@ -244,11 +245,28 @@ export function installWebSocketPatch(options) {
|
|
|
244
245
|
clearTimeout(this.closeTimer);
|
|
245
246
|
this.readyState = ProxyWebSocket.CLOSED;
|
|
246
247
|
this.bufferedAmount = 0;
|
|
247
|
-
this.
|
|
248
|
+
this.dispatchEvent(new CloseEvent("close", { code, reason, wasClean: true }));
|
|
248
249
|
const stream = this.stream;
|
|
249
250
|
this.stream = undefined;
|
|
250
251
|
this.abort.abort();
|
|
251
|
-
|
|
252
|
+
if (stream)
|
|
253
|
+
void this.finishStream(stream);
|
|
254
|
+
}
|
|
255
|
+
async finishStream(stream) {
|
|
256
|
+
const timer = setTimeout(() => { void stream.reset().catch(() => undefined); }, closeHandshakeTimeoutMs);
|
|
257
|
+
try {
|
|
258
|
+
await stream.closeWrite();
|
|
259
|
+
if (await stream.read() !== null)
|
|
260
|
+
await stream.reset();
|
|
261
|
+
else
|
|
262
|
+
await stream.close();
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
await stream.reset().catch(() => undefined);
|
|
266
|
+
}
|
|
267
|
+
finally {
|
|
268
|
+
clearTimeout(timer);
|
|
269
|
+
}
|
|
252
270
|
}
|
|
253
271
|
}
|
|
254
272
|
globalThis.WebSocket = ProxyWebSocket;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { RpcRouter } from "../rpc/server.js";
|
|
2
2
|
import { assertRpcError, assertRpcTypeId } from "../rpc/validate.js";
|
|
3
|
+
import { raceWithSignal } from "../utils/abort.js";
|
|
3
4
|
import { HandlerRegistrationError, StreamHandlers, freezeStreamHandlers, registerStreamHandlersAtomically, } from "../public/streamHandlers.js";
|
|
4
5
|
export { HandlerRegistrationError } from "../public/streamHandlers.js";
|
|
5
6
|
const bindingKey = Symbol("session handler binding");
|
|
@@ -65,7 +66,7 @@ function registerRPC(state, typeId, handler) {
|
|
|
65
66
|
throw new HandlerRegistrationError("already_registered");
|
|
66
67
|
}
|
|
67
68
|
state.requests.set(typeId, async (payload, signal, context) => {
|
|
68
|
-
const result = await handler(payload, handlerRequest(typeId, signal, context));
|
|
69
|
+
const result = await raceWithSignal(handler(payload, handlerRequest(typeId, signal, context)), signal);
|
|
69
70
|
return "error" in result ? { payload: null, error: validRPCError(result.error) } : { payload: result.payload };
|
|
70
71
|
});
|
|
71
72
|
}
|
|
@@ -74,7 +75,7 @@ function registerNotification(state, typeId, handler) {
|
|
|
74
75
|
if (state.requests.has(typeId) || state.notifications.has(typeId)) {
|
|
75
76
|
throw new HandlerRegistrationError("already_registered");
|
|
76
77
|
}
|
|
77
|
-
state.notifications.set(typeId, (payload, signal, context) => handler(payload, handlerRequest(typeId, signal, context)));
|
|
78
|
+
state.notifications.set(typeId, (payload, signal, context) => raceWithSignal(Promise.resolve(handler(payload, handlerRequest(typeId, signal, context))), signal));
|
|
78
79
|
}
|
|
79
80
|
function validateRPCRegistration(typeId, handler) {
|
|
80
81
|
try {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function raceWithSignal<T>(operation: Promise<T>, signal?: AbortSignal): Promise<T>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export async function raceWithSignal(operation, signal) {
|
|
2
|
+
if (signal === undefined)
|
|
3
|
+
return await operation;
|
|
4
|
+
if (signal.aborted) {
|
|
5
|
+
void operation.catch(() => undefined);
|
|
6
|
+
throw signal.reason ?? new DOMException("The operation was aborted", "AbortError");
|
|
7
|
+
}
|
|
8
|
+
return await new Promise((resolve, reject) => {
|
|
9
|
+
const abort = () => reject(signal.reason ?? new DOMException("The operation was aborted", "AbortError"));
|
|
10
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
11
|
+
void operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
12
|
+
});
|
|
13
|
+
}
|
|
@@ -12,6 +12,12 @@ export declare class ClaimedArtifactLeaseV3 {
|
|
|
12
12
|
private constructor();
|
|
13
13
|
}
|
|
14
14
|
export declare function claimArtifactLeaseV3(lease: ArtifactLeaseV3): ClaimedArtifactLeaseV3;
|
|
15
|
+
export declare function leaseScopeV3(lease: ArtifactLeaseV3, name: string): Readonly<{
|
|
16
|
+
scope: string;
|
|
17
|
+
scope_version: number;
|
|
18
|
+
critical: boolean;
|
|
19
|
+
payload: Readonly<Record<string, unknown>>;
|
|
20
|
+
}> | undefined;
|
|
15
21
|
/** Local routing mistakes must not claim, retire or spend the invitation. */
|
|
16
22
|
export declare function claimConnectionLeaseV3(lease: ArtifactLeaseV3, ingress?: string): ClaimedArtifactLeaseV3;
|
|
17
23
|
export declare function claimedArtifactV3(claim: ClaimedArtifactLeaseV3): ArtifactV3;
|
package/dist/v3/artifactLease.js
CHANGED
|
@@ -48,6 +48,12 @@ export function claimArtifactLeaseV3(lease) {
|
|
|
48
48
|
claimStates.set(claim, state);
|
|
49
49
|
return Object.freeze(claim);
|
|
50
50
|
}
|
|
51
|
+
export function leaseScopeV3(lease, name) {
|
|
52
|
+
const state = leaseStates.get(lease);
|
|
53
|
+
if (state === undefined || state.status !== "idle")
|
|
54
|
+
throw new ArtifactLeaseV3Error();
|
|
55
|
+
return state.artifact.scoped.find(entry => entry.scope === name);
|
|
56
|
+
}
|
|
51
57
|
/** Local routing mistakes must not claim, retire or spend the invitation. */
|
|
52
58
|
export function claimConnectionLeaseV3(lease, ingress) {
|
|
53
59
|
const state = leaseStates.get(lease);
|
package/dist/v3/contract.d.ts
CHANGED
|
@@ -23,6 +23,7 @@ export type InternalSessionTerminationV3 = Readonly<{
|
|
|
23
23
|
}>;
|
|
24
24
|
export type SessionV3 = Session;
|
|
25
25
|
export interface InternalByteStreamV3 {
|
|
26
|
+
readonly resetSignal?: AbortSignal;
|
|
26
27
|
readonly id: bigint;
|
|
27
28
|
readonly kind: string;
|
|
28
29
|
readonly terminalError: Error | undefined;
|
package/dist/v3/nodeRuntime.js
CHANGED
|
@@ -73,31 +73,16 @@ export async function connectNodeTLSSocketV3(candidate, attemptNowUnixSeconds, o
|
|
|
73
73
|
ALPNProtocols: ["http/1.1"],
|
|
74
74
|
rejectUnauthorized: policy.mode === "ca",
|
|
75
75
|
...(policy.mode === "ca"
|
|
76
|
-
?
|
|
77
|
-
? {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
: {
|
|
87
|
-
servername: host,
|
|
88
|
-
checkServerIdentity: (_servername, certificate) => {
|
|
89
|
-
// Node's historical hostname verifier may fall back to CN when the
|
|
90
|
-
// certificate has no subjectAltName. Transport v5 requires a DNS-ID
|
|
91
|
-
// or IP-ID SAN; CN alone is never an identity proof.
|
|
92
|
-
const subjectAltName = certificate.subjectaltname;
|
|
93
|
-
if (typeof subjectAltName !== "string" || !/(?:^|,\s*)(?:DNS|IP Address):/.test(subjectAltName)) {
|
|
94
|
-
return Object.assign(new Error("certificate is missing a DNS-ID or IP-ID subjectAltName"), {
|
|
95
|
-
code: "ERR_TLS_CERT_ALTNAME_INVALID",
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
return tlsCheckServerIdentity(host, certificate);
|
|
99
|
-
},
|
|
100
|
-
})
|
|
76
|
+
? {
|
|
77
|
+
...(isIPAddress(host) ? {} : { servername: host }),
|
|
78
|
+
checkServerIdentity: (_servername, certificate) => {
|
|
79
|
+
const leaf = new X509Certificate(certificate.raw);
|
|
80
|
+
const matched = isIPAddress(host) ? leaf.checkIP(host) : leaf.checkHost(host, { subject: "never", partialWildcards: false });
|
|
81
|
+
return matched === undefined ? Object.assign(new Error("certificate subjectAltName does not match the host"), {
|
|
82
|
+
code: "ERR_TLS_CERT_ALTNAME_INVALID",
|
|
83
|
+
}) : tlsCheckServerIdentity(host, certificate);
|
|
84
|
+
},
|
|
85
|
+
}
|
|
101
86
|
: isIPAddress(host)
|
|
102
87
|
? { checkServerIdentity: (_servername, certificate) => tlsCheckServerIdentity(host, certificate) }
|
|
103
88
|
: { servername: host }),
|
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import type { ByteStreamV3 } from "./contract.js";
|
|
2
|
+
export declare function incomingResetSignal(stream: ByteStreamV3): AbortSignal | undefined;
|
package/dist/v3/publicSession.js
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { SessionError } from "./contract.js";
|
|
2
2
|
import { createStreamMetadataV3, streamMetadataValuesV3 } from "./streamMetadata.js";
|
|
3
3
|
import { assertRpcTypeId } from "../rpc/validate.js";
|
|
4
|
+
import { raceWithSignal } from "../utils/abort.js";
|
|
4
5
|
const internals = new WeakMap();
|
|
6
|
+
const incomingOwners = new WeakMap();
|
|
7
|
+
export function incomingResetSignal(stream) {
|
|
8
|
+
return incomingOwners.get(stream)?.resetSignal;
|
|
9
|
+
}
|
|
5
10
|
/** @internal Read the actual session and stream owners for the capacity inventory. */
|
|
6
11
|
export function sessionInventory(session) {
|
|
7
12
|
const value = internals.get(session)?.runtimeInventory?.();
|
|
@@ -12,11 +17,13 @@ export function sessionInventory(session) {
|
|
|
12
17
|
/** @internal */
|
|
13
18
|
export function projectSessionV3(session) {
|
|
14
19
|
const notificationOwner = {
|
|
20
|
+
lifetime: new AbortController(),
|
|
15
21
|
subscriptions: new Set(),
|
|
16
22
|
closed: false,
|
|
17
23
|
};
|
|
18
24
|
const clearNotificationSubscriptions = () => {
|
|
19
25
|
notificationOwner.closed = true;
|
|
26
|
+
notificationOwner.lifetime.abort();
|
|
20
27
|
for (const unsubscribe of [...notificationOwner.subscriptions])
|
|
21
28
|
unsubscribe();
|
|
22
29
|
};
|
|
@@ -49,10 +56,12 @@ export function projectSessionV3(session) {
|
|
|
49
56
|
async acceptStream(options) {
|
|
50
57
|
try {
|
|
51
58
|
const incoming = await session.acceptStream(options);
|
|
59
|
+
const stream = projectByteStreamV3(incoming.stream);
|
|
60
|
+
incomingOwners.set(stream, incoming.stream);
|
|
52
61
|
return Object.freeze({
|
|
53
62
|
kind: incoming.kind,
|
|
54
63
|
metadata: createStreamMetadataV3(incoming.metadata),
|
|
55
|
-
stream
|
|
64
|
+
stream,
|
|
56
65
|
});
|
|
57
66
|
}
|
|
58
67
|
catch (error) {
|
|
@@ -203,7 +212,7 @@ function projectRpcPeerV3(peer, notificationOwner) {
|
|
|
203
212
|
if (!subscribed)
|
|
204
213
|
return;
|
|
205
214
|
try {
|
|
206
|
-
await handler(decoded);
|
|
215
|
+
await raceWithSignal(Promise.resolve(handler(decoded)), notificationOwner.lifetime.signal);
|
|
207
216
|
}
|
|
208
217
|
catch {
|
|
209
218
|
// Notification handlers are isolated from RPC serving.
|
|
@@ -258,19 +267,6 @@ function validateJsonValue(value, ancestors) {
|
|
|
258
267
|
ancestors.delete(value);
|
|
259
268
|
}
|
|
260
269
|
}
|
|
261
|
-
async function raceWithSignal(operation, signal) {
|
|
262
|
-
if (signal === undefined)
|
|
263
|
-
return await operation;
|
|
264
|
-
if (signal.aborted) {
|
|
265
|
-
void operation.catch(() => undefined);
|
|
266
|
-
throw signal.reason ?? new DOMException("The operation was aborted", "AbortError");
|
|
267
|
-
}
|
|
268
|
-
return await new Promise((resolve, reject) => {
|
|
269
|
-
const abort = () => reject(signal.reason ?? new DOMException("The operation was aborted", "AbortError"));
|
|
270
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
271
|
-
void operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
272
|
-
});
|
|
273
|
-
}
|
|
274
270
|
function redactSessionError(error, signal) {
|
|
275
271
|
if (signal?.aborted && error === signal.reason) {
|
|
276
272
|
return new SessionError(error instanceof Error && error.name === "TimeoutError" ? "timeout" : "canceled");
|