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 路径保持不变)
This commit is contained in:
2026-11-26 15:45:42 +08:00
parent 3790ada0f1
commit 526bede19a
11 changed files with 1057 additions and 89 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 数据库
``` ```
+413 -44
View File
@@ -30,6 +30,10 @@
max-width: 1320px; max-width: 1320px;
margin: 0 auto; margin: 0 auto;
padding: 14px 16px; padding: 14px 16px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
} }
.top-nav-title { .top-nav-title {
font-size: 18px; font-size: 18px;
@@ -52,6 +56,12 @@
font-family: Consolas, Monaco, "Courier New", monospace; font-family: Consolas, Monaco, "Courier New", monospace;
line-height: 1.5; line-height: 1.5;
} }
.mock-editor-toolbar {
display: flex;
justify-content: flex-end;
align-items: center;
margin-bottom: 2px;
}
.el-dialog.is-fullscreen .el-dialog__body { .el-dialog.is-fullscreen .el-dialog__body {
overflow-y: auto; overflow-y: auto;
max-height: calc(100vh - 120px); max-height: calc(100vh - 120px);
@@ -60,6 +70,53 @@
pointer-events: none; pointer-events: none;
opacity: 0.65; opacity: 0.65;
} }
.ws-status {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
line-height: 1;
color: #67c23a;
background: #f0f9eb;
border: 1px solid #e1f3d8;
border-radius: 12px;
padding: 6px 12px;
white-space: nowrap;
user-select: none;
}
.ws-status-offline {
color: #e6a23c;
background: #fdf6ec;
border-color: #faecd8;
}
.ws-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.18);
animation: ws-pulse 1.8s ease-in-out infinite;
}
.ws-status-offline .ws-dot {
animation: none;
box-shadow: 0 0 0 2px rgba(230, 162, 60, 0.18);
}
@keyframes ws-pulse {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0.3;
}
}
.ws-online-list {
font-size: 12px;
line-height: 1.8;
}
.ws-online-list .ws-online-self {
color: #f0c78a;
}
</style> </style>
</head> </head>
<body> <body>
@@ -67,6 +124,25 @@
<div class="top-nav"> <div class="top-nav">
<div class="top-nav-inner"> <div class="top-nav-inner">
<span class="top-nav-title">企业级数据Mock管理系统</span> <span class="top-nav-title">企业级数据Mock管理系统</span>
<el-tooltip placement="bottom-end" effect="dark" :open-delay="200">
<div slot="content">
<div class="ws-online-list">
<div>当前共 {{ wsOnline }} 个页面在线</div>
<div
v-for="c in wsClients"
:key="c.id"
:class="{ 'ws-online-self': c.cid === wsClientId }"
>
· {{ getWsClientLabel(c) }}<span v-if="c.cid === wsClientId">(当前页面)</span>
</div>
</div>
</div>
<div class="ws-status" :class="{ 'ws-status-offline': !wsConnected }">
<span class="ws-dot"></span>
<span v-if="wsConnected">在线 {{ wsOnline }} 人</span>
<span v-else>连接中断,重连中…</span>
</div>
</el-tooltip>
</div> </div>
</div> </div>
<div class="container"> <div class="container">
@@ -92,7 +168,7 @@
<span>{{ scope.row.route }}</span> <span>{{ scope.row.route }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="Mock 文件" min-width="240" show-overflow-tooltip> <el-table-column label="Mock 数据" min-width="240" show-overflow-tooltip>
<template slot-scope="scope"> <template slot-scope="scope">
<a href="javascript:void(0)" style="color:#409EFF;cursor:pointer;" @click="openMockFileFromRoute(scope.row)">{{ getMockFileAlias(scope.row.filePath) }}</a> <a href="javascript:void(0)" style="color:#409EFF;cursor:pointer;" @click="openMockFileFromRoute(scope.row)">{{ getMockFileAlias(scope.row.filePath) }}</a>
</template> </template>
@@ -133,10 +209,10 @@
</el-card> </el-card>
</el-tab-pane> </el-tab-pane>
<el-tab-pane label="数据配置" name="mocks"> <el-tab-pane label="Mock 数据" name="mocks">
<el-card class="section-card"> <el-card class="section-card">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;"> <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
<strong>数据配置(mock)</strong> <strong>Mock 数据(mock)</strong>
<div style="display:flex;gap:8px;align-items:center;"> <div style="display:flex;gap:8px;align-items:center;">
<el-select size="small" v-model="mockGroupFilter" clearable placeholder="按分组筛选" style="width:160px;"> <el-select size="small" v-model="mockGroupFilter" clearable placeholder="按分组筛选" style="width:160px;">
<el-option label="全部" :value="null"></el-option> <el-option label="全部" :value="null"></el-option>
@@ -145,7 +221,7 @@
</el-select> </el-select>
<el-input size="small" v-model="mockFileSearch" placeholder="搜索别名或路径" clearable style="width:220px;" prefix-icon="el-icon-search"></el-input> <el-input size="small" v-model="mockFileSearch" placeholder="搜索别名或路径" clearable style="width:220px;" prefix-icon="el-icon-search"></el-input>
<el-button size="mini" icon="el-icon-refresh" :loading="mocksRefreshing" @click="refreshMocks">刷新</el-button> <el-button size="mini" icon="el-icon-refresh" :loading="mocksRefreshing" @click="refreshMocks">刷新</el-button>
<el-button size="mini" type="primary" @click="openMockFileDialogForCreate">新增 Mock 文件</el-button> <el-button size="mini" type="primary" @click="openMockFileDialogForCreate">新增 Mock 数据</el-button>
<el-button size="mini" @click="openMockGroupDialog">分组管理</el-button> <el-button size="mini" @click="openMockGroupDialog">分组管理</el-button>
</div> </div>
</div> </div>
@@ -160,7 +236,7 @@
<span>{{ scope.row.alias || "-" }}</span> <span>{{ scope.row.alias || "-" }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="Mock 文件路径" min-width="320"> <el-table-column label="Mock 数据路径" min-width="320">
<template slot-scope="scope"> <template slot-scope="scope">
<span>{{ scope.row.filePath }}</span> <span>{{ scope.row.filePath }}</span>
</template> </template>
@@ -429,7 +505,7 @@
:disabled="isApiListLocked()" :disabled="isApiListLocked()"
></el-input> ></el-input>
</el-form-item> </el-form-item>
<el-form-item label="Mock 文件" prop="filePath"> <el-form-item label="Mock 数据" prop="filePath">
<div style="display:flex;gap:8px;"> <div style="display:flex;gap:8px;">
<el-select <el-select
v-model="routeDialog.form.groupFilter" v-model="routeDialog.form.groupFilter"
@@ -450,7 +526,7 @@
<el-select <el-select
v-model="routeDialog.form.filePath" v-model="routeDialog.form.filePath"
filterable filterable
placeholder="请选择 mock 文件" placeholder="请选择 Mock 数据"
style="flex: 1;" style="flex: 1;"
> >
<el-option <el-option
@@ -487,13 +563,13 @@
<span slot="footer" class="dialog-footer"> <span slot="footer" class="dialog-footer">
<el-button @click="routeDialog.visible = false">取消</el-button> <el-button @click="routeDialog.visible = false">取消</el-button>
<el-button type="primary" @click="submitRouteDialog"> <el-button type="primary" @click="submitRouteDialog">
{{ routeDialog.mode === "edit" ? "保存修改" : "创建路由+文件" }} {{ routeDialog.mode === "edit" ? "保存修改" : "创建路由 + Mock 数据" }}
</el-button> </el-button>
</span> </span>
</el-dialog> </el-dialog>
<el-dialog <el-dialog
:title="mockFileDialog.mode === 'edit' ? '修改 Mock 文件' : mockFileDialog.mode === 'copy' ? '复制 Mock 文件' : '新增 Mock 文件'" :title="mockFileDialog.mode === 'edit' ? '修改 Mock 数据' : mockFileDialog.mode === 'copy' ? '复制 Mock 数据' : '新增 Mock 数据'"
:visible.sync="mockFileDialog.visible" :visible.sync="mockFileDialog.visible"
:width="mockFileDialog.fullscreen ? '100%' : '760px'" :width="mockFileDialog.fullscreen ? '100%' : '760px'"
:fullscreen="mockFileDialog.fullscreen" :fullscreen="mockFileDialog.fullscreen"
@@ -517,7 +593,7 @@
<el-option v-for="g in mockGroups" :key="g.id" :label="g.name" :value="g.id"></el-option> <el-option v-for="g in mockGroups" :key="g.id" :label="g.name" :value="g.id"></el-option>
</el-select> </el-select>
</el-form-item> </el-form-item>
<el-form-item label="Mock 文件路径" prop="fileName"> <el-form-item label="Mock 数据路径" prop="fileName">
<el-input <el-input
v-model="mockFileDialog.form.fileName" v-model="mockFileDialog.form.fileName"
:placeholder="mockFileDialog.mode === 'edit' ? '' : '根据别名自动生成:别名_随机串.json'" :placeholder="mockFileDialog.mode === 'edit' ? '' : '根据别名自动生成:别名_随机串.json'"
@@ -526,8 +602,16 @@
<template slot="prepend">mock/</template> <template slot="prepend">mock/</template>
</el-input> </el-input>
</el-form-item> </el-form-item>
<el-form-item label="文件内容" prop="content"> <el-form-item label="数据内容" prop="content">
<div style="display:flex;justify-content:flex-end;margin-bottom:6px;"> <div class="mock-editor-toolbar">
<el-button
size="mini"
type="text"
icon="el-icon-magic-stick"
@click="formatMockJson"
>
JSON 格式化
</el-button>
<el-button size="mini" type="text" @click="mockFileDialog.fullscreen = !mockFileDialog.fullscreen"> <el-button size="mini" type="text" @click="mockFileDialog.fullscreen = !mockFileDialog.fullscreen">
<i :class="mockFileDialog.fullscreen ? 'el-icon-copy-document' : 'el-icon-full-screen'"></i> <i :class="mockFileDialog.fullscreen ? 'el-icon-copy-document' : 'el-icon-full-screen'"></i>
{{ mockFileDialog.fullscreen ? '退出全屏' : '全屏编辑' }} {{ mockFileDialog.fullscreen ? '退出全屏' : '全屏编辑' }}
@@ -544,7 +628,7 @@
</el-form> </el-form>
<span slot="footer" class="dialog-footer"> <span slot="footer" class="dialog-footer">
<el-button @click="mockFileDialog.visible = false">取消</el-button> <el-button @click="mockFileDialog.visible = false">取消</el-button>
<el-button type="primary" @click="submitMockFileDialog">保存 Mock 文件</el-button> <el-button type="primary" @click="submitMockFileDialog">保存 Mock 数据</el-button>
</span> </span>
</el-dialog> </el-dialog>
@@ -613,7 +697,7 @@
<span v-else>{{ scope.row.name }}</span> <span v-else>{{ scope.row.name }}</span>
</template> </template>
</el-table-column> </el-table-column>
<el-table-column label="文件数" width="80" align="center"> <el-table-column label="数据数" width="80" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
<span>{{ getGroupFileCount(scope.row.id) }}</span> <span>{{ getGroupFileCount(scope.row.id) }}</span>
</template> </template>
@@ -633,13 +717,13 @@
width="500px" width="500px"
> >
<div style="margin-bottom:16px;"> <div style="margin-bottom:16px;">
<p>分组「{{ deleteGroupDialog.groupName }}」下有 <strong>{{ deleteGroupDialog.fileCount }}</strong> 个 mock 文件。</p> <p>分组「{{ deleteGroupDialog.groupName }}」下有 <strong>{{ deleteGroupDialog.fileCount }}</strong> 条 Mock 数据。</p>
<p>请选择对这些文件的处理方式:</p> <p>请选择对这些 Mock 数据的处理方式:</p>
</div> </div>
<el-radio-group v-model="deleteGroupDialog.action" style="display:flex;flex-direction:column;gap:12px;"> <el-radio-group v-model="deleteGroupDialog.action" style="display:flex;flex-direction:column;gap:12px;">
<el-radio label="reassign">转移到其他分组</el-radio> <el-radio label="reassign">转移到其他分组</el-radio>
<el-radio label="unassign">取消分组(设为未分组)</el-radio> <el-radio label="unassign">取消分组(设为未分组)</el-radio>
<el-radio label="delete">删除全部文件</el-radio> <el-radio label="delete">删除全部 Mock 数据</el-radio>
</el-radio-group> </el-radio-group>
<div v-if="deleteGroupDialog.action === 'reassign'" style="margin-top:12px;"> <div v-if="deleteGroupDialog.action === 'reassign'" style="margin-top:12px;">
<el-select v-model="deleteGroupDialog.targetGroupId" placeholder="选择目标分组" style="width:100%;"> <el-select v-model="deleteGroupDialog.targetGroupId" placeholder="选择目标分组" style="width:100%;">
@@ -744,11 +828,55 @@
<script src="/assets/vue.js"></script> <script src="/assets/vue.js"></script>
<script src="/assets/element-ui/index.js"></script> <script src="/assets/element-ui/index.js"></script>
<script> <script>
// 每个标签页一个唯一 id:服务端据此把变更通知回推给「其他」页面
var PAGE_CLIENT_ID = (function () {
try {
if (window.crypto && typeof window.crypto.randomUUID === "function") {
return window.crypto.randomUUID();
}
} catch (e) {}
return (
"c-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 10)
);
})();
// 所有管理端请求都带上标签页 id,服务端用它跳过发起方
(function () {
var rawFetch = window.fetch ? window.fetch.bind(window) : null;
if (!rawFetch) return;
window.fetch = function (input, init) {
var options = init ? Object.assign({}, init) : {};
var headers = new Headers(options.headers || {});
headers.set("X-Client-Id", PAGE_CLIENT_ID);
options.headers = headers;
return rawFetch(input, options);
};
})();
var WS_RESOURCE_META = {
routes: { label: "路由配置" },
config: { label: "系统配置" },
"api-list": { label: "接口列表" },
"mock-files": { label: "Mock 数据" },
"mock-groups": { label: "分组" },
"ip-rules": { label: "个性化配置" },
};
var wsSocket = null;
var wsRetryTimer = null;
var wsRetryDelay = 1000;
var wsClosedByPage = false;
new Vue({ new Vue({
el: "#app", el: "#app",
data: function () { data: function () {
return { return {
activeMainTab: "routes", activeMainTab: "routes",
wsConnected: false,
wsOnline: 0,
wsClients: [],
wsClientId: PAGE_CLIENT_ID,
wsHasConnected: false,
routesRefreshing: false, routesRefreshing: false,
mocksRefreshing: false, mocksRefreshing: false,
apiRefreshing: false, apiRefreshing: false,
@@ -893,7 +1021,7 @@
}, },
], ],
filePath: [ filePath: [
{ required: true, message: "请选择 Mock 文件", trigger: "change" }, { required: true, message: "请选择 Mock 数据", trigger: "change" },
], ],
statusCode: [ statusCode: [
{ {
@@ -940,10 +1068,10 @@
}, },
], ],
fileName: [ fileName: [
{ required: true, message: "文件路径不能为空", trigger: "change" }, { required: true, message: "Mock 数据路径不能为空", trigger: "change" },
], ],
content: [ content: [
{ required: true, message: "请输入文件内容", trigger: "blur" }, { required: true, message: "请输入数据内容", trigger: "blur" },
], ],
}, },
}; };
@@ -975,9 +1103,156 @@
await this.loadMockGroups(); await this.loadMockGroups();
await this.loadConfig(); await this.loadConfig();
await this.loadRoutes(); await this.loadRoutes();
this.initWebSocket();
}, },
methods: { methods: {
loadRoutes: async function () { initWebSocket: function () {
if (typeof window.WebSocket === "undefined") {
console.warn("[WS] 当前浏览器不支持 WebSocket");
return;
}
window.addEventListener("beforeunload", function () {
wsClosedByPage = true;
if (wsSocket) {
try {
wsSocket.close();
} catch (e) {}
}
});
this.connectWebSocket();
},
connectWebSocket: function () {
var self = this;
if (wsClosedByPage) return;
var proto = window.location.protocol === "https:" ? "wss:" : "ws:";
var url =
proto +
"//" +
window.location.host +
"/__ws?cid=" +
encodeURIComponent(PAGE_CLIENT_ID);
var socket;
try {
socket = new WebSocket(url);
} catch (err) {
self.scheduleWebSocketReconnect();
return;
}
wsSocket = socket;
socket.onopen = function () {
var wasDisconnected = self.wsHasConnected === true;
self.wsConnected = true;
self.wsHasConnected = true;
wsRetryDelay = 1000;
if (wasDisconnected) {
// 断线重连后补齐期间可能错过的变更
self.refreshAllResources();
}
};
socket.onmessage = function (event) {
self.handleWebSocketMessage(event.data);
};
socket.onclose = function () {
if (wsSocket === socket) {
wsSocket = null;
}
self.wsConnected = false;
self.wsOnline = 0;
self.wsClients = [];
self.scheduleWebSocketReconnect();
};
socket.onerror = function () {
try {
socket.close();
} catch (e) {}
};
},
scheduleWebSocketReconnect: function () {
var self = this;
if (wsClosedByPage || wsRetryTimer) return;
wsRetryTimer = window.setTimeout(function () {
wsRetryTimer = null;
self.connectWebSocket();
}, wsRetryDelay);
wsRetryDelay = Math.min(wsRetryDelay * 2, 15000);
},
getWsClientLabel: function (client) {
if (!client) return "未知 IP";
var ip = client.ip || "未知 IP";
var remark = client.remark || "";
return remark ? remark + "(" + ip + ")" : ip;
},
handleWebSocketMessage: function (raw) {
var data;
try {
data = JSON.parse(raw);
} catch (e) {
return;
}
if (!data || !data.type) return;
if (data.type === "welcome" || data.type === "online") {
this.wsOnline = Number(data.online) || 0;
this.wsClients = Array.isArray(data.clients) ? data.clients : [];
return;
}
if (data.type === "mutation") {
this.handleRemoteMutation(data);
}
},
handleRemoteMutation: function (data) {
var meta = WS_RESOURCE_META[data.resource] || { label: "数据" };
var detail = data.detail || "更新了" + meta.label;
var actorInfo = data.actor || {};
// 该 IP 如有「个性化配置」备注,用备注作为操作人,形如 [董] 修改了路由配置
var actorName = actorInfo.name || actorInfo.remark || "";
var actor = actorName
? "[" + actorName + "]"
: actorInfo.ip || "其他客户端";
if (typeof data.online === "number") {
this.wsOnline = data.online;
}
try {
this.$notify({
title: "数据已更新",
message: actor + " " + detail + ",本页已自动刷新",
type: "info",
duration: 4500,
position: "bottom-right",
});
} catch (e) {
console.warn("[WS] 通知展示失败", e);
}
this.refreshResource(data.resource);
},
refreshResource: function (resource) {
var options = { silent: true, keepPage: true };
if (resource === "routes") {
this.loadRoutes(options);
} else if (resource === "mock-files") {
this.loadMockFiles(options);
} else if (resource === "mock-groups") {
this.loadMockGroups(options);
this.loadMockFiles(options);
} else if (resource === "api-list") {
this.loadApiList(options);
} else if (resource === "config") {
this.loadConfig(options);
} else if (resource === "ip-rules") {
this.loadIpRules(options);
} else {
this.refreshAllResources();
}
},
refreshAllResources: function () {
var options = { silent: true, keepPage: true };
this.loadApiList(options);
this.loadMockFiles(options);
this.loadMockGroups(options);
this.loadConfig(options);
this.loadRoutes(options);
this.loadIpRules(options);
},
loadRoutes: async function (options) {
try { try {
var resp = await fetch("/__routes"); var resp = await fetch("/__routes");
var data = await resp.json(); var data = await resp.json();
@@ -990,10 +1265,16 @@
data.routeEnabledMap || {}, data.routeEnabledMap || {},
data.routeApiNameMap || {}, data.routeApiNameMap || {},
); );
if (!(options && options.keepPage)) {
this.routePagination.currentPage = 1; this.routePagination.currentPage = 1;
}
} catch (err) { } catch (err) {
if (options && options.silent) {
console.warn("加载路由失败: " + err.message);
} else {
this.$message.error("加载路由失败: " + err.message); this.$message.error("加载路由失败: " + err.message);
} }
}
}, },
refreshRoutes: async function () { refreshRoutes: async function () {
this.routesRefreshing = true; this.routesRefreshing = true;
@@ -1041,7 +1322,7 @@
this.ipRulesRefreshing = false; this.ipRulesRefreshing = false;
} }
}, },
loadIpRules: async function () { loadIpRules: async function (options) {
try { try {
var resp = await fetch("/__ip-rules"); var resp = await fetch("/__ip-rules");
var data = await resp.json(); var data = await resp.json();
@@ -1057,11 +1338,17 @@
} else if (data.isAdmin === false) { } else if (data.isAdmin === false) {
this.isAdmin = false; this.isAdmin = false;
} }
if (!(options && options.keepPage)) {
this.ipRulePagination.currentPage = 1; this.ipRulePagination.currentPage = 1;
}
} catch (err) { } catch (err) {
this.ipRules = []; this.ipRules = [];
if (options && options.silent) {
console.warn("加载个性化配置失败: " + err.message);
} else {
this.$message.error("加载个性化配置失败: " + err.message); this.$message.error("加载个性化配置失败: " + err.message);
} }
}
}, },
canManageIpRule: function (rule) { canManageIpRule: function (rule) {
if (!rule) return false; if (!rule) return false;
@@ -1212,7 +1499,7 @@
}, },
getPreviewText: function (content) { getPreviewText: function (content) {
var text = String(content || "").replace(/\s+/g, " ").trim(); var text = String(content || "").replace(/\s+/g, " ").trim();
if (!text) return "(空文件)"; if (!text) return "(空内容)";
return text.length > 120 ? text.slice(0, 120) + "..." : text; return text.length > 120 ? text.slice(0, 120) + "..." : text;
}, },
getPagedData: function (list, pagination) { getPagedData: function (list, pagination) {
@@ -1340,7 +1627,7 @@
this.routeDialog.form.apiName = selected.name; this.routeDialog.form.apiName = selected.name;
}, },
onRouteDialogGroupChange: function () { onRouteDialogGroupChange: function () {
// 切换分组时清空已选文件 // 切换分组时清空已选数据
this.routeDialog.form.filePath = ""; this.routeDialog.form.filePath = "";
}, },
openRouteDialogForCreate: function () { openRouteDialogForCreate: function () {
@@ -1426,7 +1713,7 @@
var filePath = routeRow.filePath || ""; var filePath = routeRow.filePath || "";
var mockFile = this.mockFiles.find(function (f) { return f.filePath === filePath; }); var mockFile = this.mockFiles.find(function (f) { return f.filePath === filePath; });
if (!mockFile) { if (!mockFile) {
this.$message.warning("未找到对应的 Mock 文件:" + filePath); this.$message.warning("未找到对应的 Mock 数据:" + filePath);
return; return;
} }
this.openMockFileDialogForEdit(mockFile); this.openMockFileDialogForEdit(mockFile);
@@ -1454,19 +1741,89 @@
if (this.$refs.mockFileForm) this.$refs.mockFileForm.clearValidate(); if (this.$refs.mockFileForm) this.$refs.mockFileForm.clearValidate();
}); });
}, },
loadMockFiles: async function () { loadMockFiles: async function (options) {
try { try {
var resp = await fetch("/__mock-files"); var resp = await fetch("/__mock-files");
var data = await resp.json(); var data = await resp.json();
if (!resp.ok || data.success === false) { if (!resp.ok || data.success === false) {
throw new Error(data.error || "加载 mock 文件失败"); throw new Error(data.error || "加载 Mock 数据失败");
} }
this.mockFiles = Array.isArray(data.list) ? data.list : []; this.mockFiles = Array.isArray(data.list) ? data.list : [];
if (!(options && options.keepPage)) {
this.mockFilePagination.currentPage = 1; this.mockFilePagination.currentPage = 1;
}
} catch (err) { } catch (err) {
this.mockFiles = []; this.mockFiles = [];
this.$message.error("加载 mock 文件失败: " + err.message); if (options && options.silent) {
console.warn("加载 Mock 数据失败: " + err.message);
} else {
this.$message.error("加载 Mock 数据失败: " + err.message);
} }
}
},
formatMockJson: function () {
var text = String(this.mockFileDialog.form.content || "");
if (!text.trim()) {
this.$message.warning("内容为空,无需格式化");
return;
}
var result = this.formatJsonText(text);
if (!result.ok) {
this.$message.error("JSON 格式化失败:" + result.error);
return;
}
if (result.text === text) {
this.$message.info("当前内容已是格式化后的 JSON");
return;
}
this.mockFileDialog.form.content = result.text;
var form = this.$refs.mockFileForm;
if (form) {
form.validateField("content", function () {});
}
this.$message.success(
result.repaired ? "已修复为合法 JSON 并完成格式化" : "JSON 已格式化",
);
},
formatJsonText: function (text) {
try {
var parsed = JSON.parse(text);
return {
ok: true,
text: JSON.stringify(parsed, null, 2),
repaired: false,
};
} catch (strictError) {
// 兼容从浏览器控制台/代码里直接粘贴的对象字面量(单引号、无引号键、尾逗号)
var relaxed = this.relaxJsonText(text);
if (relaxed !== null && relaxed !== text) {
try {
var reparsed = JSON.parse(relaxed);
return {
ok: true,
text: JSON.stringify(reparsed, null, 2),
repaired: true,
};
} catch (e) {}
}
return {
ok: false,
error:
(strictError && strictError.message) || "内容不是合法的 JSON",
};
}
},
relaxJsonText: function (text) {
var source = String(text || "").trim();
if (!source) return null;
var first = source.charAt(0);
if (first !== "{" && first !== "[") return null;
return source
.replace(/'((?:[^'\\]|\\.)*)'/g, function (match, inner) {
return '"' + inner.replace(/\\'/g, "'").replace(/"/g, '\\"') + '"';
})
.replace(/([{,]\s*)([A-Za-z_$][\w$]*)(\s*:)/g, '$1"$2"$3')
.replace(/,\s*([}\]])/g, "$1");
}, },
submitMockFileDialog: function () { submitMockFileDialog: function () {
var self = this; var self = this;
@@ -1483,15 +1840,15 @@
doSubmitMockFileDialog: async function () { doSubmitMockFileDialog: async function () {
var fileName = (this.mockFileDialog.form.fileName || "").trim(); var fileName = (this.mockFileDialog.form.fileName || "").trim();
if (!fileName) { if (!fileName) {
this.$message.error("文件名不能为空"); this.$message.error("数据名不能为空");
return; return;
} }
if (fileName.indexOf("/") !== -1 || fileName.indexOf("\\") !== -1) { if (fileName.indexOf("/") !== -1 || fileName.indexOf("\\") !== -1) {
this.$message.error("文件名不能包含路径分隔符"); this.$message.error("数据名不能包含路径分隔符");
return; return;
} }
if (!/\.[^./\\]+$/.test(fileName)) { if (!/\.[^./\\]+$/.test(fileName)) {
this.$message.error("文件名必须包含后缀,如 .json、.txt 等"); this.$message.error("数据名必须包含后缀,如 .json、.txt 等");
return; return;
} }
var filePath = "mock/" + fileName; var filePath = "mock/" + fileName;
@@ -1508,19 +1865,19 @@
}); });
var data = await resp.json(); var data = await resp.json();
if (!resp.ok || data.success === false) { if (!resp.ok || data.success === false) {
throw new Error(data.error || "保存 mock 文件失败"); throw new Error(data.error || "保存 Mock 数据失败");
} }
this.$message.success("Mock 文件已保存"); this.$message.success("Mock 数据已保存");
this.mockFileDialog.visible = false; this.mockFileDialog.visible = false;
await this.loadMockFiles(); await this.loadMockFiles();
} catch (err) { } catch (err) {
this.$message.error("保存 mock 文件失败: " + err.message); this.$message.error("保存 Mock 数据失败: " + err.message);
} }
}, },
removeMockFile: async function (item) { removeMockFile: async function (item) {
try { try {
await this.$confirm( await this.$confirm(
"确认删除 " + item.filePath + " 吗?删除后引用该文件的路由需要重新选择。", "确认删除 " + item.filePath + " 吗?删除后引用该 Mock 数据的路由需要重新选择。",
"提示", "提示",
{ type: "warning" }, { type: "warning" },
); );
@@ -1531,17 +1888,17 @@
}); });
var data = await resp.json(); var data = await resp.json();
if (!resp.ok || data.success === false) { if (!resp.ok || data.success === false) {
throw new Error(data.error || "删除 mock 文件失败"); throw new Error(data.error || "删除 Mock 数据失败");
} }
this.$message.success("Mock 文件已删除"); this.$message.success("Mock 数据已删除");
await this.loadMockFiles(); await this.loadMockFiles();
} catch (err) { } catch (err) {
if (err !== "cancel") { if (err !== "cancel") {
this.$message.error("删除 mock 文件失败: " + err.message); this.$message.error("删除 Mock 数据失败: " + err.message);
} }
} }
}, },
loadApiList: async function () { loadApiList: async function (options) {
try { try {
var resp = await fetch("/__api-list"); var resp = await fetch("/__api-list");
var data = await resp.json(); var data = await resp.json();
@@ -1551,10 +1908,14 @@
this.apiList = Array.isArray(data.list) ? data.list : []; this.apiList = Array.isArray(data.list) ? data.list : [];
} catch (err) { } catch (err) {
this.apiList = []; this.apiList = [];
if (options && options.silent) {
console.warn("加载接口列表失败: " + err.message);
} else {
this.$message.error("加载接口列表失败: " + err.message); this.$message.error("加载接口列表失败: " + err.message);
} }
}
}, },
loadConfig: async function () { loadConfig: async function (options) {
try { try {
var resp = await fetch("/__config"); var resp = await fetch("/__config");
var data = await resp.json(); var data = await resp.json();
@@ -1565,8 +1926,12 @@
this.isAdmin = true; this.isAdmin = true;
} }
} catch (err) { } catch (err) {
if (options && options.silent) {
console.warn("加载配置失败: " + err.message);
} else {
this.$message.error("加载配置失败: " + err.message); this.$message.error("加载配置失败: " + err.message);
} }
}
}, },
saveRoutes: async function () { saveRoutes: async function () {
var payload = { var payload = {
@@ -1632,7 +1997,7 @@
this.$message.success( this.$message.success(
this.routeDialog.mode === "edit" this.routeDialog.mode === "edit"
? "路由修改成功" ? "路由修改成功"
: "接口配置文件创建成功", : "接口与 Mock 数据创建成功",
); );
this.routeDialog.visible = false; this.routeDialog.visible = false;
await this.loadMockFiles(); await this.loadMockFiles();
@@ -1779,7 +2144,7 @@
getGroupFileCount: function (groupId) { getGroupFileCount: function (groupId) {
return this.mockFiles.filter(function (f) { return f.groupId === groupId; }).length; return this.mockFiles.filter(function (f) { return f.groupId === groupId; }).length;
}, },
loadMockGroups: async function () { loadMockGroups: async function (options) {
try { try {
var resp = await fetch("/__mock-groups"); var resp = await fetch("/__mock-groups");
var data = await resp.json(); var data = await resp.json();
@@ -1789,8 +2154,12 @@
this.mockGroups = Array.isArray(data.list) ? data.list : []; this.mockGroups = Array.isArray(data.list) ? data.list : [];
} catch (err) { } catch (err) {
this.mockGroups = []; this.mockGroups = [];
if (options && options.silent) {
console.warn("加载分组失败: " + err.message);
} else {
this.$message.error("加载分组失败: " + err.message); this.$message.error("加载分组失败: " + err.message);
} }
}
}, },
openMockGroupDialog: function () { openMockGroupDialog: function () {
this.mockGroupDialog.editingId = null; this.mockGroupDialog.editingId = null;
@@ -1850,7 +2219,7 @@
confirmDeleteGroup: async function (group) { confirmDeleteGroup: async function (group) {
var fileCount = this.getGroupFileCount(group.id); var fileCount = this.getGroupFileCount(group.id);
if (fileCount === 0) { if (fileCount === 0) {
// 无文件,直接删除 // 无数据,直接删除
try { try {
var resp = await fetch("/__mock-groups", { var resp = await fetch("/__mock-groups", {
method: "DELETE", method: "DELETE",
@@ -1868,7 +2237,7 @@
} }
return; return;
} }
// 有文件,弹出确认对话框 // 有数据,弹出确认对话框
this.deleteGroupDialog.groupId = group.id; this.deleteGroupDialog.groupId = group.id;
this.deleteGroupDialog.groupName = group.name; this.deleteGroupDialog.groupName = group.name;
this.deleteGroupDialog.fileCount = fileCount; this.deleteGroupDialog.fileCount = fileCount;
+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 -1
View File
@@ -1 +1,4 @@
{"code":0,"msg":"ok"} {
"code": 0,
"msg": "ok"
}
+123 -8
View File
@@ -29,6 +29,7 @@ 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"; import type { IpRule, IpRuleConfig } from "./types";
async function handleReloadConfig( async function handleReloadConfig(
@@ -67,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(
@@ -125,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({
@@ -252,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 });
@@ -288,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,
@@ -363,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;
@@ -370,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 }));
}) })
@@ -429,9 +462,17 @@ 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 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, groupId); 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({
@@ -445,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({
@@ -509,6 +557,9 @@ async function handleMockGroups(
throw new Error("分组名称不能为空"); throw new Error("分组名称不能为空");
} }
const id = await insertMockGroup(name); const id = await insertMockGroup(name);
broadcastMutation(clientReq, "mock-groups", "create", `新增了分组「${name}」`, {
id,
});
clientRes.writeHead(200, { "Content-Type": "application/json" }); clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, id, name })); clientRes.end(JSON.stringify({ success: true, id, name }));
return; return;
@@ -521,6 +572,9 @@ async function handleMockGroups(
throw new Error("id 和 name 不能为空"); throw new Error("id 和 name 不能为空");
} }
await updateMockGroup(id, name); await updateMockGroup(id, name);
broadcastMutation(clientReq, "mock-groups", "update", `修改了分组名称为「${name}」`, {
id,
});
clientRes.writeHead(200, { "Content-Type": "application/json" }); clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, id, name })); clientRes.end(JSON.stringify({ success: true, id, name }));
return; return;
@@ -533,34 +587,50 @@ async function handleMockGroups(
} }
const fileCount = await countMockFilesByGroup(id); const fileCount = await countMockFilesByGroup(id);
const action = String(body.action || "").trim(); const action = String(body.action || "").trim();
let filesChanged = false;
if (fileCount > 0 && action === "reassign") { if (fileCount > 0 && action === "reassign") {
const targetGroupId = body.targetGroupId != null ? Number(body.targetGroupId) : null; const targetGroupId = body.targetGroupId != null ? Number(body.targetGroupId) : null;
await updateMockFilesGroupId(id, targetGroupId); await updateMockFilesGroupId(id, targetGroupId);
filesChanged = true;
} else if (fileCount > 0 && action === "delete") { } else if (fileCount > 0 && action === "delete") {
const deletedFiles = await deleteMockFilesByGroup(id); const deletedFiles = await deleteMockFilesByGroup(id);
// 删除磁盘上的文件 // 删除磁盘上的数据
for (const file of deletedFiles) { for (const file of deletedFiles) {
const fullPath = path.join(__dirname, "..", file.file_path); const fullPath = path.join(__dirname, "..", file.file_path);
if (fs.existsSync(fullPath)) { if (fs.existsSync(fullPath)) {
fs.unlinkSync(fullPath); fs.unlinkSync(fullPath);
} }
} }
filesChanged = true;
} else if (fileCount > 0) { } else if (fileCount > 0) {
// 有文件但未指定 action,返回需要确认的信息 // 有数据但未指定 action,返回需要确认的信息
clientRes.writeHead(200, { "Content-Type": "application/json" }); clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end( clientRes.end(
JSON.stringify({ JSON.stringify({
success: false, success: false,
needConfirm: true, needConfirm: true,
fileCount, fileCount,
message: `该分组下有 ${fileCount} 个 mock 文件,请指定操作`, message: `该分组下有 ${fileCount} 条 Mock 数据,请指定操作`,
}), }),
); );
return; return;
} }
const groupName =
(await loadMockGroups()).find((group) => group.id === id)?.name || `#${id}`;
await deleteMockGroup(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.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, id })); clientRes.end(JSON.stringify({ success: true, id }));
}) })
@@ -681,6 +751,13 @@ async function handleIpRules(
} }
await deleteIpRuleFromDb(ip); await deleteIpRuleFromDb(ip);
state.ipRules = await loadIpRulesFromDb(); state.ipRules = await loadIpRulesFromDb();
broadcastMutation(
clientReq,
"ip-rules",
"delete",
`删除了 IP 规则「${ip}」`,
{ ip },
);
clientRes.writeHead(200, { "Content-Type": "application/json" }); clientRes.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, ip })); clientRes.end(JSON.stringify({ success: true, ip }));
return; return;
@@ -700,8 +777,18 @@ async function handleIpRules(
); );
return; return;
} }
const existed = state.ipRules.some(
(item) => normalizeIp(item.ip) === normalizeIp(rule.ip),
);
await upsertIpRuleToDb(rule); await upsertIpRuleToDb(rule);
state.ipRules = await loadIpRulesFromDb(); 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.writeHead(200, { "Content-Type": "application/json" });
clientRes.end(JSON.stringify({ success: true, rule })); clientRes.end(JSON.stringify({ success: true, rule }));
}) })
@@ -761,8 +848,33 @@ async function handleClientIp(
); );
} }
const ASSETS_ROOT = path.join(__dirname, "..", "assets"); /** 在线客户端查询(调试用,页面主要通过 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> = { const ASSET_CONTENT_TYPES: Record<string, string> = {
".css": "text/css; charset=utf-8", ".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8", ".js": "application/javascript; charset=utf-8",
@@ -880,6 +992,9 @@ export async function dispatchAdmin(
case "/__client-ip": case "/__client-ip":
await handleClientIp(clientReq, clientRes); await handleClientIp(clientReq, clientRes);
return true; 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;
+5 -5
View File
@@ -11,9 +11,9 @@ 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;
@@ -26,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 数据校验通过`);
} }
} }
+1 -1
View File
@@ -160,7 +160,7 @@ export async function initDatabase(): Promise<void> {
if (!hadIpRules) { if (!hadIpRules) {
console.log("[DB] 数据库已自动升级: 新增 IP 管理(ip_rules)表"); console.log("[DB] 数据库已自动升级: 新增 IP 管理(ip_rules)表");
} }
// 清理不该出现在 mock 列表中的系统文件 // 清理不该出现在 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"],
+7 -7
View File
@@ -70,16 +70,16 @@ export function createProxyServer(): http.Server {
const mockFile = getMockFilePath(requestPath); const mockFile = getMockFilePath(requestPath);
const mockStatusCode = getMockStatusCode(requestPath); const mockStatusCode = getMockStatusCode(requestPath);
console.log( console.log(
`[MOCK] 拦截路由: ${requestPath} -> 使用文件: ${mockFile} | 客户端IP: ${effective.ip}${effective.matchedRule ? ` | 规则: ${effective.matchedRule.ip}` : ""}${effective.ruleMatchedViaLocalhost ? " (localhost回退)" : ""}`, `[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(effectiveConfig); const targetPort = getTargetPort(effectiveConfig);
@@ -123,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,
); );
} }
@@ -159,7 +159,7 @@ export function createProxyServer(): http.Server {
return; return;
} }
// 读取本地mock文件 // 读取本地 Mock 数据数据
const mockData = fs.readFileSync(mockFilePath, "utf-8"); const mockData = fs.readFileSync(mockFilePath, "utf-8");
// 设置响应头 // 设置响应头
@@ -179,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({
+1 -1
View File
@@ -16,7 +16,7 @@ export function isMockRoute(
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];
} }
+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})`,
);
}