cloudflare/ts/cloudflare.classes.account.ts

286 lines
9.4 KiB
TypeScript
Raw Normal View History

import plugins = require('./cloudflare.plugins');
2020-06-10 05:15:22 +00:00
import { logger } from './cloudflare.logger';
2019-07-18 15:12:03 +00:00
import * as interfaces from './interfaces';
// interfaces
2019-07-18 09:51:56 +00:00
import { WorkerManager } from './cloudflare.classes.workermanager';
import { ZoneManager } from './cloudflare.classes.zonemanager';
export class CloudflareAccount {
2020-02-19 16:58:46 +00:00
private authToken: string;
2019-07-18 12:25:10 +00:00
private accountIdentifier: string;
2019-07-18 09:51:56 +00:00
public workerManager = new WorkerManager(this);
public zoneManager = new ZoneManager(this);
2019-07-18 12:25:10 +00:00
/**
* constructor sets auth information on the CloudflareAccountInstance
* @param optionsArg
*/
2020-02-19 16:58:46 +00:00
constructor(authTokenArg: string) {
2020-02-28 14:47:03 +00:00
this.authToken = authTokenArg;
}
/**
* gets you the account identifier
*/
2019-07-18 12:25:10 +00:00
public async getAccountIdentifier() {
2019-07-18 15:12:03 +00:00
if (!this.accountIdentifier) {
const route = `/accounts?page=1&per_page=20&direction=desc`;
const response: any = await this.request('GET', route);
this.accountIdentifier = response.result[0].id;
}
2019-07-18 12:25:10 +00:00
return this.accountIdentifier;
}
2020-02-28 14:24:36 +00:00
public convenience = {
/**
2020-02-28 14:47:03 +00:00
* gets a zone id of a domain from cloudflare
* @param domainName
*/
getZoneId: async (domainName: string) => {
const domain = new plugins.smartstring.Domain(domainName);
const zoneArray = await this.convenience.listZones(domain.zoneName);
2021-01-22 20:46:26 +00:00
const filteredResponse = zoneArray.filter((zoneArg) => {
2020-02-28 14:47:03 +00:00
return zoneArg.name === domainName;
});
if (filteredResponse.length >= 1) {
return filteredResponse[0].id;
} else {
2020-06-10 05:34:47 +00:00
logger.log('error', `the domain ${domainName} does not appear to be in this account!`);
2020-02-28 14:47:03 +00:00
throw new Error(`the domain ${domainName} does not appear to be in this account!`);
}
},
/**
* gets a record
* @param domainNameArg
* @param typeArg
*/
getRecord: async (
domainNameArg: string,
2020-02-19 14:16:23 +00:00
typeArg: plugins.tsclass.network.TDnsRecordType
): Promise<interfaces.ICflareRecord> => {
const domain = new plugins.smartstring.Domain(domainNameArg);
const recordArrayArg = await this.convenience.listRecords(domain.zoneName);
2021-01-22 20:46:26 +00:00
const filteredResponse = recordArrayArg.filter((recordArg) => {
return recordArg.type === typeArg && recordArg.name === domainNameArg;
});
return filteredResponse[0];
},
/**
* creates a record
*/
createRecord: async (
domainNameArg: string,
2020-02-19 14:16:23 +00:00
typeArg: plugins.tsclass.network.TDnsRecordType,
2021-01-22 20:45:35 +00:00
contentArg: string,
ttlArg = 1
): Promise<any> => {
const domain = new plugins.smartstring.Domain(domainNameArg);
2020-02-28 14:24:36 +00:00
const domainIdArg = await this.convenience.getZoneId(domain.zoneName);
const dataObject = {
name: domain.fullName,
type: typeArg,
2021-01-22 20:45:35 +00:00
content: contentArg,
2021-01-22 20:46:26 +00:00
ttl: ttlArg,
};
const response = await this.request(
'POST',
'/zones/' + domainIdArg + '/dns_records',
dataObject
);
return response;
},
/**
* removes a record from Cloudflare
* @param domainNameArg
* @param typeArg
*/
removeRecord: async (
domainNameArg: string,
2020-02-19 14:16:23 +00:00
typeArg: plugins.tsclass.network.TDnsRecordType
): Promise<any> => {
const domain = new plugins.smartstring.Domain(domainNameArg);
const cflareRecord = await this.convenience.getRecord(domain.fullName, typeArg);
if (cflareRecord) {
const requestRoute: string = `/zones/${cflareRecord.zone_id}/dns_records/${cflareRecord.id}`;
return await this.request('DELETE', requestRoute);
} else {
throw new Error(`could not remove record for ${domainNameArg} with type ${typeArg}`);
}
},
2020-02-10 11:26:13 +00:00
/**
* cleanrecord allows the cleaning of any previous records to avoid unwanted sideeffects
*/
2020-02-19 14:16:23 +00:00
cleanRecord: async (domainNameArg: string, typeArg: plugins.tsclass.network.TDnsRecordType) => {
console.log(`cleaning record for ${domainNameArg}`);
2020-02-10 14:40:55 +00:00
},
/**
* updates a record
* @param domainNameArg
* @param typeArg
* @param valueArg
*/
2020-02-28 14:47:03 +00:00
updateRecord: async (
domainNameArg: string,
typeArg: plugins.tsclass.network.TDnsRecordType,
valueArg
) => {
// TODO: implement
const domain = new plugins.smartstring.Domain(domainNameArg);
},
/**
* list all records of a specified domain name
* @param domainNameArg - the domain name that you want to get the records from
*/
listRecords: async (domainNameArg: string): Promise<interfaces.ICflareRecord[]> => {
const domain = new plugins.smartstring.Domain(domainNameArg);
2020-02-28 14:24:36 +00:00
const domainId = await this.convenience.getZoneId(domain.zoneName);
const responseArg: any = await this.request(
'GET',
'/zones/' + domainId + '/dns_records?per_page=100'
);
const result: interfaces.ICflareRecord[] = responseArg.result;
return result;
},
/**
* list all zones in the associated authenticated account
* @param domainName
*/
listZones: async (domainName?: string): Promise<interfaces.ICflareZone[]> => {
// TODO: handle pagination
let requestRoute = `/zones?per_page=50`;
// may be optionally filtered by domain name
if (domainName) {
requestRoute = `${requestRoute}&name=${domainName}`;
}
const response: any = await this.request('GET', requestRoute);
const result = response.result;
return result;
},
/**
* purges a zone
*/
purgeZone: async (domainName: string): Promise<void> => {
const domain = new plugins.smartstring.Domain(domainName);
2020-02-28 14:24:36 +00:00
const domainId = await this.convenience.getZoneId(domain.zoneName);
const requestUrl = `/zones/${domainId}/purge_cache`;
const payload = {
2021-01-22 20:46:26 +00:00
purge_everything: true,
};
const respone = await this.request('DELETE', requestUrl, payload);
2020-02-10 11:26:13 +00:00
},
// acme convenience functions
acmeSetDnsChallenge: async (dnsChallenge: plugins.tsclass.network.IDnsChallenge) => {
2020-02-10 14:40:55 +00:00
await this.convenience.cleanRecord(dnsChallenge.hostName, 'TXT');
2021-01-22 21:12:42 +00:00
await this.convenience.createRecord(dnsChallenge.hostName, 'TXT', dnsChallenge.challenge, 120);
2020-02-10 11:26:13 +00:00
},
acmeRemoveDnsChallenge: async (dnsChallenge: plugins.tsclass.network.IDnsChallenge) => {
await this.convenience.removeRecord(dnsChallenge.hostName, 'TXT');
2021-01-22 20:46:26 +00:00
},
};
2020-02-28 14:24:36 +00:00
public async request(
2019-07-18 15:12:03 +00:00
methodArg: string,
routeArg: string,
dataArg: any = {},
requestHeadersArg = {}
): Promise<any> {
2019-07-18 09:51:56 +00:00
const options: plugins.smartrequest.ISmartRequestOptions = {
method: methodArg,
headers: {
'Content-Type': 'application/json',
2020-02-28 14:47:03 +00:00
Authorization: `Bearer ${this.authToken}`,
2019-07-18 12:25:10 +00:00
'Content-Length': Buffer.byteLength(JSON.stringify(dataArg)),
2021-01-22 20:46:26 +00:00
...requestHeadersArg,
},
2021-01-22 20:46:26 +00:00
requestBody: dataArg,
};
2020-02-28 14:47:03 +00:00
// route analysis
const routeWithoutQuery = routeArg.split('?')[0];
let queryParams: string[] = [];
if (routeArg.split('?').length > 1) {
queryParams = routeArg.split('?')[1].split('&');
}
2019-07-18 12:25:10 +00:00
// console.log(options);
let retryCount = 0; // count the amount of retries
2020-02-28 14:24:36 +00:00
let pageCount = 1;
2020-02-28 14:47:03 +00:00
const getQueryParams = () => {
let result = '';
if (queryParams.length > 0) {
result += '?';
} else {
return result;
}
let isFirst = true;
for (const queryParam of queryParams) {
if (!isFirst) {
result += '&';
}
isFirst = false;
const queryParamSerialized = queryParam.split('=');
if (queryParam === 'page') {
result += `page=${pageCount}`;
} else {
result += queryParam;
}
}
return result;
};
2020-02-28 14:24:36 +00:00
const makeRequest = async (): Promise<plugins.smartrequest.IExtendedIncomingMessage> => {
2020-02-28 14:47:03 +00:00
const requestUrl = `https://api.cloudflare.com/client/v4${routeWithoutQuery}${getQueryParams()}`;
const response = await plugins.smartrequest.request(requestUrl, options);
if (response.statusCode === 200) {
2020-02-28 14:47:03 +00:00
if (response.body.result_info) {
2020-02-28 14:24:36 +00:00
const rI = response.body.result_info;
2020-02-28 14:47:03 +00:00
if (rI.total_count / rI.per_page > pageCount) {
2020-02-28 14:24:36 +00:00
pageCount++;
2020-02-28 14:47:03 +00:00
const subresponse = await makeRequest();
response.body.result = response.body.result.concat(subresponse.body.result);
return response;
2020-02-28 14:24:36 +00:00
} else {
return response;
}
} else {
return response;
}
} else if (response.statusCode === 429) {
console.log('rate limited! Waiting for retry!');
2020-02-28 14:24:36 +00:00
return await retryRequest();
} else if (response.statusCode === 400) {
2020-02-28 14:47:03 +00:00
console.log(`bad request for route ${requestUrl}!`);
2019-07-18 12:25:10 +00:00
console.log(response.body);
2020-02-28 14:47:03 +00:00
throw new Error(`request failed for ${requestUrl}`);
} else {
2020-02-28 14:55:33 +00:00
console.log(response.body);
2020-02-28 14:57:41 +00:00
throw new Error(`request failed for ${requestUrl} with status${response.statusCode}}`);
}
};
2020-02-28 14:24:36 +00:00
2019-07-18 09:51:56 +00:00
const retryRequest = async (
delayTimeArg = Math.floor(Math.random() * (60000 - 8000) + 8000)
) => {
console.log(`retry started and waiting for ${delayTimeArg} ms`);
await plugins.smartdelay.delayFor(delayTimeArg);
if (retryCount < 10) {
retryCount++;
return await makeRequest();
}
};
2020-02-28 14:24:36 +00:00
const response = await makeRequest();
return response.body;
}
private authCheck() {
2020-02-19 16:58:46 +00:00
return !!this.authToken; // check if auth is available
}
}