@chaoyue-erp/ysy-openapi-mcp 0.0.0-stage → 1.0.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 +13 -0
- package/README.md +138 -2
- package/config.example.json +34 -0
- package/package.json +40 -4
- package/skills/ysy-openapi/SKILL.md +95 -0
- package/src/api-client.mjs +202 -0
- package/src/config.mjs +101 -0
- package/src/data-map.json +6260 -0
- package/src/errors.mjs +13 -0
- package/src/server.mjs +339 -0
- package/src/token-manager.mjs +98 -0
package/src/errors.mjs
ADDED
package/src/server.mjs
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
6
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
7
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
|
|
10
|
+
import { DATA_MAP, loadConfig, configuredModules, missingModules } from "./config.mjs";
|
|
11
|
+
import { TokenManager } from "./token-manager.mjs";
|
|
12
|
+
import { ApiClient } from "./api-client.mjs";
|
|
13
|
+
|
|
14
|
+
const cfg = loadConfig();
|
|
15
|
+
const tokens = new TokenManager(cfg);
|
|
16
|
+
const api = new ApiClient(cfg, tokens);
|
|
17
|
+
const BY_CODE = new Map(DATA_MAP.apis.map((a) => [a.apiCode, a]));
|
|
18
|
+
|
|
19
|
+
const text = (value) => ({ content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }] });
|
|
20
|
+
const fail = (message) => ({ isError: true, content: [{ type: "text", text: `错误:${message}` }] });
|
|
21
|
+
const wrap = async (fn) => {
|
|
22
|
+
try {
|
|
23
|
+
return text(await fn());
|
|
24
|
+
} catch (err) {
|
|
25
|
+
return fail(err.message || String(err));
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
function resolveApi(args) {
|
|
30
|
+
const code = args.apiCode || args.actionCode;
|
|
31
|
+
if (!code) throw new Error("请提供 apiCode(文档中的字段名为 apiCode,不是 actionCode;actionCode 仅作为兼容别名)。");
|
|
32
|
+
const found = BY_CODE.get(code);
|
|
33
|
+
if (!found) {
|
|
34
|
+
const near = DATA_MAP.apis.filter((a) => a.apiCode.includes(code.split(".")[0])).slice(0, 5).map((a) => a.apiCode);
|
|
35
|
+
throw new Error(`未找到 apiCode「${code}」。请先用 list_apis 查目录。${near.length ? `相近的 code:${near.join("、")}` : ""}`);
|
|
36
|
+
}
|
|
37
|
+
return found;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function createServer() {
|
|
41
|
+
const server = new McpServer({ name: "ysy-openapi", version: "1.0.0" });
|
|
42
|
+
|
|
43
|
+
server.registerTool(
|
|
44
|
+
"list_modules",
|
|
45
|
+
{
|
|
46
|
+
description: "列出悦商云开放接口的业务模块。一个客户端只对应一个模块,取 Token 前需确认该模块已配置密钥。返回模块名、接口数和密钥配置状态。",
|
|
47
|
+
inputSchema: {},
|
|
48
|
+
},
|
|
49
|
+
() =>
|
|
50
|
+
wrap(() => {
|
|
51
|
+
const ready = new Set(configuredModules(cfg));
|
|
52
|
+
return {
|
|
53
|
+
environment: cfg.envName,
|
|
54
|
+
endpoints: { token: cfg.tokenUrl, query: cfg.queryUrl },
|
|
55
|
+
modules: Object.entries(DATA_MAP.modules).map(([code, m]) => ({
|
|
56
|
+
moduleCode: code,
|
|
57
|
+
name: m.name,
|
|
58
|
+
apiCount: m.apiCodes.length,
|
|
59
|
+
credentialsConfigured: ready.has(code),
|
|
60
|
+
})),
|
|
61
|
+
notConfigured: missingModules(cfg),
|
|
62
|
+
hint: "一个客户端对应一个模块,多模块需分别领取密钥并分别取 Token。",
|
|
63
|
+
};
|
|
64
|
+
}),
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
server.registerTool(
|
|
68
|
+
"list_apis",
|
|
69
|
+
{
|
|
70
|
+
description: "查询接口目录(数据地图)。在调用 query 之前先用它找到正确的 apiCode。可按模块、关键字、类型过滤。",
|
|
71
|
+
inputSchema: {
|
|
72
|
+
moduleCode: z.string().optional().describe("base / mall / sale / purchase / finance / import"),
|
|
73
|
+
keyword: z.string().optional().describe("按接口名称或 apiCode 模糊搜索,如 销售、毛利、订单、明细"),
|
|
74
|
+
kind: z.enum(["query", "import", "command"]).optional().describe("query=查询,import=Excel导入,command=订单JSON写入"),
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
(args) =>
|
|
78
|
+
wrap(() => {
|
|
79
|
+
let list = DATA_MAP.apis;
|
|
80
|
+
if (args.moduleCode) list = list.filter((a) => a.moduleCode === args.moduleCode);
|
|
81
|
+
if (args.kind) list = list.filter((a) => a.kind === args.kind);
|
|
82
|
+
if (args.keyword) {
|
|
83
|
+
const k = args.keyword.toLowerCase();
|
|
84
|
+
list = list.filter((a) => a.apiCode.toLowerCase().includes(k) || a.name.toLowerCase().includes(k) || (a.summary || "").toLowerCase().includes(k));
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
total: list.length,
|
|
88
|
+
apis: list.map((a) => ({ apiCode: a.apiCode, name: a.name, moduleCode: a.moduleCode, kind: a.kind, entry: a.entry, resultPath: a.resultPath })),
|
|
89
|
+
hint: "拿到 apiCode 后用 describe_api 查看完整参数,再调用 query。",
|
|
90
|
+
};
|
|
91
|
+
}),
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
server.registerTool(
|
|
95
|
+
"describe_api",
|
|
96
|
+
{
|
|
97
|
+
description: "查看某个 apiCode 的完整参数说明:params 参数表、报表 searches 可用 key、请求示例、返回字段与数据路径。填写 query 的 params 前必须先调用此工具。",
|
|
98
|
+
inputSchema: {
|
|
99
|
+
apiCode: z.string().describe("完整接口 code,区分大小写,如 sale.list"),
|
|
100
|
+
actionCode: z.string().optional().describe("apiCode 的兼容别名,二选一"),
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
(args) =>
|
|
104
|
+
wrap(() => {
|
|
105
|
+
const a = resolveApi(args);
|
|
106
|
+
const rules = DATA_MAP.commonRules;
|
|
107
|
+
const out = {
|
|
108
|
+
apiCode: a.apiCode,
|
|
109
|
+
name: a.name,
|
|
110
|
+
moduleCode: a.moduleCode,
|
|
111
|
+
kind: a.kind,
|
|
112
|
+
entry: a.entry,
|
|
113
|
+
resultPath: a.resultPath,
|
|
114
|
+
summary: a.summary,
|
|
115
|
+
params: a.params,
|
|
116
|
+
formFields: a.formFields,
|
|
117
|
+
executeFields: a.executeFields,
|
|
118
|
+
searchKeys: a.searchKeys,
|
|
119
|
+
requestExample: a.requestExample,
|
|
120
|
+
responseFields: a.responseFields.slice(0, 40),
|
|
121
|
+
responseNotes: a.responseNotes,
|
|
122
|
+
rules: {
|
|
123
|
+
success: rules.success,
|
|
124
|
+
pagination: rules.pagination,
|
|
125
|
+
dates: rules.dates,
|
|
126
|
+
searches: rules.searches,
|
|
127
|
+
detailId: rules.detailId,
|
|
128
|
+
sort: rules.sort,
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
if (a.kind !== "query") {
|
|
132
|
+
out.warning = `此 code 属于 ${a.entry} 入口(写入类),不能用 query 工具调用;且写入工具默认禁用。`;
|
|
133
|
+
}
|
|
134
|
+
if (a.apiCode.startsWith("sale.") && a.apiCode.includes("detail")) out.reminder = "必须先查 sale.list 拿 data.list[i].id 作为 saleId。";
|
|
135
|
+
if (a.apiCode.startsWith("purchase.") && a.apiCode.includes("detail")) out.reminder = "必须先查对应采购列表拿 data.list[i].id 作为 purchaseId。";
|
|
136
|
+
return out;
|
|
137
|
+
}),
|
|
138
|
+
);
|
|
139
|
+
|
|
140
|
+
server.registerTool(
|
|
141
|
+
"query",
|
|
142
|
+
{
|
|
143
|
+
description: "调用悦商云策略网关查询数据(POST /openapi/v1/query)。请求外壳为 {moduleCode, apiCode, params}。自动取 Token、缓存并在 401 时刷新;自动把 YYYY-MM-DD 日期转为毫秒时间戳;自动按数据地图校验 code 并截断超大结果。",
|
|
144
|
+
inputSchema: {
|
|
145
|
+
apiCode: z.string().optional().describe("完整接口 code,区分大小写,如 sale.list、goods.list"),
|
|
146
|
+
actionCode: z.string().optional().describe("apiCode 的兼容别名,与 apiCode 二选一"),
|
|
147
|
+
moduleCode: z.string().optional().describe("模块 code;省略时按数据地图自动推断"),
|
|
148
|
+
params: z.record(z.any()).optional().describe("业务参数,放筛选/分页/排序;报表筛选放 params.searches"),
|
|
149
|
+
pageNum: z.number().int().min(1).optional().describe("页码,从 1 开始;翻页时保持其他筛选条件不变"),
|
|
150
|
+
pageSize: z.number().int().min(1).max(500).optional().describe("每页条数,1~500,默认 100"),
|
|
151
|
+
},
|
|
152
|
+
},
|
|
153
|
+
(args) =>
|
|
154
|
+
wrap(async () => {
|
|
155
|
+
const a = resolveApi(args);
|
|
156
|
+
if (a.kind !== "query" || a.entry !== "query") {
|
|
157
|
+
throw new Error(`apiCode「${a.apiCode}」属于 ${a.entry} 入口,不是查询接口。请改用 query 类 code,或开启写入工具后调用对应工具。`);
|
|
158
|
+
}
|
|
159
|
+
const moduleCode = args.moduleCode || a.moduleCode;
|
|
160
|
+
if (moduleCode !== a.moduleCode) {
|
|
161
|
+
throw new Error(`moduleCode 应为「${a.moduleCode}」(与 apiCode ${a.apiCode} 绑定),当前传入「${moduleCode}」。模块与 code 不匹配会返回 403。`);
|
|
162
|
+
}
|
|
163
|
+
const params = { ...(args.params || {}) };
|
|
164
|
+
if (args.pageNum !== undefined) params.pageNum = args.pageNum;
|
|
165
|
+
if (args.pageSize !== undefined) params.pageSize = args.pageSize;
|
|
166
|
+
if (params.pageSize && (Number(params.pageSize) < 1 || Number(params.pageSize) > 500)) {
|
|
167
|
+
throw new Error("pageSize 必须在 1~500 之间。");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const warnings = [];
|
|
171
|
+
if (a.apiCode.includes(".detail.")) {
|
|
172
|
+
const needsSale = a.apiCode.startsWith("sale.");
|
|
173
|
+
const idKey = needsSale ? "saleId" : "purchaseId";
|
|
174
|
+
if (params[idKey] === undefined || params[idKey] === null || params[idKey] === "") {
|
|
175
|
+
throw new Error(`明细查询必填 ${idKey}(主单 ID)。请先用 ${needsSale ? "sale.list" : "purchase.in.list / purchase.note.list"} 查询列表,取 data.list[i].id;单号不能当 ID。`);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (params.searches && typeof params.searches === "object" && a.searchKeys.length) {
|
|
179
|
+
const known = new Set(a.searchKeys.map((s) => s.key));
|
|
180
|
+
const unknown = Object.keys(params.searches).filter((k) => !known.has(k));
|
|
181
|
+
if (unknown.length) {
|
|
182
|
+
warnings.push(`searches 中的 key 未在文档中登记:${unknown.join("、")}。报表 key 必须完整照抄 describe_api 返回的 searchKeys,不能简写。`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (params.timeType !== undefined && (params.dateStart !== undefined || params.dateEnd !== undefined)) {
|
|
186
|
+
warnings.push("timeType 快捷日期与 dateStart/dateEnd 自定义区间应二选一,同时传入可能导致筛选不符合预期。");
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const result = await api.query({ moduleCode, apiCode: a.apiCode, params, api: a });
|
|
190
|
+
return { ...result, warnings: [...warnings, ...result.warnings] };
|
|
191
|
+
}),
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
server.registerTool(
|
|
195
|
+
"check_connection",
|
|
196
|
+
{
|
|
197
|
+
description: "自检连接器配置:环境地址、各模块密钥是否齐全、能否成功获取 Token。不返回 Token 明文。排查 401/403 时先用此工具。",
|
|
198
|
+
inputSchema: {
|
|
199
|
+
moduleCode: z.string().optional().describe("只检查某个模块;省略则检查全部已配置模块"),
|
|
200
|
+
},
|
|
201
|
+
},
|
|
202
|
+
(args) =>
|
|
203
|
+
wrap(async () => {
|
|
204
|
+
const modules = args.moduleCode ? [args.moduleCode] : configuredModules(cfg);
|
|
205
|
+
if (!modules.length) {
|
|
206
|
+
return {
|
|
207
|
+
ok: false,
|
|
208
|
+
environment: cfg.envName,
|
|
209
|
+
message: "未配置任何模块密钥。请复制 config.example.json 为 config.json 并填写 credentials,或设置 YSY_CLIENT_CREDENTIALS。",
|
|
210
|
+
notConfigured: missingModules(cfg),
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
const results = [];
|
|
214
|
+
for (const m of modules) {
|
|
215
|
+
if (!tokens.hasCredentials(m)) {
|
|
216
|
+
results.push({ moduleCode: m, ok: false, message: "缺少 clientId / clientSecret" });
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
const before = Date.now();
|
|
221
|
+
await tokens.get(m, { force: true });
|
|
222
|
+
results.push({ moduleCode: m, ok: true, elapsedMs: Date.now() - before, message: "Token 获取成功" });
|
|
223
|
+
} catch (err) {
|
|
224
|
+
results.push({ moduleCode: m, ok: false, message: err.message });
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return {
|
|
228
|
+
ok: results.every((r) => r.ok),
|
|
229
|
+
environment: cfg.envName,
|
|
230
|
+
tokenUrl: cfg.tokenUrl,
|
|
231
|
+
queryUrl: cfg.queryUrl,
|
|
232
|
+
allowWrites: cfg.allowWrites,
|
|
233
|
+
results,
|
|
234
|
+
notConfigured: missingModules(cfg),
|
|
235
|
+
};
|
|
236
|
+
}),
|
|
237
|
+
);
|
|
238
|
+
|
|
239
|
+
if (cfg.allowWrites) {
|
|
240
|
+
server.registerTool(
|
|
241
|
+
"import_file",
|
|
242
|
+
{
|
|
243
|
+
description: "【写入类,需显式开启】调用 /openapi/v1/import 上传 Excel 资料或单据明细。filePath 是 MCP Server 所在机器上的本地绝对路径(stdio 本地模式可用)。超时或 503 时结果不确定,禁止自动重传。",
|
|
244
|
+
inputSchema: {
|
|
245
|
+
apiCode: z.string().describe("导入 code,如 goods.import、sale.order.import"),
|
|
246
|
+
filePath: z.string().describe("本机 .xls/.xlsx 文件绝对路径,最大 50MiB"),
|
|
247
|
+
form: z.record(z.any()).optional().describe("额外表单字段,如 exeType、主单 ID、客户 ID"),
|
|
248
|
+
},
|
|
249
|
+
},
|
|
250
|
+
(args) =>
|
|
251
|
+
wrap(async () => {
|
|
252
|
+
const a = resolveApi(args);
|
|
253
|
+
if (a.entry !== "import") throw new Error(`apiCode「${a.apiCode}」不是 /import 接口。`);
|
|
254
|
+
if (!fs.existsSync(args.filePath)) throw new Error(`文件不存在:${args.filePath}`);
|
|
255
|
+
const stat = fs.statSync(args.filePath);
|
|
256
|
+
if (stat.size > 50 * 1024 * 1024) throw new Error("文件超过 50MiB 上限。");
|
|
257
|
+
const buf = fs.readFileSync(args.filePath);
|
|
258
|
+
return api.importFile({ moduleCode: a.moduleCode, apiCode: a.apiCode, form: args.form, fileBuffer: buf, fileName: path.basename(args.filePath) });
|
|
259
|
+
}),
|
|
260
|
+
);
|
|
261
|
+
|
|
262
|
+
server.registerTool(
|
|
263
|
+
"execute_order",
|
|
264
|
+
{
|
|
265
|
+
description: "【写入类,需显式开启】调用 /openapi/v1/execute 推送商城 JSON 订单。必须检查 successCount / errorCount;超时或 503 时先核对订单,禁止自动重发。",
|
|
266
|
+
inputSchema: {
|
|
267
|
+
apiCode: z.string().describe("mall.order.import 或 mall.order.ztc.import"),
|
|
268
|
+
payload: z.record(z.any()).describe("完整请求外壳,含 moduleCode / apiCode / params.formList"),
|
|
269
|
+
mallOrderSource: z.number().int().optional().describe("可选:统一覆盖 formList[].info.source,商城来源 code,见 describe_api 或 SKILL"),
|
|
270
|
+
},
|
|
271
|
+
},
|
|
272
|
+
(args) =>
|
|
273
|
+
wrap(async () => {
|
|
274
|
+
const a = resolveApi(args);
|
|
275
|
+
if (a.entry !== "execute") throw new Error(`apiCode「${a.apiCode}」不是 /execute 接口。`);
|
|
276
|
+
const payload = JSON.parse(JSON.stringify(args.payload));
|
|
277
|
+
if (args.mallOrderSource !== undefined) {
|
|
278
|
+
for (const item of payload?.params?.formList || []) {
|
|
279
|
+
item.info = { ...(item.info || {}), source: args.mallOrderSource };
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return api.execute({ moduleCode: a.moduleCode, apiCode: a.apiCode, payload });
|
|
283
|
+
}),
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
return server;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async function runStdio() {
|
|
291
|
+
const server = createServer();
|
|
292
|
+
await server.connect(new StdioServerTransport());
|
|
293
|
+
console.error(`[ysy-openapi] stdio 已启动,环境=${cfg.envName},已配置模块=${configuredModules(cfg).join(",") || "无"}`);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
async function runHttp() {
|
|
297
|
+
const httpServer = http.createServer(async (req, res) => {
|
|
298
|
+
const url = new URL(req.url || "/", "http://127.0.0.1");
|
|
299
|
+
if (url.pathname !== "/mcp") {
|
|
300
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
301
|
+
res.end(JSON.stringify({ error: "not found", mcp: "/mcp" }));
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
if (req.method === "GET" || req.method === "DELETE") {
|
|
305
|
+
res.writeHead(405, { Allow: "POST" });
|
|
306
|
+
res.end();
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
let body;
|
|
310
|
+
try {
|
|
311
|
+
const chunks = [];
|
|
312
|
+
for await (const c of req) chunks.push(c);
|
|
313
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
314
|
+
body = raw ? JSON.parse(raw) : undefined;
|
|
315
|
+
} catch (err) {
|
|
316
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
317
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32700, message: err.message }, id: null }));
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
const server = createServer();
|
|
322
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
323
|
+
res.on("close", () => transport.close());
|
|
324
|
+
await server.connect(transport);
|
|
325
|
+
await transport.handleRequest(req, res, body);
|
|
326
|
+
} catch (err) {
|
|
327
|
+
if (!res.headersSent) {
|
|
328
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
329
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: err.message }, id: body?.id ?? null }));
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
});
|
|
333
|
+
httpServer.listen(cfg.httpPort, "127.0.0.1", () => {
|
|
334
|
+
console.log(`[ysy-openapi] streamableHttp 已启动 http://127.0.0.1:${cfg.httpPort}/mcp 环境=${cfg.envName}`);
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
if (cfg.transport === "http") await runHttp();
|
|
339
|
+
else await runStdio();
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { DATA_MAP } from "./config.mjs";
|
|
2
|
+
import { TokenError } from "./errors.mjs";
|
|
3
|
+
|
|
4
|
+
const REFRESH_MARGIN_MS = 60_000;
|
|
5
|
+
|
|
6
|
+
/** 多模块 Token 管理:一个客户端对应一个模块,分别取 Token、分别缓存。 */
|
|
7
|
+
export class TokenManager {
|
|
8
|
+
constructor(cfg) {
|
|
9
|
+
this.cfg = cfg;
|
|
10
|
+
this.cache = new Map();
|
|
11
|
+
this.inflight = new Map();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
hasCredentials(moduleCode) {
|
|
15
|
+
const c = this.cfg.credentials[moduleCode];
|
|
16
|
+
return Boolean(c?.clientId && c?.clientSecret);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** 返回可直接放进 Authorization 头的 Bearer 值。 */
|
|
20
|
+
async get(moduleCode, { force = false } = {}) {
|
|
21
|
+
if (!this.hasCredentials(moduleCode)) {
|
|
22
|
+
const hint = DATA_MAP.commonRules.auth.note;
|
|
23
|
+
throw new TokenError(
|
|
24
|
+
`模块 ${moduleCode} 未配置客户端凭据。请在 config.json 的 credentials.${moduleCode} 填写 clientId / clientSecret,或填写 YSY_CLIENT_CREDENTIALS。规范:${hint}`,
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const cached = this.cache.get(moduleCode);
|
|
29
|
+
if (!force && cached && Date.now() < cached.expiresAt - REFRESH_MARGIN_MS) {
|
|
30
|
+
return cached.value;
|
|
31
|
+
}
|
|
32
|
+
if (this.inflight.has(moduleCode)) return this.inflight.get(moduleCode);
|
|
33
|
+
|
|
34
|
+
const job = this.#fetch(moduleCode)
|
|
35
|
+
.then((entry) => {
|
|
36
|
+
this.cache.set(moduleCode, entry);
|
|
37
|
+
return entry.value;
|
|
38
|
+
})
|
|
39
|
+
.finally(() => this.inflight.delete(moduleCode));
|
|
40
|
+
this.inflight.set(moduleCode, job);
|
|
41
|
+
return job;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async #fetch(moduleCode) {
|
|
45
|
+
const { clientId, clientSecret } = this.cfg.credentials[moduleCode];
|
|
46
|
+
const basic = Buffer.from(`${clientId}:${clientSecret}`, "utf8").toString("base64");
|
|
47
|
+
const controller = new AbortController();
|
|
48
|
+
const timer = setTimeout(() => controller.abort(), 10_000);
|
|
49
|
+
let res;
|
|
50
|
+
try {
|
|
51
|
+
res = await fetch(this.cfg.tokenUrl, {
|
|
52
|
+
method: "POST",
|
|
53
|
+
headers: {
|
|
54
|
+
Authorization: `Basic ${basic}`,
|
|
55
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
56
|
+
Accept: "application/json",
|
|
57
|
+
},
|
|
58
|
+
body: "grant_type=client_credentials",
|
|
59
|
+
signal: controller.signal,
|
|
60
|
+
});
|
|
61
|
+
} catch (err) {
|
|
62
|
+
throw new TokenError(`获取 Token 失败(模块 ${moduleCode}):无法连接认证服务 ${this.cfg.tokenUrl}。${err.message}`);
|
|
63
|
+
} finally {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const text = await res.text();
|
|
68
|
+
let body;
|
|
69
|
+
try {
|
|
70
|
+
body = text ? JSON.parse(text) : {};
|
|
71
|
+
} catch {
|
|
72
|
+
body = {};
|
|
73
|
+
}
|
|
74
|
+
if (!res.ok) {
|
|
75
|
+
const code = body.error || "unknown_error";
|
|
76
|
+
const tips = {
|
|
77
|
+
invalid_client: "Client ID / Secret 错误、客户端不可用或密钥已过期,请联系服务方重置密钥。",
|
|
78
|
+
invalid_request: "表单只允许 grant_type=client_credentials,不要传 client_id / scope。",
|
|
79
|
+
unsupported_grant_type: "grant_type 固定为 client_credentials。",
|
|
80
|
+
temporarily_unavailable: "认证服务暂不可用(503),稍后重试。",
|
|
81
|
+
};
|
|
82
|
+
throw new TokenError(`获取 Token 失败(模块 ${moduleCode},HTTP ${res.status},${code}):${tips[code] || text.slice(0, 200)}`);
|
|
83
|
+
}
|
|
84
|
+
if (!body.access_token) {
|
|
85
|
+
throw new TokenError(`获取 Token 失败(模块 ${moduleCode}):响应缺少 access_token。`);
|
|
86
|
+
}
|
|
87
|
+
const expiresIn = Number(body.expires_in) || 3600;
|
|
88
|
+
return {
|
|
89
|
+
value: body.access_token,
|
|
90
|
+
expiresAt: Date.now() + expiresIn * 1000,
|
|
91
|
+
expiresIn,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
invalidate(moduleCode) {
|
|
96
|
+
this.cache.delete(moduleCode);
|
|
97
|
+
}
|
|
98
|
+
}
|