-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
CrowdSecClient.ts
191 lines (164 loc) · 7.03 KB
/
CrowdSecClient.ts
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
import type { ICrowdSecClientOptions, IHTTPOptions, ITLSAuthentication } from '../interfaces/index.js';
import { pkg } from '../pkg.js';
import axios, { AxiosInstance } from 'axios';
import * as https from 'https';
import { createDebugger, getUrlRepresentation } from '../utils.js';
import { AxiosError, CrowdsecClientError, CrowdSecServerError, EErrorsCodes } from '../Errors/index.js';
import type { ErrorResponse } from '../types/index.js';
const debug = createDebugger('client');
const axiosDebug = createDebugger('axios');
const axiosDebugVerbose = axiosDebug.extend('verbose');
const defaultsHTTPOptions: Required<Required<Omit<ICrowdSecClientOptions, 'url'>>> = {
timeout: 2000,
userAgent: `node-${pkg.name}/v${pkg.version}`,
strictSSL: true
};
export abstract class CrowdSecClient {
protected debug = debug;
get http(): AxiosInstance {
return this._http;
}
private options: ICrowdSecClientOptions;
protected static http: AxiosInstance;
private readonly _http: AxiosInstance;
protected constructor(options: ICrowdSecClientOptions) {
this.options = options;
this._http = CrowdSecClient.getHTTPClient(this.options);
}
protected static getHTTPClient(options: IHTTPOptions): AxiosInstance {
const axiosOptions = {
...defaultsHTTPOptions,
...options
};
if (!options?.url) {
throw new CrowdsecClientError('options.url is needed to create a crowdsec client');
}
const baseURL = options.url.endsWith('/') ? options.url.slice(0, -1) : options.url;
return this.addAxiosDebugInterceptors(
axios.create({
baseURL,
timeout: axiosOptions.timeout,
httpsAgent: !axiosOptions.strictSSL
? new https.Agent({
rejectUnauthorized: false
})
: undefined,
headers: { 'User-Agent': axiosOptions.userAgent }
})
);
}
protected setAuthenticationByTLS(auth: ITLSAuthentication) {
this.http.defaults.httpsAgent = new https.Agent({
cert: auth.cert,
key: auth.key,
ca: auth.ca,
rejectUnauthorized: this.options.strictSSL ?? true
});
}
private static addAxiosDebugInterceptors(instance: AxiosInstance): AxiosInstance {
instance.interceptors.request.use((config) => {
// @ts-ignore
config.metadata = { startTime: new Date() };
axiosDebug(`Starting Request on url ${config.method} ${getUrlRepresentation(config)}`);
axiosDebugVerbose(`headers : %O`, config.headers);
axiosDebugVerbose(`payload : %O`, config.data);
return config;
});
instance.interceptors.response.use(
(response) => {
// @ts-ignore
const duration = (new Date() - response?.config?.metadata?.startTime) / 1000 || null;
const durationStr = duration ? ` in ${duration} seconds` : '';
axiosDebug(
`Response from ${response?.config?.method} ${getUrlRepresentation(
response?.config
)} with code ${response?.status} ${response?.statusText}${durationStr}`
);
axiosDebugVerbose('headers : %O', response?.headers);
axiosDebugVerbose(`payload : %O`, response?.data);
return response;
},
(error) => {
if (error?.response) {
const rep = error.response;
axiosDebug(
`Response from ${rep.config?.method} ${getUrlRepresentation(rep.config)} with code ${rep.status} ${rep.statusText}`
);
axiosDebugVerbose(`headers : %O`, rep.headers);
axiosDebugVerbose(`payload : %O`, rep.data);
} else {
if (error?.isAxiosError) {
axiosDebug(
`Response from ${error.config?.method} ${getUrlRepresentation(error.config)} with code ${error.code} ${
error.message
}`
);
}
}
throw error;
}
);
//add error handler
instance.interceptors.response.use(
(response) => response,
(error) => {
if (error?.response) {
const message =
(error.response.data as ErrorResponse)?.message ??
(error.response.data as ErrorResponse)?.errors ??
error.response.statusText ??
'Unknown HTTP Error';
// axios error will remove circular dependency + format a little the sub error
error = new CrowdSecServerError(message, error.response.status, error.response?.data?.errors, new AxiosError(error));
}
throw error;
}
);
return instance;
}
protected setAuthenticationHeaders(headers: Record<string, string>) {
Object.entries(headers).forEach(([key, value]) => (this._http.defaults.headers[key] = value));
}
public abstract login(): Promise<void>;
/**
* stop the current client, and running processes
*/
public abstract stop(): Promise<void>;
public abstract testConnection(): Promise<void>;
protected async _testConnection(url: string): Promise<void> {
const localDebug = this.debug.extend('testConnection');
try {
localDebug('call crowdsec');
const result = await this._http.head(url, {
validateStatus: () => true
});
localDebug('receive status %d from crowdsec', result.status);
switch (result.status) {
case 200:
localDebug('connection success');
return;
case 403:
throw new CrowdsecClientError(
'UNEXPECTED_KEY',
EErrorsCodes.CONNECTION_TEST_FAILED,
new Error('Crowdsec answer with code 403')
);
default:
throw new CrowdsecClientError(
'UNEXPECTED_STATUS_CODE',
EErrorsCodes.CONNECTION_TEST_FAILED,
new Error(`Crowdsec answer with (${result.status}) ${result.statusText}`)
);
}
} catch (e) {
if (e instanceof CrowdsecClientError) {
throw e;
}
localDebug('Error : %o', e);
if (axios.isAxiosError(e)) {
throw new CrowdsecClientError('HOST_NOT_REACHABLE', EErrorsCodes.CONNECTION_TEST_FAILED, e);
}
throw new CrowdsecClientError('UNKNOWN_ERROR', undefined, e instanceof Error ? e : undefined);
}
}
}