-
Notifications
You must be signed in to change notification settings - Fork 0
/
quickOrder.js
206 lines (195 loc) · 7.23 KB
/
quickOrder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
/* eslint-disable no-await-in-loop */
import ACMEAgent from '../lib/ACMEAgent.js';
import { encodeBase64UrlAsString } from '../utils/base64.js';
import { createCSR, derFromPrivateKeyInformation, jwkFromPrivateKeyInformation } from '../utils/certificate.js';
import { checkDnsTxt } from '../utils/dns.js';
import { dispatchEvent, dispatchExtendableEvent } from '../utils/events.js';
import { suggestImportKeyAlgorithm } from './jwkImporter.js';
const LETS_ENCRYPT_DIRECTORY_URL = 'https://acme-v02.api.letsencrypt.org/directory';
/**
* @param {Object} options
* @param {ACMEAgent} options.agent
* @param {string[]} options.urls
* @param {EventTarget} [options.eventTarget] used for async callbacks
* @return {Promise<any>} return when ready
*/
export async function processAuthorizations({ agent, urls, eventTarget }) {
const authorizations = await agent.fetchAuthorizations(urls);
/** @type {(ChallengeBase & PendingChallenge & DNSChallenge)[]} */
const challegesToValidate = [];
const completedChallenges = [];
const processingChallenges = [];
const pendingDNSChallenges = [];
for (const authz of authorizations) {
for (const challenge of authz.challenges) {
switch (challenge.status) {
case 'valid':
completedChallenges.push(challenge);
continue;
case 'invalid':
throw new Error('Invalid challenge!');
case 'processing':
processingChallenges.push(challenge);
continue;
case 'pending':
break;
default:
throw new Error(`Unknown challenge status: ${challenge.status}`);
}
if (challenge.type !== 'dns-01') continue;
const recordName = '_acme-challenge';
const recordValue = await agent.buildKeyAuthorization(challenge);
if (eventTarget) {
await dispatchExtendableEvent(eventTarget, 'dnsrecordneeded', {
name: recordName,
value: recordValue,
domain: authz.identifier.value,
});
}
pendingDNSChallenges.push({
challenge,
name: `_acme-challenge.${authz.identifier.value}`,
txt: recordValue,
});
}
}
const attemptTimestamp = new Map();
await Promise.all(pendingDNSChallenges.map(async function verifyDnsChallenge(dnsChallenge) {
const { challenge, name, txt } = dnsChallenge;
const now = performance.now();
if (await checkDnsTxt(name, txt)) {
if (eventTarget) {
await dispatchExtendableEvent(eventTarget, 'challengeverified', challenge);
}
challegesToValidate.push(challenge);
} else {
if (attemptTimestamp.has(challenge)) {
const timeSinceFirstAttempt = attemptTimestamp.get(challenge);
if (now - timeSinceFirstAttempt >= 60_000) {
throw new Error(`DNS verification failed for: ${name} ${txt}`);
}
} else {
attemptTimestamp.set(challenge, now);
}
await new Promise((resolve) => setTimeout(resolve, 5000));
await verifyDnsChallenge(dnsChallenge);
}
}));
for (const challenge of challegesToValidate) {
await agent.validateChallenge(challenge);
}
if (challegesToValidate.length || processingChallenges.length) {
// Validations were performed. Waiting for 5 seconds and checking order status
await new Promise((resolve) => setTimeout(resolve, 5000));
await processAuthorizations({ agent, urls, eventTarget });
return;
}
if (!completedChallenges.length) {
throw new Error('No challenges?');
}
}
/**
* @param {Object} options
* @param {ACMEAgent} options.agent
* @param {Order} options.order
* @param {EventTarget} [options.eventTarget] used for async callbacks
* @return {Promise<any>} return when ready
*/
export async function authorizeOrder({ order, agent, eventTarget }) {
if (order.status === 'ready' || order.status === 'valid') return;
if (order.status !== 'pending') {
throw new Error('Order not processable yet.');
}
await processAuthorizations({
agent,
urls: order.authorizations,
eventTarget,
});
}
/**
* @typedef {Object} WildcardCertificateOrderOptions
* @prop {boolean} tosAgreed
* @prop {string} email
* @prop {JWK|string|Uint8Array} accountKey Account JWK or PrivateKeyInformation (PKCS8)
* @prop {string} domain
* @prop {string} [orderUrl] existing order URL (blank for new)
* @prop {string} [directoryUrl] defaults to LetsEncrypt Production
* @prop {EventTarget} [eventTarget] used for async callbacks
* @prop {string} [organizationName]
* @prop {string} [organizationalUnitName]
* @prop {string} [localityName]
* @prop {string} [stateOrProvinceName]
* @prop {string} [countryName]
* @prop {JWK|string|Uint8Array} csrKey CSR JWK or PrivateKeyInformation (PKCS8)
* @param {WildcardCertificateOrderOptions} options
* @return {Promise<any>}
*/
export async function getWildcardCertificate(options) {
/** @type {JWK} */
let accountJWK;
/** @type {JWK} */
let csrJWK;
if (typeof options.accountKey === 'string' || options.accountKey instanceof Uint8Array) {
const der = derFromPrivateKeyInformation(options.accountKey);
accountJWK = await jwkFromPrivateKeyInformation(der, suggestImportKeyAlgorithm(der));
} else {
accountJWK = options.accountKey;
}
if (typeof options.csrKey === 'string' || options.csrKey instanceof Uint8Array) {
const der = derFromPrivateKeyInformation(options.csrKey);
csrJWK = await jwkFromPrivateKeyInformation(der, suggestImportKeyAlgorithm(der));
} else {
csrJWK = options.csrKey;
}
const agent = new ACMEAgent({
directoryUrl: options.directoryUrl || LETS_ENCRYPT_DIRECTORY_URL,
jwk: accountJWK,
});
await agent.fetchDirectory();
const account = await agent.createAccount({
termsOfServiceAgreed: options.tosAgreed,
contact: [`mailto:${options.email}`],
});
if (options.eventTarget) {
dispatchEvent(options.eventTarget, 'account', account);
dispatchEvent(options.eventTarget, 'accountUrl', agent.accountUrl);
}
let order;
if (options.orderUrl) {
order = await agent.fetchOrder(options.orderUrl);
} else {
order = await agent.createOrder({
identifiers: [
{ type: 'dns', value: options.domain },
{ type: 'dns', value: `*.${options.domain}` },
],
});
}
if (order.status === 'invalid') throw new Error('Invalid order!');
const orderUrl = agent.locations.get(order);
if (options.eventTarget) {
dispatchEvent(options.eventTarget, 'order', order);
if (orderUrl) {
dispatchEvent(options.eventTarget, 'orderUrl', order);
}
}
await authorizeOrder({ order, agent, eventTarget: options.eventTarget });
order = await agent.fetchOrder(orderUrl);
if (order.status === 'ready') {
const csrDER = await createCSR({
commonName: `*.${options.domain}`,
altNames: [`*.${options.domain}`, options.domain],
countryName: options.countryName,
localityName: options.localityName,
organizationalUnitName: options.organizationalUnitName,
organizationName: options.organizationName,
stateOrProvinceName: options.stateOrProvinceName,
jwk: csrJWK,
});
const csr = encodeBase64UrlAsString(csrDER);
order = await agent.finalizeOrder(order, csr);
}
if (order.status !== 'valid') throw new Error('Order not valid?');
const certificate = await agent.fetchCertificate(order);
return certificate;
}