Compare commits

..

41 Commits

Author SHA1 Message Date
a4e280f9f0 5.0.4 2020-02-28 14:57:42 +00:00
52bd80aebd fix(core): update 2020-02-28 14:57:41 +00:00
15e3cdae83 5.0.3 2020-02-28 14:55:34 +00:00
c72147b469 fix(core): update 2020-02-28 14:55:33 +00:00
d98c2f89c5 5.0.2 2020-02-28 14:47:04 +00:00
2b722816f6 fix(core): update 2020-02-28 14:47:03 +00:00
91d58277dd 5.0.1 2020-02-28 14:24:37 +00:00
2458da6754 fix(core): update 2020-02-28 14:24:36 +00:00
d4379d19d3 5.0.0 2020-02-19 17:00:32 +00:00
b0fdd520f3 BREAKING CHANGE(account): authorization now uses the new Account API 2020-02-19 17:00:31 +00:00
a746577945 4.0.5 2020-02-19 16:58:47 +00:00
bc4cae3333 fix(core): update 2020-02-19 16:58:46 +00:00
e0614b5956 4.0.4 2020-02-19 14:16:24 +00:00
f568949085 fix(core): update 2020-02-19 14:16:23 +00:00
bee256416f 4.0.3 2020-02-10 14:40:56 +00:00
afa2679501 fix(core): update 2020-02-10 14:40:55 +00:00
7838642fd5 4.0.2 2020-02-10 14:38:45 +00:00
7a992badf4 fix(core): update 2020-02-10 14:38:44 +00:00
c65790e2f9 4.0.1 2020-02-10 11:26:13 +00:00
7ec0fe78fc fix(core): update 2020-02-10 11:26:13 +00:00
12f4456ebd 4.0.0 2020-02-09 18:22:35 +00:00
3e8cf73877 BREAKING CHANGE(API): move to .convenience property 2020-02-09 18:22:34 +00:00
0032292714 3.0.7 2020-02-09 17:54:34 +00:00
ead87ceb63 fix(core): update 2020-02-09 17:54:33 +00:00
04d70a4d12 3.0.6 2020-02-09 17:36:30 +00:00
8da43a79d3 fix(core): update 2020-02-09 17:36:29 +00:00
3153021190 3.0.5 2019-07-19 12:39:40 +02:00
82701c19e7 fix(core): update 2019-07-19 12:39:39 +02:00
d3a68b4fef 3.0.4 2019-07-18 17:17:49 +02:00
c4c1367306 fix(core): update 2019-07-18 17:17:48 +02:00
1f5352d9f5 3.0.3 2019-07-18 17:12:04 +02:00
f652cc72fe fix(core): update 2019-07-18 17:12:03 +02:00
f510408fce 3.0.2 2019-07-18 15:31:25 +02:00
e250e9b1a2 fix(core): update 2019-07-18 15:31:24 +02:00
5a9b7bbeee 3.0.1 2019-07-18 14:44:45 +02:00
1158b4ff99 fix(core): update 2019-07-18 14:44:45 +02:00
8eb777dd45 3.0.0 2019-07-18 14:25:40 +02:00
acf5c242d3 2.0.2 2019-07-18 14:25:10 +02:00
9e9dd8d935 fix(core): update 2019-07-18 14:25:10 +02:00
b7cc500f4d 2.0.1 2019-07-18 11:51:57 +02:00
8a4126a49c fix(core): update 2019-07-18 11:51:56 +02:00
23 changed files with 2013 additions and 836 deletions

22
.gitignore vendored
View File

@ -1,6 +1,22 @@
.nogit/
# artifacts
coverage/ coverage/
docs/ public/
pages/
# installs
node_modules/ node_modules/
.nogit/ # caches
nogit/ .yarn/
.cache/
.rpt2_cache
# builds
dist/
dist_web/
dist_serve/
dist_ts_web/
# custom

View File

