node-rtc-connection 1.0.19 → 2.0.4

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 (64) hide show
  1. package/README.md +94 -85
  2. package/dist/index.cjs +20 -5606
  3. package/dist/index.mjs +25 -5598
  4. package/dist/types/crypto/der.d.ts +107 -0
  5. package/dist/types/crypto/x509.d.ts +56 -0
  6. package/dist/types/datachannel/RTCDataChannel.d.ts +179 -0
  7. package/dist/types/dtls/RTCCertificate.d.ts +163 -0
  8. package/dist/types/dtls/cipher.d.ts +81 -0
  9. package/dist/types/dtls/connection.d.ts +81 -0
  10. package/dist/types/dtls/prf.d.ts +29 -0
  11. package/dist/types/dtls/protocol.d.ts +127 -0
  12. package/dist/types/foundation/ByteBufferQueue.d.ts +71 -0
  13. package/dist/types/foundation/RTCError.d.ts +152 -0
  14. package/dist/types/ice/RTCIceCandidate.d.ts +161 -0
  15. package/dist/types/ice/ice-agent.d.ts +154 -0
  16. package/dist/types/ice/stun-message.d.ts +92 -0
  17. package/dist/types/index.d.ts +29 -0
  18. package/dist/types/peerconnection/RTCPeerConnection.d.ts +74 -0
  19. package/dist/types/sctp/association.d.ts +77 -0
  20. package/dist/types/sctp/chunks.d.ts +200 -0
  21. package/dist/types/sctp/crc32c.d.ts +24 -0
  22. package/dist/types/sctp/datachannel-manager.d.ts +51 -0
  23. package/dist/types/sctp/dcep.d.ts +56 -0
  24. package/dist/types/sdp/RTCSessionDescription.d.ts +73 -0
  25. package/dist/types/sdp/sdp-utils.d.ts +103 -0
  26. package/dist/types/stun/stun-client.d.ts +119 -0
  27. package/dist/types/transport-stack.d.ts +68 -0
  28. package/package.json +26 -21
  29. package/src/crypto/der.ts +205 -0
  30. package/src/crypto/x509.ts +146 -0
  31. package/src/datachannel/RTCDataChannel.ts +388 -0
  32. package/src/dtls/RTCCertificate.ts +396 -0
  33. package/src/dtls/cipher.ts +198 -0
  34. package/src/dtls/connection.ts +974 -0
  35. package/src/dtls/prf.ts +62 -0
  36. package/src/dtls/protocol.ts +204 -0
  37. package/src/foundation/{ByteBufferQueue.js → ByteBufferQueue.ts} +74 -72
  38. package/src/foundation/{RTCError.js → RTCError.ts} +110 -60
  39. package/src/ice/{RTCIceCandidate.js → RTCIceCandidate.ts} +140 -92
  40. package/src/ice/ice-agent.ts +609 -0
  41. package/src/ice/stun-message.ts +260 -0
  42. package/src/index.ts +72 -0
  43. package/src/peerconnection/RTCPeerConnection.ts +430 -0
  44. package/src/sctp/association.ts +523 -0
  45. package/src/sctp/chunks.ts +350 -0
  46. package/src/sctp/crc32c.ts +57 -0
  47. package/src/sctp/datachannel-manager.ts +187 -0
  48. package/src/sctp/dcep.ts +94 -0
  49. package/src/sdp/{RTCSessionDescription.js → RTCSessionDescription.ts} +42 -29
  50. package/src/sdp/sdp-utils.ts +229 -0
  51. package/src/stun/{stun-client.js → stun-client.ts} +346 -187
  52. package/src/transport-stack.ts +165 -0
  53. package/dist/index.cjs.map +0 -1
  54. package/dist/index.mjs.map +0 -1
  55. package/src/datachannel/RTCDataChannel.js +0 -354
  56. package/src/dtls/RTCCertificate.js +0 -310
  57. package/src/dtls/RTCDtlsTransport.js +0 -247
  58. package/src/ice/RTCIceTransport.js +0 -1018
  59. package/src/index.d.ts +0 -400
  60. package/src/index.js +0 -92
  61. package/src/network/network-transport.js +0 -478
  62. package/src/peerconnection/RTCPeerConnection.js +0 -875
  63. package/src/sctp/RTCSctpTransport.js +0 -253
  64. package/src/sdp/sdp-utils.js +0 -224
