@browsercore/tls 0.1.3 → 0.1.9

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 (104) hide show
  1. package/README.md +104 -4
  2. package/dist/certificates/cert-extensions.d.ts +46 -0
  3. package/dist/certificates/cert-extensions.d.ts.map +1 -0
  4. package/dist/certificates/cert-extensions.js +203 -0
  5. package/dist/certificates/cert-extensions.js.map +1 -0
  6. package/dist/certificates/certificates.d.ts +11 -9
  7. package/dist/certificates/certificates.d.ts.map +1 -1
  8. package/dist/certificates/certificates.js +75 -503
  9. package/dist/certificates/certificates.js.map +1 -1
  10. package/dist/certificates/der.d.ts +43 -0
  11. package/dist/certificates/der.d.ts.map +1 -0
  12. package/dist/certificates/der.js +204 -0
  13. package/dist/certificates/der.js.map +1 -0
  14. package/dist/certificates/hostname.d.ts +21 -0
  15. package/dist/certificates/hostname.d.ts.map +1 -0
  16. package/dist/certificates/hostname.js +46 -0
  17. package/dist/certificates/hostname.js.map +1 -0
  18. package/dist/certificates/pem.d.ts +11 -0
  19. package/dist/certificates/pem.d.ts.map +1 -0
  20. package/dist/certificates/pem.js +69 -0
  21. package/dist/certificates/pem.js.map +1 -0
  22. package/dist/connection/handshake-driver.d.ts +59 -0
  23. package/dist/connection/handshake-driver.d.ts.map +1 -0
  24. package/dist/connection/handshake-driver.js +137 -0
  25. package/dist/connection/handshake-driver.js.map +1 -0
  26. package/dist/connection/handshake-messages.d.ts +45 -0
  27. package/dist/connection/handshake-messages.d.ts.map +1 -0
  28. package/dist/connection/handshake-messages.js +170 -0
  29. package/dist/connection/handshake-messages.js.map +1 -0
  30. package/dist/connection/index.d.ts +19 -0
  31. package/dist/connection/index.d.ts.map +1 -0
  32. package/dist/connection/index.js +19 -0
  33. package/dist/connection/index.js.map +1 -0
  34. package/dist/connection/key-exchange.d.ts +24 -0
  35. package/dist/connection/key-exchange.d.ts.map +1 -0
  36. package/dist/connection/key-exchange.js +104 -0
  37. package/dist/connection/key-exchange.js.map +1 -0
  38. package/dist/connection/lifecycle.d.ts +38 -0
  39. package/dist/connection/lifecycle.d.ts.map +1 -0
  40. package/dist/connection/lifecycle.js +101 -0
  41. package/dist/connection/lifecycle.js.map +1 -0
  42. package/dist/connection/record-layer.d.ts +65 -0
  43. package/dist/connection/record-layer.d.ts.map +1 -0
  44. package/dist/connection/record-layer.js +140 -0
  45. package/dist/connection/record-layer.js.map +1 -0
  46. package/dist/crypto/keySchedule.d.ts +18 -3
  47. package/dist/crypto/keySchedule.d.ts.map +1 -1
  48. package/dist/crypto/keySchedule.js +82 -11
  49. package/dist/crypto/keySchedule.js.map +1 -1
  50. package/dist/errors.d.ts +43 -0
  51. package/dist/errors.d.ts.map +1 -1
  52. package/dist/errors.js +60 -2
  53. package/dist/errors.js.map +1 -1
  54. package/dist/extensions/extensions.d.ts +26 -25
  55. package/dist/extensions/extensions.d.ts.map +1 -1
  56. package/dist/extensions/extensions.js +92 -49
  57. package/dist/extensions/extensions.js.map +1 -1
  58. package/dist/handshake/client-hello.d.ts +30 -0
  59. package/dist/handshake/client-hello.d.ts.map +1 -0
  60. package/dist/handshake/client-hello.js +464 -0
  61. package/dist/handshake/client-hello.js.map +1 -0
  62. package/dist/handshake/grease.d.ts +70 -0
  63. package/dist/handshake/grease.d.ts.map +1 -0
  64. package/dist/handshake/grease.js +293 -0
  65. package/dist/handshake/grease.js.map +1 -0
  66. package/dist/handshake/handshake-types.d.ts +84 -0
  67. package/dist/handshake/handshake-types.d.ts.map +1 -0
  68. package/dist/handshake/handshake-types.js +31 -0
  69. package/dist/handshake/handshake-types.js.map +1 -0
  70. package/dist/handshake/handshake.d.ts +19 -118
  71. package/dist/handshake/handshake.d.ts.map +1 -1
  72. package/dist/handshake/handshake.js +19 -412
  73. package/dist/handshake/handshake.js.map +1 -1
  74. package/dist/handshake/server-hello.d.ts +33 -0
  75. package/dist/handshake/server-hello.d.ts.map +1 -0
  76. package/dist/handshake/server-hello.js +134 -0
  77. package/dist/handshake/server-hello.js.map +1 -0
  78. package/dist/handshake/state-machine.d.ts +34 -0
  79. package/dist/handshake/state-machine.d.ts.map +1 -0
  80. package/dist/handshake/state-machine.js +105 -0
  81. package/dist/handshake/state-machine.js.map +1 -0
  82. package/dist/index.d.ts +1 -1
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +1 -1
  85. package/dist/index.js.map +1 -1
  86. package/dist/profiles/profiles.d.ts +12 -2
  87. package/dist/profiles/profiles.d.ts.map +1 -1
  88. package/dist/profiles/profiles.js +22 -7
  89. package/dist/profiles/profiles.js.map +1 -1
  90. package/dist/record/record.d.ts +18 -1
  91. package/dist/record/record.d.ts.map +1 -1
  92. package/dist/record/record.js +79 -11
  93. package/dist/record/record.js.map +1 -1
  94. package/dist/tls.d.ts +62 -101
  95. package/dist/tls.d.ts.map +1 -1
  96. package/dist/tls.js +166 -566
  97. package/dist/tls.js.map +1 -1
  98. package/dist/types.d.ts +40 -6
  99. package/dist/types.d.ts.map +1 -1
  100. package/dist/utils.d.ts +7 -0
  101. package/dist/utils.d.ts.map +1 -1
  102. package/dist/utils.js +23 -0
  103. package/dist/utils.js.map +1 -1
  104. package/package.json +53 -48
