@floegence/flowersec-core 7.4.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.
Files changed (42) hide show
  1. package/THIRD_PARTY_NOTICES.md +6 -5
  2. package/dist/browser/connectSessionV3.d.ts +5 -2
  3. package/dist/browser/connectSessionV3.js +8 -1
  4. package/dist/node/acceptorV3.d.ts +1 -0
  5. package/dist/node/acceptorV3.js +4 -2
  6. package/dist/node/connectSessionV3.d.ts +5 -1
  7. package/dist/node/connectSessionV3.js +4 -0
  8. package/dist/node/tunnelRuntimeV3.js +3 -4
  9. package/dist/node/webSocketServerV3.js +1 -1
  10. package/dist/proxy/index.d.ts +1 -1
  11. package/dist/proxy/index.js +1 -1
  12. package/dist/proxy/integration.d.ts +12 -0
  13. package/dist/proxy/integration.js +33 -0
  14. package/dist/proxy/runtime.d.ts +2 -1
  15. package/dist/proxy/runtime.js +13 -5
  16. package/dist/proxy/sessionRotation.d.ts +26 -0
  17. package/dist/proxy/sessionRotation.js +131 -0
  18. package/dist/public/contract.d.ts +1 -0
  19. package/dist/v3/artifact.js +1 -1
  20. package/dist/v3/artifactLease.d.ts +2 -1
  21. package/dist/v3/artifactLease.js +7 -2
  22. package/dist/v3/connectionController.d.ts +15 -3
  23. package/dist/v3/connectionController.js +86 -17
  24. package/dist/v3/contract.d.ts +3 -0
  25. package/dist/v3/handshake.d.ts +9 -1
  26. package/dist/v3/handshake.js +53 -5
  27. package/dist/v3/protocol.d.ts +2 -1
  28. package/dist/v3/protocol.js +3 -1
  29. package/dist/v3/publicSession.d.ts +5 -1
  30. package/dist/v3/publicSession.js +7 -0
  31. package/dist/v3/security.d.ts +4 -1
  32. package/dist/v3/security.js +3 -0
  33. package/dist/v3/serverAdmission.d.ts +2 -0
  34. package/dist/v3/serverAdmission.js +1 -0
  35. package/dist/v3/session.d.ts +8 -1
  36. package/dist/v3/session.js +59 -9
  37. package/dist/v3/sessionConnector.d.ts +5 -1
  38. package/dist/v3/sessionConnector.js +7 -4
  39. package/dist/v3/unreliableMessage.js +1 -1
  40. package/package.json +4 -3
  41. package/sbom/cyclonedx.json +68 -31
  42. package/sbom/spdx.json +75 -38
@@ -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,12 +51,16 @@ 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;
55
59
  #capabilitySnapshot;
56
60
  #projectSessionFailure;
57
61
  #lifetime = new AbortController();
62
+ #rotation;
63
+ #retrying = false;
58
64
  #listeners = new Map();
59
65
  #cycle;
60
66
  #state = "idle";
