vk-ssl-auto-deploy 0.8.0 → 0.8.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,4 +1,24 @@
1
- ## 安装部署
1
+ # vk-ssl-auto-deploy
2
+
3
+ SSL证书自动部署工具 - 提供HTTP API接口,支持证书文件自动上传和部署
4
+
5
+ ## 一键安装(推荐)
6
+
7
+ Linux 服务器执行以下命令,自动完成安装、部署和开机自启配置:
8
+
9
+ ```bash
10
+ curl -fsSL https://gitee.com/vk1688/vk-ssl-auto-deploy/raw/master/install.sh | sudo bash
11
+ ```
12
+
13
+ 安装完成后,访问 `http://服务器IP:6001/admin`,默认密码:`admin@123456`
14
+
15
+ > 支持 CentOS/RHEL 和 Debian/Ubuntu 系统,自动安装 Node.js 和 PM2
16
+
17
+ ---
18
+
19
+ ## 手动安装部署
20
+
21
+ 如果一键安装失败,可以按照以下步骤手动安装:
2
22
 
3
23
  ### 1. 安装node环境(如果node环境已安装,则跳过这一步骤)
4
24
 
@@ -42,8 +62,8 @@ npm root -g
42
62
 
43
63
  则拼接上 `vk-ssl-auto-deploy`,即执行命令 `cd /usr/lib/node_modules/vk-ssl-auto-deploy` 进入工具目录
44
64
 
45
- ### 5. 编辑配置文件,修改证书保存目录
46
-
65
+ ### 5. 编辑配置文件,修改证书保存目录
66
+
47
67
  **此步骤可忽略,可以先启动服务,进入可视化管理面板设置**
48
68
 
49
69
  ```bash
@@ -159,10 +179,11 @@ pm2-startup uninstall
159
179
 
160
180
  # 方法二:在任务计划程序中删除对应的任务
161
181
  ```
162
-
163
- ### 7. 进入可视化操作面板
164
-
165
- 在浏览器上输入 `http://服务器外网IP:6001/admin` 进入可视化操作面板,口令默认为 `admin@123456`
182
+
183
+ ### 7. 进入可视化操作面板
184
+
185
+ 在浏览器上输入 `http://服务器外网IP:6001/admin` 进入可视化操作面板,口令默认为 `admin@123456`
186
+
166
187
 
167
188
  ## 查找nginx安装目录
168
189
 
@@ -194,6 +215,16 @@ sudo passwd root
194
215
 
195
216
  ## 服务器常用命令
196
217
 
218
+ ### 终止程序
219
+
220
+ ```bash
221
+ // 先查找进程id
222
+ ss -tulpn | grep 6001
223
+
224
+ // 根据进程id关闭
225
+ kill 12345
226
+ ```
227
+
197
228
  ### 进入证书目录
198
229
 
199
230
  ```bash
@@ -313,6 +344,12 @@ npm run delete
313
344
  npm run list
314
345
  ```
315
346
 
347
+ ## 卸载
348
+
349
+ ```bash
350
+ pm2 delete vk-ssl-auto-deploy; pm2 unstartup systemd; pm2 save --force; npm uninstall -g vk-ssl-auto-deploy
351
+ ```
352
+
316
353
  ## License
317
354
 
318
355
  MIT
package/app.js CHANGED
@@ -10,6 +10,7 @@ const testRouter = require('./routes/test');
10
10
  const certRouter = require('./routes/cert');
11
11
  const adminRouter = require('./routes/admin');
12
12
  const { setupWebSocket, broadcastLog } = require('./utils/websocket');
13
+ const config = require('./config.json');
13
14
 
14
15
  const app = express();
15
16
 
@@ -56,6 +57,7 @@ setupWebSocket(server);
56
57
  server.listen(port, host, () => {
57
58
  console.log('listenPort:', port);
58
59
  console.log('管理后台地址: http://' + (host === '0.0.0.0' ? 'localhost' : host) + ':' + port + '/admin');
60
+ console.log(`管理后台口令: ${config.password}`);
59
61
  });