@ -1,16 +1,16 @@
# gitzone standard # gitzone ci_default
image: hosttoday/ht-docker-node:npmci image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache: cache:
paths: paths:
- .npmci_cache/ - .npmci_cache/
key: "$CI_BUILD_STAGE" key: '$CI_BUILD_STAGE'
stages: stages:
- security - security
- test - test
- release - release
- metadata - metadata
# ==================== # ====================
# security stage # security stage
@ -18,109 +18,103 @@ stages:
mirror: mirror:
stage: security stage: security
script: script:
- npmci git mirror - npmci git mirror
tags: tags:
- docker - lossless
- notpriv - docker
- notpriv
snyk: snyk:
image: registry.gitlab.com/hosttoday/ht-docker-node:snyk
stage: security stage: security
script: script:
- npmci command npm install -g snyk - npmci npm prepare
- npmci command npm install --ignore-scripts - npmci command npm install --ignore-scripts
- npmci command snyk test - npmci command snyk test
tags: tags:
- docker - lossless
- notpriv - docker
- notpriv
# ==================== # ====================
# test stage # test stage
# ==================== # ====================
testLEGACY:
stage: test
script:
- npmci node install legacy
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
allow_failure: true
testLTS: testStable:
stage: test stage: test
script: script:
- npmci node install lts - npmci npm prepare
- npmci npm install - npmci node install stable
- npmci npm test - npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/ coverage: /\d+.?\d+?\%\s*coverage/
tags: tags:
- docker - lossless
- notpriv - docker
- priv
testSTABLE:
testBuild:
stage: test stage: test
script: script:
- npmci node install stable - npmci npm prepare
- npmci npm install - npmci node install stable
- npmci npm test - npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/ coverage: /\d+.?\d+?\%\s*coverage/
tags: tags:
- docker - lossless
- notpriv - docker
- notpriv
release: release:
stage: release stage: release
script: script:
- npmci node install stable - npmci node install stable
- npmci npm publish - npmci npm publish
only: only:
- tags - tags
tags: tags:
- docker - lossless
- notpriv - docker
- notpriv
# ==================== # ====================
# metadata stage # metadata stage
# ==================== # ====================
codequality: codequality:
stage: metadata stage: metadata
image: docker:stable
allow_failure: true allow_failure: true
services:
- docker:stable-dind
script: script:
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/') - npmci command npm install -g tslint typescript
- docker run - npmci npm prepare
--env SOURCE_CODE="$PWD" - npmci npm install
--volume "$PWD":/code - npmci command "tslint -c tslint.json ./ts/**/*.ts"
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
artifacts:
paths: [codeclimate.json]
tags: tags:
- docker - lossless
- priv - docker
- priv
trigger: trigger:
stage: metadata stage: metadata
script: script:
- npmci trigger - npmci trigger
only: only:
- tags - tags
tags: tags:
- docker - lossless
- notpriv - docker
- notpriv
pages: pages:
image: hosttoday/ht-docker-node:npmci
stage: metadata stage: metadata
script: script:
- npmci command npm install -g typedoc typescript - npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install - npmci npm install
- npmci command typedoc --module "commonjs" --target "ES2016" --out public/ ts/ - npmci command tsdoc
tags: tags:
- lossless
- docker - docker
- notpriv - notpriv
only: only:
@ -128,15 +122,5 @@ pages:
artifacts: artifacts:
expire_in: 1 week expire_in: 1 week
paths: paths:
- public - public
allow_failure: true
windowsCompatibility:
image: stefanscherer/node-windows:10-build-tools
stage: metadata
script:
- npm install & npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- windows
allow_failure: true allow_failure: true

29
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,29 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "current file",
"type": "node",
"request": "launch",
"args": [
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
}
]
}

26
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,26 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm"]
}
}
}
}
}
}
]
}

View File

