1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | import { SecureServerOptions } from 'http2';
|
19 | import { CIPHER_SUITES, getDefaultRootsData } from './tls-helpers';
|
20 |
|
21 | export interface KeyCertPair {
|
22 | private_key: Buffer;
|
23 | cert_chain: Buffer;
|
24 | }
|
25 |
|
26 | export abstract class ServerCredentials {
|
27 | abstract _isSecure(): boolean;
|
28 | abstract _getSettings(): SecureServerOptions | null;
|
29 |
|
30 | static createInsecure(): ServerCredentials {
|
31 | return new InsecureServerCredentials();
|
32 | }
|
33 |
|
34 | static createSsl(
|
35 | rootCerts: Buffer | null,
|
36 | keyCertPairs: KeyCertPair[],
|
37 | checkClientCertificate = false
|
38 | ): ServerCredentials {
|
39 | if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) {
|
40 | throw new TypeError('rootCerts must be null or a Buffer');
|
41 | }
|
42 |
|
43 | if (!Array.isArray(keyCertPairs)) {
|
44 | throw new TypeError('keyCertPairs must be an array');
|
45 | }
|
46 |
|
47 | if (typeof checkClientCertificate !== 'boolean') {
|
48 | throw new TypeError('checkClientCertificate must be a boolean');
|
49 | }
|
50 |
|
51 | const cert = [];
|
52 | const key = [];
|
53 |
|
54 | for (let i = 0; i < keyCertPairs.length; i++) {
|
55 | const pair = keyCertPairs[i];
|
56 |
|
57 | if (pair === null || typeof pair !== 'object') {
|
58 | throw new TypeError(`keyCertPair[${i}] must be an object`);
|
59 | }
|
60 |
|
61 | if (!Buffer.isBuffer(pair.private_key)) {
|
62 | throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`);
|
63 | }
|
64 |
|
65 | if (!Buffer.isBuffer(pair.cert_chain)) {
|
66 | throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`);
|
67 | }
|
68 |
|
69 | cert.push(pair.cert_chain);
|
70 | key.push(pair.private_key);
|
71 | }
|
72 |
|
73 | return new SecureServerCredentials({
|
74 | ca: rootCerts || getDefaultRootsData() || undefined,
|
75 | cert,
|
76 | key,
|
77 | requestCert: checkClientCertificate,
|
78 | ciphers: CIPHER_SUITES,
|
79 | });
|
80 | }
|
81 | }
|
82 |
|
83 | class InsecureServerCredentials extends ServerCredentials {
|
84 | _isSecure(): boolean {
|
85 | return false;
|
86 | }
|
87 |
|
88 | _getSettings(): null {
|
89 | return null;
|
90 | }
|
91 | }
|
92 |
|
93 | class SecureServerCredentials extends ServerCredentials {
|
94 | private options: SecureServerOptions;
|
95 |
|
96 | constructor(options: SecureServerOptions) {
|
97 | super();
|
98 | this.options = options;
|
99 | }
|
100 |
|
101 | _isSecure(): boolean {
|
102 | return true;
|
103 | }
|
104 |
|
105 | _getSettings(): SecureServerOptions {
|
106 | return this.options;
|
107 | }
|
108 | }
|