Compare commits

...

69 Commits

Author SHA1 Message Date
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
08c3eaa65f 2.0.27 2019-01-14 02:46:36 +01:00
2717f08476 fix(core): update 2019-01-14 02:46:36 +01:00
f16dbeea32 2.0.26 2019-01-13 21:40:40 +01:00
a0c0230419 fix(core): update 2019-01-13 21:40:40 +01:00
0d1ebf2d1a 2.0.25 2019-01-13 19:40:32 +01:00
6edbf3cb46 fix(core): update 2019-01-13 19:40:32 +01:00
b26f7ac3e9 2.0.24 2019-01-13 19:15:04 +01:00
5129c5d601 fix(core): update 2019-01-13 19:15:03 +01:00
d09b3fd1bc 2.0.23 2019-01-13 02:11:56 +01:00
14fccd40d8 fix(core): update 2019-01-13 02:11:56 +01:00
c0f45a10e0 2.0.22 2019-01-13 02:10:00 +01:00
f9db3d28fe fix(core): update 2019-01-13 02:10:00 +01:00
c3fd8750b2 2.0.21 2019-01-13 00:50:44 +01:00
2b3c28c7a1 fix(core): update 2019-01-13 00:50:43 +01:00
d6b1f942b3 2.0.20 2019-01-13 00:24:40 +01:00
7eff6ea36a fix(core): update 2019-01-13 00:24:39 +01:00
1ef3615a49 2.0.19 2019-01-13 00:06:00 +01:00
3653cdc797 fix(core): update 2019-01-13 00:06:00 +01:00
c0271648fc 2.0.18 2019-01-12 21:06:29 +01:00
5546fa5f49 fix(core): update 2019-01-12 21:06:29 +01:00
54fe89860e 2.0.17 2019-01-12 19:12:53 +01:00
d1edf75f6f fix(core): update 2019-01-12 19:12:52 +01:00
6f9c644221 2.0.16 2019-01-12 19:11:39 +01:00
0b26054687 fix(core): update 2019-01-12 19:11:39 +01:00
e3323ed4ef 2.0.15 2019-01-12 13:52:21 +01:00
24f692636c fix(core): update 2019-01-12 13:52:21 +01:00
a9f709ee7b 2.0.14 2019-01-12 13:44:18 +01:00
1b11b637a5 fix(core): update 2019-01-12 13:44:18 +01:00
ad54bf41ea 2.0.13 2019-01-09 00:01:02 +01:00
060ebf1b29 fix(core): update 2019-01-09 00:01:01 +01:00
a87c6acb8a 2.0.12 2019-01-08 20:45:36 +01:00
62d27619f4 fix(core): update 2019-01-08 20:45:35 +01:00
0faebf2a79 2.0.11 2019-01-07 12:29:11 +01:00
29ea50796c fix(core): update 2019-01-07 12:29:10 +01:00
26d1b7cbf0 2.0.10 2019-01-07 01:08:50 +01:00
c0c97835ea fix(core): update 2019-01-07 01:08:50 +01:00
d4d50b7dcf 2.0.9 2019-01-07 01:00:58 +01:00
2492fd4de2 fix(core): update 2019-01-07 01:00:58 +01:00
bef54799b6 2.0.8 2019-01-07 00:36:51 +01:00
dbe09f320a fix(core): update 2019-01-07 00:36:51 +01:00
16 changed files with 2495 additions and 1033 deletions

21
.gitignore vendored
View File

