Compare commits

...

46 Commits

Author SHA1 Message Date
42feb09b4f 6.0.3 2023-06-13 19:01:56 +02:00
d72bb28cf9 fix(core): update 2023-06-13 19:01:56 +02:00
b9f0b798c9 6.0.2 2023-06-13 18:54:26 +02:00
9b5f42ef9b fix(core): update 2023-06-13 18:54:25 +02:00
4e3355dc43 6.0.1 2022-09-27 19:24:52 +02:00
fc0a27f5b6 fix(core): update 2022-09-27 19:24:52 +02:00
0248d52548 6.0.0 2022-09-27 19:24:00 +02:00
c3984819cc BREAKING CHANGE(core): switch to esm 2022-09-27 19:24:00 +02:00
045b87a4a2 5.0.10 2022-09-27 19:23:21 +02:00
48ca9fdbb9 fix(core): update 2022-09-27 19:23:20 +02:00
e466944c55 5.0.9 2021-01-22 21:12:42 +00:00
6d8deca9d4 fix(core): update 2021-01-22 21:12:42 +00:00
a4518f3068 5.0.8 2021-01-22 20:46:26 +00:00
9e338354c6 fix(core): update 2021-01-22 20:46:26 +00:00
9d8c14d187 5.0.7 2021-01-22 20:45:36 +00:00
5a0b12f6aa fix(core): update 2021-01-22 20:45:35 +00:00
387f00078f 5.0.6 2020-06-10 05:34:48 +00:00
fe2f45e3a9 fix(core): update 2020-06-10 05:34:47 +00:00
90c9bfc906 5.0.5 2020-06-10 05:15:23 +00:00
4f9e81f612 fix(core): update 2020-06-10 05:15:22 +00:00
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
25 changed files with 17361 additions and 1506 deletions

4
.gitignore vendored
View File

@ -15,8 +15,6 @@ node_modules/
# builds
dist/
dist_web/
dist_serve/
dist_ts_web/
dist_*/
# custom

View File

@ -3,75 +3,82 @@ image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: "$CI_BUILD_STAGE"
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
- security
- test
- release
- metadata
before_script:
- npm install -g @shipzone/npmci
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
tags:
- docker
- notpriv
snyk:
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install -g snyk
- npmci command npm install --ignore-scripts
- npmci command snyk test
- npmci command npm install --production --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=prod --production
tags:
- docker
- notpriv
- docker
allow_failure: true
auditDevDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
allow_failure: true
# ====================
# test stage
# ====================
testLTS:
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install lts
- npmci npm install
- npmci npm test
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
- docker
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install lts
- npmci npm install
- npmci command npm run build
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
- docker
release:
stage: release
script:
- npmci node install lts
- npmci npm publish
- npmci node install stable
- npmci npm publish
only:
- tags
- tags
tags:
- docker
- notpriv
- lossless
- docker
- notpriv
# ====================
# metadata stage
@ -79,33 +86,37 @@ release:
codequality:
stage: metadata
allow_failure: true
only:
- tags
script:
- npmci command npm install -g tslint typescript
- npmci command npm install -g typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- docker
- priv
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
- npmci trigger
only:
- tags
- tags
tags:
- docker
- notpriv
- lossless
- docker
- notpriv
pages:
image: hosttoday/ht-docker-node:npmci
stage: metadata
script:
- npmci command npm install -g @gitzone/tsdoc
- npmci node install stable
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
- npmci command npm run buildDocs
tags:
- lossless
- docker
- notpriv
only:
@ -113,5 +124,5 @@ pages:
artifacts:
expire_in: 1 week
paths:
- public
- public
allow_failure: true

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

@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "npm test",
"name": "Run npm test",
"request": "launch",
"type": "node-terminal"
}
]
}

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", "wcc"]
}
}
}
}
}
}
]
}

View File

