Compare commits

...

53 Commits

Author SHA1 Message Date
cd2cfce683 3.0.13 2021-01-22 22:59:28 +00:00
44ab180474 fix(core): update 2021-01-22 22:59:27 +00:00
15557dfdd6 3.0.12 2021-01-22 20:31:56 +00:00
488f616d34 fix(core): update 2021-01-22 20:31:55 +00:00
e920406ce9 3.0.11 2021-01-22 18:47:02 +00:00
e044fd81bd fix(core): update 2021-01-22 18:47:01 +00:00
edaccc357d 3.0.10 2021-01-22 18:33:53 +00:00
67f645ad50 fix(core): update 2021-01-22 18:33:53 +00:00
bfeced5f34 3.0.9 2020-11-18 16:52:50 +00:00
24b9794a18 fix(core): update 2020-11-18 16:52:49 +00:00
a781329a47 3.0.8 2020-08-13 03:10:38 +00:00
6b5e0a1207 fix(core): update 2020-08-13 03:10:37 +00:00
2455adfbca 3.0.7 2020-08-12 16:36:06 +00:00
a2cf86b62f fix(core): update 2020-08-12 16:36:06 +00:00
7277906851 3.0.6 2020-05-17 16:21:26 +00:00
9da9ebb01e fix(core): update 2020-05-17 16:21:25 +00:00
f70684b773 3.0.5 2020-02-21 10:48:09 +00:00
8b19b206a4 fix(core): update 2020-02-21 10:48:08 +00:00
6be2866ddd 3.0.4 2020-02-19 19:17:59 +00:00
ab55d3c91a fix(core): update 2020-02-19 19:17:58 +00:00
c7ee7eb774 3.0.3 2020-02-19 18:48:50 +00:00
02daa13a2f fix(core): update 2020-02-19 18:48:49 +00:00
28944b1100 3.0.2 2020-02-10 20:36:02 +00:00
7ec04d6d3d fix(core): update 2020-02-10 20:36:01 +00:00
595d4d8894 3.0.1 2020-02-10 20:16:50 +00:00
04ed28f7d1 fix(core): update 2020-02-10 20:16:49 +00:00
6c95cec709 3.0.0 2020-02-10 20:13:07 +00:00
59173b3ca8 BREAKING CHANGE(core): streamline scope to certificate retrieval using dns challenge 2020-02-10 20:13:06 +00:00
c2036bba90 2.1.2 2020-02-10 11:15:48 +00:00
83afea95e6 fix(core): update 2020-02-10 11:15:47 +00:00
ac515f5e80 2.1.1 2020-01-19 11:09:32 +00:00
6abbf58b83 fix(core): update 2020-01-19 11:09:32 +00:00
9c25ecdc02 2.1.0 2019-02-06 14:37:01 +01:00
81a15da2d0 feat(Cert): now has validity check 2019-02-06 14:37:00 +01:00
86929251ba update 2019-02-06 09:47:33 +01:00
1d8fb2b296 2.0.36 2019-01-18 01:35:00 +01:00
9d5f0d7a5d fix(core): update 2019-01-18 01:34:59 +01:00
82b1d68576 2.0.35 2019-01-17 22:50:22 +01:00
e04b23aceb fix(core): update 2019-01-17 22:50:21 +01:00
8e255938b5 2.0.34 2019-01-17 22:47:58 +01:00
f2eb9666a7 fix(core): update 2019-01-17 22:47:58 +01:00
cbdb0c8b08 2.0.33 2019-01-17 22:13:10 +01:00
f821f4d9cc fix(core): update 2019-01-17 22:13:10 +01:00
6cfcf21d95 2.0.32 2019-01-17 01:15:22 +01:00
a33090bb5e fix(core): update 2019-01-17 01:15:22 +01:00
3151829f85 2.0.31 2019-01-16 22:34:38 +01:00
eca63e588c fix(core): update 2019-01-16 22:34:38 +01:00
9d23e205d8 2.0.30 2019-01-16 02:34:48 +01:00
5ecdf7c9fd fix(core): update 2019-01-16 02:34:47 +01:00
2817a65e21 2.0.29 2019-01-15 23:59:21 +01:00
09a8bc5cb5 fix(core): update 2019-01-15 23:59:21 +01:00
a1134cf227 2.0.28 2019-01-15 23:39:31 +01:00
4ee1c4b08c fix(core): update 2019-01-15 23:39:31 +01:00
21 changed files with 9982 additions and 1552 deletions

