@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,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);
@@ -2,6 +2,7 @@ import { type ArtifactLeaseV3 } from "./artifactLease.js";
2
2
  export declare class ArtifactHandleV3 {
3
3
  private readonly artifactHandleBrand;
4
4
  private constructor();
5
+ lookupKey(): string;
5
6
  }
6
7
  export type ArtifactParseErrorCodeV3 = "artifact_too_large" | "invalid_artifact";
7
8
  export declare class ArtifactParseErrorV3 extends Error {
@@ -1,8 +1,15 @@
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ import { base64urlEncode } from "../utils/base64url.js";
1
3
  import { ArtifactV3Error, decodeArtifactV3JSON, validateArtifactV3, } from "./artifact.js";
2
4
  import { createArtifactLeaseV3Internal, } from "./artifactLease.js";
3
5
  const artifacts = new WeakMap();
4
6
  export class ArtifactHandleV3 {
5
7
  constructor() { }
8
+ lookupKey() {
9
+ const artifact = unwrapArtifactHandleV3(this);
10
+ const token = artifact.path.kind === "direct" ? artifact.path.routing_token : artifact.path.token;
11
+ return base64urlEncode(sha256(new TextEncoder().encode(token)));
12
+ }
6
13
  }
7
14
  export class ArtifactParseErrorV3 extends Error {
8
15
  code;
@@ -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");
@@ -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;
@@ -3,8 +3,8 @@ import { SDK_DEFAULTS } from "../defaults.js";
3
3
  import { RpcRouter, RpcServer } from "../rpc/server.js";
4
4
  import { CarrierError } from "./carrier.js";
5
5
  import { FLOWERSEC_V3_PROFILE } from "./transportConstants.js";
6
- import { computeClientConfirmV3, computeHandshakeH0V3, computeHandshakeH1V3, computeHandshakeH2V3, computeHandshakeH3V3, computeServerConfirmV3, computeSharedSecretV3, decodeClientFinishedV3, decodeClientInitV3, decodeHandshakeFrameV3, decodeServerFinishedV3, deriveHandshakePRKV3, deriveSessionPRKV3, encodeClientFinishedCoreV3, encodeClientFinishedV3, encodeClientInitV3, encodeControlPrefaceV3, encodeServerFinishedCoreV3, encodeServerFinishedV3, generateEphemeralKeyV3, parseControlPrefaceV3, validateClientInitV3, validateServerFinishedV3, } from "./handshake.js";
7
- import { DirectionV3, InnerTypeV3, computeValidatedFSS3HashV3Internal, computeValidatedOpenHashV3Internal, computeSetupMAC, decodeInnerRecordV3, decodeOpenACKV3, decodeOpenPayload, decodeOpenRejectV3, decodeRecordHeader, decodeSetupPrefaceV3, decodeStreamKeyUpdateACKV3, deriveControlMaterial, deriveEpochZero, deriveEpochRoots, deriveNextEpoch, deriveStreamMaterial, encodeOpenACKV3, encodeOpenPayloadFromMetadataV3Internal, encodeOpenRejectV3, encodeSetupPreface, encodeStreamKeyUpdateACKV3, openRecordWithRawHeaderV3Internal, sealRecordWireV3Internal, verifySetupMAC, } from "./protocol.js";
6
+ import { computeClientConfirmV3, computeHandshakeH0V3, computeHandshakeH1V3, computeHandshakeH2V3, computeHandshakeH3V3, computeServerConfirmV3, clientSharedSecretV3, serverKeyShareV3, serverUnavailableV3, verifyServerUnavailableV3, HandshakeMessageTypeV3, decodeClientFinishedV3, decodeClientInitV3, decodeHandshakeFrameV3, decodeServerFinishedV3, deriveHandshakePRKV3, deriveSessionPRKV3, encodeClientFinishedCoreV3, encodeClientFinishedV3, encodeClientInitV3, encodeControlPrefaceV3, encodeServerFinishedCoreV3, encodeServerFinishedV3, generateEphemeralKeyV3, parseControlPrefaceV3, validateClientInitV3, validateServerFinishedV3, } from "./handshake.js";
7
+ import { DirectionV3, InnerTypeV3, computeValidatedFSS3HashV3Internal, computeValidatedOpenHashV3Internal, computeSetupMAC, decodeInnerRecordV3, decodeOpenACKV3, decodeOpenPayload, decodeOpenRejectV3, decodeRecordHeader, decodeSetupPrefaceV3, decodeStreamKeyUpdateACKV3, deriveControlMaterial, deriveEpochZero, deriveEpochRoots, deriveNextEpoch, deriveStreamMaterial, encodeOpenACKV3, encodeOpenPayloadFromMetadataV3Internal, encodeOpenRejectV3, encodeSetupPreface, encodeStreamKeyUpdateACKV3, openRecordWithRawHeaderV3Internal, sealRecordWireV3Internal, verifySetupMAC, CipherSuiteV3, } from "./protocol.js";
8
8
  import { StreamLifetimeLedgerV3, StreamLifetimeLedgerV3Error, maxLogicalStreamIDV3, } from "./streamLifetimeLedger.js";
9
9
  import { UNRELIABLE_MESSAGES_FEATURE_V3, UNRELIABLE_MESSAGE_WIRE_BYTES_V3, createInternalUnreliableMessageChannelV3, } from "./unreliableMessage.js";
10
10
  const decoder = new TextDecoder();
@@ -81,7 +81,7 @@ export async function establishSessionV3(carrier, config, options = {}) {
81
81
  catch (error) {
82
82
  control?.abort(asError(error));
83
83
  carrier.abort({ code: 6, reason: "handshake failed" });
84
- if (error instanceof SessionV3Error)
84
+ if (error instanceof SessionV3Error || error instanceof HybridUnavailableV3)
85
85
  throw error;
86
86
  throw new SessionV3Error("handshake", `Flowersec v5 handshake failed: ${errorMessage(error)}`);
87
87
  }
@@ -90,10 +90,13 @@ export async function establishSessionV3(carrier, config, options = {}) {
90
90
  establishDeadline.cancel();
91
91
  }
92
92
  }
93
+ export class HybridUnavailableV3 extends Error {
94
+ }
93
95
  export class SessionV3 {
94
96
  carrier;
95
97
  control;
96
98
  controlReader;
99
+ get usesHybridKeyExchange() { return this.suite === CipherSuiteV3.XWing; }
97
100
  path;
98
101
  endpointInstanceId;
99
102
  rpc;
@@ -1842,14 +1845,21 @@ async function clientHandshake(control, reader, config, offeredFeatures, signal)
1842
1845
  await writeAll(control, controlPreface, signal);
1843
1846
  await writeAll(control, initRaw, signal);
1844
1847
  const serverRaw = await readHandshakeFrame(reader, signal);
1848
+ const h0 = computeHandshakeH0V3(controlPreface, initRaw);
1849
+ if (serverRaw[5] === HandshakeMessageTypeV3.ServerUnavailable) {
1850
+ verifyServerUnavailableV3(serverRaw, config.psk, h0, expectations(config, false));
1851
+ await control.closeWrite();
1852
+ throw new HybridUnavailableV3();
1853
+ }
1845
1854
  const server = decodeServerFinishedV3(serverRaw, config.suite);
1846
1855
  validateServerFinishedV3(server, expectations(config, false));
1847
1856
  if ((server.core.selectedFeatures & ~offeredFeatures) !== 0) {
1848
1857
  throw protocolError("server selected an unoffered feature");
1849
1858
  }
1850
- const shared = computeSharedSecretV3(config.suite, key.privateKey, server.core.serverEphemeralPublic);
1859
+ const shared = clientSharedSecretV3(config.suite, key.privateKey, server.core.serverEphemeralPublic);
1860
+ key.privateKey.fill(0);
1851
1861
  const handshakePRK = deriveHandshakePRKV3(config.psk, shared);
1852
- const h0 = computeHandshakeH0V3(controlPreface, initRaw);
1862
+ shared.fill(0);
1853
1863
  const h1 = computeHandshakeH1V3(h0, encodeServerFinishedCoreV3(server.core, config.suite));
1854
1864
  if (!bytesEqual(server.serverConfirm, computeServerConfirmV3(handshakePRK, h1))) {
1855
1865
  throw protocolError("server confirm mismatch");
@@ -1874,13 +1884,20 @@ async function serverHandshake(control, reader, config, localFeatures, signal) {
1874
1884
  const clientRaw = await readHandshakeFrame(reader, signal);
1875
1885
  const client = decodeClientInitV3(clientRaw);
1876
1886
  validateClientInitV3(client, expectations(config, true));
1877
- const key = generateEphemeralKeyV3(config.suite, (length) => config.runtime.entropy(length));
1878
- const shared = computeSharedSecretV3(config.suite, key.privateKey, client.clientEphemeralPublic);
1887
+ const h0 = computeHandshakeH0V3(controlPreface, clientRaw);
1888
+ if (config.suite === CipherSuiteV3.XWing && config.enableHybridKeyExchange !== true) {
1889
+ await writeAll(control, serverUnavailableV3(config.psk, h0, config.localAdmissionBinding, config.localEndpointInstanceID), signal);
1890
+ await control.closeWrite();
1891
+ await reader.readEOF(signal);
1892
+ throw new HybridUnavailableV3();
1893
+ }
1894
+ const { publicKey, shared } = serverKeyShareV3(config.suite, client.clientEphemeralPublic, (length) => config.runtime.entropy(length));
1879
1895
  const handshakePRK = deriveHandshakePRKV3(config.psk, shared);
1896
+ shared.fill(0);
1880
1897
  const core = {
1881
1898
  suite: config.suite,
1882
1899
  handshakeID: sessionRandomBytes(config, 16),
1883
- serverEphemeralPublic: key.publicKey,
1900
+ serverEphemeralPublic: publicKey,
1884
1901
  nonceS: sessionRandomBytes(config, 32),
1885
1902
  sessionContractHash: config.sessionContractHash,
1886
1903
  selectedFeatures: client.selectedFeatures & localFeatures,
@@ -1888,7 +1905,6 @@ async function serverHandshake(control, reader, config, localFeatures, signal) {
1888
1905
  serverAdmissionBinding: config.localAdmissionBinding,
1889
1906
  serverEndpointInstanceID: config.localEndpointInstanceID,
1890
1907
  };
1891
- const h0 = computeHandshakeH0V3(controlPreface, clientRaw);
1892
1908
  const h1 = computeHandshakeH1V3(h0, encodeServerFinishedCoreV3(core, config.suite));
1893
1909
  const serverRaw = encodeServerFinishedV3({
1894
1910
  core,
@@ -1,7 +1,7 @@
1
1
  import type { Session } from "../public/contract.js";
2
2
  import type { RpcRouter } from "../rpc/server.js";
3
3
  import { type ArtifactV3, type CanonicalArtifactCandidateV3 } from "./artifact.js";
4
- import { type ArtifactLeaseV3 } from "./artifactLease.js";
4
+ import { type ArtifactLeaseV3, type KeyExchangeMode } from "./artifactLease.js";
5
5
  import type { CarrierSessionV3, NativeCarrierStreamV3 } from "./carrier.js";
6
6
  import type { LeaseAttemptContextV3, LeaseAttemptResultV3 } from "./connectionController.js";
7
7
  import { type SessionDeadlineFactoryV3, type SessionProtocolRuntimeV3 } from "./session.js";
@@ -25,6 +25,8 @@ export type ReadyAdmissionTransportV3 = Readonly<{
25
25
  }>;
26
26
  export type CandidateDialerV3 = (candidate: CanonicalArtifactCandidateV3, artifact: ArtifactV3, attemptNowUnixSeconds: number, capability: RuntimeCapabilityDescriptorV3, signal: AbortSignal) => Promise<ReadyAdmissionTransportV3>;
27
27
  export type SessionConnectorRuntimeV3 = Readonly<{
28
+ keyExchange?: KeyExchangeMode;
29
+ enableHybridKeyExchange?: boolean;
28
30
  capabilitySnapshot(): RuntimeCapabilityDescriptorV3;
29
31
  candidateEligible?: (candidate: CanonicalArtifactCandidateV3) => boolean;
30
32
  dial: CandidateDialerV3;
@@ -42,5 +44,7 @@ export declare function connectArtifactLeaseWithRuntimeV3(lease: ArtifactLeaseV3
42
44
  connectTimeoutMs?: number;
43
45
  signal?: AbortSignal;
44
46
  tunnelIngressURL?: string;
47
+ keyExchange?: KeyExchangeMode;
48
+ enableHybridKeyExchange?: boolean;
45
49
  }>, createRuntime: (signal: AbortSignal) => SessionConnectorRuntimeV3 | Promise<SessionConnectorRuntimeV3>): Promise<Session>;
46
50
  export declare function attemptClaimedArtifactLeaseV3(context: LeaseAttemptContextV3, runtime: SessionConnectorRuntimeV3): Promise<LeaseAttemptResultV3<Session>>;
@@ -5,13 +5,13 @@ import { selectTunnelIngress } from "./tunnelIngress.js";
5
5
  import { artifactLeaseStateV3, claimConnectionLeaseV3, claimedArtifactV3, commitArtifactLeaseSpendV3, retireArtifactLeaseV3, } from "./artifactLease.js";
6
6
  import { aggregateCandidateFailuresV3, } from "./controller.js";
7
7
  import { projectSessionV3 } from "./publicSession.js";
8
- import { ConnectErrorV3, TransportFailureV3, snapshotTransportSecurityPolicyV3, } from "./security.js";
9
- import { establishSessionV3, } from "./session.js";
8
+ import { ConnectErrorV3, VerifiedHybridRefusalV3, TransportFailureV3, snapshotTransportSecurityPolicyV3, } from "./security.js";
9
+ import { establishSessionV3, HybridUnavailableV3, } from "./session.js";
10
10
  import { supportsCandidateSecurityV3, validateRuntimeCapabilityDescriptorV3, } from "./capability.js";
11
11
  export async function connectArtifactLeaseV3(lease, runtime, signal) {
12
12
  let claim;
13
13
  try {
14
- claim = claimConnectionLeaseV3(lease, runtime.tunnelIngressURL);
14
+ claim = claimConnectionLeaseV3(lease, runtime.tunnelIngressURL, runtime.keyExchange);
15
15
  }
16
16
  catch (error) {
17
17
  if (error instanceof ConnectErrorV3)
@@ -25,7 +25,7 @@ export async function connectArtifactLeaseWithRuntimeV3(lease, options, createRu
25
25
  let ingress;
26
26
  try {
27
27
  ingress = options.tunnelIngressURL;
28
- claim = claimConnectionLeaseV3(lease, ingress);
28
+ claim = claimConnectionLeaseV3(lease, ingress, options.keyExchange);
29
29
  }
30
30
  catch (error) {
31
31
  if (error instanceof ConnectErrorV3)
@@ -282,6 +282,8 @@ async function attemptClaimedArtifactLeaseWithinDeadlineV3(context, runtime) {
282
282
  }
283
283
  catch (error) {
284
284
  carrier.abort({ code: 6, reason: "session establishment failed" });
285
+ if (error instanceof HybridUnavailableV3 && config.role === "client")
286
+ throw new VerifiedHybridRefusalV3();
285
287
  throw error instanceof ConnectErrorV3
286
288
  ? error
287
289
  : new ConnectErrorV3("connection_failed", { kind: "retryable" });
@@ -311,6 +313,7 @@ function sessionConfigFromArtifactV3(artifact, rawFSB3, runtime) {
311
313
  const tunnel = artifact.path.kind === "tunnel" ? artifact.path : undefined;
312
314
  return {
313
315
  role: tunnel?.role === 2 ? "server" : "client",
316
+ enableHybridKeyExchange: runtime.enableHybridKeyExchange === true,
314
317
  path: artifact.path.kind,
315
318
  channelID: artifact.session.channel_id,
316
319
  sessionContractHash: base64urlDecode(artifact.session.contract_hash_b64u),
@@ -204,7 +204,7 @@ export function sealUnreliableMessageDatagramV3(options) {
204
204
  };
205
205
  }
206
206
  function cipher(suite, key, nonce, aad) {
207
- if (suite === CipherSuiteV3.ChaCha20Poly1305)
207
+ if (suite === CipherSuiteV3.ChaCha20Poly1305 || suite === CipherSuiteV3.XWing)
208
208
  return chacha20poly1305(key, nonce, aad);
209
209
  if (suite === CipherSuiteV3.AES256GCM)
210
210
  return gcm(key, nonce, aad);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floegence/flowersec-core",
3
- "version": "7.5.0",
3
+ "version": "8.1.0",
4
4
  "description": "Flowersec core TypeScript library for carrier-neutral encrypted sessions and multiplexed streams.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -79,6 +79,7 @@
79
79
  "@noble/ciphers": "2.4.0",
80
80
  "@noble/curves": "2.4.0",
81
81
  "@noble/hashes": "2.4.0",
82
+ "@noble/post-quantum": "0.7.1",
82
83
  "tr46": "7.0.0",
83
84
  "ws": "8.22.0"
84
85
  },
@@ -99,7 +100,7 @@
99
100
  "vitest": "4.1.12"
100
101
  },
101
102
  "optionalDependencies": {
102
- "@floegence/flowersec-node-native": "7.5.0"
103
+ "@floegence/flowersec-node-native": "8.1.0"
103
104
  },
104
- "flowersecSourceCommit": "26145cfc2efd6d4a23f46f6738a55f17aa1ec20d"
105
+ "flowersecSourceCommit": "847786784dffb2e9a07827471531018279e5c80f"
105
106
  }