package/dist/tls.js CHANGED
@@ -9,93 +9,32 @@
9
9
  * TLS 1.2 fallback is intentionally NOT implemented: this client speaks TLS 1.3
10
10
  * only. Requesting a TLS 1.2 (only) handshake is rejected up front with a typed
11
11
  * error rather than failing silently mid-flight.
12
+ *
13
+ * The connection class is intentionally a thin coordinator: it owns the mutable
14
+ * connection state (read buffer, sequence counters, traffic secrets, transcript)
15
+ * and the public API, while every pure computation — record framing, key exchange,
16
+ * transcript hashing, alert translation, and the handshake choreography itself —
17
+ * lives in a focused module under `./connection/`. Those modules thread state
18
+ * through explicit parameters and the {@link HandshakeContext} this class
19
+ * implements, which keeps the byte-level logic unit-testable in isolation and
20
+ * this file focused on the public surface.
12
21
  */
13
- import { crypto, SHA_384 } from "@browsercore/crypto";
14
- import { TLS_1_3 } from "./types.js";
15
- import { TlsAlertError, TlsHandshakeError, ensureTlsError } from "./errors.js";
22
+ import { crypto } from "@browsercore/crypto";
23
+ import { TLS_1_3, } from "./types.js";
24
+ import { TlsHandshakeError, ensureTlsError } from "./errors.js";
16
25
  import { createId } from "./utils.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";
26
+ import { ContentType } from "./record/record.js";
27
+ import { ensureOpen, handleAlert as handleAlertRecord, handlePostHandshakeRecord as dispatchPostHandshakeRecord, emitError, notifyClose, withTimeout, readEncryptedRecord, writeEncryptedRecord, runHandshake, } from "./connection/index.js";
22
28
  /** Default handshake timeout in milliseconds. */
23
29
  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
