-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathccc-configuration.js
296 lines (255 loc) · 7.95 KB
/
ccc-configuration.js
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
const debug = require('debug')('cdn-cache-check-configuration');
debug('Entry: [%s]', __filename);
// The name of the configuration file
const configFile = 'configuration.json'
// Command line options parser
const argv = require('yargs').help(false).argv;
// Initialise console colours
const chalk = require('chalk');
// Initialise default settings
let defaultSettings = {};
try {
defaultSettings = require('./configuration.json'); // Load the defaults
} catch (error) {
debug('An error occurred loading the %s file: %O', configFile, error);
// The configuration file didn't load. Return a bare and very basic config
defaultSettings = {
method: 'get',
headersCollection: 'default',
serviceDetection: true,
IPScan: true,
headersCollections: [
{
default: [
'x-cache',
'cache-control',
'server',
'content-encoding',
'vary',
'age',
],
},
],
ApexDomains: {},
options: {
exportToCSV: true,
openAfterExport: false,
headers: {
'user-agent': 'ccc/{version} {OS}/{OSRelease}',
Connection: 'close',
},
httpOptions: {
timeout: 6000,
response_timeout: 6000,
read_timeout: 6000,
follow: 5,
compressed: true,
},
verbose: false,
},
};
}
function getSettings() {
debug('Entry::getSettings()');
// Load the defaults
let settings = defaultSettings;
debug('Loaded default settings: %O', settings);
try {
// Check command line parameters for overrides...
debug('Looking for command line switches that override default settings');
// Header Collection
if (argv.headers) {
// ** We should validate the specified collection actually exists **
settings.headersCollection = argv.headers;
debug(
'Using the specified Headers Collection: %s',
settings.headersCollection,
);
} else {
debug(
'Using the default Headers Collection: %s',
settings.headersCollection,
);
}
// Load the headers collections into the Settings object
settings.headerCollection = this.getHeaderCollection(
settings.headersCollection,
settings,
);
// Extract HTTP Method
if (argv.method) {
// Create array of supported HTTP methods
const HTTPMethods = [
'get',
'head',
'options',
'put',
'patch',
'delete',
'trace',
'connect',
];
if (HTTPMethods.includes(argv.method.toLowerCase())) {
settings.method = argv.method.toLowerCase();
debug('Setting HTTP method to: %s', settings.method);
} else {
console.log(
chalk.blue(
'Warning: %s is not a supported HTTP method. Using %s instead.',
argv.method.toUpperCase(),
settings.method.toUpperCase(),
),
);
}
}
// Number of HTTP redirects to follow
if (argv.follow !== undefined) {
// Validate that an integer was specified
if (Number.isInteger(argv.follow)) {
settings.options.httpOptions.follow = argv.follow;
debug(
'The number of HTTP redirects to follow is set to %s',
settings.options.httpOptions.follow,
);
if (settings.options.httpOptions.follow === 0) {
console.log(chalk.blue('HTTP redirects will not be followed'));
}
} else {
console.log(
chalk.yellow(
'Warning: Ignoring "--follow %s" because "follow" must be an integer specifying the number of chained HTTP redirects to follow. Using the default %s instead',
),
argv.follow,
settings.options.httpOptions.follow,
);
}
}
// Check for list-response-headers argument
if (argv.listResponseHeaders) {
settings.listResponseHeaders = true;
// We can switch off the CDN detection output because we're just listing response headers
settings.serviceDetection = false;
} else {
settings.listResponseHeaders = false;
}
// Check for '--open' argument
if (argv.open) {
settings.options.openAfterExport = true;
}
// Check for '--verbose' argument
if (argv.verbose) {
settings.options.verbose = true;
}
// Check for '--export false' argument
if (argv.export) {
if (typeof argv.export === 'string') {
if (argv.export.toLowerCase() === 'false') {
settings.options.exportToCSV = false;
// Switch off openAfterExport because we're not exporting anything
settings.options.openAfterExport = true;
}
}
}
// Check for '--ipscan false' argument
if (argv.ipscan) {
if (typeof argv.ipscan === 'string') {
if (argv.ipscan.toLowerCase() === 'false') {
settings.IPScan = false;
}
}
}
// Use a client specific customised user-agent string
// settings.options.headers['user-agent'] = this.getUserAgent();
settings.options.httpOptions.user_agent = this.getUserAgent();
debug('Using the user-agent: %s', settings.options.httpOptions.user_agent);
return settings;
} catch (error) {
console.error(`${chalk.redBright('An error occurred in getSettings()')} - ${error.message}`);
debug(error);
return settings;
}
}
function getHeaderCollection(collectionName, settings) {
debug('getHeaderCollection() is retrieving a collection named [%s]', collectionName);
// Iterate through each header collection definition
for (let i = 0; i < settings.headersCollections.length; i++) {
// Get the current (i) collection name, which will be the first (index 0) key name in the array
let currentCollection = Object.keys(settings.headersCollections[i])[0];
// Check if its name matches the supplied one
if (collectionName.toLowerCase() === currentCollection.toLowerCase()) {
// Return the array of headers
let headerCollection = settings.headersCollections[i][currentCollection];
debug('Returning header collection [%s]: %O', collectionName, headerCollection);
return (headerCollection);
}
}
// If we get here then no matches were found.
// Perhaps return something that will collect all headers - return (['*']);
console.log(
chalk.blue('WARNING: The requested header collection ') +
collectionName +
chalk.blue(' does not exist'),
);
return [];
}
function getHeaderCollections() {
debug('getHeaderCollections():: Entry');
// Extract the headersCollections array
let headersCollections = defaultSettings.headersCollections;
debug('Returning: %O', headersCollections);
return headersCollections;
}
function displayHeaderCollections(headerCollections) {
debug('displayHeaderCollections():: Entry');
// Initialise prettyJson object, to format output
let prettyJson = require('prettyjson');
// Output the formatted json contained within each array element
headerCollections.forEach((element) => console.log(prettyJson.render(element)));
}
function getUserAgent() {
try {
// Load package.json for the version number etc
const npmPackage = require('./package.json');
// Load O/S module to get client specifics
const os = require('os');
// Extract default user-agent string from default config
let userAgent = defaultSettings.options.headers['user-agent'];
// Replace embedded variables with platform specifics
userAgent = userAgent.replace('{version}', npmPackage.version);
userAgent = userAgent.replace('{OS}', os.type());
userAgent = userAgent.replace('{OSRelease}', os.release());
return userAgent;
} catch (error) {
debug('getUserAgent() caught an error: %O', error);
return global.CCC_DEFAULT_USERAGENT;
}
}
function displayConfigFileLocation() { // Display config file location
// Platform independent new line character and path separator
const EOL = require('os').EOL;
const pathSeparator = require('path').sep;
// Configuration file exists in the same directory as the main application __dirname
let configFilePath = `${__dirname}${pathSeparator}${configFile}`;
console.log(EOL + chalk.grey('Config file:') + chalk.yellowBright(configFilePath));
}
function initResponseObject() {
let defaultResponseObject = {
error: false,
statusCode: 0,
request: {},
response: {},
redirectCount: 0,
ipAddress: null,
ipFamily: null
};
return (defaultResponseObject);
}
module.exports = {
displayConfigFileLocation,
displayHeaderCollections,
getHeaderCollection,
getSettings,
getUserAgent,
getHeaderCollections,
initResponseObject
};