@browsercore/tls 0.1.0 → 0.1.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.
package/dist/tls.js CHANGED
@@ -1,23 +1,87 @@
1
1
  /**
2
2
  * @browsercore/tls — public entry point.
3
3
  *
4
- * Establishes a TLS 1.3 (with 1.2 fallback) connection over an existing
5
- * byte-stream transport. Wires together the record layer, handshake state
6
- * machine, key schedule, and certificate validation — consuming @browsercore/transport
7
- * and @browsercore/crypto, never node:crypto directly.
4
+ * Establishes a TLS 1.3 connection over an existing byte-stream transport.
5
+ * Wires together the record layer, handshake state machine, key schedule, and
6
+ * certificate validation — consuming @browsercore/transport and @browsercore/crypto,
7
+ * never node:crypto directly.
8
+ *
9
+ * TLS 1.2 fallback is intentionally NOT implemented: this client speaks TLS 1.3
10
+ * only. Requesting a TLS 1.2 (only) handshake is rejected up front with a typed
11
+ * error rather than failing silently mid-flight.
8
12
  */
9
- import { TlsHandshakeError } from "./errors.js";
13
+ import { crypto, SHA_384 } from "@browsercore/crypto";
14
+ import { TLS_1_3 } from "./types.js";
15
+ import { TlsAlertError, TlsHandshakeError, ensureTlsError } from "./errors.js";
10
16
  import { createId } from "./utils.js";
11
- import { parseRecordHeader, serializeRecordHeader, RECORD_HEADER_SIZE } from "./record/record.js";
12
- import { buildClientHello, parseServerHello } from "./handshake/handshake.js";
17
+ import { cipherSuiteToAead, ContentType, decryptRecord, encryptRecord, parseRecordHeader, serializeRecordHeader, } from "./record/record.js";
18
+ import { advanceHandshake, buildClientHello, parseServerHello, recordServerHello, HandshakeType, } from "./handshake/handshake.js";
19
+ import { cipherSuiteToHash, deriveApplicationSecrets, deriveHandshakeTrafficSecrets, deriveTrafficSecrets, hkdfExpandLabel, } from "./crypto/keySchedule.js";
20
+ import { ExtensionType, findExtension, parseExtensions, wireToNamedGroup, } from "./extensions/extensions.js";
21
+ import { parseCertificate, validateHostname, verifyChain } from "./certificates/certificates.js";
13
22
  /** Default handshake timeout in milliseconds. */
14
23
  const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;
24
+ /** AEAD authentication tag length for every cipher we support (bytes). */
25
+ const AEAD_TAG_LENGTH = 16;
26
+ /**
27
+ * Key-share groups the crypto backend can actually generate. @browsercore/crypto
28
+ * exposes only X25519 key generation today, so the handshake restricts itself to
29
+ * that group. Any profile advertising only other groups cannot be satisfied.
30
+ */
31
+ const SUPPORTED_KEY_SHARE_GROUPS = ["x25519"];
32
+ /** Map a negotiated cipher suite to the hash function used for its transcript. */
33
+ function hashFor(cipherSuite) {
34
+ return cipherSuiteToHash(cipherSuite);
35
+ }
36
+ /** Output length (bytes) of the hash used by a cipher suite. */
37
+ function hashLengthFor(hash) {
38
+ return hash === SHA_384 ? 48 : 32;
39
+ }
40
+ /** Concatenate byte chunks into a single buffer. */
41
+ function concat(...chunks) {
42
+ let total = 0;
43
+ for (const c of chunks) {
44
+ total += c.length;
45
+ }
46
+ const out = new Uint8Array(total);
47
+ let o = 0;
48
+ for (const c of chunks) {
49
+ out.set(c, o);
50
+ o += c.length;
51
+ }
52
+ return out;
53
+ }
54
+ /**
55
+ * Build the per-record AEAD nonce by XOR-ing the (zero-padded, big-endian)
56
+ * sequence number into the static IV — exactly TLS 1.3 §5.3.
57
+ */
58
+ function xorNonce(iv, seq) {
59
+ const nonce = Uint8Array.from(iv);
60
+ let s = seq;
61
+ for (let i = nonce.length - 1; i >= nonce.length - 8 && s > 0; i--) {
62
+ // bitwise XOR assign: flip the low byte of s into nonce[i]. The loop
63
+ // bounds guarantee i is a valid index, so the non-null assertion is safe.
64
+ nonce[i] ^= s & 0xff;
65
+ s = Math.floor(s / 256);
66
+ }
67
+ return nonce;
68
+ }
69
+ /** Constant-time byte comparison (length-equal only; leaks length, not contents). */
70
+ function constantTimeEqual(a, b) {
71
+ if (a.length !== b.length) {
72
+ return false;
73
+ }
74
+ let diff = 0;
75
+ for (let i = 0; i < a.length; i++) {
76
+ diff |= a[i] ^ b[i];
77
+ }
78
+ return diff === 0;
79
+ }
15
80
  /**
16
- * Establish a TLS connection over the given transport.
81
+ * Establish a TLS 1.3 connection over the given transport.
17
82
  *
18
- * Performs the full TLS 1.3 handshake (falling back to 1.2 if the server does
19
- * not support 1.3), derives traffic secrets, and returns a {@link TlsConnection}
20
- * that transparently encrypts/decrypts application data.
83
+ * Performs the full TLS 1.3 handshake, derives traffic secrets, and returns a
84
+ * {@link TlsConnection} that transparently encrypts/decrypts application data.
21
85
  *
22
86
  * @example
23
87
  * ```ts
@@ -34,56 +98,571 @@ const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;
34
98
  * ```
35
99
  */