- }
80
30
  /**
81
31
  * Establish a TLS 1.3 connection over the given transport.
82
32
  *
83
33
  * Performs the full TLS 1.3 handshake, derives traffic secrets, and returns a
84
34
  * {@link TlsConnection} that transparently encrypts/decrypts application data.
85
- *
86
- * @example
87
- * ```ts
88
- * const transport = await connect({ host: "example.com", port: 443 });
89
- * const tls = await connectTls({
90
- * transport,
91
- * serverName: "example.com",
92
- * profile: resolveProfile("modern-tls13", "example.com"),
93
- * alpnProtocols: ["h2", "http/1.1"],
94
- * });
95
- * await tls.write(new TextEncoder().encode("GET / HTTP/1.1\r\n"));
96
- * const chunk = await tls.read();
97
- * await tls.close();
98
- * ```
35
+ * Callers pass an already-connected {@link Transport}, the server name (for SNI
36
+ * + certificate validation), and a resolved profile (cipher suites, key-share
37
+ * groups, signature algorithms).
99
38
  */
100
39
  export async function connectTls(options) {
101
40
  const conn = new TlsConnectionImpl(options);
@@ -103,23 +42,45 @@ export async function connectTls(options) {
103
42
  return conn;
104
43
  }
105
44
  /** 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
- });
45
+ export function generateKeyShares(groups) {
46
+ // Wrapped in .then() so a synchronous throw (unsupported group) becomes a
47
+ // rejected promise — callers await this and tests assert with .rejects.
48
+ return Promise.resolve().then(() => {
49
+ const shares = [];
50
+ for (const group of groups) {
51
+ switch (group) {
52
+ case "x25519": {
53
+ const kp = crypto.x25519GenerateKeyPair();
54
+ shares.push({ algorithm: "x25519", privateKey: kp.secretKey, publicKey: kp.publicKey });
55
+ break;
56
+ }
57
+ case "secp256r1":
58
+ case "secp384r1": {
59
+ const kp = crypto.ecdhGenerateKeyPair(group);
60
+ shares.push({ algorithm: group, privateKey: kp.secretKey, publicKey: kp.publicKey });
61
+ break;
62
+ }
63
+ default:
64
+ // @browsercore/crypto only exposes X25519 and the two NIST ECDH
65
+ // curves today. Any other (EC)DHE group would need a backend we
66
+ // do not have — fail fast and typed rather than producing a
67
+ // bogus key.
68
+ throw new TlsHandshakeError("client_hello", {
69
+ cause: new Error(`key share group "${group}" is not supported by the crypto backend`),
70
+ });
71
+ }
116
72
  }
117
- const kp = crypto.x25519GenerateKeyPair();
118
- shares.push({ algorithm: "x25519", privateKey: kp.secretKey, publicKey: kp.publicKey });
119
- }
120
- return shares;
73
+ return shares;
74
+ });
121
75
  }
122
- /** Concrete TLS 1.3 connection implementation. */
76
+ /**
77
+ * Concrete TLS 1.3 connection implementation.
78
+ *
79
+ * Implements {@link HandshakeContext} so the handshake driver in
80
+ * `./connection/handshake-driver.ts` can read and mutate its fields directly
81
+ * (read buffer, transcript, traffic secrets, sequence counters) without the
82
+ * choreography of the handshake living inline in this class.
83
+ */
123
84
  export class TlsConnectionImpl {
124
85
  id = createId("tls");
125
86
  state = { state: "connecting" };
@@ -132,42 +93,44 @@ export class TlsConnectionImpl {
132
93
  alpnProtocol;
133
94
  /** The peer's leaf certificate, once the handshake has validated it. */
134
95
  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;
96
+ // `transport` is public-read because the handshake driver (HandshakeContext)
97
+ // needs it; it is NOT on the TlsConnection interface, so it does not leak into
98
+ // the package's public API surface.
99
+ transport;
100
+ profile;
101
+ serverName;
102
+ trustAnchors = [];
103
+ // --- HandshakeContext: mutable handshake state (read/written by the driver) ---
104
+ readBuffer = new Uint8Array(0);
105
+ transcript = [];
106
+ aead;
107
+ hash;
108
+ serverHello;
109
+ clientHsTraffic;
110
+ serverHsTraffic;
111
+ clientHsTrafficSecret;
112
+ serverHsTrafficSecret;
113
+ masterSecret;
114
+ clientHsSeq = 0;
115
+ serverHsSeq = 0;
116
+ applicationSecrets;
117
+ clientAppSeq = 0;
118
+ serverAppSeq = 0;
156
119
  /** Decrypted application payloads awaiting consumption by read(). */
157
- _appReadQueue = [];
120
+ appReadQueue = [];
158
121
  /** Lifecycle observers. */
159
- _closeListeners = [];
160
- _errorListeners = [];
122
+ closeListeners = [];
123
+ errorListeners = [];
161
124
  // `options` is optional so a connection can be constructed in isolation (e.g.
162
125
  // to assert on its default public fields) without a live transport. The real
163
126
  // entry point, connectTls, always supplies a full options object.
164
127
  constructor(options) {
165
128
  if (options !== undefined) {
166
- this._transport = options.transport;
167
- this._serverName = options.serverName;
168
- this._trustAnchors = options.trustAnchors ?? [];
129
+ this.transport = options.transport;
130
+ this.serverName = options.serverName;
131
+ this.trustAnchors = options.trustAnchors ?? [];
169
132
  // An explicit alpnProtocols option overrides whatever the profile says.
170
- this._profile =
133
+ this.profile =
171
134
  options.alpnProtocols !== undefined && options.alpnProtocols.length > 0
172
135
  ? { ...options.profile, alpnProtocols: options.alpnProtocols }
173
136
  : options.profile;
@@ -184,31 +147,57 @@ export class TlsConnectionImpl {
184
147
  if (this.state.state === "open") {
185
148
  return;
186
149
  }
187
- await this._withTimeout(timeoutMs, () => this._performHandshake());
150
+ await withTimeout(timeoutMs, () => this.performHandshake());
188
151
  }
152
+ /**
153
+ * Read the next chunk of decrypted application data. Blocks until a record
154
+ * arrives; non-application records (alerts, post-handshake messages) are
155
+ * handled inline.
156
+ */
189
157
  async read() {
190
- this._ensureOpen();
191
- if (this._appReadQueue.length > 0) {
192
- return { payload: this._appReadQueue.shift() };
158
+ ensureOpen(this.state);
159
+ if (this.appReadQueue.length > 0) {
160
+ const payload = this.appReadQueue.shift();
161
+ if (payload === undefined) {
162
+ // Length was just checked; this is unreachable but required so the
163
+ // non-null assertion can be dropped under noUncheckedIndexedAccess.
164
+ throw new TlsHandshakeError("finished", {
165
+ cause: new Error("application data queue emptied between check and shift"),
166
+ });
167
+ }
168
+ return { payload };
193
169
  }
194
170
  // Read encrypted records until an application-data payload arrives.
195
171
  for (;;) {
196
- const { innerType, content } = await this._readEncryptedRecord(this._applicationSecrets.server, this._serverAppSeq);
197
- this._serverAppSeq++;
172
+ // Sequential by necessity: each iteration mutates readBuffer and
173
+ // serverAppSeq and may early-return on APPLICATION_DATA; records must
174
+ // be processed in order, so the read cannot be parallelized.
175
+ // eslint-disable-next-line no-await-in-loop
176
+ const { innerType, content, readBuffer } = await readEncryptedRecord(this.readBuffer, this.transport, this.aead, this.applicationSecrets.server, this.serverAppSeq);
177
+ this.readBuffer = readBuffer;
178
+ this.serverAppSeq++;
198
179
  if (innerType === ContentType.APPLICATION_DATA) {
199
180
  return { payload: content };
200
181
  }
201
- this._handlePostHandshakeRecord(innerType, content);
182
+ this.handlePostHandshakeRecord(innerType, content);
202
183
  }
203
184
  }
204
- async write(data) {
205
- this._ensureOpen();
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++;
185
+ write(data) {
186
+ // Not async: there are no awaits. Synchronous throws (e.g. ensureOpen) are
187
+ // caught and returned as a rejected promise so callers can await uniformly.
188
+ try {
189
+ ensureOpen(this.state);
190
+ const traffic = this.applicationSecrets.client;
191
+ // Split into record-sized plaintext fragments (TLS records cap at 2^14 bytes).
192
+ for (let offset = 0; offset < data.length; offset += 16_384) {
193
+ const fragment = data.subarray(offset, Math.min(offset + 16_384, data.length));
194
+ writeEncryptedRecord(this.transport, this.aead, traffic, ContentType.APPLICATION_DATA, fragment, this.clientAppSeq);
195
+ this.clientAppSeq++;
196
+ }
197
+ return Promise.resolve();
198
+ }
199
+ catch (cause) {
200
+ return Promise.reject(ensureTlsError(cause));
212
201
  }
213
202
  }
214
203
  async close() {
@@ -221,463 +210,74 @@ export class TlsConnectionImpl {
221
210
  if (this.state.state === "open") {
222
211
  try {
223
212
  const alert = new Uint8Array([0x01, 0x00]); // warning / close_notify
224
- this._writeEncryptedRecord(this._applicationSecrets.client, ContentType.ALERT, alert, this._clientAppSeq);
213
+ writeEncryptedRecord(this.transport, this.aead, this.applicationSecrets.client, ContentType.ALERT, alert, this.clientAppSeq);
225
214
  }
226
215
  catch {
227
216
  // ignore — we are closing anyway
228
217
  }
229
218
  }
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
- }
219
+ await this.transport.close();
220
+ this.transition({ state: "closed", reason: { kind: "close_notify" } });
221
+ notifyClose(this.closeListeners, { kind: "close_notify" });
235
222
  }
236
223
  on(event, listener) {
224
+ // A listener accepting the union is assignable to each slot by parameter
225
+ // contravariance — no cast needed (the one that lived here was redundant).
237
226
  if (event === "close") {
238
- this._closeListeners.push(listener);
227
+ this.closeListeners.push(listener);
239
228
  }
240
229
  else {
241
- this._errorListeners.push(listener);
230
+ this.errorListeners.push(listener);
242
231
  }
243
232
  return this;
244
233
  }
245
234
  // -------------------------------------------------------------------------
246
- // Handshake state machine (RFC 8446).
235
+ // Handshake + post-handshake record handling.
247
236
  // -------------------------------------------------------------------------
248
- async _performHandshake() {
237
+ /**
238
+ * Run the handshake via the driver module. The driver mutates this object's
239
+ * HandshakeContext fields and returns the derived application secrets, which
240
+ * we store for read()/write(). `now` is read here (in the orchestrator) so
241
+ * certificate validation stays pure and testable.
242
+ */
243
+ async performHandshake() {
249
244
  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({
245
+ const now = Math.floor(Date.now() / 1000);
246
+ this.applicationSecrets = await runHandshake(this, this.profile, this.serverName, this.trustAnchors, generateKeyShares, now);
247
+ // Expose the negotiated parameters the driver wrote onto the context.
248
+ this.protocolVersion = this.serverHello.selectedVersion;
249
+ // Transition to the open state. Under exactOptionalPropertyTypes,
250
+ // `alpnProtocol?` must be omitted (not `undefined`) when unset.
251
+ this.transition({
309
252
  state: "open",
310
253
  sessionId: this.id,
311
254
  protocolVersion: this.protocolVersion,
312
255
  cipherSuite: this.cipherSuite,
313
- ...(this.alpnProtocol !== undefined ? { alpnProtocol: this.alpnProtocol } : {}),
256
+ ...(this.alpnProtocol === undefined ? {} : { alpnProtocol: this.alpnProtocol }),
314
257
  });
315
258
  }
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 };
366
- }
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
259
  /** 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);
260
+ handlePostHandshakeRecord(innerType, content) {
261
+ if (innerType === ContentType.ALERT) {
262
+ // Alerts need connection-specific handling (state transition + error
263
+ // emission) that the shared dispatcher does not own.
264
+ const { close, error } = handleAlertRecord(content);
265
+ if (close) {
266
+ this.transition({ state: "closed", reason: { kind: "close_notify" } });
267
+ return;
664
268
  }
269
+ if (error !== undefined) {
270
+ emitError(this.errorListeners, ensureTlsError(error));
271
+ }
272
+ return;
665
273
  }
274
+ // Non-alert types (HANDSHAKE, CHANGE_CIPHER_SPEC, APPLICATION_DATA):
275
+ // delegate to the shared, tested dispatcher. It ignores post-handshake
276
+ // handshake messages and throws on unexpected types.
277
+ void dispatchPostHandshakeRecord(innerType, content);
666
278
  }
667
- _ensureOpen() {
668
- if (this.state.state !== "open") {
669
- throw new TlsHandshakeError("finished", {
670
- cause: new Error(`connection not open (state: ${this.state.state})`),
671
- });
672
- }
673
- }
674
- _transition(next) {
279
+ transition(next) {
675
280
  this.state = next;
676
281
  }
677
- _emitError(error) {
678
- for (const listener of this._errorListeners) {
679
- listener(error);
680
- }
681
- }
682
282
  }
683
283
  //# sourceMappingURL=tls.js.map