@browsercore/quic 0.2.0 → 0.2.2
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.
- package/README.md +14 -9
- package/bin/coverage-md.mjs +99 -0
- package/dist/connection.d.ts +159 -24
- package/dist/connection.d.ts.map +1 -1
- package/dist/connection.js +490 -60
- package/dist/connection.js.map +1 -1
- package/dist/crypto/hash-length.d.ts +11 -0
- package/dist/crypto/hash-length.d.ts.map +1 -0
- package/dist/crypto/hash-length.js +20 -0
- package/dist/crypto/hash-length.js.map +1 -0
- package/dist/crypto/index.d.ts +8 -0
- package/dist/crypto/index.d.ts.map +1 -0
- package/dist/crypto/index.js +8 -0
- package/dist/crypto/index.js.map +1 -0
- package/dist/crypto/key-derivation.d.ts +86 -0
- package/dist/crypto/key-derivation.d.ts.map +1 -0
- package/dist/crypto/key-derivation.js +123 -0
- package/dist/crypto/key-derivation.js.map +1 -0
- package/dist/errors.d.ts +26 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +35 -0
- package/dist/errors.js.map +1 -1
- package/dist/frame/frame.d.ts.map +1 -1
- package/dist/frame/frame.js +2 -2
- package/dist/frame/frame.js.map +1 -1
- package/dist/handshake/index.d.ts +10 -0
- package/dist/handshake/index.d.ts.map +1 -0
- package/dist/handshake/index.js +9 -0
- package/dist/handshake/index.js.map +1 -0
- package/dist/handshake/quic-handshake.d.ts +73 -0
- package/dist/handshake/quic-handshake.d.ts.map +1 -0
- package/dist/handshake/quic-handshake.js +213 -0
- package/dist/handshake/quic-handshake.js.map +1 -0
- package/dist/handshake/quic-transport-adapter.d.ts +78 -0
- package/dist/handshake/quic-transport-adapter.d.ts.map +1 -0
- package/dist/handshake/quic-transport-adapter.js +140 -0
- package/dist/handshake/quic-transport-adapter.js.map +1 -0
- package/dist/index.d.ts +9 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -4
- package/dist/index.js.map +1 -1
- package/dist/packet/packet-protection.d.ts +158 -0
- package/dist/packet/packet-protection.d.ts.map +1 -0
- package/dist/packet/packet-protection.js +313 -0
- package/dist/packet/packet-protection.js.map +1 -0
- package/dist/packet/packet.d.ts +2 -2
- package/dist/packet/packet.d.ts.map +1 -1
- package/dist/packet/packet.js +4 -4
- package/dist/packet/packet.js.map +1 -1
- package/dist/stream/stream.d.ts.map +1 -1
- package/dist/stream/stream.js +10 -6
- package/dist/stream/stream.js.map +1 -1
- package/dist/types.d.ts +98 -41
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js +27 -20
- package/dist/types.js.map +1 -1
- package/package.json +8 -4
package/dist/connection.js
CHANGED
|
@@ -1,33 +1,66 @@
|
|
|
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,
|
|
5
|
-
* manager
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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
|
-
* -
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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 {
|
|
23
|
-
import {
|
|
28
|
+
import { crypto } from "@browsercore/crypto";
|
|
29
|
+
import { nodeRandomSource } from "@browsercore/transport";
|
|
30
|
+
import { QuicFrameType, systemClock, silentLogger, } from "./types.js";
|
|
31
|
+
import { parsePacketHeader, serializeShortHeader, serializeLongHeader, readPacketNumber, } from "./packet/packet.js";
|
|
32
|
+
import { protectPayload, unprotectPayload, } from "./packet/packet-protection.js";
|
|
24
33
|
import { readFrames, serializeFrame } from "./frame/frame.js";
|
|
25
|
-
import { ConnectionClosedError } from "./errors.js";
|
|
34
|
+
import { ConnectionClosedError, ConnectionClosingError, PacketProtectionError, TlsHandshakeError, } from "./errors.js";
|
|
26
35
|
import { createStreamManager } from "./stream/stream.js";
|
|
27
|
-
import { concatAll, hex } from "./utils.js";
|
|
36
|
+
import { assertNever, concatAll, hex } from "./utils.js";
|
|
28
37
|
import { decodeTransportParameters, encodeTransportParameters, fromWireParameters, toWireParameters, } from "./transport-params.js";
|
|
38
|
+
import { adaptQuicStreamToTransport } from "./handshake/quic-transport-adapter.js";
|
|
39
|
+
import { runQuicHandshake } from "./handshake/quic-handshake.js";
|
|
29
40
|
/** Largest UDP payload we will pack into a single datagram (RFC 9000 §14). */
|
|
30
41
|
const MAX_DATAGRAM_PAYLOAD = 1200;
|
|
42
|
+
/** QUIC long header version (QUIC v1, RFC 9000 §32.2.1). */
|
|
43
|
+
const QUIC_VERSION_V1 = 0x00000001;
|
|
44
|
+
/** Default TLS profile for the QUIC handshake — modern TLS 1.3, X25519 + secp256r1. */
|
|
45
|
+
const DEFAULT_TLS_PROFILE = {
|
|
46
|
+
cipherSuites: [
|
|
47
|
+
"TLS_AES_256_GCM_SHA384",
|
|
48
|
+
"TLS_AES_128_GCM_SHA256",
|
|
49
|
+
"TLS_CHACHA20_POLY1305_SHA256",
|
|
50
|
+
],
|
|
51
|
+
extensionOrder: [
|
|
52
|
+
0, 10, 11, 13, 16, 17513, 18, 23, 27, 35, 41, 43, 45, 5, 51, 65281,
|
|
53
|
+
],
|
|
54
|
+
keyShareGroups: ["x25519", "secp256r1"],
|
|
55
|
+
signatureAlgorithms: [
|
|
56
|
+
"ecdsa_secp256r1_sha256",
|
|
57
|
+
"rsa_pss_rsae_sha256",
|
|
58
|
+
"rsa_pss_rsae_sha384",
|
|
59
|
+
],
|
|
60
|
+
supportedVersions: [{ name: "TLS 1.3", wire: 0x0304 }],
|
|
61
|
+
serverName: "",
|
|
62
|
+
grease: true,
|
|
63
|
+
};
|
|
31
64
|
/**
|
|
32
65
|
* Concrete QUIC connection. The public surface matches the fixed
|
|
33
66
|
* `QuicConnection` interface; internal state is kept on the instance.
|
|
@@ -38,20 +71,50 @@ export class QuicConnectionImpl {
|
|
|
38
71
|
transport;
|
|
39
72
|
/** The peer's UDP address. */
|
|
40
73
|
peer;
|
|
41
|
-
/** Stream manager (
|
|
74
|
+
/** Stream manager (emits connection-level signals). */
|
|
42
75
|
manager;
|
|
43
76
|
/** Our current destination connection id (the one we put on outbound packets). */
|
|
44
77
|
dcid;
|
|
78
|
+
/** Logging sink for lifecycle + frame diagnostics. */
|
|
79
|
+
logger;
|
|
80
|
+
/** Random source for connection ids and packet numbers. */
|
|
81
|
+
random;
|
|
82
|
+
/**
|
|
83
|
+
* Cryptographic provider for QUIC key derivation and packet protection
|
|
84
|
+
* (RFC 9001). Seeded with the injected {@link random} source so the
|
|
85
|
+
* HKDF-based key schedule is reproducible under test.
|
|
86
|
+
*/
|
|
87
|
+
cryptoProvider;
|
|
88
|
+
/** TLS ClientHello configuration for the handshake. */
|
|
89
|
+
tlsProfile;
|
|
45
90
|
/**
|
|
46
91
|
* Our transport parameters encoded for the wire. Produced at handshake
|
|
47
92
|
* time so a TLS layer can carry them to the peer in the QUIC extension.
|
|
48
93
|
*/
|
|
49
94
|
encodedLocalParameters;
|
|
95
|
+
/** Result of the TLS handshake — set once the handshake completes. */
|
|
96
|
+
handshakeResult;
|
|
97
|
+
/**
|
|
98
|
+
* Current key phase for outbound packets. Advances from initial → handshake
|
|
99
|
+
* → application as the handshake progresses. The protection layer selects
|
|
100
|
+
* the correct secrets based on this + the packet's header form.
|
|
101
|
+
*/
|
|
102
|
+
outboundKeyPhase = "initial";
|
|
103
|
+
/** Next outbound packet number, per key phase (RFC 9000 §12.3). */
|
|
104
|
+
nextPacketNumber = {
|
|
105
|
+
initial: 0n,
|
|
106
|
+
handshake: 0n,
|
|
107
|
+
application: 0n,
|
|
108
|
+
};
|
|
109
|
+
/** Largest received packet number per key phase (for packet-number decoding). */
|
|
110
|
+
largestReceivedPn = {
|
|
111
|
+
initial: -1n,
|
|
112
|
+
handshake: -1n,
|
|
113
|
+
application: -1n,
|
|
114
|
+
};
|
|
50
115
|
/**
|
|
51
116
|
* PATH_CHALLENGEs we have issued and are awaiting a PATH_RESPONSE for,
|
|
52
117
|
* 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
118
|
*/
|
|
56
119
|
pendingPathChallenges = new Set();
|
|
57
120
|
/** Set once the connection begins graceful shutdown. */
|
|
@@ -60,12 +123,29 @@ export class QuicConnectionImpl {
|
|
|
60
123
|
closed = false;
|
|
61
124
|
/** Buffered outbound frames waiting to be packed into the next packet. */
|
|
62
125
|
outboundFrames = [];
|
|
63
|
-
constructor(id, options, manager, dcid) {
|
|
126
|
+
constructor(id, options, manager, dcid, logger) {
|
|
64
127
|
this.id = id;
|
|
65
128
|
this.transport = options.transport;
|
|
66
129
|
this.peer = options.peer;
|
|
67
130
|
this.manager = manager;
|
|
68
131
|
this.dcid = dcid;
|
|
132
|
+
this.logger = logger;
|
|
133
|
+
this.random = options.random ?? nodeRandomSource;
|
|
134
|
+
// The crypto provider is seeded with the same random source so the
|
|
135
|
+
// QUIC key schedule (RFC 9001) derives bytes deterministically when a
|
|
136
|
+
// deterministic source is injected. Delegates all other operations to
|
|
137
|
+
// the singleton `crypto` provider.
|
|
138
|
+
const randomSource = this.random;
|
|
139
|
+
this.cryptoProvider = new Proxy(crypto, {
|
|
140
|
+
get(target, prop, receiver) {
|
|
141
|
+
if (prop === "randomBytes") {
|
|
142
|
+
return (length) => randomSource.randomBytes(length);
|
|
143
|
+
}
|
|
144
|
+
return Reflect.get(target, prop, receiver);
|
|
145
|
+
},
|
|
146
|
+
});
|
|
147
|
+
// Resolve the TLS ClientHello configuration for the handshake.
|
|
148
|
+
this.tlsProfile = toTlsClientHelloConfig(options.tlsProfile, options.serverName);
|
|
69
149
|
// Encode our transport parameters for the wire at construction. A real
|
|
70
150
|
// TLS handshake would carry these to the peer in the QUIC extension;
|
|
71
151
|
// here we surface them so the handshake layer can read them.
|
|
@@ -139,6 +219,14 @@ export class QuicConnectionImpl {
|
|
|
139
219
|
getEncodedLocalParameters() {
|
|
140
220
|
return this.encodedLocalParameters;
|
|
141
221
|
}
|
|
222
|
+
/**
|
|
223
|
+
* The logging sink for this connection. A TLS handshake layer or test
|
|
224
|
+
* harness reads this to attach diagnostics, or to swap in a capturing
|
|
225
|
+
* logger — the connection itself stays agnostic to where log lines go.
|
|
226
|
+
*/
|
|
227
|
+
getLogger() {
|
|
228
|
+
return this.logger;
|
|
229
|
+
}
|
|
142
230
|
/**
|
|
143
231
|
* Ingest the peer's transport parameters from their wire encoding. Decodes
|
|
144
232
|
* them and feeds them to the stream manager so its send windows match what
|
|
@@ -153,6 +241,23 @@ export class QuicConnectionImpl {
|
|
|
153
241
|
toWireParameters(params) {
|
|
154
242
|
return toWireParameters(params);
|
|
155
243
|
}
|
|
244
|
+
/**
|
|
245
|
+
* Generate a random connection id of `length` bytes (RFC 9000 §5.1). Drawn
|
|
246
|
+
* from the injected random source so connection ids are reproducible under
|
|
247
|
+
* test. Useful for NEW_CONNECTION_ID frames and the endpoint's own source
|
|
248
|
+
* connection ids.
|
|
249
|
+
*/
|
|
250
|
+
generateConnectionId(length) {
|
|
251
|
+
return this.random.randomBytes(length);
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* The crypto provider for QUIC key derivation (RFC 9001). A handshake
|
|
255
|
+
* layer uses this to run the HKDF-based key schedule; it is seeded with the
|
|
256
|
+
* injected random source so derived keys are reproducible under test.
|
|
257
|
+
*/
|
|
258
|
+
getCrypto() {
|
|
259
|
+
return this.cryptoProvider;
|
|
260
|
+
}
|
|
156
261
|
/**
|
|
157
262
|
* Pack all buffered outbound frames into a short-header packet and send it.
|
|
158
263
|
* Splits into multiple datagrams if the payload exceeds MAX_DATAGRAM_PAYLOAD.
|
|
@@ -177,14 +282,127 @@ export class QuicConnectionImpl {
|
|
|
177
282
|
packFrames(frames) {
|
|
178
283
|
return concatAll(frames.map((f) => serializeFrame(f)));
|
|
179
284
|
}
|
|
180
|
-
/**
|
|
285
|
+
/**
|
|
286
|
+
* Wrap a serialized payload in a packet header + protect it.
|
|
287
|
+
*
|
|
288
|
+
* Selects long vs short header based on the current handshake state:
|
|
289
|
+
* - Before the handshake is complete: long-header Initial / Handshake packets.
|
|
290
|
+
* - After: short-header (1-RTT) packets.
|
|
291
|
+
*
|
|
292
|
+
* For now, we always emit short-header (1-RTT) packets once the handshake
|
|
293
|
+
* is complete, and long-header Handshake packets during the handshake.
|
|
294
|
+
* The very first packets (ClientHello) are also carried in Handshake packets
|
|
295
|
+
* by this simplified implementation — a full client would send the
|
|
296
|
+
* ClientHello in an Initial packet with a token, but the protection layer
|
|
297
|
+
* is identical.
|
|
298
|
+
*/
|
|
181
299
|
wrapPacket(payload) {
|
|
300
|
+
// No handshake performed (skipHandshake: true) — emit unprotected
|
|
301
|
+
// short-header packets for testing the data plane without a live TLS peer.
|
|
302
|
+
if (this.handshakeResult === undefined) {
|
|
303
|
+
return this.wrapPacketUnprotectedShort(payload);
|
|
304
|
+
}
|
|
305
|
+
const phase = this.outboundKeyPhase;
|
|
306
|
+
const secrets = this.getProtectionSecrets(phase);
|
|
307
|
+
if (secrets === undefined) {
|
|
308
|
+
// Pre-handshake (before the TLS handshake has produced keys): emit an
|
|
309
|
+
// unprotected packet for tests that don't exercise the protection layer.
|
|
310
|
+
// A production build would always have initial keys before the first
|
|
311
|
+
// outbound packet.
|
|
312
|
+
return this.wrapPacketUnprotected(payload, phase);
|
|
313
|
+
}
|
|
314
|
+
return this.wrapPacketProtected(payload, phase, secrets);
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Wrap a payload in a simple unprotected short-header packet — the original
|
|
318
|
+
* behavior for tests that don't exercise the TLS handshake + protection layer.
|
|
319
|
+
*/
|
|
320
|
+
wrapPacketUnprotectedShort(payload) {
|
|
182
321
|
const header = serializeShortHeader(this.dcid, 1, false, false);
|
|
183
|
-
// 1-byte packet number
|
|
184
|
-
//
|
|
185
|
-
|
|
322
|
+
// 1-byte packet number — placeholder for the protection layer, which
|
|
323
|
+
// assigns real packet numbers. Drawn from the injected random source so
|
|
324
|
+
// packet numbers are reproducible under test (RFC 9000 §17.2.4.1
|
|
325
|
+
// initial packet number SHOULD be random).
|
|
326
|
+
const packetNumber = this.random.randomBytes(1);
|
|
186
327
|
return concatAll([header, packetNumber, payload]);
|
|
187
328
|
}
|
|
329
|
+
/** Wrap a payload in a protected packet using the given key-phase secrets. */
|
|
330
|
+
wrapPacketProtected(payload, phase, secrets) {
|
|
331
|
+
const pn = this.nextPacketNumber[phase];
|
|
332
|
+
this.nextPacketNumber[phase] = pn + 1n;
|
|
333
|
+
const pnLength = 4; // 4-byte packet numbers for simplicity
|
|
334
|
+
const isLongHeader = phase !== "application";
|
|
335
|
+
const headerType = phase === "initial"
|
|
336
|
+
? 0b00 // Initial
|
|
337
|
+
: phase === "handshake"
|
|
338
|
+
? 0b10 // Handshake
|
|
339
|
+
: 0b00; // short header — long type unused
|
|
340
|
+
const firstByte = isLongHeader
|
|
341
|
+
? (0b11 << 6) | (headerType << 4) | (pnLength - 1) // form=1, fixed=1, type, pnLen
|
|
342
|
+
: (0b01 << 5) | (pnLength - 1); // form=0, fixed=1, spin=0, reserved=0, keyPhase=0, pnLen
|
|
343
|
+
// The AAD for AEAD is the unprotected header (first byte + packet number).
|
|
344
|
+
// protectPayload handles the AEAD encryption + header protection.
|
|
345
|
+
const aead = mapAeadToQuic(this.handshakeResult?.aead ?? "AES-128-GCM");
|
|
346
|
+
const { protectedPayload, maskedFirstByte, maskedPacketNumber } = protectPayload(payload, pn, pnLength, firstByte, aead, secrets.clientProtection, isLongHeader, this.cryptoProvider);
|
|
347
|
+
if (isLongHeader) {
|
|
348
|
+
// Long header: version, DCID, SCID are emitted before the packet number.
|
|
349
|
+
// For simplicity we emit a minimal long header (version + DCID/SCID length 0).
|
|
350
|
+
const header = serializeLongHeader(headerType, QUIC_VERSION_V1, this.dcid, new Uint8Array(0), pnLength);
|
|
351
|
+
// Replace the first byte of the serialized header with the masked one.
|
|
352
|
+
const maskedHeader = new Uint8Array(header);
|
|
353
|
+
maskedHeader[0] = maskedFirstByte;
|
|
354
|
+
return concatAll([maskedHeader, maskedPacketNumber, protectedPayload]);
|
|
355
|
+
}
|
|
356
|
+
// Short header: first byte + DCID + packet number + protected payload.
|
|
357
|
+
const header = new Uint8Array([maskedFirstByte]);
|
|
358
|
+
return concatAll([header, this.dcid, maskedPacketNumber, protectedPayload]);
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* Wrap a payload in an *unprotected* packet — used only before the TLS
|
|
362
|
+
* handshake has produced keys (e.g. in tests that don't exercise the
|
|
363
|
+
* protection layer). A production build would never emit these.
|
|
364
|
+
*/
|
|
365
|
+
wrapPacketUnprotected(payload, phase) {
|
|
366
|
+
const isLongHeader = phase !== "application";
|
|
367
|
+
const pnLength = 1;
|
|
368
|
+
const pn = 0n;
|
|
369
|
+
if (isLongHeader) {
|
|
370
|
+
const headerType = phase === "initial" ? 0b00 : 0b10;
|
|
371
|
+
const header = serializeLongHeader(headerType, QUIC_VERSION_V1, this.dcid, new Uint8Array(0), pnLength);
|
|
372
|
+
const packetNumber = new Uint8Array([Number(pn)]);
|
|
373
|
+
return concatAll([header, packetNumber, payload]);
|
|
374
|
+
}
|
|
375
|
+
const header = serializeShortHeader(this.dcid, pnLength, false, false);
|
|
376
|
+
const packetNumber = new Uint8Array([Number(pn)]);
|
|
377
|
+
return concatAll([header, packetNumber, payload]);
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Get the QUIC protection secrets for a given key phase. Returns undefined
|
|
381
|
+
* if the handshake has not yet produced keys for that phase (e.g. before
|
|
382
|
+
* the TLS handshake has started).
|
|
383
|
+
*/
|
|
384
|
+
getProtectionSecrets(phase) {
|
|
385
|
+
if (this.handshakeResult === undefined) {
|
|
386
|
+
return undefined;
|
|
387
|
+
}
|
|
388
|
+
return this.handshakeResult.phases.find((p) => p.phase === phase);
|
|
389
|
+
}
|
|
390
|
+
// --- TLS handshake ----------------------------------------------------------
|
|
391
|
+
/**
|
|
392
|
+
* Run the TLS 1.3 handshake over QUIC stream 0 and derive QUIC packet-
|
|
393
|
+
* protection secrets at each key phase.
|
|
394
|
+
*/
|
|
395
|
+
async performHandshake() {
|
|
396
|
+
// Open a bidirectional stream for the TLS handshake (stream 0 for the client).
|
|
397
|
+
const stream = await this.openBidirectionalStream();
|
|
398
|
+
const transport = adaptQuicStreamToTransport(stream);
|
|
399
|
+
// Run the TLS handshake, capturing QUIC protection secrets at each phase.
|
|
400
|
+
const result = await runQuicHandshake(transport, { ...this.tlsProfile, serverName: this.tlsProfile.serverName }, this.tlsProfile.serverName, this.dcid, [], Math.floor(Date.now() / 1000), this.cryptoProvider);
|
|
401
|
+
this.handshakeResult = result;
|
|
402
|
+
this.outboundKeyPhase = "application";
|
|
403
|
+
// Advance through handshake → application phases as the handshake completes.
|
|
404
|
+
// After sending the client Finished, the connection is ready for 1-RTT data.
|
|
405
|
+
}
|
|
188
406
|
// --- read loop -------------------------------------------------------------
|
|
189
407
|
/**
|
|
190
408
|
* Start the datagram read loop. Must be called once after construction.
|
|
@@ -211,17 +429,44 @@ export class QuicConnectionImpl {
|
|
|
211
429
|
return;
|
|
212
430
|
}
|
|
213
431
|
try {
|
|
432
|
+
// No handshake performed (skipHandshake: true) — parse the packet
|
|
433
|
+
// header and decode frames directly, matching the original behavior
|
|
434
|
+
// for tests that don't exercise the TLS handshake + protection layer.
|
|
435
|
+
if (this.handshakeResult === undefined) {
|
|
436
|
+
await this.dispatchDatagramUnprotected(data);
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
// Determine the key phase from the header form + type (long) or from
|
|
440
|
+
// the current handshake state (short).
|
|
441
|
+
const keyPhase = this.classifyKeyPhase(data);
|
|
214
442
|
const header = parsePacketHeader(data);
|
|
215
|
-
|
|
216
|
-
//
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
const
|
|
443
|
+
// Decrypt the packet number + remove header protection to recover the
|
|
444
|
+
// full header + packet number.
|
|
445
|
+
const { packetNumber, header: decryptedHeader } = this.unprotectHeader(data, header, keyPhase);
|
|
446
|
+
// Track the largest received packet number for this phase.
|
|
447
|
+
if (packetNumber > this.largestReceivedPn[keyPhase]) {
|
|
448
|
+
this.largestReceivedPn[keyPhase] = packetNumber;
|
|
449
|
+
}
|
|
450
|
+
this.applyHeader(decryptedHeader);
|
|
451
|
+
// Skip the header + packet number to reach the decrypted frame payload.
|
|
452
|
+
const pnLength = decryptedHeader.packetNumberLength;
|
|
453
|
+
const dcidLength = decryptedHeader.form === 0 ? this.dcid.length : 0;
|
|
454
|
+
const payloadStart = decryptedHeader.headerLength + dcidLength + pnLength;
|
|
455
|
+
const protectedPayload = data.subarray(payloadStart);
|
|
456
|
+
// AEAD-decrypt the payload.
|
|
457
|
+
const secrets = this.getProtectionSecrets(keyPhase);
|
|
458
|
+
let payload;
|
|
459
|
+
if (secrets === undefined) {
|
|
460
|
+
// Pre-handshake: no keys yet — treat the payload as plaintext
|
|
461
|
+
// (tests that don't exercise protection).
|
|
462
|
+
payload = protectedPayload;
|
|
463
|
+
}
|
|
464
|
+
else {
|
|
465
|
+
const pnOffset = decryptedHeader.headerLength + dcidLength;
|
|
466
|
+
const pnBytes = data.subarray(pnOffset, pnOffset + pnLength);
|
|
467
|
+
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);
|
|
468
|
+
payload = decrypted;
|
|
469
|
+
}
|
|
225
470
|
if (payload.length === 0) {
|
|
226
471
|
return;
|
|
227
472
|
}
|
|
@@ -231,12 +476,154 @@ export class QuicConnectionImpl {
|
|
|
231
476
|
}
|
|
232
477
|
}
|
|
233
478
|
catch (err) {
|
|
479
|
+
if (err instanceof PacketProtectionError || err instanceof TlsHandshakeError) {
|
|
480
|
+
this._handleFatal(err);
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
234
483
|
// A parse error on one datagram is not necessarily fatal for the
|
|
235
484
|
// connection, but without a protection layer to frame it we close.
|
|
236
485
|
this._handleFatal(err instanceof Error ? err : new Error(String(err)));
|
|
237
486
|
}
|
|
238
487
|
}
|
|
239
|
-
/**
|
|
488
|
+
/**
|
|
489
|
+
* Dispatch an unprotected datagram — the original behavior for tests that
|
|
490
|
+
* don't exercise the TLS handshake + protection layer. Parses the packet
|
|
491
|
+
* header and decodes frames directly, matching the pre-handshake read loop.
|
|
492
|
+
*/
|
|
493
|
+
async dispatchDatagramUnprotected(data) {
|
|
494
|
+
const header = parsePacketHeader(data);
|
|
495
|
+
this.applyHeaderUnprotected(header);
|
|
496
|
+
// Skip the header + packet number to reach the frame payload.
|
|
497
|
+
const pnLength = header.packetNumberLength;
|
|
498
|
+
// Short headers carry a variable-length DCID after the first byte;
|
|
499
|
+
// its length is not on the wire, so the connection supplies it from
|
|
500
|
+
// the handshake state we already know (this.dcid).
|
|
501
|
+
const dcidLength = header.form === 0 ? this.dcid.length : 0;
|
|
502
|
+
const payloadStart = header.headerLength + dcidLength + pnLength;
|
|
503
|
+
const payload = data.subarray(payloadStart);
|
|
504
|
+
if (payload.length === 0) {
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
507
|
+
const read = this.byteStreamReader(payload);
|
|
508
|
+
for await (const frame of readFrames(read)) {
|
|
509
|
+
this.handleFrame(frame);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
/** Apply a parsed header (unprotected path) into connection state. */
|
|
513
|
+
applyHeaderUnprotected(header) {
|
|
514
|
+
if (header.form === 1) {
|
|
515
|
+
// Long header: could carry a version negotiation. We ignore for now.
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
// Short header: the DCID on the wire is the route to the peer.
|
|
519
|
+
void header.dcid;
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Determine the key phase of an inbound packet from its first byte.
|
|
523
|
+
*
|
|
524
|
+
* Long headers: Initial (0b00) → initial, Handshake (0b10) → handshake,
|
|
525
|
+
* Retry/0-RTT → initial (we treat them as initial-key for simplicity).
|
|
526
|
+
* Short headers: application (1-RTT).
|
|
527
|
+
*/
|
|
528
|
+
classifyKeyPhase(data) {
|
|
529
|
+
if (data.length === 0) {
|
|
530
|
+
return "application";
|
|
531
|
+
}
|
|
532
|
+
const first = data[0];
|
|
533
|
+
if (first === undefined) {
|
|
534
|
+
return "application";
|
|
535
|
+
}
|
|
536
|
+
const form = (first >> 7) & 0x01;
|
|
537
|
+
if (form === 1) {
|
|
538
|
+
// Long header: type in bits 4-5.
|
|
539
|
+
const type = (first >> 4) & 0x03;
|
|
540
|
+
if (type === 0b00) {
|
|
541
|
+
return "initial";
|
|
542
|
+
}
|
|
543
|
+
if (type === 0b10) {
|
|
544
|
+
return "handshake";
|
|
545
|
+
}
|
|
546
|
+
// 0-RTT and Retry: treat as initial for simplicity.
|
|
547
|
+
return "initial";
|
|
548
|
+
}
|
|
549
|
+
// Short header: 1-RTT (application keys).
|
|
550
|
+
return "application";
|
|
551
|
+
}
|
|
552
|
+
/**
|
|
553
|
+
* Decrypt the packet number and remove header protection from an inbound
|
|
554
|
+
* packet. Returns the recovered packet number and the decrypted header.
|
|
555
|
+
*/
|
|
556
|
+
unprotectHeader(data, header, keyPhase) {
|
|
557
|
+
const secrets = this.getProtectionSecrets(keyPhase);
|
|
558
|
+
if (secrets === undefined) {
|
|
559
|
+
// No keys yet — parse the plaintext packet number directly.
|
|
560
|
+
const pnLength = header.packetNumberLength;
|
|
561
|
+
const dcidLength = header.form === 0 ? this.dcid.length : 0;
|
|
562
|
+
const pnOffset = header.headerLength + dcidLength;
|
|
563
|
+
const pn = readPacketNumber(data, pnOffset, pnLength);
|
|
564
|
+
return {
|
|
565
|
+
packetNumber: pn,
|
|
566
|
+
header: {
|
|
567
|
+
...header,
|
|
568
|
+
firstByte: data[0] ?? 0,
|
|
569
|
+
packetNumberLength: pnLength,
|
|
570
|
+
},
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
const isLong = header.form === 1;
|
|
574
|
+
const dcidLength = isLong ? 0 : this.dcid.length;
|
|
575
|
+
// We need to decrypt the packet number. The header protection sample is
|
|
576
|
+
// taken from the protected payload, but we need the packet number length
|
|
577
|
+
// to find the sample. RFC 9001 §5.4.2: the packet number length is
|
|
578
|
+
// encoded in the low 2 bits of the (unprotected) first byte. To recover
|
|
579
|
+
// it we need to first remove header protection from the first byte.
|
|
580
|
+
// Simplification: assume 4-byte packet numbers for now (matching our
|
|
581
|
+
// outbound encoding). A full implementation would try all 4 lengths.
|
|
582
|
+
const assumedPnLength = 4;
|
|
583
|
+
// The sample starts 4 bytes into the protected payload, which begins
|
|
584
|
+
// after the (encrypted) packet number.
|
|
585
|
+
const sampleOffset = header.headerLength + dcidLength + assumedPnLength + 4;
|
|
586
|
+
if (data.length < sampleOffset + 16) {
|
|
587
|
+
throw new PacketProtectionError("decrypt", {
|
|
588
|
+
cause: new Error(`packet too short for header-protection sample (need ${sampleOffset + 16}, got ${data.length})`),
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
const sample = data.subarray(sampleOffset, sampleOffset + 16);
|
|
592
|
+
const hpKey = isLong ? secrets.serverProtection.hp : secrets.serverProtection.hp;
|
|
593
|
+
const mask = this.cryptoProvider.aesEcbEncrypt(hpKey, sample);
|
|
594
|
+
// Remove header protection from the first byte.
|
|
595
|
+
const firstByte = data[0] ?? 0;
|
|
596
|
+
const firstByteMask = isLong ? 0x0f : 0x1f;
|
|
597
|
+
const unmaskedFirstByte = firstByte ^ ((mask[0] ?? 0) & firstByteMask);
|
|
598
|
+
// Recover the packet number length from the unmasked first byte.
|
|
599
|
+
const recoveredPnLength = isLong
|
|
600
|
+
? (unmaskedFirstByte & 0x03) + 1
|
|
601
|
+
: (unmaskedFirstByte & 0x03) + 1;
|
|
602
|
+
// Read the (still-masked) packet number bytes.
|
|
603
|
+
const pnByteOffset = header.headerLength + dcidLength;
|
|
604
|
+
const pnBytes = data.subarray(pnByteOffset, pnByteOffset + recoveredPnLength);
|
|
605
|
+
// Remove header protection from the packet number.
|
|
606
|
+
let packetNumber = 0n;
|
|
607
|
+
for (let i = 0; i < recoveredPnLength; i++) {
|
|
608
|
+
const maskByte = mask[1 + i];
|
|
609
|
+
const pnByte = pnBytes[i];
|
|
610
|
+
if (maskByte === undefined || pnByte === undefined) {
|
|
611
|
+
throw new PacketProtectionError("decrypt", {
|
|
612
|
+
cause: new Error(`mask/pn byte ${i} out of bounds`),
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
packetNumber = (packetNumber << 8n) | BigInt(pnByte ^ maskByte);
|
|
616
|
+
}
|
|
617
|
+
return {
|
|
618
|
+
packetNumber,
|
|
619
|
+
header: {
|
|
620
|
+
...header,
|
|
621
|
+
firstByte: unmaskedFirstByte,
|
|
622
|
+
packetNumberLength: recoveredPnLength,
|
|
623
|
+
},
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
/** Header fields after header-protection removal. */
|
|
240
627
|
applyHeader(header) {
|
|
241
628
|
if (header.form === 1) {
|
|
242
629
|
// Long header: could carry a version negotiation. We ignore for now.
|
|
@@ -262,12 +649,6 @@ export class QuicConnectionImpl {
|
|
|
262
649
|
}
|
|
263
650
|
/** Route a decoded frame: data-plane frames to the manager, the rest here. */
|
|
264
651
|
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
652
|
switch (frame.type) {
|
|
272
653
|
case QuicFrameType.RESET_STREAM:
|
|
273
654
|
case QuicFrameType.STOP_SENDING:
|
|
@@ -299,21 +680,14 @@ export class QuicConnectionImpl {
|
|
|
299
680
|
case QuicFrameType.RETIRE_CONNECTION_ID:
|
|
300
681
|
case QuicFrameType.HANDSHAKE_DONE:
|
|
301
682
|
break;
|
|
302
|
-
// Path validation (RFC 9000 §8.2.1, §19.17).
|
|
303
|
-
// answered with a matching PATH_RESPONSE; a PATH_RESPONSE from the
|
|
304
|
-
// peer validates a challenge we sent.
|
|
683
|
+
// Path validation (RFC 9000 §8.2.1, §19.17).
|
|
305
684
|
case QuicFrameType.PATH_CHALLENGE: {
|
|
306
|
-
// frame is narrowed to PathChallengeFrame here; respond with the
|
|
307
|
-
// same 8 bytes (RFC 9000 §19.17).
|
|
308
685
|
const challenge = frame;
|
|
309
686
|
this.sendFrame({ type: QuicFrameType.PATH_RESPONSE, data: challenge.data });
|
|
310
687
|
void this.flush();
|
|
311
688
|
break;
|
|
312
689
|
}
|
|
313
690
|
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
691
|
const response = frame;
|
|
318
692
|
this.pendingPathChallenges.delete(hex(response.data));
|
|
319
693
|
break;
|
|
@@ -332,8 +706,6 @@ export class QuicConnectionImpl {
|
|
|
332
706
|
async readLoop() {
|
|
333
707
|
try {
|
|
334
708
|
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
709
|
// eslint-disable-next-line no-await-in-loop -- sequential datagram consumption is required
|
|
338
710
|
const { data } = await this.transport.recv();
|
|
339
711
|
// eslint-disable-next-line no-await-in-loop -- dispatch must complete before the next datagram
|
|
@@ -383,7 +755,7 @@ export class QuicConnectionImpl {
|
|
|
383
755
|
}
|
|
384
756
|
ensureOpen() {
|
|
385
757
|
if (this.closing || this.closed) {
|
|
386
|
-
throw new
|
|
758
|
+
throw new ConnectionClosingError();
|
|
387
759
|
}
|
|
388
760
|
}
|
|
389
761
|
}
|
|
@@ -426,16 +798,43 @@ function resolveLocalParameters(options) {
|
|
|
426
798
|
// ---------------------------------------------------------------------------
|
|
427
799
|
// connectQuic
|
|
428
800
|
// ---------------------------------------------------------------------------
|
|
801
|
+
/**
|
|
802
|
+
* Convert a {@link ClientHelloConfigLike} (the public QUIC option) to a
|
|
803
|
+
* full @browsercore/tls `ClientHelloConfig` the handshake driver can consume.
|
|
804
|
+
*/
|
|
805
|
+
function toTlsClientHelloConfig(like, serverName) {
|
|
806
|
+
if (like === undefined) {
|
|
807
|
+
return { ...DEFAULT_TLS_PROFILE, serverName };
|
|
808
|
+
}
|
|
809
|
+
return {
|
|
810
|
+
cipherSuites: like.cipherSuites,
|
|
811
|
+
extensionOrder: like.extensionOrder,
|
|
812
|
+
keyShareGroups: like.keyShareGroups,
|
|
813
|
+
signatureAlgorithms: like.signatureAlgorithms,
|
|
814
|
+
supportedVersions: like.supportedVersions,
|
|
815
|
+
serverName: like.serverName || serverName,
|
|
816
|
+
...(like.alpnProtocols === undefined ? {} : { alpnProtocols: like.alpnProtocols }),
|
|
817
|
+
grease: like.grease,
|
|
818
|
+
};
|
|
819
|
+
}
|
|
429
820
|
/**
|
|
430
821
|
* Establish a QUIC connection over an existing datagram transport.
|
|
431
822
|
*
|
|
432
|
-
* Creates the stream manager and the read loop.
|
|
433
|
-
*
|
|
434
|
-
*
|
|
435
|
-
*
|
|
823
|
+
* Creates the stream manager and the read loop. By default, runs the TLS 1.3
|
|
824
|
+
* handshake over QUIC stream 0 (a bidirectional stream), derives QUIC packet-
|
|
825
|
+
* protection secrets at each key phase, and returns a connection that protects
|
|
826
|
+
* inbound + outbound packets with the derived keys.
|
|
827
|
+
*
|
|
828
|
+
* The `tlsProfile` option selects the ClientHello configuration for the
|
|
829
|
+
* handshake. Defaults to a modern TLS 1.3 profile (X25519 + secp256r1 key
|
|
830
|
+
* shares, AES-256/128-GCM + ChaCha20-Poly1305). Set `skipHandshake: true` to
|
|
831
|
+
* skip the TLS handshake and return an *unprotected* connection (the data plane
|
|
832
|
+
* is fully functional and testable with a fake datagram transport, but it is
|
|
833
|
+
* not wire-ready without a protection + handshake layer on top).
|
|
436
834
|
*/
|
|
437
|
-
export function connectQuic(options) {
|
|
438
|
-
const
|
|
835
|
+
export async function connectQuic(options) {
|
|
836
|
+
const clock = options.clock ?? systemClock;
|
|
837
|
+
const id = `quic_${clock.now().toString(36)}`;
|
|
439
838
|
// The stream manager is constructed before the connection, but its frames
|
|
440
839
|
// must reach the connection's packetizer. We bridge the two with a mutable
|
|
441
840
|
// router that we point at the connection once it exists.
|
|
@@ -447,13 +846,44 @@ export function connectQuic(options) {
|
|
|
447
846
|
localParameters: resolveLocalParameters(options),
|
|
448
847
|
peerParameters: options.transportParameters ?? {},
|
|
449
848
|
});
|
|
450
|
-
const conn = new QuicConnectionImpl(id, options, manager, options.initialDcid);
|
|
849
|
+
const conn = new QuicConnectionImpl(id, options, manager, options.initialDcid, options.logger ?? silentLogger);
|
|
451
850
|
frameRouter.send = (frame) => {
|
|
452
851
|
conn.sendFrame(frame);
|
|
453
852
|
};
|
|
454
853
|
// A larger send window may have queued stream data — the read loop drains it.
|
|
455
854
|
manager.on("maxData", () => { });
|
|
855
|
+
// Start the read loop. The handshake (if any) runs concurrently so the
|
|
856
|
+
// server's response is processed.
|
|
456
857
|
conn.startReadLoop();
|
|
457
|
-
|
|
858
|
+
if (options.skipHandshake === true) {
|
|
859
|
+
// Return an unprotected connection for testing the data plane without
|
|
860
|
+
// a live TLS peer.
|
|
861
|
+
return conn;
|
|
862
|
+
}
|
|
863
|
+
// Run the TLS handshake. On failure, the connection surfaces the error.
|
|
864
|
+
await conn.performHandshake();
|
|
865
|
+
return conn;
|
|
866
|
+
}
|
|
867
|
+
/** Map a TLS AEAD algorithm to the QUIC AEAD subset (AES-128-CCM is not used by QUIC). */
|
|
868
|
+
function mapAeadToQuic(aead) {
|
|
869
|
+
switch (aead) {
|
|
870
|
+
case "AES-128-GCM":
|
|
871
|
+
return "AES-128-GCM";
|
|
872
|
+
case "AES-256-GCM":
|
|
873
|
+
return "AES-256-GCM";
|
|
874
|
+
case "CHACHA20-POLY1305":
|
|
875
|
+
// TLS uses "CHACHA20_POLY1305" (underscores); QUIC's QuicAead type
|
|
876
|
+
// mirrors TLS naming. The packet-protection layer maps to
|
|
877
|
+
// @browsercore/crypto's "ChaCha20-Poly1305" (hyphens) internally.
|
|
878
|
+
return "CHACHA20-POLY1305";
|
|
879
|
+
case "AES-128-CCM":
|
|
880
|
+
// AES-128-CCM is negotiated by TLS but not used by QUIC v1. Fall
|
|
881
|
+
// back to AES-128-GCM; the connection will fail at the TLS layer
|
|
882
|
+
// if the server actually selects CCM.
|
|
883
|
+
return "AES-128-GCM";
|
|
884
|
+
default:
|
|
885
|
+
// Every AeadAlgorithm variant is covered above.
|
|
886
|
+
return assertNever(aead);
|
|
887
|
+
}
|
|
458
888
|
}
|
|
459
889
|
//# sourceMappingURL=connection.js.map
|