-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
414 lines (371 loc) · 12.7 KB
/
index.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/**
*
* acme-qcloud-scf
* @author Jeff2Ma
* @url https://github.com/Jeff2Ma/acme-qcloud-scf
*/
let isScfEnv = false; // 是否是云函数环境
const moment = require('moment');
const acme = require('acme-client');
const tencentcloud = require("tencentcloud-sdk-nodejs");
const axios = require('axios');
const appName = '[acme-qcloud-scf]';
acme.setLogger((message) => {
console.log(message);
});
// 读取配置文件
let config = {};
try {
config = require('./config.custom.js')
} catch (e) {
config = require('./config.example.js')
}
function log() {
const args = [];
args.push(appName);
for (let i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
console.log.apply(console, args);
}
// dnspod 实例
const DnspodApi = require('dnspod-api');
const dnspodApi = new DnspodApi({
server: config.dnspodServer || 'dnspod.cn',
token: config.dnspodToken // your login token, you can find how to get this at the top.
});
const sslClient = new tencentcloud.ssl.v20191205.Client({
credential: {
secretId: config.qcloudSecretId,
secretKey: config.qcloudSecretKey,
},
// region: "ap-shanghai",
profile: {
signMethod: "TC3-HMAC-SHA256",
httpProfile: {
reqMethod: "POST",
reqTimeout: 30,
endpoint: "ssl.tencentcloudapi.com",
},
},
})
const cdnClient = new tencentcloud.cdn.v20180606.Client({
credential: {
secretId: config.qcloudSecretId,
secretKey: config.qcloudSecretKey,
},
profile: {
signMethod: "TC3-HMAC-SHA256",
httpProfile: {
reqMethod: "POST",
reqTimeout: 30,
endpoint: "cdn.tencentcloudapi.com",
},
},
})
const webHookUrl = config?.wecomWebHook || ''; // 暂时不用
async function challengeCreateFn(authz, challenge, keyAuthorization) {
const dnsRecord = `_acme-challenge.${authz.identifier.value}`;
const recordValue = keyAuthorization;
log(`Creating TXT record for ${authz.identifier.value}: ${dnsRecord}`);
// 清空所有的 DNS 记录
await removeOldDNSRecords('firstTime');
const createRes = await dnspodApi.do({
action: 'Record.Create',
params: {
domain: config.domain,
sub_domain: '_acme-challenge',
record_line: '默认',
mx: '1',
record_type: 'TXT',
value: recordValue
}
})
log('createRes', createRes.status)
return createRes
}
async function challengeRemoveFn(authz, challenge, keyAuthorization) {
const dnsRecord = `_acme-challenge.${authz.identifier.value}`;
const recordValue = keyAuthorization;
log(`Removing TXT record for ${authz.identifier.value}: ${dnsRecord}`);
const recordListData = await dnspodApi.do({
action: 'Record.List',
params: {
domain: config.domain,
sub_domain: '_acme-challenge',
}
}).catch((e) => {
log(e)
return {}
})
log('challengeRemoveFn:recordListData', recordListData.status)
// status: { code: '10', message: '记录列表为空', created_at: '2022-05-01 11:23:49' },
if (recordListData?.status?.code + '' === '10') {
log('删除 dns 记录,已为空')
return {}
} else {
const records = recordListData?.records;
// log('records', records)
const record = records.find(item => item.value === dnsRecord)
const res = await dnspodApi.do({
action: 'Record.Remove',
params: {
domain: config.domain,
sub_domain: '_acme-challenge',
record_line: '默认',
mx: '1',
record_id: record.id,
record_type: 'TXT',
// value: recordValue
}
})
log('Record.Remove Success:', res.status);
return {}
}
}
async function removeOldDNSRecords(from = '') {
// https://docs.dnspod.cn/api/modify-records/
const recordListData = await dnspodApi.do({
action: 'Record.List',
params: {
domain: config.domain,
sub_domain: '_acme-challenge',
}
}).catch((e) => {
log(e)
return {}
})
log('removeOldDNSRecords:recordListData', recordListData.status);
if (recordListData?.status?.code + '' === '10') {
return Promise.resolve({
empty: true,
length: 0,
});
}
const records = recordListData?.records;
if (records.length) {
log('提示:检测到有旧的 dns 记录,尝试全部删除');
await Promise.all(records.map(async item => {
const res = await dnspodApi.do({
action: 'Record.Remove',
params: {
domain: config.domain,
sub_domain: '_acme-challenge',
record_line: '默认',
mx: '1',
record_id: item.id,
record_type: 'TXT',
// value: recordValue
}
})
log(`Record.Remove Success:${item.id}`, res.status)
}))
if (from && from === 'firstTime') {
log('延迟 15s,预防 dns 缓存因素影响');
await sleep(15);
}
return {}
}
return Promise.resolve({
empty: true,
length: 0,
});
}
async function sleep(s) {
return new Promise(resolve => setTimeout(resolve, s * 1000));
}
async function uploadCert2QcloudSSL(cert, key) {
// 腾讯云 SDK
log('正在上传到腾讯云 SSL 管理...');
// 待删除旧的
const {TotalCount, Certificates} = await sslClient.DescribeCertificates(
{
SearchKey: config.domain
}
).catch(() => {
})
if (TotalCount && Certificates.length) {
await Promise.all(Certificates.map(async item => {
await sslClient.DeleteCertificate({
CertificateId: item.CertificateId
})
log(`正在删除${item.CertificateId}, ${item.Domain} 证书`)
}))
}
const uploadCertificateRes = await sslClient.UploadCertificate({
CertificatePublicKey: cert.toString(),
CertificatePrivateKey: key.toString(),
Alias: config.domain
}).catch((e) => {
console.error(e)
})
log('上传本次产生的证书: ', uploadCertificateRes)
return uploadCertificateRes
}
async function initConfig(config, env) {
let envFormat = {};
if (env && typeof env === 'string') {
try {
envFormat = JSON.parse(env)
} catch (e) {
}
}
return Object.assign({}, config, envFormat)
}
async function updateCDNDomains(cert, key, CertificateId) {
const nowStr = moment(new Date()).utcOffset(8).format('YYYY-MM-DD HH:mm:ss');
const list = config.cdnDomainList || [];
if (!list || !list.length) return Promise.resolve({})
return await Promise.all(list.map(async item => {
log(`正在为如下 cdn 域名进行 https 证书绑定:${item}, ${CertificateId}`)
await cdnClient.UpdateDomainConfig({
Domain: item,
Https: {
Switch: 'on',
Http2: 'on',
CertInfo: {
CertId: CertificateId,
Message: `${appName}${nowStr}`,
}
}
}).then(
(data) => {
log(data);
},
(err) => {
console.error("error", err);
}
);
}))
}
async function postWeComRobotMsg(options) {
const content = options?.content || ''
if (!content) return '没有消息要发送';
const postData = {
"msgtype": "text",
"text": {
content: (!isScfEnv ? '[本地调试发送]' : '') + content
}, "mentioned_list": ["@all"]
};
return axios.post(config.wecomWebHook, postData)
.then(function (res) {
console.log(res.data);
return res.data;
})
.catch(function (error) {
console.log(error);
return 'st wrong when post qywx robot api';
})
.then(function (result) {
return '发送企业微信机器人成功:' + JSON.stringify(result) + 'H:' + moment().utcOffset(8).format('kk');
});
}
const main_handler = async (event = {}, context = {}, callback) => {
const environment = context?.environment || {}
config = await initConfig(config, environment);
// 云函数环境特有
if (config['SCF_NAMESPACE']) {
isScfEnv = true
}
log('isScfEnv', isScfEnv)
/* Init client */
const client = new acme.Client({
directoryUrl: (!isScfEnv || +(config.isDebug)) ? acme.directory.letsencrypt.staging : acme.directory.letsencrypt.production,
accountKey: await acme.forge.createPrivateKey(),
termsOfServiceAgreed: true,
challengePriority: ['dns-01'],
});
/* Register account */
await client.createAccount({
termsOfServiceAgreed: true,
contact: [`mailto:${config.email}`]
});
/* Place new order */
const order = await client.createOrder({
wildcard: true,
identifiers: [
{type: 'dns', value: `${config.domain}`},
{type: 'dns', value: `*.${config.domain}`}
]
});
/**
* authorizations / client.getAuthorizations(order);
* An array with one item per DNS name in the certificate order.
* All items require at least one satisfied challenge before order can be completed.
*/
const authorizations = await client.getAuthorizations(order);
const promises = authorizations.map(async (authz) => {
let challengeCompleted = false;
try {
/**
* challenges / authz.challenges
* An array of all available challenge types for a single DNS name.
* One of these challenges needs to be satisfied.
*/
const {challenges} = authz;
/* Just select Dns Way */
const challenge = challenges.find(c => c.type === 'dns-01');
const keyAuthorization = await client.getChallengeKeyAuthorization(challenge);
try {
/* Satisfy challenge */
await challengeCreateFn(authz, challenge, keyAuthorization);
log('延迟 15s,预防 dns 缓存因素影响');
await sleep(15);
/* Verify that challenge is satisfied */
await client.verifyChallenge(authz, challenge);
/* Notify ACME provider that challenge is satisfied */
await client.completeChallenge(challenge);
challengeCompleted = true;
/* Wait for ACME provider to respond with valid status */
await client.waitForValidStatus(challenge);
} finally {
/* Clean up challenge response */
try {
// await challengeRemoveFn(authz, challenge, keyAuthorization);
} catch (e) {
/**
* Catch errors thrown by challengeRemoveFn() so the order can
* be finalized, even though something went wrong during cleanup
*/
}
}
} catch (e) {
/* Deactivate pending authz when unable to complete challenge */
if (!challengeCompleted) {
try {
await client.deactivateAuthorization(authz);
} catch (f) {
/* Catch and suppress deactivateAuthorization() errors */
}
}
throw e;
}
});
/* Wait for challenges to complete */
await Promise.all(promises);
try {
/* Finalize order */
const [key, csr] = await acme.forge.createCsr({
commonName: `*.${config.domain}`,
altNames: [`${config.domain}`]
// commonName: `${config.domain}`,// 建议用根域名
// altNames: [`${config.domain}`, `*.${config.domain}`]
});
const finalized = await client.finalizeOrder(order, csr);
const cert = await client.getCertificate(finalized);
/* 完成 */
log(`CSR:\n${csr.toString()}`);
log(`Private key:\n${key.toString()}`);
log(`Certificate:\n${cert.toString()}`);
const {CertificateId} = await uploadCert2QcloudSSL(cert, key);
await updateCDNDomains(cert, key, CertificateId)
} catch (e) {
log('Finalize order error: ', e)
await postWeComRobotMsg({
content: `生成证书失败${JSON.parse(JSON.stringify(e))}`
})
}
// 清空多余的 dnsPod 记录
await removeOldDNSRecords()
};
exports.main_handler = main_handler