@jadchene/mcp-gateway-service 0.11.3 → 0.12.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/README.md +71 -76
- package/README_zh.md +71 -76
- package/config.example.json +30 -17
- package/dist/config.js +9 -0
- package/dist/http-server.js +8 -1
- package/dist/index.js +41 -13
- package/dist/mcp/client.js +1 -1
- package/dist/mcp/sdk-client.js +16 -1
- package/dist/service-registry.js +91 -4
- package/dist/version.js +0 -1
- package/dist/web-config/options.js +71 -0
- package/dist/web-config/schema.js +231 -0
- package/dist/web-config/server.js +232 -0
- package/dist/web-ui/assets/favicon-nJb-mWsM.svg +1 -0
- package/dist/web-ui/assets/index-DNU4JgNG.js +9 -0
- package/dist/web-ui/assets/index-DprXY6PS.css +1 -0
- package/dist/web-ui/index.html +14 -0
- package/package.json +74 -67
- package/scripts/verify-web-package.mjs +16 -0
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { readFile, writeFile, rename, unlink, stat } from "node:fs/promises";
|
|
4
|
+
import { resolve, extname } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { isDeepStrictEqual } from "node:util";
|
|
7
|
+
import { resolveWebOptions } from "./options.js";
|
|
8
|
+
import { configSchema, validateFormTypes } from "./schema.js";
|
|
9
|
+
/** 为固定配置文件提供受保护的管理页面。
|
|
10
|
+
* @author chenjd
|
|
11
|
+
* @created 2026-11-17 16:00:00
|
|
12
|
+
*/
|
|
13
|
+
export class ConfigWebServer {
|
|
14
|
+
/** 底层监听器。 */
|
|
15
|
+
server;
|
|
16
|
+
/** 串行保存链。 */
|
|
17
|
+
saving = Promise.resolve();
|
|
18
|
+
/** 配置服务适配器。 */
|
|
19
|
+
adapter;
|
|
20
|
+
/** 构造时仅记录参数,不监听端口。 */
|
|
21
|
+
constructor(adapter) {
|
|
22
|
+
this.adapter = adapter;
|
|
23
|
+
}
|
|
24
|
+
/** 读取文件版本和未做环境替换的配置。 */
|
|
25
|
+
async snapshot() {
|
|
26
|
+
const text = await readFile(this.adapter.configPath, "utf8");
|
|
27
|
+
return {
|
|
28
|
+
config: JSON.parse(text),
|
|
29
|
+
revision: createHash("sha256").update(text).digest("hex"),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
/** 校验草稿并阻止修改启动字段。 */
|
|
33
|
+
validate(config, current) {
|
|
34
|
+
if (!config || typeof config !== "object" || Array.isArray(config))
|
|
35
|
+
throw new Error("配置必须是 JSON 对象");
|
|
36
|
+
if (!isDeepStrictEqual(config.web, current.web))
|
|
37
|
+
throw new Error("web 启动设置只读,请编辑文件后重启");
|
|
38
|
+
validateFormTypes(config, configSchema(this.adapter.project));
|
|
39
|
+
this.adapter.validate(config);
|
|
40
|
+
}
|
|
41
|
+
/** 启动独立端口;禁用时不创建服务器。 */
|
|
42
|
+
async start() {
|
|
43
|
+
const initial = await this.snapshot();
|
|
44
|
+
const { effective, sources } = resolveWebOptions(initial.config.web, this.adapter.args, this.adapter.defaultPort);
|
|
45
|
+
if (!effective.enabled)
|
|
46
|
+
return;
|
|
47
|
+
const scheme = "http";
|
|
48
|
+
const url = `http://127.0.0.1:${effective.port}`;
|
|
49
|
+
const allowedHosts = new Set([
|
|
50
|
+
`127.0.0.1:${effective.port}`,
|
|
51
|
+
`localhost:${effective.port}`,
|
|
52
|
+
]);
|
|
53
|
+
let staticRoot = fileURLToPath(new URL("../web-ui/", import.meta.url));
|
|
54
|
+
try {
|
|
55
|
+
await stat(resolve(staticRoot, "index.html"));
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// 源码开发模式复用已构建页面,避免另外启动前端服务。
|
|
59
|
+
staticRoot = fileURLToPath(new URL("../../dist/web-ui/", import.meta.url));
|
|
60
|
+
await stat(resolve(staticRoot, "index.html"));
|
|
61
|
+
}
|
|
62
|
+
const handler = (request, response) => {
|
|
63
|
+
response.setHeader("Cache-Control", "no-store");
|
|
64
|
+
response.setHeader("X-Content-Type-Options", "nosniff");
|
|
65
|
+
response.setHeader("Referrer-Policy", "no-referrer");
|
|
66
|
+
response.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'");
|
|
67
|
+
const reply = (status, value) => {
|
|
68
|
+
response
|
|
69
|
+
.writeHead(status, {
|
|
70
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
71
|
+
})
|
|
72
|
+
.end(JSON.stringify(value));
|
|
73
|
+
};
|
|
74
|
+
void (async () => {
|
|
75
|
+
if (!allowedHosts.has(request.headers.host ?? ""))
|
|
76
|
+
return reply(403, { error: "Host rejected" });
|
|
77
|
+
const origin = request.headers.origin;
|
|
78
|
+
if (origin &&
|
|
79
|
+
![...allowedHosts].some((value) => origin === `${scheme}://${value}`))
|
|
80
|
+
return reply(403, { error: "Origin rejected" });
|
|
81
|
+
if (request.headers["sec-fetch-site"] === "cross-site")
|
|
82
|
+
return reply(403, { error: "Cross-site request rejected" });
|
|
83
|
+
const pathname = new URL(request.url ?? "/", url).pathname;
|
|
84
|
+
if (!pathname.startsWith("/api/")) {
|
|
85
|
+
if (request.method !== "GET")
|
|
86
|
+
return reply(405, { error: "Method not allowed" });
|
|
87
|
+
if (pathname !== "/" && !/^\/assets\/[a-zA-Z0-9_.-]+$/.test(pathname))
|
|
88
|
+
return reply(404, { error: "Not found" });
|
|
89
|
+
const file = resolve(staticRoot, pathname === "/" ? "index.html" : pathname.slice(1));
|
|
90
|
+
const data = await readFile(file);
|
|
91
|
+
const contentType = {
|
|
92
|
+
".html": "text/html",
|
|
93
|
+
".js": "text/javascript",
|
|
94
|
+
".css": "text/css",
|
|
95
|
+
".svg": "image/svg+xml",
|
|
96
|
+
}[extname(file)] ?? "application/octet-stream";
|
|
97
|
+
response
|
|
98
|
+
.writeHead(200, { "Content-Type": `${contentType}; charset=utf-8` })
|
|
99
|
+
.end(data);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (pathname === "/api/config" && request.method === "GET") {
|
|
103
|
+
const current = await this.snapshot();
|
|
104
|
+
return reply(200, {
|
|
105
|
+
...current,
|
|
106
|
+
project: this.adapter.project,
|
|
107
|
+
configPath: resolve(this.adapter.configPath),
|
|
108
|
+
schema: configSchema(this.adapter.project),
|
|
109
|
+
startup: this.adapter.startup,
|
|
110
|
+
web: {
|
|
111
|
+
effective,
|
|
112
|
+
sources,
|
|
113
|
+
restartRequired: !isDeepStrictEqual(current.config.web, initial.config.web),
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
if (pathname === "/api/services" && request.method === "GET" && this.adapter.services) {
|
|
118
|
+
return reply(200, { services: this.adapter.services.list() });
|
|
119
|
+
}
|
|
120
|
+
if (!["/api/config", "/api/validate", ...(this.adapter.services ? ["/api/services"] : [])].includes(pathname) ||
|
|
121
|
+
request.method !== "POST")
|
|
122
|
+
return reply(404, { error: "Not found" });
|
|
123
|
+
if (!origin ||
|
|
124
|
+
!request.headers["content-type"]?.startsWith("application/json"))
|
|
125
|
+
return reply(403, { error: "JSON and same-origin request required" });
|
|
126
|
+
const body = await readBody(request);
|
|
127
|
+
if (pathname === "/api/services" && this.adapter.services) {
|
|
128
|
+
if (typeof body.serviceId !== "string" || typeof body.action !== "string" || !["start", "stop", "restart"].includes(body.action)) {
|
|
129
|
+
return reply(400, { error: "服务标识或操作无效" });
|
|
130
|
+
}
|
|
131
|
+
await this.adapter.services.control(body.serviceId, body.action);
|
|
132
|
+
return reply(200, { services: this.adapter.services.list() });
|
|
133
|
+
}
|
|
134
|
+
const run = async () => {
|
|
135
|
+
const current = await this.snapshot();
|
|
136
|
+
if (body.revision !== current.revision)
|
|
137
|
+
return reply(409, {
|
|
138
|
+
error: "配置文件已被修改,请保留草稿并重新加载核对",
|
|
139
|
+
});
|
|
140
|
+
this.validate(body.config, current.config);
|
|
141
|
+
if (pathname === "/api/validate")
|
|
142
|
+
return reply(200, { valid: true });
|
|
143
|
+
const temp = `${this.adapter.configPath}.${randomUUID()}.tmp`;
|
|
144
|
+
try {
|
|
145
|
+
const existing = await stat(this.adapter.configPath);
|
|
146
|
+
await writeFile(temp, `${JSON.stringify(body.config, null, 2)}\n`, {
|
|
147
|
+
encoding: "utf8",
|
|
148
|
+
mode: existing.mode & 0o777,
|
|
149
|
+
});
|
|
150
|
+
if ((await this.snapshot()).revision !== current.revision)
|
|
151
|
+
return reply(409, { error: "配置文件已被修改,请重新加载核对" });
|
|
152
|
+
await rename(temp, this.adapter.configPath);
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
await unlink(temp).catch(() => undefined);
|
|
156
|
+
}
|
|
157
|
+
let loaded = true;
|
|
158
|
+
let loadError;
|
|
159
|
+
try {
|
|
160
|
+
await this.adapter.reload();
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
loaded = false;
|
|
164
|
+
loadError = error instanceof Error ? error.message : "加载失败";
|
|
165
|
+
}
|
|
166
|
+
const savedText = `${JSON.stringify(body.config, null, 2)}\n`;
|
|
167
|
+
return reply(200, {
|
|
168
|
+
saved: true,
|
|
169
|
+
loaded,
|
|
170
|
+
loadError,
|
|
171
|
+
config: body.config,
|
|
172
|
+
revision: createHash("sha256").update(savedText).digest("hex"),
|
|
173
|
+
});
|
|
174
|
+
};
|
|
175
|
+
const pending = this.saving.catch(() => undefined).then(run);
|
|
176
|
+
this.saving = pending;
|
|
177
|
+
await pending;
|
|
178
|
+
})().catch((error) => {
|
|
179
|
+
if (!response.headersSent && !response.destroyed)
|
|
180
|
+
reply(400, {
|
|
181
|
+
error: error instanceof Error ? error.message : "配置操作失败",
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
};
|
|
185
|
+
this.server = http.createServer(handler);
|
|
186
|
+
this.server.requestTimeout = 15000;
|
|
187
|
+
await new Promise((accept, reject) => {
|
|
188
|
+
this.server.once("error", reject);
|
|
189
|
+
this.server.listen(effective.port, "127.0.0.1", () => {
|
|
190
|
+
this.server.off("error", reject);
|
|
191
|
+
accept();
|
|
192
|
+
});
|
|
193
|
+
});
|
|
194
|
+
process.stderr.write(`Configuration Web: ${url} (local only)\n`);
|
|
195
|
+
}
|
|
196
|
+
/** Web 是可选入口,启动失败时释放资源并让 MCP 继续运行。 */
|
|
197
|
+
async startOptional() {
|
|
198
|
+
try {
|
|
199
|
+
await this.start();
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
await this.close();
|
|
203
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
204
|
+
process.stderr.write(`[warn] Configuration Web failed to start; MCP continues: ${message}\n`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/** 停止入口并等待已开始的保存完成。 */
|
|
208
|
+
async close() {
|
|
209
|
+
const server = this.server;
|
|
210
|
+
this.server = undefined;
|
|
211
|
+
if (!server)
|
|
212
|
+
return;
|
|
213
|
+
server.closeAllConnections();
|
|
214
|
+
await new Promise((accept) => server.close(() => accept()));
|
|
215
|
+
await this.saving.catch(() => undefined);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/** 有界读取请求,避免配置接口无限缓冲。 */
|
|
219
|
+
const readBody = async (request) => {
|
|
220
|
+
const chunks = [];
|
|
221
|
+
let size = 0;
|
|
222
|
+
for await (const chunk of request) {
|
|
223
|
+
size += chunk.length;
|
|
224
|
+
if (size > 2 * 1024 * 1024)
|
|
225
|
+
throw new Error("配置请求不能超过 2 MiB");
|
|
226
|
+
chunks.push(Buffer.from(chunk));
|
|
227
|
+
}
|
|
228
|
+
const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
229
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
230
|
+
throw new Error("请求必须是 JSON 对象");
|
|
231
|
+
return value;
|
|
232
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect width="40" height="40" rx="11" fill="#637bef"/><text x="20" y="29" text-anchor="middle" font-family="Georgia,serif" font-size="35" font-weight="bold" fill="white">m</text></svg>
|