@@ -0,0 +1,107 @@
1
+ /**
2
+ * @file der.ts
3
+ * @description Minimal ASN.1 DER encoder/decoder for X.509 certificate generation.
4
+ * @module crypto/der
5
+ *
6
+ * Implements just enough of ITU-T X.690 DER to build and read the structures
7
+ * WebRTC needs: self-signed ECDSA certificates and SubjectPublicKeyInfo.
8
+ *
9
+ * All encoders return Buffers. The TLV length is always encoded in the
10
+ * minimal (definite, shortest-form) representation required by DER.
11
+ */
12
+ export declare const TAG: Readonly<{
13
+ BOOLEAN: 1;
14
+ INTEGER: 2;
15
+ BIT_STRING: 3;
16
+ OCTET_STRING: 4;
17
+ NULL: 5;
18
+ OID: 6;
19
+ UTF8_STRING: 12;
20
+ PRINTABLE_STRING: 19;
21
+ IA5_STRING: 22;
22
+ UTC_TIME: 23;
23
+ GENERALIZED_TIME: 24;
24
+ SEQUENCE: 48;
25
+ SET: 49;
26
+ }>;
27
+ /**
28
+ * Encode a DER length in definite, shortest form.
29
+ * @param {number} len
30
+ * @returns {Buffer}
31
+ */
32
+ export declare function encodeLength(len: number): Buffer;
33
+ /**
34
+ * Wrap a body in a TLV with the given tag.
35
+ * @param {number} tag
36
+ * @param {Buffer} body
37
+ * @returns {Buffer}
38
+ */
39
+ export declare function tlv(tag: number, body: Buffer): Buffer;
40
+ /**
41
+ * Encode an unsigned big-endian integer (from a Buffer) as a DER INTEGER,
42
+ * adding a leading 0x00 when the high bit is set so it stays positive.
43
+ * @param {Buffer} buf - Big-endian magnitude.
44
+ * @returns {Buffer}
45
+ */
46
+ export declare function encodeIntegerFromBuffer(buf: Buffer): Buffer;
47
+ /**
48
+ * Encode a small non-negative JS integer as a DER INTEGER.
49
+ * @param {number} value
50
+ * @returns {Buffer}
51
+ */
52
+ export declare function encodeInteger(value: number): Buffer;
53
+ /**
54
+ * Encode an OBJECT IDENTIFIER from its dotted-decimal string.
55
+ * @param {string} oid - e.g. "1.2.840.10045.2.1"
56
+ * @returns {Buffer}
57
+ */
58
+ export declare function encodeOID(oid: string): Buffer;
59
+ /**
60
+ * Encode a BIT STRING with zero unused bits.
61
+ * @param {Buffer} data
62
+ * @returns {Buffer}
63
+ */
64
+ export declare function encodeBitString(data: Buffer): Buffer;
65
+ /**
66
+ * Encode an OCTET STRING.
67
+ * @param {Buffer} data
68
+ * @returns {Buffer}
69
+ */
70
+ export declare function encodeOctetString(data: Buffer): Buffer;
71
+ /**
72
+ * Encode a SEQUENCE from already-encoded components.
73
+ * @param {Buffer[]} components
74
+ * @returns {Buffer}
75
+ */
76
+ export declare function encodeSequence(components: Buffer[]): Buffer;
77
+ /**
78
+ * Encode a SET from already-encoded components.
79
+ * @param {Buffer[]} components
80
+ * @returns {Buffer}
81
+ */
82
+ export declare function encodeSet(components: Buffer[]): Buffer;
83
+ /**
84
+ * Encode NULL.
85
+ * @returns {Buffer}
86
+ */
87
+ export declare function encodeNull(): Buffer;
88
+ /**
89
+ * Encode a UTF8String.
90
+ * @param {string} str
91
+ * @returns {Buffer}
92
+ */
93
+ export declare function encodeUTF8String(str: string): Buffer;
94
+ /**
95
+ * Encode a context-specific [n] explicit wrapper (constructed).
96
+ * @param {number} n - context tag number
97
+ * @param {Buffer} body
98
+ * @returns {Buffer}
99
+ */
100
+ export declare function encodeExplicit(n: number, body: Buffer): Buffer;
101
+ /**
102
+ * Encode an X.509 time. Uses UTCTime for years < 2050, else GeneralizedTime,
103
+ * per RFC 5280 §4.1.2.5.
104
+ * @param {Date} date
105
+ * @returns {Buffer}
106
+ */
107
+ export declare function encodeTime(date: Date): Buffer;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @file x509.ts
3
+ * @description Self-signed X.509 v3 certificate generation for WebRTC DTLS.
4
+ * @module crypto/x509
5
+ *
6
+ * WebRTC peers authenticate by self-signed certificate. The SDP carries
7
+ * a=fingerprint as the hash of the DER-encoded certificate (RFC 8122), which
8
+ * the peer verifies against the certificate presented during the DTLS
9
+ * handshake. Node has no certificate builder, so we assemble a minimal but
10
+ * spec-valid ECDSA P-256 / ecdsa-with-SHA256 certificate by hand.
11
+ */
12
+ import * as crypto from 'crypto';
13
+ /**
14
+ * Options for {@link generateSelfSigned}.
15
+ */
16
+ export interface GenerateSelfSignedOptions {
17
+ /** CN; WebRTC uses a random value. */
18
+ commonName?: string;
19
+ /** Validity period in days. */
20
+ days?: number;
21
+ /** Override start time (default: now - 1 day). */
22
+ notBefore?: Date;
23
+ }
24
+ /**
25
+ * Result of {@link generateSelfSigned}.
26
+ */
27
+ export interface SelfSignedCertificate {
28
+ /** DER-encoded certificate. */
29
+ certDer: Buffer;
30
+ privateKey: crypto.KeyObject;
31
+ publicKey: crypto.KeyObject;
32
+ notBefore: Date;
33
+ notAfter: Date;
34
+ }
35
+ export declare const OID: Readonly<{
36
+ ecPublicKey: "1.2.840.10045.2.1";
37
+ prime256v1: "1.2.840.10045.3.1.7";
38
+ ecdsaWithSHA256: "1.2.840.10045.4.3.2";
39
+ commonName: "2.5.4.3";
40
+ }>;
41
+ /**
42
+ * Generate a self-signed ECDSA P-256 certificate.
43
+ *
44
+ * @param {GenerateSelfSignedOptions} [options]
45
+ * @returns {SelfSignedCertificate}
46
+ */
47
+ export declare function generateSelfSigned(options?: GenerateSelfSignedOptions): SelfSignedCertificate;
48
+ /**
49
+ * Compute the certificate fingerprint as used in SDP a=fingerprint (RFC 8122):
50
+ * hash over the DER-encoded certificate, uppercase hex, colon-separated.
51
+ *
52
+ * @param {Buffer} certDer
53
+ * @param {string} [algorithm='sha-256'] - 'sha-256' | 'sha-384' | 'sha-512'
54
+ * @returns {string}
55
+ */
56
+ export declare function fingerprint(certDer: Buffer, algorithm?: string): string;
@@ -0,0 +1,179 @@
1
+ /**
2
+ * @file RTCDataChannel.ts
3
+ * @description WebRTC DataChannel implementation for peer-to-peer data transfer.
4
+ * @module datachannel/RTCDataChannel
5
+ *
6
+ * Implements the W3C RTCDataChannel interface
7
+ * (https://www.w3.org/TR/webrtc/#rtcdatachannel).
8
+ */
9
+ import { EventEmitter } from 'events';
10
+ /**
11
+ * RTCDataChannelState - Current state of the data channel
12
+ * @readonly
13
+ * @enum {string}
14
+ */
15
+ export declare const RTCDataChannelState: Readonly<{
16
+ CONNECTING: "connecting";
17
+ OPEN: "open";
18
+ CLOSING: "closing";
19
+ CLOSED: "closed";
20
+ }>;
21
+ type RTCDataChannelReadyState = 'connecting' | 'open' | 'closing' | 'closed';
22
+ type RTCDataChannelBinaryType = 'arraybuffer' | 'blob';
23
+ /**
24
+ * Package-internal events that wire an RTCDataChannel to the SCTP transport.
25
+ * They are keyed by Symbol so they never collide with — or leak into — the
26
+ * public event surface ('open'/'message'/'close'/'error'/'bufferedamountlow').
27
+ * The SCTP data-channel manager and the channel communicate purely by emitting
28
+ * these on the channel's own EventEmitter:
29
+ *
30
+ * - SEND channel → transport: outbound frame `(data: Buffer, isBinary: boolean)`
31
+ * - RECEIVE transport → channel: inbound frame `(data: Buffer, isBinary: boolean)`
32
+ * - OPEN transport → channel: transition the channel to 'open'
33
+ * - SET_ID transport → channel: assign the SCTP stream id `(id: number)`
34
+ */
35
+ export declare const RTCDataChannelEvents: Readonly<{
36
+ SEND: symbol;
37
+ RECEIVE: symbol;
38
+ OPEN: symbol;
39
+ SET_ID: symbol;
40
+ }>;
41
+ /**
42
+ * RTCDataChannelInit - Configuration for creating a data channel
43
+ * @typedef {Object} RTCDataChannelInit
44
+ * @property {boolean} [ordered=true] - Whether messages must arrive in order
45
+ * @property {number} [maxPacketLifeTime] - Maximum packet lifetime in milliseconds
46
+ * @property {number} [maxRetransmits] - Maximum number of retransmissions
47
+ * @property {string} [protocol=''] - Subprotocol name
48
+ * @property {boolean} [negotiated=false] - Whether channel was negotiated out-of-band
49
+ * @property {number} [id] - Channel ID (required if negotiated is true)
50
+ */
51
+ export interface RTCDataChannelInit {
52
+ ordered?: boolean;
53
+ maxPacketLifeTime?: number;
54
+ maxRetransmits?: number;
55
+ protocol?: string;
56
+ negotiated?: boolean;
57
+ id?: number;
58
+ }
59
+ /**
60
+ * @class RTCDataChannel
61
+ * @extends EventEmitter
62
+ * @description Represents a bidirectional data channel between peers.
63
+ * Provides reliable or unreliable data transfer with configurable ordering.
64
+ *
65
+ * Events:
66
+ * - 'open': Fired when the channel opens
67
+ * - 'message': Fired when a message is received
68
+ * - 'bufferedamountlow': Fired when bufferedAmount drops below threshold
69
+ * - 'error': Fired when an error occurs
70
+ * - 'closing': Fired when the channel is closing
71
+ * - 'close': Fired when the channel closes
72
+ *
73
+ * @example
74
+ * const dataChannel = peerConnection.createDataChannel('myChannel', {
75
+ * ordered: true,
76
+ * maxRetransmits: 3
77
+ * });
78
+ *
79
+ * dataChannel.on('open', () => {
80
+ * console.log('Channel opened');
81
+ * dataChannel.send('Hello!');
82
+ * });
83
+ *
84
+ * dataChannel.on('message', (event) => {
85
+ * console.log('Received:', event.data);
86
+ * });
87
+ */
88
+ export declare class RTCDataChannel extends EventEmitter {
89
+ #private;
90
+ /**
91
+ * Create an RTCDataChannel instance.
92
+ * @param {string} label - Channel label
93
+ * @param {RTCDataChannelInit} [init] - Channel configuration
94
+ */
95
+ constructor(label: string, init?: RTCDataChannelInit);
96
+ /**
97
+ * Get the channel label.
98
+ * @returns {string} Channel label
99
+ */
100
+ get label(): string;
101
+ /**
102
+ * Check if messages are delivered in order.
103
+ * @returns {boolean} True if ordered
104
+ */
105
+ get ordered(): boolean;
106
+ /**
107
+ * Get the maximum packet lifetime in milliseconds.
108
+ * @returns {number|null} Maximum lifetime or null if not set
109
+ */
110
+ get maxPacketLifeTime(): number | null;
111
+ /**
112
+ * Get the maximum number of retransmissions.
113
+ * @returns {number|null} Maximum retransmits or null if not set
114
+ */
115
+ get maxRetransmits(): number | null;
116
+ /**
117
+ * Get the subprotocol name.
118
+ * @returns {string} Protocol name
119
+ */
120
+ get protocol(): string;
121
+ /**
122
+ * Check if the channel was negotiated out-of-band.
123
+ * @returns {boolean} True if negotiated
124
+ */
125
+ get negotiated(): boolean;
126
+ /**
127
+ * Get the channel ID.
128
+ * @returns {number|null} Channel ID or null if not assigned
129
+ */
130
+ get id(): number | null;
131
+ /**
132
+ * Get the current state of the channel.
133
+ * @returns {string} Channel state
134
+ */
135
+ get readyState(): RTCDataChannelReadyState;
136
+ /**
137
+ * Get the number of bytes queued to send.
138
+ * @returns {number} Buffered amount in bytes
139
+ */
140
+ get bufferedAmount(): number;
141
+ /**
142
+ * Get the threshold for bufferedamountlow event.
143
+ * @returns {number} Threshold in bytes
144
+ */
145
+ get bufferedAmountLowThreshold(): number;
146
+ /**
147
+ * Set the threshold for bufferedamountlow event.
148
+ * @param {number} value - Threshold in bytes
149
+ */
150
+ set bufferedAmountLowThreshold(value: number);
151
+ /**
152
+ * Get the binary data type.
153
+ * @returns {string} 'arraybuffer' or 'blob'
154
+ */
155
+ get binaryType(): RTCDataChannelBinaryType;
156
+ /**
157
+ * Set the binary data type.
158
+ * @param {string} value - 'arraybuffer' or 'blob'
159
+ * @throws {TypeError} If value is invalid
160
+ */
161
+ set binaryType(value: RTCDataChannelBinaryType);
162
+ /**
163
+ * Check if the channel is reliable (deprecated).
164
+ * @returns {boolean} True if ordered and no packet lifetime/retransmit limits
165
+ * @deprecated Use ordered, maxPacketLifeTime, and maxRetransmits instead
166
+ */
167
+ get reliable(): boolean;
168
+ /**
169
+ * Send a message through the channel.
170
+ * @param {string|ArrayBuffer|ArrayBufferView|Blob} data - Data to send
171
+ * @throws {Error} If channel is not open or data is invalid
172
+ */
173
+ send(data: string | ArrayBuffer | ArrayBufferView | Buffer): void;
174
+ /**
175
+ * Close the data channel.
176
+ */
177
+ close(): void;
178
+ }
179
+ export {};
@@ -0,0 +1,163 @@
1
+ /**
2
+ * @file RTCCertificate.ts
3
+ * @description DTLS certificate implementation for WebRTC.
4
+ * @module dtls/RTCCertificate
5
+ *
6
+ * Implements the W3C RTCCertificate interface
7
+ * (https://www.w3.org/TR/webrtc/#rtccertificate-interface). Certificate and key
8
+ * generation are handled by src/crypto/x509.ts.
9
+ */
10
+ import * as crypto from 'crypto';
11
+ /**
12
+ * RTCDtlsFingerprint - DTLS certificate fingerprint
13
+ */
14
+ export interface RTCDtlsFingerprint {
15
+ /** Hash algorithm (e.g., 'sha-256') */
16
+ algorithm: string;
17
+ /** Fingerprint value (colon-separated hex) */
18
+ value: string;
19
+ }
20
+ /** Internal certificate data held by an {@link RTCCertificate}. */
21
+ interface CertData {
22
+ certDer: Buffer | null;
23
+ privateKey: crypto.KeyObject | string;
24
+ publicKey: crypto.KeyObject | string;
25
+ expires: number;
26
+ hash?: string;
27
+ }
28
+ /** Options accepted by {@link RTCCertificate.generateCertificate}. */
29
+ interface RTCGenerateCertificateOptions {
30
+ /** Common name for the certificate */
31
+ name?: string;
32
+ /** Expiration time in ms (default: 30 days from now) */
33
+ expires?: number;
34
+ /** Days until expiration */
35
+ days?: number;
36
+ /** Hash algorithm */
37
+ hash?: string;
38
+ }
39
+ /** Key parameters accepted by {@link RTCCertificate.isSupportedKeyParams}. */
40
+ interface RTCCertificateKeyParams {
41
+ type: string;
42
+ rsaModulusLength?: number;
43
+ namedCurve?: string;
44
+ }
45
+ /** PEM serialization produced by {@link RTCCertificate.toPEM}. */
46
+ interface RTCCertificatePEM {
47
+ pemPrivateKey: string;
48
+ pemCertificate: string;
49
+ }
50
+ /**
51
+ * @class RTCCertificate
52
+ * @description Represents a certificate used for DTLS in WebRTC.
53
+ * The certificate includes a key pair and expiration time.
54
+ *
55
+ * @example
56
+ * // Generate a certificate
57
+ * const cert = await RTCCertificate.generateCertificate();
58
+ * console.log('Expires:', new Date(cert.expires));
59
+ * console.log('Fingerprints:', cert.getFingerprints());
60
+ *
61
+ * @example
62
+ * // Generate with custom expiration
63
+ * const cert = await RTCCertificate.generateCertificate({
64
+ * name: 'my-peer',
65
+ * expires: Date.now() + (90 * 24 * 60 * 60 * 1000) // 90 days
66
+ * });
67
+ */
68
+ declare class RTCCertificate {
69
+ #private;
70
+ /**
71
+ * Create an RTCCertificate instance.
72
+ * Use generateCertificate() static method instead of calling directly.
73
+ * @param certData - Internal certificate data
74
+ * @private
75
+ */
76
+ constructor(certData: CertData);
77
+ /**
78
+ * Get the DER-encoded X.509 certificate.
79
+ * Used by the DTLS handshake to transmit the local certificate.
80
+ * @internal
81
+ */
82
+ getCertificateDer(): Buffer | null;
83
+ /**
84
+ * Get the expiration time.
85
+ * @returns Expiration time in milliseconds since epoch (DOMTimeStamp)
86
+ */
87
+ get expires(): number;
88
+ /**
89
+ * Get the certificate fingerprints.
90
+ * Returns an array of fingerprints for the certificate chain.
91
+ * For self-signed certificates, this returns a single fingerprint.
92
+ *
93
+ * @returns Array of fingerprint objects
94
+ */
95
+ getFingerprints(): RTCDtlsFingerprint[];
96
+ /**
97
+ * Get the private key as a Node crypto KeyObject (for the DTLS handshake).
98
+ * @internal
99
+ */
100
+ getPrivateKeyObject(): crypto.KeyObject;
101
+ /**
102
+ * Get the private key in PEM format.
103
+ * @returns PEM-encoded private key
104
+ * @internal
105
+ */
106
+ getPrivateKey(): string;
107
+ /**
108
+ * Get the public key in PEM format.
109
+ * @returns PEM-encoded public key
110
+ * @internal
111
+ */
112
+ getPublicKey(): string;
113
+ /**
114
+ * Convert to PEM format (for serialization/storage).
115
+ * The certificate is exported as a PEM-wrapped DER X.509 certificate.
116
+ * @returns Object with pemPrivateKey and pemCertificate
117
+ */
118
+ toPEM(): RTCCertificatePEM;
119
+ /**
120
+ * Check if the certificate has expired.
121
+ * @returns True if expired, false otherwise
122
+ */
123
+ isExpired(): boolean;
124
+ /**
125
+ * Generate a new RTCCertificate asynchronously.
126
+ *
127
+ * @param options - Generation options
128
+ * @returns Promise resolving to generated certificate
129
+ *
130
+ * @example
131
+ * const cert = await RTCCertificate.generateCertificate({
132
+ * name: 'my-app',
133
+ * expires: Date.now() + (90 * 24 * 60 * 60 * 1000) // 90 days
134
+ * });
135
+ */
136
+ static generateCertificate(options?: RTCGenerateCertificateOptions): Promise<RTCCertificate>;
137
+ /**
138
+ * Create a certificate from PEM strings.
139
+ *
140
+ * @param pemPrivateKey - PEM-encoded private key
141
+ * @param pemCertificate - PEM-encoded certificate (or public key)
142
+ * @param expires - Expiration time in ms (default: 30 days from now)
143
+ * @returns Certificate instance
144
+ *
145
+ * @example
146
+ * const cert = RTCCertificate.fromPEM(
147
+ * privateKeyPEM,
148
+ * publicKeyPEM,
149
+ * Date.now() + (30 * 24 * 60 * 60 * 1000)
150
+ * );
151
+ */
152
+ static fromPEM(pemPrivateKey: string, pemCertificate: string, expires?: number): RTCCertificate;
153
+ /**
154
+ * Check if key parameters are supported.
155
+ * Currently supports RSA with 1024-4096 bits and ECDSA.
156
+ *
157
+ * @param keyParams - Key parameters
158
+ * @returns True if supported, false otherwise
159
+ */
160
+ static isSupportedKeyParams(keyParams: RTCCertificateKeyParams): boolean;
161
+ }
162
+ export default RTCCertificate;
163
+ export { RTCCertificate };
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @file cipher.ts
3
+ * @description AEAD record protection for DTLS 1.2 with AES-128-GCM.
4
+ * @module dtls/cipher
5
+ *
6
+ * Implements key derivation and the GCM record encrypt/decrypt for the suite
7
+ * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 (RFC 5288 / RFC 6347).
8
+ *
9
+ * Key block layout for AEAD (no MAC keys):
10
+ * client_write_key[16] | server_write_key[16] |
11
+ * client_write_IV[4] | server_write_IV[4] (implicit salt)
12
+ *
13
+ * GCM nonce = write_IV (4) || explicit_nonce (8)
14
+ * Record = explicit_nonce (8) || ciphertext || tag (16)
15
+ * AAD (DTLS) = seq_num (8 = epoch||seq) || type (1) || version (2) || plaintext_len (2)
16
+ */
17
+ /**
18
+ * Per-direction keys/IVs produced by {@link deriveKeys}.
19
+ */
20
+ export interface DerivedKeys {
21
+ clientKey: Buffer;
22
+ serverKey: Buffer;
23
+ clientIV: Buffer;
24
+ serverIV: Buffer;
25
+ }
26
+ /**
27
+ * Derive the master secret from the pre-master secret (RFC 5246 §8.1).
28
+ * @param {Buffer} preMasterSecret
29
+ * @param {Buffer} clientRandom - 32 bytes
30
+ * @param {Buffer} serverRandom - 32 bytes
31
+ * @returns {Buffer} 48-byte master secret
32
+ */
33
+ export declare function deriveMasterSecret(preMasterSecret: Buffer, clientRandom: Buffer, serverRandom: Buffer): Buffer;
34
+ /**
35
+ * Derive the extended master secret (RFC 7627) using the handshake hash.
36
+ * @param {Buffer} preMasterSecret
37
+ * @param {Buffer} sessionHash - hash of handshake messages through CKE
38
+ * @returns {Buffer} 48-byte master secret
39
+ */
40
+ export declare function deriveExtendedMasterSecret(preMasterSecret: Buffer, sessionHash: Buffer): Buffer;
41
+ /**
42
+ * Expand the key block and split it into per-direction keys/IVs.
43
+ * @param {Buffer} masterSecret
44
+ * @param {Buffer} clientRandom
45
+ * @param {Buffer} serverRandom
46
+ * @returns {DerivedKeys}
47
+ */
48
+ export declare function deriveKeys(masterSecret: Buffer, clientRandom: Buffer, serverRandom: Buffer): DerivedKeys;
49
+ /**
50
+ * @class GcmCipher
51
+ * @description Holds the key/IV for one direction and does record AEAD.
52
+ */
53
+ export declare class GcmCipher {
54
+ #private;
55
+ /**
56
+ * @param {Buffer} key - 16-byte AES key
57
+ * @param {Buffer} fixedIv - 4-byte implicit salt
58
+ */
59
+ constructor(key: Buffer, fixedIv: Buffer);
60
+ /**
61
+ * Encrypt a record fragment.
62
+ * @param {number} epoch
63
+ * @param {number} seq
64
+ * @param {number} type
65
+ * @param {number} version
66
+ * @param {Buffer} plaintext
67
+ * @returns {Buffer} explicit_nonce || ciphertext || tag
68
+ */
69
+ encrypt(epoch: number, seq: number, type: number, version: number, plaintext: Buffer): Buffer;
70
+ /**
71
+ * Decrypt a record fragment.
72
+ * @param {number} epoch
73
+ * @param {number} seq
74
+ * @param {number} type
75
+ * @param {number} version
76
+ * @param {Buffer} record - explicit_nonce || ciphertext || tag
77
+ * @returns {Buffer} plaintext
78
+ * @throws on authentication failure
79
+ */
80
+ decrypt(epoch: number, seq: number, type: number, version: number, record: Buffer): Buffer;
81
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @file connection.ts
3
+ * @description DTLS 1.2 connection state machine (client and server roles).
4
+ * @module dtls/connection
5
+ *
6
+ * Implements the handshake for TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 over an
7
+ * abstract datagram channel. The owner supplies an `output` callback to send
8
+ * datagrams and feeds inbound datagrams to `handlePacket`. On success the
9
+ * connection emits 'connect'; application records arrive via 'data' and are
10
+ * sent via `send`.
11
+ *
12
+ * Scope: one cipher suite, secp256r1, ECDSA P-256 certificates, extended
13
+ * master secret. This is the subset Chromium/Firefox negotiate for data
14
+ * channels, so it interoperates with browsers while staying pure-Node.
15
+ *
16
+ * References: RFC 6347 (DTLS 1.2), RFC 5246 (TLS 1.2), RFC 7627 (EMS),
17
+ * RFC 8422 (ECC cipher suites), RFC 5288 (AES-GCM).
18
+ */
19
+ import * as crypto from 'crypto';
20
+ import { EventEmitter } from 'events';
21
+ declare const ROLE: Readonly<{
22
+ CLIENT: "client";
23
+ SERVER: "server";
24
+ }>;
25
+ declare const STATE: Readonly<{
26
+ NEW: "new";
27
+ HANDSHAKING: "handshaking";
28
+ CONNECTED: "connected";
29
+ CLOSED: "closed";
30
+ FAILED: "failed";
31
+ }>;
32
+ /** A certificate fingerprint as advertised in SDP a=fingerprint. */
33
+ interface Fingerprint {
34
+ algorithm: string;
35
+ value: string;
36
+ }
37
+ /** Callback used to verify the peer's certificate fingerprint. */
38
+ type VerifyFingerprint = (fp: Fingerprint, remoteCertDer: Buffer) => boolean;
39
+ /** Constructor options for {@link DtlsConnection}. */
40
+ interface DtlsConnectionOptions {
41
+ /** 'client' | 'server' */
42
+ role: string;
43
+ /** local DER certificate */
44
+ certDer: Buffer;
45
+ /** local EC private key */
46
+ privateKey: crypto.KeyObject;
47
+ /** called with the peer cert fingerprint; return false to reject. */
48
+ verifyFingerprint?: VerifyFingerprint;
49
+ /** send a datagram to the peer */
50
+ output: (datagram: Buffer) => void;
51
+ }
52
+ /**
53
+ * @class DtlsConnection
54
+ * @extends EventEmitter
55
+ */
56
+ declare class DtlsConnection extends EventEmitter {
57
+ #private;
58
+ role: string;
59
+ state: string;
60
+ /**
61
+ * @param opts connection options
62
+ */
63
+ constructor(opts: DtlsConnectionOptions);
64
+ /** Begin the handshake (client sends the first flight). */
65
+ start(): void;
66
+ /**
67
+ * Feed an inbound datagram (one UDP packet, possibly several records).
68
+ * @param packet
69
+ */
70
+ handlePacket(packet: Buffer): void;
71
+ /**
72
+ * Send application data over the established connection.
73
+ * @param data
74
+ */
75
+ send(data: Buffer): void;
76
+ /** Send a close_notify and tear down. */
77
+ close(): void;
78
+ /** The peer's certificate DER, available after the handshake. */
79
+ getRemoteCertificate(): Buffer | null;
80
+ }
81
+ export { DtlsConnection, ROLE, STATE };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * @file prf.ts
3
+ * @description TLS 1.2 pseudo-random function (RFC 5246 §5) with SHA-256.
4
+ * @module dtls/prf
5
+ *
6
+ * The cipher suite TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uses P_SHA256 for
7
+ * the PRF. This module also exposes the underlying HMAC-based P_hash.
8
+ */
9
+ /**
10
+ * P_hash(secret, seed) expanded to `length` bytes (RFC 5246 §5).
11
+ * A(0) = seed
12
+ * A(i) = HMAC(secret, A(i-1))
13
+ * P_hash = HMAC(secret, A(1)+seed) | HMAC(secret, A(2)+seed) | ...
14
+ *
15
+ * @param hashAlg - Node hash name, e.g. 'sha256'.
16
+ * @param secret
17
+ * @param seed
18
+ * @param length
19
+ */
20
+ export declare function pHash(hashAlg: string, secret: Buffer, seed: Buffer, length: number): Buffer;
21
+ /**
22
+ * TLS 1.2 PRF = P_SHA256(secret, label + seed).
23
+ *
24
+ * @param secret
25
+ * @param label - ASCII label, e.g. "master secret".
26
+ * @param seed
27
+ * @param length
28
+ */
29
+ export declare function prf(secret: Buffer, label: string, seed: Buffer, length: number): Buffer;