@browsercore/tls 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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
@@ -0,0 +1,137 @@
1
+ /**
2
+ * TLS 1.3 handshake driver (RFC 8446).
3
+ *
4
+ * The connection class owns its mutable state (read buffer, transcript, traffic
5
+ * secrets, sequence counters); this module owns the *sequence* of the handshake
6
+ * — what to send, what to read next, when to derive which secret, when to verify
7
+ * the Finished. It operates through a {@link HandshakeContext} the connection
8
+ * implements, so it can read and write that state without the connection class
9
+ * having to carry the handshake choreography inline.
10
+ *
11
+ * Splitting the driver out of `tls.ts` keeps the public class focused on its API
12
+ * surface (read/write/close/on) and the lifecycle of its fields, while every
13
+ * byte-level handshake step lives here and stays independently readable.
14
+ */
15
+ import { TlsHandshakeError } from "../errors.js";
16
+ import { ContentType, cipherSuiteToAead } from "../record/record.js";
17
+ import { advanceHandshake, buildClientHello, parseServerHello, recordServerHello, HandshakeType, } from "../handshake/handshake.js";
18
+ import { deriveApplicationSecrets, deriveHandshakeTrafficSecrets, deriveTrafficSecrets, hashFor, } from "../crypto/keySchedule.js";
19
+ // Import from the individual submodules (not the ./index.js barrel) to avoid a
20
+ // dependency cycle: index.ts re-exports this module, so reaching back through
21
+ // it would close the loop. The submodules are the real owners of these helpers.
22
+ import { computeSharedSecret, transcriptHash, verifyServerFinished } from "./key-exchange.js";
23
+ import { buildClientFinishedMessage, parseAlpnFromEncryptedExtensions, readEncryptedHandshakeMessage, validateCertificateChain, } from "./handshake-messages.js";
24
+ import { readHeaderBytes, readRawRecord, writeEncryptedRecord, writeRecord, } from "./record-layer.js";
25
+ /** Constant: the only key-share group the crypto backend can generate. */
26
+ const SUPPORTED_GROUP = "x25519";
27
+ /** Apply the result of {@link parseServerHello} to the context's fields. */
28
+ function applyNegotiation(ctx) {
29
+ ctx.aead = cipherSuiteToAead(ctx.cipherSuite);
30
+ ctx.hash = hashFor(ctx.cipherSuite);
31
+ }
32
+ /**
33
+ * Drive the TLS 1.3 handshake to completion against `ctx`.
34
+ *
35
+ * `now` (epoch seconds) is injected by the caller — the orchestrator reads the
36
+ * clock once so this driver (and the certificate validation it invokes) stays
37
+ * pure and testable.
38
+ */
39
+ export async function runHandshake(ctx, profile, serverName, trustAnchors, generateKeyShares, now) {
40
+ // TLS 1.3 only: reject a profile that cannot negotiate TLS 1.3.
41
+ if (!profile.supportedVersions.some((v) => v.name === "TLS 1.3")) {
42
+ throw new TlsHandshakeError("client_hello", {
43
+ cause: new Error("TLS 1.2-only handshakes are not supported by this client"),
44
+ });
45
+ }
46
+ // 1. Generate key shares for the groups the crypto backend supports.
47
+ const desired = profile.keyShareGroups.filter((g) => g === SUPPORTED_GROUP);
48
+ if (desired.length === 0) {
49
+ throw new TlsHandshakeError("client_hello", {
50
+ cause: new Error("no supported key share groups in the selected profile"),
51
+ });
52
+ }
53
+ const keyPairs = await generateKeyShares(desired);
54
+ // 2. Build and send the ClientHello as a plaintext handshake record.
55
+ const clientHello = buildClientHello(profile, keyPairs);
56
+ ctx.transcript.push(clientHello);
57
+ await writeRecord(ctx.transport, ContentType.HANDSHAKE, clientHello);
58
+ // 3. Read the ServerHello (still plaintext) and validate the negotiation.
59
+ const shHeader = await readHeaderBytes(ctx.readBuffer, ctx.transport);
60
+ ctx.readBuffer = shHeader.readBuffer;
61
+ const shRecord = await readRawRecord(ctx.readBuffer, ctx.transport, shHeader);
62
+ ctx.readBuffer = shRecord.readBuffer;
63
+ if (shRecord.type !== ContentType.HANDSHAKE) {
64
+ throw new TlsHandshakeError("server_hello", {
65
+ cause: new Error(`expected handshake record, got content type ${shRecord.type}`),
66
+ });
67
+ }
68
+ ctx.transcript.push(shRecord.fragment);
69
+ const serverHello = parseServerHello(shRecord.fragment.subarray(4), {
70
+ cipherSuites: profile.cipherSuites,
71
+ supportedVersions: profile.supportedVersions,
72
+ });
73
+ ctx.serverHello = serverHello;
74
+ ctx.cipherSuite = serverHello.cipherSuite;
75
+ applyNegotiation(ctx);
76
+ // 4. (EC)DHE key exchange.
77
+ const sharedSecret = computeSharedSecret(serverHello, keyPairs);
78
+ // 5. Derive handshake traffic secrets from the ClientHello..ServerHello transcript.
79
+ const helloTranscript = transcriptHash(ctx.transcript, ctx.hash);
80
+ const { masterSecret, clientTrafficSecret, serverTrafficSecret } = deriveHandshakeTrafficSecrets(sharedSecret, helloTranscript, ctx.cipherSuite);
81
+ ctx.masterSecret = masterSecret;
82
+ ctx.clientHsTrafficSecret = clientTrafficSecret;
83
+ ctx.serverHsTrafficSecret = serverTrafficSecret;
84
+ ctx.clientHsTraffic = deriveTrafficSecrets(clientTrafficSecret, ctx.cipherSuite, ctx.hash);
85
+ ctx.serverHsTraffic = deriveTrafficSecrets(serverTrafficSecret, ctx.cipherSuite, ctx.hash);
86
+ // 6. Consume the server's encrypted flight.
87
+ await consumeServerFlight(ctx, serverName, trustAnchors, now);
88
+ // 7. Derive application traffic secrets from the full transcript.
89
+ const handshakeTranscript = transcriptHash(ctx.transcript, ctx.hash);
90
+ const applicationSecrets = deriveApplicationSecrets(ctx.masterSecret, handshakeTranscript, ctx.cipherSuite);
91
+ // 8. Send the client Finished under the client handshake traffic key.
92
+ const finishedMessage = buildClientFinishedMessage(ctx.hash, ctx.clientHsTrafficSecret, ctx.transcript);
93
+ writeEncryptedRecord(ctx.transport, ctx.aead, ctx.clientHsTraffic, ContentType.HANDSHAKE, finishedMessage, ctx.clientHsSeq);
94
+ ctx.clientHsSeq++;
95
+ return applicationSecrets;
96
+ }
97
+ /**
98
+ * Read the server's encrypted second flight message-by-message, advancing the
99
+ * handshake state machine and updating the transcript. Server Finished is
100
+ * verified against the transcript as it stood *before* the Finished message.
101
+ */
102
+ async function consumeServerFlight(ctx, serverName, trustAnchors, now) {
103
+ let phase = recordServerHello({ phase: "client_hello_sent" }, ctx.serverHello);
104
+ // EncryptedExtensions.
105
+ let message = await readEncryptedHandshakeMessage(ctx.readBuffer, ctx.transport, ctx.aead, ctx.serverHsTraffic, ctx.serverHsSeq);
106
+ ctx.readBuffer = message.readBuffer;
107
+ ctx.serverHsSeq++;
108
+ phase = advanceHandshake(phase, HandshakeType.ENCRYPTED_EXTENSIONS);
109
+ ctx.transcript.push(message.whole);
110
+ const alpn = parseAlpnFromEncryptedExtensions(message.body);
111
+ if (alpn !== undefined) {
112
+ ctx.alpnProtocol = alpn;
113
+ }
114
+ // Certificate.
115
+ message = await readEncryptedHandshakeMessage(ctx.readBuffer, ctx.transport, ctx.aead, ctx.serverHsTraffic, ctx.serverHsSeq);
116
+ ctx.readBuffer = message.readBuffer;
117
+ ctx.serverHsSeq++;
118
+ phase = advanceHandshake(phase, HandshakeType.CERTIFICATE);
119
+ ctx.transcript.push(message.whole);
120
+ const chain = await validateCertificateChain(message.body, serverName, trustAnchors, now);
121
+ ctx.peerCertificate = chain.leaf;
122
+ // CertificateVerify.
123
+ message = await readEncryptedHandshakeMessage(ctx.readBuffer, ctx.transport, ctx.aead, ctx.serverHsTraffic, ctx.serverHsSeq);
124
+ ctx.readBuffer = message.readBuffer;
125
+ ctx.serverHsSeq++;
126
+ phase = advanceHandshake(phase, HandshakeType.CERTIFICATE_VERIFY);
127
+ ctx.transcript.push(message.whole);
128
+ // Finished — verify against the transcript *before* appending the Finished.
129
+ const finishedTranscript = transcriptHash(ctx.transcript, ctx.hash);
130
+ message = await readEncryptedHandshakeMessage(ctx.readBuffer, ctx.transport, ctx.aead, ctx.serverHsTraffic, ctx.serverHsSeq);
131
+ ctx.readBuffer = message.readBuffer;
132
+ ctx.serverHsSeq++;
133
+ verifyServerFinished(message.body, finishedTranscript, ctx.hash, ctx.serverHsTrafficSecret);
134
+ advanceHandshake(phase, HandshakeType.FINISHED);
135
+ ctx.transcript.push(message.whole);
136
+ }
137
+ //# sourceMappingURL=handshake-driver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handshake-driver.js","sourceRoot":"","sources":["../../src/connection/handshake-driver.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACrE,OAAO,EACH,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,iBAAiB,EACjB,aAAa,GAGhB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACH,wBAAwB,EACxB,6BAA6B,EAC7B,oBAAoB,EACpB,OAAO,GACV,MAAM,0BAA0B,CAAC;AAalC,+EAA+E;AAC/E,8EAA8E;AAC9E,gFAAgF;AAChF,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC9F,OAAO,EACH,0BAA0B,EAC1B,gCAAgC,EAChC,6BAA6B,EAC7B,wBAAwB,GAC3B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACH,eAAe,EACf,aAAa,EACb,oBAAoB,EACpB,WAAW,GACd,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 * CertificateVerify, Finished — and produces the client's Finished in reply. Each
6
+ * function is a pure transformation over its inputs (the message bytes plus the
7
+ * slice of connection state it needs); the connection class owns the state and
8
+ * threads it through. This keeps the message-layout logic isolated from the
9
+ * record layer and the handshake state machine.
10
+ */
11
+ import { type HashId } from "@browsercore/crypto";
12
+ import type { Transport } from "@browsercore/transport";
13
+ import type { TrafficSecrets } from "../types.js";
14
+ import { type encryptRecord } from "../record/record.js";
15
+ import { type CertificateChain } from "../certificates/certificates.js";
16
+ /** Extract the negotiated ALPN protocol from EncryptedExtensions, if any. */
17
+ export declare function parseAlpnFromEncryptedExtensions(body: Uint8Array): string | undefined;
18
+ /**
19
+ * Parse a Certificate handshake message (RFC 8446 §4.4.2) into a chain. The body
20
+ * is: certificate_request_context (length-prefixed, len 1) then a length-prefixed
21
+ * list of CertificateEntry { cert_data, extensions }.
22
+ */
23
+ export declare function parseCertificateMessage(body: Uint8Array): CertificateChain;
24
+ /**
25
+ * Validate the Certificate message: hostname check against the leaf, then full
26
+ * chain verification when trust anchors are available. Returns the parsed chain.
27
+ *
28
+ * `now` (epoch seconds) is injected rather than read from the clock, so this
29
+ * helper is pure and testable — the connection supplies the current time, never
30
+ * the validation logic itself.
31
+ */
32
+ export declare function validateCertificateChain(body: Uint8Array, serverName: string, trustAnchors: readonly Uint8Array[], now: number): Promise<CertificateChain>;
33
+ /** Build the client Finished message bytes under the client handshake traffic key. */
34
+ export declare function buildClientFinishedMessage(hash: HashId, clientHsTrafficSecret: Uint8Array, transcript: readonly Uint8Array[]): Uint8Array;
35
+ /**
36
+ * Read one encrypted handshake message, decrypting and stripping the inner type.
37
+ * Returns the whole handshake message (header + body), the body alone, and the
38
+ * buffer left after consuming the record.
39
+ */
40
+ export declare function readEncryptedHandshakeMessage(readBuffer: Uint8Array, transport: Transport, aead: Parameters<typeof encryptRecord>[4], traffic: TrafficSecrets, seq: number): Promise<{
41
+ whole: Uint8Array;
42
+ body: Uint8Array;
43
+ readBuffer: Uint8Array;
44
+ }>;
45
+ //# sourceMappingURL=handshake-messages.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handshake-messages.d.ts","sourceRoot":"","sources":["../../src/connection/handshake-messages.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAU,KAAK,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAIlD,OAAO,EAA8B,KAAK,aAAa,EAAmB,MAAM,qBAAqB,CAAC;AACtG,OAAO,EAAqE,KAAK,gBAAgB,EAAoB,MAAM,iCAAiC,CAAC;AAI7J,6EAA6E;AAC7E,wBAAgB,gCAAgC,CAAC,IAAI,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAerF;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,UAAU,GAAG,gBAAgB,CA6C1E;AAED;;;;;;;GAOG;AACH,wBAAsB,wBAAwB,CAC1C,IAAI,EAAE,UAAU,EAChB,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,SAAS,UAAU,EAAE,EACnC,GAAG,EAAE,MAAM,GACZ,OAAO,CAAC,gBAAgB,CAAC,CAoB3B;AAED,sFAAsF;AACtF,wBAAgB,0BAA0B,CACtC,IAAI,EAAE,MAAM,EACZ,qBAAqB,EAAE,UAAU,EACjC,UAAU,EAAE,SAAS,UAAU,EAAE,GAClC,UAAU,CAWZ;AAED;;;;GAIG;AACH,wBAAsB,6BAA6B,CAC/C,UAAU,EAAE,UAAU,EACtB,SAAS,EAAE,SAAS,EACpB,IAAI,EAAE,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC,CAAC,CAAC,EACzC,OAAO,EAAE,cAAc,EACvB,GAAG,EAAE,MAAM,GACZ,OAAO,CAAC;IAAE,KAAK,EAAE,UAAU,CAAC;IAAC,IAAI,EAAE,UAAU,CAAC;IAAC,UAAU,EAAE,UAAU,CAAA;CAAE,CAAC,CAmC1E"}
@@ -0,0 +1,170 @@
1
+ /**
2
+ * TLS 1.3 server-flight message handling.
3
+ *
4
+ * Decodes the server's encrypted second flight — EncryptedExtensions, Certificate,
5
+ * CertificateVerify, Finished — and produces the client's Finished in reply. Each
6
+ * function is a pure transformation over its inputs (the message bytes plus the
7
+ * slice of connection state it needs); the connection class owns the state and
8
+ * threads it through. This keeps the message-layout logic isolated from the
9
+ * record layer and the handshake state machine.
10
+ */
11
+ import { crypto } from "@browsercore/crypto";
12
+ import { TlsHandshakeError } from "../errors.js";
13
+ import { ExtensionType, findExtension, parseExtensions } from "../extensions/extensions.js";
14
+ import { hkdfExpandLabel, hashLengthFor } from "../crypto/keySchedule.js";
15
+ import { ContentType, decryptRecord, readContentType } from "../record/record.js";
16
+ import { parseCertificate, validateHostname, verifyChain } from "../certificates/certificates.js";
17
+ import { transcriptHash } from "./key-exchange.js";
18
+ import { readHeaderBytes as readHeaderBytesFromRecord, readRawRecord as readRawRecordFromRecord, xorNonce } from "./record-layer.js";
19
+ /** Extract the negotiated ALPN protocol from EncryptedExtensions, if any. */
20
+ export function parseAlpnFromEncryptedExtensions(body) {
21
+ const extensions = parseExtensions(body);
22
+ const alpn = findExtension(extensions, ExtensionType.APPLICATION_LAYER_PROTOCOL_NEGOTIATION);
23
+ if (alpn === undefined) {
24
+ return undefined;
25
+ }
26
+ // Server ALPN body: length-prefixed list with a single entry.
27
+ if (alpn.data.length < 3) {
28
+ return undefined;
29
+ }
30
+ const nameLen = alpn.data[2];
31
+ if (nameLen === undefined || 3 + nameLen > alpn.data.length) {
32
+ return undefined;
33
+ }
34
+ return new TextDecoder().decode(alpn.data.subarray(3, 3 + nameLen));
35
+ }
36
+ /**
37
+ * Parse a Certificate handshake message (RFC 8446 §4.4.2) into a chain. The body
38
+ * is: certificate_request_context (length-prefixed, len 1) then a length-prefixed
39
+ * list of CertificateEntry { cert_data, extensions }.
40
+ */
41
+ export function parseCertificateMessage(body) {
42
+ let o = 0;
43
+ const readByte = () => {
44
+ const byte = body[o];
45
+ if (byte === undefined) {
46
+ throw new TlsHandshakeError("certificate", {
47
+ cause: new Error(`certificate message byte truncated at offset ${o}`),
48
+ });
49
+ }
50
+ o++;
51
+ return byte;
52
+ };
53
+ const ctxLen = readByte();
54
+ o += ctxLen;
55
+ const listLen = (readByte() << 16) | (readByte() << 8) | readByte();
56
+ const listEnd = o + listLen;
57
+ if (listEnd > body.length) {
58
+ throw new TlsHandshakeError("certificate", {
59
+ cause: new Error("certificate_list length exceeds message body"),
60
+ });
61
+ }
62
+ const certs = [];
63
+ while (o < listEnd) {
64
+ const certLen = (readByte() << 16) | (readByte() << 8) | readByte();
65
+ const certDer = body.subarray(o, o + certLen);
66
+ o += certLen;
67
+ const extLen = (readByte() << 8) | readByte();
68
+ o += extLen;
69
+ certs.push(parseCertificate(certDer));
70
+ }
71
+ if (certs.length === 0) {
72
+ throw new TlsHandshakeError("certificate", {
73
+ cause: new Error("server sent an empty certificate_list"),
74
+ });
75
+ }
76
+ // certs.length >= 1 guarantees both indices are in bounds.
77
+ const leaf = certs[0];
78
+ const root = certs.at(-1);
79
+ if (leaf === undefined || root === undefined) {
80
+ throw new TlsHandshakeError("certificate", {
81
+ cause: new Error("certificate list missing leaf or root"),
82
+ });
83
+ }
84
+ const intermediates = certs.slice(1, certs.length - 1);
85
+ return { leaf, intermediates, root };
86
+ }
87
+ /**
88
+ * Validate the Certificate message: hostname check against the leaf, then full
89
+ * chain verification when trust anchors are available. Returns the parsed chain.
90
+ *
91
+ * `now` (epoch seconds) is injected rather than read from the clock, so this
92
+ * helper is pure and testable — the connection supplies the current time, never
93
+ * the validation logic itself.
94
+ */
95
+ export async function validateCertificateChain(body, serverName, trustAnchors, now) {
96
+ const chain = parseCertificateMessage(body);
97
+ if (!validateHostname(chain.leaf, serverName)) {
98
+ throw new TlsHandshakeError("certificate", {
99
+ cause: new Error(`hostname "${serverName}" does not match the leaf certificate`),
100
+ });
101
+ }
102
+ // Full chain verification requires trust anchors. Without them we still
103
+ // performed hostname validation above; chain verification is best-effort.
104
+ if (trustAnchors.length > 0) {
105
+ // Trust anchors arrive as raw DER root certificates; verifyChain wants
106
+ // parsed TrustAnchor records (SPKI + subject). A trust anchor is a
107
+ // self-signed root, so its issuer DN is also its subject.
108
+ const anchors = trustAnchors.map((der) => {
109
+ const root = parseCertificate(der);
110
+ return { subjectPublicKeyInfo: root.subjectPublicKeyInfo, subject: root.issuer };
111
+ });
112
+ await verifyChain(chain, anchors, serverName, now);
113
+ }
114
+ return chain;
115
+ }
116
+ /** Build the client Finished message bytes under the client handshake traffic key. */
117
+ export function buildClientFinishedMessage(hash, clientHsTrafficSecret, transcript) {
118
+ const hashLen = hashLengthFor(hash);
119
+ const finishedKey = hkdfExpandLabel(clientHsTrafficSecret, "finished", new Uint8Array(0), hashLen, hash);
120
+ const verifyData = crypto.hmac(hash, finishedKey, transcriptHash(transcript, hash));
121
+ const message = new Uint8Array(4 + verifyData.length);
122
+ message[0] = 20; // HandshakeType.FINISHED
123
+ message[1] = (verifyData.length >> 16) & 0xff;
124
+ message[2] = (verifyData.length >> 8) & 0xff;
125
+ message[3] = verifyData.length & 0xff;
126
+ message.set(verifyData, 4);
127
+ return message;
128
+ }
129
+ /**
130
+ * Read one encrypted handshake message, decrypting and stripping the inner type.
131
+ * Returns the whole handshake message (header + body), the body alone, and the
132
+ * buffer left after consuming the record.
133
+ */
134
+ export async function readEncryptedHandshakeMessage(readBuffer, transport, aead, traffic, seq) {
135
+ const header = await readHeaderBytesFromRecord(readBuffer, transport);
136
+ const record = await readRawRecordFromRecord(header.readBuffer, transport, header);
137
+ if (record.type !== ContentType.APPLICATION_DATA) {
138
+ throw new TlsHandshakeError("finished", {
139
+ cause: new Error(`expected encrypted APPLICATION_DATA record, got ${record.type}`),
140
+ });
141
+ }
142
+ const nonce = xorNonce(traffic.iv, seq);
143
+ const plaintext = decryptRecord(record.fragment, traffic.key, nonce, header.raw, aead);
144
+ // plaintext = content || innerType || optional zero padding. Find the type.
145
+ let end = plaintext.length;
146
+ while (end > 0 && plaintext[end - 1] === 0) {
147
+ end--;
148
+ }
149
+ if (end === 0) {
150
+ throw new TlsHandshakeError("finished", {
151
+ cause: new Error("encrypted record plaintext is all zero padding"),
152
+ });
153
+ }
154
+ const innerTypeByte = plaintext[end - 1];
155
+ if (innerTypeByte === undefined) {
156
+ throw new TlsHandshakeError("finished", {
157
+ cause: new Error("encrypted handshake plaintext ended before the inner content type byte"),
158
+ });
159
+ }
160
+ const innerType = readContentType(innerTypeByte);
161
+ const content = plaintext.subarray(0, end - 1);
162
+ if (innerType !== ContentType.HANDSHAKE) {
163
+ throw new TlsHandshakeError("finished", {
164
+ cause: new Error(`expected inner handshake type, got ${innerType}`),
165
+ });
166
+ }
167
+ // `content` is the full handshake message (4-byte header + body).
168
+ return { whole: content, body: content.subarray(4), readBuffer: record.readBuffer };
169
+ }
170
+ //# sourceMappingURL=handshake-messages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handshake-messages.js","sourceRoot":"","sources":["../../src/connection/handshake-messages.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,MAAM,EAAe,MAAM,qBAAqB,CAAC;AAG1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC5F,OAAO,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAC1E,OAAO,EAAE,WAAW,EAAE,aAAa,EAAsB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtG,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,WAAW,EAA6D,MAAM,iCAAiC,CAAC;AAC7J,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,eAAe,IAAI,yBAAyB,EAAE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AAS,EAAE,CAAC;QACtC,MAAM,IAAI,iBAAiB,CAAC,UAAU,EAAE;YACpC,KAAK,EAAE,IAAI,KAAK,CAAC,sCAAsC,SAAS,EAAE,CAAC;SACtE,CAAC,CAAC;IACP,CAAC;IACD,kEAAkE;IAClE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,UAAU,EAAE,MAAM,CAAC,UAAU,EAAE,CAAC;AACxF,CAAC"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Pure-function surface of the connection subsystem.
3
+ *
4
+ * These modules hold every byte-level computation the TLS connection performs —
5
+ * record framing, key exchange, server-flight message handling, and lifecycle
6
+ * bookkeeping. They are written as functions over explicit inputs (the read
7
+ * buffer, traffic secrets, sequence numbers) rather than as methods reaching into
8
+ * private connection state, so the connection class (`../tls.js`) stays a thin
9
+ * coordinator that owns the mutable fields and threads them through.
10
+ *
11
+ * This barrel is the single boundary across which the connection class depends on
12
+ * its internals: tls.ts imports from here, never from the individual modules.
13
+ */
14
+ export { ensureOpen, handleAlert, handlePostHandshakeRecord, emitError, notifyClose, withTimeout } from "./lifecycle.js";
15
+ export { computeSharedSecret, transcriptHash, verifyServerFinished } from "./key-exchange.js";
16
+ export { buildClientFinishedMessage, parseAlpnFromEncryptedExtensions, readEncryptedHandshakeMessage, validateCertificateChain, } from "./handshake-messages.js";
17
+ export { readEncryptedRecord, readHeaderBytes, readRawRecord, writeEncryptedRecord, writeRecord, } from "./record-layer.js";
18
+ export { runHandshake, type HandshakeContext } from "./handshake-driver.js";
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/connection/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,yBAAyB,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACzH,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC9F,OAAO,EACH,0BAA0B,EAC1B,gCAAgC,EAChC,6BAA6B,EAC7B,wBAAwB,GAC3B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACH,mBAAmB,EACnB,eAAe,EACf,aAAa,EACb,oBAAoB,EACpB,WAAW,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,KAAK,gBAAgB,EAAE,MAAM,uBAAuB,CAAC"}
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Pure-function surface of the connection subsystem.
3
+ *
4
+ * These modules hold every byte-level computation the TLS connection performs —
5
+ * record framing, key exchange, server-flight message handling, and lifecycle
6
+ * bookkeeping. They are written as functions over explicit inputs (the read
7
+ * buffer, traffic secrets, sequence numbers) rather than as methods reaching into
8
+ * private connection state, so the connection class (`../tls.js`) stays a thin
9
+ * coordinator that owns the mutable fields and threads them through.
10
+ *
11
+ * This barrel is the single boundary across which the connection class depends on
12
+ * its internals: tls.ts imports from here, never from the individual modules.
13
+ */
14
+ export { ensureOpen, handleAlert, handlePostHandshakeRecord, emitError, notifyClose, withTimeout } from "./lifecycle.js";
15
+ export { computeSharedSecret, transcriptHash, verifyServerFinished } from "./key-exchange.js";
16
+ export { buildClientFinishedMessage, parseAlpnFromEncryptedExtensions, readEncryptedHandshakeMessage, validateCertificateChain, } from "./handshake-messages.js";
17
+ export { readEncryptedRecord, readHeaderBytes, readRawRecord, writeEncryptedRecord, writeRecord, } from "./record-layer.js";
18
+ export { runHandshake } from "./handshake-driver.js";
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/connection/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,yBAAyB,EAAE,SAAS,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACzH,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAC9F,OAAO,EACH,0BAA0B,EAC1B,gCAAgC,EAChC,6BAA6B,EAC7B,wBAAwB,GAC3B,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACH,mBAAmB,EACnB,eAAe,EACf,aAAa,EACb,oBAAoB,EACpB,WAAW,GACd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAyB,MAAM,uBAAuB,CAAC"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * (EC)DHE key exchange and transcript verification for the TLS 1.3 handshake.
3
+ *
4
+ * These are the cryptographic heart of the handshake — recovering the server's
5
+ * key share to derive the shared secret, hashing the transcript, and verifying
6
+ * (and producing) the Finished HMAC. They are pure computations over their
7
+ * inputs and the @browsercore/crypto backend; they deliberately hold no
8
+ * connection state, so the connection class can stay an orchestrator that wires
9
+ * them together.
10
+ */
11
+ import { type HashId } from "@browsercore/crypto";
12
+ import type { KeyPair } from "../types.js";
13
+ import type { ServerHello } from "../handshake/handshake.js";
14
+ /** Compute the (EC)DHE shared secret from the server's selected key share. */
15
+ export declare function computeSharedSecret(serverHello: ServerHello, keyPairs: readonly KeyPair[]): Uint8Array;
16
+ /** Hash the current handshake transcript with the negotiated cipher's hash. */
17
+ export declare function transcriptHash(transcript: readonly Uint8Array[], hash: HashId): Uint8Array;
18
+ /**
19
+ * Verify the server's Finished message: HMAC(finished_key, transcript), where
20
+ * finished_key = HKDF-Expand-Label(server_traffic_secret, "finished", "", Hash.length)
21
+ * and the transcript is ClientHello..CertificateVerify (everything before Finished).
22
+ */
23
+ export declare function verifyServerFinished(body: Uint8Array, transcript: Uint8Array, hash: HashId, serverHsTrafficSecret: Uint8Array): void;
24
+ //# sourceMappingURL=key-exchange.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"key-exchange.d.ts","sourceRoot":"","sources":["../../src/connection/key-exchange.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAU,KAAK,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAM7D,8EAA8E;AAC9E,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,WAAW,EAAE,QAAQ,EAAE,SAAS,OAAO,EAAE,GAAG,UAAU,CAwDtG;AAED,+EAA+E;AAC/E,wBAAgB,cAAc,CAAC,UAAU,EAAE,SAAS,UAAU,EAAE,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,CAQ1F;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAChC,IAAI,EAAE,UAAU,EAChB,UAAU,EAAE,UAAU,EACtB,IAAI,EAAE,MAAM,EACZ,qBAAqB,EAAE,UAAU,GAClC,IAAI,CAcN"}
@@ -0,0 +1,104 @@
1
+ /**
2
+ * (EC)DHE key exchange and transcript verification for the TLS 1.3 handshake.
3
+ *
4
+ * These are the cryptographic heart of the handshake — recovering the server's
5
+ * key share to derive the shared secret, hashing the transcript, and verifying
6
+ * (and producing) the Finished HMAC. They are pure computations over their
7
+ * inputs and the @browsercore/crypto backend; they deliberately hold no
8
+ * connection state, so the connection class can stay an orchestrator that wires
9
+ * them together.
10
+ */
11
+ import { crypto } from "@browsercore/crypto";
12
+ import { TlsHandshakeError } from "../errors.js";
13
+ import { ExtensionType, findExtension, parseExtensions, wireToNamedGroup } from "../extensions/extensions.js";
14
+ import { hkdfExpandLabel, hashLengthFor } from "../crypto/keySchedule.js";
15
+ import { assertNever, constantTimeEqual } from "../utils.js";
16
+ /** Compute the (EC)DHE shared secret from the server's selected key share. */
17
+ export function computeSharedSecret(serverHello, keyPairs) {
18
+ const extensions = parseExtensions(serverHello.extensions);
19
+ const keyShare = findExtension(extensions, ExtensionType.KEY_SHARE);
20
+ if (keyShare === undefined) {
21
+ throw new TlsHandshakeError("server_hello", {
22
+ cause: new Error("ServerHello missing required key_share extension"),
23
+ });
24
+ }
25
+ // Server KeyShareEntry: group(2) || len(2) || key_exchange.
26
+ if (keyShare.data.length < 4) {
27
+ throw new TlsHandshakeError("server_hello", {
28
+ cause: new Error("key_share entry truncated"),
29
+ });
30
+ }
31
+ // The length check above guarantees indices 0..3 are in bounds, but
32
+ // noUncheckedIndexedAccess cannot prove it — read through locals.
33
+ const d0 = keyShare.data[0];
34
+ const d1 = keyShare.data[1];
35
+ const d2 = keyShare.data[2];
36
+ const d3 = keyShare.data[3];
37
+ if (d0 === undefined || d1 === undefined || d2 === undefined || d3 === undefined) {
38
+ throw new TlsHandshakeError("server_hello", {
39
+ cause: new Error("key_share entry data truncated"),
40
+ });
41
+ }
42
+ const group = wireToNamedGroup((d0 << 8) | d1);
43
+ const keyLen = (d2 << 8) | d3;
44
+ if (keyLen + 4 !== keyShare.data.length) {
45
+ throw new TlsHandshakeError("server_hello", {
46
+ cause: new Error("key_share key_exchange length mismatch"),
47
+ });
48
+ }
49
+ const serverPublicKey = keyShare.data.subarray(4, 4 + keyLen);
50
+ const myPair = keyPairs.find((kp) => kp.algorithm === group);
51
+ if (myPair === undefined) {
52
+ throw new TlsHandshakeError("server_hello", {
53
+ cause: new Error(`server selected key share group ${group} we did not offer`),
54
+ });
55
+ }
56
+ switch (group) {
57
+ case "x25519":
58
+ return crypto.x25519SharedSecret(myPair.privateKey, serverPublicKey);
59
+ case "secp256r1":
60
+ case "secp384r1":
61
+ return crypto.ecdhSharedSecret(group, myPair.privateKey, serverPublicKey);
62
+ case "x448":
63
+ // @browsercore/crypto only exposes X25519 and the two NIST ECDH
64
+ // curves today. Other (EC)DHE groups would need a backend we do not
65
+ // have — fail fast and typed rather than producing a bogus secret.
66
+ throw new TlsHandshakeError("server_hello", {
67
+ cause: new Error(`key exchange for group ${group} is not supported by the crypto backend`),
68
+ });
69
+ default:
70
+ // All NamedGroup members are handled above — this is unrepresentable.
71
+ return assertNever(group);
72
+ }
73
+ }
74
+ /** Hash the current handshake transcript with the negotiated cipher's hash. */
75
+ export function transcriptHash(transcript, hash) {
76
+ const blob = transcript.reduce((acc, msg) => {
77
+ const next = new Uint8Array(acc.length + msg.length);
78
+ next.set(acc, 0);
79
+ next.set(msg, acc.length);
80
+ return next;
81
+ }, new Uint8Array(0));
82
+ return hash === "SHA-384" ? crypto.sha384(blob) : crypto.sha256(blob);
83
+ }
84
+ /**
85
+ * Verify the server's Finished message: HMAC(finished_key, transcript), where
86
+ * finished_key = HKDF-Expand-Label(server_traffic_secret, "finished", "", Hash.length)
87
+ * and the transcript is ClientHello..CertificateVerify (everything before Finished).
88
+ */
89
+ export function verifyServerFinished(body, transcript, hash, serverHsTrafficSecret) {
90
+ const hashLen = hashLengthFor(hash);
91
+ if (body.length !== hashLen) {
92
+ throw new TlsHandshakeError("finished", {
93
+ cause: new Error(`server Finished length ${body.length} != expected ${hashLen}`),
94
+ });
95
+ }
96
+ const finishedKey = hkdfExpandLabel(serverHsTrafficSecret, "finished", new Uint8Array(0), hashLen, hash);
97
+ const expected = crypto.hmac(hash, finishedKey, transcript);
98
+ if (!constantTimeEqual(body, expected)) {
99
+ throw new TlsHandshakeError("finished", {
100
+ cause: new Error("server Finished verify_data mismatch"),
101
+ });
102
+ }
103
+ }
104
+ //# sourceMappingURL=key-exchange.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"key-exchange.js","sourceRoot":"","sources":["../../src/connection/key-exchange.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,MAAM,EAAe,MAAM,qBAAqB,CAAC;AAG1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAC9G,OAAO,EAAE,eAAe,EAAE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,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,UAAU,CAAC,CAAC;IAC5D,IAAI,CAAC,iBAAiB,CAAC,IAAI,EAAE,QAAQ,CAAC,EAAE,CAAC;QACrC,MAAM,IAAI,iBAAiB,CAAC,UAAU,EAAE;YACpC,KAAK,EAAE,IAAI,KAAK,CAAC,sCAAsC,CAAC;SAC3D,CAAC,CAAC;IACP,CAAC;AACL,CAAC"}
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Connection lifecycle: timeouts, alerts, state transitions, error emission.
3
+ *
4
+ * The bookkeeping around a connection's lifetime — racing the handshake against
5
+ * a timeout, translating a received alert into a typed error, moving between
6
+ * lifecycle states, and notifying observers. Kept as thin functions over
7
+ * explicit state so the connection class stays a coordinator rather than owning
8
+ * this plumbing.
9
+ */
10
+ import type { CloseReason, TlsState } from "../types.js";
11
+ import { TlsAlertError, type TlsError } from "../errors.js";
12
+ import { ContentType } from "../record/record.js";
13
+ /** Race `run` against a timeout, rejecting with a handshake error if it fires. */
14
+ export declare function withTimeout(ms: number, run: () => Promise<void>): Promise<void>;
15
+ /**
16
+ * Handle a non-application record encountered while reading application data.
17
+ *
18
+ * Routes alerts to {@link handleAlert}, ignores post-handshake handshake
19
+ * messages (NewSessionTicket, KeyUpdate — out of scope for the happy path),
20
+ * and rejects any {@link ContentType.CHANGE_CIPHER_SPEC} or
21
+ * {@link ContentType.APPLICATION_DATA} that appears *inside* an encrypted
22
+ * record (application data is only valid as the outer record type; TLS 1.3 has
23
+ * no change_cipher_spec). Returns `true` if the alert was a close_notify and
24
+ * the connection should close gracefully.
25
+ */
26
+ export declare function handlePostHandshakeRecord(innerType: ContentType, content: Uint8Array): boolean;
27
+ /** Translate a received alert into a typed error and close the connection. */
28
+ export declare function handleAlert(content: Uint8Array): {
29
+ close: boolean;
30
+ error?: TlsAlertError;
31
+ };
32
+ /** Throw unless the connection is open. */
33
+ export declare function ensureOpen(state: TlsState): void;
34
+ /** Emit an error to all registered error listeners. */
35
+ export declare function emitError(listeners: readonly ((error: TlsError) => void)[], error: TlsError): void;
36
+ /** Notify all close listeners. */
37
+ export declare function notifyClose(listeners: readonly ((reason: CloseReason) => void)[], reason: CloseReason): void;
38
+ //# sourceMappingURL=lifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle.d.ts","sourceRoot":"","sources":["../../src/connection/lifecycle.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,EAAE,aAAa,EAAqB,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC/E,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAGlD,kFAAkF;AAClF,wBAAsB,WAAW,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBrF;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,yBAAyB,CAAC,SAAS,EAAE,WAAW,EAAE,OAAO,EAAE,UAAU,GAAG,OAAO,CAkB9F;AAED,8EAA8E;AAC9E,wBAAgB,WAAW,CAAC,OAAO,EAAE,UAAU,GAAG;IAAE,KAAK,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,aAAa,CAAA;CAAE,CAiB1F;AAED,2CAA2C;AAC3C,wBAAgB,UAAU,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI,CAMhD;AAED,uDAAuD;AACvD,wBAAgB,SAAS,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,KAAK,EAAE,QAAQ,KAAK,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,QAAQ,GAAG,IAAI,CAIlG;AAED,kCAAkC;AAClC,wBAAgB,WAAW,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,MAAM,EAAE,WAAW,KAAK,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,WAAW,GAAG,IAAI,CAI5G"}