36
100
  export async function connectTls(options) {
37
- // PLAN: implement the full handshake:
38
- // 1. Generate key shares for each group in options.profile.keyShareGroups
39
- // via @browsercore/crypto -> KeyPair[].
40
- // 2. buildClientHello(options.profile, keyPairs) -> write handshake record.
41
- // 3. Read ServerHello record -> parseServerHello.
42
- // 4. (EC)DHE key exchange via @browsercore/crypto -> sharedSecret.
43
- // 5. deriveHandshakeSecrets / deriveApplicationSecrets.
44
- // 6. Read + decrypt EncryptedExtensions, Certificate, CertificateVerify, Finished.
45
- // 7. verifyChain against trust anchors + serverName.
46
- // 8. Send client Finished. Transition state to "open".
47
- // Drive TlsState through connecting -> handshaking -> open.
48
- const handshakeTimeoutMs = options.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS;
49
- void handshakeTimeoutMs;
50
- void options;
51
- void parseRecordHeader;
52
- void serializeRecordHeader;
53
- void RECORD_HEADER_SIZE;
54
- void buildClientHello;
55
- void parseServerHello;
56
- throw new Error("not implemented — see PLAN.md");
101
+ const conn = new TlsConnectionImpl(options);
102
+ await conn.handshake();
103
+ return conn;
57
104
  }
