@browsercore/quic 0.2.1 → 0.2.3

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 (61) hide show
  1. package/README.md +19 -1
  2. package/dist/connection.d.ts +149 -23
  3. package/dist/connection.d.ts.map +1 -1
  4. package/dist/connection.js +543 -66
  5. package/dist/connection.js.map +1 -1
  6. package/dist/crypto/hash-length.d.ts +11 -0
  7. package/dist/crypto/hash-length.d.ts.map +1 -0
  8. package/dist/crypto/hash-length.js +20 -0
  9. package/dist/crypto/hash-length.js.map +1 -0
  10. package/dist/crypto/index.d.ts +8 -0
  11. package/dist/crypto/index.d.ts.map +1 -0
  12. package/dist/crypto/index.js +8 -0
  13. package/dist/crypto/index.js.map +1 -0
  14. package/dist/crypto/key-derivation.d.ts +87 -0
  15. package/dist/crypto/key-derivation.d.ts.map +1 -0
  16. package/dist/crypto/key-derivation.js +123 -0
  17. package/dist/crypto/key-derivation.js.map +1 -0
  18. package/dist/errors.d.ts +27 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/errors.js +36 -1
  21. package/dist/errors.js.map +1 -1
  22. package/dist/frame/frame.d.ts.map +1 -1
  23. package/dist/frame/frame.js +2 -2
  24. package/dist/frame/frame.js.map +1 -1
  25. package/dist/handshake/index.d.ts +10 -0
  26. package/dist/handshake/index.d.ts.map +1 -0
  27. package/dist/handshake/index.js +9 -0
  28. package/dist/handshake/index.js.map +1 -0
  29. package/dist/handshake/quic-handshake.d.ts +119 -0
  30. package/dist/handshake/quic-handshake.d.ts.map +1 -0
  31. package/dist/handshake/quic-handshake.js +213 -0
  32. package/dist/handshake/quic-handshake.js.map +1 -0
  33. package/dist/handshake/quic-transport-adapter.d.ts +86 -0
  34. package/dist/handshake/quic-transport-adapter.d.ts.map +1 -0
  35. package/dist/handshake/quic-transport-adapter.js +166 -0
  36. package/dist/handshake/quic-transport-adapter.js.map +1 -0
  37. package/dist/index.d.ts +8 -5
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +10 -4
  40. package/dist/index.js.map +1 -1
  41. package/dist/packet/packet-protection.d.ts +158 -0
  42. package/dist/packet/packet-protection.d.ts.map +1 -0
  43. package/dist/packet/packet-protection.js +312 -0
  44. package/dist/packet/packet-protection.js.map +1 -0
  45. package/dist/packet/packet.d.ts +2 -2
  46. package/dist/packet/packet.d.ts.map +1 -1
  47. package/dist/packet/packet.js +4 -4
  48. package/dist/packet/packet.js.map +1 -1
  49. package/dist/stream/stream.d.ts +7 -11
  50. package/dist/stream/stream.d.ts.map +1 -1
  51. package/dist/stream/stream.js +16 -28
  52. package/dist/stream/stream.js.map +1 -1
  53. package/dist/transport-params.d.ts +4 -0
  54. package/dist/transport-params.d.ts.map +1 -1
  55. package/dist/transport-params.js +8 -1
  56. package/dist/transport-params.js.map +1 -1
  57. package/dist/types.d.ts +129 -41
  58. package/dist/types.d.ts.map +1 -1
  59. package/dist/types.js +8 -20
  60. package/dist/types.js.map +1 -1
  61. package/package.json +7 -5
@@ -1,33 +1,65 @@
1
1
  /**
2
- * QUIC connection lifecycle + datagram read loop (RFC 9000 §5, §12).
2
+ * QUIC connection lifecycle + datagram read loop (RFC 9000 §5, §12) with TLS
3
+ * handshake + packet protection (RFC 9001).
3
4
  *
4
- * Wires packet header parsing/serialization, the frame layer, and the stream
5
- * manager over an injected {@link DatagramTransport} (UDP). The connection owns
6
- * the read loop: it turns inbound datagrams into frames, dispatches each to the
7
- * stream manager, and drains pending stream sends back into outbound packets.
5
+ * Wires packet header parsing/serialization, the frame layer, the stream
6
+ * manager, the TLS 1.3 handshake (over QUIC stream 0), and QUIC's two-layer
7
+ * packet protection (AEAD payload encryption + header protection) over an
8
+ * injected {@link DatagramTransport} (UDP).
9
+ *
10
+ * The connection owns the read loop: it turns inbound datagrams into frames,
11
+ * dispatches each to the stream manager, and drains pending stream sends back
12
+ * into outbound packets. After the TLS handshake completes, every packet is
13
+ * protected with the derived QUIC keys for its key phase:
14
+ *
15
+ * Initial packets → initial keys (derived from DCID)
16
+ * Handshake packets → handshake keys (derived from TLS handshake secrets)
17
+ * 1-RTT packets → application keys (derived from TLS application secrets)
8
18
  *
9
19
  * Honest limitations:
10
- * - The TLS 1.3 handshake and packet protection (header protection + AEAD
11
- * payload encryption) are out of scope. `connectQuic()` returns a connection
12
- * that moves *unprotected* frames over the transport directly — enough to
13
- * drive the data plane and to be tested with a fake datagram transport. A
14
- * production build layers protection + the handshake on top of this.
15
- * - No connection migration beyond PATH_CHALLENGE / PATH_RESPONSE, and no
16
- * liveness PING.
20
+ * - 0-RTT, KeyUpdate, key-phase-bit handling, and connection migration
21
+ * beyond PATH_CHALLENGE / PATH_RESPONSE are out of scope. No congestion
22
+ * controller. No liveness PING.
17
23
  *
18
24
  * Concurrency model: the read loop is a single async task pulling datagrams from
19
25
  * the transport. Outbound frames are produced synchronously by the stream
20
26
  * manager and packed into packets; writes resolve once bytes are buffered.
21
27
  */
