@floegence/flowersec-core 7.5.0 → 8.0.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.
@@ -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.0.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
7
+ - @floegence/flowersec-node-native-darwin-arm64 8.0.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
8
+ - @floegence/flowersec-node-native-darwin-x64 8.0.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
9
+ - @floegence/flowersec-node-native-linux-arm64-gnu 8.0.0 (Declared: MIT; selected: MIT; source: https://github.com/floegence/flowersec.git)
10
+ - @floegence/flowersec-node-native-linux-x64-gnu 8.0.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;
@@ -25,6 +25,8 @@ export async function createBrowserController(source, options, rotation) {
25
25
  const registry = await BrowserRuntimeCapabilityRegistryV3.create();
26
26
  const runtime = browserRuntime(registry, options);
27
27
  const coreOptions = {
28
+ keyExchange: options.keyExchange ?? "classic",
29
+ connectTimeoutMs: options.connectTimeoutMs ?? SDK_DEFAULTS.transport.connectTimeoutMs,
28
30
  ...(runtime.tunnelIngressURL === undefined ? {} : { tunnelIngressURL: runtime.tunnelIngressURL }),
29
31
  capabilitySnapshot: runtime.capabilitySnapshot,
30
32
  projectSessionFailure,
@@ -173,6 +175,8 @@ function browserRuntime(registry, options) {
173
175
  capabilitySnapshot: () => registry.snapshot(),
174
176
  connectTimeoutMilliseconds,
175
177
  protocolRuntime: browserSessionRuntimeV3,
178
+ keyExchange: options.keyExchange ?? "classic",
179
+ enableHybridKeyExchange: options.enableHybridKeyExchange === true,
176
180
  ...(options.tunnelIngressURL === undefined ? {} : { tunnelIngressURL: options.tunnelIngressURL }),
177
181
  ...rpcOptions(options),
178
182
  dial: async (candidate, artifact, attemptNow, capability, signal) => {
@@ -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;
@@ -21,6 +21,8 @@ export function createConnectionControllerV3(source, options) {
21
21
  }
22
22
  const runtime = nodeRuntime(options);
23
23
  const coreOptions = {
24
+ keyExchange: options.keyExchange ?? "classic",
25
+ connectTimeoutMs: options.connectTimeoutMs ?? SDK_DEFAULTS.transport.connectTimeoutMs,
24
26
  ...(runtime.tunnelIngressURL === undefined ? {} : { tunnelIngressURL: runtime.tunnelIngressURL }),
25
27
  capabilitySnapshot: runtime.capabilitySnapshot,
26
28
  projectSessionFailure,
@@ -59,6 +61,8 @@ function nodeRuntime(options) {
59
61
  (candidate.carrier === "raw_quic" || options.origin !== undefined),
60
62
  connectTimeoutMilliseconds,
61
63
  protocolRuntime: nodeSessionRuntimeV3,
64
+ keyExchange: options.keyExchange ?? "classic",
65
+ enableHybridKeyExchange: options.enableHybridKeyExchange === true,
62
66
  maxRpcFrameBytes: rpcFrameLimit(options.maxRpcFrameBytes),
63
67
  maxConcurrentRpcRequests: rpcConcurrency(options.maxConcurrentRpcRequests),
64
68
  ...(options.tunnelIngressURL === undefined ? {} : { tunnelIngressURL: options.tunnelIngressURL }),
@@ -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>;
@@ -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" &&
@@ -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;
@@ -3,6 +3,7 @@ import { p256 } from "@noble/curves/nist.js";
3
3
  import { expand, extract } from "@noble/hashes/hkdf.js";
4
4
  import { hmac } from "@noble/hashes/hmac.js";
5
5
  import { sha256 } from "@noble/hashes/sha2.js";
6
+ import { ml_kem768_x25519 as xwing } from "@noble/post-quantum/hybrid.js";
6
7
  import { base64urlDecode, base64urlEncode } from "../utils/base64url.js";
7
8
  import { concatBytes, readU32be, u32be } from "../utils/bin.js";
8
9
  import { CipherSuiteV3, ProtocolV3Error } from "./protocol.js";
@@ -19,6 +20,7 @@ export var HandshakeMessageTypeV3;
19
20
  HandshakeMessageTypeV3[HandshakeMessageTypeV3["ClientInit"] = 1] = "ClientInit";
20
21
  HandshakeMessageTypeV3[HandshakeMessageTypeV3["ServerFinished"] = 2] = "ServerFinished";
21
22
  HandshakeMessageTypeV3[HandshakeMessageTypeV3["ClientFinished"] = 3] = "ClientFinished";
23
+ HandshakeMessageTypeV3[HandshakeMessageTypeV3["ServerUnavailable"] = 4] = "ServerUnavailable";
22
24
  })(HandshakeMessageTypeV3 || (HandshakeMessageTypeV3 = {}));
23
25
  export function encodeControlPrefaceV3() {
24
26
  const out = new Uint8Array(CONTROL_PREFACE_BYTES);
@@ -36,7 +38,7 @@ export function parseControlPrefaceV3(raw) {
36
38
  }
37
39
  export function encodeHandshakeFrameV3(type, payload) {
38
40
  if (type < HandshakeMessageTypeV3.ClientInit ||
39
- type > HandshakeMessageTypeV3.ClientFinished ||
41
+ type > HandshakeMessageTypeV3.ServerUnavailable ||
40
42
  payload.length < 1 ||
41
43
  payload.length > MAX_HANDSHAKE_PAYLOAD_BYTES) {
42
44
  throw new ProtocolV3Error("invalid FSH3 handshake frame");
@@ -58,7 +60,7 @@ export function decodeHandshakeFrameV3(raw) {
58
60
  const type = raw[5];
59
61
  const length = readU32be(raw, 8);
60
62
  if (type < HandshakeMessageTypeV3.ClientInit ||
61
- type > HandshakeMessageTypeV3.ClientFinished ||
63
+ type > HandshakeMessageTypeV3.ServerUnavailable ||
62
64
  length < 1 || length > MAX_HANDSHAKE_PAYLOAD_BYTES ||
63
65
  raw.length !== HANDSHAKE_HEADER_BYTES + length) {
64
66
  throw new ProtocolV3Error("invalid FSH3 handshake frame");
@@ -182,6 +184,10 @@ export function decodeClientFinishedV3(raw) {
182
184
  }
183
185
  export function generateEphemeralKeyV3(suite, entropy) {
184
186
  let privateKey;
187
+ if (suite === CipherSuiteV3.XWing) {
188
+ const { secretKey, publicKey } = xwing.keygen(requireEntropy(entropy, 32));
189
+ return { privateKey: secretKey, publicKey };
190
+ }
185
191
  if (suite === CipherSuiteV3.ChaCha20Poly1305) {
186
192
  privateKey = requireEntropy(entropy, 32);
187
193
  }
@@ -246,6 +252,42 @@ export function deriveHandshakePRKV3(psk, sharedSecret) {
246
252
  throw new ProtocolV3Error("invalid v5 ECDH shared secret");
247
253
  return extract(sha256, sharedSecret, psk);
248
254
  }
255
+ export function serverKeyShareV3(suite, clientShare, entropy) {
256
+ if (suite === CipherSuiteV3.XWing) {
257
+ const { cipherText, sharedSecret } = xwing.encapsulate(clientShare, requireEntropy(entropy, 64));
258
+ return { publicKey: cipherText, shared: sharedSecret };
259
+ }
260
+ const key = generateEphemeralKeyV3(suite, entropy);
261
+ try {
262
+ return { publicKey: key.publicKey, shared: computeSharedSecretV3(suite, key.privateKey, clientShare) };
263
+ }
264
+ finally {
265
+ key.privateKey.fill(0);
266
+ }
267
+ }
268
+ export function clientSharedSecretV3(suite, privateKey, serverShare) {
269
+ return suite === CipherSuiteV3.XWing ? xwing.decapsulate(serverShare, privateKey) : computeSharedSecretV3(suite, privateKey, serverShare);
270
+ }
271
+ export function serverUnavailableV3(psk, h0, binding, endpoint) {
272
+ const core = { reason: "hybrid_unavailable", server_admission_binding_b64u: encode32(binding), server_endpoint_instance_id: endpoint, suite: CipherSuiteV3.XWing };
273
+ const key = expand(sha256, psk, encoder.encode("flowersec v5 server hybrid unavailable"), 32);
274
+ try {
275
+ const tag = hmac(sha256, key, concatBytes([h0, lengthPrefixed(encoder.encode(JSON.stringify(core)))]));
276
+ return encodeCanonicalHandshake(HandshakeMessageTypeV3.ServerUnavailable, { ...core, tag_b64u: encode32(tag) });
277
+ }
278
+ finally {
279
+ key.fill(0);
280
+ }
281
+ }
282
+ export function verifyServerUnavailableV3(raw, psk, h0, expected) {
283
+ const object = decodeCanonicalObject(raw, HandshakeMessageTypeV3.ServerUnavailable, ["reason", "server_admission_binding_b64u", "server_endpoint_instance_id", "suite", "tag_b64u"]);
284
+ const binding = decode32(object.server_admission_binding_b64u);
285
+ const endpoint = requireString(object.server_endpoint_instance_id);
286
+ if (expected.suite !== CipherSuiteV3.XWing || !validAdmissionBinding(expected.path, binding, expected.admissionBinding) ||
287
+ !validExpectedEndpoint(expected.path, endpoint, expected.expectedEndpointInstanceID) || !bytesEqual(raw, serverUnavailableV3(psk, h0, binding, endpoint))) {
288
+ throw new ProtocolV3Error("invalid handshake rejection");
289
+ }
290
+ }
249
291
  export function computeHandshakeH0V3(controlPrefaceRaw, clientInitRaw) {
250
292
  parseControlPrefaceV3(controlPrefaceRaw);
251
293
  decodeClientInitV3(clientInitRaw);
@@ -331,7 +373,10 @@ function validateClientInit(message) {
331
373
  assertBytes("session contract hash", message.sessionContractHash, 32);
332
374
  assertBytes("client nonce", message.nonceC, 32);
333
375
  assertBytes("client admission binding", message.clientAdmissionBinding, 32);
334
- validateEphemeralPublic(message.suite, message.clientEphemeralPublic);
376
+ if (message.suite === CipherSuiteV3.XWing)
377
+ assertBytes("X-Wing encapsulation key", message.clientEphemeralPublic, 1216);
378
+ else
379
+ validateEphemeralPublic(message.suite, message.clientEphemeralPublic);
335
380
  }
336
381
  function validateServerCore(core) {
337
382
  validateHandshakeID(core.handshakeID);
@@ -343,7 +388,10 @@ function validateServerCore(core) {
343
388
  assertBytes("session contract hash", core.sessionContractHash, 32);
344
389
  assertBytes("server nonce", core.nonceS, 32);
345
390
  assertBytes("server admission binding", core.serverAdmissionBinding, 32);
346
- validateEphemeralPublic(core.suite, core.serverEphemeralPublic);
391
+ if (core.suite === CipherSuiteV3.XWing)
392
+ assertBytes("X-Wing ciphertext", core.serverEphemeralPublic, 1120);
393
+ else
394
+ validateEphemeralPublic(core.suite, core.serverEphemeralPublic);
347
395
  }
348
396
  function validateEphemeralPublic(suite, value) {
349
397
  try {
@@ -403,7 +451,7 @@ function requireInteger(value, max) {
403
451
  return value;
404
452
  }
405
453
  function requireSuite(value) {
406
- if (value !== CipherSuiteV3.ChaCha20Poly1305 && value !== CipherSuiteV3.AES256GCM)
454
+ if (value !== CipherSuiteV3.ChaCha20Poly1305 && value !== CipherSuiteV3.AES256GCM && value !== CipherSuiteV3.XWing)
407
455
  return invalidSuite();
408
456
  return value;
409
457
  }
@@ -6,7 +6,8 @@ export declare enum DirectionV3 {
6
6
  }
7
7
  export declare enum CipherSuiteV3 {
8
8
  ChaCha20Poly1305 = 1,
9
- AES256GCM = 2
9
+ AES256GCM = 2,
10
+ XWing = 3
10
11
  }
11
12
  export type EpochRootsV3 = Readonly<{
12
13
  epochSecret: Uint8Array;
@@ -37,6 +37,7 @@ export var CipherSuiteV3;
37
37
  (function (CipherSuiteV3) {
38
38
  CipherSuiteV3[CipherSuiteV3["ChaCha20Poly1305"] = 1] = "ChaCha20Poly1305";
39
39
  CipherSuiteV3[CipherSuiteV3["AES256GCM"] = 2] = "AES256GCM";
40
+ CipherSuiteV3[CipherSuiteV3["XWing"] = 3] = "XWing";
40
41
  })(CipherSuiteV3 || (CipherSuiteV3 = {}));
41
42
  export var InnerTypeV3;
42
43
  (function (InnerTypeV3) {
@@ -394,7 +395,7 @@ export function sealRecordWireV3Internal(suite, material, h3, logicalStreamID, d
394
395
  writeInnerRecord(inner, type, payload);
395
396
  const nonce = recordNonce(material.noncePrefix, sequence);
396
397
  const aad = buildValidatedRecordAAD(h3, logicalStreamID, direction, rawHeader);
397
- if (suite === CipherSuiteV3.ChaCha20Poly1305) {
398
+ if (suite === CipherSuiteV3.ChaCha20Poly1305 || suite === CipherSuiteV3.XWing) {
398
399
  chacha20poly1305(material.recordKey, nonce, aad).encrypt(inner, body);
399
400
  }
400
401
  else {
@@ -426,6 +427,7 @@ export function openRecordWithRawHeaderV3Internal(suite, material, h3, logicalSt
426
427
  function cipher(suite, key, nonce, aad) {
427
428
  switch (suite) {
428
429
  case CipherSuiteV3.ChaCha20Poly1305:
430
+ case CipherSuiteV3.XWing:
429
431
  return chacha20poly1305(key, nonce, aad);
430
432
  case CipherSuiteV3.AES256GCM:
431
433
  return gcm(key, nonce, aad);
@@ -45,6 +45,7 @@ export function projectSessionV3(session) {
45
45
  };
46
46
  void session.termination.then(finishTermination, finishTermination);
47
47
  const projected = Object.freeze({
48
+ usesHybridKeyExchange: session.usesHybridKeyExchange === true,
48
49
  rpc,
49
50
  ...(unreliable === undefined ? {} : { unreliableMessages: unreliable }),
50
51
  async openStream(kind, options) {
@@ -6,7 +6,7 @@ export declare class TransportFailureV3 extends Error {
6
6
  readonly detail?: TransportFailureDetailV3 | undefined;
7
7
  constructor(code: TransportFailureCodeV3, detail?: TransportFailureDetailV3 | undefined, cause?: unknown);
8
8
  }
9
- export type PublicConnectErrorCodeV3 = "tunnel_ingress_mismatch" | "artifact_invalid" | "expired_artifact" | "transport_security_unsupported" | "transport_security_failed" | "connection_failed";
9
+ export type PublicConnectErrorCodeV3 = "hybrid_unavailable" | "tunnel_ingress_mismatch" | "artifact_invalid" | "expired_artifact" | "transport_security_unsupported" | "transport_security_failed" | "connection_failed";
10
10
  export type RetryDispositionV3 = Readonly<{
11
11
  kind: "terminal";
12
12
  }> | Readonly<{
@@ -21,6 +21,9 @@ export declare class ConnectErrorV3 extends Error {
21
21
  readonly retryDisposition: RetryDispositionV3;
22
22
  constructor(code: PublicConnectErrorCodeV3, disposition: RetryDispositionInputV3);
23
23
  }
24
+ export declare class VerifiedHybridRefusalV3 extends ConnectErrorV3 {
25
+ constructor();
26
+ }
24
27
  export type TransportSecuritySnapshotV3 = Readonly<{
25
28
  mode: "ca";
26
29
  }> | Readonly<{
@@ -19,6 +19,9 @@ export class ConnectErrorV3 extends Error {
19
19
  this.retryDisposition = validateRetryDispositionValueV3(disposition);
20
20
  }
21
21
  }
22
+ export class VerifiedHybridRefusalV3 extends ConnectErrorV3 {
23
+ constructor() { super("hybrid_unavailable", { kind: "terminal" }); }
24
+ }
22
25
  export function snapshotTransportSecurityPolicyV3(policy, attemptNowUnixSeconds, supportedModes) {
23
26
  if (!Number.isSafeInteger(attemptNowUnixSeconds) || attemptNowUnixSeconds < 0) {
24
27
  throw new TransportFailureV3("invalid_artifact");