58
- /** Concrete TLS connection implementation (filled in per PLAN.md). */
105
+ /** Generate key shares for the requested groups (delegates to @browsercore/crypto). */
106
+ export async function generateKeyShares(groups) {
107
+ const shares = [];
108
+ for (const group of groups) {
109
+ if (group !== "x25519") {
110
+ // @browsercore/crypto only exposes X25519 key generation today. Other
111
+ // (EC)DHE groups would need a backend we do not have — fail fast and
112
+ // typed rather than producing a bogus key.
113
+ throw new TlsHandshakeError("client_hello", {
114
+ cause: new Error(`key share group "${group}" is not supported by the crypto backend`),
115
+ });
116
+ }
117
+ const kp = crypto.x25519GenerateKeyPair();
118
+ shares.push({ algorithm: "x25519", privateKey: kp.secretKey, publicKey: kp.publicKey });
119
+ }
120
+ return shares;
121
+ }
122
+ /** Concrete TLS 1.3 connection implementation. */
59
123
  export class TlsConnectionImpl {
60
124
  id = createId("tls");
61
125
  state = { state: "connecting" };
62
- protocolVersion;
63
- cipherSuite;
126
+ // This client speaks TLS 1.3 only, so the public fields default to the only
127
+ // protocol version it can negotiate. They are overwritten once a ServerHello
128
+ // is parsed. Defaults let a no-arg `new TlsConnectionImpl()` be inspected
129
+ // without a live transport (used by the public-API-surface test).
130
+ cipherSuite = "TLS_AES_128_GCM_SHA256";
131
+ protocolVersion = TLS_1_3;
64
132
  alpnProtocol;
65
- constructor() {
66
- // Placeholder values so the readonly fields are initialized.
67
- this.protocolVersion = { name: "TLS 1.3", wire: 0x0304 };
68
- this.cipherSuite = "TLS_AES_128_GCM_SHA256";
133
+ /** The peer's leaf certificate, once the handshake has validated it. */
134
+ peerCertificate;
135
+ _transport;
136
+ _profile;
137
+ _serverName;
138
+ _trustAnchors = [];
139
+ /** Buffered bytes not yet consumed by the record framer. */
140
+ _readBuffer = new Uint8Array(0);
141
+ /** Running handshake transcript: full handshake messages (with 4-byte headers). */
142
+ _transcript = [];
143
+ _aead;
144
+ _hash;
145
+ _serverHello;
146
+ _clientHsTraffic;
147
+ _serverHsTraffic;
148
+ _clientHsTrafficSecret;
149
+ _serverHsTrafficSecret;
150
+ _masterSecret;
151
+ _applicationSecrets;
152
+ _clientHsSeq = 0;
153
+ _serverHsSeq = 0;
154
+ _clientAppSeq = 0;
155
+ _serverAppSeq = 0;
156
+ /** Decrypted application payloads awaiting consumption by read(). */
157
+ _appReadQueue = [];
158
+ /** Lifecycle observers. */
159
+ _closeListeners = [];
160
+ _errorListeners = [];
161
+ // `options` is optional so a connection can be constructed in isolation (e.g.
162
+ // to assert on its default public fields) without a live transport. The real
163
+ // entry point, connectTls, always supplies a full options object.
164
+ constructor(options) {
165
+ if (options !== undefined) {
166
+ this._transport = options.transport;
167
+ this._serverName = options.serverName;
168
+ this._trustAnchors = options.trustAnchors ?? [];
169
+ // An explicit alpnProtocols option overrides whatever the profile says.
170
+ this._profile =
171
+ options.alpnProtocols !== undefined && options.alpnProtocols.length > 0
172
+ ? { ...options.profile, alpnProtocols: options.alpnProtocols }
173
+ : options.profile;
174
+ }
175
+ }
176
+ // -------------------------------------------------------------------------
177
+ // Public async handshake API.
178
+ // -------------------------------------------------------------------------
179
+ /**
180
+ * Drive the TLS 1.3 handshake to completion. Idempotent: calling it more than
181
+ * once on an open connection is a no-op.
182
+ */
183
+ async handshake(timeoutMs = DEFAULT_HANDSHAKE_TIMEOUT_MS) {
184
+ if (this.state.state === "open") {
185
+ return;
186
+ }
187
+ await this._withTimeout(timeoutMs, () => this._performHandshake());
69
188
  }
70
189
  async read() {
71
190
  this._ensureOpen();
72
- void this._applicationSecrets;
73
- throw new Error("not implemented — see PLAN.md");
191
+ if (this._appReadQueue.length > 0) {
192
+ return { payload: this._appReadQueue.shift() };
193
+ }
194
+ // Read encrypted records until an application-data payload arrives.
195
+ for (;;) {
196
+ const { innerType, content } = await this._readEncryptedRecord(this._applicationSecrets.server, this._serverAppSeq);
197
+ this._serverAppSeq++;
198
+ if (innerType === ContentType.APPLICATION_DATA) {
199
+ return { payload: content };
200
+ }
201
+ this._handlePostHandshakeRecord(innerType, content);
202
+ }
74
203
  }
75
- async write(_data) {
204
+ async write(data) {
76
205
  this._ensureOpen();
77
- void this._transport;
78
- throw new Error("not implemented — see PLAN.md");
206
+ const traffic = this._applicationSecrets.client;
207
+ // Split into record-sized plaintext fragments (TLS records cap at 2^14 bytes).
208
+ for (let offset = 0; offset < data.length; offset += 16_384) {
209
+ const fragment = data.subarray(offset, Math.min(offset + 16_384, data.length));
210
+ this._writeEncryptedRecord(traffic, ContentType.APPLICATION_DATA, fragment, this._clientAppSeq);
211
+ this._clientAppSeq++;
212
+ }
79
213
  }
80
214
  async close() {
81
- throw new Error("not implemented — see PLAN.md");
215
+ if (this.state.state === "closed") {
216
+ return;
217
+ }
218
+ // Send close_notify under the current (application) traffic keys, then
219
+ // tear down the transport. Best-effort: a failing alert must not mask the
220
+ // close itself.
221
+ if (this.state.state === "open") {
222
+ try {
223
+ const alert = new Uint8Array([0x01, 0x00]); // warning / close_notify
224
+ this._writeEncryptedRecord(this._applicationSecrets.client, ContentType.ALERT, alert, this._clientAppSeq);
225
+ }
226
+ catch {
227
+ // ignore — we are closing anyway
228
+ }
229
+ }
230
+ await this._transport.close();
231
+ this._transition({ state: "closed", reason: { kind: "close_notify" } });
232
+ for (const listener of this._closeListeners) {
233
+ listener({ kind: "close_notify" });
234
+ }
235
+ }
236
+ on(event, listener) {
237
+ if (event === "close") {
238
+ this._closeListeners.push(listener);
239
+ }
240
+ else {
241
+ this._errorListeners.push(listener);
242
+ }
243
+ return this;
244
+ }
245
+ // -------------------------------------------------------------------------
246
+ // Handshake state machine (RFC 8446).
247
+ // -------------------------------------------------------------------------
248
+ async _performHandshake() {
249
+ this.state = { state: "handshaking" };
250
+ // TLS 1.3 only: reject a profile that cannot negotiate TLS 1.3.
251
+ if (!this._profile.supportedVersions.some((v) => v.name === "TLS 1.3")) {
252
+ throw new TlsHandshakeError("client_hello", {
253
+ cause: new Error("TLS 1.2-only handshakes are not supported by this client"),
254
+ });
255
+ }
256
+ // 1. Generate key shares for the groups the crypto backend supports.
257
+ const desired = this._profile.keyShareGroups.filter((g) => SUPPORTED_KEY_SHARE_GROUPS.includes(g));
258
+ if (desired.length === 0) {
259
+ throw new TlsHandshakeError("client_hello", {
260
+ cause: new Error("no supported key share groups in the selected profile"),
261
+ });
262
+ }
263
+ const keyPairs = await generateKeyShares(desired);
264
+ // 2. Build and send the ClientHello as a plaintext handshake record.
265
+ const clientHello = buildClientHello(this._profile, keyPairs);
266
+ this._transcript.push(clientHello);
267
+ await this._writeRecord(ContentType.HANDSHAKE, clientHello);
268
+ // 3. Read the ServerHello (still plaintext) and validate the negotiation.
269
+ const shHeader = await this._readHeaderBytes();
270
+ const shRecord = await this._readRawRecord(shHeader);
271
+ if (shRecord.type !== ContentType.HANDSHAKE) {
272
+ throw new TlsHandshakeError("server_hello", {
273
+ cause: new Error(`expected handshake record, got content type ${shRecord.type}`),
274
+ });
275
+ }
276
+ this._transcript.push(shRecord.fragment);
277
+ const serverHello = parseServerHello(shRecord.fragment.subarray(4), {
278
+ cipherSuites: this._profile.cipherSuites,
279
+ supportedVersions: this._profile.supportedVersions,
280
+ });
281
+ this._serverHello = serverHello;
282
+ this.cipherSuite = serverHello.cipherSuite;
283
+ this.protocolVersion = serverHello.selectedVersion;
284
+ this._aead = cipherSuiteToAead(this.cipherSuite);
285
+ this._hash = hashFor(this.cipherSuite);
286
+ // 4. (EC)DHE key exchange: recover the server's key share and compute the shared secret.
287
+ const sharedSecret = this._computeSharedSecret(serverHello, keyPairs);
288
+ // 5. Derive handshake traffic secrets from the ClientHello..ServerHello transcript.
289
+ const helloTranscript = this._transcriptHash();
290
+ const { masterSecret, clientTrafficSecret, serverTrafficSecret } = deriveHandshakeTrafficSecrets(sharedSecret, helloTranscript, this.cipherSuite);
291
+ this._masterSecret = masterSecret;
292
+ this._clientHsTrafficSecret = clientTrafficSecret;
293
+ this._serverHsTrafficSecret = serverTrafficSecret;
294
+ this._clientHsTraffic = deriveTrafficSecrets(clientTrafficSecret, this.cipherSuite, this._hash);
295
+ this._serverHsTraffic = deriveTrafficSecrets(serverTrafficSecret, this.cipherSuite, this._hash);
296
+ // 6. Consume the server's encrypted flight: EncryptedExtensions, Certificate,
297
+ // CertificateVerify, Finished.
298
+ await this._consumeServerFlight();
299
+ // 7. Derive application traffic secrets from the full handshake transcript.
300
+ const handshakeTranscript = this._transcriptHash();
301
+ this._applicationSecrets = deriveApplicationSecrets(this._masterSecret, handshakeTranscript, this.cipherSuite);
302
+ // 8. Send the client Finished under the client handshake traffic key.
303
+ await this._sendClientFinished();
304
+ // 9. Transition to the open state; negotiated parameters are already exposed
305
+ // on the public fields (cipherSuite, protocolVersion, alpnProtocol, ...).
306
+ // Under exactOptionalPropertyTypes, `alpnProtocol?` must be omitted (not
307
+ // `undefined`) when the server did not negotiate one.
308
+ this._transition({
309
+ state: "open",
310
+ sessionId: this.id,
311
+ protocolVersion: this.protocolVersion,
312
+ cipherSuite: this.cipherSuite,
313
+ ...(this.alpnProtocol !== undefined ? { alpnProtocol: this.alpnProtocol } : {}),
314
+ });
315
+ }
316
+ /**
317
+ * Read the server's encrypted second flight message-by-message, advancing the
318
+ * handshake state machine and updating the transcript. Server Finished is
319
+ * verified against the transcript as it stood *before* the Finished message.
320
+ */
321
+ async _consumeServerFlight() {
322
+ // The server_hello_received phase, carrying the parsed ServerHello forward
323
+ // so advanceHandshake can validate the rest of the flight against it.
324
+ let phase = recordServerHello({ phase: "client_hello_sent" }, this._serverHello);
325
+ // EncryptedExtensions.
326
+ let message = await this._readEncryptedHandshakeMessage(this._serverHsTraffic, this._serverHsSeq);
327
+ this._serverHsSeq++;
328
+ phase = advanceHandshake(phase, HandshakeType.ENCRYPTED_EXTENSIONS);
329
+ this._transcript.push(message.whole);
330
+ this._handleEncryptedExtensions(message.body);
331
+ // Certificate.
332
+ message = await this._readEncryptedHandshakeMessage(this._serverHsTraffic, this._serverHsSeq);
333
+ this._serverHsSeq++;
334
+ phase = advanceHandshake(phase, HandshakeType.CERTIFICATE);
335
+ this._transcript.push(message.whole);
336
+ await this._handleCertificate(message.body);
337
+ // CertificateVerify.
338
+ message = await this._readEncryptedHandshakeMessage(this._serverHsTraffic, this._serverHsSeq);
339
+ this._serverHsSeq++;
340
+ phase = advanceHandshake(phase, HandshakeType.CERTIFICATE_VERIFY);
341
+ this._transcript.push(message.whole);
342
+ // Finished — verify against the transcript *before* appending the Finished.
343
+ const finishedTranscript = this._transcriptHash();
344
+ message = await this._readEncryptedHandshakeMessage(this._serverHsTraffic, this._serverHsSeq);
345
+ this._serverHsSeq++;
346
+ this._verifyServerFinished(message.body, finishedTranscript);
347
+ advanceHandshake(phase, HandshakeType.FINISHED);
348
+ this._transcript.push(message.whole);
349
+ }
350
+ // -------------------------------------------------------------------------
351
+ // Record layer.
352
+ // -------------------------------------------------------------------------
353
+ /** Write an unencrypted record (used for the initial ClientHello/ServerHello). */
354
+ async _writeRecord(type, fragment) {
355
+ await this._transport.write(concat(serializeRecordHeader(type, fragment.length), fragment));
356
+ }
357
+ /**
358
+ * Read the 5-byte record header and return it raw (needed as AEAD AAD) plus
359
+ * the parsed length. The caller is responsible for consuming the fragment.
360
+ */
361
+ async _readHeaderBytes() {
362
+ await this._ensureBytes(5);
363
+ const raw = this._readBuffer.subarray(0, 5);
364
+ const parsed = parseRecordHeader(raw);
365
+ return { raw, length: parsed.length };
82
366
  }
83
- on(_event, _listener) {
84
- void _event;
85
- void _listener;
86
- throw new Error("not implemented — see PLAN.md");
367
+ /** Read a complete record given its already-consumed header. */
368
+ async _readRawRecord(header) {
369
+ await this._ensureBytes(5 + header.length);
370
+ // type is byte 0 of the header; parseRecordHeader already validated it.
371
+ const type = header.raw[0];
372
+ const fragment = this._readBuffer.subarray(5, 5 + header.length);
373
+ this._readBuffer = this._readBuffer.subarray(5 + header.length);
374
+ return { type, fragment };
375
+ }
376
+ /**
377
+ * Read and decrypt one record, returning its inner content type and content.
378
+ * TLS 1.3 wraps encrypted handshake messages in records whose outer type is
379
+ * application_data; the real type is the last non-zero byte of the plaintext.
380
+ */
381
+ async _readEncryptedRecord(traffic, seq) {
382
+ const header = await this._readHeaderBytes();
383
+ const record = await this._readRawRecord(header);
384
+ if (record.type !== ContentType.APPLICATION_DATA) {
385
+ throw new TlsHandshakeError("finished", {
386
+ cause: new Error(`expected encrypted APPLICATION_DATA record, got ${record.type}`),
387
+ });
388
+ }
389
+ const nonce = xorNonce(traffic.iv, seq);
390
+ const plaintext = decryptRecord(record.fragment, traffic.key, nonce, header.raw, this._aead);
391
+ // plaintext = content || innerType || optional zero padding. Find the type.
392
+ let end = plaintext.length;
393
+ while (end > 0 && plaintext[end - 1] === 0) {
394
+ end--;
395
+ }
396
+ if (end === 0) {
397
+ throw new TlsHandshakeError("finished", {
398
+ cause: new Error("encrypted record plaintext is all zero padding"),
399
+ });
400
+ }
401
+ const innerType = plaintext[end - 1];
402
+ return { innerType, content: plaintext.subarray(0, end - 1) };
403
+ }
404
+ /** Pull bytes from the transport until at least `n` are buffered. */
405
+ async _ensureBytes(n) {
406
+ while (this._readBuffer.length < n) {
407
+ const chunk = await this._transport.read();
408
+ this._readBuffer = concat(this._readBuffer, chunk);
409
+ }
410
+ }
411
+ // -------------------------------------------------------------------------
412
+ // Key exchange + transcript.
413
+ // -------------------------------------------------------------------------
414
+ /** Compute the (EC)DHE shared secret from the server's selected key share. */
415
+ _computeSharedSecret(serverHello, keyPairs) {
416
+ const extensions = parseExtensions(serverHello.extensions);
417
+ const keyShare = findExtension(extensions, ExtensionType.KEY_SHARE);
418
+ if (keyShare === undefined) {
419
+ throw new TlsHandshakeError("server_hello", {
420
+ cause: new Error("ServerHello missing required key_share extension"),
421
+ });
422
+ }
423
+ // Server KeyShareEntry: group(2) || len(2) || key_exchange.
424
+ if (keyShare.data.length < 4) {
425
+ throw new TlsHandshakeError("server_hello", {
426
+ cause: new Error("key_share entry truncated"),
427
+ });
428
+ }
429
+ const group = wireToNamedGroup((keyShare.data[0] << 8) | keyShare.data[1]);
430
+ const keyLen = (keyShare.data[2] << 8) | keyShare.data[3];
431
+ if (keyLen + 4 !== keyShare.data.length) {
432
+ throw new TlsHandshakeError("server_hello", {
433
+ cause: new Error("key_share key_exchange length mismatch"),
434
+ });
435
+ }
436
+ const serverPublicKey = keyShare.data.subarray(4, 4 + keyLen);
437
+ const myPair = keyPairs.find((kp) => kp.algorithm === group);
438
+ if (myPair === undefined) {
439
+ throw new TlsHandshakeError("server_hello", {
440
+ cause: new Error(`server selected key share group ${group} we did not offer`),
441
+ });
442
+ }
443
+ switch (group) {
444
+ case "x25519":
445
+ return crypto.x25519SharedSecret(myPair.privateKey, serverPublicKey);
446
+ default:
447
+ throw new TlsHandshakeError("server_hello", {
448
+ cause: new Error(`key exchange for group ${group} is not supported by the crypto backend`),
449
+ });
450
+ }
451
+ }
452
+ /** Hash the current handshake transcript with the negotiated cipher's hash. */
453
+ _transcriptHash() {
454
+ const blob = concat(...this._transcript);
455
+ return this._hash === SHA_384 ? crypto.sha384(blob) : crypto.sha256(blob);
456
+ }
457
+ // -------------------------------------------------------------------------
458
+ // Handshake message handling.
459
+ // -------------------------------------------------------------------------
460
+ /** Read one encrypted handshake message, decrypting and stripping the inner type. */
461
+ async _readEncryptedHandshakeMessage(traffic, seq) {
462
+ const header = await this._readHeaderBytes();
463
+ const record = await this._readRawRecord(header);
464
+ if (record.type !== ContentType.APPLICATION_DATA) {
465
+ throw new TlsHandshakeError("finished", {
466
+ cause: new Error(`expected encrypted APPLICATION_DATA record, got ${record.type}`),
467
+ });
468
+ }
469
+ const nonce = xorNonce(traffic.iv, seq);
470
+ const plaintext = decryptRecord(record.fragment, traffic.key, nonce, header.raw, this._aead);
471
+ // plaintext = content || innerType || optional zero padding. Find the type.
472
+ let end = plaintext.length;
473
+ while (end > 0 && plaintext[end - 1] === 0) {
474
+ end--;
475
+ }
476
+ if (end === 0) {
477
+ throw new TlsHandshakeError("finished", {
478
+ cause: new Error("encrypted record plaintext is all zero padding"),
479
+ });
480
+ }
481
+ const innerType = plaintext[end - 1];
482
+ const content = plaintext.subarray(0, end - 1);
483
+ if (innerType !== ContentType.HANDSHAKE) {
484
+ throw new TlsHandshakeError("finished", {
485
+ cause: new Error(`expected inner handshake type, got ${innerType}`),
486
+ });
487
+ }
488
+ // `content` is the full handshake message (4-byte header + body).
489
+ return { whole: content, body: content.subarray(4) };
490
+ }
491
+ /** Extract the negotiated ALPN protocol from EncryptedExtensions, if any. */
492
+ _handleEncryptedExtensions(body) {
493
+ const extensions = parseExtensions(body);
494
+ const alpn = findExtension(extensions, ExtensionType.APPLICATION_LAYER_PROTOCOL_NEGOTIATION);
495
+ if (alpn === undefined) {
496
+ return;
497
+ }
498
+ // Server ALPN body: length-prefixed list with a single entry.
499
+ if (alpn.data.length < 3) {
500
+ return;
501
+ }
502
+ const nameLen = alpn.data[2];
503
+ if (3 + nameLen > alpn.data.length) {
504
+ return;
505
+ }
506
+ this.alpnProtocol = new TextDecoder().decode(alpn.data.subarray(3, 3 + nameLen));
507
+ }
508
+ /** Parse the Certificate message, validate hostname, and verify the chain. */
509
+ async _handleCertificate(body) {
510
+ const chain = this._parseCertificateMessage(body);
511
+ this.peerCertificate = chain.leaf;
512
+ if (!validateHostname(chain.leaf, this._serverName)) {
513
+ throw new TlsHandshakeError("certificate", {
514
+ cause: new Error(`hostname "${this._serverName}" does not match the leaf certificate`),
515
+ });
516
+ }
517
+ // Full chain verification requires trust anchors. Without them we still
518
+ // performed hostname validation above; chain verification is best-effort.
519
+ if (this._trustAnchors.length > 0) {
520
+ // Trust anchors arrive as raw DER root certificates; verifyChain wants
521
+ // parsed TrustAnchor records (SPKI + subject). A trust anchor is a
522
+ // self-signed root, so its issuer DN is also its subject.
523
+ const anchors = this._trustAnchors.map((der) => {
524
+ const root = parseCertificate(der);
525
+ return { subjectPublicKeyInfo: root.subjectPublicKeyInfo, subject: root.issuer };
526
+ });
527
+ await verifyChain(chain, anchors, this._serverName, Math.floor(Date.now() / 1000));
528
+ }
529
+ }
530
+ /**
531
+ * Parse a Certificate handshake message (RFC 8446 §4.4.2) into a chain. The
532
+ * body is: certificate_request_context (length-prefixed, len 1) then a
533
+ * length-prefixed list of CertificateEntry { cert_data, extensions }.
534
+ */
535
+ _parseCertificateMessage(body) {
536
+ let o = 0;
537
+ const ctxLen = body[o++];
538
+ o += ctxLen;
539
+ const listLen = (body[o++] << 16) | (body[o++] << 8) | body[o++];
540
+ const listEnd = o + listLen;
541
+ if (listEnd > body.length) {
542
+ throw new TlsHandshakeError("certificate", {
543
+ cause: new Error("certificate_list length exceeds message body"),
544
+ });
545
+ }
546
+ const certs = [];
547
+ while (o < listEnd) {
548
+ const certLen = (body[o++] << 16) | (body[o++] << 8) | body[o++];
549
+ const certDer = body.subarray(o, o + certLen);
550
+ o += certLen;
551
+ const extLen = (body[o++] << 8) | body[o++];
552
+ o += extLen;
553
+ certs.push(parseCertificate(certDer));
554
+ }
555
+ if (certs.length === 0) {
556
+ throw new TlsHandshakeError("certificate", {
557
+ cause: new Error("server sent an empty certificate_list"),
558
+ });
559
+ }
560
+ const leaf = certs[0];
561
+ const root = certs[certs.length - 1];
562
+ const intermediates = certs.slice(1, certs.length - 1);
563
+ return { leaf, intermediates, root };
564
+ }
565
+ /**
566
+ * Verify the server's Finished message: HMAC(finished_key, transcript), where
567
+ * finished_key = HKDF-Expand-Label(server_traffic_secret, "finished", "", Hash.length)
568
+ * and the transcript is ClientHello..CertificateVerify (everything before Finished).
569
+ */
570
+ _verifyServerFinished(body, transcript) {
571
+ const hashLen = hashLengthFor(this._hash);
572
+ if (body.length !== hashLen) {
573
+ throw new TlsHandshakeError("finished", {
574
+ cause: new Error(`server Finished length ${body.length} != expected ${hashLen}`),
575
+ });
576
+ }
577
+ const finishedKey = hkdfExpandLabel(this._serverHsTrafficSecret, "finished", new Uint8Array(0), hashLen, this._hash);
578
+ const expected = crypto.hmac(this._hash, finishedKey, transcript);
579
+ if (!constantTimeEqual(body, expected)) {
580
+ throw new TlsHandshakeError("finished", {
581
+ cause: new Error("server Finished verify_data mismatch"),
582
+ });
583
+ }
584
+ }
585
+ /** Build and send the client Finished under the client handshake traffic key. */
586
+ async _sendClientFinished() {
587
+ const hashLen = hashLengthFor(this._hash);
588
+ const transcript = this._transcriptHash();
589
+ const finishedKey = hkdfExpandLabel(this._clientHsTrafficSecret, "finished", new Uint8Array(0), hashLen, this._hash);
590
+ const verifyData = crypto.hmac(this._hash, finishedKey, transcript);
591
+ const message = new Uint8Array(4 + verifyData.length);
592
+ message[0] = HandshakeType.FINISHED;
593
+ message[1] = (verifyData.length >> 16) & 0xff;
594
+ message[2] = (verifyData.length >> 8) & 0xff;
595
+ message[3] = verifyData.length & 0xff;
596
+ message.set(verifyData, 4);
597
+ this._writeEncryptedRecord(this._clientHsTraffic, ContentType.HANDSHAKE, message, this._clientHsSeq);
598
+ this._clientHsSeq++;
599
+ }
600
+ // -------------------------------------------------------------------------
601
+ // Encrypted record I/O (handshake + application traffic).
602
+ // -------------------------------------------------------------------------
603
+ /**
604
+ * Encrypt a payload under `traffic` and write it as an encrypted record whose
605
+ * outer type is application_data. The inner content type byte is appended to
606
+ * the plaintext before encryption.
607
+ */
608
+ _writeEncryptedRecord(traffic, innerType, content, seq) {
609
+ const plaintext = concat(content, new Uint8Array([innerType]));
610
+ const header = serializeRecordHeader(ContentType.APPLICATION_DATA, plaintext.length + AEAD_TAG_LENGTH);
611
+ const nonce = xorNonce(traffic.iv, seq);
612
+ const ciphertext = encryptRecord(plaintext, traffic.key, nonce, header, this._aead);
613
+ void this._transport.write(concat(header, ciphertext));
614
+ }
615
+ /** Handle a non-application record encountered while reading application data. */
616
+ _handlePostHandshakeRecord(innerType, content) {
617
+ switch (innerType) {
618
+ case ContentType.ALERT:
619
+ this._handleAlert(content);
620
+ break;
621
+ case ContentType.HANDSHAKE:
622
+ // Post-handshake handshake (e.g. NewSessionTicket, KeyUpdate) — out of
623
+ // scope for the happy path; ignore but do not error.
624
+ break;
625
+ default:
626
+ throw new TlsHandshakeError("finished", {
627
+ cause: new Error(`unexpected post-handshake record type ${innerType}`),
628
+ });
629
+ }
630
+ }
631
+ /** Translate a received alert into a typed error and close the connection. */
632
+ _handleAlert(content) {
633
+ if (content.length < 2) {
634
+ this._emitError(ensureTlsError(new TlsAlertError("fatal", 0, { cause: new Error("truncated alert record") })));
635
+ return;
636
+ }
637
+ const level = content[0] === 0x02 ? "fatal" : "warning";
638
+ const description = content[1];
639
+ if (description === 0) {
640
+ // close_notify — graceful.
641
+ this._transition({ state: "closed", reason: { kind: "close_notify" } });
642
+ return;
643
+ }
644
+ this._emitError(ensureTlsError(new TlsAlertError(level, description)));
645
+ }
646
+ // -------------------------------------------------------------------------
647
+ // Timeouts + lifecycle.
648
+ // -------------------------------------------------------------------------
649
+ async _withTimeout(ms, run) {
650
+ let timer;
651
+ const timeout = new Promise((_, reject) => {
652
+ timer = setTimeout(() => {
653
+ reject(new TlsHandshakeError("finished", {
654
+ cause: new Error(`handshake timed out after ${ms}ms`),
655
+ }));
656
+ }, ms);
657
+ });
658
+ try {
659
+ await Promise.race([run(), timeout]);
660
+ }
661
+ finally {
662
+ if (timer !== undefined) {
663
+ clearTimeout(timer);
664
+ }
665
+ }
87
666
  }
88
667
  _ensureOpen() {
89
668
  if (this.state.state !== "open") {
@@ -92,11 +671,13 @@ export class TlsConnectionImpl {
92
671
  });
93
672
  }
94
673
  }
95
- }
96
- /** Generate key shares for the requested groups (delegates to @browsercore/crypto). */
97
- export async function generateKeyShares(groups) {
98
- // PLAN: for each group call @browsercore/crypto generateKeyPair(group).
99
- void groups;
100
- throw new Error("not implemented — see PLAN.md");
674
+ _transition(next) {
675
+ this.state = next;
676
+ }
677
+ _emitError(error) {
678
+ for (const listener of this._errorListeners) {
679
+ listener(error);
680
+ }
681
+ }
101
682
  }
102
683
  //# sourceMappingURL=tls.js.map