sslauto-mcp 0.0.0-stage → 0.2.0

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SSLAuto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,287 @@
1
- # Temporary Holding Version
1
+ # SSLAuto MCP Server 安装与配置说明
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 给 AI 客户端(Trae / Qoder / Claude Desktop / Cursor 等)装一个本地的 SSL 证书能力服务。
4
+ 包含只读能力(检测线上证书、解析证书内容)与申请能力(邮箱绑定、下单、DNS/文件验证、一次性私钥链接)。
5
+
6
+ ## 零、从 npm 安装(最快)
7
+
8
+ 已发布到 npm:<https://www.npmjs.com/package/sslauto-mcp>
9
+
10
+ ```json
11
+ {
12
+ "mcpServers": {
13
+ "sslauto": {
14
+ "command": "npx",
15
+ "args": ["-y", "sslauto-mcp"],
16
+ "env": {
17
+ "SSLAUTO_API_BASE": "https://sslauto.dfrdev.com"
18
+ }
19
+ }
20
+ }
21
+ }
22
+ ```
23
+
24
+ 不需要提前安装 Node 包,`npx` 会按需拉取;要求 Node >= 18。需要在已登录的 AI 客户端里改用长期访问令牌时,再加一个 `SSLAUTO_TOKEN`(在 SSLAuto 网站生成,形如 `sk_...`)。
25
+
26
+ 本机源码目录方式见下文「方式 A / 方式 B」,适合调试或离线环境。
27
+
28
+ ## 一、能力清单
29
+
30
+ | 工具 | 说明 | 是否联网 |
31
+ | --- | --- | --- |
32
+ | `ssl_domain_check` | 实时拨测域名 443 端口,返回到期时间、剩余天数、颁发者、SAN、证书链层数、TLS 协议,并判断证书是否匹配域名 | 是,调用 SSLAuto 公开接口 |
33
+ | `ssl_cert_parse` | 本地解析 PEM 或裸 Base64 证书,支持证书链;可校验证书是否覆盖指定域名(通配符按单级匹配) | 否,零上传 |
34
+ | `ssl_bind_email` | 邮箱验证码绑定,创建未认领的影子账户,返回 `principalId` 与认领链接 | 是 |
35
+ | `ssl_order_create` | 申请证书,支持选择验证方式(DNS / 文件)与品牌(Let's Encrypt / ZeroSSL / LiteSSL) | 是 |
36
+ | `ssl_order_status` | 查询订单状态、待配置的 TXT 记录或验证文件、到期时间 | 是 |
37
+ | `ssl_order_verify` | 触发 DNS 或文件校验,通过后提交 CA 签发 | 是 |
38
+ | `ssl_key_link` | 为已签发证书生成一次性私钥下载链接(15 分钟、单次有效),不返回私钥正文 | 是 |
39
+ | `ssl_account_info` | 查询当前账户套餐、配额与认领状态 | 是 |
40
+
41
+ 两个只读工具标记为 `readOnlyHint`,客户端不会弹「危险操作」确认;写操作会弹确认。
42
+
43
+ ## 二、目录结构
44
+
45
+ ```
46
+ skills/ssl-mcp/
47
+ ├── server.mjs # MCP 服务入口(stdio)
48
+ ├── lib/cert-parser.mjs # 纯本地 X.509 解析器,无第三方依赖
49
+ ├── package.json
50
+ ├── install.sh # 一键安装:探测 Node、装依赖、写客户端配置
51
+ ├── .gitignore # 忽略 node_modules
52
+ ```
53
+
54
+ ## 三、环境要求
55
+
56
+ - Node.js >= 18(依赖内置 `fetch` 与 `AbortSignal.timeout`)
57
+ - 能访问 `https://sslauto.dfrdev.com`
58
+
59
+ 配置里的 `command` 必须写 Node 18+ 的**绝对路径**,不能写 `node`。原因是客户端的 PATH 往往与你终端里的不同:本机 `/usr/bin/node` 是 v10,Trae 的环境里也有同样的问题,写 `node` 会直接语法错误退出。
60
+
61
+ 不同电脑、不同用户的 Node 路径各不相同(nvm / fnm / volta / mise / asdf / Homebrew / 官方安装包),所以不要互相复制路径,用下面的安装脚本自动探测。
62
+
63
+ ## 四、安装
64
+
65
+ ### 方式 A:一键脚本(推荐,源码目录方式)
66
+
67
+ ```bash
68
+ cd skills/ssl-mcp
69
+ bash install.sh --client trae
70
+ ```
71
+
72
+ 脚本会:
73
+
74
+ 1. 扫描本机的 Node 安装位置(含 nvm、fnm、volta、mise、asdf、Homebrew、`/usr/local/bin`、`/usr/bin`、Trae 自带目录),挑出**满足 >=18 的最高版本**;
75
+ 2. 缺少 `node_modules` 时自动用同版本 npm 安装依赖;
76
+ 3. 把 `sslauto` 合并进客户端配置,`command` 与 `args` 全部替换成当前机器的绝对路径;
77
+ 4. 合并而不是覆盖:已有的其它 MCP 服务器保留,原文件备份为 `mcp.json.bak`;现有 JSON 非法时直接中止,不写坏文件。
78
+
79
+ 支持的客户端与默认配置路径:
80
+
81
+ | `--client` | 配置文件 |
82
+ | --- | --- |
83
+ | `trae`(默认) | Linux:`~/.config/Trae CN/User/mcp.json`;macOS:`~/Library/Application Support/Trae CN/User/mcp.json` |
84
+ | `claude` | Linux:`~/.config/Claude/claude_desktop_config.json`;macOS:`~/Library/Application Support/Claude/claude_desktop_config.json` |
85
+ | `cursor` | `~/.cursor/mcp.json` |
86
+ | 其它 | 用 `--config /绝对/路径/mcp.json` 指定 |
87
+
88
+ 只想看会生成什么、不落盘:
89
+
90
+ ```bash
91
+ bash install.sh --print
92
+ ```
93
+
94
+ Windows 用 PowerShell 时,按「方式 B」手动改,把 `command` 指向本机 `node.exe` 的绝对路径(如 `C:\Program Files\nodejs\node.exe`),`args` 指向 `server.mjs` 的绝对路径。
95
+
96
+ ### 方式 B:手动安装
97
+
98
+ ```bash
99
+ cd <你的 skills/ssl-mcp 目录>
100
+ npm install --omit=dev --no-audit --no-fund
101
+ command -v node && node -v # 确认 >= 18,并把这条路径填进配置
102
+ ```
103
+
104
+ 依赖只有 `@modelcontextprotocol/sdk` 与 `zod`,约 95 个包,几秒完成。
105
+
106
+ ## 五、Trae 配置
107
+
108
+ 用户级配置文件:`~/.config/Trae CN/User/mcp.json`,本机生成结果如下(**其它机器不要照抄路径**,用 `install.sh` 生成):
109
+
110
+ ```json
111
+ {
112
+ "mcpServers": {
113
+ "sslauto": {
114
+ "command": "/home/dfr/.nvm/versions/node/v22.14.0/bin/node",
115
+ "args": ["/datas/work/program/myApp/sslauto-business-prod/skills/ssl-mcp/server.mjs"],
116
+ "env": {
117
+ "SSLAUTO_API_BASE": "https://sslauto.dfrdev.com",
118
+ "SSLAUTO_TIMEOUT_MS": "25000"
119
+ }
120
+ }
121
+ }
122
+ }
123
+ ```
124
+
125
+ 启用步骤:
126
+
127
+ 1. 确认 `sslauto` 出现在 MCP 面板的服务器列表中且状态为已连接。本机实测 Trae 会自动感知配置变更并重连,无需重启。
128
+ 2. 在对话里问一句「sslauto 有哪些工具」,能看到 `ssl_domain_check` 和 `ssl_cert_parse` 即可。
129
+ 3. 工具列表在会话初始化时注入,配置生效前已打开的会话不会热更新,需要新开一个会话。
130
+
131
+ 配置位置说明(2026-11-25 实测):
132
+
133
+ - Trae CN 实际读取的是用户级配置 `~/.config/Trae CN/User/mcp.json`,日志中的标识为 `mcp.config.usrlocalmcp.sslauto`
134
+ - 项目级 `.trae/mcp.json` 在当前版本没有被加载,因此本仓库不再维护该文件,统一用 `install.sh` 写用户级配置
135
+
136
+ 如果只想给某个项目用,当前版本建议在 MCP 面板里关闭/开启来切换;换机器时重新执行 `install.sh` 即可。
137
+
138
+ ## 六、Qoder / Claude Desktop / Cursor
139
+
140
+ Qoder、Claude Desktop、Cursor 的配置结构与上面一致,把 `mcpServers` 片段合并进各自的 MCP 配置文件即可:
141
+
142
+ - Qoder:MCP 设置中新增 stdio 服务,命令与参数同上
143
+ - Claude Desktop:`claude_desktop_config.json`
144
+ - Cursor:`.cursor/mcp.json`
145
+
146
+ Windows 或换机器时,需要把 `command` 与 `args` 改成目标机器上的真实路径。
147
+
148
+ ## 七、验证方式
149
+
150
+ ### 方式一:对话验证(推荐)
151
+
152
+ 在 Trae 新开会话,依次输入:
153
+
154
+ ```
155
+ sslauto 有哪些工具
156
+ 帮我查一下 sslauto.dfrdev.com 的证书
157
+ ```
158
+
159
+ 预期返回(真实输出,2026-11-25 实测):
160
+
161
+ ```
162
+ sslauto.dfrdev.com 的证书有效。
163
+
164
+ - 到期时间:2027-02-09(剩余 75 天)
165
+ - 颁发者:Let's Encrypt
166
+ - 域名匹配:是
167
+ - 证书链:4 层,TLS 协议 TLSv1.3
168
+ - 覆盖域名:sslauto.dfrdev.com
169
+ ```
170
+
171
+ 后面还会附一段结构化 JSON,字段包括 `daysLeft`、`validFrom`、`validTo`、`issuer`、`domainMatched`、`chainLength`、`protocol`、`cipher`、`sans`、`serialNumber`、`fingerprintSha256`、`latencyMs`。
172
+
173
+ ### 方式二:命令行验证
174
+
175
+ 不依赖客户端,直接确认服务能启动、工具已注册、接口可调用:
176
+
177
+ ```bash
178
+ cd /datas/work/program/myApp/sslauto-business-prod/skills/ssl-mcp
179
+ /home/dfr/.nvm/versions/node/v22.14.0/bin/node --input-type=module <<'EOF'
180
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
181
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
182
+ const c = new Client({ name: 'verify', version: '1.0.0' });
183
+ await c.connect(new StdioClientTransport({ command: process.execPath, args: ['./server.mjs'] }));
184
+ console.log('tools:', (await c.listTools()).tools.map((t) => t.name).join(', '));
185
+ const r = await c.callTool({ name: 'ssl_domain_check', arguments: { domain: 'www.baidu.com' } });
186
+ console.log(r.content[0].text.split('\n')[0]);
187
+ await c.close();
188
+ EOF
189
+ ```
190
+
191
+ 预期输出:
192
+
193
+ ```
194
+ tools: ssl_domain_check, ssl_cert_parse
195
+ ✅ www.baidu.com 的证书有效。
196
+ ```
197
+
198
+ ## 八、工具参数
199
+
200
+ ### ssl_domain_check
201
+
202
+ | 参数 | 类型 | 必填 | 说明 |
203
+ | --- | --- | --- | --- |
204
+ | `domain` | string | 是 | 域名,如 `www.example.com`。可带 `https://` 前缀、路径、端口,服务端会自动清洗 |
205
+
206
+ 拒绝的输入:IP 字面量、通配符、`localhost`、`.local`、`.internal`、非法域名。
207
+
208
+ ### ssl_cert_parse
209
+
210
+ | 参数 | 类型 | 必填 | 说明 |
211
+ | --- | --- | --- | --- |
212
+ | `pem` | string | 是 | 包含 `-----BEGIN CERTIFICATE-----` 的 PEM,或证书的裸 Base64 |
213
+ | `domain` | string | 否 | 校验证书是否覆盖该域名 |
214
+
215
+ 支持一次传入证书链,返回数组,第 1 张标记为 `leaf`,其余为 `chain`。
216
+
217
+ ## 九、环境变量
218
+
219
+ | 变量 | 默认值 | 说明 |
220
+ | --- | --- | --- |
221
+ | `SSLAUTO_API_BASE` | `https://sslauto.dfrdev.com` | 接口根地址,可指向测试环境 |
222
+ | `SSLAUTO_TIMEOUT_MS` | `25000` | 单次请求超时(毫秒) |
223
+
224
+ ## 十、常见问题
225
+
226
+ **配置看起来一样,但工具调用报 URL 错误**
227
+
228
+ `env` 的值必须是纯域名,不能带反引号、引号或空格。下面这种写法是错的:
229
+
230
+ ```json
231
+ "SSLAUTO_API_BASE": "`https://sslauto.dfrdev.com`"
232
+ ```
233
+
234
+ 反引号会被当成 URL 的一部分,`fetch` 直接抛 `Invalid URL`。
235
+
236
+ **直接复制别人的 `command` / `args` 结果启动失败**
237
+
238
+ 不同机器的 Node 安装位置和项目路径都不一样,复制必然失败。用 `install.sh` 在本机生成,或手动把 `command` 换成 `command -v node` 的输出、`args` 换成 `server.mjs` 的真实绝对路径。
239
+
240
+ **MCP 面板里显示 stopped / Fail to start**
241
+
242
+ 配置已经读到,但子进程启动后立刻退出。按下面顺序排查:
243
+
244
+ 1. 看 `command` 是不是 `node` 这种相对命令。Trae 的 PATH 里没有你的 nvm 目录,会落到 `/usr/bin/node`(本机 v10),直接语法错误退出。
245
+ 2. 看日志确认具体报错:
246
+
247
+ ```bash
248
+ tail -30 "/home/dfr/.config/Trae CN/logs/$(ls -t "/home/dfr/.config/Trae CN/logs" | head -1)/window2/exthost/mcp-servers-host.log"
249
+ ```
250
+
251
+ 日志里出现 `MCPClient#onStderr` 后面跟着 `server.mjs:14` 和 `Unexpected token {`,就是 Node 版本问题。
252
+ 出现 `MCPClient#start Connected` 加 `Got tools: ssl_domain_check, ssl_cert_parse`,说明已正常连上。
253
+
254
+ **改了配置但对话里还是调不到工具**
255
+
256
+ MCP 工具列表在会话初始化时注入,配置生效前打开的会话不会热更新。新开一个会话即可。
257
+
258
+ **启动失败,提示 `Unexpected token` 或语法错误**
259
+ 用的是 Node 10/12。把 `command` 改成 Node 18+ 的绝对路径。
260
+
261
+ **提示 `spawn node ENOENT`**
262
+ `command` 写成了相对命令,客户端的工作目录里找不到 `node`。改成绝对路径。
263
+
264
+ **返回「检测过于频繁」**
265
+ 公开接口按 IP 限流:10 次/分钟、100 次/天,同一域名结果缓存 5 分钟。等一会再试即可,批量检测建议分批。
266
+
267
+ **返回「目标域名不可检测」**
268
+ 目标解析到内网、回环或云元数据地址,被 SSRF 防护拦截。这是预期行为。
269
+
270
+ **域名不存在或未部署 HTTPS**
271
+ 工具不会报错,而是返回 `reachable: false` 和原因,AI 会据此解释。
272
+
273
+ **证书解析失败**
274
+ 检查是否复制完整。裸 Base64 也支持,但长度必须大于 64 个字符。
275
+
276
+ ## 十一、安全边界
277
+
278
+ - 检测接口免登录,只返回目标站点自身公开的证书信息,不涉及任何账号数据。
279
+ - 解析工具在本地完成,证书内容不会上传到任何服务器。
280
+ - 不读取、不传输私钥;P1 版本没有任何写操作。
281
+ - 公开接口已具备域名格式校验、SSRF 防护、并发限制与限流。
282
+
283
+ ## 十二、后续规划
284
+
285
+ - P2:申请闭环(`ssl_order_create` → 手动 DNS → `ssl_order_status` → 一次性链接取证书)
286
+ - P3:云 DNS 自动验证、服务端托管续签、Agent 自动部署
287
+ - 平台适配:豆包 / 元宝 / 百度等插件壳,复用同一套能力接口
@@ -0,0 +1,345 @@
1
+ /**
2
+ * 纯本地 X.509 / PEM 证书解析器(无第三方依赖)。
3
+ *
4
+ * 用途:AI 侧拿到一段证书文本(PEM 或裸 Base64)时,不联网即可读出主体、
5
+ * 颁发者、有效期、SAN、公钥类型与 SHA-256 指纹。解析失败一律抛出带中文
6
+ * 说明的 Error,方便直接回显给用户。
7
+ */
8
+
9
+ import { createHash } from 'node:crypto';
10
+
11
+ const ATTR_NAME = {
12
+ '2.5.4.3': 'CN',
13
+ '2.5.4.6': 'C',
14
+ '2.5.4.7': 'L',
15
+ '2.5.4.8': 'ST',
16
+ '2.5.4.10': 'O',
17
+ '2.5.4.11': 'OU',
18
+ '2.5.4.4': 'SN',
19
+ '2.5.4.5': 'serialNumber',
20
+ '2.5.4.42': 'GN',
21
+ '1.2.840.113549.1.9.1': 'emailAddress',
22
+ '0.9.2342.19200300.100.1.25': 'DC'
23
+ };
24
+
25
+ const OID_RSA = '1.2.840.113549.1.1.1';
26
+ const OID_EC = '1.2.840.10045.2.1';
27
+ const OID_ED25519 = '1.3.101.112';
28
+ const OID_SAN = '2.5.29.17';
29
+
30
+ const CURVES = {
31
+ '1.2.840.10045.3.1.7': 'P-256',
32
+ '1.3.132.0.34': 'P-384',
33
+ '1.3.132.0.35': 'P-521',
34
+ '1.3.132.0.10': 'secp256k1'
35
+ };
36
+
37
+ function readTLV(bytes, pos) {
38
+ if (pos + 2 > bytes.length) throw new Error('证书数据不完整。');
39
+ const tag = bytes[pos];
40
+ const first = bytes[pos + 1];
41
+ let header = 2;
42
+ let len = first;
43
+ if (first & 0x80) {
44
+ const n = first & 0x7f;
45
+ if (n === 0 || n > 4 || pos + 2 + n > bytes.length) {
46
+ throw new Error('证书长度字段异常。');
47
+ }
48
+ len = 0;
49
+ for (let i = 0; i < n; i++) len = len * 256 + bytes[pos + 2 + i];
50
+ header = 2 + n;
51
+ }
52
+ const start = pos + header;
53
+ if (start + len > bytes.length) throw new Error('证书数据不完整。');
54
+ return { tag, start, end: start + len };
55
+ }
56
+
57
+ function children(bytes, node) {
58
+ const list = [];
59
+ let p = node.start;
60
+ while (p < node.end) {
61
+ const t = readTLV(bytes, p);
62
+ list.push(t);
63
+ p = t.end;
64
+ }
65
+ return list;
66
+ }
67
+
68
+ function ascii(bytes, node) {
69
+ let s = '';
70
+ for (let i = node.start; i < node.end; i++) s += String.fromCharCode(bytes[i]);
71
+ return s;
72
+ }
73
+
74
+ function utf8(bytes, node) {
75
+ let out = '';
76
+ let i = node.start;
77
+ while (i < node.end) {
78
+ const c = bytes[i++];
79
+ if (c < 0x80) {
80
+ out += String.fromCharCode(c);
81
+ } else if (c < 0xe0) {
82
+ out += String.fromCharCode(((c & 0x1f) << 6) | (bytes[i++] & 0x3f));
83
+ } else if (c < 0xf0) {
84
+ out += String.fromCharCode(((c & 0x0f) << 12) | ((bytes[i++] & 0x3f) << 6) | (bytes[i++] & 0x3f));
85
+ } else {
86
+ let cp = ((c & 0x07) << 18) | ((bytes[i++] & 0x3f) << 12) | ((bytes[i++] & 0x3f) << 6) | (bytes[i++] & 0x3f);
87
+ cp -= 0x10000;
88
+ out += String.fromCharCode(0xd800 + (cp >> 10), 0xdc00 + (cp & 0x3ff));
89
+ }
90
+ }
91
+ return out;
92
+ }
93
+
94
+ function decodeString(bytes, node) {
95
+ if (node.tag === 0x1e) {
96
+ let s = '';
97
+ for (let i = node.start; i + 1 < node.end; i += 2) {
98
+ s += String.fromCharCode((bytes[i] << 8) | bytes[i + 1]);
99
+ }
100
+ return s;
101
+ }
102
+ if (node.tag === 0x1c) {
103
+ let u = '';
104
+ for (let j = node.start; j + 3 < node.end; j += 4) {
105
+ u += String.fromCharCode((bytes[j] << 24) | (bytes[j + 1] << 16) | (bytes[j + 2] << 8) | bytes[j + 3]);
106
+ }
107
+ return u;
108
+ }
109
+ return utf8(bytes, node);
110
+ }
111
+
112
+ function oidToString(bytes, node) {
113
+ const parts = [];
114
+ const first = bytes[node.start];
115
+ parts.push(Math.floor(first / 40));
116
+ parts.push(first % 40);
117
+ let val = 0;
118
+ for (let i = node.start + 1; i < node.end; i++) {
119
+ const c = bytes[i];
120
+ val = val * 128 + (c & 0x7f);
121
+ if (!(c & 0x80)) {
122
+ parts.push(val);
123
+ val = 0;
124
+ }
125
+ }
126
+ return parts.join('.');
127
+ }
128
+
129
+ function parseName(bytes, node) {
130
+ const attrs = [];
131
+ const sets = children(bytes, node);
132
+ for (let i = 0; i < sets.length; i++) {
133
+ const atvs = children(bytes, sets[i]);
134
+ for (let j = 0; j < atvs.length; j++) {
135
+ const pair = children(bytes, atvs[j]);
136
+ if (pair.length < 2) continue;
137
+ const type = oidToString(bytes, pair[0]);
138
+ attrs.push({
139
+ type,
140
+ name: ATTR_NAME[type] || type,
141
+ value: decodeString(bytes, pair[1])
142
+ });
143
+ }
144
+ }
145
+ return attrs;
146
+ }
147
+
148
+ function attrValue(attrs, type) {
149
+ for (let i = 0; i < attrs.length; i++) {
150
+ if (attrs[i].type === type) return attrs[i].value;
151
+ }
152
+ return '';
153
+ }
154
+
155
+ /** 输出完整 DN(含 CN),避免截断后丢失最关键的主体信息。 */
156
+ function formatName(attrs) {
157
+ return attrs.map((a) => a.name + '=' + a.value).join(', ');
158
+ }
159
+
160
+ function parseTime(bytes, node) {
161
+ const raw = ascii(bytes, node).replace(/\s/g, '');
162
+ let y;
163
+ let rest;
164
+ if (node.tag === 0x18) {
165
+ y = parseInt(raw.slice(0, 4), 10);
166
+ rest = raw.slice(4);
167
+ } else if (node.tag === 0x17) {
168
+ const yy = parseInt(raw.slice(0, 2), 10);
169
+ y = yy >= 50 ? 1900 + yy : 2000 + yy;
170
+ rest = raw.slice(2);
171
+ } else {
172
+ return NaN;
173
+ }
174
+ const mo = parseInt(rest.slice(0, 2), 10);
175
+ const d = parseInt(rest.slice(2, 4), 10);
176
+ const h = parseInt(rest.slice(4, 6), 10) || 0;
177
+ const mi = parseInt(rest.slice(6, 8), 10) || 0;
178
+ const s = parseInt(rest.slice(8, 10), 10) || 0;
179
+ if (isNaN(y) || isNaN(mo) || isNaN(d)) return NaN;
180
+ return Date.UTC(y, mo - 1, d, h, mi, s);
181
+ }
182
+
183
+ function parseSans(bytes, extensions) {
184
+ const names = [];
185
+ for (let i = 0; i < extensions.length; i++) {
186
+ const ext = extensions[i];
187
+ if (ext.oid !== OID_SAN) continue;
188
+ try {
189
+ const seq = readTLV(bytes, ext.value.start);
190
+ const list = children(bytes, seq);
191
+ for (let j = 0; j < list.length; j++) {
192
+ if (list[j].tag === 0x82) names.push(utf8(bytes, list[j]));
193
+ }
194
+ } catch {
195
+ /* 单个扩展解析失败不影响主体信息 */
196
+ }
197
+ }
198
+ return names;
199
+ }
200
+
201
+ function parseExtensions(bytes, tbsItems) {
202
+ const exts = [];
203
+ for (let i = 0; i < tbsItems.length; i++) {
204
+ if (tbsItems[i].tag !== 0xa3) continue;
205
+ try {
206
+ const seq = children(bytes, tbsItems[i])[0];
207
+ const list = children(bytes, seq);
208
+ for (let j = 0; j < list.length; j++) {
209
+ const fields = children(bytes, list[j]);
210
+ if (!fields.length) continue;
211
+ const oid = oidToString(bytes, fields[0]);
212
+ let valueNode = fields[1];
213
+ if (valueNode && valueNode.tag === 0x01) valueNode = fields[2];
214
+ if (!valueNode || valueNode.tag !== 0x04) continue;
215
+ exts.push({ oid, value: valueNode });
216
+ }
217
+ } catch {
218
+ /* 扩展结构异常时忽略扩展 */
219
+ }
220
+ }
221
+ return exts;
222
+ }
223
+
224
+ function keyLabel(bytes, spkiNode) {
225
+ try {
226
+ const spki = children(bytes, spkiNode);
227
+ const alg = children(bytes, spki[0]);
228
+ const oid = oidToString(bytes, alg[0]);
229
+ if (oid === OID_RSA) {
230
+ const bitString = spki[1];
231
+ const inner = readTLV(bytes, bitString.start + 1);
232
+ const nums = children(bytes, inner);
233
+ const mod = nums[0];
234
+ let len = mod.end - mod.start;
235
+ if (bytes[mod.start] === 0) len -= 1;
236
+ return 'RSA ' + len * 8;
237
+ }
238
+ if (oid === OID_EC) {
239
+ const curve = alg[1] ? oidToString(bytes, alg[1]) : '';
240
+ return 'EC ' + (CURVES[curve] || '');
241
+ }
242
+ if (oid === OID_ED25519) return 'Ed25519';
243
+ return '其他密钥';
244
+ } catch {
245
+ return '密钥未知';
246
+ }
247
+ }
248
+
249
+ function serialHex(bytes, node) {
250
+ let hex = '';
251
+ for (let i = node.start; i < node.end; i++) {
252
+ hex += (bytes[i] < 16 ? '0' : '') + bytes[i].toString(16);
253
+ }
254
+ return hex.toUpperCase();
255
+ }
256
+
257
+ function parseCert(der) {
258
+ if (!der || der.length < 64) throw new Error('证书数据过短,可能复制不完整。');
259
+ const root = readTLV(der, 0);
260
+ if (root.tag !== 0x30) throw new Error('证书不是有效的 DER 结构。');
261
+ const top = children(der, root);
262
+ if (top.length < 3 || top[0].tag !== 0x30) throw new Error('证书结构不完整。');
263
+
264
+ const tbsItems = children(der, top[0]);
265
+ let i = 0;
266
+ if (tbsItems[0] && tbsItems[0].tag === 0xa0) i = 1;
267
+ const serialNode = tbsItems[i++];
268
+ i += 1; /* signature algorithm */
269
+ const issuerNode = tbsItems[i++];
270
+ const validityNode = tbsItems[i++];
271
+ const subjectNode = tbsItems[i++];
272
+ const spkiNode = tbsItems[i++];
273
+ if (!issuerNode || !validityNode || !subjectNode) {
274
+ throw new Error('证书缺少颁发者、主体或有效期。');
275
+ }
276
+
277
+ const times = children(der, validityNode);
278
+ if (times.length < 2) throw new Error('证书有效期信息不完整。');
279
+ const notBeforeMs = parseTime(der, times[0]);
280
+ const notAfterMs = parseTime(der, times[1]);
281
+ if (isNaN(notBeforeMs) || isNaN(notAfterMs)) throw new Error('证书有效期格式无法识别。');
282
+
283
+ const issuerAttrs = parseName(der, issuerNode);
284
+ const subjectAttrs = parseName(der, subjectNode);
285
+ const extensions = parseExtensions(der, tbsItems);
286
+
287
+ return {
288
+ subject: formatName(subjectAttrs),
289
+ subjectCN: attrValue(subjectAttrs, '2.5.4.3'),
290
+ subjectO: attrValue(subjectAttrs, '2.5.4.10'),
291
+ issuer: formatName(issuerAttrs),
292
+ issuerCN: attrValue(issuerAttrs, '2.5.4.3'),
293
+ issuerO: attrValue(issuerAttrs, '2.5.4.10'),
294
+ serialNumber: serialNode ? serialHex(der, serialNode) : '',
295
+ fingerprintSha256: createHash('sha256').update(Buffer.from(der)).digest('hex')
296
+ .toUpperCase().replace(/(.{2})(?!$)/g, '$1:'),
297
+ notBefore: new Date(notBeforeMs).toISOString(),
298
+ notAfter: new Date(notAfterMs).toISOString(),
299
+ notBeforeMs,
300
+ notAfterMs,
301
+ sans: parseSans(der, extensions),
302
+ keyType: spkiNode ? keyLabel(der, spkiNode) : '',
303
+ selfSigned: formatName(issuerAttrs) === formatName(subjectAttrs)
304
+ };
305
+ }
306
+
307
+ function base64ToBytes(text) {
308
+ const clean = text.replace(/\s+/g, '');
309
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(clean)) throw new Error('证书内容包含无法识别的字符。');
310
+ const pad = clean.length % 4;
311
+ if (pad === 1) throw new Error('Base64 内容不完整,请重新复制证书。');
312
+ const padded = pad === 2 ? clean + '==' : pad === 3 ? clean + '=' : clean;
313
+ const buf = Buffer.from(padded, 'base64');
314
+ if (!buf.length) throw new Error('证书不是有效的 Base64 编码。');
315
+ return buf;
316
+ }
317
+
318
+ /** 从一段文本中解析所有证书,返回数组(支持证书链)。 */
319
+ export function parsePem(text) {
320
+ if (!text || !String(text).trim()) throw new Error('还没有可解析的证书内容。');
321
+ const blocks = [];
322
+ const re = /-----BEGIN CERTIFICATE-----([\s\S]*?)-----END CERTIFICATE-----/g;
323
+ let m;
324
+ while ((m = re.exec(text)) !== null) blocks.push(m[1]);
325
+ if (!blocks.length) {
326
+ const cleaned = String(text).replace(/-----[^-]+-----/g, '');
327
+ if (cleaned.replace(/\s+/g, '').length > 64) blocks.push(cleaned);
328
+ }
329
+ if (!blocks.length) {
330
+ throw new Error('没有找到证书内容,请粘贴包含 BEGIN CERTIFICATE 的 PEM 证书。');
331
+ }
332
+ return blocks.map((block) => parseCert(base64ToBytes(block)));
333
+ }
334
+
335
+ /** 通配符按单级匹配:*.example.com 命中 a.example.com,不命中 a.b.example.com。 */
336
+ export function domainMatches(pattern, domain) {
337
+ const p = String(pattern || '').trim().toLowerCase().replace(/\.$/, '');
338
+ const d = String(domain || '').trim().toLowerCase().replace(/\.$/, '');
339
+ if (!p || !d) return false;
340
+ if (p === d) return true;
341
+ if (!p.startsWith('*.')) return false;
342
+ const suffix = p.slice(1);
343
+ if (!d.endsWith(suffix)) return false;
344
+ return d.slice(0, d.length - suffix.length).indexOf('.') === -1;
345
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "sslauto-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "SSLAuto MCP Server:域名 SSL 证书检测、证书解析、证书申请与一次性私钥交付",
5
+ "type": "module",
6
+ "bin": {
7
+ "sslauto-mcp": "server.mjs"
8
+ },
9
+ "main": "server.mjs",
10
+ "files": [
11
+ "server.mjs",
12
+ "lib/",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
19
+ "scripts": {
20
+ "start": "node server.mjs"
21
+ },
22
+ "keywords": [
23
+ "mcp",
24
+ "model-context-protocol",
25
+ "ssl",
26
+ "tls",
27
+ "certificate",
28
+ "acme",
29
+ "letsencrypt",
30
+ "zerossl",
31
+ "ssl-check",
32
+ "certificate-expiry",
33
+ "ai-agent"
34
+ ],
35
+ "homepage": "https://sslauto.dfrdev.com/",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/wzdfr/sslauto-business-prod.git",
39
+ "directory": "skills/ssl-mcp"
40
+ },
41
+ "bugs": {
42
+ "url": "https://github.com/wzdfr/sslauto-business-prod/issues"
43
+ },
44
+ "license": "MIT",
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "registry": "https://registry.npmjs.org/"
48
+ },
49
+ "dependencies": {
50
+ "@modelcontextprotocol/sdk": "^1.32.2",
51
+ "zod": "^3.25.76"
52
+ }
53
+ }
package/server.mjs ADDED
@@ -0,0 +1,631 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * SSLAuto MCP Server(P1:只读能力)
4
+ *
5
+ * 提供的工具:
6
+ * - ssl_domain_check:检测任意域名的线上证书(调用 SSLAuto 公开接口)
7
+ * - ssl_cert_parse :本地解析 PEM / 证书链,不联网
8
+ *
9
+ * 环境变量:
10
+ * SSLAUTO_API_BASE 接口根地址,默认 https://sslauto.dfrdev.com
11
+ * SSLAUTO_TIMEOUT_MS 单次请求超时,默认 25000
12
+ */
13
+
14
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
15
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
16
+ import { z } from 'zod';
17
+ import { parsePem, domainMatches } from './lib/cert-parser.mjs';
18
+
19
+ const API_BASE = (process.env.SSLAUTO_API_BASE || 'https://sslauto.dfrdev.com').replace(/\/+$/, '');
20
+ const TIMEOUT_MS = Number(process.env.SSLAUTO_TIMEOUT_MS || 25000);
21
+ const SITE = 'https://sslauto.dfrdev.com';
22
+
23
+ const DAY = 86400000;
24
+
25
+ const DOMAIN_RE = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
26
+ const IPV4_RE = /^\d{1,3}(\.\d{1,3}){3}$/;
27
+
28
+ /** 去协议、路径、端口与大小写;拒绝 IP、通配符与内网域名。 */
29
+ function normalizeDomain(raw) {
30
+ if (typeof raw !== 'string') return null;
31
+ let value = raw.trim().toLowerCase();
32
+ if (!value || value.length > 512) return null;
33
+ const scheme = value.indexOf('://');
34
+ if (scheme >= 0) value = value.slice(scheme + 3);
35
+ let cut = value.length;
36
+ for (const stop of ['/', '?', '#', ' ', '\t']) {
37
+ const idx = value.indexOf(stop);
38
+ if (idx >= 0 && idx < cut) cut = idx;
39
+ }
40
+ value = value.slice(0, cut);
41
+ if (value.startsWith('[')) return null;
42
+ const colon = value.indexOf(':');
43
+ if (colon >= 0) value = value.slice(0, colon);
44
+ if (value.startsWith('@') || value.includes('*')) return null;
45
+ if (IPV4_RE.test(value)) return null;
46
+ if (value === 'localhost' || value.endsWith('.local') || value.endsWith('.internal')) return null;
47
+ if (!DOMAIN_RE.test(value)) return null;
48
+ return value;
49
+ }
50
+
51
+ function fmtDate(ms) {
52
+ const n = Number(ms);
53
+ if (!Number.isFinite(n)) return '未知';
54
+ return new Date(n).toISOString().slice(0, 10);
55
+ }
56
+
57
+ function daysBetween(ms) {
58
+ return Math.floor((Number(ms) - Date.now()) / DAY);
59
+ }
60
+
61
+ function text(body) {
62
+ return { content: [{ type: 'text', text: body }] };
63
+ }
64
+
65
+ function fail(message) {
66
+ return { isError: true, content: [{ type: 'text', text: message }] };
67
+ }
68
+
69
+ function jsonBlock(value) {
70
+ return JSON.stringify(value, null, 2);
71
+ }
72
+
73
+ const server = new McpServer({
74
+ name: 'sslauto',
75
+ version: '0.1.0'
76
+ });
77
+
78
+ server.registerTool(
79
+ 'ssl_domain_check',
80
+ {
81
+ title: '检测域名 SSL 证书',
82
+ description:
83
+ '实时检测一个公网域名 443 端口上的 SSL/TLS 证书:到期时间、剩余天数、颁发者、覆盖的域名(SAN)、' +
84
+ '证书链层数、TLS 协议,并判断证书是否与域名匹配。只读操作,不需要登录,不会接触私钥。' +
85
+ '当用户说「帮我查一下 xxx.com 的证书」「xxx.com 域名检测」「这个网站证书什么时候过期」时调用。',
86
+ inputSchema: {
87
+ domain: z.string().min(1).describe('要检测的域名,如 www.example.com;可带 https:// 前缀或路径')
88
+ },
89
+ annotations: {
90
+ readOnlyHint: true,
91
+ destructiveHint: false,
92
+ idempotentHint: true,
93
+ openWorldHint: true
94
+ }
95
+ },
96
+ async ({ domain }) => {
97
+ const host = normalizeDomain(domain);
98
+ if (!host) {
99
+ return fail('域名格式不正确,请输入形如 www.example.com 的公网域名(不要包含端口、路径、IP 或通配符)。');
100
+ }
101
+
102
+ let payload;
103
+ try {
104
+ const url = `${API_BASE}/api/public/ssl/check?domain=${encodeURIComponent(host)}`;
105
+ const resp = await fetch(url, {
106
+ headers: { accept: 'application/json', 'user-agent': 'sslauto-mcp/0.1.0' },
107
+ signal: AbortSignal.timeout(TIMEOUT_MS)
108
+ });
109
+ if (!resp.ok) {
110
+ return fail(`检测服务返回 HTTP ${resp.status},请稍后重试。`);
111
+ }
112
+ payload = await resp.json();
113
+ } catch (e) {
114
+ const name = e && e.name ? e.name : '';
115
+ if (name === 'TimeoutError' || name === 'AbortError') {
116
+ return fail(`连接证书检测服务超时(${TIMEOUT_MS}ms),请稍后重试。`);
117
+ }
118
+ return fail(`无法连接证书检测服务:${e && e.message ? e.message : String(e)}`);
119
+ }
120
+
121
+ if (!payload || payload.code !== 200 || !payload.data) {
122
+ const msg = payload && payload.message ? payload.message : '检测服务返回了非预期结果';
123
+ return fail(`检测失败:${msg}`);
124
+ }
125
+
126
+ const d = payload.data;
127
+ if (d.reachable === false) {
128
+ return text(
129
+ `⚠️ ${host} 未能取到证书:${d.reason || '连接失败或未部署 HTTPS'}。\n\n` +
130
+ `常见原因:该域名没有开放 443 端口、没有部署 HTTPS、或当前网络无法访问目标站点。\n\n` +
131
+ jsonBlock({
132
+ domain: host,
133
+ reachable: false,
134
+ reason: d.reason || '连接失败或未部署 HTTPS'
135
+ })
136
+ );
137
+ }
138
+
139
+ const daysLeft = Number(d.daysLeft);
140
+ const notAfter = d.notAfter;
141
+ const matched = d.domainMatched === true;
142
+ const expired = daysLeft < 0;
143
+ let status = '有效';
144
+ let icon = '✅';
145
+ if (expired) {
146
+ status = '已过期';
147
+ icon = '❌';
148
+ } else if (daysLeft <= 7) {
149
+ status = '即将过期(高风险)';
150
+ icon = '🚨';
151
+ } else if (daysLeft <= 30) {
152
+ status = '临近到期';
153
+ icon = '⚠️';
154
+ }
155
+
156
+ const sans = Array.isArray(d.sans) ? d.sans : [];
157
+ const sanPreview = sans.slice(0, 10).join(', ') + (sans.length > 10 ? ` 等 ${sans.length} 个` : '');
158
+
159
+ const lines = [
160
+ `${icon} ${host} 的证书${status}。`,
161
+ ``,
162
+ `- 到期时间:${fmtDate(notAfter)}(剩余 ${daysLeft} 天)`,
163
+ `- 颁发者:${d.issuerOrg || d.issuer || d.issuerCN || '未知'}`,
164
+ `- 域名匹配:${matched ? '是' : '否(当前证书未覆盖该域名)'}`,
165
+ `- 证书链:${d.chainLength || 1} 层,TLS 协议 ${d.protocol || '未知'}`,
166
+ `- 覆盖域名:${sanPreview || '未提供'}`
167
+ ];
168
+
169
+ if (!matched) {
170
+ lines.push('', '⚠️ 证书与域名不匹配,浏览器会提示不安全。请检查是否部署了其他域名的证书,或 CDN 节点证书未同步。');
171
+ }
172
+ if (expired) {
173
+ lines.push('', '证书已过期,请尽快更换。');
174
+ } else if (daysLeft <= 30) {
175
+ lines.push('', `建议在剩余 30 天内完成续期。如需自动续签与集中托管,可访问 ${SITE}。`);
176
+ }
177
+
178
+ lines.push('', '```json', jsonBlock({
179
+ domain: host,
180
+ reachable: true,
181
+ status,
182
+ daysLeft,
183
+ validFrom: fmtDate(d.notBefore ?? d.validFrom),
184
+ validTo: fmtDate(notAfter ?? d.validTo),
185
+ issuer: d.issuerOrg || d.issuer || d.issuerCN || '',
186
+ issuerCN: d.issuerCN || '',
187
+ subjectCN: d.subjectCN || '',
188
+ domainMatched: matched,
189
+ chainLength: d.chainLength || 1,
190
+ protocol: d.protocol || '',
191
+ cipher: d.cipher || d.cipherSuite || '',
192
+ sans,
193
+ serialNumber: d.serialNumber || d.serialNo || '',
194
+ fingerprintSha256: d.fingerprint || '',
195
+ latencyMs: d.latencyMs ?? null
196
+ }), '```');
197
+
198
+ return text(lines.join('\n'));
199
+ }
200
+ );
201
+
202
+ server.registerTool(
203
+ 'ssl_cert_parse',
204
+ {
205
+ title: '解析证书内容',
206
+ description:
207
+ '在本地解析一段证书文本(PEM 或裸 Base64,支持包含多张证书的证书链),' +
208
+ '输出主体、颁发者、有效期、剩余天数、SAN 覆盖域名、公钥类型、序列号与 SHA-256 指纹。' +
209
+ '不联网、不上传任何内容,可用于分析用户粘贴的证书或证书文件。',
210
+ inputSchema: {
211
+ pem: z.string().min(1).describe('证书内容,需包含 -----BEGIN CERTIFICATE-----,或为证书的 Base64 内容'),
212
+ domain: z.string().optional().describe('可选:校验证书是否覆盖该域名,按通配符单级匹配规则判断')
213
+ },
214
+ annotations: {
215
+ readOnlyHint: true,
216
+ destructiveHint: false,
217
+ idempotentHint: true,
218
+ openWorldHint: false
219
+ }
220
+ },
221
+ async ({ pem, domain }) => {
222
+ let certs;
223
+ try {
224
+ certs = parsePem(pem);
225
+ } catch (e) {
226
+ return fail(`证书解析失败:${e && e.message ? e.message : String(e)}`);
227
+ }
228
+ if (!certs.length) {
229
+ return fail('没有在输入中找到可解析的证书。');
230
+ }
231
+
232
+ const target = domain ? normalizeDomain(domain) : null;
233
+ if (domain && !target) {
234
+ return fail('用于校对的域名格式不正确,请输入形如 www.example.com 的域名。');
235
+ }
236
+
237
+ const items = certs.map((c, index) => {
238
+ const daysLeft = daysBetween(c.notAfterMs);
239
+ const names = c.sans.length ? c.sans : c.subjectCN ? [c.subjectCN] : [];
240
+ const matched = target
241
+ ? names.some((name) => domainMatches(name, target))
242
+ : null;
243
+ return {
244
+ index: index + 1,
245
+ role: index === 0 ? 'leaf' : 'chain',
246
+ subject: c.subject,
247
+ subjectCN: c.subjectCN,
248
+ issuer: c.issuer,
249
+ issuerO: c.issuerO,
250
+ serialNumber: c.serialNumber,
251
+ notBefore: new Date(c.notBeforeMs).toISOString(),
252
+ notAfter: new Date(c.notAfterMs).toISOString(),
253
+ daysLeft,
254
+ expired: daysLeft < 0,
255
+ sans: c.sans,
256
+ keyType: c.keyType,
257
+ selfSigned: c.selfSigned,
258
+ fingerprintSha256: c.fingerprintSha256,
259
+ domainMatched: matched
260
+ };
261
+ });
262
+
263
+ const leaf = items[0];
264
+ const lines = [
265
+ `已解析 ${items.length} 张证书。`,
266
+ ``,
267
+ `- 主体:${leaf.subject || '(空)'}`,
268
+ `- 颁发者:${leaf.issuer || '(空)'}`,
269
+ `- 有效期:${leaf.notBefore.slice(0, 10)} ~ ${leaf.notAfter.slice(0, 10)}(剩余 ${leaf.daysLeft} 天)`,
270
+ `- 公钥:${leaf.keyType || '未知'}`,
271
+ `- 覆盖域名:${leaf.sans.length ? leaf.sans.slice(0, 10).join(', ') : leaf.subjectCN || '未提供'}`
272
+ ];
273
+ if (target) {
274
+ lines.push(`- 是否覆盖 ${target}:${leaf.domainMatched ? '是' : '否'}`);
275
+ }
276
+ if (leaf.expired) {
277
+ lines.push('', '❌ 该证书已过期。');
278
+ } else if (leaf.daysLeft <= 30) {
279
+ lines.push('', `⚠️ 该证书将在 ${leaf.daysLeft} 天后到期,建议尽快续期。`);
280
+ }
281
+
282
+ lines.push('', '```json', jsonBlock(items), '```');
283
+ return text(lines.join('\n'));
284
+ }
285
+ );
286
+
287
+ const transport = new StdioServerTransport();
288
+ await server.connect(transport);
289
+
290
+ // ==================== P2 证书申请能力 ====================
291
+ // Bearer token / principalId 通过环境变量传入:
292
+ // SSLAUTO_TOKEN 已登录用户的 AI 访问令牌(用户在网页上生成)
293
+ // SSLAUTO_PRINCIPAL_ID 邮箱验证过的影子账户 ID(ssl_bind_email 后自动缓存到会话)
294
+
295
+ const API_TOKEN = process.env.SSLAUTO_TOKEN || '';
296
+ const SESSION = { principalId: null };
297
+ const SCOPES = 'cert:apply,cert:view,cert:download,ai:*';
298
+
299
+ async function api(method, path, body, auth = true) {
300
+ const opts = {
301
+ method,
302
+ headers: { accept: 'application/json', 'content-type': 'application/json', 'user-agent': 'sslauto-mcp/0.2.0' },
303
+ signal: AbortSignal.timeout(TIMEOUT_MS)
304
+ };
305
+ if (auth && API_TOKEN) opts.headers.authorization = `Bearer ${API_TOKEN}`;
306
+ if (body !== undefined) opts.body = JSON.stringify(body);
307
+ const url = path.startsWith('http') ? path : `${API_BASE}${path}`;
308
+ const resp = await fetch(url, opts);
309
+ const payload = await resp.json().catch(() => ({ code: resp.status, message: resp.statusText }));
310
+ if (!resp.ok || (payload && payload.code !== 200)) {
311
+ const msg = payload && payload.message ? payload.message : `HTTP ${resp.status}`;
312
+ throw new Error(msg);
313
+ }
314
+ return payload.data;
315
+ }
316
+
317
+ server.registerTool(
318
+ 'ssl_bind_email',
319
+ {
320
+ title: '绑定邮箱创建 AI 证书账户',
321
+ description:
322
+ '给邮箱发送 6 位验证码;带验证码调用后创建一个 SSLAuto 影子账户并返回 principalId。' +
323
+ '后续下单可以用 principalId 作为匿名身份,也可以用已登录用户生成的 SSLAUTO_TOKEN。' +
324
+ '场景:用户第一次在 AI 里申请证书时需要先绑定邮箱。',
325
+ inputSchema: {
326
+ email: z.string().describe('用户的邮箱地址,如 user@example.com'),
327
+ code: z.string().optional().describe('首次调用留空发验证码;第二次调用带上验证码(6 位数字)'),
328
+ clientName: z.string().optional().describe('客户端名称,用于来源统计(如 trae / qoder / doubao)')
329
+ },
330
+ annotations: {
331
+ readOnlyHint: false,
332
+ destructiveHint: false,
333
+ idempotentHint: false,
334
+ openWorldHint: false
335
+ }
336
+ },
337
+ async ({ email, code, clientName }) => {
338
+ if (!email) return fail('请提供邮箱地址。');
339
+ if (!code) {
340
+ try {
341
+ await api('POST', '/api/ai/v1/bind/send-code', { email });
342
+ return text(
343
+ `📧 验证码已发送到 ${email}。\n\n` +
344
+ `请让用户查收邮件,拿到 6 位验证码后再次调用本工具,参数带上 code=。\n` +
345
+ `验证码 10 分钟有效。`
346
+ );
347
+ } catch (e) { return fail(`发送验证码失败:${e.message}`); }
348
+ }
349
+ try {
350
+ const data = await api('POST', '/api/ai/v1/bind/verify', { email, code, clientType: 'MCP', clientName: clientName || 'sslauto-mcp' }, false);
351
+ SESSION.principalId = data.principalId;
352
+ return text(
353
+ `✅ 邮箱已绑定。\n\n` +
354
+ `- principalId:${data.principalId}(已缓存在当前会话)\n` +
355
+ `- claimUrl:${data.claimUrl}\n\n` +
356
+ `可以直接调用 ssl_order_create 申请证书。用户最终需要打开 claimUrl 认领账户才能领取私钥。`
357
+ );
358
+ } catch (e) { return fail(`绑定失败:${e.message}`); }
359
+ }
360
+ );
361
+
362
+ server.registerTool(
363
+ 'ssl_order_create',
364
+ {
365
+ title: '创建 SSL 证书申请订单',
366
+ description:
367
+ '为一个或多个域名创建 SSL 证书申请订单。需要先通过 ssl_bind_email 绑定邮箱(或已配置 SSLAUTO_TOKEN)。\n' +
368
+ '调用前必须先和用户确认两个选项,不要替用户默认决定:\n' +
369
+ '1) 域名验证方式 validation:DNS(默认,配置 TXT 记录)或 FILE(在网站根目录放验证文件);\n' +
370
+ '2) 证书品牌 brand:LETSENCRYPT(默认)、ZEROSSL、LITESSL。\n' +
371
+ '约束:通配符域名(*.example.com)只能用 DNS 验证;LITESSL 需要平台侧已配置 EAB。\n' +
372
+ '危险操作:会创建真实的 ACME 订单并消耗证书配额。',
373
+ inputSchema: {
374
+ domains: z.array(z.string()).min(1).describe('要申请证书的域名列表,如 ["www.example.com"]'),
375
+ validation: z.enum(['DNS', 'FILE']).optional()
376
+ .describe('域名验证方式:DNS=手动添加 TXT 记录(默认);FILE=HTTP 文件验证,需在网站根目录放置指定文件。通配符域名只能选 DNS'),
377
+ brand: z.enum(['LETSENCRYPT', 'ZEROSSL', 'LITESSL']).optional()
378
+ .describe('证书品牌:LETSENCRYPT(默认)、ZEROSSL、LITESSL。用户未明确选择时用 LETSENCRYPT'),
379
+ keyType: z.string().optional().describe('密钥类型:RSA(默认)或 ECC'),
380
+ remark: z.string().optional().describe('备注,方便用户在 SSLAuto 后台识别这张证书')
381
+ },
382
+ annotations: {
383
+ readOnlyHint: false,
384
+ destructiveHint: true,
385
+ idempotentHint: false,
386
+ openWorldHint: false
387
+ }
388
+ },
389
+ async ({ domains, validation, brand, keyType, remark }) => {
390
+ if (!domains || !domains.length) return fail('请至少提供一个域名。');
391
+ const clean = domains.map((d) => normalizeDomain(d)).filter(Boolean);
392
+ if (!clean.length) return fail('域名格式不正确,请输入形如 www.example.com 的域名。');
393
+
394
+ const mode = (validation || 'DNS').toUpperCase();
395
+ const certBrand = (brand || 'LETSENCRYPT').toUpperCase();
396
+ if (mode === 'FILE' && clean.some((d) => d.startsWith('*.'))) {
397
+ return fail('通配符域名只能用 DNS 验证,请把 validation 改成 DNS。');
398
+ }
399
+
400
+ const body = {
401
+ domains: clean,
402
+ keyType: keyType || 'RSA',
403
+ brand: certBrand,
404
+ validation: mode === 'FILE' ? 'HTTP_FILE' : 'MANUAL_DNS',
405
+ remark
406
+ };
407
+ if (!API_TOKEN) {
408
+ if (!SESSION.principalId) {
409
+ return fail('请先调用 ssl_bind_email 绑定邮箱,或设置 SSLAUTO_TOKEN 环境变量。');
410
+ }
411
+ body.principalId = SESSION.principalId;
412
+ }
413
+ try {
414
+ const data = await api('POST', '/api/ai/v1/orders', body);
415
+ const lines = [
416
+ `✅ 订单已创建。`,
417
+ ``,
418
+ `- 订单 ID:${data.orderId}`,
419
+ `- 状态:${data.status}`,
420
+ `- 域名:${(data.domains || []).join(', ')}`,
421
+ `- 证书品牌:${data.brand || certBrand}`,
422
+ `- 验证方式:${mode === 'FILE' ? 'HTTP 文件验证' : '手动 DNS(TXT)'}`
423
+ ];
424
+
425
+ if (mode === 'FILE' && Array.isArray(data.fileChallenges)) {
426
+ lines.push('', `需要在网站根目录创建以下文件(路径相对于站点根目录,不要改名、不要加后缀):`);
427
+ for (const f of data.fileChallenges) {
428
+ lines.push(` - 域名:${f.domain}`);
429
+ lines.push(` 路径:${f.path}`);
430
+ lines.push(` 内容:${f.content}`);
431
+ lines.push(` 验证地址(文件放好后应能直接访问):${f.url}`);
432
+ }
433
+ lines.push('', '文件放好且能通过 HTTP 访问后,调用 ssl_order_verify 触发校验与签发。');
434
+ } else if (Array.isArray(data.dnsRecords)) {
435
+ lines.push('', `DNS TXT 记录(请到域名解析平台添加):`);
436
+ for (const r of data.dnsRecords) {
437
+ lines.push(` - 域名:${r.domain}`);
438
+ lines.push(` 记录类型:TXT`);
439
+ lines.push(` 主机记录:${r.name}`);
440
+ lines.push(` 记录值:${r.value}`);
441
+ lines.push(` TTL:${r.ttl ?? 60}`);
442
+ }
443
+ lines.push('', '记录生效后(通常 1–5 分钟),调用 ssl_order_verify 触发校验与签发。');
444
+ }
445
+
446
+ lines.push('', '```json', jsonBlock(data), '```');
447
+ return text(lines.join('\n'));
448
+ } catch (e) { return fail(`创建订单失败:${e.message}`); }
449
+ }
450
+ );
451
+
452
+ server.registerTool(
453
+ 'ssl_order_status',
454
+ {
455
+ title: '查询证书订单状态',
456
+ description:
457
+ '查询一个证书订单的当前状态(PENDING / WAIT_DNS / WAIT_FILE / ISSUING / ISSUED / FAILED / REVOKED)、' +
458
+ '待配置的 TXT 记录或验证文件、签发进度与到期时间。' +
459
+ '建议在用户说「DNS 配好了 / 文件传好了」之后先查一次再决定是否调用 verify。',
460
+ inputSchema: {
461
+ orderId: z.number().int().positive().describe('订单 ID(ssl_order_create 返回的 orderId)')
462
+ },
463
+ annotations: {
464
+ readOnlyHint: true,
465
+ destructiveHint: false,
466
+ idempotentHint: true,
467
+ openWorldHint: false
468
+ }
469
+ },
470
+ async ({ orderId }) => {
471
+ try {
472
+ const data = await api('GET', `/api/ai/v1/orders?id=${orderId}`, undefined, false);
473
+ const modeText = data.validation === 'HTTP_FILE' ? 'HTTP 文件验证' : '手动 DNS(TXT)';
474
+ const lines = [
475
+ `订单 #${data.orderId}:${data.status}`,
476
+ ``,
477
+ `- 域名:${(data.domains || []).join(', ')}`,
478
+ `- 证书品牌:${data.brand || 'LETSENCRYPT'}`,
479
+ `- 验证方式:${modeText}`,
480
+ `- 剩余天数:${data.daysLeft ?? '—'}`,
481
+ `- 到期时间:${data.notAfter ? new Date(data.notAfter).toISOString().slice(0, 10) : '—'}`,
482
+ `- 来源:${data.source || 'WEB'}`
483
+ ];
484
+ if (data.status === 'WAIT_FILE' && Array.isArray(data.fileChallenges)) {
485
+ lines.push('', '尚未校验,需要放置以下文件:');
486
+ for (const f of data.fileChallenges) {
487
+ lines.push(` - ${f.domain}:${f.path}`);
488
+ lines.push(` 内容:${f.content}`);
489
+ }
490
+ lines.push('', '文件可访问后调用 ssl_order_verify。');
491
+ } else if (data.status === 'WAIT_DNS' && Array.isArray(data.dnsRecords)) {
492
+ lines.push('', '尚未校验,需要添加以下 TXT 记录:');
493
+ for (const r of data.dnsRecords) {
494
+ lines.push(` - ${r.name} = ${r.value}`);
495
+ }
496
+ lines.push('', '记录生效后调用 ssl_order_verify。');
497
+ }
498
+ lines.push('', '```json', jsonBlock(data), '```');
499
+ return text(lines.join('\n'));
500
+ } catch (e) { return fail(`查询订单失败:${e.message}`); }
501
+ }
502
+ );
503
+
504
+ server.registerTool(
505
+ 'ssl_order_verify',
506
+ {
507
+ title: '触发域名校验并签发证书',
508
+ description:
509
+ '对 WAIT_DNS 或 WAIT_FILE 状态的订单执行一次校验:DNS 订单检查 TXT 记录,文件订单检查网站根目录下的验证文件。' +
510
+ '校验通过后提交 CA 签发,通常需要 1-3 分钟;可以再调用 ssl_order_status 查看结果。' +
511
+ '危险操作:会向 ACME CA 提交一次验证请求,频繁失败会导致 CA 限流。',
512
+ inputSchema: {
513
+ orderId: z.number().int().positive().describe('订单 ID')
514
+ },
515
+ annotations: {
516
+ readOnlyHint: false,
517
+ destructiveHint: true,
518
+ idempotentHint: true,
519
+ openWorldHint: false
520
+ }
521
+ },
522
+ async ({ orderId }) => {
523
+ try {
524
+ const data = await api('POST', '/api/ai/v1/orders/verify', { id: orderId }, false);
525
+ const isFile = data.validation === 'HTTP_FILE';
526
+ const lines = [`订单 #${data.orderId} 当前状态:${data.status}`];
527
+ if (data.status === 'ISSUED') {
528
+ lines.push('', `✅ 证书已签发成功!`);
529
+ lines.push(` 调用 ssl_key_link 获取一次性下载链接,让用户领取私钥。`);
530
+ } else if (data.status === 'WAIT_DNS' || data.status === 'WAIT_FILE') {
531
+ lines.push('', isFile ? '⚠️ 文件校验还没通过。' : '⚠️ DNS 校验还没通过。');
532
+ lines.push(isFile
533
+ ? ' 请确认验证文件已放在网站根目录,且能通过 http://域名/.well-known/acme-challenge/文件名 访问。'
534
+ : ' 请确认 TXT 记录已生效(可用 https://dnschecker.org 查询)。');
535
+ } else if (data.status === 'FAILED') {
536
+ lines.push('', isFile ? '❌ 验证失败,请检查验证文件是否可访问、是否被重写规则拦截。' : '❌ 验证失败,请检查 DNS 配置或稍后再试。');
537
+ }
538
+ return text(lines.join('\n'));
539
+ } catch (e) { return fail(`验证失败:${e.message}`); }
540
+ }
541
+ );
542
+
543
+ server.registerTool(
544
+ 'ssl_key_link',
545
+ {
546
+ title: '获取证书私钥一次性下载链接',
547
+ description:
548
+ '为已签发的证书生成一个一次性下载链接,15 分钟内有效,打开后只能领取一次。' +
549
+ '⚠️ 这个工具**不会返回私钥正文**,只返回下载链接。请直接把链接告诉用户,不要在对话中索要或粘贴私钥。' +
550
+ '⚠️ 未认领账户(影子账户)需要先给邮箱发送验证码完成认领,认领流程见 claimUrl。',
551
+ inputSchema: {
552
+ orderId: z.number().int().positive().describe('已签发的证书订单 ID'),
553
+ fileType: z.enum(['zip', 'privkey', 'cert', 'chain', 'fullchain']).optional()
554
+ .describe('下载格式,默认 zip(包含 privkey / cert / chain / fullchain)'),
555
+ email: z.string().optional().describe('未认领账户必须提供邮箱 + code'),
556
+ code: z.string().optional().describe('未认领账户必须提供邮箱验证码')
557
+ },
558
+ annotations: {
559
+ readOnlyHint: false,
560
+ destructiveHint: true,
561
+ idempotentHint: false,
562
+ openWorldHint: false
563
+ }
564
+ },
565
+ async ({ orderId, fileType, email, code }) => {
566
+ if (fileType === 'privkey') {
567
+ // 强制 zip:只给下载链接,绝不暴露私钥正文
568
+ fileType = 'zip';
569
+ }
570
+ const body = { orderId, fileType: fileType || 'zip', email, code };
571
+ try {
572
+ const data = await api('POST', '/api/ai/v1/key-ticket', body, false);
573
+ const lines = [
574
+ `🔗 证书下载链接已生成。`,
575
+ ``,
576
+ `- 链接:${SITE}${data.url}`,
577
+ `- 有效期:${data.expiresIn} 秒(${Math.round(data.expiresIn / 60)} 分钟)`,
578
+ `- 仅可用一次`,
579
+ ``
580
+ ];
581
+ lines.push('⚠️ 重要:');
582
+ lines.push(`- 不要让用户把私钥粘贴到对话里,也不要尝试在工具调用参数里索要私钥正文。`);
583
+ lines.push(`- 如果链接过期,重新调用本工具会得到新的链接。`);
584
+ lines.push(`- 影子账户的用户需要先在网页上完成认领(之前 ssl_bind_email 返回的 claimUrl),认领后才能领取私钥。`);
585
+ return text(lines.join('\n'));
586
+ } catch (e) {
587
+ const msg = String(e.message || '');
588
+ if (msg.includes('认领')) {
589
+ return fail(`未认领账户不能领取私钥。请让用户打开 ssl_bind_email 返回的 claimUrl 先完成认领。服务端返回:${msg}`);
590
+ }
591
+ return fail(`获取下载链接失败:${msg}`);
592
+ }
593
+ }
594
+ );
595
+
596
+ server.registerTool(
597
+ 'ssl_account_info',
598
+ {
599
+ title: '查询当前 AI 账户信息',
600
+ description:
601
+ '查看当前绑定账户/令牌对应的 SSLAuto 账户信息:用户名、套餐、剩余证书配额、已用配额、认领状态等。' +
602
+ '没有绑定或令牌时会返回 401。',
603
+ inputSchema: {},
604
+ annotations: {
605
+ readOnlyHint: true,
606
+ destructiveHint: false,
607
+ idempotentHint: true,
608
+ openWorldHint: false
609
+ }
610
+ },
611
+ async () => {
612
+ if (!API_TOKEN && !SESSION.principalId) {
613
+ return fail('尚未绑定邮箱或设置 SSLAUTO_TOKEN,无法查询账户信息。请先调用 ssl_bind_email。');
614
+ }
615
+ try {
616
+ const data = await api('GET', '/api/ai/v1/me', undefined, false);
617
+ const quota = data.certQuota == null || data.certQuota < 0 ? '无限' : data.certQuota;
618
+ const lines = [
619
+ `当前账户:`,
620
+ ``,
621
+ `- 用户:${data.username}(${data.nickname || ''})`,
622
+ `- 租户:${data.tenantId}`,
623
+ `- 套餐:${data.planCode}`,
624
+ `- 证书配额:${data.certUsed}/${quota}`,
625
+ `- 认领状态:${data.claimStatus || '已是正式账户'}`
626
+ ];
627
+ return text(lines.join('\n'));
628
+ } catch (e) { return fail(`查询失败:${e.message}`); }
629
+ }
630
+ );
631
+