@ -1,50 +0,0 @@
# @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
[![build status](https://gitlab.com/mojoio/cloudflare/badges/master/build.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 '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)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html)
[![repo-footer](https://mojoio.gitlab.io/assets/repo-footer.svg)](https://maintainedby.lossless.com)

View File

@ -4,12 +4,13 @@
"npmAccessLevel": "public"
},
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "mojoio",
"gitrepo": "cloudflare",
"shortDescription": "easy cloudflare management",
"npmPackagename": "@mojoio/cloudflare",
"description": "easy cloudflare management",
"npmPackagename": "@apiclient.xyz/cloudflare",
"license": "MIT"
}
}

13511
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,15 @@
{
"name": "@mojoio/cloudflare",
"version": "3.0.5",
"name": "@apiclient.xyz/cloudflare",
"version": "6.0.3",
"private": false,
"description": "easy cloudflare management",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
"scripts": {
"test": "(tstest test/)",
"build": "(tsbuild)"
"build": "(tsbuild --web --allowimplicitany)",
"buildDocs": "tsdoc"
},
"repository": {
"type": "git",
@ -24,32 +26,34 @@
},
"homepage": "https://gitlab.com/pushrocks/cflare#readme",
"dependencies": {
"@pushrocks/smartdelay": "^2.0.3",
"@pushrocks/smartlog": "^2.0.19",
"@pushrocks/smartpromise": "^3.0.2",
"@pushrocks/smartrequest": "^1.1.16",
"@pushrocks/smartstring": "^3.0.10",
"@tsclass/tsclass": "^2.0.1"
"@pushrocks/smartdelay": "^3.0.1",
"@pushrocks/smartlog": "^3.0.2",
"@pushrocks/smartpromise": "^4.0.2",
"@pushrocks/smartrequest": "^2.0.15",
"@pushrocks/smartstring": "^4.0.5",
"@tsclass/tsclass": "^4.0.42"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.11",
"@gitzone/tsrun": "^1.2.8",
"@gitzone/tstest": "^1.0.24",
"@pushrocks/qenv": "^4.0.0",
"@pushrocks/tapbundle": "^3.0.11",
"@types/node": "^12.6.6",
"tslint": "^5.18.0",
"tslint-config-prettier": "^1.18.0"
"@gitzone/tsbuild": "^2.1.66",
"@gitzone/tsrun": "^1.2.42",
"@gitzone/tstest": "^1.0.74",
"@pushrocks/qenv": "^5.0.2",
"@pushrocks/tapbundle": "^5.0.4",
"@types/node": "^20.3.1"
},
"files": [
"ts/*",
"ts_web/*",
"dist/*",
"dist_web/*",
"dist_ts_web/*",
"assets/*",
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
]
}

4420
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

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

52
readme.md Normal file
View File

@ -0,0 +1,52 @@
# @apiclient.xyz/cloudflare
easy cloudflare management
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@apiclient.xyz/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
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/mojoio/cloudflare/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/mojoio/cloudflare/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@apiclient.xyz/cloudflare)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/mojoio/cloudflare)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@apiclient.xyz/cloudflare)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@apiclient.xyz/cloudflare)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@apiclient.xyz/cloudflare)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
## Usage
Use TypeScript for best in class instellisense.
```javascript
import * as cflare from '@apiclient.xyz/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

@ -3,7 +3,7 @@ import { expect, tap } from '@pushrocks/tapbundle';
// tslint:disable-next-line: no-implicit-dependencies
import { Qenv } from '@pushrocks/qenv';
import cloudflare = require('../ts/index');
import * as cloudflare from '../ts/index.js';
const testQenv = new Qenv(process.cwd(), process.cwd() + '/.nogit');
@ -11,71 +11,76 @@ 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({
email: testQenv.getEnvVarOnDemand('CF_EMAIL'),
key: testQenv.getEnvVarOnDemand('CF_KEY')
});
testCloudflareAccount = new cloudflare.CloudflareAccount(testQenv.getEnvVarOnDemand('CF_KEY'));
});
tap.skip.test('.listZones() -> should display an entire account', async tools => {
tap.test('.listZones() -> should display an entire account', async (tools) => {
tools.timeout(600000);
const result = await testCloudflareAccount.listZones();
const result = await testCloudflareAccount.convenience.listZones();
console.log(result);
});
tap.test(
'.getZoneId(domainName) -> should get an Cloudflare Id for a domain string',
async tools => {
async (tools) => {
tools.timeout(600000);
await testCloudflareAccount.getZoneId('bleu.de');
await testCloudflareAccount.convenience.getZoneId('bleu.de');
}
);
tap.test(
'.listRecords(domainName) -> should list all records for a specific Domain Name',
async tools => {
async (tools) => {
tools.timeout(600000);
await testCloudflareAccount.listRecords('bleu.de').then(async responseArg => {
await testCloudflareAccount.convenience.listRecords('bleu.de').then(async (responseArg) => {
console.log(responseArg);
});
}
);
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);
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',
120
);
});
tap.test('should get a record from Cloudflare', async tools => {
tap.test('should get a record from Cloudflare', async (tools) => {
tools.timeout(600000);
await testCloudflareAccount.getRecord(`${randomPrefix}subdomain.bleu.de`, 'A').then(responseArg => {
console.log(responseArg);
});
await testCloudflareAccount.convenience
.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);
await testCloudflareAccount
await testCloudflareAccount.convenience
.removeRecord(`${randomPrefix}subdomain.bleu.de`, 'A')
.then(async responseArg => {
.then(async (responseArg) => {
console.log(responseArg);
});
});
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)) })`);
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'
}
pattern: 'https://*bleu.de/hello',
},
]);
console.log(worker);
});

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
*/
export const commitinfo = {
name: '@apiclient.xyz/cloudflare',
version: '6.0.3',
description: 'easy cloudflare management'
}