22
- import { QuicFrameType, } from "./types.js";
23
- import { parsePacketHeader, serializeShortHeader } from "./packet/packet.js";
28
+ import { createRandomSource } from "@browsercore/transport";
29
+ import { QuicFrameType, systemClock, } from "./types.js";
30
+ import { parsePacketHeader, serializeShortHeader, serializeLongHeader, readPacketNumber, } from "./packet/packet.js";
31
+ import { protectPayload, unprotectPayload, } from "./packet/packet-protection.js";
24
32
  import { readFrames, serializeFrame } from "./frame/frame.js";
25
- import { ConnectionClosedError } from "./errors.js";
33
+ import { ConnectionClosedError, ConnectionClosingError, PacketProtectionError, QuicError, TlsHandshakeError, } from "./errors.js";
26
34
  import { createStreamManager } from "./stream/stream.js";
27
- import { concatAll, hex } from "./utils.js";
35
+ import { assertNever, concatAll, hex } from "./utils.js";
28
36
  import { decodeTransportParameters, encodeTransportParameters, fromWireParameters, toWireParameters, } from "./transport-params.js";
37
+ import { adaptQuicStreamToTransport } from "./handshake/quic-transport-adapter.js";
38
+ import { runQuicHandshake } from "./handshake/quic-handshake.js";
29
39
  /** Largest UDP payload we will pack into a single datagram (RFC 9000 §14). */
30
40
  const MAX_DATAGRAM_PAYLOAD = 1200;
41
+ /** QUIC long header version (QUIC v1, RFC 9000 §32.2.1). */
42
+ const QUIC_VERSION_V1 = 0x00000001;
43
+ /** Default TLS profile for the QUIC handshake — modern TLS 1.3, X25519 + secp256r1. */
44
+ const DEFAULT_TLS_PROFILE = {
45
+ cipherSuites: [
46
+ "TLS_AES_256_GCM_SHA384",
47
+ "TLS_AES_128_GCM_SHA256",
48
+ "TLS_CHACHA20_POLY1305_SHA256",
49
+ ],
50
+ extensionOrder: [
51
+ 0, 10, 11, 13, 16, 17513, 18, 23, 27, 35, 41, 43, 45, 5, 51, 65281,
52
+ ],
53
+ keyShareGroups: ["x25519", "secp256r1"],
54
+ signatureAlgorithms: [
55
+ "ecdsa_secp256r1_sha256",
56
+ "rsa_pss_rsae_sha256",
57
+ "rsa_pss_rsae_sha384",
58
+ ],
59
+ supportedVersions: [{ name: "TLS 1.3", wire: 0x0304 }],
60
+ serverName: "",
61
+ grease: true,
62
+ };
31
63
  /**
32
64
  * Concrete QUIC connection. The public surface matches the fixed
33
65
  * `QuicConnection` interface; internal state is kept on the instance.
@@ -38,20 +70,54 @@ export class QuicConnectionImpl {
38
70
  transport;
39
71
  /** The peer's UDP address. */
40
72
  peer;
41
- /** Stream manager (also an EventEmitter for connection-level signals). */
73
+ /** Stream manager (signals connection-level events via QuicSignalSink). */
42
74
  manager;
43
75
  /** Our current destination connection id (the one we put on outbound packets). */
44
76
  dcid;
77
+ /** Random source for connection ids and packet numbers. */
78
+ random;
79
+ /**
80
+ * Cryptographic provider for QUIC key derivation and packet protection
81
+ * (RFC 9001). Seeded with the injected {@link random} source so the
82
+ * HKDF-based key schedule is reproducible under test.
83
+ */
84
+ cryptoProvider;
85
+ /** TLS ClientHello configuration for the handshake. */
86
+ tlsProfile;
45
87
  /**
46
88
  * Our transport parameters encoded for the wire. Produced at handshake
47
89
  * time so a TLS layer can carry them to the peer in the QUIC extension.
48
90
  */
49
91
  encodedLocalParameters;
92
+ /**
93
+ * EventProvider for the QUIC→TLS transport adapter. Resolved from
94
+ * {@link QuicOptions.events} or {@link QuicOptions.platform}.events —
95
+ * there is no singleton fallback.
96
+ */
97
+ events;
98
+ /** Result of the TLS handshake — set once the handshake completes. */
99
+ handshakeResult;
100
+ /**
101
+ * Current key phase for outbound packets. Advances from initial → handshake
102
+ * → application as the handshake progresses. The protection layer selects
103
+ * the correct secrets based on this + the packet's header form.
104
+ */
105
+ outboundKeyPhase = "initial";
106
+ /** Next outbound packet number, per key phase (RFC 9000 §12.3). */
107
+ nextPacketNumber = {
108
+ initial: 0n,
109
+ handshake: 0n,
110
+ application: 0n,
111
+ };
112
+ /** Largest received packet number per key phase (for packet-number decoding). */
113
+ largestReceivedPn = {
114
+ initial: -1n,
115
+ handshake: -1n,
116
+ application: -1n,
117
+ };
50
118
  /**
51
119
  * PATH_CHALLENGEs we have issued and are awaiting a PATH_RESPONSE for,
52
120
  * keyed by the hex-encoded 8-byte challenge data (RFC 9000 §8.2.1).
53
- * A full implementation would also track the address pair being validated
54
- * and retire stale challenges on a timer; this is the data plane only.
55
121
  */
