@floegence/flowersec-core 6.0.0 → 6.1.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.
@@ -0,0 +1,187 @@
1
+ import { Agent } from "node:https";
2
+ import { Duplex } from "node:stream";
3
+ import { connect as tlsConnect } from "node:tls";
4
+ /** Internal shared route admission, including disposal of a late result. */
5
+ export async function openConnectionPath(path, hostname, port, signal) {
6
+ if (signal.aborted)
7
+ throw new Error("Connection path canceled");
8
+ return await new Promise((resolve, reject) => {
9
+ let settled = false;
10
+ const abort = () => {
11
+ if (settled)
12
+ return;
13
+ settled = true;
14
+ reject(new Error("Connection path canceled"));
15
+ };
16
+ signal.addEventListener("abort", abort, { once: true });
17
+ void Promise.resolve().then(async () => await path.connect({ hostname, port, signal })).then((stream) => {
18
+ if (!(stream instanceof Duplex))
19
+ throw new Error("Invalid connection path stream");
20
+ if (settled || signal.aborted) {
21
+ stream.destroy();
22
+ return;
23
+ }
24
+ settled = true;
25
+ signal.removeEventListener("abort", abort);
26
+ resolve(stream);
27
+ }).catch(() => {
28
+ signal.removeEventListener("abort", abort);
29
+ if (settled)
30
+ return;
31
+ settled = true;
32
+ reject(new Error("Connection path failed"));
33
+ });
34
+ });
35
+ }
36
+ /** Admitted providers retain their reservation until the actual route attempt exits. */
37
+ export async function openOwnedConnectionPath(path, hostname, port, signal) {
38
+ if (signal.aborted)
39
+ throw new Error("Connection path canceled");
40
+ const stream = await path.connect({ hostname, port, signal });
41
+ if (!(stream instanceof Duplex))
42
+ throw new Error("Invalid connection path stream");
43
+ if (signal.aborted || stream.destroyed) {
44
+ if (!stream.closed) {
45
+ const closed = new Promise(resolve => stream.once("close", resolve));
46
+ stream.on("error", () => undefined);
47
+ stream.destroy();
48
+ await closed;
49
+ }
50
+ throw new Error("Connection path canceled");
51
+ }
52
+ return stream;
53
+ }
54
+ /** HTTPS bootstrap and host bridges use the same explicit path as Session.
55
+ * The Agent preserves the requested host, CA verification and SNI. It provides
56
+ * no TLS bypass, redirects or direct-connect fallback. Destroying the Agent
57
+ * cancels route attempts as well as closing established sockets.
58
+ */
59
+ export function createConnectionPathAgent(options) {
60
+ const timeout = options.connectTimeoutMs ?? 10_000;
61
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || typeof options.connectionPath?.connect !== "function") {
62
+ throw new Error("Invalid connection path options");
63
+ }
64
+ return new ConnectionPathAgent(options, timeout);
65
+ }
66
+ // Node invokes this Agent hook for each ClientRequest; @types/node omits it.
67
+ const nativeAddRequest = Agent.prototype.addRequest;
68
+ function rejectUnassignedRequest(request, error) {
69
+ // An unassigned ClientRequest defers destroy errors until its Agent supplies
70
+ // the completion callback, including when no socket could be constructed.
71
+ request.onSocket(undefined, error);
72
+ }
73
+ class ConnectionPathAgent extends Agent {
74
+ #options;
75
+ #timeout;
76
+ #lifetime = new AbortController();
77
+ #requests = [];
78
+ #admitting = false;
79
+ // Node accounts asynchronous factories only after their callback. Admit the
80
+ // next request once its predecessor has an assigned socket, so native pool
81
+ // limits include every in-flight route without constructing TLS prematurely.
82
+ addRequest(request, options) {
83
+ if (this.#lifetime.signal.aborted || this.#options.signal?.aborted) {
84
+ rejectUnassignedRequest(request, new Error("Connection path canceled"));
85
+ return;
86
+ }
87
+ this.#requests.push({ request, options });
88
+ this.#drain();
89
+ }
90
+ #drain() {
91
+ if (this.#admitting)
92
+ return;
93
+ let next = this.#requests.shift();
94
+ while (next?.request.destroyed) {
95
+ rejectUnassignedRequest(next.request, new Error("Connection path canceled"));
96
+ next = this.#requests.shift();
97
+ }
98
+ if (next === undefined)
99
+ return;
100
+ const { request, options } = next;
101
+ this.#admitting = true;
102
+ let settled = false;
103
+ const advance = () => {
104
+ if (settled)
105
+ return;
106
+ settled = true;
107
+ request.off("socket", advance);
108
+ request.off("close", advance);
109
+ request.off("error", advance);
110
+ this.#admitting = false;
111
+ queueMicrotask(() => this.#drain());
112
+ };
113
+ request.once("socket", advance);
114
+ request.once("close", advance);
115
+ request.once("error", advance);
116
+ try {
117
+ nativeAddRequest.call(this, request, options);
118
+ }
119
+ catch (error) {
120
+ rejectUnassignedRequest(request, error instanceof Error ? error : new Error("Connection path failed"));
121
+ advance();
122
+ }
123
+ }
124
+ constructor(options, timeout) {
125
+ super({ keepAlive: true, maxCachedSessions: 0 });
126
+ this.#options = options;
127
+ this.#timeout = timeout;
128
+ }
129
+ createConnection(options, callback) {
130
+ if (callback === undefined)
131
+ throw new Error("Connection path Agent requires an asynchronous callback");
132
+ const fail = (error) => callback(error, undefined);
133
+ const hostname = options.host ?? options.servername;
134
+ const port = Number(options.port ?? 443);
135
+ if (typeof hostname !== "string" || hostname === "" || !Number.isSafeInteger(port) || port < 1 || port > 65535) {
136
+ queueMicrotask(() => fail(new Error("Invalid connection path target")));
137
+ return undefined;
138
+ }
139
+ const timeout = new AbortController();
140
+ const timer = setTimeout(() => timeout.abort(), this.#timeout);
141
+ const signals = [this.#lifetime.signal, timeout.signal];
142
+ if (this.#options.signal !== undefined)
143
+ signals.push(this.#options.signal);
144
+ if (options.signal !== undefined)
145
+ signals.push(options.signal);
146
+ const signal = AbortSignal.any(signals);
147
+ void openConnectionPath(this.#options.connectionPath, hostname, port, signal).then((transport) => {
148
+ if (signal.aborted) {
149
+ clearTimeout(timer);
150
+ transport.destroy();
151
+ fail(new Error("Connection path canceled"));
152
+ return;
153
+ }
154
+ // Only SDK-owned TLS options are accepted. Agent request overrides cannot
155
+ // turn off verification or replace the connection factory.
156
+ let socket;
157
+ try {
158
+ socket = tlsConnect({
159
+ host: hostname, port, socket: transport,
160
+ ...(hostname.includes(":") || /^\d+\.\d+\.\d+\.\d+$/u.test(hostname) ? {} : { servername: hostname }),
161
+ minVersion: "TLSv1.3", rejectUnauthorized: true,
162
+ ...(this.#options.ca === undefined ? {} : { ca: this.#options.ca }),
163
+ });
164
+ }
165
+ catch {
166
+ clearTimeout(timer);
167
+ transport.destroy();
168
+ fail(new Error("Connection path TLS failed"));
169
+ return;
170
+ }
171
+ transport.on("error", (error) => socket.destroy(error));
172
+ const abort = () => { socket.destroy(new Error("Connection path canceled")); };
173
+ signal.addEventListener("abort", abort, { once: true });
174
+ socket.once("secureConnect", () => { clearTimeout(timer); signal.removeEventListener("abort", abort); });
175
+ socket.once("close", () => { clearTimeout(timer); signal.removeEventListener("abort", abort); transport.destroy(); });
176
+ callback(null, socket);
177
+ }, () => { clearTimeout(timer); fail(new Error("Connection path failed")); });
178
+ // Node's asynchronous Agent factory reports exclusively via callback.
179
+ return undefined;
180
+ }
181
+ destroy() {
182
+ this.#lifetime.abort();
183
+ for (const { request } of this.#requests.splice(0))
184
+ rejectUnassignedRequest(request, new Error("Connection path canceled"));
185
+ super.destroy();
186
+ }
187
+ }
@@ -52,3 +52,5 @@ export type { NodeWSSTunnelClientListenerOptions, NodeNativeTunnelClientListener
52
52
  export type { NodeTunnelDialerOptions, TunnelEndpointDialerPreparationOptions } from "./endpointDialer.js";
53
53
  export { prepareTunnelEndpointDialer, TunnelEndpointDialerPreparation } from "./endpointDialer.js";
54
54
  export type { ProxyCredentialPolicy, ProxyCookieScope, ProxyCredentialAuthentication } from "./proxyCredentials.js";
55
+ export { createConnectionPathAgent } from "./connectionPath.js";
56
+ export type { NodeConnectionPath, ConnectionPathAgentOptions } from "./connectionPath.js";
@@ -24,3 +24,4 @@ export { createRegisteredPoolTunnelAuthority, RegisteredPoolTunnelAuthority } fr
24
24
  export { createRegisteredTunnelControlAuthority, RegisteredTunnelControlAuthority, createRegisteredPoolTunnelServer, createRegisteredLiveTunnelServer, RegisteredTunnelServer } from "./registeredTunnelControl.js";
25
25
  export { createRegisteredLiveTunnelControlAuthority, RegisteredLiveTunnelControlAuthority, createRegisteredLiveTunnelClientAuthorization } from "./registeredLiveTunnelControl.js";
26
26
  export { prepareTunnelEndpointDialer, TunnelEndpointDialerPreparation } from "./endpointDialer.js";
27
+ export { createConnectionPathAgent } from "./connectionPath.js";
@@ -1,3 +1,4 @@
1
+ import { type NodeConnectionPath } from "./connectionPath.js";
1
2
  import type { V4TransportEnvironment } from "../v4/public.js";
2
3
  import type { V4LiveAuthorizationConfig } from "../v4/runtime/liveAuthorization.js";
3
4
  export interface V4NodeLiveHTTPSOptions {
@@ -5,6 +6,7 @@ export interface V4NodeLiveHTTPSOptions {
5
6
  readonly baseURL: string;
6
7
  /** Host-resolved numeric address for that origin; no resolver is invoked. */
7
8
  readonly remoteAddress: string;
9
+ readonly connectionPath?: NodeConnectionPath;
8
10
  readonly authority: string;
9
11
  readonly tenant: string;
10
12
  readonly audience: string;
@@ -1,3 +1,4 @@
1
+ import { openOwnedConnectionPath } from "./connectionPath.js";
1
2
  import { constants, X509Certificate } from "node:crypto";
2
3
  import { Agent, request as httpsRequest } from "node:https";
3
4
  import { isIP } from "node:net";
@@ -42,6 +43,8 @@ function responseSize(response, maximum) {
42
43
  * verifies the signed ActivationAuthorization against its selected winner. */
43
44
  export function createV4NodeLiveHTTPS(environment, options) {
44
45
  const owner = originalEnvironment(environment);
46
+ requireControl(options.connectionPath === undefined || typeof options.connectionPath.connect === "function");
47
+ const connectionPath = options.connectionPath === undefined ? undefined : Object.freeze({ connect: options.connectionPath.connect.bind(options.connectionPath) });
45
48
  const input = options.baseURL;
46
49
  requireControl(typeof input === "string" && input.length > 0 && input.length <= 2048 && !/[\s%\\?#]/u.test(input));
47
50
  let url;
@@ -104,18 +107,21 @@ export function createV4NodeLiveHTTPS(environment, options) {
104
107
  requireControl(destination instanceof Uint8Array && destination.byteLength >= 1 && destination.byteLength <= 73728, "control_response_capacity");
105
108
  requireControl(active.size < maxConcurrentRequests, "resource_exhausted");
106
109
  const resources = owner.resources, reservation = resources.root.reserve({ owner: credentialOwner(resources, "node_live_https_request"), accounts: resources.accounts, charge });
107
- const controller = new AbortController();
110
+ const controller = new AbortController(), routeCancellation = new AbortController();
108
111
  active.add(controller);
112
+ let route, routeDone = Promise.resolve();
109
113
  let socket, agent, http, response;
110
114
  let timer, body, success = false, responseComplete = false;
111
115
  let socketDone = Promise.resolve(), requestDone = Promise.resolve(), responseDone = Promise.resolve(), writeDone = Promise.resolve();
112
116
  let failed, rejectPending;
113
117
  const stop = (code) => {
118
+ routeCancellation.abort();
114
119
  failed ??= new Error(code);
115
120
  rejectPending?.(failed);
116
121
  http?.destroy();
117
122
  response?.destroy();
118
123
  socket?.destroy();
124
+ route?.destroy();
119
125
  agent?.destroy();
120
126
  };
121
127
  const abort = () => { controller.abort(); }, aborted = () => stop("canceled");
@@ -153,6 +159,14 @@ export function createV4NodeLiveHTTPS(environment, options) {
153
159
  const tlsOptions = { host: remoteAddress, port, secureContext: context, minVersion: "TLSv1.3", maxVersion: "TLSv1.3",
154
160
  servername: isIP(host) ? "" : host, rejectUnauthorized: true, ALPNProtocols: ["http/1.1"],
155
161
  checkServerIdentity: (_name, certificate) => checkServerIdentity(host, certificate), highWaterMark: 16384, allowHalfOpen: false };
162
+ if (connectionPath !== undefined) {
163
+ route = await openOwnedConnectionPath(connectionPath, remoteAddress, port, routeCancellation.signal);
164
+ const transport = route;
165
+ routeDone = new Promise(resolve => transport.once("close", resolve));
166
+ transport.on("error", () => stop("control_transport_failed"));
167
+ guard();
168
+ tlsOptions.socket = transport;
169
+ }
156
170
  socket = connect(tlsOptions);
157
171
  const connection = socket;
158
172
  socketDone = new Promise(resolve => connection.once("close", () => { if (!responseComplete)
@@ -267,10 +281,11 @@ export function createV4NodeLiveHTTPS(environment, options) {
267
281
  http?.destroy();
268
282
  response?.destroy();
269
283
  socket?.destroy();
284
+ route?.destroy();
270
285
  agent?.destroy();
271
286
  // An aborted await is not native cleanup. Retain both byte buffers and
272
287
  // the original reservation through real write/request/socket callbacks.
273
- await Promise.all([writeDone, requestDone, responseDone, socketDone]);
288
+ await Promise.all([writeDone, requestDone, responseDone, socketDone, routeDone]);
274
289
  body?.fill(0);
275
290
  if (!success)
276
291
  destination.fill(0);
@@ -16,6 +16,10 @@ export interface RegisteredPoolTunnelAuthorityOptions {
16
16
  }>;
17
17
  readonly publicationMS: bigint;
18
18
  readonly serverAllow: NodePoolServerAllowReceiverOptions;
19
+ /** Keep the original Grant issuance transaction separate from the physical
20
+ * B preparation. Trusted local fixtures use this when route activation must
21
+ * precede the finite physical admission window. */
22
+ readonly deferPreparation?: boolean;
19
23
  }
20
24
  export interface RegisteredPoolTunnelMaterial extends GrantIssuanceInput {
21
25
  readonly clientGrant: Uint8Array;
@@ -27,9 +31,14 @@ export interface RegisteredPoolTunnelMaterial extends GrantIssuanceInput {
27
31
  export declare class RegisteredPoolTunnelAuthority {
28
32
  #private;
29
33
  constructor(token: symbol, options: RegisteredPoolTunnelAuthorityOptions);
30
- /** The physical listener and fixed server transfer backing exist before
31
- * entering the original Grant issuance transaction. */
34
+ /** The physical listener and fixed server transfer backing normally exist
35
+ * before the original Grant issuance transaction. Deferred callers may
36
+ * issue first, after their route activation hook, then start this one-shot
37
+ * physical preparation explicitly. */
32
38
  prepare(token: symbol): Promise<void>;
39
+ /** Start the deferred physical B preparation after the caller has made the
40
+ * original route available. The same one-shot ownership checks apply. */
41
+ startPreparation(): Promise<void>;
33
42
  acceptor(): Acceptor;
34
43
  poolServerAllowBinding(): PoolServerAllowBinding;
35
44
  /** Returning completes issuance and verified installation. B's activation
@@ -39,6 +39,7 @@ export class RegisteredPoolTunnelAuthority {
39
39
  #published = false;
40
40
  #consumed = false;
41
41
  #started = false;
42
+ #deferPreparation;
42
43
  #busy = false;
43
44
  #closed = false;
44
45
  #released = false;
@@ -68,6 +69,7 @@ export class RegisteredPoolTunnelAuthority {
68
69
  this.#serverOptions = Object.freeze({ ...options.server, policy: Object.freeze({ ...policy, authorities: Object.freeze([...policy.authorities]), cryptoProfiles: Object.freeze([...policy.cryptoProfiles]),
69
70
  ...(policy.tunnel === undefined ? {} : { tunnel: Object.freeze({ ...policy.tunnel }) }) }), listener: Object.freeze({ ...options.server.listener }) });
70
71
  this.#publicationMS = options.publicationMS;
72
+ this.#deferPreparation = options.deferPreparation === true;
71
73
  this.#done = new Promise(resolve => { this.#resolve = resolve; });
72
74
  this.#allowReceiver = new NodePoolServerAllowReceiver(this.#environment, options.serverAllow, (request, grant) => {
73
75
  this.#check();
@@ -90,11 +92,13 @@ export class RegisteredPoolTunnelAuthority {
90
92
  }
91
93
  }
92
94
  #check() { requireCredential(!this.#closed, "credential_closed"); this.#dependency.check(); }
93
- /** The physical listener and fixed server transfer backing exist before
94
- * entering the original Grant issuance transaction. */
95
+ /** The physical listener and fixed server transfer backing normally exist
96
+ * before the original Grant issuance transaction. Deferred callers may
97
+ * issue first, after their route activation hook, then start this one-shot
98
+ * physical preparation explicitly. */
95
99
  async prepare(token) {
96
100
  this.#check();
97
- requireCredential(token === capability && !this.#started);
101
+ requireCredential(token === capability && !this.#started && !this.#busy);
98
102
  this.#started = true;
99
103
  this.#busy = true;
100
104
  let work, reference;
@@ -146,13 +150,16 @@ export class RegisteredPoolTunnelAuthority {
146
150
  void this.close();
147
151
  }
148
152
  }
153
+ /** Start the deferred physical B preparation after the caller has made the
154
+ * original route available. The same one-shot ownership checks apply. */
155
+ async startPreparation() { await this.prepare(capability); }
149
156
  acceptor() { this.#check(); requireCredential(this.#acceptor !== undefined); return this.#acceptor; }
150
157
  poolServerAllowBinding() { this.#check(); return this.#allowReceiver.binding(); }
151
158
  /** Returning completes issuance and verified installation. B's activation
152
159
  * remains closed until A publishes after its own original TxA-P success. */
153
160
  async issue() {
154
161
  this.#check();
155
- requireCredential(this.#acceptor !== undefined && !this.#busy && !this.#issued && !this.#consumed, "credential_binding");
162
+ requireCredential((this.#acceptor !== undefined || this.#deferPreparation) && !this.#busy && !this.#issued && !this.#consumed, "credential_binding");
156
163
  this.#busy = true;
157
164
  this.#issued = true;
158
165
  let grants;
@@ -285,7 +292,8 @@ export class RegisteredPoolTunnelAuthority {
285
292
  export async function createRegisteredPoolTunnelAuthority(options) {
286
293
  const owner = new RegisteredPoolTunnelAuthority(capability, options);
287
294
  try {
288
- await owner.prepare(capability);
295
+ if (options.deferPreparation !== true)
296
+ await owner.prepare(capability);
289
297
  return owner;
290
298
  }
291
299
  catch (error) {
@@ -1,3 +1,4 @@
1
+ import { type NodeConnectionPath } from "./connectionPath.js";
1
2
  import type { IncomingMessage } from "node:http";
2
3
  import type { ClientSessionAdmission } from "../v4/runtime/sessionAdmission.js";
3
4
  import { type X509Certificate } from "node:crypto";
@@ -18,6 +19,8 @@ import type { TimeInterval } from "../v4/runtime/timeArithmetic.js";
18
19
  export interface V4NodeWSSOptions {
19
20
  /** One numeric address, captured before preparation. No resolver or retry. */
20
21
  readonly remoteAddress: string;
22
+ /** Optional mandatory route below unchanged target TLS; honors cancellation. */
23
+ readonly connectionPath?: NodeConnectionPath;
21
24
  readonly origin?: string;
22
25
  /** Immutable trust anchors for CA mode; pin mode uses only signed leaf DER. */
23
26
  readonly ca?: readonly (string | Uint8Array)[];
@@ -1,3 +1,4 @@
1
+ import { openOwnedConnectionPath } from "./connectionPath.js";
1
2
  import { createHash, constants } from "node:crypto";
2
3
  import { isIP } from "node:net";
3
4
  import { connect as tlsConnect, checkServerIdentity } from "node:tls";
@@ -128,6 +129,10 @@ export class NodeWSSCarrier {
128
129
  #done;
129
130
  #resolve;
130
131
  #socket;
132
+ #routeCancellation = new AbortController();
133
+ #routePending = false;
134
+ #routeStream;
135
+ #routeEnded = true;
131
136
  #pendingSocket;
132
137
  #pendingEnded = true;
133
138
  #websocket;
@@ -404,6 +409,22 @@ export class NodeWSSCarrier {
404
409
  ...(policy.mode === 0n ? { ca: options.ca.map(value => typeof value === "string" ? value : Buffer.from(value)) } : {}),
405
410
  checkServerIdentity: (_name, certificate) => checkServerIdentity(policy.host, certificate),
406
411
  highWaterMark: this.maximum, allowHalfOpen: false };
412
+ if (options.connectionPath !== undefined) {
413
+ this.#routePending = true;
414
+ try {
415
+ const route = await openOwnedConnectionPath(options.connectionPath, options.remoteAddress, policy.port, this.#routeCancellation.signal);
416
+ this.#routeStream = route;
417
+ this.#routeEnded = route.closed;
418
+ route.on("error", error => stop(error));
419
+ route.once("close", () => { this.#routeEnded = true; void this.close(); this.#finish(); });
420
+ guard();
421
+ tlsOptions.socket = route;
422
+ }
423
+ finally {
424
+ this.#routePending = false;
425
+ this.#finish();
426
+ }
427
+ }
407
428
  const socket = this.#socket = tlsConnect(tlsOptions);
408
429
  this.#socketEnded = false;
409
430
  socket.on("error", error => stop(error));
@@ -619,6 +640,8 @@ export class NodeWSSCarrier {
619
640
  close() {
620
641
  if (!this.#closing) {
621
642
  this.#closing = true;
643
+ this.#routeCancellation.abort();
644
+ this.#routeStream?.destroy();
622
645
  for (const bytes of this.#queue)
623
646
  bytes.fill(0);
624
647
  this.#queue = [];
@@ -632,7 +655,7 @@ export class NodeWSSCarrier {
632
655
  }
633
656
  retainDependency() { this.dependency.check(); requireCredential(this.role === "client" && !this.#closing && !this.#cleaned); this.ownsDependency = true; }
634
657
  #finish() {
635
- if (this.#cleaned || !this.#closing || !this.#pendingEnded || !this.#socketEnded || !this.#websocketEnded || this.#sending)
658
+ if (this.#cleaned || !this.#closing || this.#routePending || !this.#routeEnded || !this.#pendingEnded || !this.#socketEnded || !this.#websocketEnded || this.#sending)
636
659
  return;
637
660
  this.#cleaned = true;
638
661
  this.#validity = undefined;
@@ -645,6 +668,7 @@ export class NodeWSSCarrier {
645
668
  }
646
669
  export function nodeWSSAdmissionCosts(maxFrame, options, runtimeBytes) {
647
670
  requireCredential(typeof runtimeBytes === "bigint" && runtimeBytes > 0n && runtimeBytes <= 0xffffffffffffffffn, "configuration_capacity");
671
+ requireCredential(options.connectionPath === undefined || typeof options.connectionPath.connect === "function", "configuration_capacity");
648
672
  requireCredential(isIP(options.remoteAddress) !== 0 && Number.isSafeInteger(options.queueMessages) && options.queueMessages >= 1 && options.queueMessages <= 64 &&
649
673
  typeof options.runtimeBytes === "bigint" && options.runtimeBytes > 0n && options.runtimeBytes <= 0xffffffffffffffffn &&
650
674
  typeof options.nativeBytes === "bigint" && options.nativeBytes >= 1048576n && options.nativeBytes <= 0xffffffffffffffffn &&
@@ -1,4 +1,4 @@
1
- import type { ProxyStream } from "./stream.js";
1
+ import { type ProxyStream } from "./stream.js";
2
2
  import { SessionError, type OperationOptions } from "../public/contract.js";
3
3
  import { type ServiceWorkerControllerGuardConflictPolicy, type ServiceWorkerControllerGuardMonitorOptions, type ServiceWorkerControllerGuardRepairOptions } from "./controllerGuard.js";
4
4
  import type { ProxyRuntime } from "./types.js";
@@ -1,3 +1,4 @@
1
+ import { writeAll } from "./stream.js";
1
2
  import { StreamAdmission } from "./admission.js";
2
3
  import { enableResponseFlowControl, usesServiceWorkerResponseFlowControl } from "./serviceWorkerRuntime.js";
3
4
  import { fetchProxyPort, prepareProxyFetch } from "./fetch.js";
@@ -69,11 +70,12 @@ export class MessagePortByteStream {
69
70
  throw new SessionError("canceled");
70
71
  if (data.length === 0)
71
72
  return 0;
72
- if (data.length > MAX_BRIDGE_CHUNK_BYTES || this.buffered + data.length > MAX_BRIDGE_BUFFER_BYTES) {
73
+ const length = Math.min(data.length, MAX_BRIDGE_CHUNK_BYTES, MAX_BRIDGE_BUFFER_BYTES - this.buffered);
74
+ if (length <= 0) {
73
75
  throw new SessionError("resource_exhausted");
74
76
  }
75
77
  const id = this.nextWrite++;
76
- const copy = data.slice();
78
+ const copy = data.slice(0, length);
77
79
  this.buffered += copy.length;
78
80
  await new Promise((resolve, reject) => {
79
81
  const onAbort = () => this.settleWrite(id, new SessionError("canceled"));
@@ -91,7 +93,7 @@ export class MessagePortByteStream {
91
93
  this.settleWrite(id, new SessionError("operation_failed"));
92
94
  }
93
95
  });
94
- return data.length;
96
+ return length;
95
97
  }
96
98
  async closeWrite() {
97
99
  if (this.closed || this.writeClosed)
@@ -374,7 +376,7 @@ async function bridgeStreams(runtimeStream, port, signal) {
374
376
  await bridge.closeWrite();
375
377
  return;
376
378
  }
377
- await bridge.write(chunk, { signal: controller.signal });
379
+ await writeAll(bridge, chunk, { signal: controller.signal });
378
380
  }
379
381
  })().catch((error) => { controller.abort(error); void resetBoth(); throw error; });
380
382
  const right = (async () => {
@@ -384,9 +386,7 @@ async function bridgeStreams(runtimeStream, port, signal) {
384
386
  await runtimeStream.closeWrite();
385
387
  return;
386
388
  }
387
- let offset = 0;
388
- while (offset < chunk.length)
389
- offset += await runtimeStream.write(chunk.subarray(offset), { signal: controller.signal });
389
+ await writeAll(runtimeStream, chunk, { signal: controller.signal });
390
390
  }
391
391
  })().catch((error) => { controller.abort(error); void resetBoth(); throw error; });
392
392
  try {
@@ -745,8 +745,10 @@ export class V4EnvironmentRuntime {
745
745
  job.timer = setTimeout(timeout, timerChunk(original.remainingMS()));
746
746
  }
747
747
  catch {
748
- abort.abort();
748
+ // Abort synchronously notifies cancellation observers, so preserve
749
+ // the original deadline outcome before fencing the provider.
749
750
  rejectCanceled(new Error("deadline_exceeded"));
751
+ abort.abort();
750
752
  }
751
753
  };
752
754
  timeout();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floegence/flowersec-core",
3
- "version": "6.0.0",
3
+ "version": "6.1.0",
4
4
  "description": "Flowersec core TypeScript library for carrier-neutral encrypted sessions and multiplexed streams.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -75,7 +75,7 @@
75
75
  "@noble/ciphers": "2.4.0",
76
76
  "@noble/curves": "2.4.0",
77
77
  "@noble/hashes": "2.4.0",
78
- "@types/node": "26.4.0",
78
+ "@types/node": "26.6.3",
79
79
  "@types/ws": "8.18.1",
80
80
  "brotli-dec-wasm": "2.3.2",
81
81
  "tough-cookie": "6.0.2",
@@ -84,21 +84,21 @@
84
84
  },
85
85
  "devDependencies": {
86
86
  "@playwright/test": "1.62.1",
87
- "@typescript-eslint/eslint-plugin": "8.68.0",
88
- "@typescript-eslint/parser": "8.68.0",
87
+ "@typescript-eslint/eslint-plugin": "8.70.1",
88
+ "@typescript-eslint/parser": "8.70.1",
89
89
  "@typescript/native": "npm:typescript@7.0.2",
90
- "@vitest/coverage-v8": "4.1.11",
90
+ "@vitest/coverage-v8": "5.0.2",
91
91
  "ajv": "8.20.0",
92
92
  "ajv-formats": "3.0.1",
93
93
  "ajv-formats-draft2019": "1.6.1",
94
- "eslint": "10.9.1",
94
+ "eslint": "10.11.0",
95
95
  "tsx": "4.23.13",
96
96
  "typescript": "npm:@typescript/typescript6@6.0.2",
97
97
  "vite": "8.2.1",
98
- "vitest": "4.1.11"
98
+ "vitest": "5.0.2"
99
99
  },
100
100
  "optionalDependencies": {
101
- "@floegence/flowersec-node-native": "6.0.0"
101
+ "@floegence/flowersec-node-native": "6.1.0"
102
102
  },
103
- "flowersecSourceCommit": "0ba0ffb47bb698ad7c19e31ec9262eda0c69c106"
103
+ "flowersecSourceCommit": "bcd910a426b905a0453c3ce93607bd359117248d"
104
104
  }