-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhttps-client.ts
More file actions
223 lines (187 loc) · 6.88 KB
/
https-client.ts
File metadata and controls
223 lines (187 loc) · 6.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import https from 'https';
import fs from 'fs';
import { HttpsClientConfig, ValidatedHttpsClientConfig, CertificateData } from './types.js';
import { Telemetry } from './telemetry.js';
export class HttpsClientManager {
private httpsAgent?: https.Agent;
private validatedConfig: ValidatedHttpsClientConfig;
private telemetry: Telemetry;
private enabled: boolean = false;
constructor(config: HttpsClientConfig, telemetry: Telemetry) {
this.telemetry = telemetry;
this.validatedConfig = this.createValidatedConfig(config);
}
initialize(): void {
// If no meaningful HTTPS config provided, don't enable HTTPS client
if (!this.hasMeaningfulConfig()) {
this.enabled = false;
this.telemetry.debug('📡 Using default HTTP client for backend APIs');
return;
}
this.validateHttpsConfig();
this.setupHttpsAgent();
this.enabled = true;
this.telemetry.info('🔒 HTTPS client configured for backend API connections');
}
isHttpsEnabled(): boolean {
return this.enabled;
}
getAgent(): https.Agent | undefined {
return this.httpsAgent;
}
applyToFetchOptions(url: string, options: RequestInit): void {
if (!this.enabled) {
return;
}
// Apply HTTPS agent only for HTTPS URLs
if (url.startsWith('https://') && this.httpsAgent) {
(options as any).agent = this.httpsAgent;
}
// Apply timeout
if (this.validatedConfig.timeout) {
(options as any).signal = AbortSignal.timeout(this.validatedConfig.timeout);
}
}
private createValidatedConfig(config: HttpsClientConfig): ValidatedHttpsClientConfig {
return {
...config,
timeout: config.timeout || 30000,
rejectUnauthorized: config.rejectUnauthorized ?? true,
keepAlive: config.keepAlive ?? true,
certificateType: this.determineCertificateType(config)
};
}
private determineCertificateType(config: HttpsClientConfig): 'none' | 'cert-key' | 'pfx' {
if (config.pfxFile) return 'pfx';
if (config.certFile && config.keyFile) return 'cert-key';
return 'none';
}
private hasMeaningfulConfig(): boolean {
const config = this.validatedConfig;
return !!(
config.certFile ||
config.keyFile ||
config.pfxFile ||
config.caFile ||
config.rejectUnauthorized !== true || // Non-default value
config.timeout !== 30000 || // Non-default value
config.keepAlive !== true // Non-default value
);
}
private validateHttpsConfig(): void {
const errors: string[] = [];
const config = this.validatedConfig;
// Validate certificate configuration groups
const hasCertKey = config.certFile || config.keyFile;
const hasPfx = config.pfxFile;
if (hasCertKey && hasPfx) {
errors.push('Cannot specify both cert/key files and PFX file simultaneously');
}
// GROUP A: Cert/Key validation
if (config.certFile && !config.keyFile) {
errors.push('keyFile is required when certFile is specified');
}
if (config.keyFile && !config.certFile) {
errors.push('certFile is required when keyFile is specified');
}
// Validate file existence
const filesToCheck = [
{ path: config.certFile, name: 'certFile' },
{ path: config.keyFile, name: 'keyFile' },
{ path: config.pfxFile, name: 'pfxFile' },
{ path: config.caFile, name: 'caFile' }
].filter(f => f.path);
for (const file of filesToCheck) {
if (!fs.existsSync(file.path!)) {
errors.push(`${file.name} not found: ${file.path}`);
}
}
// Check if encrypted files have passphrase
const certOrPfxFile = config.certFile || config.pfxFile;
if (certOrPfxFile && this.isEncryptedFile(certOrPfxFile)) {
if (!config.passphrase) {
errors.push('passphrase is required for encrypted certificate files');
}
}
// Validate timeout
if (config.timeout < 1000 || config.timeout > 300000) {
errors.push('timeout must be between 1000ms and 300000ms');
}
// FAIL STARTUP if any validation errors
if (errors.length > 0) {
const errorMessage = `❌ HTTPS client configuration errors:\n${errors.map(e => ` • ${e}`).join('\n')}`;
this.telemetry.error(errorMessage);
throw new Error(`Invalid HTTPS client configuration: ${errors.join('; ')}`);
}
}
private isEncryptedFile(filePath: string): boolean {
if (!filePath || !fs.existsSync(filePath)) return false;
try {
const content = fs.readFileSync(filePath, 'utf8');
return content.includes('ENCRYPTED') || content.includes('Proc-Type: 4,ENCRYPTED');
} catch {
return false; // Assume not encrypted if can't read
}
}
private setupHttpsAgent(): void {
const agentOptions: https.AgentOptions = {
rejectUnauthorized: this.validatedConfig.rejectUnauthorized,
keepAlive: this.validatedConfig.keepAlive,
};
try {
const certificates = this.loadCertificates();
if (certificates.ca) {
agentOptions.ca = certificates.ca;
this.telemetry.debug(`📋 Loaded CA certificate from ${this.validatedConfig.caFile}`);
}
if (certificates.cert && certificates.key) {
agentOptions.cert = certificates.cert;
agentOptions.key = certificates.key;
if (certificates.passphrase) {
agentOptions.passphrase = certificates.passphrase;
}
this.telemetry.debug(`🔑 Loaded client certificate from ${this.validatedConfig.certFile}`);
}
if (certificates.pfx) {
agentOptions.pfx = certificates.pfx;
if (certificates.passphrase) {
agentOptions.passphrase = certificates.passphrase;
}
this.telemetry.debug(`📦 Loaded PFX certificate from ${this.validatedConfig.pfxFile}`);
}
this.httpsAgent = new https.Agent(agentOptions);
} catch (error) {
const errorMessage = `Failed to setup HTTPS client: ${(error as Error).message}`;
this.telemetry.error(errorMessage);
throw new Error(errorMessage);
}
}
private loadCertificates(): CertificateData {
const config = this.validatedConfig;
const certificates: CertificateData = {};
try {
// Load CA certificate
if (config.caFile) {
certificates.ca = fs.readFileSync(config.caFile);
}
// Load client certificates (cert/key pair)
if (config.certFile && config.keyFile) {
certificates.cert = fs.readFileSync(config.certFile);
certificates.key = fs.readFileSync(config.keyFile);
if (config.passphrase) {
certificates.passphrase = config.passphrase;
}
}
// Load PFX certificate
if (config.pfxFile) {
certificates.pfx = fs.readFileSync(config.pfxFile);
if (config.passphrase) {
certificates.passphrase = config.passphrase;
}
}
return certificates;
} catch (error) {
throw new Error(`Failed to load certificate files: ${(error as Error).message}`);
}
}
}