@floegence/flowersec-core 8.1.0 → 8.2.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 (48) hide show
  1. package/THIRD_PARTY_NOTICES.md +8 -5
  2. package/dist/browser/connectSessionV3.d.ts +4 -0
  3. package/dist/browser/connectSessionV3.js +12 -4
  4. package/dist/browser/index.d.ts +1 -1
  5. package/dist/browser/index.js +1 -1
  6. package/dist/facade.d.ts +4 -0
  7. package/dist/facade.js +3 -0
  8. package/dist/node/connectSessionV3.d.ts +4 -0
  9. package/dist/node/connectSessionV3.js +7 -0
  10. package/dist/node/index.d.ts +1 -1
  11. package/dist/node/index.js +1 -1
  12. package/dist/node/nativeTransportAddon.d.ts +4 -3
  13. package/dist/node/nativeTransportAddon.js +3 -2
  14. package/dist/node/rawQuicAdapterV3.d.ts +2 -2
  15. package/dist/node/rawQuicAdapterV3.js +5 -3
  16. package/dist/tunnelAuth/artifact.d.ts +34 -0
  17. package/dist/tunnelAuth/artifact.js +74 -0
  18. package/dist/tunnelAuth/credentials.d.ts +17 -0
  19. package/dist/tunnelAuth/credentials.js +40 -0
  20. package/dist/tunnelAuth/hpke.d.ts +36 -0
  21. package/dist/tunnelAuth/hpke.js +124 -0
  22. package/dist/v3/artifact.d.ts +27 -8
  23. package/dist/v3/artifact.js +78 -42
  24. package/dist/v3/artifactLease.d.ts +4 -2
  25. package/dist/v3/artifactLease.js +13 -1
  26. package/dist/v3/browserRuntime.js +5 -3
  27. package/dist/v3/connectionController.d.ts +2 -2
  28. package/dist/v3/connectionController.js +8 -4
  29. package/dist/v3/handshake.d.ts +22 -21
  30. package/dist/v3/handshake.js +58 -60
  31. package/dist/v3/nodeRuntime.js +4 -1
  32. package/dist/v3/protocol.d.ts +17 -16
  33. package/dist/v3/protocol.js +60 -64
  34. package/dist/v3/runtimeAdapters.d.ts +2 -2
  35. package/dist/v3/runtimeAdapters.js +2 -1
  36. package/dist/v3/security.d.ts +1 -1
  37. package/dist/v3/session.d.ts +14 -4
  38. package/dist/v3/session.js +174 -114
  39. package/dist/v3/sessionConnector.d.ts +2 -2
  40. package/dist/v3/sessionConnector.js +24 -13
  41. package/dist/v3/tunnelIngress.js +2 -1
  42. package/dist/v3/unreliableMessage.d.ts +3 -0
  43. package/dist/v3/unreliableMessage.js +24 -22
  44. package/dist/v3/wireProfile.d.ts +52 -0
  45. package/dist/v3/wireProfile.js +20 -0
  46. package/package.json +5 -3
  47. package/sbom/cyclonedx.json +133 -31
  48. package/sbom/spdx.json +110 -39
@@ -1,10 +1,11 @@
1
1
  import { WebSocketBinaryTransport } from "../ws-client/binaryTransport.js";
2
+ import { endpointIngress } from "./wireProfile.js";
2
3
  import { adaptNativeCarrierSessionV3, } from "./carrier.js";
3
4
  import { TransportFailureV3 } from "./security.js";
4
5
  import { createWebSocketCarrierSessionV3 } from "./webSocketCarrier.js";
5
6
  import { websocketSubprotocolForPathV3 } from "./transportConstants.js";