60
62
 
61
63
  // 导出应用
package/config.json CHANGED
@@ -1,8 +1,9 @@
1
- {
2
- "key": "h85ymdt87reg4pr2p652zcgsuw2jsg7r",
3
- "certSaveDir": "/vk-cert",
4
- "nginxDir": "/www/server/nginx/sbin/nginx",
5
- "domains": [],
6
- "callbackCommand": [],
7
- "password": "admin@123456"
1
+ {
2
+ "key": "",
3
+ "certSaveDir": "/vk-cert",
4
+ "nginxDir": "/www/server/nginx/sbin/nginx",
5
+ "domains": [],
6
+ "callbackCommand": [],
7
+ "password": "admin@123456",
8
+ "callbackIpWhitelist": []
8
9
  }
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "vk-ssl-auto-deploy",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
4
4
  "description": "SSL证书自动部署工具 - 提供HTTP API接口,支持证书文件自动上传和部署",
5
5
  "main": "app.js",
6
6
  "scripts": {
7
+ "init": "npm install --registry https://registry.npmmirror.com",
7
8
  "dev": "node ./app.js",
8
9
  "start": "pm2 start ./ecosystem.config.js --name vk-ssl-auto-deploy",
9
10
  "stop": "pm2 stop vk-ssl-auto-deploy",
@@ -37,7 +38,7 @@
37
38
  "views/",
38
39
  "public/",
39
40
  "app.js",
40
- "config.json",
41
+ "config.json",
41
42
  "ecosystem.config.js",
42
43
  "README.md"
43
44
  ],
@@ -1,8 +1,8 @@
1
- body {
2
- padding: 50px;
3
- font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
4
- }
5
-
6
- a {
7
- color: #00B7FF;
8
- }
1
+ body {
2
+ padding: 50px;
3
+ font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
4
+ }
5
+
6
+ a {
7
+ color: #00B7FF;
8
+ }
package/routes/admin.js CHANGED
@@ -166,13 +166,16 @@ router.post('/api/config', verifyPassword, (req, res) => {
166
166
  });
167
167
  }
168
168
 
169
- // 确保 domains 和 callbackCommand 是数组
169
+ // 确保 domains、callbackCommandcallbackIpWhitelist 是数组
170
170
  if (!Array.isArray(newConfig.domains)) {
171
171
  newConfig.domains = [];
172
172
  }
173
173
  if (!Array.isArray(newConfig.callbackCommand)) {
174
174
  newConfig.callbackCommand = [];
175
175
  }
176
+ if (!Array.isArray(newConfig.callbackIpWhitelist)) {
177
+ newConfig.callbackIpWhitelist = [];
178
+ }
176
179
 
177
180
  // 保存配置文件
178
181
  fs.writeFileSync(CONFIG_FILE, JSON.stringify(newConfig, null, '\t'), 'utf8');
package/routes/cert.js CHANGED
@@ -14,6 +14,9 @@ const execAsync = promisify(exec);
14
14
  // 获取广播函数
15
15
  const { broadcastLog } = require('../utils/websocket');
16
16
 
17
+ // IP白名单验证工具
18
+ const { isIPInWhitelist, getClientIP } = require('../utils/ipValidator');
19
+
17
20
  // 配置文件路径
18
21
  const CONFIG_FILE = path.join(__dirname, '..', 'config.json');
19
22
 
@@ -294,6 +297,81 @@ function parseCertificate(certContent) {
294
297
  }
295
298
  }
296
299
 
