Compare commits

..
18 Commits
Author SHA1 Message Date
admin 526bede19a feat: WebSocket 实时同步、变更通知显示个性备注、Mock 数据 JSON 格式化
- 服务端新增 /__ws(原生 RFC6455 实现,零第三方依赖,复用同一 HTTP 端口),支持在线人数广播、数据变更广播、心跳保活与断线清理
- 各写接口(config/routes/api-list/mock-files/mock-groups/ip-rules)写入成功后广播 mutation 事件,按 X-Client-Id 请求头跳过发起方,避免自我提示
- 通知中的操作人取该 IP「个性化配置」的备注,显示为 [董] 更新了路由配置,无备注时回退显示 IP
- 管理页顶栏新增「在线 N 人」徽标(悬浮显示各客户端备注/IP),断线指数退避重连,重连成功后自动补刷全部数据
- Mock 数据弹窗新增「JSON 格式化」,支持修复单引号、无引号键、尾逗号等松散写法,非法内容给出具体报错位置
- 新增调试接口 GET /__ws-clients;全站文案「Mock 文件」统一改为「Mock 数据」(DB 表名与 /__mock-files 路径保持不变)
2026-11-26 15:45:42 +08:00
admin 3790ada0f1 修复接口管理修改错位问题 2026-09-23 10:04:02 +08:00
admin b8aee98468 feat:路由配置、数据配置加表单校验 2026-09-08 11:27:53 +08:00
adminandCursor 07a6af6fd9 feat: Mock 文件名按别名自动生成,路由展示与选择改为别名
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-08 11:20:56 +08:00
adminandCursor 574757f903 feat: 管理员新增个性化配置支持任意 IP 输入
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-01 15:07:51 +08:00
adminandCursor 9bec3208f8 feat: 管理员白名单与个性化配置权限控制
系统配置仅允许 admin_list.txt 白名单 IP 编辑;localhost 访问时解析为 LAN IP;个性化配置支持按 IP 权限隔离,新增时自动填充当前 IP。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-31 11:02:16 +08:00
admin 2b8cb3ca9a admin.html改为内部资源调用 2026-08-05 14:08:39 +08:00
admin 0fb285b045 自动升级 2026-07-10 12:01:20 +08:00
admin 0223db88b7 feat:新增IP个性化配置 2026-07-10 11:57:28 +08:00
admin 46bdff3734 加刷新按钮,切换tab自动刷新 2026-06-10 17:55:05 +08:00
admin a23a9846b3 全屏编辑mock数据 2026-06-09 14:33:03 +08:00
admin 03c2c83f68 路由配置中,点击Mock数据可以直接修改文件内容 2026-06-09 14:21:35 +08:00
admin 2a7d4efa59 解决未启用状态下的接口显示错误 2026-06-09 13:57:38 +08:00
admin 43fc4ebf57 新增mock文件必须要添加文件后缀 2026-06-05 09:51:50 +08:00
admin 5a89528e91 新增复制mock数据 2026-06-04 15:57:02 +08:00
admin 43435af89b 解决中文编码问题 2026-06-04 15:45:56 +08:00
admin 31095c967e mock数据分组管理 2026-06-04 15:24:11 +08:00
admin b1e4d2d7e7 升级pnpm到最新 2026-06-04 12:50:29 +08:00
27 changed files with 14973 additions and 171 deletions
+35 -13
View File
@@ -1,19 +1,20 @@
## API Proxy Mock ## API Proxy Mock
基于 Node.js 的轻量级 **HTTP 代理 + 本地 Mock**:所有配置(路由映射、服务器参数、接口列表)统一存储在 SQLite,mock 内容保存在 `mock/` 目录文件中,其余请求按配置(HTTP/HTTPS)转发到真实后端。通过 `/__admin` 管理面板进行可视化管理。 基于 Node.js 的轻量级 **HTTP 代理 + 本地 Mock**:所有配置(路由映射、服务器参数、接口列表)统一存储在 SQLite,mock 内容保存在 `mock/` 目录数据中,其余请求按配置(HTTP/HTTPS)转发到真实后端。通过 `/__admin` 管理面板进行可视化管理。
### 功能说明 ### 功能说明
- **代理转发**:未命中 Mock 的请求会转发到 `config.targetHost`(由 `targetHttps` 决定 HTTP/HTTPS,`targetPort` 可配)。 - **代理转发**:未命中 Mock 的请求会转发到 `config.targetHost`(由 `targetHttps` 决定 HTTP/HTTPS,`targetPort` 可配)。
- **本地 Mock**:命中路由时直接读取 `mock/` 目录下的文件作为响应体。 - **本地 Mock**:命中路由时直接读取 `mock/` 目录下的数据作为响应体。
- **SQLite 存储**:路由列表、接口列表、服务器配置全部存储在 `data/mock-mappings.sqlite3`。 - **SQLite 存储**:路由列表、接口列表、服务器配置全部存储在 `data/mock-mappings.sqlite3`。
- **Mock 总开关**:`mockEnabled` 为 `false` 时**不拦截**任何 Mock 路由,全部走代理。 - **Mock 总开关**:`mockEnabled` 为 `false` 时**不拦截**任何 Mock 路由,全部走代理。
- **Mock 响应**:带简单 CORS 头,以及 `X-Mock-Source`、`X-Mock-Timestamp` 便于排查。 - **Mock 响应**:带简单 CORS 头,以及 `X-Mock-Source`、`X-Mock-Timestamp` 便于排查。
- **管理面板**:访问 `/__admin` 进入 Element UI 可视化管理界面,支持以下功能: - **管理面板**:访问 `/__admin` 进入 Element UI 可视化管理界面,支持以下功能:
- **路由配置**:增删改查路由映射,启用/禁用单条路由,已启用路由自动置顶排序。 - **路由配置**:增删改查路由映射,启用/禁用单条路由,已启用路由自动置顶排序。
- **Mock 数据配置**:新增/编辑/删除 Mock 文件,`mock/` 目录固定,只需输入文件名和后缀。 - **Mock 数据**:新增/编辑/删除 Mock 数据,编辑器支持一键 JSON 格式化(自动修复单引号、无引号键、尾逗号等常见写法),`mock/` 目录固定,只需输入数据名和后缀。
- **接口管理**:增删改查预置接口列表,支持 JSON 数组批量导入。 - **接口管理**:增删改查预置接口列表,支持 JSON 数组批量导入。
- **基础配置**:Mock 开关、默认 Content-Type(下拉选择)、代理端口(修改需重启)、目标主机/端口/HTTPS。 - **基础配置**:Mock 开关、默认 Content-Type(下拉选择)、代理端口(修改需重启)、目标主机/端口/HTTPS。
- **实时同步(WebSocket)**:服务端内置 `/__ws`,管理页面打开即自动连接并显示当前在线人数;任一客户端的增删改都会广播给其他页面,弹窗提示后自动刷新对应数据(路由 / Mock 数据 / 接口列表 / 系统配置 / 个性化配置)。
### 环境要求 ### 环境要求
@@ -54,12 +55,12 @@ npm run typecheck
| 表名 | 用途 | | 表名 | 用途 |
| --- | --- | | --- | --- |
| `route_mappings` | 路由 → mock 文件映射 + 状态码 + 启用状态 + 接口名称 | | `route_mappings` | 路由 → Mock 数据映射 + 状态码 + 启用状态 + 接口名称 |
| `api_list` | 预置接口清单(名称 + 路径) | | `api_list` | 预置接口清单(名称 + 路径) |
| `mock_files` | mock 文件路径 + 别名 | | `mock_files` | Mock 数据路径 + 别名 |
| `server_config` | 服务器配置(端口、目标主机、Content-Type 等) | | `server_config` | 服务器配置(端口、目标主机、Content-Type 等) |
首次启动时,如果 `mock_files` 表为空,会自动扫描 `mock/` 目录下的文件并导入数据库。 首次启动时,如果 `mock_files` 表为空,会自动扫描 `mock/` 目录下的数据并导入数据库。
### 管理接口 ### 管理接口
@@ -75,10 +76,30 @@ npm run typecheck
| `GET` | `http://localhost:<proxyPort>/__api-list` | 获取预置接口列表 | | `GET` | `http://localhost:<proxyPort>/__api-list` | 获取预置接口列表 |
| `POST` | `http://localhost:<proxyPort>/__api-list` | 新增/编辑预置接口 | | `POST` | `http://localhost:<proxyPort>/__api-list` | 新增/编辑预置接口 |
| `DELETE` | `http://localhost:<proxyPort>/__api-list` | 删除预置接口 | | `DELETE` | `http://localhost:<proxyPort>/__api-list` | 删除预置接口 |
| `GET` | `http://localhost:<proxyPort>/__mock-files` | 获取 mock 文件列表 | | `GET` | `http://localhost:<proxyPort>/__mock-files` | 获取 Mock 数据列表 |
| `POST` | `http://localhost:<proxyPort>/__mock-files` | 创建/更新 mock 文件 | | `POST` | `http://localhost:<proxyPort>/__mock-files` | 创建/更新 Mock 数据 |
| `DELETE` | `http://localhost:<proxyPort>/__mock-files` | 删除 mock 文件 | | `DELETE` | `http://localhost:<proxyPort>/__mock-files` | 删除 Mock 数据 |
| `GET` | `http://localhost:<proxyPort>/__admin` | 配置管理页面(Element UI) | | `GET` | `http://localhost:<proxyPort>/__admin` | 配置管理页面(Element UI) |
| `GET` | `http://localhost:<proxyPort>/__ws-clients` | 查看当前 WebSocket 在线客户端 |
| `WS` | `ws://localhost:<proxyPort>/__ws` | 实时同步通道(在线人数 / 变更通知) |
#### WebSocket 实时同步
管理页面加载后会自动连接 `ws://<host>/__ws?cid=<标签页id>`,服务端复用同一 HTTP 端口(`upgrade` 事件),无需额外端口。
服务端 → 客户端的消息:
| 消息 | 说明 |
| --- | --- |
| `{type:"welcome", clientId, online, clients}` | 连接成功,返回在线人数与客户端列表 |
| `{type:"online", online, clients}` | 在线人数变化(有人进入/离开) |
| `{type:"mutation", resource, action, detail, actor:{ip,cid,name}}` | 其他客户端修改了数据,前端弹窗提示并刷新对应资源 |
`actor.name` 取自该 IP 在「个性化配置」中的备注;配置了备注时通知里用 `[备注]` 代替 IP(如 `[董] 修改了 Mock 数据「xxx」`),未配置则回退显示 IP。
`resource` 取值:`routes`、`mock-files`、`mock-groups`、`api-list`、`config`、`ip-rules`。
回声抑制:管理页所有请求都会带上 `X-Client-Id` 请求头(值为该标签页 id),服务端广播时跳过同 id 的连接,因此发起变更的页面不会收到自己的通知(它已在本地刷新)。
#### `POST /__routes` 请求示例 #### `POST /__routes` 请求示例
@@ -122,13 +143,13 @@ npm run typecheck
### TypeScript 与编译说明 ### TypeScript 与编译说明
- 项目根目录包含 `tsconfig.json`,请使用 **`tsc -p .`** 或 **`npm run typecheck`** 做整项目检查。 - 项目根目录包含 `tsconfig.json`,请使用 **`tsc -p .`** 或 **`npm run typecheck`** 做整项目检查。
- **不要**使用 `tsc .\index.api.ts` 这类「命令行附带单个文件」的方式,否则会与 `tsconfig.json` 冲突并报 **TS5112**。 - **不要**使用 `tsc .\index.api.ts` 这类「命令行附带单个数据」的方式,否则会与 `tsconfig.json` 冲突并报 **TS5112**。
### 目录结构 ### 目录结构
``` ```
├── index.api.ts # 服务入口 ├── index.api.ts # 服务入口
├── admin.html # 管理面板(Vue 2 + Element UI 单文件) ├── admin.html # 管理面板(Vue 2 + Element UI 单数据)
├── src/ ├── src/
│ ├── types.ts # TypeScript 类型定义 │ ├── types.ts # TypeScript 类型定义
│ ├── constants.ts # 路径常量(MOCK_DIR、DB_FILE 等) │ ├── constants.ts # 路径常量(MOCK_DIR、DB_FILE 等)
@@ -137,11 +158,12 @@ npm run typecheck
│ ├── config.ts # 配置加载/保存 │ ├── config.ts # 配置加载/保存
│ ├── proxy.ts # HTTP 服务 + 代理转发 + Mock 响应 │ ├── proxy.ts # HTTP 服务 + 代理转发 + Mock 响应
│ ├── admin-handlers.ts # 管理接口处理 │ ├── admin-handlers.ts # 管理接口处理
│ ├── mock-files.ts # Mock 文件加载与管理 │ ├── mock-files.ts # Mock 数据加载与管理
│ ├── route-matching.ts # 路由匹配逻辑 │ ├── route-matching.ts # 路由匹配逻辑
│ ├── api-list.ts # 预置接口列表管理 │ ├── api-list.ts # 预置接口列表管理
│ ├── ws.ts # WebSocket 服务(在线人数 + 变更广播)
│ └── utils.ts # 工具函数 │ └── utils.ts # 工具函数
├── mock/ # Mock 响应文件(文本原样返回) ├── mock/ # Mock 响应数据(文本原样返回)
└── data/ └── data/
└── mock-mappings.sqlite3 # SQLite 数据库 └── mock-mappings.sqlite3 # SQLite 数据库
``` ```
+1393 -80
View File
File diff suppressed because it is too large Load Diff
+2
View File
@@ -0,0 +1,2 @@
192.168.3.9
192.168.3.12
Binary file not shown.
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+11932
View File
File diff suppressed because it is too large Load Diff
+5
View File
@@ -11,9 +11,11 @@ import {
getEffectiveTargetPort, getEffectiveTargetPort,
} from "./src/proxy"; } from "./src/proxy";
import { state } from "./src/state"; import { state } from "./src/state";
import { attachWebSocketServer, WS_PATH } from "./src/ws";
function startServer(): void { function startServer(): void {
const proxyServer = createProxyServer(); const proxyServer = createProxyServer();
attachWebSocketServer(proxyServer);
proxyServer.listen(state.config.proxyPort, "0.0.0.0", () => { proxyServer.listen(state.config.proxyPort, "0.0.0.0", () => {
const targetPort = getEffectiveTargetPort(); const targetPort = getEffectiveTargetPort();
const https = getEffectiveTargetHttps(); const https = getEffectiveTargetHttps();
@@ -42,6 +44,9 @@ function startServer(): void {
console.log( console.log(
` GET http://localhost:${state.config.proxyPort}/__admin 管理面板`, ` GET http://localhost:${state.config.proxyPort}/__admin 管理面板`,
); );
console.log(
` WS ws://localhost:${state.config.proxyPort}${WS_PATH} 实时同步(在线人数/变更通知)`,
);
console.log(`========================================`); console.log(`========================================`);
console.log(`Mock路由列表:`); console.log(`Mock路由列表:`);
+4
View File
@@ -0,0 +1,4 @@
{
"code": 0,
"msg": "ok"
}
+1 -1
View File
@@ -1 +1 @@
{"code":0,"msg":"ok"} {"code":0,"msg":"3"}
+1
View File
@@ -0,0 +1 @@
{}
-5
View File
@@ -11,10 +11,5 @@
}, },
"dependencies": { "dependencies": {
"sqlite3": "^6.0.1" "sqlite3": "^6.0.1"
},
"pnpm": {
"onlyBuiltDependencies": [
"sqlite3"
]
} }
} }
+4
View File
@@ -0,0 +1,4 @@
packages:
- "*"
allowBuilds:
sqlite3: true
+533 -14
View File
@@ -9,7 +9,19 @@ import {
insertApiItemToDb, insertApiItemToDb,
updateApiItemInDb, updateApiItemInDb,
deleteApiItemFromDb, deleteApiItemFromDb,
loadMockGroups,
insertMockGroup,
updateMockGroup,
deleteMockGroup,
countMockFilesByGroup,
updateMockFilesGroupId,
deleteMockFilesByGroup,
loadIpRulesFromDb,
upsertIpRuleToDb,
deleteIpRuleFromDb,
} from "./db"; } from "./db";
import { isAdminClient, resolveAdminClientIp, canManageIpRule } from "./admin-list";
import { isValidIpAddress, normalizeIp, resolveEffectiveConfig, getMachineLanIpv4Addresses, formatTargetSummary } from "./ip-rules";
import { import {
loadMockFiles, loadMockFiles,
normalizeMockFilePath, normalizeMockFilePath,
@@ -17,6 +29,8 @@ import {
} from "./mock-files"; } from "./mock-files";
import { normalizeStatusCode, readBody } from "./utils"; import { normalizeStatusCode, readBody } from "./utils";
import { state } from "./state"; import { state } from "./state";
import { broadcastMutation, getOnlineClients, getOnlineCount } from "./ws";
import type { IpRule, IpRuleConfig } from "./types";
async function handleReloadConfig( async function handleReloadConfig(
clientReq: http.IncomingMessage, clientReq: http.IncomingMessage,
@@ -54,6 +68,12 @@ async function handleReloadConfig(
console.log( console.log(
`[ADMIN] 通过API重新加载配置 (路由数: ${oldCount} -> ${newCount})`, `[ADMIN] 通过API重新加载配置 (路由数: ${oldCount} -> ${newCount})`,
); );
broadcastMutation(
clientReq,
"config",
"update",
"重新加载了系统配置",
);
} catch (error) { } catch (error) {
clientRes.writeHead(500, { "Content-Type": "application/json" }); clientRes.writeHead(500, { "Content-Type": "application/json" });
clientRes.end( clientRes.end(
@@ -88,8 +108,18 @@ async function handleConfig(
readBody(clientReq) readBody(clientReq)
.then(async (bodyText) => { .then(async (bodyText) => {
const body = bodyText ? JSON.parse(bodyText) : {}; const body = bodyText ? JSON.parse(bodyText) : {};
// 保存服务器配置 // 保存服务器配置(仅 admin_list.txt 白名单 IP 可修改)
if (body.config) { if (body.config) {
if (!isAdminClient(clientReq)) {
clientRes.writeHead(403, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: false,
error: "当前 IP 不在管理员白名单内,无法修改基础配置",
}),
);
return;
}
await saveConfig(body.config); await saveConfig(body.config);
} }
// 保存路由配置 // 保存路由配置
@@ -102,6 +132,12 @@ async function handleConfig(
); );
} }
validateMockFiles(); validateMockFiles();
if (body.config) {
broadcastMutation(clientReq, "config", "update", "修改了系统配置");
}
if (body.routes || body.routeStatuses || body.routeEnabledMap) {
broadcastMutation(clientReq, "routes", "update", "更新了路由配置");
}
clientRes.writeHead(200, { "Content-Type": "application/json" }); clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end( clientRes.end(
JSON.stringify({ JSON.stringify({
@@ -128,13 +164,10 @@ async function handleConfig(
clientRes.end( clientRes.end(
JSON.stringify( JSON.stringify(
{ {
routes: state.rawRoutes,
routeStatuses: state.rawRouteStatuses,
routeEnabledMap: state.routeEnabledMap,
routeApiNameMap: state.routeApiNameMap,
config: state.config, config: state.config,
canEditBasicConfig: isAdminClient(clientReq),
clientIp: resolveAdminClientIp(clientReq),
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
totalRoutes: Object.keys(state.rawRoutes).length,
}, },
null, null,
2, 2,
@@ -155,16 +188,31 @@ async function handleRoutes(
clientReq: http.IncomingMessage, clientReq: http.IncomingMessage,
clientRes: http.ServerResponse, clientRes: http.ServerResponse,
): Promise<void> { ): Promise<void> {
if (clientReq.method !== "POST") { if (clientReq.method !== "GET" && clientReq.method !== "POST") {
clientRes.writeHead(405, { clientRes.writeHead(405, {
"Content-Type": "application/json", "Content-Type": "application/json",
Allow: "POST", Allow: "GET, POST",
}); });
clientRes.end( clientRes.end(
JSON.stringify({ JSON.stringify({
success: false, success: false,
error: "Method Not Allowed", error: "Method Not Allowed",
allow: ["POST"], allow: ["GET, POST"],
}),
);
return;
}
if (clientReq.method === "GET") {
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: true,
routes: state.rawRoutes,
routeStatuses: state.rawRouteStatuses,
routeEnabledMap: state.routeEnabledMap,
routeApiNameMap: state.routeApiNameMap,
totalRoutes: Object.keys(state.rawRoutes).length,
}), }),
); );
return; return;
@@ -217,12 +265,12 @@ async function handleRoutes(
const fullPath = resolveMockFullPath(normalizedFilePath); const fullPath = resolveMockFullPath(normalizedFilePath);
if (useExistingFile) { if (useExistingFile) {
if (!fs.existsSync(fullPath)) { if (!fs.existsSync(fullPath)) {
throw new Error("mock file does not exist"); throw new Error("Mock 数据不存在");
} }
} else { } else {
if (!overwrite && fs.existsSync(fullPath)) { if (!overwrite && fs.existsSync(fullPath)) {
throw new Error( throw new Error(
"mock file already exists, set overwrite=true to replace", "Mock 数据已存在,如需覆盖请设置 overwrite=true",
); );
} }
fs.mkdirSync(path.dirname(fullPath), { recursive: true }); fs.mkdirSync(path.dirname(fullPath), { recursive: true });
@@ -253,11 +301,20 @@ async function handleRoutes(
await saveRoutes(nextRoutes, nextStatuses, nextEnabledMap, nextApiNameMap); await saveRoutes(nextRoutes, nextStatuses, nextEnabledMap, nextApiNameMap);
await upsertMockFilePathToDb(normalizedFilePath); await upsertMockFilePathToDb(normalizedFilePath);
const isEdit = !!originalRoute;
broadcastMutation(
clientReq,
"routes",
isEdit ? "update" : "create",
`${isEdit ? "修改" : "新增"}了路由 ${route}`,
{ route },
);
clientRes.writeHead(200, { "Content-Type": "application/json" }); clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end( clientRes.end(
JSON.stringify({ JSON.stringify({
success: true, success: true,
message: "Route and mock file created successfully", message: "Route and mock data created successfully",
route, route,
filePath: normalizedFilePath, filePath: normalizedFilePath,
statusCode, statusCode,
@@ -328,6 +385,14 @@ async function handleApiList(
} else { } else {
await insertApiItemToDb({ route, name }); await insertApiItemToDb({ route, name });
} }
const isEdit = !!originalRoute;
broadcastMutation(
clientReq,
"api-list",
isEdit ? "update" : "create",
`${isEdit ? "修改" : "新增"}了接口「${name}」`,
{ route },
);
clientRes.writeHead(200, { "Content-Type": "application/json" }); clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, route, name })); clientRes.end(JSON.stringify({ success: true, route, name }));
return; return;
@@ -335,6 +400,9 @@ async function handleApiList(
// DELETE // DELETE
await deleteApiItemFromDb(route); await deleteApiItemFromDb(route);
broadcastMutation(clientReq, "api-list", "delete", `删除了接口 ${route}`, {
route,
});
clientRes.writeHead(200, { "Content-Type": "application/json" }); clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, route })); clientRes.end(JSON.stringify({ success: true, route }));
}) })
@@ -393,9 +461,18 @@ async function handleMockFiles(
if (clientReq.method === "POST") { if (clientReq.method === "POST") {
const content = String(body.content || ""); const content = String(body.content || "");
const groupId = body.groupId != null ? Number(body.groupId) : null;
const existed = fs.existsSync(fullPath);
fs.mkdirSync(path.dirname(fullPath), { recursive: true }); fs.mkdirSync(path.dirname(fullPath), { recursive: true });
fs.writeFileSync(fullPath, content, "utf-8"); fs.writeFileSync(fullPath, content, "utf-8");
await upsertMockFilePathToDb(normalizedPath, alias); await upsertMockFilePathToDb(normalizedPath, alias, groupId);
broadcastMutation(
clientReq,
"mock-files",
existed ? "update" : "create",
`${existed ? "修改" : "新增"}了 Mock 数据「${alias || normalizedPath}」`,
{ filePath: normalizedPath },
);
clientRes.writeHead(200, { "Content-Type": "application/json" }); clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end( clientRes.end(
JSON.stringify({ JSON.stringify({
@@ -409,10 +486,17 @@ async function handleMockFiles(
// DELETE // DELETE
if (!fs.existsSync(fullPath)) { if (!fs.existsSync(fullPath)) {
throw new Error("mock file does not exist"); throw new Error("Mock 数据不存在");
} }
fs.unlinkSync(fullPath); fs.unlinkSync(fullPath);
await removeMockFilePathFromDb(normalizedPath); await removeMockFilePathFromDb(normalizedPath);
broadcastMutation(
clientReq,
"mock-files",
"delete",
`删除了 Mock 数据「${alias || normalizedPath}」`,
{ filePath: normalizedPath },
);
clientRes.writeHead(200, { "Content-Type": "application/json" }); clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end( clientRes.end(
JSON.stringify({ JSON.stringify({
@@ -432,6 +516,424 @@ async function handleMockFiles(
}); });
} }
async function handleMockGroups(
clientReq: http.IncomingMessage,
clientRes: http.ServerResponse,
): Promise<void> {
if (
clientReq.method !== "GET" &&
clientReq.method !== "POST" &&
clientReq.method !== "PUT" &&
clientReq.method !== "DELETE"
) {
clientRes.writeHead(405, {
"Content-Type": "application/json",
Allow: "GET, POST, PUT, DELETE",
});
clientRes.end(
JSON.stringify({
success: false,
error: "Method Not Allowed",
allow: ["GET, POST, PUT, DELETE"],
}),
);
return;
}
if (clientReq.method === "GET") {
const list = await loadMockGroups();
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, list }));
return;
}
readBody(clientReq)
.then(async (bodyText) => {
const body = bodyText ? JSON.parse(bodyText) : {};
if (clientReq.method === "POST") {
const name = String(body.name || "").trim();
if (!name) {
throw new Error("分组名称不能为空");
}
const id = await insertMockGroup(name);
broadcastMutation(clientReq, "mock-groups", "create", `新增了分组「${name}」`, {
id,
});
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, id, name }));
return;
}
if (clientReq.method === "PUT") {
const id = Number(body.id);
const name = String(body.name || "").trim();
if (!id || !name) {
throw new Error("id 和 name 不能为空");
}
await updateMockGroup(id, name);
broadcastMutation(clientReq, "mock-groups", "update", `修改了分组名称为「${name}」`, {
id,
});
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, id, name }));
return;
}
// DELETE
const id = Number(body.id);
if (!id) {
throw new Error("id 不能为空");
}
const fileCount = await countMockFilesByGroup(id);
const action = String(body.action || "").trim();
let filesChanged = false;
if (fileCount > 0 && action === "reassign") {
const targetGroupId = body.targetGroupId != null ? Number(body.targetGroupId) : null;
await updateMockFilesGroupId(id, targetGroupId);
filesChanged = true;
} else if (fileCount > 0 && action === "delete") {
const deletedFiles = await deleteMockFilesByGroup(id);
// 删除磁盘上的数据
for (const file of deletedFiles) {
const fullPath = path.join(__dirname, "..", file.file_path);
if (fs.existsSync(fullPath)) {
fs.unlinkSync(fullPath);
}
}
filesChanged = true;
} else if (fileCount > 0) {
// 有数据但未指定 action,返回需要确认的信息
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: false,
needConfirm: true,
fileCount,
message: `该分组下有 ${fileCount} 条 Mock 数据,请指定操作`,
}),
);
return;
}
const groupName =
(await loadMockGroups()).find((group) => group.id === id)?.name || `#${id}`;
await deleteMockGroup(id);
broadcastMutation(clientReq, "mock-groups", "delete", `删除了分组「${groupName}」`, {
id,
});
if (filesChanged) {
broadcastMutation(
clientReq,
"mock-files",
"update",
`分组「${groupName}」下的 Mock 数据已变更`,
);
}
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, id }));
})
.catch((error) => {
clientRes.writeHead(400, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: false,
error: (error as Error).message,
}),
);
});
}
function parseIpRuleBody(body: Record<string, unknown>): IpRule {
const ip = String(body.ip || "").trim();
if (!isValidIpAddress(ip)) {
throw new Error("IP 地址格式无效");
}
const blocked = body.blocked === true;
const useCustomConfig = body.useCustomConfig === true && !blocked;
const configInput = (body.config || {}) as IpRuleConfig;
const config: IpRuleConfig = {};
if (useCustomConfig) {
if (configInput.mockEnabled !== undefined) {
config.mockEnabled = configInput.mockEnabled !== false;
}
if (configInput.defaultContentType) {
config.defaultContentType = String(configInput.defaultContentType).trim();
}
if (configInput.targetHost) {
config.targetHost = String(configInput.targetHost).trim();
}
if (configInput.targetPort !== undefined && configInput.targetPort !== null) {
const port = Number(configInput.targetPort);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error("目标端口无效");
}
config.targetPort = port;
}
if (configInput.targetHttps !== undefined) {
config.targetHttps = configInput.targetHttps !== false;
}
}
if (!blocked && !useCustomConfig) {
throw new Error("请至少启用「拉黑」或「个性化配置」");
}
return {
ip,
blocked,
remark: String(body.remark || "").trim(),
useCustomConfig,
config,
};
}
async function handleIpRules(
clientReq: http.IncomingMessage,
clientRes: http.ServerResponse,
): Promise<void> {
if (
clientReq.method !== "GET" &&
clientReq.method !== "POST" &&
clientReq.method !== "DELETE"
) {
clientRes.writeHead(405, {
"Content-Type": "application/json",
Allow: "GET, POST, DELETE",
});
clientRes.end(
JSON.stringify({
success: false,
error: "Method Not Allowed",
allow: ["GET, POST, DELETE"],
}),
);
return;
}
if (clientReq.method === "GET") {
const clientIp = resolveAdminClientIp(clientReq);
const isAdmin = isAdminClient(clientReq);
const list = isAdmin
? state.ipRules
: state.ipRules.filter(
(rule) => normalizeIp(rule.ip) === normalizeIp(clientIp),
);
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: true,
list,
clientIp,
isAdmin,
}),
);
return;
}
readBody(clientReq)
.then(async (bodyText) => {
const body = bodyText ? JSON.parse(bodyText) : {};
if (clientReq.method === "DELETE") {
const ip = String(body.ip || "").trim();
if (!ip) {
throw new Error("ip 不能为空");
}
if (!canManageIpRule(clientReq, ip)) {
clientRes.writeHead(403, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: false,
error: "只能删除与当前 IP 匹配的个性化配置",
}),
);
return;
}
await deleteIpRuleFromDb(ip);
state.ipRules = await loadIpRulesFromDb();
broadcastMutation(
clientReq,
"ip-rules",
"delete",
`删除了 IP 规则「${ip}」`,
{ ip },
);
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, ip }));
return;
}
const rule = parseIpRuleBody(body);
if (!isAdminClient(clientReq)) {
rule.ip = resolveAdminClientIp(clientReq);
}
if (!canManageIpRule(clientReq, rule.ip)) {
clientRes.writeHead(403, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: false,
error: "只能修改与当前 IP 匹配的个性化配置",
}),
);
return;
}
const existed = state.ipRules.some(
(item) => normalizeIp(item.ip) === normalizeIp(rule.ip),
);
await upsertIpRuleToDb(rule);
state.ipRules = await loadIpRulesFromDb();
broadcastMutation(
clientReq,
"ip-rules",
existed ? "update" : "create",
`${existed ? "修改" : "新增"}了 IP 规则「${rule.ip}」`,
{ ip: rule.ip },
);
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, rule }));
})
.catch((error) => {
clientRes.writeHead(400, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: false,
error: (error as Error).message,
}),
);
});
}
async function handleClientIp(
clientReq: http.IncomingMessage,
clientRes: http.ServerResponse,
): Promise<void> {
if (clientReq.method !== "GET") {
clientRes.writeHead(405, {
"Content-Type": "application/json",
Allow: "GET",
});
clientRes.end(
JSON.stringify({
success: false,
error: "Method Not Allowed",
allow: ["GET"],
}),
);
return;
}
const effective = resolveEffectiveConfig(clientReq);
const matchedRule = effective.matchedRule;
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: true,
clientIp: effective.ip,
localIpv4Addresses: getMachineLanIpv4Addresses(),
matchedRule: matchedRule
? {
ip: matchedRule.ip,
remark: matchedRule.remark,
blocked: matchedRule.blocked,
useCustomConfig: matchedRule.useCustomConfig,
}
: null,
ruleMatchedViaLocalhost:
!effective.blocked && effective.ruleMatchedViaLocalhost === true,
effectiveTarget: effective.blocked
? null
: formatTargetSummary(effective.config),
globalTarget: formatTargetSummary(state.config),
}),
);
}
/** 在线客户端查询(调试用,页面主要通过 WebSocket 获取在线人数) */
async function handleWsClients(
clientReq: http.IncomingMessage,
clientRes: http.ServerResponse,
): Promise<void> {
if (clientReq.method !== "GET") {
clientRes.writeHead(405, {
"Content-Type": "application/json",
Allow: "GET",
});
clientRes.end(
JSON.stringify({ success: false, error: "Method Not Allowed", allow: ["GET"] }),
);
return;
}
clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
success: true,
online: getOnlineCount(),
clients: getOnlineClients(),
timestamp: new Date().toISOString(),
}),
);
}
const ASSETS_ROOT = path.join(__dirname, "..", "assets");
const ASSET_CONTENT_TYPES: Record<string, string> = {
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".woff": "font/woff",
".ttf": "font/ttf",
".map": "application/json",
};
async function handleAdminAssets(
requestPath: string,
clientReq: http.IncomingMessage,
clientRes: http.ServerResponse,
): Promise<void> {
if (clientReq.method !== "GET" && clientReq.method !== "HEAD") {
clientRes.writeHead(405, { "Content-Type": "text/plain; charset=utf-8" });
clientRes.end("Method Not Allowed");
return;
}
const relativePath = decodeURIComponent(requestPath.slice("/assets/".length));
if (!relativePath || relativePath.includes("\0")) {
clientRes.writeHead(400, { "Content-Type": "text/plain; charset=utf-8" });
clientRes.end("Bad Request");
return;
}
const resolved = path.resolve(ASSETS_ROOT, relativePath);
const assetsRootResolved = path.resolve(ASSETS_ROOT);
if (
resolved !== assetsRootResolved &&
!resolved.startsWith(assetsRootResolved + path.sep)
) {
clientRes.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" });
clientRes.end("Forbidden");
return;
}
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) {
clientRes.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
clientRes.end("Not Found");
return;
}
const ext = path.extname(resolved).toLowerCase();
const contentType =
ASSET_CONTENT_TYPES[ext] || "application/octet-stream";
const body = fs.readFileSync(resolved);
clientRes.writeHead(200, {
"Content-Type": contentType,
"Content-Length": body.length,
"Cache-Control": "public, max-age=86400",
});
if (clientReq.method === "HEAD") {
clientRes.end();
return;
}
clientRes.end(body);
}
async function handleAdminPage( async function handleAdminPage(
clientReq: http.IncomingMessage, clientReq: http.IncomingMessage,
clientRes: http.ServerResponse, clientRes: http.ServerResponse,
@@ -460,6 +962,11 @@ export async function dispatchAdmin(
clientReq: http.IncomingMessage, clientReq: http.IncomingMessage,
clientRes: http.ServerResponse, clientRes: http.ServerResponse,
): Promise<boolean> { ): Promise<boolean> {
if (requestPath === "/assets" || requestPath.startsWith("/assets/")) {
await handleAdminAssets(requestPath, clientReq, clientRes);
return true;
}
switch (requestPath) { switch (requestPath) {
case "/__reload-config": case "/__reload-config":
await handleReloadConfig(clientReq, clientRes); await handleReloadConfig(clientReq, clientRes);
@@ -476,6 +983,18 @@ export async function dispatchAdmin(
case "/__mock-files": case "/__mock-files":
await handleMockFiles(clientReq, clientRes); await handleMockFiles(clientReq, clientRes);
return true; return true;
case "/__mock-groups":
await handleMockGroups(clientReq, clientRes);
return true;
case "/__ip-rules":
await handleIpRules(clientReq, clientRes);
return true;
case "/__client-ip":
await handleClientIp(clientReq, clientRes);
return true;
case "/__ws-clients":
await handleWsClients(clientReq, clientRes);
return true;
case "/__admin": case "/__admin":
await handleAdminPage(clientReq, clientRes); await handleAdminPage(clientReq, clientRes);
return true; return true;
+45
View File
@@ -0,0 +1,45 @@
import * as fs from "fs";
import * as http from "http";
import { ADMIN_LIST_FILE } from "./constants";
import { resolveClientIp, normalizeIp } from "./ip-rules";
import { state } from "./state";
export function loadAdminList(): string[] {
if (!fs.existsSync(ADMIN_LIST_FILE)) {
return [];
}
const content = fs.readFileSync(ADMIN_LIST_FILE, "utf-8");
return content
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line && !line.startsWith("#"))
.map(normalizeIp);
}
/** 客户端 IP 是否在 admin_list.txt 白名单内(localhost 会映射为本机 LAN IP) */
export function isAdminClient(req: http.IncomingMessage): boolean {
const adminList = loadAdminList();
if (adminList.length === 0) {
return false;
}
const whitelist = new Set(adminList.map(normalizeIp));
const clientIp = resolveClientIp(req, adminList);
return whitelist.has(clientIp);
}
export function resolveAdminClientIp(req: http.IncomingMessage): string {
const adminList = loadAdminList();
const hintIps = [...adminList, ...state.ipRules.map((rule) => rule.ip)];
return resolveClientIp(req, hintIps);
}
/** 是否可管理指定 IP 的规则(管理员可操作全部,普通用户仅可操作自身 IP) */
export function canManageIpRule(
req: http.IncomingMessage,
ruleIp: string,
): boolean {
if (isAdminClient(req)) {
return true;
}
return normalizeIp(ruleIp) === normalizeIp(resolveAdminClientIp(req));
}
+9 -5
View File
@@ -5,14 +5,15 @@ import {
loadRoutesFromDb, loadRoutesFromDb,
loadServerConfig, loadServerConfig,
saveServerConfig, saveServerConfig,
loadIpRulesFromDb,
} from "./db"; } from "./db";
import { getActiveRoutes } from "./route-matching"; import { getActiveRoutes } from "./route-matching";
import { state } from "./state"; import { state } from "./state";
import type { AppConfig, RouteApiNameMap, RouteEnabledMap } from "./types"; import type { AppConfig, RouteApiNameMap, RouteEnabledMap } from "./types";
// 验证mock文件是否存在 // 验证 Mock 数据是否存在
export function validateMockFiles(): void { export function validateMockFiles(): void {
console.log(`[CONFIG] 验证mock文件...`); console.log(`[CONFIG] 验证 Mock 数据...`);
const missingFiles: Array<{ const missingFiles: Array<{
route: string; route: string;
filePath: string; filePath: string;
@@ -25,17 +26,17 @@ export function validateMockFiles(): void {
if (!fs.existsSync(fullPath)) { if (!fs.existsSync(fullPath)) {
missingFiles.push({ route, filePath, fullPath }); missingFiles.push({ route, filePath, fullPath });
console.warn( console.warn(
`[CONFIG] 警告: mock文件不存在 - ${filePath} (用于路由: ${route})`, `[CONFIG] 警告: Mock 数据不存在 - ${filePath} (用于路由: ${route})`,
); );
} }
} }
if (missingFiles.length > 0) { if (missingFiles.length > 0) {
console.log( console.log(
`[CONFIG] 缺少 ${missingFiles.length} 个mock文件,请创建这些文件`, `[CONFIG] 缺少 ${missingFiles.length} 条 Mock 数据,请创建对应数据`,
); );
} else { } else {
console.log(`[CONFIG] 所有mock文件验证通过`); console.log(`[CONFIG] 所有 Mock 数据校验通过`);
} }
} }
@@ -50,6 +51,8 @@ export async function loadConfig(): Promise<void> {
state.routeEnabledMap = dbMappings.routeEnabledMap; state.routeEnabledMap = dbMappings.routeEnabledMap;
state.routeApiNameMap = dbMappings.routeApiNameMap; state.routeApiNameMap = dbMappings.routeApiNameMap;
state.ipRules = await loadIpRulesFromDb();
const activeCount = Object.values(state.routeEnabledMap).filter( const activeCount = Object.values(state.routeEnabledMap).filter(
(v) => v !== false, (v) => v !== false,
).length; ).length;
@@ -64,6 +67,7 @@ export async function loadConfig(): Promise<void> {
state.rawRouteStatuses = {}; state.rawRouteStatuses = {};
state.routeEnabledMap = {}; state.routeEnabledMap = {};
state.routeApiNameMap = {}; state.routeApiNameMap = {};
state.ipRules = [];
state.config = { state.config = {
cacheConfig: true, cacheConfig: true,
reloadOnChange: true, reloadOnChange: true,
+1
View File
@@ -5,3 +5,4 @@ export const MOCK_DIR = path.join(__dirname, "..", "mock");
export const DATA_DIR = path.join(__dirname, "..", "data"); export const DATA_DIR = path.join(__dirname, "..", "data");
export const DB_FILE = path.join(DATA_DIR, "mock-mappings.sqlite3"); export const DB_FILE = path.join(DATA_DIR, "mock-mappings.sqlite3");
export const LEGACY_DB_FILE = path.join(MOCK_DIR, "mock-mappings.sqlite3"); export const LEGACY_DB_FILE = path.join(MOCK_DIR, "mock-mappings.sqlite3");
export const ADMIN_LIST_FILE = path.join(__dirname, "..", "admin_list.txt");
+199 -2
View File
@@ -7,11 +7,15 @@ import type {
ApiListItem, ApiListItem,
AppConfig, AppConfig,
MockFileRow, MockFileRow,
MockGroupRow,
RouteApiNameMap, RouteApiNameMap,
RouteConfig, RouteConfig,
RouteEnabledMap, RouteEnabledMap,
RouteRow, RouteRow,
RouteStatusConfig, RouteStatusConfig,
IpRule,
IpRuleRow,
IpRuleConfig,
} from "./types"; } from "./types";
export function dbRun(sql: string, params: unknown[] = []): Promise<void> { export function dbRun(sql: string, params: unknown[] = []): Promise<void> {
@@ -53,11 +57,22 @@ export function openDatabase(): Promise<void> {
}); });
} }
async function tableExists(name: string): Promise<boolean> {
const rows = await dbAll<{ cnt: number }>(
"SELECT COUNT(*) AS cnt FROM sqlite_master WHERE type='table' AND name=?",
[name],
);
return (rows[0]?.cnt ?? 0) > 0;
}
export async function initDatabase(): Promise<void> { export async function initDatabase(): Promise<void> {
fs.mkdirSync(MOCK_DIR, { recursive: true }); fs.mkdirSync(MOCK_DIR, { recursive: true });
fs.mkdirSync(DATA_DIR, { recursive: true }); fs.mkdirSync(DATA_DIR, { recursive: true });
if (!fs.existsSync(DB_FILE) && fs.existsSync(LEGACY_DB_FILE)) { if (!fs.existsSync(DB_FILE) && fs.existsSync(LEGACY_DB_FILE)) {
fs.copyFileSync(LEGACY_DB_FILE, DB_FILE); fs.copyFileSync(LEGACY_DB_FILE, DB_FILE);
console.log(
`[DB] 已从旧路径迁移数据库: ${LEGACY_DB_FILE} -> ${DB_FILE}`,
);
} }
await openDatabase(); await openDatabase();
await dbRun(` await dbRun(`
@@ -100,6 +115,12 @@ export async function initDatabase(): Promise<void> {
name TEXT NOT NULL name TEXT NOT NULL
) )
`); `);
await dbRun(`
CREATE TABLE IF NOT EXISTS mock_groups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE
)
`);
await dbRun(` await dbRun(`
CREATE TABLE IF NOT EXISTS mock_files ( CREATE TABLE IF NOT EXISTS mock_files (
file_path TEXT PRIMARY KEY, file_path TEXT PRIMARY KEY,
@@ -111,13 +132,35 @@ export async function initDatabase(): Promise<void> {
).catch(() => { ).catch(() => {
// ignore when column already exists // ignore when column already exists
}); });
await dbRun(
"ALTER TABLE mock_files ADD COLUMN group_id INTEGER",
).catch(() => {
// ignore when column already exists
});
await dbRun(` await dbRun(`
CREATE TABLE IF NOT EXISTS server_config ( CREATE TABLE IF NOT EXISTS server_config (
key TEXT PRIMARY KEY, key TEXT PRIMARY KEY,
value TEXT NOT NULL value TEXT NOT NULL
) )
`); `);
// 清理不该出现在 mock 列表中的系统文件 const hadIpRules = await tableExists("ip_rules");
await dbRun(`
CREATE TABLE IF NOT EXISTS ip_rules (
ip TEXT PRIMARY KEY,
blocked INTEGER NOT NULL DEFAULT 0,
remark TEXT NOT NULL DEFAULT '',
use_custom_config INTEGER NOT NULL DEFAULT 0,
mock_enabled INTEGER,
default_content_type TEXT,
target_host TEXT,
target_port INTEGER,
target_https INTEGER
)
`);
if (!hadIpRules) {
console.log("[DB] 数据库已自动升级: 新增 IP 管理(ip_rules)表");
}
// 清理不该出现在 mock 列表中的系统数据
await dbRun( await dbRun(
"DELETE FROM mock_files WHERE file_path = ? OR file_path LIKE ?", "DELETE FROM mock_files WHERE file_path = ? OR file_path LIKE ?",
["mock/api-list.json", "%.sqlite3"], ["mock/api-list.json", "%.sqlite3"],
@@ -211,8 +254,16 @@ export async function deleteApiItemFromDb(route: string): Promise<void> {
export async function upsertMockFilePathToDb( export async function upsertMockFilePathToDb(
filePath: string, filePath: string,
alias?: string, alias?: string,
groupId?: number | null,
): Promise<void> { ): Promise<void> {
if (typeof alias === "string") { if (typeof alias === "string") {
if (typeof groupId !== "undefined") {
await dbRun(
"INSERT INTO mock_files(file_path, alias, group_id) VALUES(?, ?, ?) ON CONFLICT(file_path) DO UPDATE SET alias = excluded.alias, group_id = excluded.group_id",
[filePath, alias, groupId ?? null],
);
return;
}
await dbRun( await dbRun(
"INSERT INTO mock_files(file_path, alias) VALUES(?, ?) ON CONFLICT(file_path) DO UPDATE SET alias = excluded.alias", "INSERT INTO mock_files(file_path, alias) VALUES(?, ?) ON CONFLICT(file_path) DO UPDATE SET alias = excluded.alias",
[filePath, alias], [filePath, alias],
@@ -230,14 +281,75 @@ export async function removeMockFilePathFromDb(filePath: string): Promise<void>
export async function loadMockFilePathsFromDb(): Promise<MockFileRow[]> { export async function loadMockFilePathsFromDb(): Promise<MockFileRow[]> {
const rows = await dbAll<MockFileRow>( const rows = await dbAll<MockFileRow>(
"SELECT file_path, alias FROM mock_files ORDER BY file_path ASC", "SELECT file_path, alias, group_id FROM mock_files ORDER BY file_path ASC",
); );
return rows.map((row) => ({ return rows.map((row) => ({
file_path: row.file_path, file_path: row.file_path,
alias: String(row.alias || ""), alias: String(row.alias || ""),
group_id: row.group_id ?? null,
})); }));
} }
// ── mock_groups CRUD ──
export async function loadMockGroups(): Promise<MockGroupRow[]> {
const rows = await dbAll<MockGroupRow>(
"SELECT id, name FROM mock_groups ORDER BY id ASC",
);
return rows.map((row) => ({ id: row.id, name: row.name }));
}
export async function insertMockGroup(name: string): Promise<number> {
await dbRun("INSERT INTO mock_groups(name) VALUES(?)", [name]);
const row = await dbAll<{ id: number }>(
"SELECT id FROM mock_groups WHERE name = ?",
[name],
);
return row[0]?.id ?? 0;
}
export async function updateMockGroup(
id: number,
name: string,
): Promise<void> {
await dbRun("UPDATE mock_groups SET name = ? WHERE id = ?", [name, id]);
}
export async function deleteMockGroup(id: number): Promise<void> {
await dbRun("DELETE FROM mock_groups WHERE id = ?", [id]);
}
export async function countMockFilesByGroup(
groupId: number,
): Promise<number> {
const rows = await dbAll<{ cnt: number }>(
"SELECT COUNT(*) AS cnt FROM mock_files WHERE group_id = ?",
[groupId],
);
return rows[0]?.cnt ?? 0;
}
export async function updateMockFilesGroupId(
oldGroupId: number,
newGroupId: number | null,
): Promise<void> {
await dbRun("UPDATE mock_files SET group_id = ? WHERE group_id = ?", [
newGroupId,
oldGroupId,
]);
}
export async function deleteMockFilesByGroup(
groupId: number,
): Promise<MockFileRow[]> {
const rows = await dbAll<MockFileRow>(
"SELECT file_path FROM mock_files WHERE group_id = ?",
[groupId],
);
await dbRun("DELETE FROM mock_files WHERE group_id = ?", [groupId]);
return rows.map((row) => ({ file_path: row.file_path, alias: "", group_id: null }));
}
const DEFAULT_SERVER_CONFIG: AppConfig = { const DEFAULT_SERVER_CONFIG: AppConfig = {
cacheConfig: true, cacheConfig: true,
reloadOnChange: true, reloadOnChange: true,
@@ -291,3 +403,88 @@ export async function saveServerConfig(config: AppConfig): Promise<void> {
]); ]);
} }
} }
function rowToIpRule(row: IpRuleRow): IpRule {
const config: IpRuleConfig = {};
if (row.mock_enabled != null) {
config.mockEnabled = row.mock_enabled !== 0;
}
if (row.default_content_type) {
config.defaultContentType = row.default_content_type;
}
if (row.target_host) {
config.targetHost = row.target_host;
}
if (row.target_port != null) {
config.targetPort = row.target_port;
}
if (row.target_https != null) {
config.targetHttps = row.target_https !== 0;
}
return {
ip: row.ip,
blocked: row.blocked !== 0,
remark: row.remark || "",
useCustomConfig: row.use_custom_config !== 0,
config,
};
}
export async function loadIpRulesFromDb(): Promise<IpRule[]> {
const rows = await dbAll<IpRuleRow>(
"SELECT ip, blocked, remark, use_custom_config, mock_enabled, default_content_type, target_host, target_port, target_https FROM ip_rules ORDER BY ip ASC",
);
return rows.map(rowToIpRule);
}
export async function upsertIpRuleToDb(rule: IpRule): Promise<void> {
const mockEnabled =
rule.config.mockEnabled !== undefined
? rule.config.mockEnabled
? 1
: 0
: null;
const targetHttps =
rule.config.targetHttps !== undefined
? rule.config.targetHttps
? 1
: 0
: null;
await dbRun(
`INSERT INTO ip_rules(
ip, blocked, remark, use_custom_config,
mock_enabled, default_content_type, target_host, target_port, target_https
) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(ip) DO UPDATE SET
blocked = excluded.blocked,
remark = excluded.remark,
use_custom_config = excluded.use_custom_config,
mock_enabled = excluded.mock_enabled,
default_content_type = excluded.default_content_type,
target_host = excluded.target_host,
target_port = excluded.target_port,
target_https = excluded.target_https`,
[
rule.ip,
rule.blocked ? 1 : 0,
rule.remark || "",
rule.useCustomConfig ? 1 : 0,
mockEnabled,
rule.config.defaultContentType || null,
rule.config.targetHost || null,
rule.config.targetPort ?? null,
targetHttps,
],
);
}
export async function deleteIpRuleFromDb(ip: string): Promise<void> {
await dbRun("DELETE FROM ip_rules WHERE ip = ?", [ip]);
}
export async function saveAllIpRulesToDb(rules: IpRule[]): Promise<void> {
await dbRun("DELETE FROM ip_rules");
for (const rule of rules) {
await upsertIpRuleToDb(rule);
}
}
+222
View File
@@ -0,0 +1,222 @@
import * as http from "http";
import * as os from "os";
import { state } from "./state";
import type { AppConfig, IpRule, IpRuleConfig } from "./types";
export function normalizeIp(raw: string): string {
let ip = raw.trim();
if (ip.startsWith("::ffff:")) {
ip = ip.slice(7);
}
if (ip === "::1") {
return "127.0.0.1";
}
return ip;
}
export function getClientIp(req: http.IncomingMessage): string {
const forwarded = req.headers["x-forwarded-for"];
if (forwarded) {
const first = String(
Array.isArray(forwarded) ? forwarded[0] : forwarded,
)
.split(",")[0]
.trim();
if (first) {
return normalizeIp(first);
}
}
const realIp = req.headers["x-real-ip"];
if (realIp) {
const value = String(Array.isArray(realIp) ? realIp[0] : realIp).trim();
if (value) {
return normalizeIp(value);
}
}
const remote = req.socket.remoteAddress || "";
return normalizeIp(remote);
}
function getIpv4Subnet24(ip: string): string | undefined {
const parts = ip.split(".");
if (parts.length !== 4) {
return undefined;
}
return `${parts[0]}.${parts[1]}.${parts[2]}`;
}
/** 本机非回环 IPv4 地址,用于 localhost 访问时的规则回退 */
export function getMachineLanIpv4Addresses(): string[] {
const ips = new Set<string>();
const interfaces = os.networkInterfaces();
for (const addrs of Object.values(interfaces)) {
if (!addrs) continue;
for (const addr of addrs) {
const family = String(addr.family);
if (family === "IPv4" && !addr.internal) {
ips.add(normalizeIp(addr.address));
}
}
}
return Array.from(ips).sort();
}
/**
* localhost 访问时将 127.0.0.1 映射为本机 LAN IPv4。
* hints 用于在多个网卡时优先选择(如白名单、IP 规则中已配置的地址)。
*/
export function resolveLocalhostToLanIp(hints: string[] = []): string | undefined {
const lanIps = getMachineLanIpv4Addresses();
if (lanIps.length === 0) {
return undefined;
}
if (lanIps.length === 1) {
return lanIps[0];
}
const hintSet = new Set(hints.map(normalizeIp));
if (hintSet.size > 0) {
const matched = lanIps.filter((ip) => hintSet.has(normalizeIp(ip)));
if (matched.length === 1) {
return matched[0];
}
if (matched.length > 1) {
return matched.sort()[0];
}
const hintSubnets = new Set(
[...hintSet]
.map(getIpv4Subnet24)
.filter((subnet): subnet is string => !!subnet),
);
if (hintSubnets.size > 0) {
const sameSubnet = lanIps.filter((ip) => {
const subnet = getIpv4Subnet24(ip);
return subnet ? hintSubnets.has(subnet) : false;
});
if (sameSubnet.length === 1) {
return sameSubnet[0];
}
if (sameSubnet.length > 1) {
return sameSubnet.sort()[0];
}
}
}
const ruleLanIps = state.ipRules
.map((rule) => normalizeIp(rule.ip))
.filter((ip) => lanIps.includes(ip));
if (ruleLanIps.length === 1) {
return ruleLanIps[0];
}
const private192 = lanIps.filter((ip) => ip.startsWith("192.168."));
if (private192.length >= 1) {
return private192.sort()[0];
}
return lanIps[0];
}
/** 解析用于展示与策略匹配的客户端 IP(localhost → LAN IPv4) */
export function resolveClientIp(
req: http.IncomingMessage,
hints: string[] = [],
): string {
const raw = normalizeIp(getClientIp(req));
if (raw !== "127.0.0.1") {
return raw;
}
return resolveLocalhostToLanIp(hints) ?? raw;
}
export function findIpRule(clientIp: string): IpRule | undefined {
const normalized = normalizeIp(clientIp);
return state.ipRules.find(
(rule) => normalizeIp(rule.ip) === normalized,
);
}
export function mergeConfigWithIpRule(
baseConfig: AppConfig,
ruleConfig: IpRuleConfig,
): AppConfig {
return {
...baseConfig,
mockEnabled:
ruleConfig.mockEnabled !== undefined
? ruleConfig.mockEnabled
: baseConfig.mockEnabled,
defaultContentType:
ruleConfig.defaultContentType || baseConfig.defaultContentType,
targetHost: ruleConfig.targetHost || baseConfig.targetHost,
targetPort:
ruleConfig.targetPort !== undefined
? ruleConfig.targetPort
: baseConfig.targetPort,
targetHttps:
ruleConfig.targetHttps !== undefined
? ruleConfig.targetHttps
: baseConfig.targetHttps,
};
}
export type EffectiveConfigResult =
| { blocked: true; ip: string; matchedRule?: IpRule }
| {
blocked: false;
config: AppConfig;
ip: string;
matchedRule?: IpRule;
ruleMatchedViaLocalhost?: boolean;
};
export function resolveEffectiveConfig(
req: http.IncomingMessage,
): EffectiveConfigResult {
const rawIp = normalizeIp(getClientIp(req));
const hintIps = state.ipRules.map((rule) => rule.ip);
const ip = resolveClientIp(req, hintIps);
const rule = findIpRule(ip);
const ruleMatchedViaLocalhost =
rawIp === "127.0.0.1" && !!rule && normalizeIp(rule.ip) !== rawIp;
if (rule?.blocked) {
return { blocked: true, ip, matchedRule: rule };
}
if (rule?.useCustomConfig) {
return {
blocked: false,
config: mergeConfigWithIpRule(state.config, rule.config),
ip,
matchedRule: rule,
ruleMatchedViaLocalhost,
};
}
return { blocked: false, config: state.config, ip };
}
export function formatTargetSummary(config: AppConfig): string {
const https = config.targetHttps !== false;
const port =
config.targetPort != null
? config.targetPort
: https
? 443
: 80;
const proto = https ? "https" : "http";
const defaultPort = https ? 443 : 80;
const host = config.targetHost || "localhost";
return port === defaultPort
? `${proto}://${host}`
: `${proto}://${host}:${port}`;
}
export function isValidIpAddress(value: string): boolean {
const ip = value.trim();
if (!ip) return false;
const ipv4 =
/^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(ip);
if (ipv4) return true;
return /^[\da-fA-F:]+$/.test(ip) && ip.includes(":");
}
+2 -1
View File
@@ -63,7 +63,7 @@ export async function loadMockFiles(): Promise<MockFileItem[]> {
for (const filePath of fsFiles) { for (const filePath of fsFiles) {
await upsertMockFilePathToDb(filePath); await upsertMockFilePathToDb(filePath);
} }
files = fsFiles.map((filePath) => ({ file_path: filePath, alias: "" })); files = fsFiles.map((filePath) => ({ file_path: filePath, alias: "", group_id: null }));
} }
const result: MockFileItem[] = []; const result: MockFileItem[] = [];
@@ -75,6 +75,7 @@ export async function loadMockFiles(): Promise<MockFileItem[]> {
filePath, filePath,
alias: String(item.alias || ""), alias: String(item.alias || ""),
content: fs.readFileSync(fullPath, "utf-8"), content: fs.readFileSync(fullPath, "utf-8"),
groupId: item.group_id ?? null,
}); });
} }
return result; return result;
+62 -28
View File
@@ -3,32 +3,50 @@ import * as http from "http";
import * as https from "https"; import * as https from "https";
import * as path from "path"; import * as path from "path";
import { dispatchAdmin } from "./admin-handlers"; import { dispatchAdmin } from "./admin-handlers";
import { resolveEffectiveConfig, formatTargetSummary } from "./ip-rules";
import { import {
getMockFilePath, getMockFilePath,
getMockStatusCode, getMockStatusCode,
isMockRoute, isMockRoute,
} from "./route-matching"; } from "./route-matching";
import { state } from "./state"; import { state } from "./state";
import type { AppConfig } from "./types";
import { decodeBodyByEncoding } from "./utils"; import { decodeBodyByEncoding } from "./utils";
function isTargetHttps(): boolean { function isTargetHttps(config: AppConfig): boolean {
return state.config.targetHttps !== false; return config.targetHttps !== false;
} }
function getTargetPort(): number { function getTargetPort(config: AppConfig): number {
if (state.config.targetPort != null) return state.config.targetPort; if (config.targetPort != null) return config.targetPort;
return isTargetHttps() ? 443 : 80; return isTargetHttps(config) ? 443 : 80;
} }
function upstreamRequest( function upstreamRequest(
options: http.RequestOptions, options: http.RequestOptions,
useHttps: boolean,
callback: (proxyRes: http.IncomingMessage) => void, callback: (proxyRes: http.IncomingMessage) => void,
): http.ClientRequest { ): http.ClientRequest {
return isTargetHttps() return useHttps
? https.request(options, callback) ? https.request(options, callback)
: http.request(options, callback); : http.request(options, callback);
} }
function handleBlockedIp(
clientRes: http.ServerResponse,
ip: string,
): void {
clientRes.writeHead(403, { "Content-Type": "application/json" });
clientRes.end(
JSON.stringify({
error: "Access denied",
message: "Your IP address is blocked",
ip,
timestamp: new Date().toISOString(),
}),
);
}
export function createProxyServer(): http.Server { export function createProxyServer(): http.Server {
return http.createServer(async (clientReq, clientRes) => { return http.createServer(async (clientReq, clientRes) => {
const parsedUrl = new URL(`http://localhost${clientReq.url!}`); const parsedUrl = new URL(`http://localhost${clientReq.url!}`);
@@ -38,34 +56,46 @@ export function createProxyServer(): http.Server {
const handled = await dispatchAdmin(requestPath, clientReq, clientRes); const handled = await dispatchAdmin(requestPath, clientReq, clientRes);
if (handled) return; if (handled) return;
const effective = resolveEffectiveConfig(clientReq);
if (effective.blocked) {
console.log(`[IP] 拒绝访问: ${effective.ip}`);
handleBlockedIp(clientRes, effective.ip);
return;
}
const effectiveConfig = effective.config;
// 检查是否为需要mock的路由 // 检查是否为需要mock的路由
if (isMockRoute(requestPath)) { if (isMockRoute(requestPath, effectiveConfig)) {
const mockFile = getMockFilePath(requestPath); const mockFile = getMockFilePath(requestPath);
const mockStatusCode = getMockStatusCode(requestPath); const mockStatusCode = getMockStatusCode(requestPath);
console.log(`[MOCK] 拦截路由: ${requestPath} -> 使用文件: ${mockFile}`); console.log(
`[MOCK] 拦截路由: ${requestPath} -> 使用数据: ${mockFile} | 客户端IP: ${effective.ip}${effective.matchedRule ? ` | 规则: ${effective.matchedRule.ip}` : ""}${effective.ruleMatchedViaLocalhost ? " (localhost回退)" : ""}`,
);
try { try {
const mockFilePath = path.join(__dirname, "..", mockFile); const mockFilePath = path.join(__dirname, "..", mockFile);
// 检查文件是否存在 // 检查数据是否存在
if (!fs.existsSync(mockFilePath)) { if (!fs.existsSync(mockFilePath)) {
console.warn( console.warn(
`[MOCK] Mock文件不存在,回源并自动生成: ${mockFilePath}`, `[MOCK] Mock 数据不存在,回源并自动生成: ${mockFilePath}`,
); );
const targetPort = getTargetPort(); const targetPort = getTargetPort(effectiveConfig);
const useHttps = isTargetHttps(effectiveConfig);
const options: http.RequestOptions = { const options: http.RequestOptions = {
hostname: state.config.targetHost, hostname: effectiveConfig.targetHost,
port: targetPort, port: targetPort,
method: clientReq.method, method: clientReq.method,
path: parsedUrl.pathname + parsedUrl.search, path: parsedUrl.pathname + parsedUrl.search,
headers: { headers: {
...clientReq.headers, ...clientReq.headers,
host: state.config.targetHost, host: effectiveConfig.targetHost,
}, },
}; };
const proxyReq = upstreamRequest(options, (proxyRes) => { const proxyReq = upstreamRequest(options, useHttps, (proxyRes) => {
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
proxyRes.on("data", (chunk: Buffer) => { proxyRes.on("data", (chunk: Buffer) => {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
@@ -93,10 +123,10 @@ export function createProxyServer(): http.Server {
: decodedBuffer; : decodedBuffer;
fs.mkdirSync(path.dirname(mockFilePath), { recursive: true }); fs.mkdirSync(path.dirname(mockFilePath), { recursive: true });
fs.writeFileSync(mockFilePath, toWrite); fs.writeFileSync(mockFilePath, toWrite);
console.log(`[MOCK] 已自动写入mock文件: ${mockFilePath}`); console.log(`[MOCK] 已自动写入 Mock 数据数据: ${mockFilePath}`);
} catch (writeErr) { } catch (writeErr) {
console.error( console.error(
`[MOCK] 自动写入mock文件失败: ${mockFilePath}`, `[MOCK] 自动写入 Mock 数据数据失败: ${mockFilePath}`,
writeErr, writeErr,
); );
} }
@@ -104,7 +134,7 @@ export function createProxyServer(): http.Server {
clientRes.writeHead(mockStatusCode, { clientRes.writeHead(mockStatusCode, {
...proxyRes.headers, ...proxyRes.headers,
"X-Mock-Autogenerated": "true", "X-Mock-Autogenerated": "true",
"X-Mock-Source": mockFile, "X-Mock-Source": encodeURIComponent(mockFile),
"X-Mock-Status-Code": String(mockStatusCode), "X-Mock-Status-Code": String(mockStatusCode),
}); });
clientRes.end(bodyBuffer); clientRes.end(bodyBuffer);
@@ -129,18 +159,18 @@ export function createProxyServer(): http.Server {
return; return;
} }
// 读取本地mock文件 // 读取本地 Mock 数据数据
const mockData = fs.readFileSync(mockFilePath, "utf-8"); const mockData = fs.readFileSync(mockFilePath, "utf-8");
// 设置响应头 // 设置响应头
const contentType = const contentType =
state.config.defaultContentType || "application/json"; effectiveConfig.defaultContentType || "application/json";
clientRes.writeHead(mockStatusCode, { clientRes.writeHead(mockStatusCode, {
"Content-Type": contentType, "Content-Type": contentType,
"Access-Control-Allow-Origin": "*", "Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type", "Access-Control-Allow-Headers": "Content-Type",
"X-Mock-Source": mockFile, "X-Mock-Source": encodeURIComponent(mockFile),
"X-Mock-Status-Code": String(mockStatusCode), "X-Mock-Status-Code": String(mockStatusCode),
"X-Mock-Timestamp": new Date().toISOString(), "X-Mock-Timestamp": new Date().toISOString(),
}); });
@@ -149,7 +179,7 @@ export function createProxyServer(): http.Server {
clientRes.end(mockData); clientRes.end(mockData);
console.log(`[MOCK] 成功返回mock数据: ${mockFile}`); console.log(`[MOCK] 成功返回mock数据: ${mockFile}`);
} catch (error) { } catch (error) {
console.error(`[MOCK] 读取mock文件失败: ${mockFile}`, error); console.error(`[MOCK] 读取 Mock 数据数据失败: ${mockFile}`, error);
clientRes.writeHead(500, { "Content-Type": "application/json" }); clientRes.writeHead(500, { "Content-Type": "application/json" });
clientRes.end( clientRes.end(
JSON.stringify({ JSON.stringify({
@@ -165,22 +195,26 @@ export function createProxyServer(): http.Server {
} }
// 如果不是mock路由,正常代理转发 // 如果不是mock路由,正常代理转发
console.log(`[PROXY] 转发请求: ${requestPath}`); const targetSummary = formatTargetSummary(effectiveConfig);
console.log(
`[PROXY] 转发请求: ${requestPath} | 客户端IP: ${effective.ip} -> ${targetSummary}${effective.matchedRule ? ` | 规则: ${effective.matchedRule.ip}${effective.matchedRule.remark ? "/" + effective.matchedRule.remark : ""}` : " | 全局配置"}${effective.ruleMatchedViaLocalhost ? " (localhost回退)" : ""}`,
);
const targetPort = getTargetPort(); const targetPort = getTargetPort(effectiveConfig);
const useHttps = isTargetHttps(effectiveConfig);
const options: http.RequestOptions = { const options: http.RequestOptions = {
hostname: state.config.targetHost, hostname: effectiveConfig.targetHost,
port: targetPort, port: targetPort,
method: clientReq.method, method: clientReq.method,
path: parsedUrl.pathname + parsedUrl.search, path: parsedUrl.pathname + parsedUrl.search,
headers: { headers: {
...clientReq.headers, ...clientReq.headers,
host: state.config.targetHost, host: effectiveConfig.targetHost,
}, },
}; };
const proxyReq = upstreamRequest(options, (proxyRes) => { const proxyReq = upstreamRequest(options, useHttps, (proxyRes) => {
clientRes.writeHead(proxyRes.statusCode!, proxyRes.headers); clientRes.writeHead(proxyRes.statusCode!, proxyRes.headers);
proxyRes.pipe(clientRes); proxyRes.pipe(clientRes);
}); });
@@ -203,9 +237,9 @@ export function createProxyServer(): http.Server {
export function getEffectiveTargetPort(): number { export function getEffectiveTargetPort(): number {
if (state.config.targetPort != null) return state.config.targetPort; if (state.config.targetPort != null) return state.config.targetPort;
return isTargetHttps() ? 443 : 80; return state.config.targetHttps !== false ? 443 : 80;
} }
export function getEffectiveTargetHttps(): boolean { export function getEffectiveTargetHttps(): boolean {
return isTargetHttps(); return state.config.targetHttps !== false;
} }
+11 -3
View File
@@ -1,14 +1,22 @@
import { state } from "./state"; import { state } from "./state";
import { normalizeStatusCode } from "./utils"; import { normalizeStatusCode } from "./utils";
import type { AppConfig } from "./types";
function isMockEnabled(config: AppConfig): boolean {
return config.mockEnabled !== false;
}
// 检查是否为mock路由的函数 // 检查是否为mock路由的函数
export function isMockRoute(requestPath: string): boolean { export function isMockRoute(
if (state.config.mockEnabled === false) return false; requestPath: string,
config: AppConfig = state.config,
): boolean {
if (!isMockEnabled(config)) return false;
if (!state.rawRoutes.hasOwnProperty(requestPath)) return false; if (!state.rawRoutes.hasOwnProperty(requestPath)) return false;
return state.routeEnabledMap[requestPath] !== false; return state.routeEnabledMap[requestPath] !== false;
} }
// 获取mock文件路径 // 获取mock数据路径
export function getMockFilePath(requestPath: string): string { export function getMockFilePath(requestPath: string): string {
return state.rawRoutes[requestPath]; return state.rawRoutes[requestPath];
} }
+2 -1
View File
@@ -1,5 +1,5 @@
import type sqlite3 from "sqlite3"; import type sqlite3 from "sqlite3";
import type { AppConfig, RouteApiNameMap, RouteConfig, RouteEnabledMap, RouteStatusConfig } from "./types"; import type { AppConfig, IpRule, RouteApiNameMap, RouteConfig, RouteEnabledMap, RouteStatusConfig } from "./types";
export const state = { export const state = {
rawRoutes: {} as RouteConfig, rawRoutes: {} as RouteConfig,
@@ -15,4 +15,5 @@ export const state = {
targetPort: 443, targetPort: 443,
} as AppConfig, } as AppConfig,
db: null as unknown as sqlite3.Database, db: null as unknown as sqlite3.Database,
ipRules: [] as IpRule[],
}; };
+36
View File
@@ -35,6 +35,7 @@ export interface MockFileItem {
filePath: string; filePath: string;
alias: string; alias: string;
content: string; content: string;
groupId: number | null;
} }
export interface RouteRow { export interface RouteRow {
@@ -53,7 +54,42 @@ export interface RouteApiNameMap {
[route: string]: string; [route: string]: string;
} }
export interface MockGroupRow {
id: number;
name: string;
}
export interface MockFileRow { export interface MockFileRow {
file_path: string; file_path: string;
alias: string; alias: string;
group_id: number | null;
}
/** 单 IP 可覆盖的服务端配置(不含 proxyPort) */
export interface IpRuleConfig {
mockEnabled?: boolean;
defaultContentType?: string;
targetHost?: string;
targetPort?: number;
targetHttps?: boolean;
}
export interface IpRule {
ip: string;
blocked: boolean;
remark: string;
useCustomConfig: boolean;
config: IpRuleConfig;
}
export interface IpRuleRow {
ip: string;
blocked: number;
remark: string;
use_custom_config: number;
mock_enabled: number | null;
default_content_type: string | null;
target_host: string | null;
target_port: number | null;
target_https: number | null;
} }
+1 -1
View File
@@ -37,7 +37,7 @@ export function decodeBodyByEncoding(
return zlib.inflateSync(bodyBuffer); return zlib.inflateSync(bodyBuffer);
} }
} catch (error) { } catch (error) {
console.warn("[MOCK] 解压上游响应失败,按原始内容写入文件", error); console.warn("[MOCK] 解压上游响应失败,按原始内容写入数据", error);
} }
return bodyBuffer; return bodyBuffer;
} }
+454
View File
@@ -0,0 +1,454 @@
import * as crypto from "crypto";
import type { IncomingMessage, Server } from "http";
import type { Duplex } from "stream";
import { resolveAdminClientIp } from "./admin-list";
import { normalizeIp } from "./ip-rules";
import { state } from "./state";
/** WebSocket 升级路径(与管理接口同级,不参与代理转发) */
export const WS_PATH = "/__ws";
const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
const HEARTBEAT_INTERVAL_MS = 30000;
const MAX_FRAME_PAYLOAD = 2 * 1024 * 1024;
const OPCODE_CONTINUATION = 0x0;
const OPCODE_TEXT = 0x1;
const OPCODE_BINARY = 0x2;
const OPCODE_CLOSE = 0x8;
const OPCODE_PING = 0x9;
const OPCODE_PONG = 0xa;
/** 变更涉及的资源类型,前端据此决定刷新哪一块数据 */
export type MutationResource =
| "routes"
| "config"
| "api-list"
| "mock-files"
| "mock-groups"
| "ip-rules";
export type MutationAction = "create" | "update" | "delete";
interface WsClient {
/** 服务端会话唯一 id */
id: string;
/** 浏览器端标签页 id(用于回声抑制,不回推给发起方) */
cid: string;
socket: Duplex;
ip: string;
name: string;
connectedAt: number;
alive: boolean;
buffer: Buffer;
fragmentOpcode: number;
fragments: Buffer[];
closed: boolean;
}
interface PresenceClient {
id: string;
cid: string;
ip: string;
name: string;
/** 个性化配置中的备注,没有则为空串 */
remark: string;
connectedAt: number;
}
const clients = new Map<string, WsClient>();
let heartbeatTimer: NodeJS.Timeout | null = null;
function encodeFrame(opcode: number, payload: Buffer): Buffer {
const length = payload.length;
let header: Buffer;
if (length < 126) {
header = Buffer.alloc(2);
header[1] = length;
} else if (length < 65536) {
header = Buffer.alloc(4);
header[1] = 126;
header.writeUInt16BE(length, 2);
} else {
header = Buffer.alloc(10);
header[1] = 127;
header.writeBigUInt64BE(BigInt(length), 2);
}
header[0] = 0x80 | opcode;
return Buffer.concat([header, payload]);
}
function writeFrame(client: WsClient, opcode: number, payload: Buffer): void {
if (client.closed) return;
try {
client.socket.write(encodeFrame(opcode, payload));
} catch (error) {
console.warn(`[WS] 写入失败,断开客户端 ${client.ip}:`, (error as Error).message);
removeClient(client);
}
}
function sendJson(client: WsClient, data: unknown): void {
writeFrame(client, OPCODE_TEXT, Buffer.from(JSON.stringify(data), "utf-8"));
}
function presenceList(): PresenceClient[] {
return Array.from(clients.values()).map((client) => ({
id: client.id,
cid: client.cid,
ip: client.ip,
name: client.name,
remark: resolveActorRemark(client.ip),
connectedAt: client.connectedAt,
}));
}
/** 按 IP 查「个性化配置」里的备注,作为通知中的展示名 */
export function resolveActorRemark(ip: string): string {
if (!ip) return "";
const target = normalizeIp(ip);
const matched = state.ipRules.find(
(rule) => normalizeIp(rule.ip) === target && (rule.remark || "").trim(),
);
return matched ? String(matched.remark).trim() : "";
}
function presenceMessage(): Record<string, unknown> {
return {
type: "online",
online: clients.size,
clients: presenceList(),
ts: Date.now(),
};
}
/** 广播任意消息;excludeCid 用于跳过变更发起方所在的标签页 */
function broadcast(payload: unknown, excludeCid?: string): void {
const frame = Buffer.from(JSON.stringify(payload), "utf-8");
for (const client of Array.from(clients.values())) {
if (excludeCid && client.cid === excludeCid) continue;
writeFrame(client, OPCODE_TEXT, frame);
}
}
function broadcastPresence(): void {
broadcast(presenceMessage());
}
function removeClient(client: WsClient): void {
if (client.closed) return;
client.closed = true;
const existed = clients.delete(client.id);
try {
client.socket.destroy();
} catch {
// 忽略销毁异常
}
if (existed) {
console.log(`[WS] 客户端断开: ${client.ip} (在线 ${clients.size})`);
broadcastPresence();
}
}
function closeWithReason(client: WsClient, code: number, reason: string): void {
if (client.closed) return;
const body = Buffer.alloc(2 + Buffer.byteLength(reason, "utf-8"));
body.writeUInt16BE(code, 0);
body.write(reason, 2, "utf-8");
writeFrame(client, OPCODE_CLOSE, body);
removeClient(client);
}
function handleText(client: WsClient, text: string): void {
let message: Record<string, unknown>;
try {
const parsed: unknown = JSON.parse(text);
if (!parsed || typeof parsed !== "object") return;
message = parsed as Record<string, unknown>;
} catch {
return;
}
if (message.type === "ping") {
client.alive = true;
sendJson(client, { type: "pong", ts: Date.now() });
return;
}
if (message.type === "rename" && typeof message.name === "string") {
client.name = message.name.trim().slice(0, 40);
broadcastPresence();
return;
}
if (message.type === "whoami") {
sendJson(client, {
...presenceMessage(),
type: "welcome",
clientId: client.id,
cid: client.cid,
});
}
}
function handleFrame(
client: WsClient,
fin: boolean,
opcode: number,
payload: Buffer,
): void {
if (opcode === OPCODE_CLOSE) {
closeWithReason(client, 1000, "bye");
return;
}
if (opcode === OPCODE_PING) {
writeFrame(client, OPCODE_PONG, payload);
return;
}
if (opcode === OPCODE_PONG) {
client.alive = true;
return;
}
let data: Buffer;
if (opcode === OPCODE_CONTINUATION) {
client.fragments.push(payload);
if (!fin) return;
data = Buffer.concat(client.fragments);
opcode = client.fragmentOpcode;
client.fragments = [];
client.fragmentOpcode = 0;
} else if (!fin) {
client.fragmentOpcode = opcode;
client.fragments = [payload];
return;
} else {
data = payload;
}
if (opcode === OPCODE_TEXT) {
handleText(client, data.toString("utf-8"));
}
}
/** 从累积缓冲区中按帧循环解析,遇到不完整帧时保留剩余数据等待下一批 */
function consumeBuffer(client: WsClient): void {
for (;;) {
if (client.closed) return;
const buf = client.buffer;
if (buf.length < 2) return;
const fin = (buf[0] & 0x80) !== 0;
const opcode = buf[0] & 0x0f;
const masked = (buf[1] & 0x80) !== 0;
let payloadLength = buf[1] & 0x7f;
let offset = 2;
if (payloadLength === 126) {
if (buf.length < offset + 2) return;
payloadLength = buf.readUInt16BE(offset);
offset += 2;
} else if (payloadLength === 127) {
if (buf.length < offset + 8) return;
const big = buf.readBigUInt64BE(offset);
offset += 8;
if (big > BigInt(MAX_FRAME_PAYLOAD)) {
closeWithReason(client, 1009, "frame too large");
return;
}
payloadLength = Number(big);
}
if (payloadLength > MAX_FRAME_PAYLOAD) {
closeWithReason(client, 1009, "frame too large");
return;
}
let maskKey: Buffer | null = null;
if (masked) {
if (buf.length < offset + 4) return;
maskKey = buf.subarray(offset, offset + 4);
offset += 4;
}
if (buf.length < offset + payloadLength) return;
const payload = Buffer.from(buf.subarray(offset, offset + payloadLength));
client.buffer = Buffer.from(buf.subarray(offset + payloadLength));
if (maskKey) {
for (let i = 0; i < payload.length; i++) {
payload[i] ^= maskKey[i % 4];
}
}
handleFrame(client, fin, opcode, payload);
}
}
function startHeartbeat(): void {
if (heartbeatTimer) return;
heartbeatTimer = setInterval(() => {
for (const client of Array.from(clients.values())) {
if (!client.alive) {
removeClient(client);
continue;
}
client.alive = false;
writeFrame(client, OPCODE_PING, Buffer.alloc(0));
}
}, HEARTBEAT_INTERVAL_MS);
if (typeof heartbeatTimer.unref === "function") {
heartbeatTimer.unref();
}
}
function getHeaderValue(req: IncomingMessage, name: string): string {
const raw = req.headers[name];
if (!raw) return "";
const value = Array.isArray(raw) ? raw[0] : raw;
return String(value || "").trim();
}
function handleUpgrade(req: IncomingMessage, socket: Duplex): void {
let pathname = "/";
let cid = "";
try {
const url = new URL(req.url || "/", `http://${req.headers.host || "localhost"}`);
pathname = url.pathname;
cid = (url.searchParams.get("cid") || "").trim();
} catch {
pathname = "/";
}
if (pathname !== WS_PATH) {
socket.write("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n");
socket.destroy();
return;
}
const key = getHeaderValue(req, "sec-websocket-key");
if (!key) {
socket.write("HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n");
socket.destroy();
return;
}
const accept = crypto
.createHash("sha1")
.update(key + WS_GUID)
.digest("base64");
socket.write(
"HTTP/1.1 101 Switching Protocols\r\n" +
"Upgrade: websocket\r\n" +
"Connection: Upgrade\r\n" +
`Sec-WebSocket-Accept: ${accept}\r\n\r\n`,
);
const client: WsClient = {
id: crypto.randomUUID().slice(0, 8),
cid: cid || crypto.randomUUID(),
socket,
ip: resolveAdminClientIp(req),
name: "",
connectedAt: Date.now(),
alive: true,
buffer: Buffer.alloc(0),
fragmentOpcode: 0,
fragments: [],
closed: false,
};
clients.set(client.id, client);
socket.on("data", (chunk: Buffer) => {
if (client.closed) return;
const piece = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
client.buffer = client.buffer.length
? Buffer.concat([client.buffer, piece])
: piece;
consumeBuffer(client);
});
socket.on("error", () => removeClient(client));
socket.on("end", () => removeClient(client));
socket.on("close", () => removeClient(client));
sendJson(client, {
type: "welcome",
clientId: client.id,
cid: client.cid,
online: clients.size,
clients: presenceList(),
ts: Date.now(),
});
broadcastPresence();
startHeartbeat();
console.log(`[WS] 客户端连接: ${client.ip} (在线 ${clients.size})`);
}
/** 把 WebSocket 服务挂到已有的 HTTP server 上(复用同一端口) */
export function attachWebSocketServer(server: Server): void {
server.on("upgrade", (req: IncomingMessage, socket, head) => {
try {
if (head && head.length > 0) {
// 升级请求里附带的帧数据极少见,直接丢弃以免帧解析错位
console.warn("[WS] 升级请求携带了额外数据,已忽略", head.length);
}
handleUpgrade(req, socket as Duplex);
} catch (error) {
console.error("[WS] 升级连接失败:", error);
try {
socket.destroy();
} catch {
// ignore
}
}
});
}
export function getOnlineCount(): number {
return clients.size;
}
/** 在线客户端快照,供调试接口使用 */
export function getOnlineClients(): PresenceClient[] {
return presenceList();
}
/**
* 广播一条数据变更通知。
* 会跳过发起变更的标签页(通过请求头 x-client-id 匹配),其余客户端收到后自动刷新。
*/
export function broadcastMutation(
req: IncomingMessage | null,
resource: MutationResource,
action: MutationAction,
detail: string,
extra?: Record<string, unknown>,
): void {
if (clients.size === 0) return;
const cid = req ? getHeaderValue(req, "x-client-id") : "";
const ip = req ? resolveAdminClientIp(req) : "";
const remark = resolveActorRemark(ip);
const payload: Record<string, unknown> = {
type: "mutation",
resource,
action,
detail,
// name 为该 IP 个性化配置里的备注,未配置时回退为空串(前端再用 ip 展示)
actor: { ip, cid, name: remark, remark },
online: clients.size,
ts: Date.now(),
...(extra || {}),
};
broadcast(payload, cid || undefined);
console.log(
`[WS] 变更广播: ${resource}/${action} <- ${remark ? `${remark}(${ip || "unknown"})` : ip || "unknown"} (在线 ${clients.size})`,
);
}