View File

@ -1,14 +1,13 @@
import plugins = require('./cloudflare.plugins');
import * as interfaces from './interfaces';
import * as plugins from './cloudflare.plugins.js';
import { logger } from './cloudflare.logger.js';
import * as interfaces from './interfaces/index.js';
// interfaces
import { TDnsRecord } from '@tsclass/tsclass';
import { WorkerManager } from './cloudflare.classes.workermanager';
import { ZoneManager } from './cloudflare.classes.zonemanager';
import { WorkerManager } from './cloudflare.classes.workermanager.js';
import { ZoneManager } from './cloudflare.classes.zonemanager.js';
export class CloudflareAccount {
private authEmail: string;
private authKey: string;
private authToken: string;
private accountIdentifier: string;
public workerManager = new WorkerManager(this);
@ -18,192 +17,259 @@ export class CloudflareAccount {
* constructor sets auth information on the CloudflareAccountInstance
* @param optionsArg
*/
constructor(optionsArg: { email: string; key: string }) {
this.authEmail = optionsArg.email;
this.authKey = optionsArg.key;
constructor(authTokenArg: string) {
this.authToken = authTokenArg;
}
/**
* gets you the account identifier
*/
public async getAccountIdentifier() {
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;
// console.log('Account identifier is: ' + this.accountIdentifier);
}
return this.accountIdentifier;
}
/**
* gets a zone id of a domain from cloudflare
* @param domainName
*/
public async getZoneId(domainName: string) {
const domain = new plugins.smartstring.Domain(domainName);
const zoneArray = await this.listZones(domain.zoneName);
const filteredResponse = zoneArray.filter(zoneArg => {
return zoneArg.name === domainName;
});
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!`
public convenience = {
/**
* 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);
const filteredResponse = zoneArray.filter((zoneArg) => {
return zoneArg.name === domainName;
});
if (filteredResponse.length >= 1) {
return filteredResponse[0].id;
} else {
logger.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 filteredResponse[0];
},
/**
* creates a record
*/
createRecord: async (
domainNameArg: string,
typeArg: plugins.tsclass.network.TDnsRecordType,
contentArg: string,
ttlArg = 1
): Promise<any> => {
const domain = new plugins.smartstring.Domain(domainNameArg);
const domainIdArg = await this.convenience.getZoneId(domain.zoneName);
const dataObject = {
name: domain.fullName,
type: typeArg,
content: contentArg,
ttl: ttlArg,
};
const response = await this.request(
'POST',
'/zones/' + domainIdArg + '/dns_records',
dataObject
);
throw new Error(`the domain ${domainName} does not appear to be in this account!`);
}
}
return response;
},
/**
* removes a record from Cloudflare
* @param domainNameArg
* @param typeArg
*/
removeRecord: async (
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 {
throw new Error(`could not remove record for ${domainNameArg} with type ${typeArg}`);
}
},
/**
* 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`;
/**
* gets a record
* @param domainNameArg
* @param typeArg
*/
public async getRecord(
domainNameArg: string,
typeArg: TDnsRecord
): Promise<interfaces.ICflareRecord> {
const domain = new plugins.smartstring.Domain(domainNameArg);
const recordArrayArg = await this.listRecords(domain.zoneName);
const filteredResponse = recordArrayArg.filter(recordArg => {
return recordArg.type === typeArg && recordArg.name === domainNameArg;
});
return filteredResponse[0];
}
// may be optionally filtered by domain name
if (domainName) {
requestRoute = `${requestRoute}&name=${domainName}`;
}
public async createRecord(
domainNameArg: string,
typeArg: TDnsRecord,
contentArg: string
): Promise<any> {
const domain = new plugins.smartstring.Domain(domainNameArg);
const domainIdArg = await this.getZoneId(domain.zoneName);
const dataObject = {
name: domain.fullName,
type: typeArg,
content: contentArg
};
const response = await this.request(
'POST',
'/zones/' + domainIdArg + '/dns_records',
dataObject
);
return response;
}
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);
const domainId = await this.convenience.getZoneId(domain.zoneName);
const requestUrl = `/zones/${domainId}/purge_cache`;
const payload = {
purge_everything: true,
};
const respone = await this.request('DELETE', requestUrl, payload);
},
// acme convenience functions
acmeSetDnsChallenge: async (dnsChallenge: plugins.tsclass.network.IDnsChallenge) => {
await this.convenience.cleanRecord(dnsChallenge.hostName, 'TXT');
await this.convenience.createRecord(
dnsChallenge.hostName,
'TXT',
dnsChallenge.challenge,
120
);
},
acmeRemoveDnsChallenge: async (dnsChallenge: plugins.tsclass.network.IDnsChallenge) => {
await this.convenience.removeRecord(dnsChallenge.hostName, 'TXT');
},
};
/**
* removes a record from Cloudflare
* @param domainNameArg
* @param typeArg
*/
public async removeRecord(domainNameArg: string, typeArg: TDnsRecord): Promise<any> {
const domain = new plugins.smartstring.Domain(domainNameArg);
const cflareRecord = await this.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}`);
}
}
/**
* updates a record
* @param domainNameArg
* @param typeArg
* @param valueArg
*/
public updateRecord(domainNameArg: string, typeArg: string, valueArg) {
// TODO: implement
const done = plugins.smartpromise.defer();
const domain = new plugins.smartstring.Domain(domainNameArg);
return done.promise;
}
/**
* list all records of a specified domain name
* @param domainNameArg - the domain name that you want to get the records from
*/
public async listRecords(domainNameArg: string): Promise<interfaces.ICflareRecord[]> {
const domain = new plugins.smartstring.Domain(domainNameArg);
const domainId = await this.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
*/
public async listZones(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;
}
public async purgeZone(domainName: string) {
const domain = new plugins.smartstring.Domain(domainName);
const domainId = await this.getZoneId(domain.zoneName);
const requestUrl = `/zones/${domainId}/purge_cache`;
const payload = {
purge_everything: true
};
const respone = await this.request('DELETE', requestUrl, payload);
}
public request(
public async request(
methodArg: string,
routeArg: string,
dataArg: any = {},
requestHeadersArg = {}
): Promise<any> {
const done = plugins.smartpromise.defer();
const options: plugins.smartrequest.ISmartRequestOptions = {
method: methodArg,
headers: {
'Content-Type': 'application/json',
'X-Auth-Email': this.authEmail,
'X-Auth-Key': this.authKey,
Authorization: `Bearer ${this.authToken}`,
'Content-Length': Buffer.byteLength(JSON.stringify(dataArg)),
...requestHeadersArg
...requestHeadersArg,
},
requestBody: dataArg
requestBody: dataArg,
};
// route analysis
const routeWithoutQuery = routeArg.split('?')[0];
let queryParams: string[] = [];
if (routeArg.split('?').length > 1) {
queryParams = routeArg.split('?')[1].split('&');
}
// console.log(options);
let retryCount = 0; // count the amount of retries
let pageCount = 1;
const makeRequest = async () => {
const response: any = await plugins.smartrequest.request(
`https://api.cloudflare.com/client/v4${routeArg}`,
options
);
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) {
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) {
console.log('rate limited! Waiting for retry!');
retryRequest();
return await retryRequest();
} else if (response.statusCode === 400) {
console.log(`bad request for route ${routeArg}! Going to retry!`);
console.log(`bad request for route ${requestUrl}!`);
console.log(response.body);
throw new Error(`request failed for ${requestUrl}`);
} else {
console.log(response.statusCode);
done.reject(new Error('request failed'));
console.log(response.body);
throw new Error(`request failed for ${requestUrl} with status${response.statusCode}}`);
}
};
const retryRequest = async (
delayTimeArg = Math.floor(Math.random() * (60000 - 8000) + 8000)
) => {
@ -214,11 +280,11 @@ export class CloudflareAccount {
return await makeRequest();
}
};
makeRequest();
return done.promise;
const response = await makeRequest();
return response.body;
}
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,3 @@
import * as plugins from './cloudflare.plugins.js';
export class CloudflareRecord {}