@ -1,54 +0,0 @@
# cflare
easy cloudflare management
## Availabililty
[![npm](https://mojoio.gitlab.io/assets/repo-button-npm.svg)](https://www.npmjs.com/package/cflare)
[![git](https://mojoio.gitlab.io/assets/repo-button-git.svg)](https://GitLab.com/mojoio/cflare)
[![git](https://mojoio.gitlab.io/assets/repo-button-mirror.svg)](https://github.com/mojoio/cflare)
[![docs](https://mojoio.gitlab.io/assets/repo-button-docs.svg)](https://mojoio.gitlab.io/cflare/)
## Status for master
[![build status](https://GitLab.com/mojoio/cflare/badges/master/build.svg)](https://GitLab.com/mojoio/cflare/commits/master)
[![coverage report](https://GitLab.com/mojoio/cflare/badges/master/coverage.svg)](https://GitLab.com/mojoio/cflare/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/cflare.svg)](https://www.npmjs.com/package/cflare)
[![Dependency Status](https://david-dm.org/mojoio/cflare.svg)](https://david-dm.org/mojoio/cflare)
[![bitHound Dependencies](https://www.bithound.io/github/mojoio/cflare/badges/dependencies.svg)](https://www.bithound.io/github/mojoio/cflare/master/dependencies/npm)
[![bitHound Code](https://www.bithound.io/github/mojoio/cflare/badges/code.svg)](https://www.bithound.io/github/mojoio/cflare)
[![TypeScript](https://img.shields.io/badge/TypeScript-2.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%206.x.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Usage
Use TypeScript for best in class instellisense.
```javascript
import * as cflare from 'cflare'
let myCflareAccount = new cflare.CflareAccount()
testCflareAccount.auth({
email: 'someuser@example.com',
key: 'someLongApiKey'
})
let myAsyncCflareManagement = async () => {
// get things
let myZones = await myCflareAccount.listZones() // zones are fully typed
let myIdForADomain = await myCflareAccount.getZoneId('example.com') // type number
let myRecordsForADomain = await myCflareAccount.listRecords('example.com') // records are fully typed
// set things
myCflareAccount.updateRecord(...)
myCflareAccount.createRecord(...)
myCflareAccount.deleteRecord(...)
}
```
For further information read the linked docs at the top of this README.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
[![repo-footer](https://mojoio.gitlab.io/assets/repo-footer.svg)](https://mojo.io)

View File

@ -2,5 +2,16 @@
"npmci": { "npmci": {
"npmGlobalTools": [], "npmGlobalTools": [],
"npmAccessLevel": "public" "npmAccessLevel": "public"
},
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "mojoio",
"gitrepo": "cloudflare",
"shortDescription": "easy cloudflare management",
"npmPackagename": "@mojoio/cloudflare",
"license": "MIT"
}
} }
} }

1775
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "@mojoio/cloudflare", "name": "@mojoio/cloudflare",
"version": "2.0.0", "version": "5.0.4",
"private": false, "private": false,
"description": "easy cloudflare management", "description": "easy cloudflare management",
"main": "dist/index.js", "main": "dist/index.js",
@ -24,19 +24,32 @@
}, },
"homepage": "https://gitlab.com/pushrocks/cflare#readme", "homepage": "https://gitlab.com/pushrocks/cflare#readme",
"dependencies": { "dependencies": {
"@pushrocks/smartdelay": "^2.0.2", "@pushrocks/smartdelay": "^2.0.6",
"@pushrocks/smartlog": "^2.0.1", "@pushrocks/smartlog": "^2.0.21",
"@pushrocks/smartpromise": "^2.0.5", "@pushrocks/smartpromise": "^3.0.6",
"@pushrocks/smartrequest": "^1.1.14", "@pushrocks/smartrequest": "^1.1.47",
"@pushrocks/smartstring": "^3.0.4", "@pushrocks/smartstring": "^3.0.18",
"@tsclass/tsclass": "^1.0.48" "@tsclass/tsclass": "^3.0.7"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.0.22", "@gitzone/tsbuild": "^2.1.17",
"@gitzone/tsrun": "^1.1.12", "@gitzone/tsrun": "^1.2.8",
"@gitzone/tstest": "^1.0.15", "@gitzone/tstest": "^1.0.28",
"@pushrocks/qenv": "^2.0.2", "@pushrocks/qenv": "^4.0.6",
"@pushrocks/tapbundle": "^3.0.5", "@pushrocks/tapbundle": "^3.2.0",
"@types/node": "^10.5.8" "@types/node": "^13.7.2",
} "tslint": "^6.0.0",
"tslint-config-prettier": "^1.18.0"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_web/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
]
} }

View File

@ -1,3 +1,2 @@
vars: required:
- CF_EMAIL
- CF_KEY - CF_KEY

45
readme.md Normal file
View File

@ -0,0 +1,45 @@
# @mojoio/cloudflare
easy cloudflare management
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@mojoio/cloudflare)
* [gitlab.com (source)](https://gitlab.com/mojoio/cloudflare)
* [github.com (source mirror)](https://github.com/mojoio/cloudflare)
* [docs (typedoc)](https://mojoio.gitlab.io/cloudflare/)
## Status for master
[![pipeline status](https://gitlab.com/mojoio/cloudflare/badges/master/pipeline.svg)](https://gitlab.com/mojoio/cloudflare/commits/master)
[![coverage report](https://gitlab.com/mojoio/cloudflare/badges/master/coverage.svg)](https://gitlab.com/mojoio/cloudflare/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/@mojoio/cloudflare.svg)](https://www.npmjs.com/package/@mojoio/cloudflare)
[![Known Vulnerabilities](https://snyk.io/test/npm/@mojoio/cloudflare/badge.svg)](https://snyk.io/test/npm/@mojoio/cloudflare)
[![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-prettier-ff69b4.svg)](https://prettier.io/)
## Usage
Use TypeScript for best in class instellisense.
```javascript
import * as cflare from '@mojoio/cloudflare';
const myCflareAccount = new cflare.CflareAccount('mySuperAwesomeAccountToken');
const myAsyncCflareManagement = async () => {
// get things
const myZones = await myCflareAccount.listZones(); // zones are fully typed
const myIdForADomain = await myCflareAccount.getZoneId('example.com'); // type number
const myRecordsForADomain = await myCflareAccount.listRecords('example.com'); // records are fully typed
};
```
## Contribution
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
For further information read the linked docs at the top of this readme.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)

View File

@ -1,19 +1,22 @@
// tslint:disable-next-line: no-implicit-dependencies
import { expect, tap } from '@pushrocks/tapbundle'; import { expect, tap } from '@pushrocks/tapbundle';
import cloudflare = require('../ts/index'); // tslint:disable-next-line: no-implicit-dependencies
import { Qenv } from '@pushrocks/qenv'; import { Qenv } from '@pushrocks/qenv';
let testQenv = new Qenv(process.cwd(), process.cwd() + '/.nogit');
let testCloudflareAccount = new cloudflare.CloudflareAccount(); import cloudflare = require('../ts/index');
testCloudflareAccount.auth({
email: process.env.CF_EMAIL, const testQenv = new Qenv(process.cwd(), process.cwd() + '/.nogit');
key: process.env.CF_KEY
const randomPrefix = Math.floor(Math.random() * 2000);
let testCloudflareAccount: cloudflare.CloudflareAccount;
tap.test('should create a valid instance of CloudflareAccount', async () => {
testCloudflareAccount = new cloudflare.CloudflareAccount(testQenv.getEnvVarOnDemand('CF_KEY'));
}); });
let randomPrefix = Math.floor(Math.random() * 2000); tap.test('.listZones() -> should display an entire account', async tools => {
tap.skip.test('.listZones() -> should display an entire account', async tools => {
tools.timeout(600000); tools.timeout(600000);
let result = await testCloudflareAccount.listZones(); const result = await testCloudflareAccount.convenience.listZones();
console.log(result); console.log(result);
}); });
@ -21,7 +24,7 @@ tap.test(
'.getZoneId(domainName) -> should get an Cloudflare Id for a domain string', '.getZoneId(domainName) -> should get an Cloudflare Id for a domain string',
async tools => { async tools => {
tools.timeout(600000); tools.timeout(600000);
await testCloudflareAccount.getZoneId('bleu.de'); await testCloudflareAccount.convenience.getZoneId('bleu.de');
} }
); );
@ -29,7 +32,7 @@ tap.test(
'.listRecords(domainName) -> should list all records for a specific Domain Name', '.listRecords(domainName) -> should list all records for a specific Domain Name',
async tools => { async tools => {
tools.timeout(600000); tools.timeout(600000);
await testCloudflareAccount.listRecords('bleu.de').then(async responseArg => { await testCloudflareAccount.convenience.listRecords('bleu.de').then(async responseArg => {
console.log(responseArg); console.log(responseArg);
}); });
} }
@ -37,19 +40,25 @@ tap.test(
tap.test('should create a valid record for a subdomain', async tools => { tap.test('should create a valid record for a subdomain', async tools => {
tools.timeout(600000); tools.timeout(600000);
await testCloudflareAccount.createRecord(`${randomPrefix}subdomain.bleu.de`, 'A', '127.0.0.1'); await testCloudflareAccount.convenience.createRecord(
`${randomPrefix}subdomain.bleu.de`,
'A',
'127.0.0.1'
);
}); });
tap.test('should get a record from Cloudflare', async tools => { tap.test('should get a record from Cloudflare', async tools => {
tools.timeout(600000); tools.timeout(600000);
await testCloudflareAccount.getRecord('bleu.de', 'A').then(function(responseArg) { await testCloudflareAccount.convenience
console.log(responseArg); .getRecord(`${randomPrefix}subdomain.bleu.de`, 'A')
}); .then(responseArg => {
console.log(responseArg);
});
}); });
tap.test('should remove a subdomain record from Cloudflare', async tools => { tap.test('should remove a subdomain record from Cloudflare', async tools => {
tools.timeout(600000); tools.timeout(600000);
await testCloudflareAccount await testCloudflareAccount.convenience
.removeRecord(`${randomPrefix}subdomain.bleu.de`, 'A') .removeRecord(`${randomPrefix}subdomain.bleu.de`, 'A')
.then(async responseArg => { .then(async responseArg => {
console.log(responseArg); console.log(responseArg);
@ -57,7 +66,27 @@ tap.test('should remove a subdomain record from Cloudflare', async tools => {
}); });
tap.test('.purge(some.domain) -> should purge everything', async () => { tap.test('.purge(some.domain) -> should purge everything', async () => {
await testCloudflareAccount.purgeZone('bleu.de'); await testCloudflareAccount.convenience.purgeZone('bleu.de');
});
// WORKERS
tap.test('should create a worker', async () => {
const worker = await testCloudflareAccount.workerManager.createWorker(
'myawesomescript',
`addEventListener('fetch', event => { event.respondWith(fetch(event.request)) })`
);
await worker.setRoutes([
{
zoneName: 'bleu.de',
pattern: 'https://*bleu.de/hello'
}
]);
console.log(worker);
});
tap.test('should get workers', async () => {
const workerArray = await testCloudflareAccount.workerManager.listWorkers();
console.log(workerArray);
}); });
tap.start(); tap.start();

View File

@ -1,175 +1,273 @@
import plugins = require('./cloudflare.plugins'); import plugins = require('./cloudflare.plugins');
import * as interfaces from './cloudflare.interfaces'; import * as interfaces from './interfaces';
// interfaces // interfaces
import { TDnsRecord } from '@tsclass/tsclass'; import { WorkerManager } from './cloudflare.classes.workermanager';
import { ZoneManager } from './cloudflare.classes.zonemanager';
export class CloudflareAccount { export class CloudflareAccount {
private authEmail: string; private authToken: string;
private authKey: string; private accountIdentifier: string;
constructor() {
// Nothing here
}
auth(optionsArg: { email: string; key: string }) { public workerManager = new WorkerManager(this);
this.authEmail = optionsArg.email; public zoneManager = new ZoneManager(this);
this.authKey = optionsArg.key;
/**
* constructor sets auth information on the CloudflareAccountInstance
* @param optionsArg
*/
constructor(authTokenArg: string) {
this.authToken = authTokenArg;
} }
/** /**
* gets a zone id of a domain from cloudflare * gets you the account identifier
* @param domainName
*/ */
async getZoneId(domainName: string) { public async getAccountIdentifier() {
let domain = new plugins.smartstring.Domain(domainName); if (!this.accountIdentifier) {
let zoneArray = await this.listZones(domain.zoneName); const route = `/accounts?page=1&per_page=20&direction=desc`;
let filteredResponse = zoneArray.filter(zoneArg => { const response: any = await this.request('GET', route);
return zoneArg.name === domainName; this.accountIdentifier = response.result[0].id;
});
if (filteredResponse.length >= 1) {
return filteredResponse[0].id;
} else {
plugins.smartlog.defaultLogger.error(`the domain ${domainName} does not appear to be in this account!`);
throw new Error(`the domain ${domainName} does not appear to be in this account!`);
} }
return this.accountIdentifier;
} }
/** public convenience = {
* gets a record /**
* @param domainNameArg * gets a zone id of a domain from cloudflare
* @param typeArg * @param domainName
*/ */
async getRecord(domainNameArg: string, typeArg: TDnsRecord): Promise<interfaces.ICflareRecord> { getZoneId: async (domainName: string) => {
let done = plugins.smartpromise.defer<interfaces.ICflareRecord>(); const domain = new plugins.smartstring.Domain(domainName);
let result: interfaces.ICflareRecord; const zoneArray = await this.convenience.listZones(domain.zoneName);
const filteredResponse = zoneArray.filter(zoneArg => {
let domain = new plugins.smartstring.Domain(domainNameArg); return zoneArg.name === domainName;
this.listRecords(domain.zoneName).then(recordArrayArg => { });
let filteredResponse = recordArrayArg.filter(recordArg => { if (filteredResponse.length >= 1) {
return filteredResponse[0].id;
} else {
plugins.smartlog.defaultLogger.log(
'error',
`the domain ${domainName} does not appear to be in this account!`
);
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,
typeArg: plugins.tsclass.network.TDnsRecordType
): Promise<interfaces.ICflareRecord> => {
const domain = new plugins.smartstring.Domain(domainNameArg);
const recordArrayArg = await this.convenience.listRecords(domain.zoneName);
const filteredResponse = recordArrayArg.filter(recordArg => {
return recordArg.type === typeArg && recordArg.name === domainNameArg; return recordArg.type === typeArg && recordArg.name === domainNameArg;
}); });
done.resolve(filteredResponse[0]); return filteredResponse[0];
}); },
return done.promise; /**
} * creates a record
*/
async createRecord(domainNameArg: string, typeArg: TDnsRecord, contentArg: string) { createRecord: async (
let done = plugins.smartpromise.defer(); domainNameArg: string,
let domain = new plugins.smartstring.Domain(domainNameArg); typeArg: plugins.tsclass.network.TDnsRecordType,
let domainIdArg = await this.getZoneId(domain.zoneName); contentArg: string
let dataObject = { ): Promise<any> => {
name: domain.fullName, const domain = new plugins.smartstring.Domain(domainNameArg);
type: typeArg, const domainIdArg = await this.convenience.getZoneId(domain.zoneName);
content: contentArg const dataObject = {
}; name: domain.fullName,
this.request('POST', '/zones/' + domainIdArg + '/dns_records', dataObject).then(function( type: typeArg,
responseArg content: contentArg
) { };
done.resolve(responseArg); const response = await this.request(
}); 'POST',
return done.promise; '/zones/' + domainIdArg + '/dns_records',
} dataObject
);
removeRecord(domainNameArg: string, typeArg: TDnsRecord) { return response;
let done = plugins.smartpromise.defer(); },
let domain = new plugins.smartstring.Domain(domainNameArg); /**
this.getRecord(domain.fullName, typeArg).then(responseArg => { * removes a record from Cloudflare
if (responseArg) { * @param domainNameArg
let requestRoute: string = * @param typeArg
'/zones/' + responseArg.zone_id + '/dns_records/' + responseArg.id; */
this.request('DELETE', requestRoute).then(responseArg => { removeRecord: async (
done.resolve(responseArg); domainNameArg: string,
}); 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 { } else {
done.reject(); throw new Error(`could not remove record for ${domainNameArg} with type ${typeArg}`);
} }
}); },
return done.promise; /**
} * cleanrecord allows the cleaning of any previous records to avoid unwanted sideeffects
*/
cleanRecord: async (domainNameArg: string, typeArg: plugins.tsclass.network.TDnsRecordType) => {
console.log(`cleaning record for ${domainNameArg}`);
},
/**
* updates a record
* @param domainNameArg
* @param typeArg
* @param valueArg
*/
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);
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`;
updateRecord(domainNameArg: string, typeArg: string, valueArg) { // may be optionally filtered by domain name
let done = plugins.smartpromise.defer(); if (domainName) {
let domain = new plugins.smartstring.Domain(domainNameArg); requestRoute = `${requestRoute}&name=${domainName}`;
return done.promise; }
}
/** const response: any = await this.request('GET', requestRoute);
* list all records of a specified domain name const result = response.result;
* @param domainNameArg - the domain name that you want to get the records from return result;
*/ },
async listRecords(domainNameArg: string): Promise<interfaces.ICflareRecord[]> { /**
let domain = new plugins.smartstring.Domain(domainNameArg); * purges a zone
let domainId = await this.getZoneId(domain.zoneName); */
let responseArg: any = await this.request( purgeZone: async (domainName: string): Promise<void> => {
'GET', const domain = new plugins.smartstring.Domain(domainName);
'/zones/' + domainId + '/dns_records?per_page=100' const domainId = await this.convenience.getZoneId(domain.zoneName);
); const requestUrl = `/zones/${domainId}/purge_cache`;
let result: interfaces.ICflareRecord[] = responseArg.result; const payload = {
return result; purge_everything: true
} };
const respone = await this.request('DELETE', requestUrl, payload);
/** },
* list all zones in the associated authenticated account // acme convenience functions
* @param domainName acmeSetDnsChallenge: async (dnsChallenge: plugins.tsclass.network.IDnsChallenge) => {
*/ await this.convenience.cleanRecord(dnsChallenge.hostName, 'TXT');
async listZones(domainName?: string): Promise<interfaces.ICflareZone[]> { await this.convenience.createRecord(dnsChallenge.hostName, 'TXT', dnsChallenge.challenge);
// TODO: handle pagination },
let requestRoute = `/zones?per_page=50`; acmeRemoveDnsChallenge: async (dnsChallenge: plugins.tsclass.network.IDnsChallenge) => {
await this.convenience.removeRecord(dnsChallenge.hostName, 'TXT');
// may be optionally filtered by domain name
if (domainName) {
requestRoute = `${requestRoute}&name=${domainName}`;
} }
};
let response: any = await this.request('GET', requestRoute); public async request(
let result = response.result; methodArg: string,
return result; routeArg: string,
} dataArg: any = {},
requestHeadersArg = {}
async purgeZone(domainName: string) { ): Promise<any> {
let domain = new plugins.smartstring.Domain(domainName); const options: plugins.smartrequest.ISmartRequestOptions = {
let domainId = await this.getZoneId(domain.zoneName);
let requestUrl = `/zones/${domainId}/purge_cache`;
let payload = {
purge_everything: true
};
let respone = await this.request('DELETE', requestUrl, payload);
}
request(methodArg: string, routeArg: string, dataArg = {}) {
let done = plugins.smartpromise.defer();
let options: plugins.smartrequest.ISmartRequestOptions = {
method: methodArg, method: methodArg,
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Auth-Email': this.authEmail, Authorization: `Bearer ${this.authToken}`,
'X-Auth-Key': this.authKey, 'Content-Length': Buffer.byteLength(JSON.stringify(dataArg)),
'Content-Length': Buffer.byteLength(JSON.stringify(dataArg)) ...requestHeadersArg
}, },
requestBody: dataArg requestBody: dataArg
}; };
let retryCount = 0; // count the amount of retries // route analysis
const routeWithoutQuery = routeArg.split('?')[0];
let queryParams: string[] = [];
if (routeArg.split('?').length > 1) {
queryParams = routeArg.split('?')[1].split('&');
}
let makeRequest = async () => { // console.log(options);
let response: any = await plugins.smartrequest.request(
`https://api.cloudflare.com/client/v4${routeArg}`, let retryCount = 0; // count the amount of retries
options let pageCount = 1;
);
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;
};
const makeRequest = async (): Promise<plugins.smartrequest.IExtendedIncomingMessage> => {
const requestUrl = `https://api.cloudflare.com/client/v4${routeWithoutQuery}${getQueryParams()}`;
const response = await plugins.smartrequest.request(requestUrl, options);
if (response.statusCode === 200) { if (response.statusCode === 200) {
done.resolve(response.body); if (response.body.result_info) {
const rI = response.body.result_info;
if (rI.total_count / rI.per_page > pageCount) {
pageCount++;
const subresponse = await makeRequest();
response.body.result = response.body.result.concat(subresponse.body.result);
return response;
} else {
return response;
}
} else {
return response;
}
} else if (response.statusCode === 429) { } else if (response.statusCode === 429) {
console.log('rate limited! Waiting for retry!'); console.log('rate limited! Waiting for retry!');
retryRequest(); return await retryRequest();
} else if (response.statusCode === 400) { } else if (response.statusCode === 400) {
console.log(`bad request for route ${routeArg}! Going to retry!`); console.log(`bad request for route ${requestUrl}!`);
retryRequest(); console.log(response.body);
throw new Error(`request failed for ${requestUrl}`);
} else { } else {
console.log(response.statusCode); console.log(response.body);
done.reject(new Error('request failed')); throw new Error(`request failed for ${requestUrl} with status${response.statusCode}}`);
} }
}; };
let retryRequest = async (delayTimeArg = Math.floor(Math.random() * (60000 - 8000) + 8000)) => {
const retryRequest = async (
delayTimeArg = Math.floor(Math.random() * (60000 - 8000) + 8000)
) => {
console.log(`retry started and waiting for ${delayTimeArg} ms`); console.log(`retry started and waiting for ${delayTimeArg} ms`);
await plugins.smartdelay.delayFor(delayTimeArg); await plugins.smartdelay.delayFor(delayTimeArg);
if (retryCount < 10) { if (retryCount < 10) {
@ -177,11 +275,11 @@ export class CloudflareAccount {
return await makeRequest(); return await makeRequest();
} }
}; };
makeRequest(); const response = await makeRequest();
return done.promise; return response.body;
} }
private authCheck() { private authCheck() {
return this.authEmail && this.authKey; // check if auth is available return !!this.authToken; // check if auth is available
} }
} }

View File

@ -0,0 +1,5 @@
import * as plugins from './cloudflare.plugins';
export class CloudflareRecord {
}

View File

@ -0,0 +1,92 @@
import * as plugins from './cloudflare.plugins';
import * as interfaces from './interfaces';
import { WorkerManager } from './cloudflare.classes.workermanager';
export interface IWorkerRoute extends interfaces.ICflareWorkerRoute {
zoneName: string;
}
export class CloudflareWorker {
// STATIC
public static async fromApiObject(
workerManager: WorkerManager,
apiObject
): Promise<CloudflareWorker> {
const newWorker = new CloudflareWorker(workerManager);
Object.assign(newWorker, apiObject);
await newWorker.getRoutes();
return newWorker;
}
// INSTANCE
private workerManager: WorkerManager;
public script: string;
public id: string;
public etag: string;
// tslint:disable-next-line: variable-name
public created_on: string;
// tslint:disable-next-line: variable-name
public modified_on: string;
public routes: IWorkerRoute[] = [];
constructor(workerManagerArg: WorkerManager) {
this.workerManager = workerManagerArg;
}
/**
* gets all routes for a worker
*/
public async getRoutes() {
const zones = await this.workerManager.cfAccount.convenience.listZones();
for (const zone of zones) {
const requestRoute = `/zones/${zone.id}/workers/routes`;
const response: {
result: interfaces.ICflareWorkerRoute[];
} = await this.workerManager.cfAccount.request('GET', requestRoute);
for (const route of response.result) {
console.log('hey');
console.log(route);
console.log(this.id);
if (route.script === this.id) {
this.routes.push({ ...route, zoneName: zone.name });
}
}
}
}
public async setRoutes(routeArray: Array<{ zoneName: string; pattern: string }>) {
for (const newRoute of routeArray) {
// lets determine wether a route is new, needs an update or already up to date.
let routeStatus: 'new' | 'needsUpdate' | 'alreadyUpToDate' = 'new';
let routeIdForUpdate: string;
for (const existingRoute of this.routes) {
if (existingRoute.pattern === newRoute.pattern) {
routeStatus = 'needsUpdate';
routeIdForUpdate = existingRoute.id;
if (existingRoute.script === this.id) {
routeStatus = 'alreadyUpToDate';
plugins.smartlog.defaultLogger.log('info', `route already exists, no update needed`);
}
}
}
// lets care about actually setting routes
if (routeStatus === 'new') {
const zoneId = await this.workerManager.cfAccount.convenience.getZoneId(newRoute.zoneName);
const requestRoute = `/zones/${zoneId}/workers/routes`;
await this.workerManager.cfAccount.request('POST', requestRoute, {
pattern: newRoute.pattern,
script: this.id
});
} else if (routeStatus === 'needsUpdate') {
const zoneId = await this.workerManager.cfAccount.convenience.getZoneId(newRoute.zoneName);
const requestRoute = `/zones/${zoneId}/workers/routes/${routeIdForUpdate}`;
await this.workerManager.cfAccount.request('PUT', requestRoute, {
pattern: newRoute.pattern,
script: this.id
});
}
}
}
}

View File

@ -0,0 +1,36 @@
import * as plugins from './cloudflare.plugins';
import { CloudflareAccount } from './cloudflare.classes.account';
import { CloudflareWorker } from './cloudflare.classes.worker';
export class WorkerManager {
public cfAccount: CloudflareAccount;
constructor(cfAccountArg: CloudflareAccount) {
this.cfAccount = cfAccountArg;
}
public async createWorker(workerName: string, workerScript: string): Promise<CloudflareWorker> {
const accountIdentifier = await this.cfAccount.getAccountIdentifier();
const route = `/accounts/${accountIdentifier}/workers/scripts/${workerName}`;
const responseBody = await this.cfAccount.request('PUT', route, workerScript, {
'Content-Type': 'application/javascript',
'Content-Length': Buffer.byteLength(workerScript)
});
return CloudflareWorker.fromApiObject(this, responseBody.result);
}
/**
* lists workers
*/
public async listWorkers() {
const accountIdentifier = await this.cfAccount.getAccountIdentifier();
const route = `/accounts/${accountIdentifier}/workers/scripts`;
const response = await this.cfAccount.request('GET', route);
const results = response.result;
const workers: CloudflareWorker[] = [];
for (const apiObject of results) {
workers.push(await CloudflareWorker.fromApiObject(this, apiObject));
}
return workers;
}
}

View File

@ -1,6 +1,13 @@
import * as plugins from './cloudflare.plugins'; import * as plugins from './cloudflare.plugins';
import * as interfaces from './interfaces';
export class CloudflareZone implements interfaces.ICflareZone {
public static createFromApiObject(apiObject: interfaces.ICflareZone) {
const cloudflareZone = new CloudflareZone();
Object.assign(cloudflareZone, apiObject);
return cloudflareZone;
}
export interface ICflareZone {
id: string; id: string;
name: string; name: string;
development_mode: number; development_mode: number;
@ -40,20 +47,5 @@ export interface ICflareZone {
paused: boolean; paused: boolean;
type: string; type: string;
checked_on: string; checked_on: string;
}
export interface ICflareRecord {
id: string;
type: string;
name: string;
content: string;
proxiable: boolean;
proxied: boolean;
ttl: number;
locked: boolean;
zone_id: string;
zone_name: string;
created_on: string;
modified_on: string;
data: any;
} }

View File

@ -0,0 +1,32 @@
import * as plugins from './cloudflare.plugins';
import * as interfaces from './interfaces';
import { CloudflareAccount } from './cloudflare.classes.account';
import { CloudflareZone } from './cloudflare.classes.zone';
export class ZoneManager {
public cfAccount: CloudflareAccount;
public zoneName: string;
constructor(cfAccountArg: CloudflareAccount) {
this.cfAccount = cfAccountArg;
}
public async getZones(zoneName: string) {
let requestRoute = `/zones?per_page=50`;
// may be optionally filtered by domain name
if (zoneName) {
requestRoute = `${requestRoute}&name=${zoneName}`;
}
const response: any = await this.cfAccount.request('GET', requestRoute);
const apiObjects: interfaces.ICflareZone[] = response.result;
const cloudflareZoneArray = [];
for (const apiObject of apiObjects) {
cloudflareZoneArray.push(CloudflareZone.createFromApiObject(apiObject));
}
return cloudflareZoneArray;
}
}

View File

@ -1 +1,2 @@
export { CloudflareAccount } from './cloudflare.classes.account'; export { CloudflareAccount } from './cloudflare.classes.account';
export { CloudflareWorker } from './cloudflare.classes.worker';

View File

@ -0,0 +1,15 @@
export interface ICflareRecord {
id: string;
type: string;
name: string;
content: string;
proxiable: boolean;
proxied: boolean;
ttl: number;
locked: boolean;
zone_id: string;
zone_name: string;
created_on: string;
modified_on: string;
data: any;
}

View File

@ -0,0 +1,5 @@
export interface ICflareWorkerRoute {
id: string;
pattern: string;
script: string;
}

View File

@ -0,0 +1,41 @@
export interface ICflareZone {
id: string;
name: string;
development_mode: number;
original_name_servers: string[];
original_registrar: string;
original_dnshost: string;
created_on: string;
modified_on: string;
name_servers: string[];
owner: {
id: string;
email: string;
owner_type: string;
};
permissions: string[];
plan: {
id: string;
name: string;
price: number;
currency: string;
frequency: string;
legacy_id: string;
is_subscribed: boolean;
can_subscribe: boolean;
};
plan_pending: {
id: string;
name: string;
price: number;
currency: string;
frequency: string;
legacy_id: string;
is_subscribed: string;
can_subscribe: string;
};
status: string;
paused: boolean;
type: string;
checked_on: string;
}

3
ts/interfaces/index.ts Normal file
View File

@ -0,0 +1,3 @@
export * from './cloudflare.api.record';
export * from './cloudflare.api.zone';
export * from './cloudflare.api.workerroute';

View File

@ -1,3 +1,17 @@
{ {
"extends": "tslint-config-standard" "extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
} }