56
122
  pendingPathChallenges = new Set();
57
123
  /** Set once the connection begins graceful shutdown. */
@@ -60,18 +126,73 @@ export class QuicConnectionImpl {
60
126
  closed = false;
61
127
  /** Buffered outbound frames waiting to be packed into the next packet. */
62
128
  outboundFrames = [];
63
- constructor(id, options, manager, dcid) {
129
+ /**
130
+ * @param onPeerClose Register a handler for peer CONNECTION_CLOSE signals.
131
+ * The stream manager calls this through its signal sink;
132
+ * the connection supplies the handler at construction.
133
+ */
134
+ constructor(id, options, manager, dcid, onPeerClose) {
64
135
  this.id = id;
65
136
  this.transport = options.transport;
66
137
  this.peer = options.peer;
67
138
  this.manager = manager;
68
139
  this.dcid = dcid;
140
+ // Let the caller (connectQuic) wire the peer-close signal handler.
141
+ if (onPeerClose !== undefined) {
142
+ onPeerClose((errorCode, reason) => {
143
+ void this.onPeerClose(errorCode, reason);
144
+ });
145
+ }
146
+ this.random = options.random ?? createRandomSource();
147
+ // Resolve the crypto provider: explicit option → platform. There is no
148
+ // singleton fallback — QUIC's key schedule (RFC 9001) delegates all
149
+ // operations to the injected provider, which is seeded with the same
150
+ // random source below to make derived bytes reproducible under test.
151
+ const randomSource = this.random;
152
+ const cryptoBackend = options.crypto ?? options.platform?.crypto?.provider;
153
+ if (cryptoBackend === undefined) {
154
+ throw new QuicError("QuicOptions requires `crypto` or `platform.crypto.provider` for the QUIC key schedule (RFC 9001)");
155
+ }
156
+ this.cryptoProvider = new Proxy(cryptoBackend, {
157
+ get(target, prop, receiver) {
158
+ if (prop === "randomBytes") {
159
+ return (length) => randomSource.randomBytes(length);
160
+ }
161
+ return Reflect.get(target, prop, receiver);
162
+ },
163
+ });
164
+ // Resolve the TLS ClientHello configuration for the handshake.
165
+ this.tlsProfile = toTlsClientHelloConfig(options.tlsProfile, options.serverName);
69
166
  // Encode our transport parameters for the wire at construction. A real
70
167
  // TLS handshake would carry these to the peer in the QUIC extension;
71
168
  // here we surface them so the handshake layer can read them.
72
169
  this.encodedLocalParameters = encodeTransportParameters(toWireParameters(resolveLocalParameters(options)));
170
+ // EventProvider is injected by the composition root (browsersmith).
171
+ // Resolve from the explicit option first, then platform.events. There
172
+ // is no singleton fallback — the QUIC→TLS transport adapter requires
173
+ // one to drive the handshake.
174
+ const resolvedEvents = options.events ?? options.platform?.events;
175
+ if (resolvedEvents === undefined) {
176
+ throw new QuicError("QuicOptions requires `events` or `platform.events` for the QUIC→TLS transport adapter");
177
+ }
178
+ this.events = resolvedEvents;
73
179
  }
74
180
  // --- public QuicConnection surface ------------------------------------------
181
+ /**
182
+ * Resolve when the QUIC handshake completes and the connection is
183
+ * protected. HTTP/3 SETTINGS exchange may only begin after this resolves.
184
+ *
185
+ * When `skipHandshake` is true in QuicOptions, this resolves immediately
186
+ * since no TLS handshake is performed.
187
+ */
188
+ async handshake() {
189
+ // If the handshake has already completed, resolve immediately
190
+ if (this.handshakeResult !== undefined) {
191
+ return;
192
+ }
193
+ // Perform the TLS handshake
194
+ await this.performHandshake();
195
+ }
75
196
  openBidirectionalStream() {
76
197
  return Promise.resolve().then(() => {
77
198
  this.ensureOpen();
@@ -153,6 +274,23 @@ export class QuicConnectionImpl {
153
274
  toWireParameters(params) {
154
275
  return toWireParameters(params);
155
276
  }
277
+ /**
278
+ * Generate a random connection id of `length` bytes (RFC 9000 §5.1). Drawn
279
+ * from the injected random source so connection ids are reproducible under
280
+ * test. Useful for NEW_CONNECTION_ID frames and the endpoint's own source
281
+ * connection ids.
282
+ */
283
+ generateConnectionId(length) {
284
+ return this.random.randomBytes(length);
285
+ }
286
+ /**
287
+ * The crypto provider for QUIC key derivation (RFC 9001). A handshake
288
+ * layer uses this to run the HKDF-based key schedule; it is seeded with the
289
+ * injected random source so derived keys are reproducible under test.
290
+ */
291
+ getCrypto() {
292
+ return this.cryptoProvider;
293
+ }
156
294
  /**
157
295
  * Pack all buffered outbound frames into a short-header packet and send it.
158
296
  * Splits into multiple datagrams if the payload exceeds MAX_DATAGRAM_PAYLOAD.
@@ -177,24 +315,136 @@ export class QuicConnectionImpl {
177
315
  packFrames(frames) {
178
316
  return concatAll(frames.map((f) => serializeFrame(f)));
179
317
  }
180
- /** Wrap a serialized payload in a short (1-RTT) header + packet number. */
318
+ /**
319
+ * Wrap a serialized payload in a packet header + protect it.
320
+ *
321
+ * Selects long vs short header based on the current handshake state:
322
+ * - Before the handshake is complete: long-header Initial / Handshake packets.
323
+ * - After: short-header (1-RTT) packets.
324
+ *
325
+ * For now, we always emit short-header (1-RTT) packets once the handshake
326
+ * is complete, and long-header Handshake packets during the handshake.
327
+ * The very first packets (ClientHello) are also carried in Handshake packets
328
+ * by this simplified implementation — a full client would send the
329
+ * ClientHello in an Initial packet with a token, but the protection layer
330
+ * is identical.
331
+ */
181
332
  wrapPacket(payload) {
333
+ // No handshake performed (skipHandshake: true) — emit unprotected
334
+ // short-header packets for testing the data plane without a live TLS peer.
335
+ if (this.handshakeResult === undefined) {
336
+ return this.wrapPacketUnprotectedShort(payload);
337
+ }
338
+ const phase = this.outboundKeyPhase;
339
+ const secrets = this.getProtectionSecrets(phase);
340
+ if (secrets === undefined) {
341
+ // Pre-handshake (before the TLS handshake has produced keys): emit an
342
+ // unprotected packet for tests that don't exercise the protection layer.
343
+ // A production build would always have initial keys before the first
344
+ // outbound packet.
345
+ return this.wrapPacketUnprotected(payload, phase);
346
+ }
347
+ return this.wrapPacketProtected(payload, phase, secrets);
348
+ }
349
+ /**
350
+ * Wrap a payload in a simple unprotected short-header packet — the original
351
+ * behavior for tests that don't exercise the TLS handshake + protection layer.
352
+ */
353
+ wrapPacketUnprotectedShort(payload) {
182
354
  const header = serializeShortHeader(this.dcid, 1, false, false);
183
- // 1-byte packet number (relative offset 0) — placeholder for the
184
- // protection layer, which assigns real packet numbers.
185
- const packetNumber = new Uint8Array([0]);
355
+ // 1-byte packet number — placeholder for the protection layer, which
356
+ // assigns real packet numbers. Drawn from the injected random source so
357
+ // packet numbers are reproducible under test (RFC 9000 §17.2.4.1
358
+ // initial packet number SHOULD be random).
359
+ const packetNumber = this.random.randomBytes(1);
186
360
  return concatAll([header, packetNumber, payload]);
187
361
  }
362
+ /** Wrap a payload in a protected packet using the given key-phase secrets. */
363
+ wrapPacketProtected(payload, phase, secrets) {
364
+ const pn = this.nextPacketNumber[phase];
365
+ this.nextPacketNumber[phase] = pn + 1n;
366
+ const pnLength = 4; // 4-byte packet numbers for simplicity
367
+ const isLongHeader = phase !== "application";
368
+ const headerType = phase === "initial"
369
+ ? 0b00 // Initial
370
+ : phase === "handshake"
371
+ ? 0b10 // Handshake
372
+ : 0b00; // short header — long type unused
373
+ const firstByte = isLongHeader
374
+ ? (0b11 << 6) | (headerType << 4) | (pnLength - 1) // form=1, fixed=1, type, pnLen
375
+ : (0b01 << 5) | (pnLength - 1); // form=0, fixed=1, spin=0, reserved=0, keyPhase=0, pnLen
376
+ // The AAD for AEAD is the unprotected header (first byte + packet number).
377
+ // protectPayload handles the AEAD encryption + header protection.
378
+ const aead = mapAeadToQuic(this.handshakeResult?.aead ?? "AES-128-GCM");
379
+ const { protectedPayload, maskedFirstByte, maskedPacketNumber } = protectPayload(payload, pn, pnLength, firstByte, aead, secrets.clientProtection, isLongHeader, this.cryptoProvider);
380
+ if (isLongHeader) {
381
+ // Long header: version, DCID, SCID are emitted before the packet number.
382
+ // For simplicity we emit a minimal long header (version + DCID/SCID length 0).
383
+ const header = serializeLongHeader(headerType, QUIC_VERSION_V1, this.dcid, new Uint8Array(0), pnLength);
384
+ // Replace the first byte of the serialized header with the masked one.
385
+ const maskedHeader = new Uint8Array(header);
386
+ maskedHeader[0] = maskedFirstByte;
387
+ return concatAll([maskedHeader, maskedPacketNumber, protectedPayload]);
388
+ }
389
+ // Short header: first byte + DCID + packet number + protected payload.
390
+ const header = new Uint8Array([maskedFirstByte]);
391
+ return concatAll([header, this.dcid, maskedPacketNumber, protectedPayload]);
392
+ }
393
+ /**
394
+ * Wrap a payload in an *unprotected* packet — used only before the TLS
395
+ * handshake has produced keys (e.g. in tests that don't exercise the
396
+ * protection layer). A production build would never emit these.
397
+ */
398
+ wrapPacketUnprotected(payload, phase) {
399
+ const isLongHeader = phase !== "application";
400
+ const pnLength = 1;
401
+ const pn = 0n;
402
+ if (isLongHeader) {
403
+ const headerType = phase === "initial" ? 0b00 : 0b10;
404
+ const header = serializeLongHeader(headerType, QUIC_VERSION_V1, this.dcid, new Uint8Array(0), pnLength);
405
+ const packetNumber = new Uint8Array([Number(pn)]);
406
+ return concatAll([header, packetNumber, payload]);
407
+ }
408
+ const header = serializeShortHeader(this.dcid, pnLength, false, false);
409
+ const packetNumber = new Uint8Array([Number(pn)]);
410
+ return concatAll([header, packetNumber, payload]);
411
+ }
412
+ /**
413
+ * Get the QUIC protection secrets for a given key phase. Returns undefined
414
+ * if the handshake has not yet produced keys for that phase (e.g. before
415
+ * the TLS handshake has started).
416
+ */
417
+ getProtectionSecrets(phase) {
418
+ if (this.handshakeResult === undefined) {
419
+ return undefined;
420
+ }
421
+ return this.handshakeResult.phases.find((p) => p.phase === phase);
422
+ }
423
+ // --- TLS handshake ----------------------------------------------------------
424
+ /**
425
+ * Run the TLS 1.3 handshake over QUIC stream 0 and derive QUIC packet-
426
+ * protection secrets at each key phase.
427
+ */
428
+ async performHandshake() {
429
+ // Open a bidirectional stream for the TLS handshake (stream 0 for the client).
430
+ const stream = await this.openBidirectionalStream();
431
+ const transport = adaptQuicStreamToTransport(stream, this.events);
432
+ // Run the TLS handshake, capturing QUIC protection secrets at each phase.
433
+ const result = await runQuicHandshake(transport, { ...this.tlsProfile, serverName: this.tlsProfile.serverName }, this.tlsProfile.serverName, this.dcid, [], Math.floor(Date.now() / 1000), this.cryptoProvider);
434
+ this.handshakeResult = result;
435
+ this.outboundKeyPhase = "application";
436
+ // Advance through handshake → application phases as the handshake completes.
437
+ // After sending the client Finished, the connection is ready for 1-RTT data.
438
+ }
188
439
  // --- read loop -------------------------------------------------------------
189
440
  /**
190
441
  * Start the datagram read loop. Must be called once after construction.
191
442
  * Runs until the transport closes or the connection tears down.
443
+ *
444
+ * Peer CONNECTION_CLOSE signals are received through the stream manager's
445
+ * signal sink (wired at construction time), not via a direct subscription.
192
446
  */
193
447
  startReadLoop() {
194
- // React to connection-level signals from the stream manager.
195
- this.manager.on("connectionClose", ({ errorCode, reason }) => {
196
- void this.onPeerClose(errorCode, reason);
197
- });
198
448
  void this.readLoop();
199
449
  }
200
450
  async onPeerClose(errorCode, reason) {
@@ -211,17 +461,44 @@ export class QuicConnectionImpl {
211
461
  return;
212
462
  }
213
463
  try {
464
+ // No handshake performed (skipHandshake: true) — parse the packet
465
+ // header and decode frames directly, matching the original behavior
466
+ // for tests that don't exercise the TLS handshake + protection layer.
467
+ if (this.handshakeResult === undefined) {
468
+ await this.dispatchDatagramUnprotected(data);
469
+ return;
470
+ }
471
+ // Determine the key phase from the header form + type (long) or from
472
+ // the current handshake state (short).
473
+ const keyPhase = this.classifyKeyPhase(data);
214
474
  const header = parsePacketHeader(data);
215
- this.applyHeader(header);
216
- // Skip the header + packet number to reach the frame payload. The
217
- // protection layer would decrypt first in a full implementation.
218
- const pnLength = header.packetNumberLength;
219
- // Short headers carry a variable-length DCID after the first byte;
220
- // its length is not on the wire, so the connection supplies it from
221
- // the handshake state we already know (this.dcid).
222
- const dcidLength = header.form === 0 ? this.dcid.length : 0;
223
- const payloadStart = header.headerLength + dcidLength + pnLength;
224
- const payload = data.subarray(payloadStart);
475
+ // Decrypt the packet number + remove header protection to recover the
476
+ // full header + packet number.
477
+ const { packetNumber, header: decryptedHeader } = this.unprotectHeader(data, header, keyPhase);
478
+ // Track the largest received packet number for this phase.
479
+ if (packetNumber > this.largestReceivedPn[keyPhase]) {
480
+ this.largestReceivedPn[keyPhase] = packetNumber;
481
+ }
482
+ this.applyHeader(decryptedHeader);
483
+ // Skip the header + packet number to reach the decrypted frame payload.
484
+ const pnLength = decryptedHeader.packetNumberLength;
485
+ const dcidLength = decryptedHeader.form === 0 ? this.dcid.length : 0;
486
+ const payloadStart = decryptedHeader.headerLength + dcidLength + pnLength;
487
+ const protectedPayload = data.subarray(payloadStart);
488
+ // AEAD-decrypt the payload.
489
+ const secrets = this.getProtectionSecrets(keyPhase);
490
+ let payload;
491
+ if (secrets === undefined) {
492
+ // Pre-handshake: no keys yet — treat the payload as plaintext
493
+ // (tests that don't exercise protection).
494
+ payload = protectedPayload;
495
+ }
496
+ else {
497
+ const pnOffset = decryptedHeader.headerLength + dcidLength;
498
+ const pnBytes = data.subarray(pnOffset, pnOffset + pnLength);
499
+ const { payload: decrypted } = unprotectPayload(decryptedHeader.firstByte ?? data[0] ?? 0, pnBytes, pnLength, protectedPayload, decryptedHeader.form === 1, mapAeadToQuic(this.handshakeResult?.aead ?? "AES-128-GCM"), secrets.serverProtection, this.cryptoProvider);
500
+ payload = decrypted;
501
+ }
225
502
  if (payload.length === 0) {
226
503
  return;
227
504
  }
@@ -231,12 +508,154 @@ export class QuicConnectionImpl {
231
508
  }
232
509
  }
233
510
  catch (err) {
511
+ if (err instanceof PacketProtectionError || err instanceof TlsHandshakeError) {
512
+ this._handleFatal(err);
513
+ return;
514
+ }
234
515
  // A parse error on one datagram is not necessarily fatal for the
235
516
  // connection, but without a protection layer to frame it we close.
236
517
  this._handleFatal(err instanceof Error ? err : new Error(String(err)));
237
518
  }
238
519
  }
239
- /** Pull the DCID / version from a parsed header into connection state. */
520
+ /**
521
+ * Dispatch an unprotected datagram — the original behavior for tests that
522
+ * don't exercise the TLS handshake + protection layer. Parses the packet
523
+ * header and decodes frames directly, matching the pre-handshake read loop.
524
+ */
525
+ async dispatchDatagramUnprotected(data) {
526
+ const header = parsePacketHeader(data);
527
+ this.applyHeaderUnprotected(header);
528
+ // Skip the header + packet number to reach the frame payload.
529
+ const pnLength = header.packetNumberLength;
530
+ // Short headers carry a variable-length DCID after the first byte;
531
+ // its length is not on the wire, so the connection supplies it from
532
+ // the handshake state we already know (this.dcid).
533
+ const dcidLength = header.form === 0 ? this.dcid.length : 0;
534
+ const payloadStart = header.headerLength + dcidLength + pnLength;
535
+ const payload = data.subarray(payloadStart);
536
+ if (payload.length === 0) {
537
+ return;
538
+ }
539
+ const read = this.byteStreamReader(payload);
540
+ for await (const frame of readFrames(read)) {
541
+ this.handleFrame(frame);
542
+ }
543
+ }
544
+ /** Apply a parsed header (unprotected path) into connection state. */
545
+ applyHeaderUnprotected(header) {
546
+ if (header.form === 1) {
547
+ // Long header: could carry a version negotiation. We ignore for now.
548
+ return;
549
+ }
550
+ // Short header: the DCID on the wire is the route to the peer.
551
+ void header.dcid;
552
+ }
553
+ /**
554
+ * Determine the key phase of an inbound packet from its first byte.
555
+ *
556
+ * Long headers: Initial (0b00) → initial, Handshake (0b10) → handshake,
557
+ * Retry/0-RTT → initial (we treat them as initial-key for simplicity).
558
+ * Short headers: application (1-RTT).
559
+ */
560
+ classifyKeyPhase(data) {
561
+ if (data.length === 0) {
562
+ return "application";
563
+ }
564
+ const first = data[0];
565
+ if (first === undefined) {
566
+ return "application";
567
+ }
568
+ const form = (first >> 7) & 0x01;
569
+ if (form === 1) {
570
+ // Long header: type in bits 4-5.
571
+ const type = (first >> 4) & 0x03;
572
+ if (type === 0b00) {
573
+ return "initial";
574
+ }
575
+ if (type === 0b10) {
576
+ return "handshake";
577
+ }
578
+ // 0-RTT and Retry: treat as initial for simplicity.
579
+ return "initial";
580
+ }
581
+ // Short header: 1-RTT (application keys).
582
+ return "application";
583
+ }
584
+ /**
585
+ * Decrypt the packet number and remove header protection from an inbound
586
+ * packet. Returns the recovered packet number and the decrypted header.
587
+ */
588
+ unprotectHeader(data, header, keyPhase) {
589
+ const secrets = this.getProtectionSecrets(keyPhase);
590
+ if (secrets === undefined) {
591
+ // No keys yet — parse the plaintext packet number directly.
592
+ const pnLength = header.packetNumberLength;
593
+ const dcidLength = header.form === 0 ? this.dcid.length : 0;
594
+ const pnOffset = header.headerLength + dcidLength;
595
+ const pn = readPacketNumber(data, pnOffset, pnLength);
596
+ return {
597
+ packetNumber: pn,
598
+ header: {
599
+ ...header,
600
+ firstByte: data[0] ?? 0,
601
+ packetNumberLength: pnLength,
602
+ },
603
+ };
604
+ }
605
+ const isLong = header.form === 1;
606
+ const dcidLength = isLong ? 0 : this.dcid.length;
607
+ // We need to decrypt the packet number. The header protection sample is
608
+ // taken from the protected payload, but we need the packet number length
609
+ // to find the sample. RFC 9001 §5.4.2: the packet number length is
610
+ // encoded in the low 2 bits of the (unprotected) first byte. To recover
611
+ // it we need to first remove header protection from the first byte.
612
+ // Simplification: assume 4-byte packet numbers for now (matching our
613
+ // outbound encoding). A full implementation would try all 4 lengths.
614
+ const assumedPnLength = 4;
615
+ // The sample starts 4 bytes into the protected payload, which begins
616
+ // after the (encrypted) packet number.
617
+ const sampleOffset = header.headerLength + dcidLength + assumedPnLength + 4;
618
+ if (data.length < sampleOffset + 16) {
619
+ throw new PacketProtectionError("decrypt", {
620
+ cause: new Error(`packet too short for header-protection sample (need ${sampleOffset + 16}, got ${data.length})`),
621
+ });
622
+ }
623
+ const sample = data.subarray(sampleOffset, sampleOffset + 16);
624
+ const hpKey = isLong ? secrets.serverProtection.hp : secrets.serverProtection.hp;
625
+ const mask = this.cryptoProvider.aesEcbEncrypt(hpKey, sample);
626
+ // Remove header protection from the first byte.
627
+ const firstByte = data[0] ?? 0;
628
+ const firstByteMask = isLong ? 0x0f : 0x1f;
629
+ const unmaskedFirstByte = firstByte ^ ((mask[0] ?? 0) & firstByteMask);
630
+ // Recover the packet number length from the unmasked first byte.
631
+ const recoveredPnLength = isLong
632
+ ? (unmaskedFirstByte & 0x03) + 1
633
+ : (unmaskedFirstByte & 0x03) + 1;
634
+ // Read the (still-masked) packet number bytes.
635
+ const pnByteOffset = header.headerLength + dcidLength;
636
+ const pnBytes = data.subarray(pnByteOffset, pnByteOffset + recoveredPnLength);
637
+ // Remove header protection from the packet number.
638
+ let packetNumber = 0n;
639
+ for (let i = 0; i < recoveredPnLength; i++) {
640
+ const maskByte = mask[1 + i];
641
+ const pnByte = pnBytes[i];
642
+ if (maskByte === undefined || pnByte === undefined) {
643
+ throw new PacketProtectionError("decrypt", {
644
+ cause: new Error(`mask/pn byte ${i} out of bounds`),
645
+ });
646
+ }
647
+ packetNumber = (packetNumber << 8n) | BigInt(pnByte ^ maskByte);
648
+ }
649
+ return {
650
+ packetNumber,
651
+ header: {
652
+ ...header,
653
+ firstByte: unmaskedFirstByte,
654
+ packetNumberLength: recoveredPnLength,
655
+ },
656
+ };
657
+ }
658
+ /** Header fields after header-protection removal. */
240
659
  applyHeader(header) {
241
660
  if (header.form === 1) {
242
661
  // Long header: could carry a version negotiation. We ignore for now.
@@ -262,12 +681,6 @@ export class QuicConnectionImpl {
262
681
  }
263
682
  /** Route a decoded frame: data-plane frames to the manager, the rest here. */
264
683
  handleFrame(frame) {
265
- // Data-plane frames are dispatched to the stream manager, which may emit
266
- // outbound control frames (MAX_DATA, MAX_STREAM_DATA, ...). Connection /
267
- // handshake layer concerns (PADDING, PING, ACK, CRYPTO, NEW_TOKEN,
268
- // NEW_CONNECTION_ID, RETIRE_CONNECTION_ID, HANDSHAKE_DONE) are relayed
269
- // only. PATH_CHALLENGE / PATH_RESPONSE are handled below for path
270
- // validation (RFC 9000 §8.2.1).
271
684
  switch (frame.type) {
272
685
  case QuicFrameType.RESET_STREAM:
273
686
  case QuicFrameType.STOP_SENDING:
@@ -299,21 +712,14 @@ export class QuicConnectionImpl {
299
712
  case QuicFrameType.RETIRE_CONNECTION_ID:
300
713
  case QuicFrameType.HANDSHAKE_DONE:
301
714
  break;
302
- // Path validation (RFC 9000 §8.2.1, §19.17). A peer-sent challenge is
303
- // answered with a matching PATH_RESPONSE; a PATH_RESPONSE from the
304
- // peer validates a challenge we sent.
715
+ // Path validation (RFC 9000 §8.2.1, §19.17).
305
716
  case QuicFrameType.PATH_CHALLENGE: {
306
- // frame is narrowed to PathChallengeFrame here; respond with the
307
- // same 8 bytes (RFC 9000 §19.17).
308
717
  const challenge = frame;
309
718
  this.sendFrame({ type: QuicFrameType.PATH_RESPONSE, data: challenge.data });
310
719
  void this.flush();
311
720
  break;
312
721
  }
313
722
  case QuicFrameType.PATH_RESPONSE: {
314
- // frame is narrowed to PathResponseFrame here; drop the matching
315
- // challenge from the pending set. An unmatched response is a
316
- // no-op (silently ignored).
317
723
  const response = frame;
318
724
  this.pendingPathChallenges.delete(hex(response.data));
319
725
  break;
@@ -332,8 +738,6 @@ export class QuicConnectionImpl {
332
738
  async readLoop() {
333
739
  try {
334
740
  while (!this.closed) {
335
- // The read loop pulls one datagram at a time and must process it
336
- // before pulling the next (ordered, in-order frame dispatch).
337
741
  // eslint-disable-next-line no-await-in-loop -- sequential datagram consumption is required
338
742
  const { data } = await this.transport.recv();
339
743
  // eslint-disable-next-line no-await-in-loop -- dispatch must complete before the next datagram
@@ -383,7 +787,7 @@ export class QuicConnectionImpl {
383
787
  }
384
788
  ensureOpen() {
385
789
  if (this.closing || this.closed) {
386
- throw new Error("connection is closing");
790
+ throw new ConnectionClosingError();
387
791
  }
388
792
  }
389
793
  }
@@ -426,34 +830,107 @@ function resolveLocalParameters(options) {
426
830
  // ---------------------------------------------------------------------------
427
831
  // connectQuic
428
832
  // ---------------------------------------------------------------------------
833
+ /**
834
+ * Convert a {@link ClientHelloConfigLike} (the public QUIC option) to a
835
+ * full @browsercore/tls `ClientHelloConfig` the handshake driver can consume.
836
+ */
837
+ function toTlsClientHelloConfig(like, serverName) {
838
+ if (like === undefined) {
839
+ return { ...DEFAULT_TLS_PROFILE, serverName };
840
+ }
841
+ return {
842
+ cipherSuites: like.cipherSuites,
843
+ extensionOrder: like.extensionOrder,
844
+ keyShareGroups: like.keyShareGroups,
845
+ signatureAlgorithms: like.signatureAlgorithms,
846
+ supportedVersions: like.supportedVersions,
847
+ serverName: like.serverName || serverName,
848
+ ...(like.alpnProtocols === undefined ? {} : { alpnProtocols: like.alpnProtocols }),
849
+ grease: like.grease,
850
+ };
851
+ }
429
852
  /**
430
853
  * Establish a QUIC connection over an existing datagram transport.
431
854
  *
432
- * Creates the stream manager and the read loop. Because the TLS handshake and
433
- * packet protection are out of scope, this returns a connection that moves
434
- * unprotected frames — the data plane is fully functional and testable with a
435
- * fake datagram transport.
855
+ * Creates the stream manager and the read loop. By default, runs the TLS 1.3
856
+ * handshake over QUIC stream 0 (a bidirectional stream), derives QUIC packet-
857
+ * protection secrets at each key phase, and returns a connection that protects
858
+ * inbound + outbound packets with the derived keys.
859
+ *
860
+ * The `tlsProfile` option selects the ClientHello configuration for the
861
+ * handshake. Defaults to a modern TLS 1.3 profile (X25519 + secp256r1 key
862
+ * shares, AES-256/128-GCM + ChaCha20-Poly1305). Set `skipHandshake: true` to
863
+ * skip the TLS handshake and return an *unprotected* connection (the data plane
864
+ * is fully functional and testable with a fake datagram transport, but it is
865
+ * not wire-ready without a protection + handshake layer on top).
436
866
  */
437
- export function connectQuic(options) {
438
- const id = `quic_${Date.now().toString(36)}`;
867
+ export async function connectQuic(options) {
868
+ // Resolve the clock: explicit option → platform.time.clock → systemClock.
869
+ const clock = options.clock
870
+ ?? options.platform?.time?.clock
871
+ ?? systemClock;
872
+ const id = `quic_${clock.now().toString(36)}`;
439
873
  // The stream manager is constructed before the connection, but its frames
440
874
  // must reach the connection's packetizer. We bridge the two with a mutable
441
875
  // router that we point at the connection once it exists.
442
876
  const frameRouter = { send: () => { } };
877
+ // The connection is not yet constructed when we build the manager, so we
878
+ // defer resolving the signal handler until after the connection exists.
879
+ let peerCloseHandler;
443
880
  const manager = createStreamManager({
444
881
  sendFrame: (frame) => {
445
882
  frameRouter.send(frame);
446
883
  },
884
+ signals: {
885
+ onIncomingStream: () => { },
886
+ onConnectionClose: (errorCode, reason) => {
887
+ if (peerCloseHandler !== undefined) {
888
+ peerCloseHandler(errorCode, reason);
889
+ }
890
+ },
891
+ onMaxData: () => { },
892
+ },
447
893
  localParameters: resolveLocalParameters(options),
448
894
  peerParameters: options.transportParameters ?? {},
449
895
  });
450
- const conn = new QuicConnectionImpl(id, options, manager, options.initialDcid);
896
+ const conn = new QuicConnectionImpl(id, options, manager, options.initialDcid, (handler) => {
897
+ peerCloseHandler = handler;
898
+ });
451
899
  frameRouter.send = (frame) => {
452
900
  conn.sendFrame(frame);
453
901
  };
454
- // A larger send window may have queued stream data — the read loop drains it.
455
- manager.on("maxData", () => { });
902
+ // Start the read loop. The handshake (if any) runs concurrently so the
903
+ // server's response is processed.
456
904
  conn.startReadLoop();
457
- return Promise.resolve(conn);
905
+ if (options.skipHandshake === true) {
906
+ // Return an unprotected connection for testing the data plane without
907
+ // a live TLS peer.
908
+ return conn;
909
+ }
910
+ // Run the TLS handshake. On failure, the connection surfaces the error.
911
+ await conn.performHandshake();
912
+ return conn;
913
+ }
914
+ /** Map a TLS AEAD algorithm to the QUIC AEAD subset (AES-128-CCM is not used by QUIC). */
915
+ function mapAeadToQuic(aead) {
916
+ switch (aead) {
917
+ case "AES-128-GCM":
918
+ return "AES-128-GCM";
919
+ case "AES-256-GCM":
920
+ return "AES-256-GCM";
921
+ case "CHACHA20-POLY1305":
922
+ // TLS uses "CHACHA20_POLY1305" (underscores); QUIC's QuicAead type
923
+ // mirrors TLS naming. The packet-protection layer maps to
924
+ // @browsercore/crypto's "ChaCha20-Poly1305" (hyphens) internally.
925
+ return "CHACHA20-POLY1305";
926
+ case "AES-128-CCM":
927
+ // AES-128-CCM is negotiated by TLS but not used by QUIC v1. Fall
928
+ // back to AES-128-GCM; the connection will fail at the TLS layer
929
+ // if the server actually selects CCM.
930
+ return "AES-128-GCM";
931
+ default:
932
+ // Every AeadAlgorithm variant is covered above.
933
+ return assertNever(aead);
934
+ }
458
935
  }
459
936
  //# sourceMappingURL=connection.js.map