@jadchene/mcp-gateway-service 0.11.2 → 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.
@@ -0,0 +1,231 @@
1
+ const string = (label, required = false) => ({
2
+ type: "string",
3
+ label,
4
+ required,
5
+ });
6
+ const bool = (label, value = false) => ({
7
+ type: "boolean",
8
+ label,
9
+ default: value,
10
+ });
11
+ const number = (label, min, max, value) => ({ type: "number", label, min, max, default: value });
12
+ const object = (label, properties, required = false) => ({ type: "object", label, properties, required });
13
+ const array = (label, item, required = false) => ({
14
+ type: "array",
15
+ label,
16
+ item,
17
+ required,
18
+ });
19
+ const map = (label, item) => ({
20
+ type: "map",
21
+ label,
22
+ item,
23
+ });
24
+ const enumeration = (label, options) => ({
25
+ type: "string",
26
+ label,
27
+ options,
28
+ required: true,
29
+ });
30
+ const password = (label, required = false) => ({
31
+ ...string(label, required),
32
+ secret: true,
33
+ });
34
+ const strings = (label) => array(label, string("值"));
35
+ const port = (value) => number("端口", 1, 65535, value);
36
+ const timeout = (label = "连接超时(毫秒)") => number(label, 1, 2147483647);
37
+ const sessionFields = {
38
+ sessionIdleTimeoutMs: number("会话空闲超时(毫秒)", 100, 86400000, 1800000),
39
+ maxSessions: number("会话上限", 1, 1024, 32),
40
+ };
41
+ const access = {
42
+ enable: bool("启用", true),
43
+ codexAutoReview: bool("Codex 自动审批"),
44
+ dangerMode: bool("Full Access"),
45
+ };
46
+ const identity = {
47
+ host: string("主机", true),
48
+ port: port(22),
49
+ username: string("用户名", true),
50
+ password: password("密码"),
51
+ privateKeyPath: string("私钥文件路径"),
52
+ privateKey: { ...password("私钥内容"), multiline: true },
53
+ passphrase: password("私钥口令"),
54
+ strictHostKeyChecking: bool("校验主机密钥", true),
55
+ hostKeySha256: {
56
+ type: "string|array",
57
+ label: "主机 SHA-256 指纹",
58
+ item: string("指纹"),
59
+ },
60
+ };
61
+ const sqlConnection = {
62
+ host: string("主机", true),
63
+ port: port(),
64
+ databaseName: string("数据库名", true),
65
+ user: string("用户名", true),
66
+ password: password("密码", true),
67
+ connectTimeoutMs: timeout(),
68
+ ssl: {
69
+ type: "boolean|map",
70
+ label: "SSL",
71
+ item: { type: "any", label: "SSL 选项" },
72
+ },
73
+ };
74
+ /** 根据原有配置结构提供完整字段表;web 由只读启动区域展示。 */
75
+ export const configSchema = (project) => {
76
+ if (project === "gateway")
77
+ return object("Gateway 配置", {
78
+ logging: object("日志", {
79
+ enable: bool("启用文件日志"),
80
+ path: string("日志路径"),
81
+ maxBytes: number("单文件字节上限", 1024, Number.MAX_SAFE_INTEGER, 10485760),
82
+ }),
83
+ services: array("下游 MCP 服务", object("服务", {
84
+ serviceId: string("服务标识", true),
85
+ name: string("名称", true),
86
+ description: string("描述"),
87
+ enable: bool("启用", true),
88
+ webUrl: string("Web 配置地址"),
89
+ codexAutoReview: bool("Codex 自动审批"),
90
+ callTimeoutMs: number("调用超时(毫秒)", 1, 86400000),
91
+ confirmationRequiredTools: strings("需要确认的工具"),
92
+ disabledTools: strings("禁用工具"),
93
+ transport: { ...object("传输配置", {}, true), variants: {} },
94
+ }), true),
95
+ });
96
+ if (project === "ssh")
97
+ return object("SSH 配置", {
98
+ ...sessionFields,
99
+ logDir: string("日志目录"),
100
+ defaultTimeout: number("命令超时(毫秒)", 100, 3600000, 60000),
101
+ commandBlacklist: strings("命令黑名单正则"),
102
+ commandWhitelist: strings("命令白名单正则"),
103
+ allowedLocalRoots: strings("允许的本地目录"),
104
+ servers: {
105
+ ...map("SSH 主机", object("主机", {
106
+ ...identity,
107
+ ...access,
108
+ readOnly: bool("只读模式"),
109
+ desc: string("描述"),
110
+ allowedRemoteRoots: strings("允许删除的远程根目录"),
111
+ workingDirectories: map("工作目录", object("目录", {
112
+ path: string("路径", true),
113
+ desc: string("描述", true),
114
+ })),
115
+ proxyJump: object("跳板机", identity),
116
+ })),
117
+ required: true,
118
+ },
119
+ });
120
+ return object("Database 配置", {
121
+ ...sessionFields,
122
+ logging: object("日志", {
123
+ enabled: bool("启用文件日志"),
124
+ directory: string("日志目录"),
125
+ }),
126
+ query: object("查询设置", { timeoutMs: timeout("查询超时(毫秒)") }),
127
+ databases: array("数据源", object("数据库", {
128
+ key: string("标识", true),
129
+ type: enumeration("数据库类型", [
130
+ "mysql",
131
+ "oracle",
132
+ "postgresql",
133
+ "redis",
134
+ ]),
135
+ readonly: { ...bool("只读模式", true), required: true },
136
+ ...access,
137
+ connection: {
138
+ ...object("连接配置", {}, true),
139
+ variants: {
140
+ mysql: object("MySQL 连接", { ...sqlConnection, port: port(3306) }),
141
+ postgresql: object("PostgreSQL 连接", {
142
+ ...sqlConnection,
143
+ port: port(5432),
144
+ }),
145
+ oracle: object("Oracle 连接", {
146
+ host: string("主机", true),
147
+ port: port(1521),
148
+ serviceName: string("服务名"),
149
+ sid: string("SID"),
150
+ user: string("用户名", true),
151
+ password: password("密码", true),
152
+ connectTimeoutMs: timeout(),
153
+ clientMode: {
154
+ ...enumeration("客户端模式", ["thin", "thick"]),
155
+ required: false,
156
+ },
157
+ clientLibDir: string("客户端库目录"),
158
+ }),
159
+ redis: object("Redis 连接", {
160
+ url: password("连接 URL"),
161
+ host: string("主机"),
162
+ port: port(6379),
163
+ databaseName: number("数据库编号", 0, Number.MAX_SAFE_INTEGER),
164
+ username: string("用户名"),
165
+ password: password("密码"),
166
+ connectTimeoutMs: timeout(),
167
+ }),
168
+ },
169
+ },
170
+ }), true),
171
+ });
172
+ };
173
+ /** 传输类型从自身读取,连接类型从父级读取;无关字段仍留在草稿中。 */
174
+ export const resolveField = (field, value, parent) => {
175
+ if (field.label === "传输配置") {
176
+ const type = value?.type;
177
+ return object("传输配置", {
178
+ type: enumeration("传输类型", ["stdio", "http"]),
179
+ ...(type === "http"
180
+ ? {
181
+ url: string("MCP HTTP 地址", true),
182
+ headers: map("请求头", password("值")),
183
+ }
184
+ : {
185
+ command: string("启动命令", true),
186
+ args: strings("命令参数"),
187
+ cwd: string("工作目录"),
188
+ env: map("环境变量", password("值")),
189
+ inheritEnv: bool("继承全部环境变量"),
190
+ envAllowlist: strings("允许继承的环境变量"),
191
+ }),
192
+ }, true);
193
+ }
194
+ return field.variants?.[String(parent?.type)] ?? field;
195
+ };
196
+ /** 验证已知字段的类型,未知字段交给项目原有规则处理。 */
197
+ export const validateFormTypes = (value, raw, path = "", parent) => {
198
+ const field = resolveField(raw, value, parent);
199
+ if (value === undefined)
200
+ return;
201
+ if (field.type === "any")
202
+ return;
203
+ const type = Array.isArray(value)
204
+ ? "array"
205
+ : value !== null && typeof value === "object"
206
+ ? "object"
207
+ : typeof value;
208
+ if (!field.type
209
+ .split("|")
210
+ .map((item) => (item === "map" ? "object" : item))
211
+ .includes(type))
212
+ throw new Error(`${path || "配置"}: 应为 ${field.type}`);
213
+ if (field.options && !field.options.includes(String(value)))
214
+ throw new Error(`${path}: 可选值为 ${field.options.join(", ")}`);
215
+ if (type === "number" &&
216
+ (!Number.isInteger(value) ||
217
+ Number(value) < (field.min ?? -Infinity) ||
218
+ Number(value) > (field.max ?? Infinity)))
219
+ throw new Error(`${path}: 数值超出允许范围`);
220
+ if (type === "array")
221
+ value.forEach((item, index) => validateFormTypes(item, field.item ?? { type: "any" }, `${path}[${index}]`));
222
+ if (type === "object") {
223
+ for (const [key, child] of Object.entries(value)) {
224
+ const descriptor = field.properties && Object.hasOwn(field.properties, key)
225
+ ? field.properties[key]
226
+ : field.item;
227
+ if (descriptor)
228
+ validateFormTypes(child, descriptor, path ? `${path}.${key}` : key, value);
229
+ }
230
+ }
231
+ };
@@ -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>