View File

@ -1,6 +1,7 @@
import * as plugins from './cloudflare.plugins';
import * as interfaces from './interfaces';
import { WorkerManager } from './cloudflare.classes.workermanager';
import * as plugins from './cloudflare.plugins.js';
import * as interfaces from './interfaces/index.js';
import { WorkerManager } from './cloudflare.classes.workermanager.js';
import { logger } from './cloudflare.logger.js';
export interface IWorkerRoute extends interfaces.ICflareWorkerRoute {
zoneName: string;
@ -8,16 +9,19 @@ export interface IWorkerRoute extends interfaces.ICflareWorkerRoute {
export class CloudflareWorker {
// STATIC
public static async fromApiObject(workerManager: WorkerManager, apiObject): Promise<CloudflareWorker> {
public static async fromApiObject(
workerManager: WorkerManager,
apiObject
): Promise<CloudflareWorker> {
const newWorker = new CloudflareWorker(workerManager);
Object.assign(newWorker, apiObject.result);
Object.assign(newWorker, apiObject);
await newWorker.getRoutes();
return newWorker;
}
// INSTANCE
private workerManager: WorkerManager;
public script: string;
public id: string;
public etag: string;
@ -35,22 +39,24 @@ export class CloudflareWorker {
* gets all routes for a worker
*/
public async getRoutes() {
const zones = await this.workerManager.cfAccount.listZones();
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);
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});
this.routes.push({ ...route, zoneName: zone.name });
}
}
}
}
public async setRoutes(routeArray: Array<{zoneName: string, pattern: string}>) {
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';
@ -61,25 +67,25 @@ export class CloudflareWorker {
routeIdForUpdate = existingRoute.id;
if (existingRoute.script === this.id) {
routeStatus = 'alreadyUpToDate';
plugins.smartlog.defaultLogger.log('info', `route already exists, no update needed`);
logger.log('info', `route already exists, no update needed`);
}
}
}
// lets care about actually setting routes
if (routeStatus === 'new') {
const zoneId = await this.workerManager.cfAccount.getZoneId(newRoute.zoneName);
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
script: this.id,
});
} else if (routeStatus === 'needsUpdate') {
const zoneId = await this.workerManager.cfAccount.getZoneId(newRoute.zoneName);
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
script: this.id,
});
}
}

