sliftutils 1.0.4 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ /** NOTE: We also generate the domain *.domain */
2
+ export declare const getHTTPSCert: {
3
+ (key: string): Promise<{
4
+ key: string;
5
+ cert: string;
6
+ }>;
7
+ clear(key: string): void;
8
+ clearAll(): void;
9
+ forceSet(key: string, value: Promise<{
10
+ key: string;
11
+ cert: string;
12
+ }>): void;
13
+ getAllKeys(): string[];
14
+ get(key: string): Promise<{
15
+ key: string;
16
+ cert: string;
17
+ }> | undefined;
18
+ };
@@ -0,0 +1,201 @@
1
+
2
+ import { addRecord, deleteRecord, getRecords, setRecord } from "./dns";
3
+ import { cache, lazy } from "socket-function/src/caching";
4
+ import * as forge from "node-forge";
5
+ import acme from "acme-client";
6
+ import { magenta, red } from "socket-function/src/formatting/logColors";
7
+ import { formatDateTime, formatTime } from "socket-function/src/formatting/format";
8
+ import { timeInHour, timeInMinute } from "socket-function/src/misc";
9
+ import { delay } from "socket-function/src/batching";
10
+ import fs from "fs";
11
+ import { getKeyStore } from "./persistentLocalStorage";
12
+
13
+ // For example:
14
+ /*
15
+ let domain = "querysubtest.com";
16
+ await loadIdentityCA(domain);
17
+
18
+ let listenPublic = false;
19
+ let port = 9823;
20
+ let localDomain = "127-0-0-1." + domain;
21
+ await addRecord("A", localDomain, "127.0.0.1");
22
+ let keyCert = await getHTTPSCert(domain);
23
+ */
24
+
25
+ // Expire EXPIRATION_THRESHOLD% of the way through the certificate's lifetime
26
+ const EXPIRATION_THRESHOLD = 0.4;
27
+
28
+ /** NOTE: We also generate the domain *.domain */
29
+ export const getHTTPSCert = cache(async (domain: string): Promise<{ key: string; cert: string }> => {
30
+ if (!domain.endsWith(".")) {
31
+ domain = domain + ".";
32
+ }
33
+
34
+ // No matter what, reset this from the in-memory cache in an hour. This is fine. We'll just see the cache on disk and see that it hasn't expired. Or we might see that it has expired, and then we will get the new value.
35
+ setTimeout(() => {
36
+ getHTTPSCert.clear(domain);
37
+ }, timeInHour);
38
+
39
+ let keyCert: { key: string; cert: string } | undefined;
40
+ let path = domain + ".cert";
41
+
42
+ try {
43
+ keyCert = JSON.parse(fs.readFileSync(path, "utf8")) as { key: string; cert: string };
44
+ } catch { }
45
+ if (keyCert) {
46
+ // If 40% of the lifetime has passed, renew it (has to be < the threshold
47
+ // in EdgeCertController).
48
+ let certObj = parseCert(keyCert.cert);
49
+ let expirationTime = +new Date(certObj.validity.notAfter);
50
+ let createTime = +new Date(certObj.validity.notBefore);
51
+ let renewDate = createTime + (expirationTime - createTime) * EXPIRATION_THRESHOLD;
52
+ if (renewDate < Date.now()) {
53
+ console.log(magenta(`Renewing domain ${domain} (renew target is ${formatDateTime(renewDate)}).`));
54
+ keyCert = undefined;
55
+ }
56
+ } else {
57
+ console.log(magenta(`No cert found for domain ${domain}, generating shortly.`));
58
+ }
59
+ if (keyCert) {
60
+ return keyCert;
61
+ }
62
+
63
+ const accountKey = await getAccountKey(domain);
64
+ let altDomains: string[] = [];
65
+
66
+ // altDomains.push("noproxy." + domain);
67
+ // // NOTE: Allowing local access is just an optimization, not to avoid having to forward ports
68
+ // // (unless you type 127-0-0-1.domain into the browser... then I guess you don't have to forward ports?)
69
+ // altDomains.push("127-0-0-1." + domain);
70
+
71
+ // NOTE: I forget why we were not allowing wildcard domains. I think it was to prevent
72
+ // any HTTPS domains from impersonating servers. But... servers have two levels, so that isn't
73
+ // an issue. And even if they didn't they store their public key in their domain, so you
74
+ // can't really impersonate them anyways...
75
+ // - AND, we need this for IP type A records, which... we need to pick the server we want
76
+ // to connect to.
77
+ altDomains.push("*." + domain);
78
+
79
+ try {
80
+ keyCert = await generateCert({ accountKey, domain, altDomains });
81
+ } catch (e) {
82
+ if (String(e).includes("authorization must be pending")) {
83
+ console.log(`Authorization appears to be pending, waiting 2 minutes for other process to create certificate`);
84
+ await delay(timeInMinute * 2);
85
+ return await getHTTPSCert(domain);
86
+ }
87
+ throw e;
88
+ }
89
+ await fs.promises.writeFile(path, JSON.stringify(keyCert));
90
+ return keyCert;
91
+ });
92
+
93
+
94
+ const getAccountKey = async function getAccountKey(domain: string) {
95
+ let accountKey = getKeyStore<string>(domain, "letsEncryptAccountKey");
96
+ let secret = await accountKey.get();
97
+ if (!secret) {
98
+ // Should only HAPPEN ONCE, EVER!
99
+ console.error(red(`Generating new letsencrypt account key`));
100
+ const keyPair = forge.pki.rsa.generateKeyPair();
101
+ secret = forge.pki.privateKeyToPem(keyPair.privateKey);
102
+ await accountKey.set(secret);
103
+ }
104
+ return secret;
105
+ };
106
+
107
+
108
+ function parseCert(PEMorDER: string | Buffer) {
109
+ return forge.pki.certificateFromPem(normalizeCertToPEM(PEMorDER));
110
+ }
111
+
112
+ function normalizeCertToPEM(PEMorDER: string | Buffer): string {
113
+ if (PEMorDER.toString().startsWith("-----BEGIN CERTIFICATE-----")) {
114
+ return PEMorDER.toString();
115
+ }
116
+ PEMorDER = PEMorDER.toString("base64");
117
+ return "-----BEGIN CERTIFICATE-----\n" + PEMorDER + "\n-----END CERTIFICATE-----";
118
+ }
119
+
120
+
121
+ async function generateCert(config: {
122
+ accountKey: string;
123
+ domain: string;
124
+ altDomains?: string[];
125
+ }): Promise<{
126
+ domains: string[];
127
+ key: string;
128
+ cert: string;
129
+ }> {
130
+ let { accountKey, domain } = config;
131
+
132
+ console.log(magenta(`Generating new cert for ${domain}`));
133
+
134
+ let domainList = [domain, ...config.altDomains || []];
135
+ // Strip trailing "."
136
+ domainList = domainList.map(x => x.endsWith(".") ? x.slice(0, -1) : x);
137
+
138
+ const [certificateKey, certificateCsr] = await acme.forge.createCsr({
139
+ commonName: domainList[0],
140
+ altNames: domainList.slice(1),
141
+ });
142
+
143
+ // So... acme-client is fine. Just re-implement the "auto" mode ourselves, to have more control over it.
144
+ const client = new acme.Client({
145
+ directoryUrl: acme.directory.letsencrypt.production,
146
+ accountKey: accountKey,
147
+ });
148
+
149
+ const accountPayload = {
150
+ termsOfServiceAgreed: true,
151
+ contact: [`mailto:devops@perspectanalytics.com`],
152
+ };
153
+
154
+ try {
155
+ await client.getAccountUrl();
156
+ } catch {
157
+ await client.createAccount(accountPayload);
158
+ }
159
+
160
+ const orderPayload = {
161
+ identifiers: domainList.map(domain => ({ type: "dns", value: domain })),
162
+ };
163
+ const order = await client.createOrder(orderPayload);
164
+ const authorizations = await client.getAuthorizations(order);
165
+ console.log(`Starting authorizations: ${JSON.stringify(authorizations)}`);
166
+
167
+ for (let auth of authorizations) {
168
+ if (auth.status === "valid") {
169
+ console.log(`Authorization already valid for ${auth.identifier.value}`);
170
+ continue;
171
+ }
172
+ console.log(`Starting authorization for ${JSON.stringify(auth)}`);
173
+
174
+ // Only use DNS authorization
175
+ let challenge = auth.challenges.find(x => x.type === "dns-01");
176
+ if (!challenge) {
177
+ throw new Error("No DNS challenge found");
178
+ }
179
+ const keyAuthorization = await client.getChallengeKeyAuthorization(challenge);
180
+
181
+ let hostname = auth.identifier.value;
182
+ let challengeRecordName = "_acme-challenge." + hostname + ".";
183
+ await setRecord("TXT", challengeRecordName, keyAuthorization);
184
+
185
+ await client.completeChallenge(challenge);
186
+ console.log(`Challenge completed`);
187
+
188
+ await client.waitForValidStatus(challenge);
189
+ console.log(`Status of order is valid`);
190
+ }
191
+
192
+ const finalized = await client.finalizeOrder(order, certificateCsr);
193
+ console.log(`Order finalized`);
194
+
195
+ let cert = await client.getCertificate(finalized);
196
+ return {
197
+ domains: domainList,
198
+ key: certificateKey.toString(),
199
+ cert: cert,
200
+ };
201
+ }
@@ -0,0 +1,17 @@
1
+
2
+
3
+ declare module "node-forge" {
4
+ declare type Ed25519PublicKey = {
5
+ publicKeyBytes: Buffer;
6
+ } & Buffer;
7
+ declare type Ed25519PrivateKey = {
8
+ privateKeyBytes: Buffer;
9
+ } & Buffer;
10
+ class ed25519 {
11
+ static generateKeyPair(): { publicKey: Ed25519PublicKey, privateKey: Ed25519PrivateKey };
12
+ static privateKeyToPem(key: Ed25519PrivateKey): string;
13
+ static privateKeyFromPem(pem: string): Ed25519PrivateKey;
14
+ static publicKeyToPem(key: Ed25519PublicKey): string;
15
+ static publicKeyFromPem(pem: string): Ed25519PublicKey;
16
+ }
17
+ }
@@ -0,0 +1,5 @@
1
+ import { MaybePromise } from "socket-function/src/types";
2
+ export declare function getKeyStore<T>(appName: string, key: string): {
3
+ get(): MaybePromise<T | undefined>;
4
+ set(value: T | null): MaybePromise<void>;
5
+ };
@@ -0,0 +1,36 @@
1
+ import { isNode } from "socket-function/src/misc";
2
+ import fs from "fs";
3
+ import os from "os";
4
+ import { MaybePromise } from "socket-function/src/types";
5
+ import { cache } from "socket-function/src/caching";
6
+
7
+ export function getKeyStore<T>(appName: string, key: string): {
8
+ get(): MaybePromise<T | undefined>;
9
+ set(value: T | null): MaybePromise<void>;
10
+ } {
11
+ if (isNode()) {
12
+ let path = os.homedir() + `/keystore_${appName}_` + key + ".json";
13
+ return {
14
+ get() {
15
+ let contents: string | undefined = undefined;
16
+ try { contents = fs.readFileSync(path, "utf8"); } catch { }
17
+ if (!contents) return undefined;
18
+ return JSON.parse(contents) as T;
19
+ },
20
+ set(value: T | null) {
21
+ fs.writeFileSync(path, JSON.stringify(value));
22
+ }
23
+ };
24
+ } else {
25
+ return {
26
+ get() {
27
+ let json = localStorage.getItem(key);
28
+ if (!json) return undefined;
29
+ return JSON.parse(json) as T;
30
+ },
31
+ set(value: T | null) {
32
+ localStorage.setItem(key, JSON.stringify(value));
33
+ }
34
+ };
35
+ }
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sliftutils",
3
- "version": "1.0.4",
3
+ "version": "1.1.1",
4
4
  "main": "index.js",
5
5
  "license": "MIT",
6
6
  "files": [
@@ -43,7 +43,9 @@
43
43
  },
44
44
  "dependencies": {
45
45
  "@types/chrome": "^0.0.237",
46
+ "@types/node-forge": "^1.3.11",
46
47
  "@types/shell-quote": "^1.7.5",
48
+ "acme-client": "^5.0.0",
47
49
  "js-sha256": "^0.11.1",
48
50
  "mobx": "^6.13.3",
49
51
  "preact-old-types": "^10.28.1",