@@ -65,7 +71,8 @@ export class ConnectionControllerV3 {
65
71
  #scheduler;
66
72
  #closeOperation;
67
73
  #transitionGeneration = 0;
68
- constructor(source, connector, options) {
74
+ constructor(source, connector, options, rotation) {
75
+ this.#rotation = rotation;
69
76
  if (source === null || typeof source !== "object" || typeof source.acquire !== "function") {
70
77
  throw new TypeError("Flowersec v5 artifact source must provide acquire()");
71
78
  }
@@ -78,6 +85,11 @@ export class ConnectionControllerV3 {
78
85
  this.#source = source;
79
86
  this.#connector = connector;
80
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;
81
93
  this.#tunnelIngressURL = options.tunnelIngressURL;
82
94
  this.#cycle = new ControllerCycleStateV3(maximumAttempts);
83
95
  this.#nowUnixSeconds = options.nowUnixSeconds ?? (() => Math.floor(Date.now() / 1_000));
@@ -100,10 +112,10 @@ export class ConnectionControllerV3 {
100
112
  resolveScheduler = resolve;
101
113
  rejectScheduler = reject;
102
114
  });
103
- void this.#run().then(resolveScheduler, rejectScheduler);
115
+ void this.#run().finally(() => this.#rotation?.stop()).then(resolveScheduler, rejectScheduler);
104
116
  }
105
117
  retryNow() {
106
- return this.#state === "waiting" && this.#retry.retryNow();
118
+ return this.#retrying && this.#retry.retryNow();
107
119
  }
108
120
  subscribe(listener) {
109
121
  if (typeof listener !== "function")
@@ -193,11 +205,13 @@ export class ConnectionControllerV3 {
193
205
  unsubscribe();
194
206
  void Promise.allSettled([
195
207
  this.#scheduler ?? Promise.resolve(),
208
+ this.#rotation?.stop() ?? Promise.resolve(),
196
209
  active?.close() ?? Promise.resolve(),
197
210
  ]).then(() => resolveClose());
198
211
  return closeOperation;
199
212
  }
200
213
  async #run() {
214
+ let fallback;
201
215
  let next = "primary";
202
216
  let pendingDisposition;
203
217
  let replacementContext;
@@ -236,7 +250,12 @@ export class ConnectionControllerV3 {
236
250
  this.#forceTerminalDisposition();
237
251
  return;
238
252
  }
239
- 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);
240
259
  if (this.#lifetime.signal.aborted) {
241
260
  if (acquisition.kind === "lease")
242
261
  await this.#claimAndRetire(acquisition.lease);
@@ -245,7 +264,9 @@ export class ConnectionControllerV3 {
245
264
  if (acquisition.kind === "failure") {
246
265
  const error = sourceFailure(acquisition);
247
266
  const ordinal = this.#cycle.recordFailedAcquisitionOrLease();
248
- this.#recordFailure("artifact", error.code, error.retryDisposition);
267
+ this.#recordFailure("artifact", error.code, fallback ? { kind: "terminal" } : error.retryDisposition);
268
+ if (fallback)
269
+ return;
249
270
  if (error.retryDisposition.kind === "terminal" || this.#attemptBudgetExhausted())
250
271
  return;
251
272
  pendingDisposition = error.retryDisposition;
@@ -254,7 +275,7 @@ export class ConnectionControllerV3 {
254
275
  }
255
276
  let claim;
256
277
  try {
257
- claim = claimConnectionLeaseV3(acquisition.lease, this.#tunnelIngressURL);
278
+ claim = claimConnectionLeaseV3(acquisition.lease, this.#tunnelIngressURL, mode);
258
279
  }
259
280
  catch (error) {
260
281
  this.#cycle.recordFailedAcquisitionOrLease();
@@ -274,6 +295,9 @@ export class ConnectionControllerV3 {
274
295
  let allCandidates;
275
296
  try {
276
297
  validateArtifactV3(artifact);
298
+ if (fallback && (performance.now() >= deadline || !validClassicReplacement(fallback.from, artifact)))
299
+ throw new TypeError("invalid fallback grant");
300
+ this.#rotation?.accept(artifact);
277
301
  allCandidates = canonicalizeCandidatesV3(artifact.path.kind, artifact.path.candidates).candidates;
278
302
  }
279
303
  catch {
@@ -289,8 +313,10 @@ export class ConnectionControllerV3 {
289
313
  catch {
290
314
  await retireArtifactLeaseV3(claim);
291
315
  this.#cycle.recordFailedAcquisitionOrLease();
292
- const error = new ConnectErrorV3("expired_artifact", { kind: "retryable" });
316
+ const error = new ConnectErrorV3("expired_artifact", { kind: fallback ? "terminal" : "retryable" });
293
317
  this.#recordFailure("connect", error.code, error.retryDisposition);
318
+ if (fallback)
319
+ return;
294
320
  if (this.#attemptBudgetExhausted())
295
321
  return;
296
322
  next = "primary";
@@ -317,7 +343,7 @@ export class ConnectionControllerV3 {
317
343
  artifact,
318
344
  candidates,
319
345
  claim,
320
- signal: this.#lifetime.signal,
346
+ signal,
321
347
  capability,
322
348
  assertArtifactFresh: () => this.#assertArtifactFresh(artifact),
323
349
  });
@@ -353,6 +379,7 @@ export class ConnectionControllerV3 {
353
379
  return;
354
380
  }
355
381
  if (result.kind === "established") {
382
+ fallback = undefined;
356
383
  if (artifactLeaseStateV3(claim) !== "consumed") {
357
384
  if (artifactLeaseStateV3(claim) === "claimed")
358
385
  await retireArtifactLeaseV3(claim);
@@ -366,8 +393,17 @@ export class ConnectionControllerV3 {
366
393
  this.#failure = undefined;
367
394
  this.#disposition = undefined;
368
395
  this.#session = result.session;
396
+ const budget = this.#rotation?.publish(result.session);
369
397
  this.#transition("connected");
370
- const termination = await this.#waitTermination(result.session);
398
+ const ended = this.#waitTermination(result.session);
399
+ const termination = budget ? await Promise.race([ended, budget.then(() => "rotate")]) : await ended;
400
+ if (termination === "rotate") {
401
+ await this.#rotation.slot();
402
+ next = "primary";
403
+ replacementContext = undefined;
404
+ pendingDisposition = undefined;
405
+ continue;
406
+ }
371
407
  if (termination === undefined || this.#lifetime.signal.aborted)
372
408
  return;
373
409
  this.#session = undefined;
@@ -392,6 +428,14 @@ export class ConnectionControllerV3 {
392
428
  pendingDisposition = disposition;
393
429
  continue;
394
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
+ }
395
439
  if (result.kind === "pre_spend_failure") {
396
440
  if (artifactLeaseStateV3(claim) !== "claimed") {
397
441
  this.#cycle.recordFailedAcquisitionOrLease();
@@ -423,6 +467,14 @@ export class ConnectionControllerV3 {
423
467
  };
424
468
  }
425
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
+ }
426
478
  this.#recordFailure("connect", postSpendResult.error.code, postSpendResult.error.retryDisposition);
427
479
  if (postSpendResult.error.retryDisposition.kind === "terminal" || this.#attemptBudgetExhausted())
428
480
  return;
@@ -474,8 +526,8 @@ export class ConnectionControllerV3 {
474
526
  pendingDisposition = refresh.retryDisposition;
475
527
  }
476
528
  }
477
- async #acquire() {
478
- const acquisition = new SourceAcquisitionRaceV3(this.#source, this.#lifetime.signal);
529
+ async #acquire(mode, signal) {
530
+ const acquisition = new SourceAcquisitionRaceV3(this.#source, signal, mode);
479
531
  let deliveredLeaseSnapshot;
480
532
  try {
481
533
  const result = await acquisition.value();
@@ -592,6 +644,9 @@ export class ConnectionControllerV3 {
592
644
  #transition(state) {
593
645
  if (this.#state === "closed" && state !== "closed")
594
646
  return;
647
+ this.#retrying = state === "waiting";
648
+ if ((state === "waiting" || state === "connecting") && this.#session && this.#rotation?.canServe(this.#session))
649
+ state = "connected";
595
650
  this.#state = state;
596
651
  const generation = ++this.#transitionGeneration;
597
652
  const snapshot = this.#snapshot();
@@ -614,8 +669,8 @@ function detachableSubscription(remove) {
614
669
  remove = undefined;
615
670
  };
616
671
  }
617
- export function createConnectionControllerV3(source, connector, options) {
618
- return new ConnectionControllerV3(source, connector, options);
672
+ export function createConnectionControllerV3(source, connector, options, rotation) {
673
+ return new ConnectionControllerV3(source, connector, options, rotation);
619
674
  }
620
675
  /** Serializes source delivery and controller cancellation at one ownership gate. */
621
676
  class SourceAcquisitionRaceV3 {
@@ -627,7 +682,7 @@ class SourceAcquisitionRaceV3 {
627
682
  #rejectSettled;
628
683
  #signal;
629
684
  #abort;
630
- constructor(source, signal) {
685
+ constructor(source, signal, mode) {
631
686
  this.#signal = signal;
632
687
  this.#settled = new Promise((resolve, reject) => {
633
688
  this.#resolveSettled = resolve;
@@ -636,7 +691,7 @@ class SourceAcquisitionRaceV3 {
636
691
  try {
637
692
  // Invoke the source before returning so a synchronous close cannot abort
638
693
  // before the source has installed its own cancellation observer.
639
- this.#sourcePromise = Promise.resolve(source.acquire({ signal }));
694
+ this.#sourcePromise = Promise.resolve(source.acquireForKeyExchange ? source.acquireForKeyExchange(mode, { signal }) : source.acquire({ signal }));
640
695
  }
641
696
  catch (error) {
642
697
  this.#sourcePromise = Promise.reject(error);
@@ -705,6 +760,7 @@ const LEASE_ATTEMPT_RESULT_KINDS_V3 = new Set([
705
760
  "post_spend_failure",
706
761
  ]);
707
762
  const CONNECT_ERROR_CODES_V3 = new Set([
763
+ "hybrid_unavailable",
708
764
  "tunnel_ingress_mismatch",
709
765
  "artifact_invalid",
710
766
  "expired_artifact",
@@ -764,13 +820,26 @@ function normalizeLeaseAttemptResultV3(value, candidates, capability) {
764
820
  const error = Reflect.get(value, "error");
765
821
  if (!(error instanceof ConnectErrorV3) || !CONNECT_ERROR_CODES_V3.has(error.code))
766
822
  return undefined;
767
- const normalizedError = new ConnectErrorV3(error.code, validateRetryDispositionV3(error.retryDisposition));
823
+ const normalizedError = error instanceof VerifiedHybridRefusalV3 ? new VerifiedHybridRefusalV3() : new ConnectErrorV3(error.code, validateRetryDispositionV3(error.retryDisposition));
768
824
  return Object.freeze({ kind, error: normalizedError });
769
825
  }
770
826
  catch {
771
827
  return undefined;
772
828
  }
773
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
+ }
774
843
  function isManagedSessionV3(value) {
775
844
  return value !== null && typeof value === "object" &&
776
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;
@@ -49,6 +50,8 @@ export interface InternalSessionV3 {
49
50
  streams: number;
50
51
  residual: number;
51
52
  }>;
53
+ watchStreamBudget?(minimum: number, setupMs: number): Promise<void>;
54
+ canAllocateStream?(): boolean;
52
55
  readonly unreliableMessages?: UnreliableMessageChannelV3 | undefined;
53
56
  openStream(kind: string, options?: InternalStreamOpenOptionsV3): Promise<InternalByteStreamV3>;
54
57
  acceptStream(options?: OperationOptionsV3): Promise<InternalIncomingStreamV3>;
@@ -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);
@@ -1,2 +1,6 @@
1
- import type { ByteStreamV3 } from "./contract.js";
1
+ import type { ByteStreamV3, SessionV3 } from "./contract.js";
2
+ export declare function streamBudgetOwner(session: SessionV3): {
3
+ watch: (minimum: number, setupMs: number) => Promise<void>;
4
+ available: () => boolean;
5
+ };
2
6
  export declare function incomingResetSignal(stream: ByteStreamV3): AbortSignal | undefined;
@@ -4,6 +4,12 @@ import { assertRpcTypeId } from "../rpc/validate.js";
4
4
  import { raceWithSignal } from "../utils/abort.js";
5
5
  const internals = new WeakMap();
6
6
  const incomingOwners = new WeakMap();
7
+ export function streamBudgetOwner(session) {
8
+ const owner = internals.get(session);
9
+ if (!owner?.watchStreamBudget || !owner.canAllocateStream)
10
+ throw new TypeError("unmanaged session");
11
+ return { watch: owner.watchStreamBudget.bind(owner), available: owner.canAllocateStream.bind(owner) };
12
+ }
7
13
  export function incomingResetSignal(stream) {
8
14
  return incomingOwners.get(stream)?.resetSignal;
9
15
  }
@@ -39,6 +45,7 @@ export function projectSessionV3(session) {
39
45
  };
40
46
  void session.termination.then(finishTermination, finishTermination);
41
47
  const projected = Object.freeze({
48
+ usesHybridKeyExchange: session.usesHybridKeyExchange === true,
42
49
  rpc,
43
50
  ...(unreliable === undefined ? {} : { unreliableMessages: unreliable }),
44
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");
@@ -24,6 +24,7 @@ export declare function rejectSessionAdmissionV3(received: ReceivedSessionAdmiss
24
24
  }>>, admissionReasons: ReadonlySet<string>, signal?: AbortSignal): Promise<never>;
25
25
  export declare function acceptReceivedSessionV3(received: ReceivedSessionAdmissionV3, artifact: ArtifactV3, options: Readonly<{
26
26
  runtime: SessionProtocolRuntimeV3;
27
+ enableHybridKeyExchange?: boolean;
27
28
  maxRpcFrameBytes?: number;
28
29
  maxConcurrentRpcRequests?: number;
29
30
  admissionReasons: ReadonlySet<string>;
@@ -33,6 +34,7 @@ export declare function acceptReceivedSessionV3(received: ReceivedSessionAdmissi
33
34
  }>): Promise<SessionV3>;
34
35
  export declare function acceptCarrierSessionV3(carrier: CarrierSessionV3, authorize: AdmissionAuthorizerV3, options: Readonly<{
35
36
  runtime: SessionProtocolRuntimeV3;
37
+ enableHybridKeyExchange?: boolean;
36
38
  maxRpcFrameBytes?: number;
37
39
  maxConcurrentRpcRequests?: number;
38
40
  admissionReasons: ReadonlySet<string>;
@@ -77,6 +77,7 @@ async function acceptCarrierBoundSessionV3(received, artifact, options) {
77
77
  const binding = received.decoded.localAdmissionBinding;
78
78
  return await establishSessionV3(received.carrier, {
79
79
  role: "server",
80
+ enableHybridKeyExchange: options.enableHybridKeyExchange === true,
80
81
  path: artifact.path.kind,
81
82
  channelID: artifact.session.channel_id,
82
83
  sessionContractHash: base64urlDecode(artifact.session.contract_hash_b64u),
@@ -3,7 +3,7 @@ import { RpcRouter, type RpcServerOptions } from "../rpc/server.js";
3
3
  import type { InternalByteStreamV3 as ByteStreamV3, InternalIncomingStreamV3 as IncomingStreamV3, InternalRpcPeerV3, InternalSessionTerminationV3 as SessionTerminationV3, InternalSessionV3 as SessionV3Contract, OperationOptionsV3, PathKind, InternalStreamOpenOptionsV3, UnreliableMessageChannelV3 } from "./contract.js";
4
4
  import { type CarrierSessionV3, type CarrierStreamV3 } from "./carrier.js";
5
5
  import type { SessionContractV3 } from "./artifact.js";
6
- import { DirectionV3, InnerTypeV3, type EpochRootsV3, type RecordMaterialV3, type RecordHeaderV3, type CipherSuiteV3 } from "./protocol.js";
6
+ import { DirectionV3, InnerTypeV3, type EpochRootsV3, type RecordMaterialV3, type RecordHeaderV3, CipherSuiteV3 } from "./protocol.js";
7
7
  export type SessionRoleV3 = "client" | "server";
8
8
  export type SessionDeadlinePhaseV3 = "establish" | "rekey_prepare" | "rekey_completion";
9
9
  export type SessionDeadlineHandleV3 = Readonly<{
@@ -18,6 +18,7 @@ export type SessionDeadlinesV3 = Readonly<{
18
18
  factory?: SessionDeadlineFactoryV3;
19
19
  }>;
20
20
  export type SessionConfigV3 = Readonly<{
21
+ enableHybridKeyExchange?: boolean;
21
22
  role: SessionRoleV3;
22
23
  path: PathKind;
23
24
  channelID: string;
@@ -67,10 +68,13 @@ type HandshakeMaterial = Readonly<{
67
68
  selectedFeatures: number;
68
69
  }>;
69
70
  export declare function establishSessionV3(carrier: CarrierSessionV3, config: SessionConfigV3, options?: OperationOptionsV3): Promise<SessionV3>;
71
+ export declare class HybridUnavailableV3 extends Error {
72
+ }
70
73
  export declare class SessionV3 implements SessionV3Contract {
71
74
  private readonly carrier;
72
75
  private readonly control;
73
76
  private readonly controlReader;
77
+ get usesHybridKeyExchange(): boolean;
74
78
  readonly path: PathKind;
75
79
  readonly endpointInstanceId: string | undefined;
76
80
  readonly rpc: SessionRpcPeerV3;
@@ -96,6 +100,7 @@ export declare class SessionV3 implements SessionV3Contract {
96
100
  private applicationWriteBytes;
97
101
  private applicationWrites;
98
102
  private nextLogicalID;
103
+ private budgetChanged;
99
104
  private receivedGoAway;
100
105
  private receivedGoAwayLastAccepted;
101
106
  private receivedGoAwayReason;
@@ -189,6 +194,8 @@ export declare class SessionV3 implements SessionV3Contract {
189
194
  private closeOnce;
190
195
  private waitStopped;
191
196
  waitTermination(): Promise<SessionTerminationV3>;
197
+ canAllocateStream(): boolean;
198
+ watchStreamBudget(minimum: number, setupMs: number): Promise<void>;
192
199
  runtimeInventory(): Readonly<{
193
200
  active: boolean;
194
201
  streams: number;