View File

@ -1,6 +1,6 @@
import * as plugins from './cloudflare.plugins';
import { CloudflareAccount } from './cloudflare.classes.account';
import { CloudflareWorker } from './cloudflare.classes.worker';
import * as plugins from './cloudflare.plugins.js';
import { CloudflareAccount } from './cloudflare.classes.account.js';
import { CloudflareWorker } from './cloudflare.classes.worker.js';
export class WorkerManager {
public cfAccount: CloudflareAccount;
@ -14,9 +14,9 @@ export class WorkerManager {
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)
'Content-Length': Buffer.byteLength(workerScript),
});
return CloudflareWorker.fromApiObject(this, responseBody);
return CloudflareWorker.fromApiObject(this, responseBody.result);
}
/**
@ -26,6 +26,11 @@ export class WorkerManager {
const accountIdentifier = await this.cfAccount.getAccountIdentifier();
const route = `/accounts/${accountIdentifier}/workers/scripts`;
const response = await this.cfAccount.request('GET', route);
console.log(response);
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,50 @@
import * as plugins from './cloudflare.plugins';
import * as interfaces from './interfaces';
import * as plugins from './cloudflare.plugins.js';
import * as interfaces from './interfaces/index.js';
export class CloudflareZone {
// TODO
}
export class CloudflareZone implements interfaces.ICflareZone {
public static createFromApiObject(apiObject: interfaces.ICflareZone) {
const cloudflareZone = new CloudflareZone();
Object.assign(cloudflareZone, apiObject);
return cloudflareZone;
}
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;
}

View File

@ -1,5 +1,7 @@
import * as plugins from './cloudflare.plugins';
import { CloudflareAccount } from './cloudflare.classes.account';
import * as plugins from './cloudflare.plugins.js';
import * as interfaces from './interfaces/index.js';
import { CloudflareAccount } from './cloudflare.classes.account.js';
import { CloudflareZone } from './cloudflare.classes.zone.js';
export class ZoneManager {
public cfAccount: CloudflareAccount;
@ -8,4 +10,23 @@ export class ZoneManager {
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;
}
}

3
ts/cloudflare.logger.ts Normal file
View File

@ -0,0 +1,3 @@
import * as plugins from './cloudflare.plugins.js';
export const logger = new plugins.smartlog.ConsoleLog();

View File

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

View File

@ -12,4 +12,4 @@ export interface ICflareRecord {
created_on: string;
modified_on: string;
data: any;
}
}

View File

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

11
tsconfig.json Normal file
View File

@ -0,0 +1,11 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "nodenext",
"esModuleInterop": true,
"verbatimModuleSyntax": true,
}
}

View File

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