6
7
  export async function readyWebSocketAdmissionV3(candidate, artifact, socket, signal) {
7
- const subprotocol = websocketSubprotocolForPathV3(artifact.path.kind);
8
+ const subprotocol = artifact.v === 1 ? endpointIngress.subprotocol : websocketSubprotocolForPathV3(artifact.path.kind);
8
9
  await waitForWebSocketOpen(socket, subprotocol, signal);
9
10
  const transport = new WebSocketBinaryTransport(socket);
10
11
  let finalized = false;
@@ -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 = "hybrid_unavailable" | "tunnel_ingress_mismatch" | "artifact_invalid" | "expired_artifact" | "transport_security_unsupported" | "transport_security_failed" | "connection_failed";
9
+ export type PublicConnectErrorCodeV3 = "endpoint_auth_failed" | "endpoint_auth_unsupported" | "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<{
@@ -3,6 +3,8 @@ 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 { type WireProfile } from "./wireProfile.js";
7
+ import { type TunnelAuth } from "../tunnelAuth/credentials.js";
6
8
  import { DirectionV3, InnerTypeV3, type EpochRootsV3, type RecordMaterialV3, type RecordHeaderV3, CipherSuiteV3 } from "./protocol.js";
7
9
  export type SessionRoleV3 = "client" | "server";
8
10
  export type SessionDeadlinePhaseV3 = "establish" | "rekey_prepare" | "rekey_completion";
@@ -24,7 +26,6 @@ export type SessionConfigV3 = Readonly<{
24
26
  channelID: string;
25
27
  sessionContractHash: Uint8Array;
26
28
  suite: CipherSuiteV3;
27
- psk: Uint8Array;
28
29
  maxInboundStreams: number;
29
30
  localAdmissionBinding: Uint8Array;
30
31
  peerAdmissionBinding: Uint8Array;
@@ -38,14 +39,22 @@ export type SessionConfigV3 = Readonly<{
38
39
  idleTimeoutMs?: number;
39
40
  closeTimeoutMs?: number;
40
41
  runtime: SessionProtocolRuntimeV3;
41
- }>;
42
+ }> & (Readonly<{
43
+ psk: Uint8Array;
44
+ endpointAuth?: never;
45
+ }> | Readonly<{
46
+ endpointAuth: TunnelAuth;
47
+ rendezvousGroupID: string;
48
+ listenerAudience: string;
49
+ psk?: never;
50
+ }>);
42
51
  export type SessionProtocolRuntimeV3 = Readonly<{
43
52
  entropy(length: number): Uint8Array;
44
53
  monotonicMilliseconds(): number;
45
54
  }>;
46
55
  export declare class SessionV3Error extends Error {
47
- readonly code: "aborted" | "closed" | "going_away" | "handshake" | "open_rejected" | "protocol" | "rekey_failed" | "resource_exhausted" | "stream_reset" | "timeout";
48
- constructor(code: "aborted" | "closed" | "going_away" | "handshake" | "open_rejected" | "protocol" | "rekey_failed" | "resource_exhausted" | "stream_reset" | "timeout", message: string);
56
+ readonly code: "aborted" | "closed" | "going_away" | "handshake" | "endpoint_auth_failed" | "open_rejected" | "protocol" | "rekey_failed" | "resource_exhausted" | "stream_reset" | "timeout";
57
+ constructor(code: "aborted" | "closed" | "going_away" | "handshake" | "endpoint_auth_failed" | "open_rejected" | "protocol" | "rekey_failed" | "resource_exhausted" | "stream_reset" | "timeout", message: string);
49
58
  }
50
59
  declare class SessionRpcPeerV3 implements InternalRpcPeerV3 {
51
60
  private readonly createClient;
@@ -147,6 +156,7 @@ export declare class SessionV3 implements SessionV3Contract {
147
156
  private readonly terminationState;
148
157
  private readonly terminationController;
149
158
  private readonly suite;
159
+ readonly wireProfile: WireProfile;
150
160
  private readonly runtime;
151
161
  private readonly deadlines;
152
162
  private readonly idleTimeoutMs;
@@ -2,9 +2,11 @@ import { RpcClient } from "../rpc/client.js";
2
2
  import { SDK_DEFAULTS } from "../defaults.js";
3
3
  import { RpcRouter, RpcServer } from "../rpc/server.js";
4
4
  import { CarrierError } from "./carrier.js";
5
- import { FLOWERSEC_V3_PROFILE } from "./transportConstants.js";
5
+ import { transportV5, tunnelAuthV1 } from "./wireProfile.js";
6
+ import { hasTunnelAuth, initiateTunnelAuth, respondTunnelAuth } from "../tunnelAuth/credentials.js";
7
+ import { EndpointHandshakeError } from "../tunnelAuth/hpke.js";
6
8
  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";
9
+ import { DirectionV3, ProtocolV3Error, 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
10
  import { StreamLifetimeLedgerV3, StreamLifetimeLedgerV3Error, maxLogicalStreamIDV3, } from "./streamLifetimeLedger.js";
9
11
  import { UNRELIABLE_MESSAGES_FEATURE_V3, UNRELIABLE_MESSAGE_WIRE_BYTES_V3, createInternalUnreliableMessageChannelV3, } from "./unreliableMessage.js";
10
12
  const decoder = new TextDecoder();
@@ -81,6 +83,10 @@ export async function establishSessionV3(carrier, config, options = {}) {
81
83
  catch (error) {
82
84
  control?.abort(asError(error));
83
85
  carrier.abort({ code: 6, reason: "handshake failed" });
86
+ if (config.endpointAuth && (error instanceof ProtocolV3Error || error instanceof EndpointHandshakeError ||
87
+ (error instanceof SessionV3Error && error.code === "protocol"))) {
88
+ throw new SessionV3Error("endpoint_auth_failed", "tunnel endpoint authentication failed");
89
+ }
84
90
  if (error instanceof SessionV3Error || error instanceof HybridUnavailableV3)
85
91
  throw error;
86
92
  throw new SessionV3Error("handshake", `Flowersec v5 handshake failed: ${errorMessage(error)}`);
@@ -169,6 +175,7 @@ export class SessionV3 {
169
175
  terminationState = deferred();
170
176
  terminationController = new AbortController();
171
177
  suite;
178
+ wireProfile;
172
179
  runtime;
173
180
  deadlines;
174
181
  idleTimeoutMs;
@@ -181,6 +188,7 @@ export class SessionV3 {
181
188
  this.controlReader = controlReader;
182
189
  this.path = config.path;
183
190
  this.suite = config.suite;
191
+ this.wireProfile = config.endpointAuth ? tunnelAuthV1 : transportV5;
184
192
  this.runtime = config.runtime;
185
193
  this.deadlines = config.deadlines;
186
194
  this.idleTimeoutMs = sessionIdleTimeoutMs(config);
@@ -194,11 +202,12 @@ export class SessionV3 {
194
202
  this.peerLedger = new StreamLifetimeLedgerV3(this.role === 1 ? 2 : 1);
195
203
  this.outboundLedger = new StreamLifetimeLedgerV3(this.role);
196
204
  this.h3 = material.h3.slice();
197
- this.sendRoots.set(0, deriveEpochZero(material.sessionPRK, this.sendDirection));
198
- this.receiveRoots.set(0, deriveEpochZero(material.sessionPRK, this.receiveDirection));
205
+ this.sendRoots.set(0, deriveEpochZero(material.sessionPRK, this.sendDirection, this.wireProfile));
206
+ this.receiveRoots.set(0, deriveEpochZero(material.sessionPRK, this.receiveDirection, this.wireProfile));
199
207
  this.unreliableMessages = (material.selectedFeatures & UNRELIABLE_MESSAGES_FEATURE_V3) !== 0
200
208
  ? createInternalUnreliableMessageChannelV3({
201
209
  transport: requireUnreliableDatagrams(carrier),
210
+ profile: this.wireProfile,
202
211
  suite: this.suite,
203
212
  h3: this.h3,
204
213
  sendDirection: this.sendDirection,
@@ -332,14 +341,14 @@ export class SessionV3 {
332
341
  this.assertOpen();
333
342
  const roots = this.rootForSend(stream.sendEpoch);
334
343
  const material = stream.sendMaterial(roots, this.h3, this.sendDirection);
335
- const wire = sealRecordWireV3Internal(this.suite, material, this.h3, stream.id, this.sendDirection, stream.sendEpoch, stream.sendSequence, type, payload);
344
+ const wire = sealRecordWireV3Internal(this.suite, material, this.h3, stream.id, this.sendDirection, stream.sendEpoch, stream.sendSequence, type, payload, this.wireProfile);
336
345
  stream.sendSequence += 1n;
337
346
  await writeAll(stream.carrier, wire, signal);
338
347
  this.markAuthenticatedActivity();
339
348
  }
340
349
  async readStreamRecord(stream) {
341
350
  const rawHeader = await stream.reader.readExactly(24);
342
- const header = decodeRecordHeader(rawHeader);
351
+ const header = decodeRecordHeader(rawHeader, this.wireProfile);
343
352
  const priorACK = stream.priorACK !== undefined &&
344
353
  header.epoch === stream.priorACK.epoch && header.sequence === stream.priorACK.sequence;
345
354
  if (!priorACK && (header.epoch !== stream.receiveEpoch || header.sequence !== stream.receiveSequence)) {
@@ -348,7 +357,7 @@ export class SessionV3 {
348
357
  const roots = this.rootForReceive(header.epoch);
349
358
  const material = stream.receiveMaterial(roots, this.h3, this.receiveDirection, header.epoch);
350
359
  const ciphertext = await stream.reader.readExactly(header.ciphertextLength, undefined, true);
351
- const inner = decodeInnerRecordV3(openRecordWithRawHeaderV3Internal(this.suite, material, this.h3, stream.id, this.receiveDirection, header, rawHeader, ciphertext));
360
+ const inner = decodeInnerRecordV3(openRecordWithRawHeaderV3Internal(this.suite, material, this.h3, stream.id, this.receiveDirection, header, rawHeader, ciphertext, this.wireProfile));
352
361
  if (priorACK) {
353
362
  if (inner.type !== InnerTypeV3.StreamKeyUpdateACK)
354
363
  throw protocolError("late old-epoch record is not rekey ACK");
@@ -458,8 +467,8 @@ export class SessionV3 {
458
467
  };
459
468
  const prefaceRaw = encodeSetupPreface({
460
469
  ...unsigned,
461
- setupMAC: computeSetupMAC(roots.setupRoot, this.h3, unsigned),
462
- });
470
+ setupMAC: computeSetupMAC(roots.setupRoot, this.h3, unsigned, this.wireProfile),
471
+ }, this.wireProfile);
463
472
  await writeAll(carrierStream, prefaceRaw, options.signal);
464
473
  if (!this.localOpeningAllowedAfterGoAway(id)) {
465
474
  throw new SessionV3Error("going_away", "logical stream is beyond the peer GOAWAY boundary");
@@ -472,7 +481,7 @@ export class SessionV3 {
472
481
  });
473
482
  stream = new EncryptedStreamV3(this, carrierStream, id, kind, this.sendEpoch, this.receiveEpoch, releasePermit);
474
483
  this.streams.set(id, stream);
475
- stream.setOpenHash(computeValidatedOpenHashV3Internal(openRaw));
484
+ stream.setOpenHash(computeValidatedOpenHashV3Internal(openRaw, this.wireProfile));
476
485
  await stream.send(InnerTypeV3.Open, openRaw, options.signal);
477
486
  stream.startPump();
478
487
  await raceAbort(stream.opened.promise, options.signal);
@@ -524,14 +533,14 @@ export class SessionV3 {
524
533
  let prefaceRaw;
525
534
  let preface;
526
535
  prefaceRaw = await reader.readExactly(56);
527
- preface = decodeSetupPrefaceV3(prefaceRaw);
536
+ preface = decodeSetupPrefaceV3(prefaceRaw, this.wireProfile);
528
537
  const peerRole = this.role === 1 ? 2 : 1;
529
538
  if (preface.openerRole !== peerRole || preface.initialSendEpoch !== this.receiveEpoch) {
530
539
  await carrierStream.reset().catch(() => undefined);
531
540
  return;
532
541
  }
533
542
  const receiveRoots = this.rootForReceive(preface.initialSendEpoch);
534
- if (!verifySetupMAC(receiveRoots.setupRoot, this.h3, preface) || !this.acceptsPeerStreamAfterGoAway(preface.logicalStreamID)) {
543
+ if (!verifySetupMAC(receiveRoots.setupRoot, this.h3, preface, this.wireProfile) || !this.acceptsPeerStreamAfterGoAway(preface.logicalStreamID)) {
535
544
  await carrierStream.reset().catch(() => undefined);
536
545
  return;
537
546
  }
@@ -574,7 +583,7 @@ export class SessionV3 {
574
583
  if (first.type !== InnerTypeV3.Open)
575
584
  throw protocolError("OPEN must be first");
576
585
  const open = decodeOpenPayload(first.payload);
577
- const openHash = computeValidatedOpenHashV3Internal(first.payload);
586
+ const openHash = computeValidatedOpenHashV3Internal(first.payload, this.wireProfile);
578
587
  if (open.logicalStreamID !== preface.logicalStreamID ||
579
588
  !bytesEqual(open.fss3Hash, computeValidatedFSS3HashV3Internal(prefaceRaw))) {
580
589
  throw protocolError("OPEN binding mismatch");
@@ -735,25 +744,25 @@ export class SessionV3 {
735
744
  return task;
736
745
  }
737
746
  async writeControl(type, payload) {
738
- const material = this.controlSendKey ??= deriveControlRecordKey(this.rootForSend(this.controlSendEpoch), this.h3, this.sendDirection, this.controlSendEpoch);
739
- const wire = sealRecordWireV3Internal(this.suite, material, this.h3, 0n, this.sendDirection, this.controlSendEpoch, this.controlSendSequence, type, payload);
747
+ const material = this.controlSendKey ??= deriveControlRecordKey(this.rootForSend(this.controlSendEpoch), this.h3, this.sendDirection, this.controlSendEpoch, this.wireProfile);
748
+ const wire = sealRecordWireV3Internal(this.suite, material, this.h3, 0n, this.sendDirection, this.controlSendEpoch, this.controlSendSequence, type, payload, this.wireProfile);
740
749
  this.controlSendSequence += 1n;
741
750
  await writeAll(this.control, wire);
742
751
  this.markAuthenticatedActivity();
743
752
  }
744
753
  async readControl() {
745
754
  const rawHeader = await this.controlReader.readExactly(24);
746
- const header = decodeRecordHeader(rawHeader);
755
+ const header = decodeRecordHeader(rawHeader, this.wireProfile);
747
756
  const cutover = header.epoch === this.controlReceiveEpoch + 1 &&
748
757
  header.epoch <= this.receiveEpoch && header.sequence === 0n;
749
758
  if (!cutover && (header.epoch !== this.controlReceiveEpoch || header.sequence !== this.controlReceiveSequence)) {
750
759
  throw protocolError("unexpected control epoch or sequence");
751
760
  }
752
761
  const ciphertext = await this.controlReader.readExactly(header.ciphertextLength, undefined, true);
753
- const material = (!cutover ? this.controlReceiveKey : undefined) ?? deriveControlRecordKey(this.rootForReceive(header.epoch), this.h3, this.receiveDirection, header.epoch);
762
+ const material = (!cutover ? this.controlReceiveKey : undefined) ?? deriveControlRecordKey(this.rootForReceive(header.epoch), this.h3, this.receiveDirection, header.epoch, this.wireProfile);
754
763
  let inner;
755
764
  try {
756
- inner = decodeInnerRecordV3(openRecordWithRawHeaderV3Internal(this.suite, material, this.h3, 0n, this.receiveDirection, header, rawHeader, ciphertext));
765
+ inner = decodeInnerRecordV3(openRecordWithRawHeaderV3Internal(this.suite, material, this.h3, 0n, this.receiveDirection, header, rawHeader, ciphertext, this.wireProfile));
757
766
  }
758
767
  catch (error) {
759
768
  wipeRecordKey(material);
@@ -964,7 +973,7 @@ export class SessionV3 {
964
973
  respondersFrozen = true;
965
974
  const nextEpoch = currentEpoch + 1;
966
975
  const currentRoots = this.rootForSend(currentEpoch);
967
- const nextRoots = deriveEpochRoots(deriveNextEpoch(currentRoots.rekeyRoot, this.h3, this.sendDirection, nextEpoch));
976
+ const nextRoots = deriveEpochRoots(deriveNextEpoch(currentRoots.rekeyRoot, this.h3, this.sendDirection, nextEpoch, this.wireProfile), this.wireProfile);
968
977
  this.sendRoots.set(nextEpoch, nextRoots);
969
978
  this.preparingSendEpoch = nextEpoch;
970
979
  const watermark = this.nextLogicalID > 2n ? this.nextLogicalID - 2n : 0n;
@@ -1121,7 +1130,7 @@ export class SessionV3 {
1121
1130
  this.pendingReceiveEpoch = nextEpoch;
1122
1131
  const current = this.rootForReceive(this.receiveEpoch);
1123
1132
  if (!this.receiveRoots.has(nextEpoch)) {
1124
- this.receiveRoots.set(nextEpoch, deriveEpochRoots(deriveNextEpoch(current.rekeyRoot, this.h3, this.receiveDirection, nextEpoch)));
1133
+ this.receiveRoots.set(nextEpoch, deriveEpochRoots(deriveNextEpoch(current.rekeyRoot, this.h3, this.receiveDirection, nextEpoch, this.wireProfile), this.wireProfile));
1125
1134
  }
1126
1135
  const streams = [...this.streams.values()];
1127
1136
  await Promise.all(streams.map(async (stream) => await stream.waitReceiveRekey(transition, nextEpoch, signal)));
@@ -1622,7 +1631,7 @@ class EncryptedStreamV3 {
1622
1631
  sendMaterial(roots, h3, direction) {
1623
1632
  let material = this.sendMaterials.get(this.sendEpoch);
1624
1633
  if (material === undefined) {
1625
- material = deriveStreamMaterial(roots.streamRoot, h3, this.id, direction, this.sendEpoch);
1634
+ material = deriveStreamMaterial(roots.streamRoot, h3, this.id, direction, this.sendEpoch, this.session.wireProfile);
1626
1635
  this.sendMaterials.set(this.sendEpoch, material);
1627
1636
  }
1628
1637
  return material;
@@ -1630,7 +1639,7 @@ class EncryptedStreamV3 {
1630
1639
  receiveMaterial(roots, h3, direction, epoch) {
1631
1640
  let material = this.receiveMaterials.get(epoch);
1632
1641
  if (material === undefined) {
1633
- material = deriveStreamMaterial(roots.streamRoot, h3, this.id, direction, epoch);
1642
+ material = deriveStreamMaterial(roots.streamRoot, h3, this.id, direction, epoch, this.session.wireProfile);
1634
1643
  this.receiveMaterials.set(epoch, material);
1635
1644
  }
1636
1645
  return material;
@@ -1770,7 +1779,7 @@ class EncryptedStreamV3 {
1770
1779
  throw protocolError("invalid stream rekey transition");
1771
1780
  const current = this.session.rootForReceive(this.receiveEpoch);
1772
1781
  if (!this.session.hasReceiveRoots(nextEpoch)) {
1773
- this.session.installReceiveRoots(nextEpoch, deriveEpochRoots(deriveNextEpoch(current.rekeyRoot, this.session.transcriptHash(), this.session.receiveDirectionValue(), nextEpoch)));
1782
+ this.session.installReceiveRoots(nextEpoch, deriveEpochRoots(deriveNextEpoch(current.rekeyRoot, this.session.transcriptHash(), this.session.receiveDirectionValue(), nextEpoch, this.session.wireProfile), this.session.wireProfile));
1774
1783
  }
1775
1784
  if (this.pendingSendRekey?.transition === transition && this.pendingSendRekey.epoch === nextEpoch) {
1776
1785
  this.priorACK = { epoch: header.epoch, sequence: this.receiveSequence };
@@ -1827,104 +1836,147 @@ class EncryptedStreamV3 {
1827
1836
  }
1828
1837
  }
1829
1838
  async function clientHandshake(control, reader, config, offeredFeatures, signal) {
1839
+ const profile = config.endpointAuth ? tunnelAuthV1 : transportV5;
1840
+ let setup;
1830
1841
  const key = generateEphemeralKeyV3(config.suite, (length) => config.runtime.entropy(length));
1831
- const controlPreface = encodeControlPrefaceV3();
1832
- const initRaw = encodeClientInitV3({
1833
- profile: FLOWERSEC_V3_PROFILE,
1834
- channelID: config.channelID,
1835
- sessionContractHash: config.sessionContractHash,
1836
- clientRole: 1,
1837
- suite: config.suite,
1838
- clientEphemeralPublic: key.publicKey,
1839
- nonceC: sessionRandomBytes(config, 32),
1840
- selectedFeatures: offeredFeatures,
1841
- maxInboundStreams: config.maxInboundStreams,
1842
- clientAdmissionBinding: config.localAdmissionBinding,
1843
- clientEndpointInstanceID: config.localEndpointInstanceID,
1844
- });
1845
- await writeAll(control, controlPreface, signal);
1846
- await writeAll(control, initRaw, signal);
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();
1842
+ let handshakePRK;
1843
+ try {
1844
+ setup = config.endpointAuth && await initiateTunnelAuth(config.endpointAuth, endpointBinding(config));
1845
+ const controlPreface = encodeControlPrefaceV3(profile);
1846
+ const initRaw = encodeClientInitV3({
1847
+ profile: profile.name,
1848
+ ...(setup ? { hpkeEnc: setup.enc } : {}),
1849
+ channelID: config.channelID,
1850
+ sessionContractHash: config.sessionContractHash,
1851
+ clientRole: 1,
1852
+ suite: config.suite,
1853
+ clientEphemeralPublic: key.publicKey,
1854
+ nonceC: sessionRandomBytes(config, 32),
1855
+ selectedFeatures: offeredFeatures,
1856
+ maxInboundStreams: config.maxInboundStreams,
1857
+ clientAdmissionBinding: config.localAdmissionBinding,
1858
+ clientEndpointInstanceID: config.localEndpointInstanceID,
1859
+ }, profile);
1860
+ await writeAll(control, controlPreface, signal);
1861
+ await writeAll(control, initRaw, signal);
1862
+ const serverRaw = await readHandshakeFrame(reader, signal, profile);
1863
+ const h0 = computeHandshakeH0V3(controlPreface, initRaw, profile);
1864
+ if (serverRaw[5] === HandshakeMessageTypeV3.ServerUnavailable) {
1865
+ if (!config.psk)
1866
+ throw protocolError("unexpected handshake rejection");
1867
+ verifyServerUnavailableV3(serverRaw, config.psk, h0, expectations(config, false));
1868
+ await control.closeWrite();
1869
+ throw new HybridUnavailableV3();
1870
+ }
1871
+ const server = decodeServerFinishedV3(serverRaw, config.suite, profile);
1872
+ validateServerFinishedV3(server, expectations(config, false));
1873
+ if ((server.core.selectedFeatures & ~offeredFeatures) !== 0) {
1874
+ throw protocolError("server selected an unoffered feature");
1875
+ }
1876
+ const shared = clientSharedSecretV3(config.suite, key.privateKey, server.core.serverEphemeralPublic);
1877
+ key.privateKey.fill(0);
1878
+ handshakePRK = extractHandshakeKey(setup?.secret ?? config.psk, shared);
1879
+ const h1 = computeHandshakeH1V3(h0, encodeServerFinishedCoreV3(server.core, config.suite, profile), profile);
1880
+ if (!bytesEqual(server.serverConfirm, computeServerConfirmV3(handshakePRK, h1, profile))) {
1881
+ throw protocolError("server confirm mismatch");
1882
+ }
1883
+ const clientCore = encodeClientFinishedCoreV3(server.core.handshakeID, profile);
1884
+ const h2 = computeHandshakeH2V3(h1, serverRaw, clientCore, profile);
1885
+ const clientRaw = encodeClientFinishedV3({
1886
+ handshakeID: server.core.handshakeID,
1887
+ clientConfirm: computeClientConfirmV3(handshakePRK, h2, profile),
1888
+ }, profile);
1889
+ await writeAll(control, clientRaw, signal);
1890
+ const h3 = computeHandshakeH3V3(h2, clientRaw, profile);
1891
+ return {
1892
+ h3,
1893
+ sessionPRK: deriveSessionPRKV3(h3, handshakePRK),
1894
+ selectedFeatures: server.core.selectedFeatures,
1895
+ };
1896
+ }
1897
+ finally {
1898
+ key.privateKey.fill(0);
1899
+ setup?.secret.fill(0);
1900
+ handshakePRK?.fill(0);
1853
1901
  }
1854
- const server = decodeServerFinishedV3(serverRaw, config.suite);
1855
- validateServerFinishedV3(server, expectations(config, false));
1856
- if ((server.core.selectedFeatures & ~offeredFeatures) !== 0) {
1857
- throw protocolError("server selected an unoffered feature");
1858
- }
1859
- const shared = clientSharedSecretV3(config.suite, key.privateKey, server.core.serverEphemeralPublic);
1860
- key.privateKey.fill(0);
1861
- const handshakePRK = deriveHandshakePRKV3(config.psk, shared);
1862
- shared.fill(0);
1863
- const h1 = computeHandshakeH1V3(h0, encodeServerFinishedCoreV3(server.core, config.suite));
1864
- if (!bytesEqual(server.serverConfirm, computeServerConfirmV3(handshakePRK, h1))) {
1865
- throw protocolError("server confirm mismatch");
1866
- }
1867
- const clientCore = encodeClientFinishedCoreV3(server.core.handshakeID);
1868
- const h2 = computeHandshakeH2V3(h1, serverRaw, clientCore);
1869
- const clientRaw = encodeClientFinishedV3({
1870
- handshakeID: server.core.handshakeID,
1871
- clientConfirm: computeClientConfirmV3(handshakePRK, h2),
1872
- });
1873
- await writeAll(control, clientRaw, signal);
1874
- const h3 = computeHandshakeH3V3(h2, clientRaw);
1875
- return {
1876
- h3,
1877
- sessionPRK: deriveSessionPRKV3(h3, handshakePRK),
1878
- selectedFeatures: server.core.selectedFeatures,
1879
- };
1880
1902
  }
1881
1903
  async function serverHandshake(control, reader, config, localFeatures, signal) {
1904
+ const profile = config.endpointAuth ? tunnelAuthV1 : transportV5;
1882
1905
  const controlPreface = await reader.readExactly(16, signal);
1883
- parseControlPrefaceV3(controlPreface);
1884
- const clientRaw = await readHandshakeFrame(reader, signal);
1885
- const client = decodeClientInitV3(clientRaw);
1886
- validateClientInitV3(client, expectations(config, true));
1887
- const h0 = computeHandshakeH0V3(controlPreface, clientRaw);
1906
+ parseControlPrefaceV3(controlPreface, profile);
1907
+ const clientRaw = await readHandshakeFrame(reader, signal, profile);
1908
+ const client = decodeClientInitV3(clientRaw, profile);
1909
+ validateClientInitV3(client, expectations(config, true), profile);
1910
+ const h0 = computeHandshakeH0V3(controlPreface, clientRaw, profile);
1888
1911
  if (config.suite === CipherSuiteV3.XWing && config.enableHybridKeyExchange !== true) {
1912
+ if (!config.psk)
1913
+ throw protocolError("endpoint suite unavailable");
1889
1914
  await writeAll(control, serverUnavailableV3(config.psk, h0, config.localAdmissionBinding, config.localEndpointInstanceID), signal);
1890
1915
  await control.closeWrite();
1891
1916
  await reader.readEOF(signal);
1892
1917
  throw new HybridUnavailableV3();
1893
1918
  }
1894
- const { publicKey, shared } = serverKeyShareV3(config.suite, client.clientEphemeralPublic, (length) => config.runtime.entropy(length));
1895
- const handshakePRK = deriveHandshakePRKV3(config.psk, shared);
1896
- shared.fill(0);
1897
- const core = {
1898
- suite: config.suite,
1899
- handshakeID: sessionRandomBytes(config, 16),
1900
- serverEphemeralPublic: publicKey,
1901
- nonceS: sessionRandomBytes(config, 32),
1902
- sessionContractHash: config.sessionContractHash,
1903
- selectedFeatures: client.selectedFeatures & localFeatures,
1904
- maxInboundStreams: config.maxInboundStreams,
1905
- serverAdmissionBinding: config.localAdmissionBinding,
1906
- serverEndpointInstanceID: config.localEndpointInstanceID,
1907
- };
1908
- const h1 = computeHandshakeH1V3(h0, encodeServerFinishedCoreV3(core, config.suite));
1909
- const serverRaw = encodeServerFinishedV3({
1910
- core,
1911
- serverConfirm: computeServerConfirmV3(handshakePRK, h1),
1912
- }, config.suite);
1913
- await writeAll(control, serverRaw, signal);
1914
- const clientFinishedRaw = await readHandshakeFrame(reader, signal);
1915
- const clientFinished = decodeClientFinishedV3(clientFinishedRaw);
1916
- if (!bytesEqual(clientFinished.handshakeID, core.handshakeID))
1917
- throw protocolError("handshake ID mismatch");
1918
- const clientCore = encodeClientFinishedCoreV3(clientFinished.handshakeID);
1919
- const h2 = computeHandshakeH2V3(h1, serverRaw, clientCore);
1920
- if (!bytesEqual(clientFinished.clientConfirm, computeClientConfirmV3(handshakePRK, h2))) {
1921
- throw protocolError("client confirm mismatch");
1922
- }
1923
- const h3 = computeHandshakeH3V3(h2, clientFinishedRaw);
1919
+ const secret = config.endpointAuth && await respondTunnelAuth(config.endpointAuth, endpointBinding(config), client.hpkeEnc);
1920
+ let handshakePRK;
1921
+ try {
1922
+ const { publicKey, shared } = serverKeyShareV3(config.suite, client.clientEphemeralPublic, (length) => config.runtime.entropy(length));
1923
+ handshakePRK = extractHandshakeKey(secret ?? config.psk, shared);
1924
+ const core = {
1925
+ suite: config.suite,
1926
+ handshakeID: sessionRandomBytes(config, 16),
1927
+ serverEphemeralPublic: publicKey,
1928
+ nonceS: sessionRandomBytes(config, 32),
1929
+ sessionContractHash: config.sessionContractHash,
1930
+ selectedFeatures: client.selectedFeatures & localFeatures,
1931
+ maxInboundStreams: config.maxInboundStreams,
1932
+ serverAdmissionBinding: config.localAdmissionBinding,
1933
+ serverEndpointInstanceID: config.localEndpointInstanceID,
1934
+ };
1935
+ const h1 = computeHandshakeH1V3(h0, encodeServerFinishedCoreV3(core, config.suite, profile), profile);
1936
+ const serverRaw = encodeServerFinishedV3({
1937
+ core,
1938
+ serverConfirm: computeServerConfirmV3(handshakePRK, h1, profile),
1939
+ }, config.suite, profile);
1940
+ await writeAll(control, serverRaw, signal);
1941
+ const clientFinishedRaw = await readHandshakeFrame(reader, signal, profile);
1942
+ const clientFinished = decodeClientFinishedV3(clientFinishedRaw, profile);
1943
+ if (!bytesEqual(clientFinished.handshakeID, core.handshakeID))
1944
+ throw protocolError("handshake ID mismatch");
1945
+ const clientCore = encodeClientFinishedCoreV3(clientFinished.handshakeID, profile);
1946
+ const h2 = computeHandshakeH2V3(h1, serverRaw, clientCore, profile);
1947
+ if (!bytesEqual(clientFinished.clientConfirm, computeClientConfirmV3(handshakePRK, h2, profile))) {
1948
+ throw protocolError("client confirm mismatch");
1949
+ }
1950
+ const h3 = computeHandshakeH3V3(h2, clientFinishedRaw, profile);
1951
+ return {
1952
+ h3,
1953
+ sessionPRK: deriveSessionPRKV3(h3, handshakePRK),
1954
+ selectedFeatures: core.selectedFeatures,
1955
+ };
1956
+ }
1957
+ finally {
1958
+ secret?.fill(0);
1959
+ handshakePRK?.fill(0);
1960
+ }
1961
+ }
1962
+ function extractHandshakeKey(salt, shared) {
1963
+ try {
1964
+ if (!salt)
1965
+ throw protocolError("missing handshake secret");
1966
+ return deriveHandshakePRKV3(salt, shared);
1967
+ }
1968
+ finally {
1969
+ shared.fill(0);
1970
+ }
1971
+ }
1972
+ function endpointBinding(config) {
1973
+ const initiator = config.role === "client";
1924
1974
  return {
1925
- h3,
1926
- sessionPRK: deriveSessionPRKV3(h3, handshakePRK),
1927
- selectedFeatures: core.selectedFeatures,
1975
+ mode: config.endpointAuth.mode, suite: config.suite, channelID: config.channelID,
1976
+ rendezvousGroupID: config.rendezvousGroupID, listenerAudience: config.listenerAudience,
1977
+ clientEndpointID: initiator ? config.localEndpointInstanceID : config.expectedPeerEndpointInstanceID,
1978
+ serverEndpointID: initiator ? config.expectedPeerEndpointInstanceID : config.localEndpointInstanceID,
1979
+ contractHash: config.sessionContractHash,
1928
1980
  };
1929
1981
  }
1930
1982
  function expectations(config, peerIsClient) {
@@ -1938,13 +1990,13 @@ function expectations(config, peerIsClient) {
1938
1990
  expectedEndpointInstanceID: config.expectedPeerEndpointInstanceID,
1939
1991
  };
1940
1992
  }
1941
- async function readHandshakeFrame(reader, signal) {
1993
+ async function readHandshakeFrame(reader, signal, profile) {
1942
1994
  const header = await reader.readExactly(12, signal);
1943
1995
  const length = new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(8, false);
1944
1996
  if (length < 1 || length > 8_192)
1945
1997
  throw protocolError("invalid handshake payload length");
1946
1998
  const raw = concat(header, await reader.readExactly(length, signal));
1947
- decodeHandshakeFrameV3(raw);
1999
+ decodeHandshakeFrameV3(raw, profile);
1948
2000
  return raw;
1949
2001
  }
1950
2002
  class ExactReader {
@@ -2252,13 +2304,21 @@ function validateConfig(carrier, config) {
2252
2304
  sessionCloseTimeoutMs(config);
2253
2305
  for (const [name, value] of [
2254
2306
  ["session contract hash", config.sessionContractHash],
2255
- ["PSK", config.psk],
2256
2307
  ["local admission binding", config.localAdmissionBinding],
2257
2308
  ["peer admission binding", config.peerAdmissionBinding],
2258
2309
  ]) {
2259
2310
  if (value.length !== 32)
2260
2311
  throw new SessionV3Error("handshake", `${name} must be 32 bytes`);
2261
2312
  }
2313
+ if (config.endpointAuth) {
2314
+ if (!hasTunnelAuth(config.endpointAuth) || config.psk !== undefined || config.path !== "tunnel" || config.endpointAuth.role !== (config.role === "client" ? 1 : 2) ||
2315
+ (config.suite === CipherSuiteV3.XWing && !config.enableHybridKeyExchange)) {
2316
+ throw protocolError("invalid endpoint authentication configuration");
2317
+ }
2318
+ }
2319
+ else if (config.psk?.length !== 32) {
2320
+ throw protocolError("invalid handshake PSK");
2321
+ }
2262
2322
  if (config.path === "direct") {
2263
2323
  if (config.localEndpointInstanceID !== "" || config.expectedPeerEndpointInstanceID !== "") {
2264
2324
  throw new SessionV3Error("handshake", "direct session endpoint IDs must be empty");
@@ -2387,8 +2447,8 @@ function bytesEqual(left, right) {
2387
2447
  difference |= left[index] ^ right[index];
2388
2448
  return difference === 0;
2389
2449
  }
2390
- function deriveControlRecordKey(roots, h3, direction, epoch) {
2391
- const { secret, recordKey, noncePrefix } = deriveControlMaterial(roots.controlRoot, h3, direction, epoch);
2450
+ function deriveControlRecordKey(roots, h3, direction, epoch, profile) {
2451
+ const { secret, recordKey, noncePrefix } = deriveControlMaterial(roots.controlRoot, h3, direction, epoch, profile);
2392
2452
  secret.fill(0);
2393
2453
  return { recordKey, noncePrefix };
2394
2454
  }
@@ -1,6 +1,6 @@
1
1
  import type { Session } from "../public/contract.js";
2
2
  import type { RpcRouter } from "../rpc/server.js";
3
- import { type ArtifactV3, type CanonicalArtifactCandidateV3 } from "./artifact.js";
3
+ import { type ConnectionArtifact, type CanonicalArtifactCandidateV3 } from "./artifact.js";
4
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";
@@ -23,7 +23,7 @@ export type ReadyAdmissionTransportV3 = Readonly<{
23
23
  close(): Promise<void>;
24
24
  abort(): void;
25
25
  }>;
26
- export type CandidateDialerV3 = (candidate: CanonicalArtifactCandidateV3, artifact: ArtifactV3, attemptNowUnixSeconds: number, capability: RuntimeCapabilityDescriptorV3, signal: AbortSignal) => Promise<ReadyAdmissionTransportV3>;
26
+ export type CandidateDialerV3 = (candidate: CanonicalArtifactCandidateV3, artifact: ConnectionArtifact, attemptNowUnixSeconds: number, capability: RuntimeCapabilityDescriptorV3, signal: AbortSignal) => Promise<ReadyAdmissionTransportV3>;
27
27
  export type SessionConnectorRuntimeV3 = Readonly<{
28
28
  keyExchange?: KeyExchangeMode;
29
29
  enableHybridKeyExchange?: boolean;