19
.gitignore vendored
View File

@ -1,5 +1,20 @@
node_modules/
.nogit/
# artifacts
coverage/
public/
pages/
.nogit/
# installs
node_modules/
# caches
.yarn/
.cache/
.rpt2_cache
# builds
dist/
dist_*/
# custom

View File

@ -1,10 +1,10 @@
# gitzone standard
image: hosttoday/ht-docker-node:npmci
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: "$CI_BUILD_STAGE"
key: '$CI_BUILD_STAGE'
stages:
- security
@ -19,63 +19,41 @@ mirror:
stage: security
script:
- npmci git mirror
only:
- tags
tags:
- lossless
- docker
- notpriv
snyk:
auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- 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
auditDevDependencies:
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 config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high --only=dev
tags:
- docker
- notpriv
sast:
stage: security
image: registry.gitlab.com/hosttoday/ht-docker-dbase:npmci
variables:
DOCKER_DRIVER: overlay2
allow_failure: true
services:
- docker:stable-dind
script:
- npmci npm prepare
- npmci npm install
- npmci command npm run build
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SAST_CONFIDENCE_LEVEL="${SAST_CONFIDENCE_LEVEL:-3}"
--volume "$PWD:/code"
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/sast:$SP_VERSION" /app/bin/run /code
artifacts:
reports:
sast: gl-sast-report.json
tags:
- docker
- priv
# ====================
# test stage
# ====================
testLTS:
stage: test
script:
- npmci npm prepare
- npmci node install lts
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
testSTABLE:
testStable:
stage: test
script:
- npmci npm prepare
@ -85,7 +63,17 @@ testSTABLE:
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
release:
stage: release
@ -95,6 +83,7 @@ release:
only:
- tags
tags:
- lossless
- docker
- notpriv
@ -103,20 +92,16 @@ release:
# ====================
codequality:
stage: metadata
image: docker:stable
allow_failure: true
services:
- docker:stable-dind
only:
- tags
script:
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SOURCE_CODE="$PWD"
--volume "$PWD":/code
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
artifacts:
paths: [codeclimate.json]
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
@ -127,18 +112,20 @@ trigger:
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
image: hosttoday/ht-docker-node:npmci
stage: metadata
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 command typedoc --module "commonjs" --target "ES2016" --out public/ ts/
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:

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

View File