300
+ /**
301
+ * 从证书中提取所有域名(包括 CN 和 SAN)
302
+ * @param {string} certContent - 证书内容(PEM格式)
303
+ * @returns {Array<string>} 域名列表
304
+ */
305
+ function extractDomainsFromCert(certContent) {
306
+ const domains = new Set();
307
+
308
+ try {
309
+ // 优先使用 Node.js 内置的 crypto 模块
310
+ if (crypto.X509Certificate) {
311
+ const cert = new crypto.X509Certificate(certContent);
312
+
313
+ // 提取 CN (Common Name)
314
+ const cnMatch = cert.subject.match(/CN=([^,]+)/);
315
+ if (cnMatch && cnMatch[1]) {
316
+ domains.add(cnMatch[1].trim());
317
+ }
318
+
319
+ // 提取 SAN (Subject Alternative Names)
320
+ // subjectAltName 格式类似: "DNS:example.com, DNS:*.example.com, DNS:www.example.com"
321
+ if (cert.subjectAltName) {
322
+ const sanEntries = cert.subjectAltName.split(',');
323
+ for (const entry of sanEntries) {
324
+ const trimmed = entry.trim();
325
+ // 只处理 DNS 类型的 SAN
326
+ if (trimmed.startsWith('DNS:')) {
327
+ const domain = trimmed.substring(4).trim();
328
+ if (domain) {
329
+ domains.add(domain);
330
+ }
331
+ }
332
+ }
333
+ }
334
+
335
+ if (domains.size > 0) {
336
+ return Array.from(domains);
337
+ }
338
+ }
339
+
340
+ // 降级方案:使用 node-forge
341
+ try {
342
+ const cert = forge.pki.certificateFromPem(certContent);
343
+
344
+ // 提取 CN
345
+ const cn = cert.subject.attributes.find(attr => attr.name === 'commonName');
346
+ if (cn && cn.value) {
347
+ domains.add(cn.value);
348
+ }
349
+
350
+ // 提取 SAN
351
+ const sanExtension = cert.extensions?.find(ext => ext.name === 'subjectAltName');
352
+ if (sanExtension && sanExtension.altNames) {
353
+ for (const altName of sanExtension.altNames) {
354
+ // type 2 = DNS
355
+ if (altName.type === 2 && altName.value) {
356
+ domains.add(altName.value);
357
+ }
358
+ }
359
+ }
360
+
361
+ if (domains.size > 0) {
362
+ return Array.from(domains);
363
+ }
364
+ } catch (forgeError) {
365
+ logger.warn('[域名提取] node-forge 解析失败:', forgeError.message);
366
+ }
367
+
368
+ } catch (error) {
369
+ logger.error('[域名提取错误]', error.message);
370
+ }
371
+
372
+ return Array.from(domains);
373
+ }
374
+
297
375
  /**
298
376
  * 检查本地证书文件的有效期
299
377
  * @param {string} certFilePath - 证书文件路径(.crt或.pem)
@@ -863,6 +941,213 @@ router.get('/execute', verifyPassword, async (req, res) => {
863
941
  });
864
942
  });
865
943
 
944
+ /**
945
+ * POST /api/cert/callback
946
+ * 无忧SSL证书平台回调接口
947
+ * 接收平台推送的证书,自动保存并部署
948
+ */
949
+ router.post('/callback', async (req, res) => {
950
+ const startTime = Date.now();
951
+ const config = getConfig();
952
+ const clientIP = getClientIP(req);
953
+
954
+ logger.divider();
955
+ logger.step(`\n[回调接收] ${new Date().toLocaleString()} - 收到证书推送请求`);
956
+ logger.info(`[回调信息] 请求来源IP: ${clientIP}`);
957
+
958
+ // IP白名单验证
959
+ const whitelist = config.callbackIpWhitelist;
960
+ if (whitelist && Array.isArray(whitelist) && whitelist.length > 0) {
961
+ if (!isIPInWhitelist(clientIP, whitelist)) {
962
+ logger.error(`[回调拒绝] IP ${clientIP} 不在白名单中`);
963
+ logger.divider();
964
+ return res.json({
965
+ code: -1,
966
+ msg: `IP地址 ${clientIP} 不在白名单中,访问被拒绝`
967
+ });
968
+ }
969
+ logger.success(`[回调验证] IP ${clientIP} 白名单验证通过`);
970
+ } else {
971
+ logger.dim('[回调信息] 未配置IP白名单,允许所有IP访问');
972
+ }
973
+
974
+ try {
975
+ const { cert, key, remark } = req.body;
976
+
977
+ // 参数验证
978
+ if (!cert || typeof cert !== 'string') {
979
+ logger.error('[回调错误] 缺少证书内容或格式错误');
980
+ return res.json({
981
+ code: -1,
982
+ msg: '缺少证书内容(cert)或格式错误'
983
+ });
984
+ }
985
+
986
+ if (!key || typeof key !== 'string') {
987
+ logger.error('[回调错误] 缺少私钥内容或格式错误');
988
+ return res.json({
989
+ code: -1,
990
+ msg: '缺少私钥内容(key)或格式错误'
991
+ });
992
+ }
993
+
994
+ // 验证证书格式
995
+ if (!cert.includes('-----BEGIN CERTIFICATE-----') || !cert.includes('-----END CERTIFICATE-----')) {
996
+ logger.error('[回调错误] 证书格式不正确,缺少PEM标记');
997
+ return res.json({
998
+ code: -1,
999
+ msg: '证书格式不正确,必须是PEM格式'
1000
+ });
1001
+ }
1002
+
1003
+ // 验证私钥格式
1004
+ const keyPatterns = [
1005
+ '-----BEGIN PRIVATE KEY-----',
1006
+ '-----BEGIN RSA PRIVATE KEY-----',
1007
+ '-----BEGIN EC PRIVATE KEY-----'
1008
+ ];
1009
+ const hasValidKeyFormat = keyPatterns.some(pattern => key.includes(pattern));
1010
+ if (!hasValidKeyFormat) {
1011
+ logger.error('[回调错误] 私钥格式不正确,缺少PEM标记');
1012
+ return res.json({
1013
+ code: -1,
1014
+ msg: '私钥格式不正确,必须是PEM格式'
1015
+ });
1016
+ }
1017
+
1018
+ // 解析证书信息
1019
+ const certInfo = parseCertificate(cert);
1020
+ if (!certInfo) {
1021
+ logger.error('[回调错误] 无法解析证书内容');
1022
+ return res.json({
1023
+ code: -1,
1024
+ msg: '证书内容解析失败,请检查证书是否有效'
1025
+ });
1026
+ }
1027
+
1028
+ // 检查证书有效期
1029
+ const now = new Date();
1030
+ if (certInfo.notAfter < now) {
1031
+ logger.error('[回调错误] 证书已过期');
1032
+ return res.json({
1033
+ code: -1,
1034
+ msg: `证书已过期,过期时间: ${certInfo.notAfter.toISOString()}`
1035
+ });
1036
+ }
1037
+
1038
+ if (certInfo.notBefore > now) {
1039
+ logger.warn('[回调警告] 证书尚未生效,但仍将保存');
1040
+ }
1041
+
1042
+ // 从证书中提取域名
1043
+ const domains = extractDomainsFromCert(cert);
1044
+ if (domains.length === 0) {
1045
+ logger.error('[回调错误] 无法从证书中提取域名');
1046
+ return res.json({
1047
+ code: -1,
1048
+ msg: '无法从证书中提取域名信息'
1049
+ });
1050
+ }
1051
+
1052
+ logger.info(`[回调信息] 证书域名: ${domains.join(', ')}`);
1053
+ logger.info(`[回调信息] 证书颁发者: ${certInfo.issuer}`);
1054
+ logger.info(`[回调信息] 有效期至: ${certInfo.notAfter.toLocaleString()}`);
1055
+ if (remark) {
1056
+ logger.info(`[回调信息] 备注: ${remark}`);
1057
+ }
1058
+
1059
+ // 生成文件名(使用现有的命名规则)
1060
+ const fileName = generateFileName(domains);
1061
+ logger.info(`[回调信息] 生成文件名: ${fileName}`);
1062
+
1063
+ // 保存证书文件
1064
+ try {
1065
+ saveCertFiles(fileName, cert, key);
1066
+ logger.success(`[回调成功] 证书已保存: ${fileName}.crt, ${fileName}.key, ${fileName}.pem`);
1067
+ } catch (saveError) {
1068
+ logger.error('[回调错误] 证书保存失败:', saveError.message);
1069
+ return res.json({
1070
+ code: -1,
1071
+ msg: `证书保存失败: ${saveError.message}`
1072
+ });
1073
+ }
1074
+
1075
+ // 重载 Nginx
1076
+ const nginxResult = await reloadNginx();
1077
+ if (nginxResult.success) {
1078
+ logger.success('[回调完成] Nginx 重载成功');
1079
+ } else if (nginxResult.message === '未配置nginxDir') {
1080
+ logger.dim('[回调完成] 跳过 Nginx 重载(未配置)');
1081
+ } else {
1082
+ logger.warn('[回调警告] Nginx 重载失败,但证书已保存:', nginxResult.message);
1083
+ }
1084
+
1085
+ // 计算耗时
1086
+ const duration = Date.now() - startTime;
1087
+ logger.success(`[回调完成] 处理耗时: ${duration}ms`);
1088
+ logger.divider();
1089
+
1090
+ // 通过 WebSocket 通知前端刷新
1091
+ if (broadcastLog) {
1092
+ setTimeout(() => {
1093
+ broadcastLog('CERT_CALLBACK_RECEIVED', 'cert_update');
1094
+ }, 500);
1095
+ }
1096
+
1097
+ // 返回成功响应
1098
+ return res.json({
1099
+ code: 0,
1100
+ msg: 'ok'
1101
+ });
1102
+
1103
+ } catch (error) {
1104
+ logger.error('[回调异常]', error);
1105
+ logger.divider();
1106
+ return res.json({
1107
+ code: -1,
1108
+ msg: `处理异常: ${error.message}`
1109
+ });
1110
+ }
1111
+ });
1112
+
1113
+ /**
1114
+ * GET /api/cert/callback/test
1115
+ * 测试回调接口是否可用
1116
+ */
1117
+ router.get('/callback/test', (req, res) => {
1118
+ const config = getConfig();
1119
+ const clientIP = getClientIP(req);
1120
+ const whitelist = config.callbackIpWhitelist || [];
1121
+ const isWhitelistEnabled = whitelist.length > 0;
1122
+ const isIPAllowed = isIPInWhitelist(clientIP, whitelist);
1123
+
1124
+ res.json({
1125
+ code: 0,
1126
+ msg: '回调接口可用',
1127
+ data: {
1128
+ endpoint: '/api/cert/callback',
1129
+ method: 'POST',
1130
+ contentType: 'application/json',
1131
+ requiredParams: ['cert', 'key'],
1132
+ optionalParams: ['remark'],
1133
+ security: {
1134
+ yourIP: clientIP,
1135
+ whitelistEnabled: isWhitelistEnabled,
1136
+ whitelistCount: whitelist.length,
1137
+ isYourIPAllowed: isIPAllowed,
1138
+ whitelist: isWhitelistEnabled ? whitelist : '未配置(允许所有IP)'
1139
+ },
1140
+ exampleRequest: {
1141
+ cert: '-----BEGIN CERTIFICATE-----\n...证书内容...\n-----END CERTIFICATE-----',
1142
+ key: '-----BEGIN PRIVATE KEY-----\n...私钥内容...\n-----END PRIVATE KEY-----',
1143
+ remark: '可选的备注信息'
1144
+ },
1145
+ successResponse: { code: 0, msg: 'ok' },
1146
+ errorResponse: { code: -1, msg: '错误原因' }
1147
+ }
1148
+ });
1149
+ });
1150
+
866
1151
  // 启动时初始化定时任务
867
1152
  initScheduledTask();
868
1153