@floegence/flowersec-core 7.5.0 → 8.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.
Files changed (40) hide show
  1. package/THIRD_PARTY_NOTICES.md +6 -5
  2. package/dist/browser/connectSessionV3.d.ts +3 -1
  3. package/dist/browser/connectSessionV3.js +7 -4
  4. package/dist/framing/jsonframe.d.ts +1 -1
  5. package/dist/framing/jsonframe.js +13 -6
  6. package/dist/node/acceptorV3.d.ts +1 -0
  7. package/dist/node/acceptorV3.js +2 -0
  8. package/dist/node/connectSessionV3.d.ts +7 -3
  9. package/dist/node/connectSessionV3.js +9 -6
  10. package/dist/public/contract.d.ts +1 -0
  11. package/dist/public/sessionHandlers.d.ts +3 -1
  12. package/dist/public/sessionHandlers.js +11 -3
  13. package/dist/rpc/server.js +3 -3
  14. package/dist/v3/artifact.js +1 -1
  15. package/dist/v3/artifactLease.d.ts +2 -1
  16. package/dist/v3/artifactLease.js +7 -2
  17. package/dist/v3/connectionController.d.ts +6 -1
  18. package/dist/v3/connectionController.js +63 -11
  19. package/dist/v3/connectorRPCLimits.d.ts +7 -0
  20. package/dist/v3/connectorRPCLimits.js +14 -0
  21. package/dist/v3/contract.d.ts +1 -0
  22. package/dist/v3/handshake.d.ts +9 -1
  23. package/dist/v3/handshake.js +53 -5
  24. package/dist/v3/protocol.d.ts +2 -1
  25. package/dist/v3/protocol.js +3 -1
  26. package/dist/v3/publicApi.d.ts +1 -0
  27. package/dist/v3/publicApi.js +7 -0
  28. package/dist/v3/publicSession.js +1 -0
  29. package/dist/v3/security.d.ts +4 -1
  30. package/dist/v3/security.js +3 -0
  31. package/dist/v3/serverAdmission.d.ts +2 -0
  32. package/dist/v3/serverAdmission.js +1 -0
  33. package/dist/v3/session.d.ts +5 -1
  34. package/dist/v3/session.js +25 -9
  35. package/dist/v3/sessionConnector.d.ts +5 -1
  36. package/dist/v3/sessionConnector.js +7 -4
  37. package/dist/v3/unreliableMessage.js +1 -1
  38. package/package.json +4 -3
  39. package/sbom/cyclonedx.json +68 -31
  40. package/sbom/spdx.json +75 -38
@@ -3,14 +3,15 @@
3
3
  This file is generated from the canonical Flowersec source dependency inventory for flowersec-ts.
4
4
  Do not edit it manually. License decisions are reviewed by the repository source license policy.
5
5
 
6
- - @floegence/flowersec-node-native 7.5.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
7
- - @floegence/flowersec-node-native-darwin-arm64 7.5.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
8
- - @floegence/flowersec-node-native-darwin-x64 7.5.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
9
- - @floegence/flowersec-node-native-linux-arm64-gnu 7.5.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
10
- - @floegence/flowersec-node-native-linux-x64-gnu 7.5.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
6
+ - @floegence/flowersec-node-native 8.1.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
7
+ - @floegence/flowersec-node-native-darwin-arm64 8.1.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
8
+ - @floegence/flowersec-node-native-darwin-x64 8.1.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
9
+ - @floegence/flowersec-node-native-linux-arm64-gnu 8.1.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
10
+ - @floegence/flowersec-node-native-linux-x64-gnu 8.1.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
11
11
  - @noble/ciphers 2.4.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.4.0.tgz)
12
12
  - @noble/curves 2.4.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz)
13
13
  - @noble/hashes 2.4.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz)
14
+ - @noble/post-quantum 0.7.1 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/@noble/post-quantum/-/post-quantum-0.7.1.tgz)
14
15
  - @types/node 26.4.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/@types/node/-/node-26.4.0.tgz)
15
16
  - punycode 2.3.1 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz)