@ -1,63 +0,0 @@
# smartacme
acme implementation in TypeScript
## Availabililty
[![npm](https://umbrellazone.gitlab.io/assets/repo-button-npm.svg)](https://www.npmjs.com/package/smartacme)
[![git](https://umbrellazone.gitlab.io/assets/repo-button-git.svg)](https://GitLab.com/umbrellazone/smartacme)
[![git](https://umbrellazone.gitlab.io/assets/repo-button-mirror.svg)](https://github.com/umbrellazone/smartacme)
[![docs](https://umbrellazone.gitlab.io/assets/repo-button-docs.svg)](https://umbrellazone.gitlab.io/smartacme/)
## Status for master
[![build status](https://GitLab.com/umbrellazone/smartacme/badges/master/build.svg)](https://GitLab.com/umbrellazone/smartacme/commits/master)
[![coverage report](https://GitLab.com/umbrellazone/smartacme/badges/master/coverage.svg)](https://GitLab.com/umbrellazone/smartacme/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/smartacme.svg)](https://www.npmjs.com/package/smartacme)
[![Dependency Status](https://david-dm.org/umbrellazone/smartacme.svg)](https://david-dm.org/umbrellazone/smartacme)
[![bitHound Dependencies](https://www.bithound.io/github/umbrellazone/smartacme/badges/dependencies.svg)](https://www.bithound.io/github/umbrellazone/smartacme/master/dependencies/npm)
[![bitHound Code](https://www.bithound.io/github/umbrellazone/smartacme/badges/code.svg)](https://www.bithound.io/github/umbrellazone/smartacme)
[![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 { SmartAcme } from 'smartacme';
let smac = new SmartAcme()(async () => {
// learn async/await, it'll make your life easier
// optionally accepts a filePath Arg with a stored acmeaccount.json
// will create an account and
let myAccount = await smac.createAcmeAccount();
// will return a dnsHash to set in your DNS record
let myCert = await myAccount.createAcmeCert('example.com');
// gets and accepts the specified challenge
// first argument optional, defaults to dns-01 (which is the cleanest method for production use)
let myChallenge = await myCert.getChallenge('dns-01');
/* ----------
Now you need to set the challenge in your DNS
myChallenge.domainNamePrefixed is the address for the record
myChallenge.dnsKeyHash is the ready to use txt record value expected by letsencrypt
-------------*/
})();
```
## Other relevant npm modules
| module name | description |
| ----------- | ------------------------------------------------------------------- |
| cert | a higlevel production module that uses smartacme to manage certs |
| smartnginx | a highlevel production tool for docker environments to manage nginx |
> 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://umbrellazone.gitlab.io/assets/repo-footer.svg)](https://umbrella.zone

View File

@ -1,4 +1,16 @@
{
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"gitrepo": "smartacme",
"shortDescription": "acme with an easy yet powerful interface in TypeScript",
"npmPackagename": "@pushrocks/smartacme",
"license": "MIT",
"projectDomain": "push.rocks"
}
},
"npmci": {
"npmGlobalTools": [],
"npmAccessLevel": "public"

10765
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,13 @@
{
"name": "@pushrocks/smartacme",
"version": "2.0.27",
"version": "3.0.13",
"private": false,
"description": "acme implementation in TypeScript",
"main": "dist/index.js",
"typings": "dist/index.d.ts",
"description": "acme with an easy yet powerful interface in TypeScript",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"scripts": {
"test": "(tstest test/)",
"build": "(tsbuild)"
"build": "(tsbuild --web)"
},
"repository": {
"type": "git",
@ -25,27 +25,44 @@
},
"homepage": "https://gitlab.com/umbrellazone/smartacme#README",
"dependencies": {
"@pushrocks/lik": "^3.0.4",
"@pushrocks/smartdata": "^3.1.13",
"@pushrocks/smartdelay": "^2.0.2",
"@pushrocks/smartdns": "^3.0.8",
"@pushrocks/smartexpress": "^3.0.4",
"@pushrocks/smartpromise": "^2.0.5",
"@pushrocks/smartrequest": "^1.1.14",
"@pushrocks/smartstring": "^3.0.8",
"@pushrocks/smarttime": "^3.0.5",
"@pushrocks/smartunique": "^3.0.1",
"acme-client": "2.2.2"
"@pushrocks/lik": "^4.0.20",
"@pushrocks/smartdata": "^3.1.54",
"@pushrocks/smartdelay": "^2.0.10",
"@pushrocks/smartdns": "^4.0.7",
"@pushrocks/smartexpress": "^3.0.100",
"@pushrocks/smartlog": "^2.0.39",
"@pushrocks/smartpromise": "^3.1.3",
"@pushrocks/smartrequest": "^1.1.51",
"@pushrocks/smartstring": "^3.0.24",
"@pushrocks/smarttime": "^3.0.38",
"@pushrocks/smartunique": "^3.0.3",
"@tsclass/tsclass": "^3.0.29",
"acme-client": "^4.1.2"
},
"devDependencies": {
"@gitzone/tsbuild": "^2.1.4",
"@gitzone/tsrun": "^1.1.17",
"@gitzone/tstest": "^1.0.18",
"@mojoio/cloudflare": "^2.0.0",
"@pushrocks/qenv": "^3.0.2",
"@pushrocks/tapbundle": "^3.0.7",
"@types/node": "^10.12.18",
"tslint": "^5.12.0",
"tslint-config-prettier": "^1.17.0"
}
"@gitzone/tsbuild": "^2.1.25",
"@gitzone/tsrun": "^1.2.12",
"@gitzone/tstest": "^1.0.52",
"@mojoio/cloudflare": "^5.0.9",
"@pushrocks/qenv": "^4.0.10",
"@pushrocks/tapbundle": "^3.2.9",
"@types/node": "^14.14.22",
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.18.0"
},
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
],
"browserslist": [
"last 1 chrome versions"
]
}

View File

@ -1,6 +1,5 @@
required:
- CF_EMAIL
- CF_KEY
- CF_TOKEN
- MONGODB_URL
- MONGODB_PASSWORD
- MONGODB_DATABASE

66
readme.md Normal file
View File

@ -0,0 +1,66 @@
# @pushrocks/smartacme
acme with an easy yet powerful interface in TypeScript
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartacme)
* [gitlab.com (source)](https://gitlab.com/pushrocks/smartacme)
* [github.com (source mirror)](https://github.com/pushrocks/smartacme)
* [docs (typedoc)](https://pushrocks.gitlab.io/smartacme/)
## Status for master
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/smartacme/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/smartacme/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/smartacme)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/smartacme)](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/@pushrocks/smartacme)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/smartacme)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/smartacme)](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 { SmartAcme } from 'smartacme';
const run = async () => {
smartAcmeInstance = new smartacme.SmartAcme({
accountEmail: 'domains@lossless.org',
accountPrivateKey: null,
mongoDescriptor: {
mongoDbName: testQenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'),
mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL'),
},
removeChallenge: async (dnsChallenge) => {
// somehow provide a function that is able to remove the dns challenge
},
setChallenge: async (dnsChallenge) => {
// somehow provide a function that is able to the dns challenge
},
environment: 'integration',
});
await smartAcmeInstance.init();
// myCert has properties for public/private keys and csr ;)
const myCert = await smartAcmeInstance.getCertificateForDomain('bleu.de');
};
```
## 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,7 +1,9 @@
import { tap, expect } from '@pushrocks/tapbundle';
import { Qenv } from '@pushrocks/qenv';
import * as cloudflare from '@mojoio/cloudflare';
const testQenv = new Qenv('./', './.nogit/');
const testCloudflare = new cloudflare.CloudflareAccount(testQenv.getEnvVarOnDemand('CF_TOKEN'));
import * as smartacme from '../ts/index';
@ -12,22 +14,24 @@ tap.test('should create a valid instance of SmartAcme', async () => {
accountEmail: 'domains@lossless.org',
accountPrivateKey: null,
mongoDescriptor: {
mongoDbName: testQenv.getEnvVarOnDemand('MONGODB_DATABASE'),
mongoDbPass: testQenv.getEnvVarOnDemand('MONGODB_PASSWORD'),
mongoDbUrl: testQenv.getEnvVarOnDemand('MONGODB_URL')
mongoDbName: testQenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'),
mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL'),
},
removeChallenge: async (...args) => {
console.log(args);
removeChallenge: async (dnsChallenge) => {
testCloudflare.convenience.acmeRemoveDnsChallenge(dnsChallenge);
},
setChallenge: async (...args) => {
console.log(args);
setChallenge: async (dnsChallenge) => {
testCloudflare.convenience.acmeSetDnsChallenge(dnsChallenge);
},
validateRemoteRequest: async () => {
return true;
}
environment: 'integration',
});
await smartAcmeInstance.init();
// await smartAcmeInstance.getCertificateForDomain('bleu.de');
});
tap.test('should get a domain certificate', async () => {
const certificate = await smartAcmeInstance.getCertificateForDomain('bleu.de');
console.log(certificate);
});
tap.test('certmatcher should correctly match domains', async () => {

View File

@ -1,3 +1 @@
export * from './smartacme.classes.smartacme';
export * from './smartacme.classes.certremoteclient';

View File

@ -1,9 +0,0 @@
export type TCertStatus = 'existing' | 'nonexisting' | 'pending' | 'failed';
export interface ICert {
domainName: string;
created: number;
privateKey: string;
publicKey: string;
csr: string;
}

View File

@ -1,11 +0,0 @@
import { ICert, TCertStatus } from './cert';
export interface ICertRemoteRequest {
secret: string;
domainName: string;
}
export interface ICertRemoteResponse {
status: TCertStatus;
certificate?: ICert;
}

View File

@ -1,3 +1 @@
export * from './accountdata';
export * from './cert';
export * from './certremote';

View File

@ -5,14 +5,14 @@ import * as interfaces from './interfaces';
import { CertManager } from './smartacme.classes.certmanager';
import { Collection, svDb, unI } from '@pushrocks/smartdata';
import { ICert } from './interfaces';
@plugins.smartdata.Collection(() => {
return CertManager.activeDB;
})
export class Cert extends plugins.smartdata.SmartDataDbDoc<Cert> implements interfaces.ICert {
export class Cert extends plugins.smartdata.SmartDataDbDoc<Cert, plugins.tsclass.network.ICert>
implements plugins.tsclass.network.ICert {
@unI()
public index: string;
public id: string;
@svDb()
public domainName: string;
@ -29,10 +29,32 @@ export class Cert extends plugins.smartdata.SmartDataDbDoc<Cert> implements inte
@svDb()
public csr: string;
constructor(optionsArg: ICert) {
@svDb()
public validUntil: number;
public isStillValid(): boolean {
return this.validUntil >= Date.now();
}
public shouldBeRenewed(): boolean {
const shouldBeValidAtLeastUntil =
Date.now() +
plugins.smarttime.getMilliSecondsFromUnits({
days: 10,
});
return !(this.validUntil >= shouldBeValidAtLeastUntil);
}
public update(certDataArg: plugins.tsclass.network.ICert) {
Object.keys(certDataArg).forEach((key) => {
this[key] = certDataArg[key];
});
}
constructor(optionsArg: plugins.tsclass.network.ICert) {
super();
if (optionsArg) {
Object.keys(optionsArg).forEach(key => {
Object.keys(optionsArg).forEach((key) => {
this[key] = optionsArg[key];
});
}

View File

@ -4,25 +4,26 @@ import { SmartAcme } from './smartacme.classes.smartacme';
import * as interfaces from './interfaces';
export class CertManager {
// =========
// STATIC
// =========
public static activeDB: plugins.smartdata.SmartdataDb;
// =========
// INSTANCE
// =========
private mongoDescriptor: plugins.smartdata.IMongoDescriptor;
public smartdataDb: plugins.smartdata.SmartdataDb;
public pendingMap: plugins.lik.Stringmap;
public interestMap: plugins.lik.InterestMap<string, Cert>;
constructor(smartAcmeArg: SmartAcme,optionsArg: {
constructor(
smartAcmeArg: SmartAcme,
optionsArg: {
mongoDescriptor: plugins.smartdata.IMongoDescriptor;
}) {
}
) {
this.mongoDescriptor = optionsArg.mongoDescriptor;
}
@ -33,18 +34,17 @@ export class CertManager {
CertManager.activeDB = this.smartdataDb;
// Pending Map
this.pendingMap = new plugins.lik.Stringmap();
this.interestMap = new plugins.lik.InterestMap((certName) => certName);
}
/**
* retrieves a certificate
* @returns the Cert class or null
* @param domainName the domain Name to retrieve the vcertificate for
* @param certDomainNameArg the domain Name to retrieve the vcertificate for
*/
public async retrieveCertificate(domainName: string): Promise<Cert> {
await this.checkCerts();
const existingCertificate: Cert = await Cert.getInstance({
domainName
public async retrieveCertificate(certDomainNameArg: string): Promise<Cert> {
const existingCertificate: Cert = await Cert.getInstance<Cert>({
domainName: certDomainNameArg,
});
if (existingCertificate) {
@ -52,41 +52,26 @@ export class CertManager {
} else {
return null;
}
}
/**
* stores the certificate with the
* @param publicKeyArg
* @param privateKeyArg
* @param csrArg
* stores the certificate
* @param optionsArg
*/
public async storeCertificate(optionsArg: interfaces.ICert) {
public async storeCertificate(optionsArg: plugins.tsclass.network.ICert) {
const cert = new Cert(optionsArg);
await cert.save();
const interest = this.interestMap.findInterest(cert.domainName);
if (interest) {
interest.fullfillInterest(cert);
interest.markLost();
}
}
public async deleteCertificate(domainNameArg: string) {
public async deleteCertificate(certDomainNameArg: string) {
const cert: Cert = await Cert.getInstance<Cert>({
domainName: certDomainNameArg,
});
await cert.delete();
}
public async getCertificateStatus(domainNameArg: string): Promise<interfaces.TCertStatus> {
const isPending = this.pendingMap.checkString('domainNameArg');
if (isPending) {
return 'pending';
}
// otherwise lets continue
const existingCertificate = this.retrieveCertificate(domainNameArg);
if (existingCertificate) {
return 'existing';
}
return 'nonexisting';
}
/**
* checks all certs for expiration
*/
private async checkCerts() {};
}

View File

@ -1,6 +1,15 @@
import * as plugins from './smartacme.plugins';
import * as interfaces from './interfaces';
/**
* certmatcher is responsible for matching certificates
*/
export class CertMatcher {
/**
* creates a domainName for the certificate that will include the broadest scope
* for wild card certificates
* @param domainNameArg the domainNameArg to create the scope from
*/
public getCertificateDomainNameByDomainName(domainNameArg: string): string {
const originalDomain = new plugins.smartstring.Domain(domainNameArg);
if (!originalDomain.level4) {

View File

@ -1,47 +0,0 @@
import * as plugins from './smartacme.plugins';
import * as interfaces from './interfaces';
import { ICertRemoteResponse } from './interfaces';
// tslint:disable-next-line: max-classes-per-file
export class CertRemoteClient {
private remoteUrl: string;
private secret: string;
constructor(optionsArg: {
remoteUrl: string;
secret: string;
}) {
this.remoteUrl = optionsArg.remoteUrl;
this.secret = optionsArg.secret;
}
/**
*
* @param domainNameArg
*/
async getCertificateForDomain(domainNameArg: string): Promise<interfaces.ICert> {
let certificate: interfaces.ICert;
const doRequestCycle = async (): Promise<interfaces.ICert> => {
const response: ICertRemoteResponse = (await plugins.smartrequest.postJson(this.remoteUrl, {
requestBody: <interfaces.ICertRemoteRequest>{
domainName: domainNameArg,
secret: this.secret
}
})).body;
switch(response.status) {
case 'pending':
await plugins.smartdelay.delayFor(5000);
const finalResponse = await doRequestCycle();
return finalResponse;
case 'existing':
return response.certificate;
case 'failed':
default:
console.log(`could not retrieve certificate for ${domainNameArg}`);
return null;
}
};
certificate = await doRequestCycle();
return certificate;
}
}

View File

@ -3,9 +3,6 @@ import { Cert } from './smartacme.classes.cert';
import { CertManager } from './smartacme.classes.certmanager';
import { CertMatcher } from './smartacme.classes.certmatcher';
import * as interfaces from './interfaces';
import { request } from 'http';
/**
* the options for the class @see SmartAcme
*/
@ -13,8 +10,8 @@ export interface ISmartAcmeOptions {
accountPrivateKey?: string;
accountEmail: string;
mongoDescriptor: plugins.smartdata.IMongoDescriptor;
setChallenge: (domainName: string, keyAuthorization: string) => Promise<any>;
removeChallenge: (domainName: string) => Promise<any>;
setChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
removeChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
environment: 'production' | 'integration';
}
@ -33,26 +30,23 @@ export class SmartAcme {
// the acme client
private client: any;
private smartdns = new plugins.smartdns.Smartdns();
private smartdns = new plugins.smartdns.Smartdns({});
public logger: plugins.smartlog.ConsoleLog;
// the account private key
private privateKey: string;
// challenge fullfillment
private setChallenge: (domainName: string, keyAuthorization: string) => Promise<any>;
private removeChallenge: (domainName: string) => Promise<any>;
private setChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
private removeChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
// certmanager
private certmanager: CertManager;
private certmatcher: CertMatcher;
/**
* the remote handler to hand the request and response to.
*/
public certremoteHandler: (req: plugins.smartexpress.Request, res: plugins.smartexpress.Response) => Promise<any>;
constructor(optionsArg: ISmartAcmeOptions) {
this.options = optionsArg;
this.logger = new plugins.smartlog.ConsoleLog();
}
/**
@ -63,45 +57,19 @@ export class SmartAcme {
*/
public async init() {
this.privateKey =
this.options.accountPrivateKey || (await plugins.acme.forge.createPrivateKey());
this.options.accountPrivateKey || (await plugins.acme.forge.createPrivateKey()).toString();
this.setChallenge = this.options.setChallenge;
this.removeChallenge = this.options.removeChallenge;
// CertMangaer
this.certmanager = new CertManager(this, {
mongoDescriptor: this.options.mongoDescriptor
mongoDescriptor: this.options.mongoDescriptor,
});
await this.certmanager.init();
// CertMatcher
this.certmatcher = new CertMatcher();
// CertRemoteHandler
this.certremoteHandler = async (req, res) => {
const requestBody: interfaces.ICertRemoteRequest = req.body;
const status: interfaces.TCertStatus = await this.certmanager.getCertificateStatus(requestBody.domainName);
const existingCertificate = await this.certmanager.retrieveCertificate(
requestBody.domainName
);
let response: interfaces.ICertRemoteResponse;
switch (status) {
case 'existing':
response = {
status,
certificate: await existingCertificate.createSavableObject()
};
break;
default:
response = {
status
};
break;
}
res.status(200);
res.send(response);
res.end();
};
// ACME Client
this.client = new plugins.acme.Client({
directoryUrl: (() => {
@ -111,13 +79,13 @@ export class SmartAcme {
return plugins.acme.directory.letsencrypt.staging;
}
})(),
accountKey: this.privateKey
accountKey: this.privateKey,
});
/* Register account */
await this.client.createAccount({
termsOfServiceAgreed: true,
contact: [`mailto:${this.options.accountEmail}`]
contact: [`mailto:${this.options.accountEmail}`],
});
}
@ -125,18 +93,46 @@ export class SmartAcme {
await this.certmanager.smartdataDb.close();
}
/**
* gets a certificate
* it runs through the following steps
*
* * look in the database
* * if in the database and still valid return it
* * if not in the database announce it
* * then get it from letsencrypt
* * store it
* * remove it from the pending map (which it go onto by announcing it)
* * retrieve it from the databse and return it
*
* @param domainArg
*/
public async getCertificateForDomain(domainArg: string): Promise<Cert> {
const certDomain = this.certmatcher.getCertificateDomainNameByDomainName(domainArg);
const certDomainName = this.certmatcher.getCertificateDomainNameByDomainName(domainArg);
const retrievedCertificate = await this.certmanager.retrieveCertificate(certDomainName);
const retrievedCertificate = await this.certmanager.retrieveCertificate(certDomain);
if (retrievedCertificate) {
if (
!retrievedCertificate &&
(await this.certmanager.interestMap.checkInterest(certDomainName))
) {
const existingCertificateInterest = this.certmanager.interestMap.findInterest(certDomainName);
const certificate = existingCertificateInterest.interestFullfilled;
return certificate;
} else if (retrievedCertificate && !retrievedCertificate.shouldBeRenewed()) {
return retrievedCertificate;
} else if (retrievedCertificate && retrievedCertificate.shouldBeRenewed()) {
await retrievedCertificate.delete();
}
// lets make sure others get the same interest
const currentDomainInterst = await this.certmanager.interestMap.addInterest(certDomainName);
/* Place new order */
const order = await this.client.createOrder({
identifiers: [{ type: 'dns', value: certDomain }, { type: 'dns', value: `*.${certDomain}` }]
identifiers: [
{ type: 'dns', value: certDomainName },
{ type: 'dns', value: `*.${certDomainName}` },
],
});
/* Get authorizations and select challenges */
@ -144,8 +140,8 @@ export class SmartAcme {
for (const authz of authorizations) {
console.log(authz);
const domainDnsName: string = `_acme-challenge.${authz.identifier.value}`;
const dnsChallenge: string = authz.challenges.find(challengeArg => {
const fullHostName: string = `_acme-challenge.${authz.identifier.value}`;
const dnsChallenge: string = authz.challenges.find((challengeArg) => {
return challengeArg.type === 'dns-01';
});
// process.exit(1);
@ -153,8 +149,12 @@ export class SmartAcme {
try {
/* Satisfy challenge */
await this.setChallenge(domainDnsName, keyAuthorization);
await this.smartdns.checkUntilAvailable(domainDnsName, 'TXT', keyAuthorization, 100, 5000);
await this.setChallenge({
hostName: fullHostName,
challenge: keyAuthorization,
});
await plugins.smartdelay.delayFor(30000);
await this.smartdns.checkUntilAvailable(fullHostName, 'TXT', keyAuthorization, 100, 5000);
console.log('Cool down an extra 60 second for region availability');
await plugins.smartdelay.delayFor(60000);
@ -169,7 +169,10 @@ export class SmartAcme {
} finally {
/* Clean up challenge response */
try {
await this.removeChallenge(domainDnsName);
await this.removeChallenge({
hostName: fullHostName,
challenge: keyAuthorization,
});
} catch (e) {
console.log(e);
}
@ -178,27 +181,32 @@ export class SmartAcme {
/* Finalize order */
const [key, csr] = await plugins.acme.forge.createCsr({
commonName: `*.${certDomain}`,
altNames: [certDomain]
commonName: `*.${certDomainName}`,
altNames: [certDomainName],
});
await this.client.finalizeOrder(order, csr);
const cert = await this.client.getCertificate(order);
/* Done */
console.log(`CSR:\n${csr.toString()}`);
console.log(`Private key:\n${key.toString()}`);
console.log(`Certificate:\n${cert.toString()}`);
await this.certmanager.storeCertificate({
domainName: certDomain,
id: plugins.smartunique.shortId(),
domainName: certDomainName,
privateKey: key.toString(),
publicKey: cert.toString(),
csr: csr.toString(),
created: Date.now()
created: Date.now(),
validUntil:
Date.now() +
plugins.smarttime.getMilliSecondsFromUnits({
days: 90,
}),
});
const newCertificate = await this.certmanager.retrieveCertificate(certDomain);
const newCertificate = await this.certmanager.retrieveCertificate(certDomainName);
currentDomainInterst.fullfillInterest(newCertificate);
currentDomainInterst.destroy();
return newCertificate;
}
}

View File

@ -4,15 +4,33 @@ import * as smartdata from '@pushrocks/smartdata';
import * as smartdelay from '@pushrocks/smartdelay';
import * as smartdns from '@pushrocks/smartdns';
import * as smartexpress from '@pushrocks/smartexpress';
import * as smartlog from '@pushrocks/smartlog';
import * as smartpromise from '@pushrocks/smartpromise';
import * as smartrequest from '@pushrocks/smartrequest';
import * as smartunique from '@pushrocks/smartunique';
import * as smartstring from '@pushrocks/smartstring';
import * as smarttime from '@pushrocks/smarttime';
export { lik, smartdata, smartdelay, smartdns, smartexpress, smartpromise, smartrequest, smartunique, smartstring, smarttime };
export {
lik,
smartdata,
smartdelay,
smartdns,
smartexpress,
smartlog,
smartpromise,
smartrequest,
smartunique,
smartstring,
smarttime,
};
// thirs party scope
// @tsclass scope
import * as tsclass from '@tsclass/tsclass';
export { tsclass };
// third party scope
import * as acme from 'acme-client';
export { acme };