@ -1,5 +1,22 @@
node_modules/ .nogit/
# artifacts
coverage/ coverage/
public/ public/
pages/ pages/
.nogit/
# installs
node_modules/
# caches
.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,127 +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 npm prepare - npmci npm prepare
- npmci command npm install -g snyk
- 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
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 # test stage
# ==================== # ====================
testLTS: testStable:
stage: test stage: test
script: script:
- npmci npm prepare - npmci npm prepare
- npmci node install lts - npmci node install stable
- npmci npm install - npmci npm install
- npmci npm test - 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 npm prepare - npmci npm prepare
- npmci node install stable - npmci node install stable
- npmci npm install - npmci npm install
- npmci npm test - 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 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:
@ -146,5 +122,5 @@ pages:
artifacts: artifacts:
expire_in: 1 week expire_in: 1 week
paths: paths:
- public - public
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,24 +1,19 @@
# smartacme # @pushrocks/smartuniverse
acme with an easy yet powerful interface in TypeScript
acme implementation in TypeScript ## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/smartuniverse)
## Availabililty * [gitlab.com (source)](https://gitlab.com/pushrocks/smartuniverse)
* [github.com (source mirror)](https://github.com/pushrocks/smartuniverse)
[![npm](https://umbrellazone.gitlab.io/assets/repo-button-npm.svg)](https://www.npmjs.com/package/smartacme) * [docs (typedoc)](https://pushrocks.gitlab.io/smartuniverse/)
[![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 ## Status for master
[![build status](https://gitlab.com/pushrocks/smartuniverse/badges/master/build.svg)](https://gitlab.com/pushrocks/smartuniverse/commits/master)
[![build status](https://GitLab.com/umbrellazone/smartacme/badges/master/build.svg)](https://GitLab.com/umbrellazone/smartacme/commits/master) [![coverage report](https://gitlab.com/pushrocks/smartuniverse/badges/master/coverage.svg)](https://gitlab.com/pushrocks/smartuniverse/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/@pushrocks/smartuniverse.svg)](https://www.npmjs.com/package/@pushrocks/smartuniverse)
[![npm downloads per month](https://img.shields.io/npm/dm/smartacme.svg)](https://www.npmjs.com/package/smartacme) [![Known Vulnerabilities](https://snyk.io/test/npm/@pushrocks/smartuniverse/badge.svg)](https://snyk.io/test/npm/@pushrocks/smartuniverse)
[![Dependency Status](https://david-dm.org/umbrellazone/smartacme.svg)](https://david-dm.org/umbrellazone/smartacme) [![TypeScript](https://img.shields.io/badge/TypeScript->=%203.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![bitHound Dependencies](https://www.bithound.io/github/umbrellazone/smartacme/badges/dependencies.svg)](https://www.bithound.io/github/umbrellazone/smartacme/master/dependencies/npm) [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
[![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/) [![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Usage ## Usage
@ -28,36 +23,14 @@ Use TypeScript for best in class instellisense.
```javascript ```javascript
import { SmartAcme } from 'smartacme'; import { SmartAcme } from 'smartacme';
let smac = new SmartAcme()(async () => { let smac = new SmartAcme()
// learn async/await, it'll make your life easier
// optionally accepts a filePath Arg with a stored acmeaccount.json // TODO
// 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 For further information read the linked docs at the top of this readme.
| 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) > MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
> | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html) | 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 [![repo-footer](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://maintainedby.lossless.com)

View File

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

2775
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +1,8 @@
{ {
"name": "@pushrocks/smartacme", "name": "@pushrocks/smartacme",
"version": "2.0.7", "version": "3.0.1",
"private": false, "private": false,
"description": "acme implementation in TypeScript", "description": "acme with an easy yet powerful interface in TypeScript",
"main": "dist/index.js", "main": "dist/index.js",
"typings": "dist/index.d.ts", "typings": "dist/index.d.ts",
"scripts": { "scripts": {
@ -25,20 +25,40 @@
}, },
"homepage": "https://gitlab.com/umbrellazone/smartacme#README", "homepage": "https://gitlab.com/umbrellazone/smartacme#README",
"dependencies": { "dependencies": {
"@pushrocks/smartdelay": "^2.0.2", "@pushrocks/lik": "^3.0.17",
"@pushrocks/smartdns": "^3.0.4", "@pushrocks/smartdata": "^3.1.25",
"@pushrocks/smartpromise": "^2.0.5", "@pushrocks/smartdelay": "^2.0.6",
"acme-client": "^2.2.1" "@pushrocks/smartdns": "^3.0.8",
"@pushrocks/smartexpress": "^3.0.57",
"@pushrocks/smartlog": "^2.0.21",
"@pushrocks/smartpromise": "^3.0.6",
"@pushrocks/smartrequest": "^1.1.47",
"@pushrocks/smartstring": "^3.0.18",
"@pushrocks/smarttime": "^3.0.12",
"@pushrocks/smartunique": "^3.0.1",
"@tsclass/tsclass": "^3.0.4",
"acme-client": "^3.3.1"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.4", "@gitzone/tsbuild": "^2.1.17",
"@gitzone/tsrun": "^1.1.17", "@gitzone/tsrun": "^1.2.8",
"@gitzone/tstest": "^1.0.18", "@gitzone/tstest": "^1.0.28",
"@mojoio/cloudflare": "^2.0.0", "@mojoio/cloudflare": "^4.0.3",
"@pushrocks/qenv": "^3.0.2", "@pushrocks/qenv": "^4.0.6",
"@pushrocks/tapbundle": "^3.0.7", "@pushrocks/tapbundle": "^3.2.0",
"@types/node": "^10.12.18", "@types/node": "^13.7.0",
"tslint": "^5.12.0", "tslint": "^6.0.0",
"tslint-config-prettier": "^1.17.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,6 @@
required: required:
- CF_EMAIL - CF_EMAIL
- CF_KEY - CF_KEY
- MONGODB_URL
- MONGODB_PASSWORD
- MONGODB_DATABASE

View File

@ -1,22 +1,50 @@
import { tap, expect } from '@pushrocks/tapbundle'; 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({
email: testQenv.getEnvVarOnDemand('CF_EMAIL'),
key: testQenv.getEnvVarOnDemand('CF_KEY')
});
import * as smartacme from '../ts/index'; import * as smartacme from '../ts/index';
let smartAcmeInstance: smartacme.SmartAcme; let smartAcmeInstance: smartacme.SmartAcme;
tap.test('should create a valid instance of SmartAcme', async () => { tap.test('should create a valid instance of SmartAcme', async () => {
smartAcmeInstance = new smartacme.SmartAcme(); smartAcmeInstance = new smartacme.SmartAcme({
await smartAcmeInstance.init({
accountEmail: 'domains@lossless.org', accountEmail: 'domains@lossless.org',
accountPrivateKey: null, accountPrivateKey: null,
removeChallenge: async (...args) => { mongoDescriptor: {
console.log(args); mongoDbName: testQenv.getEnvVarRequired('MONGODB_DATABASE'),
mongoDbPass: testQenv.getEnvVarRequired('MONGODB_PASSWORD'),
mongoDbUrl: testQenv.getEnvVarRequired('MONGODB_URL')
}, },
setChallenge: async (...args) => { removeChallenge: async (dnsChallenge) => {
console.log(args); testCloudflare.convenience.acmeRemoveDnsChallenge(dnsChallenge);
} },
setChallenge: async (dnsChallenge) => {
testCloudflare.convenience.acmeSetDnsChallenge(dnsChallenge);
},
environment: 'integration'
}); });
// await smartAcmeInstance.getCertificateForDomain('bleu.de'); await smartAcmeInstance.init();
});
tap.test('should get a domain certificate', async () => {
await smartAcmeInstance.getCertificateForDomain('bleu.de');
});
tap.test('certmatcher should correctly match domains', async () => {
const certMatcherMod = await import('../ts/smartacme.classes.certmatcher');
const certMatcher = new certMatcherMod.CertMatcher();
const matchedCert = certMatcher.getCertificateDomainNameByDomainName('level3.level2.level1');
expect(matchedCert).to.equal('level2.level1');
});
tap.test('should stop correctly', async () => {
await smartAcmeInstance.stop();
}); });
tap.start(); tap.start();

View File

@ -0,0 +1,62 @@
import * as plugins from './smartacme.plugins';
import * as interfaces from './interfaces';
import { CertManager } from './smartacme.classes.certmanager';
import { Collection, svDb, unI } from '@pushrocks/smartdata';
@plugins.smartdata.Collection(() => {
return CertManager.activeDB;
})
export class Cert extends plugins.smartdata.SmartDataDbDoc<Cert> implements plugins.tsclass.network.ICert {
@unI()
public id: string;
@svDb()
public domainName: string;
@svDb()
public created: number;
@svDb()
public privateKey: string;
@svDb()
public publicKey: string;
@svDb()
public csr: string;
@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 => {
this[key] = optionsArg[key];
});
}
}
}

View File

@ -0,0 +1,77 @@
import * as plugins from './smartacme.plugins';
import { Cert } from './smartacme.classes.cert';
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 interestMap: plugins.lik.InterestMap<string, Cert>;
constructor(
smartAcmeArg: SmartAcme,
optionsArg: {
mongoDescriptor: plugins.smartdata.IMongoDescriptor;
}
) {
this.mongoDescriptor = optionsArg.mongoDescriptor;
}
public async init() {
// Smartdata DB
this.smartdataDb = new plugins.smartdata.SmartdataDb(this.mongoDescriptor);
await this.smartdataDb.init();
CertManager.activeDB = this.smartdataDb;
// Pending Map
this.interestMap = new plugins.lik.InterestMap((certName) => certName);
}
/**
* retrieves a certificate
* @returns the Cert class or null
* @param certDomainNameArg the domain Name to retrieve the vcertificate for
*/
public async retrieveCertificate(certDomainNameArg: string): Promise<Cert> {
const existingCertificate: Cert = await Cert.getInstance({
domainName: certDomainNameArg
});
if (existingCertificate) {
return existingCertificate;
} else {
return null;
}
}
/**
* stores the certificate
* @param optionsArg
*/
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(certDomainNameArg: string) {
const cert: Cert = await Cert.getInstance({
domainName: certDomainNameArg
});
await cert.delete();
}
}

View File

@ -0,0 +1,19 @@
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) {
return `${originalDomain.level2}.${originalDomain.level1}`;
}
}
}

View File

@ -1,49 +1,139 @@
import * as plugins from './smartacme.plugins'; import * as plugins from './smartacme.plugins';
import { Cert } from './smartacme.classes.cert';
import { CertManager } from './smartacme.classes.certmanager';
import { CertMatcher } from './smartacme.classes.certmatcher';
/** /**
* * the options for the class @see SmartAcme
*/ */
export interface ISmartAcmeStorage {} export interface ISmartAcmeOptions {
accountPrivateKey?: string;
accountEmail: string;
mongoDescriptor: plugins.smartdata.IMongoDescriptor;
setChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
removeChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
environment: 'production' | 'integration';
logger?: plugins.smartlog.Smartlog;
}
/**
* class SmartAcme
* can be used for setting up communication with an ACME authority
*
* ```ts
* const mySmartAcmeInstance = new SmartAcme({
* // see ISmartAcmeOptions for options
* })
* ```
*/
export class SmartAcme { export class SmartAcme {
private options: ISmartAcmeOptions;
// the acme client // the acme client
private client: any; private client: any;
private smartdns = new plugins.smartdns.Smartdns(); private smartdns = new plugins.smartdns.Smartdns();
public logger: plugins.smartlog.Smartlog;
// the account private key // the account private key
private privateKey: string; private privateKey: string;
// challenge fullfillment // challenge fullfillment
private setChallenge: (domainName: string, keyAuthorization: string) => Promise<any>; private setChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
private removeChallenge: (domainName: string) => Promise<any>; private removeChallenge: (dnsChallengeArg: plugins.tsclass.network.IDnsChallenge) => Promise<any>;
public async init(optionsArg: { // certmanager
accountPrivateKey?: string; private certmanager: CertManager;
accountEmail: string; private certmatcher: CertMatcher;
setChallenge: (domainName: string, keyAuthorization: string) => Promise<any>
removeChallenge: (domainName: string) => Promise<any>; constructor(optionsArg: ISmartAcmeOptions) {
}) { this.options = optionsArg;
this.privateKey = optionsArg.accountPrivateKey || (await plugins.acme.forge.createPrivateKey()); this.options.logger
this.setChallenge = optionsArg.setChallenge; ? (this.logger = optionsArg.logger)
this.removeChallenge = optionsArg.removeChallenge; : (this.logger = plugins.smartlog.defaultLogger);
}
/**
* inits the instance
* ```ts
* await myCloudlyInstance.init() // does not support options
* ```
*/
public async init() {
this.privateKey =
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
});
await this.certmanager.init();
// CertMatcher
this.certmatcher = new CertMatcher();
// ACME Client
this.client = new plugins.acme.Client({ this.client = new plugins.acme.Client({
directoryUrl: plugins.acme.directory.letsencrypt.staging, directoryUrl: (() => {
if (this.options.environment === 'production') {
return plugins.acme.directory.letsencrypt.production;
} else {
return plugins.acme.directory.letsencrypt.staging;
}
})(),
accountKey: this.privateKey accountKey: this.privateKey
}); });
/* Register account */ /* Register account */
await this.client.createAccount({ await this.client.createAccount({
termsOfServiceAgreed: true, termsOfServiceAgreed: true,
contact: [`mailto:${optionsArg.accountEmail}`] contact: [`mailto:${this.options.accountEmail}`]
}); });
} }
public async getCertificateForDomain(domainArg: string) { public async stop() {
const domain = domainArg; 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 certDomainName = this.certmatcher.getCertificateDomainNameByDomainName(domainArg);
const retrievedCertificate = await this.certmanager.retrieveCertificate(certDomainName);
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
await this.certmanager.interestMap.addInterest(certDomainName);
/* Place new order */ /* Place new order */
const order = await this.client.createOrder({ const order = await this.client.createOrder({
identifiers: [{ type: 'dns', value: domain }, { type: 'dns', value: `*.${domain}` }] identifiers: [
{ type: 'dns', value: certDomainName },
{ type: 'dns', value: `*.${certDomainName}` }
]
}); });
/* Get authorizations and select challenges */ /* Get authorizations and select challenges */
@ -51,7 +141,7 @@ export class SmartAcme {
for (const authz of authorizations) { for (const authz of authorizations) {
console.log(authz); console.log(authz);
const domainDnsName: string = `_acme-challenge.${authz.identifier.value}`; const fullHostName: string = `_acme-challenge.${authz.identifier.value}`;
const dnsChallenge: string = authz.challenges.find(challengeArg => { const dnsChallenge: string = authz.challenges.find(challengeArg => {
return challengeArg.type === 'dns-01'; return challengeArg.type === 'dns-01';
}); });
@ -60,9 +150,13 @@ export class SmartAcme {
try { try {
/* Satisfy challenge */ /* Satisfy challenge */
await this.setChallenge(domainDnsName, keyAuthorization); await this.setChallenge({
await this.smartdns.checkUntilAvailable(domainDnsName, 'TXT', keyAuthorization); hostName: fullHostName,
challenge: keyAuthorization
});
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);
/* Verify that challenge is satisfied */ /* Verify that challenge is satisfied */
await this.client.verifyChallenge(authz, dnsChallenge); await this.client.verifyChallenge(authz, dnsChallenge);
@ -75,7 +169,10 @@ export class SmartAcme {
} finally { } finally {
/* Clean up challenge response */ /* Clean up challenge response */
try { try {
await this.removeChallenge(domainDnsName); await this.removeChallenge({
hostName: fullHostName,
challenge: keyAuthorization
});
} catch (e) { } catch (e) {
console.log(e); console.log(e);
} }
@ -84,18 +181,30 @@ export class SmartAcme {
/* Finalize order */ /* Finalize order */
const [key, csr] = await plugins.acme.forge.createCsr({ const [key, csr] = await plugins.acme.forge.createCsr({
commonName: `*.${domain}`, commonName: `*.${certDomainName}`,
altNames: [domain] altNames: [certDomainName]
}); });
await this.client.finalizeOrder(order, csr); await this.client.finalizeOrder(order, csr);
const cert = await this.client.getCertificate(order); const cert = await this.client.getCertificate(order);
/* Done */ /* Done */
console.log(`CSR:\n${csr.toString()}`);
console.log(`Private key:\n${key.toString()}`);
console.log(`Certificate:\n${cert.toString()}`);
}
toStorageObject() {} await this.certmanager.storeCertificate({
id: plugins.smartunique.shortId(),
domainName: certDomainName,
privateKey: key.toString(),
publicKey: cert.toString(),
csr: csr.toString(),
created: Date.now(),
validUntil:
Date.now() +
plugins.smarttime.getMilliSecondsFromUnits({
days: 90
})
});
const newCertificate = await this.certmanager.retrieveCertificate(certDomainName);
return newCertificate;
}
} }

View File

@ -1,11 +1,38 @@
// @pushrocks scope // @pushrocks scope
import * as lik from '@pushrocks/lik';
import * as smartdata from '@pushrocks/smartdata';
import * as smartdelay from '@pushrocks/smartdelay'; import * as smartdelay from '@pushrocks/smartdelay';
import * as smartdns from '@pushrocks/smartdns'; 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 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 { smartdelay, smartdns, smartpromise }; 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'; import * as acme from 'acme-client';
export { acme }; export { acme };

7
tsconfig.json Normal file
View File

@ -0,0 +1,7 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"target": "es2017",
"module": "commonjs"
}
}