-
Notifications
You must be signed in to change notification settings - Fork 42
/
index.js
618 lines (585 loc) · 17 KB
/
index.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
const _ = require('lodash');
const fs = require('fs');
/**
*
* @param options
* @constructor
*/
function CloudflareCli(options) {
const requiredOptions = ['token'];
let self = this;
self.email = null;
self.key = null;
self.perPage = 50;
let CloudFlareClient = require('./lib/apiClient');
let format = require('util').format;
let formatters = require('./lib/formatters');
/**
* Available commands
* @type {Object}
*/
const commands = {
add: {
aliases: ['add', 'addrecord'],
shortcut: 'a',
callback: addRecord,
description: 'Add a new record',
params: ['name', 'content'],
optionalParams: [],
mergeAdditionalParams: true,
formatter: new formatters.MessageFormatter()
},
alwaysUseHttps: {
aliases: ['always-use-https'],
shortcut: 'https',
callback: toggleAlwaysUseHttps,
params: ['mode'],
optionalParams: [],
description: "Redirect all requests with scheme 'http' to 'https'",
formatter: new formatters.MessageFormatter()
},
devmode: {
aliases: ['devmode'],
shortcut: 'dev',
callback: toggleDevMode,
params: ['mode'],
optionalParams: [],
description: "Turn dev mode on or off",
formatter: new formatters.MessageFormatter()
},
disable: {
aliases: ['disable', 'disablecf', 'disablecache', 'disableproxy'],
shortcut: 'dis',
callback: disableProxy,
description: 'Disable Cloudflare caching for given record',
params: ['name'],
optionalParams: ['content'],
formatter: new formatters.MessageFormatter()
},
edit: {
aliases: ['edit', 'editrecord'],
shortcut: 'e',
callback: editRecord,
description: 'Edit a DNS record',
params: ['name', 'content'],
optionalParams: [],
formatter: new formatters.MessageFormatter()
},
enable: {
aliases: ['enable', 'enablecf', 'enablecache', 'enableproxy'],
shortcut: 'en',
callback: enableProxy,
description: 'Enable Cloudflare caching for given record',
params: ['name'],
optionalParams: ['content'],
formatter: new formatters.MessageFormatter()
},
find: {
aliases: ['find', 'findrecord'],
shortcut: 'f',
callback: findRecord,
description: 'Find a record',
params: ['name'],
optionalParams: ['content'],
formatter: new formatters.TableFormatter({
head: ['Type', 'Name', 'Value', 'TTL', 'Active', 'ID'],
colWidths: [8, 40, 50, 10, 8, 34],
values: ['type', 'name', 'content', 'ttl', 'proxied', 'id']
})
},
help: {
aliases: ['help'],
shortcut: 'h',
params: [],
callback: showHelp,
description: 'Show help',
formatter: new formatters.MessageFormatter()
},
purge: {
aliases: ['purge', 'purgefile', 'purgecache'],
shortcut: 'p',
callback: purgeCache,
params: [],
description: 'Purge files from cache'
},
rm: {
aliases: ['rm', 'remove', 'removerecord'],
shortcut: 'r',
callback: removeRecord,
description: 'Remove a record',
params: ['name'],
optionalParams: ['content'],
formatter: new formatters.MessageFormatter()
},
ls: {
aliases: ['ls', 'listrecords', 'list'],
shortcut: 'l',
callback: listRecords,
params: [],
optionalParams: [],
description: 'List records for given domain',
formatter: new formatters.TableFormatter({
head: ['Type', 'Name', 'Value', 'TTL', 'Active', 'ID'],
colWidths: [8, 40, 50, 10, 8, 34],
values: ['type', 'name', 'content', 'ttl', 'proxied', 'id']
})
},
zoneAdd: {
aliases: ['zone-add', 'add-zone', 'addzone'],
shortcut: 'za',
callback: addZone,
description: 'Add a new zone to your Cloudflare account',
params: ['name'],
optionalParams: [],
formatter: new formatters.MessageFormatter()
},
//TODO uncomment once guard is in place for deleting zones
// zoneRm: {
// aliases: ['zone-rm', 'removezone', 'rmzone'],
// shortcut: 'zr',
// callback: removeZone,
// description: 'Remove a zone from your Cloudflare account',
// params: ['name'],
// optionalParams: [],
// formatter: new formatters.MessageFormatter()
// },
zones: {
aliases: ['zone-ls', 'zones', 'listdomains', 'listzones'],
shortcut: 'z',
callback: listZones,
params: [],
description: 'List zones in your cloudflare account',
formatter: new formatters.TableFormatter({
head: ['Name', 'Plan', 'Active', 'ID', 'Account'],
colWidths: [50, 20, 10, 40, 40],
values: ['name', 'planName', 'status', 'id', 'accountName']
})
}
};
self.runCommand = runCommand;
self.addRecord = addRecord;
self.disableProxy = disableProxy;
self.editRecord = editRecord;
self.enableProxy = enableProxy;
self.findRecord = findRecord;
self.listRecords = listRecords;
self.addZone = addZone;
self.removeZone = removeZone;
self.listZones = listZones;
self.purgeCache = purgeCache;
self.removeRecord = removeRecord;
self.showHelp = showHelp;
self.toggleDevMode = toggleDevMode;
self.toggleAlwaysUseHttps = toggleAlwaysUseHttps;
init(options);
/**
* Set up client
* @param options
*/
function init(options) {
self.email = options.email;
self.key = options.token;
self.cloudflareClient = new CloudFlareClient(options.token, options.email);
}
/**
* Run the given command and output the result
* @param command
* @param options
*/
function runCommand(command, options) {
let cmd = getCommand(command);
if (!cmd || command === 'help') {
cmd = getCommand('help');
} else {
try {
validateConfig(options);
} catch (error) {
console.log(error.message);
process.exit(1);
}
}
let fn = cmd.callback;
let opts = mapParams(cmd, options);
fn(opts).then(function (result) {
if (cmd.formatter) {
cmd.formatter.format(result.messages, options);
} else {
console.log(result);
}
}).catch(function (error) {
let formatter = new formatters.MessageFormatter();
//Log error from server if provided in the response
if (error.response && error.response.data.errors) {
formatter.format([`Error response received: ${error.response.data.errors[0].message}`]);
} else if (error.message) {
formatter.format([`Error when communicating with api: ${error.message}`]);
} else {
formatter.format([`Error: ${error}`]);
}
process.exit(1);
});
}
/**
* Create a new record of the given type
* @param options
* @return {*}
*/
function addRecord(options) {
options.type = options.type || 'CNAME';
return getZone(options.domain)
.then(function (zone) {
return self.cloudflareClient.addRecord(
zone.id,
_.extend({ttl: 1}, mapRecordOptions(options)));
})
.then(function (response) {
return new Result([
format(
'Added %s record %s -> %s',
response.data.result.type,
response.data.result.name,
response.data.result.content
)
]);
}
)
}
/**
* Enable/disable Always Use HTTPS mode
* @param options
*/
function toggleAlwaysUseHttps(options) {
return getZone(options.domain).then(function (zone) {
return self.cloudflareClient.setAlwaysUseHttps(zone.id, options.mode);
}).then(function () {
return new Result(['Always Use HTTPS mode changed to ' + options.mode]);
})
}
/**
* Enable proxying/caching for given record
* @param options
* @return {Promise}
*/
function enableProxy(options) {
options.activate = true;
return editRecord(options);
}
/**
* Disable proxying/caching for given record
* @param options
* @return {Promise}
*/
function disableProxy(options) {
options.activate = false;
return editRecord(options);
}
/**
* Edit a record
* @param options
* @returns {Promise}
*/
function editRecord(options) {
return find(options.domain, getQueryParams(options, ['name', 'type', 'query'])).then(function (response) {
const records = response.data.result;
//Properties that are editable
options = mapRecordOptions(options);
if (records.length === 0) {
throw new Error('No matching records found');
} else if (records.length === 1) {
let record = records[0];
options.type = options.type || record.type;
options.content = options.content || record.content;
return self.cloudflareClient.editRecord(record.zone_id, record.id, options);
} else {
throw new Error(format('%d matching records found, unable to update', records.count));
}
}).then(function (response) {
let record = response.data.result;
return new Result([
format('Updated %s record %s (id: %s)', record.type, record.name, record.id)
]);
});
}
/**
* Remove a record/record(s) matching the given name
* @param options
*/
function removeRecord(options) {
let query = getQueryParams(options, ['name', 'content', 'type', 'query']);
if (query.name === undefined) {
return Promise.reject('name not provided');
}
return find(options.domain, query).then(function (response) {
let records = response.data.result;
if (records.length === 0) {
throw new Error('No matching records found');
}
let results = [];
_.each(records, function (record) {
results.push(self.cloudflareClient.removeRecord(record.zone_id, record.id));
});
return Promise.all(results);
}).then(function (responses) {
let messages = _.map(responses, function (response) {
return 'Deleted record with id ' + response.data.result.id;
});
return new Result(messages);
});
}
/**
* Find command
* @param options
* @returns {Promise}
*/
function findRecord(options) {
let query = getQueryParams(options, ['name', 'content', 'type', 'query']);
return find(options.domain, query).then(function (result) {
return new Result(result.data.result);
});
}
/**
* Find a given record
* @param domain
* @param query
* @return {Promise}
*/
function find(domain, query) {
if (query.name && !query.name.includes(domain)) {
query.name = query.name + '.' + domain;
}
if (query.query) {
query = _.extend(query, query.query);
delete query.query;
}
return getZone(domain).then(function (zone) {
return self.cloudflareClient.findRecord(zone.id, query);
});
}
/**
* List records for given domain
* @param options
* @returns {Promise}
*/
function listRecords(options) {
return getZone(options.domain).then(function (zone) {
return self.cloudflareClient.findRecord(zone.id, {page: 1, per_page: self.perPage})
.then(function (response) {
let promises = [Promise.resolve(response)];
for (let i = 2; i <= response.data['result_info']['total_pages']; i++) {
promises.push(self.cloudflareClient.findRecord(zone.id, {page: i, per_page: self.perPage}));
}
return Promise.all(promises);
});
}).then(function (responses) {
let rows = [];
_.each(responses, function (response) {
_.each(response.data.result, function (item) {
item.ttl = (item.ttl === 1) ? 'Auto' : item.ttl;
rows.push(item);
});
});
return new Result(rows);
});
}
/**
*
* @param options
* @returns {PromiseLike<Result> | Promise<Result>}
*/
function addZone(options) {
return self.cloudflareClient.addZone(options.name).then(function (response) {
return new Result([
format(
'Added zone %s',
response.data.result.name
)
]);
});
}
/**
*
* @param options
* @returns {Promise<any>}
*/
function removeZone(options) {
return getZone(options.name).then(function (zone) {
return self.cloudflareClient.removeZone(zone.id);
}).then(function (response) {
return new Result(['Deleted zone with id ' + response.data.result.id]);
});
}
/**
* List zones in the current account
* @return {Promise}
*/
function listZones() {
return self.cloudflareClient.findZones({page: 1, per_page: self.perPage})
.then(function (response) {
let promises = [Promise.resolve(response)];
for (let i = 2; i <= response.data['result_info']['total_pages']; i++) {
promises.push(self.cloudflareClient.findZones({page: i, per_page: self.perPage}));
}
return Promise.all(promises);
})
.then(function (responses) {
let rows = [];
_.each(responses, function (response) {
_.each(response.data.result, function (item) {
rows.push(_.extend(
item,
{
planName: item.plan.name,
accountName: item.account.name
}
));
})
});
return new Result(rows);
});
}
/**
* Enable/disable dev mode
* @param options
*/
function toggleDevMode(options) {
return getZone(options.domain).then(function (zone) {
//Use alternate api client
return self.cloudflareClient.setDevelopmentMode(zone.id, options.mode);
}).then(function () {
return new Result(['Dev mode changed to ' + options.mode]);
})
}
/**
* Purge files from cache
* @param options
* @returns {Promise}
*/
function purgeCache(options) {
return getZone(options.domain).then(function (zone) {
let query = (options._[1]) ? {files: options._.slice(1)} : {purge_everything: true};
return self.cloudflareClient.purgeCache(zone.id, query);
}).then(function () {
return new Result('Purged cache successfully');
});
}
/**
*
* @param zoneName {String}
* @returns {Promise}
*/
function getZone(zoneName) {
return self.cloudflareClient.findZones({name: zoneName}).then(function (response) {
return response.data.result[0];
});
}
/**
* Display Help
* @return {Promise}
*/
function showHelp() {
return Promise.resolve(new Result([fs.readFileSync(__dirname + '/doc/help.txt', 'utf8')]));
}
/**
* Get command from available commands by name
* @param commandName
* @return {Object}
*/
function getCommand(commandName) {
return _.find(commands, function (command) {
return _.includes(command.aliases, commandName);
});
}
/**
*
* @param cmd
* @param params
* @return {Object}
*/
function mapParams(cmd, params) {
let query = [];
if (cmd.mergeAdditionalParams && params._ !== undefined) {
let paramCount = cmd.params.length + cmd.optionalParams.length;
params._[paramCount] = _.slice(params._, paramCount).join(' ');
}
//Process query option
if (params.query) {
query = params.query.split(',');
params.query = _.fromPairs(
_.map(query,
function (filter) {
return filter.split(':');
}
)
);
}
return _.extend(params, _.fromPairs(_.zip(cmd.params.concat(cmd.optionalParams), _.drop(params._, 1))));
}
/**
* Map options to parameters when adding or editing records
* @param options
* @return {*}
*/
function mapRecordOptions(options) {
if (options.type === 'SRV') {
let contentParts = options.content.split(' ');
let serverParts = options.name.split('.');
options.data = {
service: serverParts[0],
proto: serverParts[1],
name: _.slice(serverParts, 2).join('.'),
priority: parseInt(contentParts[0]),
weight: parseInt(contentParts[1]),
port: parseInt(contentParts[2]),
target: contentParts[3]
}
}
if (options.activate !== undefined) {
options.proxied = options.activate;
}
if (options.name !== undefined) {
options.name = _.toString(options.name);
}
options = _.omit(options, ['domain', 'email', 'token', '_', 'activate', 'a']);
return options;
}
/**
*
* @param options
* @param allowed
*/
function getQueryParams(options, allowed) {
return _(options).pick(allowed)
.omitBy(_.isUndefined)
.mapValues((val) => {
if (val instanceof Object) {
return val;
} else {
return _.toString(val);
}
}).value();
}
/**
* Check that required config is set
* @param config
*/
function validateConfig(config) {
let missing = [];
_.each(requiredOptions, function (option) {
if (config[option] === undefined) {
missing.push(option);
}
});
if (missing.length > 0) {
throw new Error('The following required parameters were not provided: ' + missing.join(','));
}
}
}
/**
*
* @param messages
* @constructor
*/
function Result(messages) {
this.messages = messages;
}
module.exports = CloudflareCli;