16
17
  - tr46 7.0.0 (Declared: MIT; selected: MIT; source: https://registry.npmjs.org/tr46/-/tr46-7.0.0.tgz)
@@ -1,6 +1,6 @@
1
1
  import type { Session } from "../public/contract.js";
2
2
  import { RPCHandlers, type SessionHandlerBinding } from "../public/sessionHandlers.js";
3
- import { type ArtifactLeaseV3 } from "../v3/artifactLease.js";
3
+ import { type ArtifactLeaseV3, type KeyExchangeMode } from "../v3/artifactLease.js";
4
4
  import { type ArtifactSourceV3, type ConnectionControllerV3, type RotationDriver } from "../v3/connectionController.js";
5
5
  import { type PrivateLoopbackArtifactLeaseV1, type PrivateLoopbackArtifactSourceV1 } from "./privateLoopbackV1.js";
6
6
  import { type HTTPDirectArtifactLeaseV1, type HTTPDirectArtifactSourceV1 } from "./httpDirectV1.js";
@@ -14,6 +14,8 @@ type ControllerRPCOptions = Omit<RPCOptions, "rpcHandlers"> & Readonly<{
14
14
  }>;
15
15
  type TunnelOptions = Readonly<{
16
16
  tunnelIngressURL?: string;
17
+ keyExchange?: KeyExchangeMode;
18
+ enableHybridKeyExchange?: boolean;
17
19
  }>;
18
20
  export type SessionOptionsV3 = RPCOptions & TunnelOptions & Readonly<{
19
21
  signal?: AbortSignal;
@@ -1,6 +1,5 @@
1
1
  import { SDK_DEFAULTS } from "../defaults.js";
2
- import { rpcFrameLimit } from "../framing/jsonframe.js";
3
- import { rpcConcurrency } from "../rpc/server.js";
2
+ import { connectorRPCLimits } from "../v3/connectorRPCLimits.js";
4
3
  import { createRPCRouter, freezeRPCHandlers, RPCHandlers } from "../public/sessionHandlers.js";
5
4
  import { claimArtifactLeaseV3, retireArtifactLeaseV3, } from "../v3/artifactLease.js";
6
5
  import { createConnectionControllerV3 as createCoreControllerV3, } from "../v3/connectionController.js";
@@ -25,6 +24,8 @@ export async function createBrowserController(source, options, rotation) {
25
24
  const registry = await BrowserRuntimeCapabilityRegistryV3.create();
26
25
  const runtime = browserRuntime(registry, options);
27
26
  const coreOptions = {
27
+ keyExchange: options.keyExchange ?? "classic",
28
+ connectTimeoutMs: options.connectTimeoutMs ?? SDK_DEFAULTS.transport.connectTimeoutMs,
28
29
  ...(runtime.tunnelIngressURL === undefined ? {} : { tunnelIngressURL: runtime.tunnelIngressURL }),
29
30
  capabilitySnapshot: runtime.capabilitySnapshot,
30
31
  projectSessionFailure,
@@ -154,9 +155,9 @@ async function retireInnerLease(lease) {
154
155
  }
155
156
  }
156
157
  function rpcOptions(options) {
158
+ const limits = connectorRPCLimits(options);
157
159
  const handlers = options.rpcHandlers === undefined ? undefined : freezeRPCHandlers(options.rpcHandlers);
158
- return { maxRpcFrameBytes: rpcFrameLimit(options.maxRpcFrameBytes),
159
- maxConcurrentRpcRequests: rpcConcurrency(options.maxConcurrentRpcRequests),
160
+ return { ...limits,
160
161
  ...(handlers === undefined ? {} : { createRPCRouter: () => createRPCRouter(handlers) }) };
161
162
  }
162
163
  function requireControllerHandlers(options) {
@@ -173,6 +174,8 @@ function browserRuntime(registry, options) {
173
174
  capabilitySnapshot: () => registry.snapshot(),
174
175
  connectTimeoutMilliseconds,
175
176
  protocolRuntime: browserSessionRuntimeV3,
177
+ keyExchange: options.keyExchange ?? "classic",
178
+ enableHybridKeyExchange: options.enableHybridKeyExchange === true,
176
179
  ...(options.tunnelIngressURL === undefined ? {} : { tunnelIngressURL: options.tunnelIngressURL }),
177
180
  ...rpcOptions(options),
178
181
  dial: async (candidate, artifact, attemptNow, capability, signal) => {
@@ -12,7 +12,7 @@ type ReadExactlyFn = (n: number) => Promise<Uint8Array>;
12
12
  type ReadExactlyLike = Readonly<{
13
13
  readExactly: (n: number) => Promise<Uint8Array>;
14
14
  }>;
15
- export declare function writeJsonFrame(write: WriteFn | WriteLike, v: unknown, maxBytes?: number, rpc?: boolean): Promise<void>;
15
+ export declare function writeJsonFrame(write: WriteFn | WriteLike, v: unknown, maxBytes?: number, rpc?: boolean, overflow?: () => unknown): Promise<void>;
16
16
  export declare function readJsonFrame(readExactly: ReadExactlyFn | ReadExactlyLike, maxBytes: number): Promise<unknown>;
17
17
  export declare function readRpcFrame(readExactly: ReadExactlyFn | ReadExactlyLike, maxBytes: number): Promise<{
18
18
  value: unknown;
@@ -37,13 +37,10 @@ function normalizeReadExactly(readExactly) {
37
37
  return typeof readExactly === "function" ? readExactly : (n) => readExactly.readExactly(n);
38
38
  }
39
39
  // writeJsonFrame encodes a JSON payload with a 4-byte length prefix.
40
- export async function writeJsonFrame(write, v, maxBytes = 0, rpc = false) {
41
- const text = JSON.stringify(v);
42
- if (typeof text !== "string")
43
- throw new JsonFramingError("invalid JSON value");
40
+ function encodedLength(text, maxBytes) {
44
41
  let length = text.length;
45
42
  if (maxBytes > 0 && length > maxBytes)
46
- throw new JsonFramingError("frame too large");
43
+ return length;
47
44
  for (let i = 0; i < text.length; i++) {
48
45
  const code = text.charCodeAt(i);
49
46
  if (code < 0x80)
@@ -56,8 +53,18 @@ export async function writeJsonFrame(write, v, maxBytes = 0, rpc = false) {
56
53
  i++;
57
54
  }
58
55
  }
59
- if (length > 0xffffffff || (maxBytes > 0 && length > maxBytes))
56
+ return length;
57
+ }
58
+ export async function writeJsonFrame(write, v, maxBytes = 0, rpc = false, overflow) {
59
+ const text = JSON.stringify(v);
60
+ if (typeof text !== "string")
61
+ throw new JsonFramingError("invalid JSON value");
62
+ const length = encodedLength(text, maxBytes);
63
+ if (length > 0xffffffff || (maxBytes > 0 && length > maxBytes)) {
64
+ if (overflow)
65
+ return await writeJsonFrame(write, overflow(), maxBytes, rpc);
60
66
  throw new JsonFramingError("frame too large");
67
+ }
61
68
  const release = rpc ? reserveFrame(length, 4 + length + 2 * text.length) : noCharge;
62
69
  try {
63
70
  const frame = new Uint8Array(4 + length);
@@ -29,6 +29,7 @@ export type AcceptorListenerV3 = (NodeWebTransportListenerConfig & Readonly<{
29
29
  }>;
30
30
  }>;
31
31
  export type AcceptorOptionsV3 = Readonly<{
32
+ enableHybridKeyExchange?: boolean;
32
33
  listeners: readonly AcceptorListenerV3[];
33
34
  maxInboundStreams: number;
34
35
  /** Bounds admissions in progress and authenticated sessions awaiting accept. */
@@ -117,6 +117,7 @@ async function admit(state, carrier, ingress, providers) {
117
117
  };
118
118
  const internal = await acceptCarrierSessionV3(carrier, authorize, {
119
119
  runtime: nodeSessionRuntimeV3,
120
+ enableHybridKeyExchange: state.enableHybridKeyExchange,
120
121
  maxRpcFrameBytes: state.maxRpcFrameBytes,
121
122
  maxConcurrentRpcRequests: state.maxConcurrentRpcRequests,
122
123
  admissionReasons: state.admissionReasons,
@@ -191,6 +192,7 @@ export async function createAcceptorV3(options) {
191
192
  }
192
193
  const acceptor = new AcceptorV3();
193
194
  const state = {
195
+ enableHybridKeyExchange: options.enableHybridKeyExchange === true,
194
196
  listeners: Object.freeze(listeners),
195
197
  authorize: options.authorize,
196
198
  ...(options.resolveHandlers === undefined ? {} : { resolveHandlers: options.resolveHandlers }),
@@ -1,10 +1,12 @@
1
1
  import type { NodeConnectionPath } from "./connectionPath.js";
2
2
  import type { Session } from "../public/contract.js";
3
- import type { ArtifactLeaseV3 } from "../v3/artifactLease.js";
3
+ import type { ArtifactLeaseV3, KeyExchangeMode } from "../v3/artifactLease.js";
4
4
  import { type ArtifactSourceV3, type ConnectionControllerV3 } from "../v3/connectionController.js";
5
5
  import { RPCHandlers, type SessionHandlerBinding } from "./acceptor.js";
6
6
  export type NodeTLSRootsV3 = string | Uint8Array | readonly (string | Uint8Array)[];
7
7
  export type SessionOptionsV3 = Readonly<{
8
+ keyExchange?: KeyExchangeMode;
9
+ enableHybridKeyExchange?: boolean;
8
10
  webTransport?: boolean;
9
11
  origin?: string;
10
12
  roots?: NodeTLSRootsV3;
@@ -18,6 +20,8 @@ export type SessionOptionsV3 = Readonly<{
18
20
  tunnelIngressURL?: string;
19
21
  }>;
20
22
  export type ConnectionControllerOptionsV3 = Readonly<{
23
+ keyExchange?: KeyExchangeMode;
24
+ enableHybridKeyExchange?: boolean;
21
25
  webTransport?: boolean;
22
26
  origin?: string;
23
27
  roots?: NodeTLSRootsV3;
@@ -29,5 +33,5 @@ export type ConnectionControllerOptionsV3 = Readonly<{
29
33
  maxConcurrentRpcRequests?: number;
30
34
  tunnelIngressURL?: string;
31
35
  }>;
32
- export declare function connectV3(lease: ArtifactLeaseV3, options: SessionOptionsV3): Promise<Session>;
33
- export declare function createConnectionControllerV3(source: ArtifactSourceV3, options: ConnectionControllerOptionsV3): ConnectionControllerV3<Session>;
36
+ export declare function connectV3(lease: ArtifactLeaseV3, options?: SessionOptionsV3): Promise<Session>;
37
+ export declare function createConnectionControllerV3(source: ArtifactSourceV3, options?: ConnectionControllerOptionsV3): ConnectionControllerV3<Session>;
@@ -1,6 +1,5 @@
1
1
  import { SDK_DEFAULTS } from "../defaults.js";
2
- import { rpcFrameLimit } from "../framing/jsonframe.js";
3
- import { rpcConcurrency } from "../rpc/server.js";
2
+ import { connectorRPCLimits } from "../v3/connectorRPCLimits.js";
4
3
  import { createConnectionControllerV3 as createCoreControllerV3, } from "../v3/connectionController.js";
5
4
  import { connectNodeWebSocketV3, detectNodeRuntimeCapabilityV3, } from "../v3/nodeRuntime.js";
6
5
  import { attemptClaimedArtifactLeaseV3, connectArtifactLeaseWithRuntimeV3, } from "../v3/sessionConnector.js";
@@ -10,17 +9,19 @@ import { nodeSessionRuntimeV3 } from "../v3/nodeSessionRuntime.js";
10
9
  import { createNativeRawQuicDriver, createNativeWebTransportDriver, tryLoadNativeTransportAddon, } from "./nativeTransportAddon.js";
11
10
  import { createNodeRawQuicClientV3 } from "./rawQuicAdapterV3.js";
12
11
  import { createRPCRouter, freezeRPCHandlers, RPCHandlers, } from "./acceptor.js";
13
- export async function connectV3(lease, options) {
12
+ export async function connectV3(lease, options = {}) {
14
13
  validateWebTransportOptIn(options);
15
14
  return await connectArtifactLeaseWithRuntimeV3(lease, options, () => nodeRuntime(options));
16
15
  }
17
- export function createConnectionControllerV3(source, options) {
16
+ export function createConnectionControllerV3(source, options = {}) {
18
17
  validateWebTransportOptIn(options);
19
18
  if (options.rpcHandlers !== undefined && !(options.rpcHandlers instanceof RPCHandlers)) {
20
19
  throw new ConnectErrorV3("artifact_invalid", { kind: "terminal" });
21
20
  }
22
21
  const runtime = nodeRuntime(options);
23
22
  const coreOptions = {
23
+ keyExchange: options.keyExchange ?? "classic",
24
+ connectTimeoutMs: options.connectTimeoutMs ?? SDK_DEFAULTS.transport.connectTimeoutMs,
24
25
  ...(runtime.tunnelIngressURL === undefined ? {} : { tunnelIngressURL: runtime.tunnelIngressURL }),
25
26
  capabilitySnapshot: runtime.capabilitySnapshot,
26
27
  projectSessionFailure,
@@ -46,6 +47,7 @@ function nodeRuntime(options) {
46
47
  const rawQuic = addon === undefined ? undefined : createNativeRawQuicDriver(addon);
47
48
  const webTransport = addon !== undefined && options.webTransport === true ? createNativeWebTransportDriver(addon) : undefined;
48
49
  const capability = detectNodeRuntimeCapabilityV3(rawQuic !== undefined, options.origin !== undefined, webTransport !== undefined);
50
+ const limits = connectorRPCLimits(options);
49
51
  let rpcSnapshot;
50
52
  try {
51
53
  rpcSnapshot = options.rpcHandlers === undefined ? undefined : freezeRPCHandlers(options.rpcHandlers);
@@ -59,8 +61,9 @@ function nodeRuntime(options) {
59
61
  (candidate.carrier === "raw_quic" || options.origin !== undefined),
60
62
  connectTimeoutMilliseconds,
61
63
  protocolRuntime: nodeSessionRuntimeV3,
62
- maxRpcFrameBytes: rpcFrameLimit(options.maxRpcFrameBytes),
63
- maxConcurrentRpcRequests: rpcConcurrency(options.maxConcurrentRpcRequests),
64
+ keyExchange: options.keyExchange ?? "classic",
65
+ enableHybridKeyExchange: options.enableHybridKeyExchange === true,
66
+ ...limits,
64
67
  ...(options.tunnelIngressURL === undefined ? {} : { tunnelIngressURL: options.tunnelIngressURL }),
65
68
  ...(rpcSnapshot === undefined ? {} : { createRPCRouter: () => createRPCRouter(rpcSnapshot) }),
66
69
  dial: async (candidate, artifact, attemptNow, _capability, signal) => {
@@ -67,6 +67,7 @@ export type SessionTermination = Readonly<{
67
67
  peerCloseReceived?: true;
68
68
  }>;
69
69
  export interface Session {
70
+ readonly usesHybridKeyExchange?: boolean;
70
71
  readonly rpc: RpcPeer;
71
72
  readonly unreliableMessages?: UnreliableMessageChannel;
72
73
  openStream(kind: string, options?: StreamOpenOptions): Promise<ByteStream>;
@@ -30,7 +30,9 @@ export declare class RPCHandlers {
30
30
  constructor();
31
31
  /** Bind local state for one connect or accepted session. Reuse the registry across sessions. */
32
32
  forSession(context: object): SessionHandlerBinding<this>;
33
- handleRPC(typeId: number, handler: RPCHandler): void;
33
+ handleRPC(typeId: number, handler: RPCHandler, options?: Readonly<{
34
+ acceptsNotifications?: boolean;
35
+ }>): void;
34
36
  handleNotification(typeId: number, handler: NotificationHandler): void;
35
37
  }
36
38
  export declare class SessionHandlersV3 extends RPCHandlers {
@@ -14,8 +14,11 @@ export class RPCHandlers {
14
14
  throw new HandlerRegistrationError("invalid_handler");
15
15
  return Object.freeze({ [bindingKey]: Object.freeze({ handlers: this, context }) });
16
16
  }
17
- handleRPC(typeId, handler) {
18
- registerRPC(mutableRPCHandlerState(this), typeId, handler);
17
+ handleRPC(typeId, handler, options = {}) {
18
+ const acceptsNotifications = options.acceptsNotifications ?? false;
19
+ if (typeof acceptsNotifications !== "boolean")
20
+ throw new HandlerRegistrationError("invalid_handler");
21
+ registerRPC(mutableRPCHandlerState(this), typeId, handler, acceptsNotifications);
19
22
  }
20
23
  handleNotification(typeId, handler) {
21
24
  registerNotification(mutableRPCHandlerState(this), typeId, handler);
@@ -60,7 +63,7 @@ export function registerSessionStreamHandlersAtomically(handlers, entries) {
60
63
  const state = mutableSessionHandlerState(handlers);
61
64
  registerStreamHandlersAtomically(state.streams, entries);
62
65
  }
63
- function registerRPC(state, typeId, handler) {
66
+ function registerRPC(state, typeId, handler, acceptsNotifications) {
64
67
  validateRPCRegistration(typeId, handler);
65
68
  if (state.requests.has(typeId) || state.notifications.has(typeId)) {
66
69
  throw new HandlerRegistrationError("already_registered");
@@ -69,6 +72,11 @@ function registerRPC(state, typeId, handler) {
69
72
  const result = await raceWithSignal(handler(payload, handlerRequest(typeId, signal, context)), signal);
70
73
  return "error" in result ? { payload: null, error: validRPCError(result.error) } : { payload: result.payload };
71
74
  });
75
+ if (acceptsNotifications) {
76
+ state.notifications.set(typeId, async (payload, signal, context) => {
77
+ await raceWithSignal(handler(payload, handlerRequest(typeId, signal, context)), signal);
78
+ });
79
+ }
72
80
  }
73
81
  function registerNotification(state, typeId, handler) {
74
82
  validateRPCRegistration(typeId, handler);
@@ -229,10 +229,10 @@ export class RpcServer {
229
229
  payload: out.payload,
230
230
  ...(error != null ? { error } : {}),
231
231
  };
232
- await this.writeEnvelope(resp);
232
+ await this.writeEnvelope(resp, () => ({ ...resp, payload: null, error: { code: 413, message: "encoded RPC response exceeds write limit" } }));
233
233
  }
234
- async writeEnvelope(envelope) {
235
- const write = this.writeChain.then(() => writeJsonFrame(this.transport.write, envelope, this.options.maxFrameBytes, true));
234
+ async writeEnvelope(envelope, overflow) {
235
+ const write = this.writeChain.then(() => writeJsonFrame(this.transport.write, envelope, this.options.maxFrameBytes, true, overflow));
236
236
  this.writeChain = write;
237
237
  try {
238
238
  await write;
@@ -372,7 +372,7 @@ function validateSession(session) {
372
372
  let previous = 0;
373
373
  const suites = new Set();
374
374
  for (const suite of session.allowed_suites) {
375
- if ((suite !== 1 && suite !== 2) || suite <= previous || suites.has(suite)) {
375
+ if ((suite !== 1 && suite !== 2 && !(suite === 3 && session.allowed_suites.length === 1)) || suite <= previous || suites.has(suite)) {
376
376
  throw invalidArtifact("allowed suites");
377
377
  }
378
378
  previous = suite;
@@ -19,7 +19,8 @@ export declare function leaseScopeV3(lease: ArtifactLeaseV3, name: string): Read
19
19
  payload: Readonly<Record<string, unknown>>;
20
20
  }> | undefined;
21
21
  /** Local routing mistakes must not claim, retire or spend the invitation. */
22
- export declare function claimConnectionLeaseV3(lease: ArtifactLeaseV3, ingress?: string): ClaimedArtifactLeaseV3;
22
+ export type KeyExchangeMode = "classic" | "hybridRequired" | "hybridPreferred";
23
+ export declare function claimConnectionLeaseV3(lease: ArtifactLeaseV3, ingress?: string, mode?: KeyExchangeMode): ClaimedArtifactLeaseV3;
23
24
  export declare function claimedArtifactV3(claim: ClaimedArtifactLeaseV3): ArtifactV3;
24
25
  export declare function commitArtifactLeaseSpendV3(claim: ClaimedArtifactLeaseV3, signal?: AbortSignal): Promise<void>;
25
26
  export declare function retireArtifactLeaseV3(claim: ClaimedArtifactLeaseV3): Promise<void>;
@@ -1,5 +1,6 @@
1
1
  import { canonicalizeCandidatesV3 } from "./artifact.js";
2
2
  import { selectTunnelIngress } from "./tunnelIngress.js";
3
+ import { ConnectErrorV3 } from "./security.js";
3
4
  export class ArtifactLeaseV3Error extends Error {
4
5
  code = "already_consumed";
5
6
  constructor() {
@@ -54,12 +55,16 @@ export function leaseScopeV3(lease, name) {
54
55
  throw new ArtifactLeaseV3Error();
55
56
  return state.artifact.scoped.find(entry => entry.scope === name);
56
57
  }
57
- /** Local routing mistakes must not claim, retire or spend the invitation. */
58
- export function claimConnectionLeaseV3(lease, ingress) {
58
+ export function claimConnectionLeaseV3(lease, ingress, mode = "classic") {
59
59
  const state = leaseStates.get(lease);
60
60
  if (state === undefined || state.status !== "idle")
61
61
  throw new ArtifactLeaseV3Error();
62
62
  const path = state.artifact?.path;
63
+ if (mode !== "classic" && mode !== "hybridRequired" && mode !== "hybridPreferred")
64
+ throw new ConnectErrorV3("artifact_invalid", { kind: "terminal" });
65
+ if (path?.kind === "tunnel" && path.role === 2 ? mode !== "classic" : (state.artifact?.session?.default_suite === 3) !== (mode !== "classic")) {
66
+ throw new ConnectErrorV3("artifact_invalid", { kind: "terminal" });
67
+ }
63
68
  if (path?.kind === "tunnel" || (path?.kind === "direct" && ingress !== undefined)) {
64
69
  selectTunnelIngress(path.kind, canonicalizeCandidatesV3(path.kind, path.candidates).candidates, ingress);
65
70
  }
@@ -1,5 +1,5 @@
1
1
  import { type ArtifactV3, type CanonicalArtifactCandidateV3 } from "./artifact.js";
2
- import { type ArtifactLeaseV3, type ClaimedArtifactLeaseV3 } from "./artifactLease.js";
2
+ import { type ArtifactLeaseV3, type ClaimedArtifactLeaseV3, type KeyExchangeMode } from "./artifactLease.js";
3
3
  import { type CandidateFailureV3, type ControllerClockV3 } from "./controller.js";
4
4
  import { ConnectErrorV3, type RetryDispositionV3 } from "./security.js";
5
5
  import { type RuntimeCapabilityDescriptorV3 } from "./capability.js";
@@ -12,6 +12,9 @@ export type ArtifactSourceResultV3 = Readonly<{
12
12
  disposition: RetryDispositionV3;
13
13
  }>;
14
14
  export type ArtifactSourceV3 = Readonly<{
15
+ acquireForKeyExchange?(mode: "classic" | "hybridRequired", options: Readonly<{
16
+ signal: AbortSignal;
17
+ }>): Promise<ArtifactSourceResultV3>;
15
18
  acquire(options: Readonly<{
16
19
  signal: AbortSignal;
17
20
  }>): Promise<ArtifactSourceResultV3>;
@@ -77,6 +80,8 @@ export interface RotationDriver<Session> {
77
80
  stop(): Promise<void>;
78
81
  }
79
82
  export type ConnectionControllerOptionsV3 = Readonly<{
83
+ keyExchange?: KeyExchangeMode;
84
+ connectTimeoutMs?: number;
80
85
  tunnelIngressURL?: string;
81
86
  maximumAttempts?: number;
82
87
  clock?: ControllerClockV3;
@@ -1,7 +1,9 @@
1
1
  import { canonicalizeCandidatesV3, validateArtifactV3, } from "./artifact.js";
2
2
  import { artifactLeaseStateV3, claimArtifactLeaseV3, claimConnectionLeaseV3, claimedArtifactV3, retireArtifactLeaseV3, } from "./artifactLease.js";
3
+ import { canonicalizeJCSV3 } from "./jcs.js";
4
+ import { SDK_DEFAULTS } from "../defaults.js";
3
5
  import { ControllerCycleStateV3, ControllerRetryWaitV3, aggregateCandidateFailuresV3, blockPolicyRefreshTriggersV3, endpointKeyV3, filterBlockedCandidatesV3, selectReplacementCandidatesV3, } from "./controller.js";
4
- import { ConnectErrorV3, TransportFailureV3, validateRetryDispositionV3, } from "./security.js";
6
+ import { ConnectErrorV3, VerifiedHybridRefusalV3, TransportFailureV3, validateRetryDispositionV3, } from "./security.js";
5
7
  import { validateRuntimeCapabilityDescriptorV3, } from "./capability.js";
6
8
  const ARTIFACT_SOURCE_FAILURE_CODES_V3 = new Set([
7
9
  "artifact_invalid",
@@ -49,6 +51,8 @@ export class ConnectionControllerV3 {
49
51
  #source;
50
52
  #connector;
51
53
  #maximumAttempts;
54
+ #keyExchange;
55
+ #connectTimeout;
52
56
  #tunnelIngressURL;
53
57
  #nowUnixSeconds;
54
58
  #retry;
@@ -81,6 +85,11 @@ export class ConnectionControllerV3 {
81
85
  this.#source = source;
82
86
  this.#connector = connector;
83
87
  this.#maximumAttempts = maximumAttempts;
88
+ this.#keyExchange = options.keyExchange ?? "classic";
89
+ if (!["classic", "hybridRequired", "hybridPreferred"].includes(this.#keyExchange)) {
90
+ throw new TypeError("Unsupported Flowersec key exchange mode");
91
+ }
92
+ this.#connectTimeout = options.connectTimeoutMs ?? SDK_DEFAULTS.transport.connectTimeoutMs;
84
93
  this.#tunnelIngressURL = options.tunnelIngressURL;
85
94
  this.#cycle = new ControllerCycleStateV3(maximumAttempts);
86
95
  this.#nowUnixSeconds = options.nowUnixSeconds ?? (() => Math.floor(Date.now() / 1_000));
@@ -202,6 +211,7 @@ export class ConnectionControllerV3 {
202
211
  return closeOperation;
203
212
  }
204
213
  async #run() {
214
+ let fallback;
205
215
  let next = "primary";
206
216
  let pendingDisposition;
207
217
  let replacementContext;
@@ -240,7 +250,12 @@ export class ConnectionControllerV3 {
240
250
  this.#forceTerminalDisposition();
241
251
  return;
242
252
  }
243
- const acquisition = await this.#acquire();
253
+ const deadline = fallback?.deadline ?? performance.now() + this.#connectTimeout;
254
+ const mode = fallback || this.#keyExchange === "classic" ? "classic" : "hybridRequired";
255
+ const signal = fallback
256
+ ? AbortSignal.any([this.#lifetime.signal, AbortSignal.timeout(Math.max(0, Math.ceil(deadline - performance.now())))])
257
+ : this.#lifetime.signal;
258
+ const acquisition = await this.#acquire(mode, signal);
244
259
  if (this.#lifetime.signal.aborted) {
245
260
  if (acquisition.kind === "lease")
246
261
  await this.#claimAndRetire(acquisition.lease);
@@ -249,7 +264,9 @@ export class ConnectionControllerV3 {
249
264
  if (acquisition.kind === "failure") {
250
265
  const error = sourceFailure(acquisition);
251
266
  const ordinal = this.#cycle.recordFailedAcquisitionOrLease();
252
- this.#recordFailure("artifact", error.code, error.retryDisposition);
267
+ this.#recordFailure("artifact", error.code, fallback ? { kind: "terminal" } : error.retryDisposition);
268
+ if (fallback)
269
+ return;
253
270
  if (error.retryDisposition.kind === "terminal" || this.#attemptBudgetExhausted())
254
271
  return;
255
272
  pendingDisposition = error.retryDisposition;
@@ -258,7 +275,7 @@ export class ConnectionControllerV3 {
258
275
  }
259
276
  let claim;
260
277
  try {
261
- claim = claimConnectionLeaseV3(acquisition.lease, this.#tunnelIngressURL);
278
+ claim = claimConnectionLeaseV3(acquisition.lease, this.#tunnelIngressURL, mode);
262
279
  }
263
280
  catch (error) {
264
281
  this.#cycle.recordFailedAcquisitionOrLease();
@@ -278,6 +295,8 @@ export class ConnectionControllerV3 {
278
295
  let allCandidates;
279
296
  try {
280
297
  validateArtifactV3(artifact);
298
+ if (fallback && (performance.now() >= deadline || !validClassicReplacement(fallback.from, artifact)))
299
+ throw new TypeError("invalid fallback grant");
281
300
  this.#rotation?.accept(artifact);
282
301
  allCandidates = canonicalizeCandidatesV3(artifact.path.kind, artifact.path.candidates).candidates;
283
302
  }
@@ -294,8 +313,10 @@ export class ConnectionControllerV3 {
294
313
  catch {
295
314
  await retireArtifactLeaseV3(claim);
296
315
  this.#cycle.recordFailedAcquisitionOrLease();
297
- const error = new ConnectErrorV3("expired_artifact", { kind: "retryable" });
316
+ const error = new ConnectErrorV3("expired_artifact", { kind: fallback ? "terminal" : "retryable" });
298
317
  this.#recordFailure("connect", error.code, error.retryDisposition);
318
+ if (fallback)
319
+ return;
299
320
  if (this.#attemptBudgetExhausted())
300
321
  return;
301
322
  next = "primary";
@@ -322,7 +343,7 @@ export class ConnectionControllerV3 {
322
343
  artifact,
323
344
  candidates,
324
345
  claim,
325
- signal: this.#lifetime.signal,
346
+ signal,
326
347
  capability,
327
348
  assertArtifactFresh: () => this.#assertArtifactFresh(artifact),
328
349
  });
@@ -358,6 +379,7 @@ export class ConnectionControllerV3 {
358
379
  return;
359
380
  }
360
381
  if (result.kind === "established") {
382
+ fallback = undefined;
361
383
  if (artifactLeaseStateV3(claim) !== "consumed") {
362
384
  if (artifactLeaseStateV3(claim) === "claimed")
363
385
  await retireArtifactLeaseV3(claim);
@@ -406,6 +428,14 @@ export class ConnectionControllerV3 {
406
428
  pendingDisposition = disposition;
407
429
  continue;
408
430
  }
431
+ if (fallback) {
432
+ if (artifactLeaseStateV3(claim) === "claimed")
433
+ await retireArtifactLeaseV3(claim);
434
+ this.#cycle.recordFailedAcquisitionOrLease();
435
+ const failure = result.kind === "candidate_failures" ? aggregateCandidateFailuresV3(result.failures, false) : result.error;
436
+ this.#recordFailure("connect", failure === "policy_refresh" ? "transport_security_failed" : failure.code, { kind: "terminal" });
437
+ return;
438
+ }
409
439
  if (result.kind === "pre_spend_failure") {
410
440
  if (artifactLeaseStateV3(claim) !== "claimed") {
411
441
  this.#cycle.recordFailedAcquisitionOrLease();
@@ -437,6 +467,14 @@ export class ConnectionControllerV3 {
437
467
  };
438
468
  }
439
469
  this.#cycle.recordFailedAcquisitionOrLease();
470
+ if (this.#keyExchange === "hybridPreferred" && this.#source.acquireForKeyExchange &&
471
+ postSpendResult.error instanceof VerifiedHybridRefusalV3 && performance.now() < deadline &&
472
+ !this.#attemptBudgetExhausted()) {
473
+ fallback = { from: artifact, deadline };
474
+ next = "primary";
475
+ replacementContext = undefined;
476
+ continue;
477
+ }
440
478
  this.#recordFailure("connect", postSpendResult.error.code, postSpendResult.error.retryDisposition);
441
479
  if (postSpendResult.error.retryDisposition.kind === "terminal" || this.#attemptBudgetExhausted())
442
480
  return;
@@ -488,8 +526,8 @@ export class ConnectionControllerV3 {
488
526
  pendingDisposition = refresh.retryDisposition;
489
527
  }
490
528
  }
491
- async #acquire() {
492
- const acquisition = new SourceAcquisitionRaceV3(this.#source, this.#lifetime.signal);
529
+ async #acquire(mode, signal) {
530
+ const acquisition = new SourceAcquisitionRaceV3(this.#source, signal, mode);
493
531
  let deliveredLeaseSnapshot;
494
532
  try {
495
533
  const result = await acquisition.value();
@@ -644,7 +682,7 @@ class SourceAcquisitionRaceV3 {
644
682
  #rejectSettled;
645
683
  #signal;
646
684
  #abort;
647
- constructor(source, signal) {
685
+ constructor(source, signal, mode) {
648
686
  this.#signal = signal;
649
687
  this.#settled = new Promise((resolve, reject) => {
650
688
  this.#resolveSettled = resolve;
@@ -653,7 +691,7 @@ class SourceAcquisitionRaceV3 {
653
691
  try {
654
692
  // Invoke the source before returning so a synchronous close cannot abort
655
693
  // before the source has installed its own cancellation observer.
656
- this.#sourcePromise = Promise.resolve(source.acquire({ signal }));
694
+ this.#sourcePromise = Promise.resolve(source.acquireForKeyExchange ? source.acquireForKeyExchange(mode, { signal }) : source.acquire({ signal }));
657
695
  }
658
696
  catch (error) {
659
697
  this.#sourcePromise = Promise.reject(error);
@@ -722,6 +760,7 @@ const LEASE_ATTEMPT_RESULT_KINDS_V3 = new Set([
722
760
  "post_spend_failure",
723
761
  ]);
724
762
  const CONNECT_ERROR_CODES_V3 = new Set([
763
+ "hybrid_unavailable",
725
764
  "tunnel_ingress_mismatch",
726
765
  "artifact_invalid",
727
766
  "expired_artifact",
@@ -781,13 +820,26 @@ function normalizeLeaseAttemptResultV3(value, candidates, capability) {
781
820
  const error = Reflect.get(value, "error");
782
821
  if (!(error instanceof ConnectErrorV3) || !CONNECT_ERROR_CODES_V3.has(error.code))
783
822
  return undefined;
784
- const normalizedError = new ConnectErrorV3(error.code, validateRetryDispositionV3(error.retryDisposition));
823
+ const normalizedError = error instanceof VerifiedHybridRefusalV3 ? new VerifiedHybridRefusalV3() : new ConnectErrorV3(error.code, validateRetryDispositionV3(error.retryDisposition));
785
824
  return Object.freeze({ kind, error: normalizedError });
786
825
  }
787
826
  catch {
788
827
  return undefined;
789
828
  }
790
829
  }
830
+ function validClassicReplacement(previous, next) {
831
+ const before = previous.path, after = next.path;
832
+ if (previous.session.default_suite !== 3 || next.session.default_suite === 3 ||
833
+ previous.session.channel_id !== next.session.channel_id || previous.session.e2ee_psk_b64u === next.session.e2ee_psk_b64u ||
834
+ before.listener_audience !== after.listener_audience || canonicalizeJCSV3(previous.scoped) !== canonicalizeJCSV3(next.scoped) ||
835
+ canonicalizeCandidatesV3(before.kind, before.candidates).hashBase64URL !== canonicalizeCandidatesV3(after.kind, after.candidates).hashBase64URL)
836
+ return false;
837
+ if (before.kind === "direct")
838
+ return after.kind === "direct" && before.routing_token !== after.routing_token;
839
+ return after.kind === "tunnel" && before.role === 1 && after.role === 1 && before.token !== after.token &&
840
+ before.rendezvous_group_id !== after.rendezvous_group_id && before.local_endpoint_instance_id === after.local_endpoint_instance_id &&
841
+ before.expected_peer_endpoint_instance_id === after.expected_peer_endpoint_instance_id;
842
+ }
791
843
  function isManagedSessionV3(value) {
792
844
  return value !== null && typeof value === "object" &&
793
845
  typeof Reflect.get(value, "waitTermination") === "function" &&
@@ -0,0 +1,7 @@
1
+ export declare function connectorRPCLimits(options: Readonly<{
2
+ maxRpcFrameBytes?: number;
3
+ maxConcurrentRpcRequests?: number;
4
+ }>): {
5
+ maxRpcFrameBytes: number;
6
+ maxConcurrentRpcRequests: number;
7
+ };
@@ -0,0 +1,14 @@
1
+ import { rpcFrameLimit } from "../framing/jsonframe.js";
2
+ import { rpcConcurrency } from "../rpc/server.js";
3
+ import { ConnectErrorV3 } from "./security.js";
4
+ export function connectorRPCLimits(options) {
5
+ try {
6
+ return {
7
+ maxRpcFrameBytes: rpcFrameLimit(options.maxRpcFrameBytes),
8
+ maxConcurrentRpcRequests: rpcConcurrency(options.maxConcurrentRpcRequests),
9
+ };
10
+ }
11
+ catch {
12
+ throw new ConnectErrorV3("artifact_invalid", { kind: "terminal" });
13
+ }
14
+ }
@@ -40,6 +40,7 @@ export interface InternalIncomingStreamV3 {
40
40
  readonly stream: InternalByteStreamV3;
41
41
  }
42
42
  export interface InternalSessionV3 {
43
+ readonly usesHybridKeyExchange?: boolean;
43
44
  readonly path: PathKind;
44
45
  readonly endpointInstanceId: string | undefined;
45
46
  readonly rpc: InternalRpcPeerV3;
@@ -3,7 +3,8 @@ import { FLOWERSEC_V3_PROFILE } from "./transportConstants.js";
3
3
  export declare enum HandshakeMessageTypeV3 {
4
4
  ClientInit = 1,
5
5
  ServerFinished = 2,
6
- ClientFinished = 3
6
+ ClientFinished = 3,
7
+ ServerUnavailable = 4
7
8
  }
8
9
  export type HandshakeFrameV3 = Readonly<{
9
10
  type: HandshakeMessageTypeV3;
@@ -70,6 +71,13 @@ export declare function generateEphemeralKeyV3(suite: CipherSuiteV3, entropy: (l
70
71
  export declare function ephemeralPublicKeyV3(suite: CipherSuiteV3, privateKey: Uint8Array): Uint8Array;
71
72
  export declare function computeSharedSecretV3(suite: CipherSuiteV3, privateKey: Uint8Array, peerPublicKey: Uint8Array): Uint8Array;
72
73
  export declare function deriveHandshakePRKV3(psk: Uint8Array, sharedSecret: Uint8Array): Uint8Array;
74
+ export declare function serverKeyShareV3(suite: CipherSuiteV3, clientShare: Uint8Array, entropy: (length: number) => Uint8Array): {
75
+ publicKey: Uint8Array<ArrayBufferLike>;
76
+ shared: Uint8Array<ArrayBufferLike>;
77
+ };
78
+ export declare function clientSharedSecretV3(suite: CipherSuiteV3, privateKey: Uint8Array, serverShare: Uint8Array): Uint8Array<ArrayBufferLike>;
79
+ export declare function serverUnavailableV3(psk: Uint8Array, h0: Uint8Array, binding: Uint8Array, endpoint: string): Uint8Array;
80
+ export declare function verifyServerUnavailableV3(raw: Uint8Array, psk: Uint8Array, h0: Uint8Array, expected: HandshakeExpectationsV3): void;
73
81
  export declare function computeHandshakeH0V3(controlPrefaceRaw: Uint8Array, clientInitRaw: Uint8Array): Uint8Array;
74
82
  export declare function computeHandshakeH1V3(h0: Uint8Array, serverCoreRaw: Uint8Array): Uint8Array;
75
83
  export declare function computeServerConfirmV3(handshakePRK: Uint8Array, h1: Uint8Array): Uint8Array;