@teamdream/sems-mcp 0.0.0-stage → 1.1.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,6 @@
1
+ Copyright (c) 2026 TeamDream. All rights reserved.
2
+
3
+ This package is published for use together with an authorized Haijun SEMS
4
+ (海竣信息系统) deployment. No permission is granted to copy, modify,
5
+ distribute, sublicense, or sell this software outside the terms agreed with
6
+ TeamDream.
package/README.md CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # @teamdream/sems-mcp
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
+ 海竣信息系统(SEMS)的 MCP 连接器。以 **stdio** 方式运行在用户电脑上,把销售单、采购单、报价、合同、库存、
4
+ 客户供应商、工作日志与经营统计等能力暴露成 28 个 `sems_*` 工具,供支持 MCP 的客户端(如 WorkBuddy)调用。
5
+
6
+ - **不直连 SEMS**:所有请求经 `sems-proxy` 转发,出站前用 HMAC-SHA256 签名。
7
+ - **不持有账号密码**:绑定只下发一对 `key_id` + `secret`,密码只提交给 SEMS 登录接口。
8
+ - **写操作两阶段**:起草(不写库)→ 用户确认 → 凭 `draftId + digest` 提交,摘要不一致会被拒绝。
9
+
10
+ ## 环境要求
11
+
12
+ | 项 | 要求 |
13
+ |---|---|
14
+ | Node.js | >= 22.18 |
15
+ | 网络 | 能访问 sems-proxy(建议 HTTPS) |
16
+ | 系统 | Windows / macOS / Linux |
17
+
18
+ ## 安装与配置
19
+
20
+ 通常不需要手动安装:在 WorkBuddy 连接器市场添加「海竣信息系统助手」,客户端会用 `npx` 自动拉起本包。
21
+
22
+ 手工配置 MCP 客户端时,在 `mcp.json` 中加:
23
+
24
+ ```json
25
+ {
26
+ "mcpServers": {
27
+ "sems": {
28
+ "type": "stdio",
29
+ "command": "npx",
30
+ "args": ["-y", "@teamdream/sems-mcp@1.0.1"],
31
+ "env": {
32
+ "WB_PROXY_BASE_URL": "https://<你的 sems-proxy 地址>",
33
+ "WB_BIND_TOKEN": "<绑定码>"
34
+ }
35
+ }
36
+ }
37
+ }
38
+ ```
39
+
40
+ 也可以全局安装后直接用命令启动:
41
+
42
+ ```bash
43
+ npm install -g @teamdream/sems-mcp
44
+ sems-mcp
45
+ ```
46
+
47
+ ## 绑定流程
48
+
49
+ 1. 浏览器打开 `<WB_PROXY_BASE_URL>/bind`,用 SEMS 账号登录并勾选要绑定的公司;
50
+ 2. 页面给出一次性绑定码,填进 MCP 客户端的表单(或 `WB_BIND_TOKEN`);
51
+ 3. 下次启动时自动用绑定码换密钥,写入 `~/.sems-mcp/binding.json`(权限 0600),之后不再需要绑定码。
52
+
53
+ 命令行绑定(等价流程,适合排障):
54
+
55
+ ```bash
56
+ sems-mcp-bind --proxy https://<你的 sems-proxy 地址>
57
+ ```
58
+
59
+ 一家公司绑定后可以在会话里用 `sems_switch_tenant` 切换,不需要重新绑定。
60
+
61
+ ## 环境变量
62
+
63
+ | 变量 | 必填 | 说明 |
64
+ |---|---|---|
65
+ | `WB_PROXY_BASE_URL` | 二选一 | sems-proxy 地址,如 `https://ai-agent.example.com` |
66
+ | `WB_BIND_TOKEN` | 否 | 连接器表单带回的绑定码;有值就尝试兑换密钥 |
67
+ | `WB_KEY_ID` / `WB_SECRET` | 否 | 手工指定密钥,优先级高于绑定文件 |
68
+ | `WB_TENANT_ID` | 否 | 指定公司;留空用绑定时选中的默认公司 |
69
+ | `WB_BINDING_FILE` | 否 | 覆盖密钥文件路径,默认 `~/.sems-mcp/binding.json` |
70
+ | `WB_TIMEOUT_MS` | 否 | 单次请求超时,默认 `30000` |
71
+ | `WB_LOG_LEVEL` | 否 | `debug` / `info` / `warn` / `error`,默认 `info`,日志只写 stderr |
72
+
73
+ ## 安全说明
74
+
75
+ - 日志走 stderr 并脱敏,stdout 只输出 JSON-RPC 帧;
76
+ - 密钥只落 `~/.sems-mcp/binding.json`;Windows 无法把文件权限收到 0600,请确认该目录不被他人读取;
77
+ - 权限预检是 fail-closed:结构异常时按「无权限」处理;
78
+ - 成本、利润、采购价等字段由服务端按账号权限删除,无权限时字段不存在而不是空值。
79
+
80
+ ## 可用工具
81
+
82
+ 工具清单真源在服务端的 `configs/tools.yaml`。不确定能力边界时先调 `sems_capabilities`。
83
+
84
+ 不提供删单、改单、审批、导出 Excel/PDF、发消息、跨公司汇总。
85
+
86
+ ## 开发
87
+
88
+ ```bash
89
+ npm ci
90
+ npm run build # 产出 dist(含 shebang)
91
+ npm run typecheck
92
+ npm test
93
+ npm run dev # 需要 .env,参考 .env.example
94
+ ```
95
+
96
+ 发布:`npm publish --registry=https://registry.npmjs.org`。`prepublishOnly` 会先跑 typecheck 与测试,
97
+ `prepack` 会重新构建 `dist`,包内只包含 `dist/**/*.js`、README 与 LICENSE。
package/dist/bind.js ADDED
@@ -0,0 +1,212 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 绑定命令行:`sems-mcp-bind`
4
+ *
5
+ * 职责只有一件 —— 把浏览器里完成的绑定结果落到本机:
6
+ *
7
+ * POST /bind/start → 打印一个绑定码与网址
8
+ * 用户在浏览器提交账号密码并选公司
9
+ * POST /bind/poll → 拿回 key_id + secret → 写 ~/.sems-mcp/binding.json
10
+ *
11
+ * 🔴 本进程**从不接触 SEMS 密码**。这是整个绑定设计的目的:
12
+ * 密码只提交给 SEMS 的登录接口,MCP 这一侧只拿到一把 HMAC 密钥。
13
+ *
14
+ * 与 `main.ts` 分开的原因:main 是 stdio 服务端,stdout 只能出 JSON-RPC 帧;
15
+ * 绑定是给人看的交互式命令,两者共用入口会让「多打一行提示」直接弄坏协议。
16
+ */
17
+ import { createHash } from "node:crypto";
18
+ import { mkdirSync, writeFileSync } from "node:fs";
19
+ import { dirname } from "node:path";
20
+ import { defaultBindingPath } from "./config.js";
21
+ class BindError extends Error {
22
+ }
23
+ function parseArgs(argv) {
24
+ let proxy = process.env["WB_PROXY_BASE_URL"] ?? "http://127.0.0.1:5802";
25
+ let out = defaultBindingPath();
26
+ for (let i = 0; i < argv.length; i += 1) {
27
+ const arg = argv[i];
28
+ if ((arg === "--proxy" || arg === "-p") && argv[i + 1]) {
29
+ proxy = argv[i + 1];
30
+ i += 1;
31
+ }
32
+ else if ((arg === "--out" || arg === "-o") && argv[i + 1]) {
33
+ out = argv[i + 1];
34
+ i += 1;
35
+ }
36
+ else if (arg === "--help" || arg === "-h") {
37
+ process.stdout.write(help());
38
+ process.exit(0);
39
+ }
40
+ else {
41
+ throw new BindError(`无法识别的参数:${arg}\n\n${help()}`);
42
+ }
43
+ }
44
+ return { proxy: proxy.replace(/\/+$/, ""), out };
45
+ }
46
+ function help() {
47
+ return [
48
+ "用法:sems-mcp-bind [--proxy <proxy 地址>] [--out <binding.json 路径>]",
49
+ "",
50
+ " --proxy, -p sems-proxy 地址,默认 http://127.0.0.1:5802",
51
+ " 也可用环境变量 WB_PROXY_BASE_URL",
52
+ " --out, -o 密钥文件路径,默认 ~/.sems-mcp/binding.json",
53
+ "",
54
+ "绑定过程中密码只在浏览器里输入,本命令不会询问、也不会保存你的海竣信息系统密码。",
55
+ "",
56
+ ].join("\n");
57
+ }
58
+ async function postJson(url, body, timeoutMs = 30_000) {
59
+ let response;
60
+ try {
61
+ response = await fetch(url, {
62
+ method: "POST",
63
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
64
+ body: JSON.stringify(body),
65
+ signal: AbortSignal.timeout(timeoutMs),
66
+ });
67
+ }
68
+ catch (err) {
69
+ throw new BindError(`连不上 sems-proxy(${url}):${err instanceof Error ? err.message : String(err)}\n`
70
+ + "请确认 proxy 已启动、地址与端口正确。");
71
+ }
72
+ const text = await response.text();
73
+ let payload;
74
+ try {
75
+ payload = text ? JSON.parse(text) : {};
76
+ }
77
+ catch {
78
+ throw new BindError(`proxy 返回了非 JSON 内容(HTTP ${response.status}):${text.slice(0, 200)}`);
79
+ }
80
+ if (!response.ok) {
81
+ const message = payload.message ?? payload.msg ?? text;
82
+ throw new BindError(`请求失败(HTTP ${response.status}):${String(message)}`);
83
+ }
84
+ return payload;
85
+ }
86
+ /** 写密钥文件。内容等同于凭据,所以只写这一份、权限收到最小。 */
87
+ function writeBinding(path, payload) {
88
+ mkdirSync(dirname(path), { recursive: true });
89
+ writeFileSync(path, `${JSON.stringify(payload, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
90
+ }
91
+ function fingerprint(secret) {
92
+ return createHash("sha256").update(secret, "utf8").digest("hex").slice(0, 16);
93
+ }
94
+ /**
95
+ * 解析 `/bind/poll` 返回的公司列表。
96
+ *
97
+ * 字段可能缺失(老版本 proxy 只回单个 `sems_tenant_id`),此时退化成
98
+ * 「一家公司、就是默认那家」,不当作错误 —— 绑定的主要目的是拿到密钥。
99
+ */
100
+ function companies(result) {
101
+ const list = result.identities;
102
+ if (Array.isArray(list) && list.length > 0) {
103
+ return list.flatMap((item) => {
104
+ if (typeof item !== "object" || item === null)
105
+ return [];
106
+ const record = item;
107
+ const tenantId = record["tenantId"] ?? record["sems_tenant_id"];
108
+ if (tenantId === undefined || tenantId === null)
109
+ return [];
110
+ return [
111
+ {
112
+ tenantId: String(tenantId),
113
+ name: String(record["name"] ?? tenantId),
114
+ isDefault: record["isDefault"] === true,
115
+ },
116
+ ];
117
+ });
118
+ }
119
+ if (result.sems_tenant_id !== undefined && result.sems_tenant_id !== null) {
120
+ return [
121
+ {
122
+ tenantId: String(result.sems_tenant_id),
123
+ name: String(result.sems_username ?? result.sems_tenant_id),
124
+ isDefault: true,
125
+ },
126
+ ];
127
+ }
128
+ return [];
129
+ }
130
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
131
+ async function main() {
132
+ const args = parseArgs(process.argv.slice(2));
133
+ process.stdout.write(`\n正在向 ${args.proxy} 申请绑定码…\n`);
134
+ const ticket = await postJson(`${args.proxy}/bind/start`, {});
135
+ const minutes = Math.round(ticket.expires_in / 60);
136
+ process.stdout.write([
137
+ "",
138
+ "──────────────────────────────────────────────",
139
+ ` 绑定码:${ticket.code}`,
140
+ "",
141
+ ` 请在浏览器打开:${ticket.bind_url}`,
142
+ "",
143
+ ` 输入你的海竣信息系统账号密码,选择要绑定的公司。`,
144
+ ` 密码只提交给海竣信息系统,本命令不会看到它。`,
145
+ "──────────────────────────────────────────────",
146
+ "",
147
+ `等待完成…(${minutes} 分钟内有效,按 Ctrl+C 取消)`,
148
+ "",
149
+ ].join("\n"));
150
+ const deadline = Date.now() + ticket.expires_in * 1000;
151
+ let interval = Math.max(1, ticket.interval) * 1000;
152
+ while (Date.now() < deadline) {
153
+ await sleep(interval);
154
+ const result = await postJson(`${args.proxy}/bind/poll`, {
155
+ poll_token: ticket.poll_token,
156
+ });
157
+ if (result.status === "PENDING")
158
+ continue;
159
+ if (result.status === "EXPIRED") {
160
+ throw new BindError(`绑定码已过期(${result.message ?? "超过有效时间"})。请重新运行本命令生成新的绑定码。`);
161
+ }
162
+ if (!result.key_id || !result.secret || !result.proxy_base_url) {
163
+ throw new BindError("proxy 返回的绑定结果不完整(缺少 key_id / secret / proxy_base_url)");
164
+ }
165
+ const bound = companies(result);
166
+ writeBinding(args.out, {
167
+ proxy_base_url: result.proxy_base_url,
168
+ key_id: result.key_id,
169
+ secret: result.secret,
170
+ // 留空 = 用绑定时选中的默认公司。刻意不写死默认公司的 id:
171
+ // 将来重新绑定换了默认公司,写死的旧 id 会指向一家已被作废的公司。
172
+ active_tenant: "",
173
+ identities: bound,
174
+ sems_username: result.sems_username,
175
+ sems_tenant_id: result.sems_tenant_id,
176
+ });
177
+ const defaultCompany = bound.find((item) => item.isDefault) ?? bound[0];
178
+ const companyLines = bound.length > 1
179
+ ? bound.map((item) => ` · ${item.name}${item.isDefault ? "(默认)" : ""}(公司 ${item.tenantId})`)
180
+ : [];
181
+ process.stdout.write([
182
+ "",
183
+ "✓ 绑定完成",
184
+ "",
185
+ ` 账号:${result.sems_username ?? "?"}`,
186
+ ...(bound.length > 1
187
+ ? [` 已绑定 ${bound.length} 家公司:`, ...companyLines]
188
+ : [` 公司:${defaultCompany ? `${defaultCompany.name}(${defaultCompany.tenantId})` : "?"}`]),
189
+ ` 密钥标识:${result.key_id}`,
190
+ ` 密钥指纹:${fingerprint(result.secret)}…`,
191
+ ` 已写入:${args.out}`,
192
+ "",
193
+ ...(bound.length > 1
194
+ ? ["在 WorkBuddy 里说「切到 XX 公司」即可换公司,不需要重新绑定。", ""]
195
+ : []),
196
+ "接下来回到 WorkBuddy 新开一个会话,工具即可使用。",
197
+ process.platform === "win32"
198
+ ? "⚠️ Windows 无法像 Linux 那样把文件权限收到 0600,请确认该目录不被他人读取。"
199
+ : "",
200
+ "",
201
+ ]
202
+ .filter((line) => line !== "")
203
+ .join("\n"));
204
+ return;
205
+ }
206
+ throw new BindError("等待超时,未完成绑定。请重新运行本命令。");
207
+ }
208
+ main().catch((err) => {
209
+ const message = err instanceof BindError ? err.message : err instanceof Error ? err.message : String(err);
210
+ process.stderr.write(`\n✗ ${message}\n\n`);
211
+ process.exit(1);
212
+ });
@@ -0,0 +1,111 @@
1
+ /**
2
+ * 错误归一化。
3
+ *
4
+ * 一个响应可能来自三个地方,形状各不相同,必须能分清:
5
+ *
6
+ * | 来源 | 形状 | 判据 |
7
+ * |---|---|---|
8
+ * | sems-proxy 拦下(验签/白名单/写开关/令牌) | `{code: <http>, error: "CODE", message, detail?}` | 有 `error` 字段 |
9
+ * | SEMS 业务失败 | `{code: 1, msg: "..."}`(成功是 `code: 0`) | 无 `error`,code 为数字 |
10
+ * | 网络/超时/畸形响应 | 无响应体 | fetch 抛错 |
11
+ *
12
+ * 🔴 不能用 `code` 区分前两者:proxy 的 `code` 是 HTTP 状态码(数字),SEMS 的 `code`
13
+ * 是业务码(也数字)。只有 `error` 字段是 proxy 独有。
14
+ *
15
+ * 错误文案不在这里写:唯一来源是 `contracts/error-codes.yaml`,经生成器固化进
16
+ * `generated/manifest.ts`。两端各写一套中文必然漂移。
17
+ */
18
+ import { ERROR_MAP } from "../generated/manifest.js";
19
+ export class ProxyError extends Error {
20
+ code;
21
+ http;
22
+ retry;
23
+ detail;
24
+ hint;
25
+ constructor(code, http, message, retry, detail,
26
+ /** 给用户的「下一步该做什么」,只在能给出确定动作时填写。 */
27
+ hint) {
28
+ super(message);
29
+ this.code = code;
30
+ this.http = http;
31
+ this.retry = retry;
32
+ this.detail = detail;
33
+ this.hint = hint;
34
+ this.name = "ProxyError";
35
+ }
36
+ }
37
+ const HINTS = {
38
+ REBIND_REQUIRED: "绑定已失效(常见原因:海竣信息系统密码被修改、海竣信息系统的 Redis 被清空、绑定满 90 天)。请重新绑定后重试。",
39
+ KEY_UNKNOWN: "本机保存的密钥在服务端不存在(可能服务端数据库被重建)。请重新绑定。",
40
+ KEY_REVOKED: "该密钥已被管理员吊销。请重新绑定。",
41
+ HMAC_TS_SKEW: "本机时间与服务器相差超过 60 秒,签名会被判定过期。请校准系统时间(开启自动同步)后重试。",
42
+ HMAC_MISSING: "本机没有正确附加签名头,通常意味着 sems-mcp 版本过旧或配置被改写。",
43
+ HMAC_INVALID: "密钥与服务器记录不一致(常见原因:重新绑定后仍在使用旧密钥)。请确认使用最新的绑定信息。",
44
+ NOT_IN_ALLOWLIST: "该能力尚未对 WorkBuddy 开放。白名单在构建期打进 sems-proxy 镜像,"
45
+ + "登记到 configs/whitelist.yaml 后必须重建 sems-proxy 才生效(只重启容器无效)。",
46
+ WRITE_DISABLED: "写操作当前是关闭的(ALLOW_WRITE=false),只能查询。",
47
+ CONTRACT_MISMATCH: "本机的 sems-mcp 与服务器端的 sems-proxy 版本不匹配,请升级后重试。",
48
+ RATE_LIMITED: "调用过于频繁,请稍等几秒再试。",
49
+ UPSTREAM_TIMEOUT: "海竣信息系统响应超时,服务可能正忙。稍后重试通常可恢复。",
50
+ };
51
+ function hintFor(code) {
52
+ return HINTS[code];
53
+ }
54
+ function isRecord(value) {
55
+ return typeof value === "object" && value !== null && !Array.isArray(value);
56
+ }
57
+ /** 解析 proxy 自己产生的错误;`error` 字段不存在时返回 null,交给上游分支。 */
58
+ function parseProxyError(status, body) {
59
+ if (!isRecord(body))
60
+ return null;
61
+ const raw = body.error;
62
+ if (typeof raw !== "string" || raw.length === 0)
63
+ return null;
64
+ const known = ERROR_MAP[raw];
65
+ const message = typeof body.message === "string" && body.message
66
+ ? String(body.message)
67
+ : (known?.message ?? `请求失败(${raw})`);
68
+ const detailRaw = body.detail;
69
+ const detail = typeof detailRaw === "string" && detailRaw ? detailRaw : undefined;
70
+ return new ProxyError(raw, status, message, known?.retry ?? false, detail, hintFor(raw));
71
+ }
72
+ /** 把任意一次失败响应归一成 ProxyError。 */
73
+ export function errorFromResponse(status, text) {
74
+ let body = null;
75
+ try {
76
+ body = text ? JSON.parse(text) : null;
77
+ }
78
+ catch {
79
+ body = null;
80
+ }
81
+ const proxyError = parseProxyError(status, body);
82
+ if (proxyError)
83
+ return proxyError;
84
+ // 走到这里说明响应来自 SEMS 本身。它的 `msg` 是后端抛出的中文提示,可以直接给用户;
85
+ // 但如果是网关/nginx 的 HTML 错误页,就没有可读文案,只能按状态码兜底。
86
+ if (isRecord(body)) {
87
+ const msg = body.msg;
88
+ if (typeof msg === "string" && msg.trim()) {
89
+ return new ProxyError("UPSTREAM_ERROR", status, msg.trim(), false);
90
+ }
91
+ }
92
+ if (status === 401) {
93
+ return new ProxyError("REBIND_REQUIRED", status, "海竣信息系统拒绝了当前令牌", false, undefined, hintFor("REBIND_REQUIRED"));
94
+ }
95
+ return new ProxyError("UPSTREAM_ERROR", status, `海竣信息系统返回了无法识别的响应(HTTP ${status})`, status >= 500, text ? text.slice(0, 200) : undefined);
96
+ }
97
+ /** 网络层失败(连接被拒、超时、DNS)。 */
98
+ export function errorFromNetwork(err, timeoutMs) {
99
+ const name = err?.name;
100
+ if (name === "AbortError" || name === "TimeoutError") {
101
+ return new ProxyError("UPSTREAM_TIMEOUT", 504, `请求超时(${timeoutMs}ms)`, true, undefined, hintFor("UPSTREAM_TIMEOUT"));
102
+ }
103
+ const cause = err?.cause?.code;
104
+ const detail = cause ?? err?.message ?? String(err);
105
+ return new ProxyError("UPSTREAM_ERROR", 502, "无法连接 sems-proxy", true, detail, "请检查网络、proxy 地址是否正确,以及 sems-proxy 容器是否在运行。");
106
+ }
107
+ /** 供工具层直接抛出「本地就能判定」的错误(例如缺少权限、参数非法)。 */
108
+ export function localError(code, detail) {
109
+ const known = ERROR_MAP[code];
110
+ return new ProxyError(code, known?.http ?? 400, known?.message ?? "请求不合法", known?.retry ?? false, detail, hintFor(code));
111
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * sems-proxy 调用客户端:HMAC-SHA256 签名 + 转发。
3
+ *
4
+ * 🔴 签名原文必须与 `server/proxy/app/hmac_auth.py` 逐字节一致:
5
+ *
6
+ * HMAC_SHA256(secret, method + "\n" + path + "\n" + ts + "\n" + nonce + "\n" + sha256(body))
7
+ *
8
+ * 三个容易错的地方,每一条都只会表现为「签名校验失败」,没有任何线索指向真正原因:
9
+ *
10
+ * 1. **`path` 不含 query**。proxy 用 `request.scope["path"]` 参与验签,query 单独走
11
+ * `query_params`。把 `?a=1` 拼进签名原文必然失败。
12
+ * 2. **摘要对象是「实际发送的字节」**。所以本文件先把 body 序列化成 Buffer,
13
+ * 对同一份 Buffer 既算摘要又发送;绝不能先算摘要再让 fetch 自己再序列化一遍。
14
+ * 3. **path 不能带 `%`**。proxy 的 `normalize_path` 会拒绝含 `%` 的路径(防二次编码),
15
+ * 因此路径段禁止 URL 编码;只有 query 的键值才编码。
16
+ */
17
+ import { createHash, createHmac, randomBytes } from "node:crypto";
18
+ import { errorFromNetwork, errorFromResponse, ProxyError } from "./errors.js";
19
+ /**
20
+ * 上传请求的 body 摘要占位符。
21
+ *
22
+ * multipart 的每个 part 之间插的是随机 boundary,同一份文件两次构造出的字节不同,
23
+ * 因此无法用「实际字节的哈希」参与签名——那样客户端算完摘要再交给 fetch,
24
+ * boundary 会被重新生成,签名必然对不上。两端约定用这个字面量代替。
25
+ * 与 `server/proxy/app/paths.py` 的 `MULTIPART_BODY_HASH` 必须一致。
26
+ */
27
+ export const MULTIPART_BODY_HASH = "multipart";
28
+ const EMPTY_BODY_HASH = createHash("sha256").update(Buffer.alloc(0)).digest("hex");
29
+ /**
30
+ * 签名原文(与 `server/proxy/app/hmac_auth.py` 逐字节一致):
31
+ *
32
+ * HMAC_SHA256(secret, method + "\n" + path + "\n" + ts + "\n" + nonce + "\n" + sha256(body)
33
+ * [+ "\n" + tenant])
34
+ *
35
+ * 最后一段只在「选定了一家具体公司」时才拼上。这一点不是可选项:
36
+ * 同一把密钥能进多家公司,proxy 只能靠签名区分请求该落到哪家,
37
+ * 租户头若不在签名里,改一个头就能跨公司取数据。
38
+ */
39
+ export function sign(secret, method, path, ts, nonce, bodyHash, tenant = "") {
40
+ const parts = [method.toUpperCase(), path, ts, nonce, bodyHash];
41
+ if (tenant)
42
+ parts.push(tenant);
43
+ const message = parts.join("\n");
44
+ return createHmac("sha256", secret).update(message, "utf8").digest("hex");
45
+ }
46
+ /** 与 Python 端 `body_digest()` 等价:对字节做 SHA-256。 */
47
+ export function bodyDigest(body) {
48
+ if (!body || body.length === 0)
49
+ return EMPTY_BODY_HASH;
50
+ return createHash("sha256").update(body).digest("hex");
51
+ }
52
+ function buildQuery(query) {
53
+ if (!query)
54
+ return "";
55
+ const params = new URLSearchParams();
56
+ for (const [key, value] of Object.entries(query)) {
57
+ if (value === undefined)
58
+ continue;
59
+ if (Array.isArray(value)) {
60
+ // SEMS 的多值查询用逗号拼接(如 ascs=a,b),不是重复键。
61
+ if (value.length > 0)
62
+ params.append(key, value.join(","));
63
+ continue;
64
+ }
65
+ params.append(key, String(value));
66
+ }
67
+ const text = params.toString();
68
+ return text ? `?${text}` : "";
69
+ }
70
+ function serializeBody(body, method) {
71
+ if (body === undefined || body === null) {
72
+ if (method === "GET" || method === "DELETE")
73
+ return null;
74
+ return Buffer.from("{}", "utf8");
75
+ }
76
+ if (typeof body === "string")
77
+ return Buffer.from(body, "utf8");
78
+ // 用 UTF-8 而非转义中文:SEMS 后端按 UTF-8 解析,转义虽然也能解析,
79
+ // 但会让日志和审计里的中文变成 \uXXXX,排障时看不清。
80
+ return Buffer.from(JSON.stringify(body), "utf8");
81
+ }
82
+ export class ProxyClient {
83
+ config;
84
+ constructor(config) {
85
+ this.config = config;
86
+ }
87
+ signedHeaders(method, path, bodyHash) {
88
+ const ts = String(Math.floor(Date.now() / 1000));
89
+ const nonce = randomBytes(16).toString("base64url");
90
+ // 每次请求都读一次:sems_switch_tenant 会就地改它,不能在这里缓存成常量
91
+ const tenant = this.config.activeTenant;
92
+ const signature = sign(this.config.secret, method, path, ts, nonce, bodyHash, tenant);
93
+ return {
94
+ "X-Sems-Key": this.config.keyId,
95
+ "X-Sems-Ts": ts,
96
+ "X-Sems-Nonce": nonce,
97
+ "X-Sems-Sign": signature,
98
+ ...(tenant ? { "X-Sems-Tenant": tenant } : {}),
99
+ };
100
+ }
101
+ /** 发一次请求并归一化失败。每次调用都重新取时间戳与 nonce(nonce 不可复用)。 */
102
+ async send(call) {
103
+ const url = `${this.config.proxyBaseUrl}${call.path}${buildQuery(call.query)}`;
104
+ let body;
105
+ let bodyHash;
106
+ let contentType;
107
+ if (call.raw) {
108
+ body = call.raw.bytes;
109
+ bodyHash = call.raw.bodyHash;
110
+ contentType = call.raw.contentType;
111
+ }
112
+ else {
113
+ body = serializeBody(call.body, call.method);
114
+ bodyHash = bodyDigest(body);
115
+ contentType = body ? "application/json" : null;
116
+ }
117
+ const headers = {
118
+ ...this.signedHeaders(call.method, call.path, bodyHash),
119
+ Accept: "application/json",
120
+ };
121
+ if (contentType)
122
+ headers["Content-Type"] = contentType;
123
+ let response;
124
+ try {
125
+ response = await fetch(url, {
126
+ method: call.method,
127
+ headers,
128
+ ...(body ? { body: new Uint8Array(body) } : {}),
129
+ signal: AbortSignal.timeout(call.timeoutMs ?? this.config.timeoutMs),
130
+ });
131
+ }
132
+ catch (err) {
133
+ throw errorFromNetwork(err, call.timeoutMs ?? this.config.timeoutMs);
134
+ }
135
+ const text = await response.text();
136
+ if (!response.ok)
137
+ throw errorFromResponse(response.status, text);
138
+ if (!text)
139
+ return { status: response.status, data: null };
140
+ try {
141
+ return { status: response.status, data: JSON.parse(text) };
142
+ }
143
+ catch {
144
+ throw new ProxyError("UPSTREAM_ERROR", response.status, "海竣信息系统返回了非 JSON 内容", false, text.slice(0, 200));
145
+ }
146
+ }
147
+ /** 失败统一抛 `ProxyError`,调用方不需要判 HTTP 状态码。 */
148
+ async call(call) {
149
+ try {
150
+ return await this.send(call);
151
+ }
152
+ catch (err) {
153
+ // 时间戳越界是本机时钟漂移导致的,重新取一次当前时间通常就能过;
154
+ // 契约里 HMAC_TS_SKEW 的 retry=true 就是这个意思,所以在这里就地重试一次。
155
+ if (err instanceof ProxyError && err.code === "HMAC_TS_SKEW") {
156
+ return this.send(call);
157
+ }
158
+ throw err;
159
+ }
160
+ }
161
+ }
162
+ /** `/health` 是 proxy 的显式路由,不需要签名,也不会被 catch-all 拦下。 */
163
+ export async function fetchHealth(config) {
164
+ const response = await fetch(`${config.proxyBaseUrl}/health`, {
165
+ headers: { Accept: "application/json" },
166
+ signal: AbortSignal.timeout(Math.min(config.timeoutMs, 10_000)),
167
+ });
168
+ const text = await response.text();
169
+ if (!response.ok)
170
+ throw errorFromResponse(response.status, text);
171
+ const doc = JSON.parse(text);
172
+ const profile = doc["profile"];
173
+ const upstream = doc["upstream"];
174
+ const allowWrite = doc["allow_write"];
175
+ return {
176
+ version: String(doc["version"] ?? "?"),
177
+ contractVersion: Number(doc["contract_version"] ?? 0),
178
+ ...(typeof profile === "string" ? { profile } : {}),
179
+ ...(typeof upstream === "string" ? { upstream } : {}),
180
+ ...(typeof allowWrite === "boolean" ? { allowWrite } : {}),
181
+ };
182
+ }