Compare commits

..
4 Commits
Author SHA1 Message Date
836061373 afda8d04fd feat(demo): 按插件当前实现重写演示页
- 列表/筛选对齐真实 Console:八维筛选、语义动作中文描述、登录失败结果语义
- 详情抽屉展示字段级 diff(脱敏/截断/封顶)与 AuditLog Extension 原始 JSON
- 新增行内「历史」快捷、按筛选条件导出 UTF-8 BOM CSV
- 设置页覆盖审计开关/字段变更/系统变更/保留期与登录失败告警(含测试与模拟触发)
- 模拟器支持 HTTP 捕获管线与系统内部变更两条通道
- 核心纯函数重写并扩充至 56 个单元用例
2026-11-23 00:05:12 +08:00
836061373 602744debd chore: 新增 .gitattributes 统一换行策略与二进制文件处理
- 文本统一 LF(脚本/sh 强制 LF,批处理 CRLF),仓库现状已全部为 LF,无大规模重写
- png/jar/zip/pdf 等标记 binary,避免文本转换与 diff 噪音
- package-lock.json 标记为生成物
2026-11-22 23:54:53 +08:00
836061373 9329f313f4 chore: 整理仓库结构与文档——测试截图归档至 docs/assets,修正报告并补全文档索引
- gui-test-screenshots/ 迁至 docs/assets/gui-test-screenshots/,测试证据归入 docs
- 修正测试报告中的截图路径与“未纳入版本控制”矛盾表述,测试凭据脱敏
- README 仓库结构补全 .github/.agents/转发脚本/锁文件,文档表补全全部文档
2026-11-22 23:54:53 +08:00
836061373 fd43c069ae docs: 新增发布验收待办完成记录(6 项待办执行总结归档至 docs)
- docs/operation-audit-release-todos-completion.md:待办完成总览表、
  正式构建/CI-CD/卸载/2.26.0 下探/元数据与 ui/ 迁移的关键执行细节、
  提交记录、剩余发布动作与环境备注
- 验收清单确认报告参考链接补充该完成记录
2026-11-22 23:44:31 +08:00
17 changed files with 3904 additions and 833 deletions
+21
View File
@@ -0,0 +1,21 @@
# 统一换行:仓库内文本一律 LF,避免跨平台提交产生无意义 diff
* text=auto eol=lf
# 脚本与 Windows 批处理
*.sh text eol=lf
gradlew text eol=lf
*.bat text eol=crlf
*.cmd text eol=crlf
# 二进制文件不做文本转换与 diff
*.png binary
*.jpg binary
*.jpeg binary
*.gif binary
*.ico binary
*.jar binary
*.zip binary
*.pdf binary
# 锁文件按生成物处理,减少 diff 噪音
package-lock.json linguist-generated=true
+21 -6
View File
@@ -28,7 +28,12 @@ Halo 2.x **操作审计插件**:回答"**谁、在什么时候、对什么资
│ ├── src/ # 捕获过滤器、审计模型、查询端点、保留期清理
│ └── ui/ # Console 前端(Vue 3 + vitest)
├── demo/ # Console UI 静态演示页(纯前端、模拟数据、零构建依赖)
├── docs/ # 设计文档:产品设计 · 技术方案
├── docs/ # 设计 / 验收 / 测试文档
│ └── assets/gui-test-screenshots/ # 浏览器级 UI 验收截图证据
├── .github/workflows/ # CI/CD(复用 halo-sigs 官方可复用工作流)
├── .agents/skills/ # 项目级 AI 技能(halo-plugin-dev)
├── gradlew / gradlew.bat # 仓库根转发脚本:CI 在根目录执行,转发到 plugin-operation-audit/
├── skills-lock.json # 技能安装锁文件
└── AGENTS.md # AI 协作约定(每次改动需 commit、测试全绿后交付)
```
@@ -58,14 +63,15 @@ cd demo
python -m http.server 8721 # 访问 http://127.0.0.1:8721/
```
也可直接双击打开 `demo/index.html`(`file://` 下可运行)。演示页内置若干故事线,
可体验"排查这篇文章谁改过""登录爆破回溯""误操作定位"等典型场景,
并通过"模拟一次操作"按钮验证捕获规则的边界。
也可直接双击打开 `demo/index.html`(`file://` 下可运行)。演示页已按当前插件实现重写,
包含八维筛选、语义动作与中文描述、字段级变更 diff、登录失败标注与告警、CSV 导出、
系统内部变更,以及复现捕获管线的「模拟一次操作」。内置故事线可直接体验
"排查这篇文章谁改过""登录爆破回溯""定时发布归属""误操作定位"等场景。
### 运行演示测试
```bash
node --test demo/test/audit-core.test.mjs
node --test demo/test/audit-core.test.mjs # 56 个用例
```
## 相关文档
@@ -73,6 +79,15 @@ node --test demo/test/audit-core.test.mjs
| 文档 | 内容 |
|---|---|
| [plugin-operation-audit/README.md](plugin-operation-audit/README.md) | 插件详情:功能、安装、设置、模型 group 与已知局限 |
| [demo/README.md](demo/README.md) | 演示页说明:演示了什么、与真实实现的差异 |
| [demo/README.md](demo/README.md) | 演示页说明:演示了什么、故事线复现方式、与真实实现的差异 |
| [docs/operation-audit-design.md](docs/operation-audit-design.md) | 产品设计:MVP 范围、设计原则 |
| [docs/operation-audit-tech-design.md](docs/operation-audit-tech-design.md) | 技术方案:架构、数据模型、风险预案 |
| [docs/operation-audit-roadmap.md](docs/operation-audit-roadmap.md) | 功能增量评估(MVP 之后的候选能力) |
| [docs/operation-audit-halo-compliance.md](docs/operation-audit-halo-compliance.md) | Halo 官方开发规范符合性评审 |
| [docs/plugin-release-checklist.md](docs/plugin-release-checklist.md) | 插件发布验收清单(官方流程存档) |
| [docs/operation-audit-release-checklist-review.md](docs/operation-audit-release-checklist-review.md) | 发布验收逐项确认报告 |
| [docs/operation-audit-release-todos-completion.md](docs/operation-audit-release-todos-completion.md) | 发布验收待办完成记录 |
| [docs/plugin-testing.md](docs/plugin-testing.md) | Halo 官方测试流程文档存档 |
| [docs/operation-audit-test-report.md](docs/operation-audit-test-report.md) | 分层测试报告(源码级 + 联调 + UI 验收) |
| [docs/ai-assisted.md](docs/ai-assisted.md) | AI 辅助开发说明与文档上下文 |
| [docs/assets/gui-test-screenshots/](docs/assets/gui-test-screenshots/) | 浏览器级 UI 验收截图证据 |
+79 -34
View File
@@ -1,8 +1,12 @@
# 操作审计插件 · Console UI Demo
> 对应文档:[operation-audit-design.md](../docs/operation-audit-design.md)(产品设计)· [operation-audit-tech-design.md](../docs/operation-audit-tech-design.md)(技术方案)
> 已按**当前已实现的插件**(Halo 2.26.1)重写:不再是最初的界面原型,而是把插件的
> 查询/筛选、字段级 diff、登录结果判定、CSV 导出、登录失败告警与系统内部变更等能力
> 用纯前端方式完整复现,便于在没有 Halo 实例时体验与验收。
>
> **纯前端静态 Demo,无任何后端与构建依赖**,用于在开发真实插件前验证界面布局与操作流程是否合理。
> 对应实现:[plugin-operation-audit](../plugin-operation-audit/) · 设计文档:
> [operation-audit-design.md](../docs/operation-audit-design.md) ·
> [operation-audit-tech-design.md](../docs/operation-audit-tech-design.md)
## 快速开始
@@ -18,46 +22,77 @@ python -m http.server 8721
## 演示了什么
模拟 Halo Console 外壳(左侧菜单新增"操作审计"插件入口),包含两个页面:
### 审计日志(与真实 Console 页面一致)
### 审计日志(产品设计 4.2)
- **列表列**:操作者 / 时间、动作(HTTP 方法徽标)、资源 / 路径、描述、结果、IP。
描述列展示语义动作的中文短语(登录、登录失败、发布文章、启用插件、修改密码……),
不是裸的 HTTP 方法。
- **八维筛选**:操作者(精确匹配)、资源类型、动作、语义动作、结果、关键字
(资源名称 / 路径模糊匹配)、开始时间、结束时间。下拉即时生效,文本与时间用「查询」
或回车;筛选条件摘要与「清除筛选」始终可见。
- **登录失败标注**:表单登录成败在 HTTP 层都是 302,按重定向目标是否含 `error`
参数判定;失败回显页 `GET /login?error=...`(HTTP 200)同样标红「失败」,
不会把 200/302 误读为登录成功。
- **行内「历史」快捷**:有资源名称的记录可一键预填「资源类型 + 资源名关键字」,
直接回答"这篇文章被谁改过"。
- **只读详情抽屉**:操作者、尝试用户、描述、动作、资源、结果、路径、时间、IP、
User-Agent、记录标识,以及**字段变更**(新增 / 修改 / 删除,旧值删除线 → 新值)
与原始 `AuditLog` Extension JSON;不提供任何删除/修改入口。
- **CSV 导出**:按当前筛选条件导出全部记录,UTF-8 BOM + CRLF,列与界面一致
(含「尝试用户」「操作描述」「变更」),带引号转义与公式注入防护,Excel/WPS 直开不乱码。
- **分页**:10 / 20 / 50 条每页。
- 列表:时间、操作者、动作(HTTP 方法徽标)、资源(类型 + 名称)、结果(状态码)、来源 IP
- 筛选:操作者 / 资源类型 / 动作 / 结果 / 时间范围 / 关键字(资源名称与路径模糊匹配)
- 分页:10 / 20 / 50 条每页
- 详情:点击任意行打开右侧抽屉,展示全部字段(含完整路径、User-Agent、原始 JSON),**只读,无任何修改/删除入口**(设计原则 3)
- 数据内置若干"故事线",可直接体验典型场景:
- **排查"这篇文章谁改过"**:关键字输入 `hello-halo`
- **安全回溯**:资源类型选 `auth` + 结果选"失败"(可见 20 天前同一攻击 IP `203.0.113.66` 的 6 次登录爆破)
- **误操作定位**:关键字输入 `weekly-2026-w45`(1 天前被删除的文章)
### 插件设置
### 插件设置(产品设计 4.3 / 技术方案 D5、D6)
- **审计设置**:启用审计、记录字段变更、记录系统内部变更、保留天数(最小 7 天);
关闭审计后日志页出现横幅,新操作不再记录。
- **告警通知**:启用登录失败告警、Webhook Secret 引用、触发阈值、统计窗口、
「发送测试告警」与「模拟 5 次登录失败」。达阈值后页面顶部出现红色告警横幅,
并可一键筛选"只看失败记录";告警 JSON 负载在设置页展示。
演示页不发起真实网络请求(真实插件由后端推送并带 SSRF 防护)。
- **清理预览**:按保留期实时统计待清理条数,可模拟一次定时清理。
- 审计开关:关闭后日志页出现横幅,新操作不再记录
- 保留天数:修改后"清理预览"实时计算待清理条数,可点击"模拟一次清理"体验定时清理效果
### 模拟一次操作(复现捕获管线)
### 模拟一次操作(技术方案 D1 / 5.1 / 5.2)
右上角「模拟一次操作」有两个通道:
右上角"模拟一次操作"按钮可模拟任意后台请求,Demo 按真实捕获管线逐步判定:
1. **页面 / API 操作**:填写操作者、方法、路径、响应状态、重定向目标
(登录用)、尝试的用户名与请求体 JSON,演示页按真实管线判定:
- `shouldCapture`:`/apis/**` 写操作、`/login`、`/logout`;匿名 / 读操作不记录;
- `resolveResource`:从路径解析资源类型与名称;
- `classifyLogin`:302 重定向目标含 `error` → 登录失败(标注 `login-failure`);
- 字段级 diff:PUT / PATCH(Merge Patch 或 JSON Patch)/ POST / DELETE,
自动脱敏密码/令牌类字段,超长截断、超 30 条封顶。
预设按钮覆盖:编辑文章(含 diff)、发布文章、升级插件、修改密码(脱敏)、
登录失败(表单 302)、登录成功、失败回显、读操作不记录。
2. **系统内部变更**:模拟定时发布等非页面操作,执行者记为「系统」、无 IP/UA、
状态恒 200,仅更新/删除两类事件,附字段变更。
1. `shouldCapture`:是否命中捕获规则(`/apis/**` 写操作 + `/login`、`/logout`;匿名请求不记录)
2. `resolveResource`:从路径解析资源类型与名称
3. 命中则生成审计记录置顶高亮;未命中则用 toast 解释原因(读操作 / 匿名 / 路径不匹配)
## 故事线(可直接复现)
预设按钮包含"登录失败""查询文章列表(读)"等例子,可直观验证规则边界(登录失败记"未知用户")。
| 场景 | 操作 |
|---|---|
| 排查 hello-halo 被谁改过 | 关键字输入 `hello-halo`,或点击任意该资源记录的「历史」;打开详情看字段 diff |
| 登录爆破回溯 | 语义动作选「登录失败」:20 天前同一 IP `203.0.113.66` 的 6 次撞库 + 失败回显页 |
| 定时发布(系统内部变更) | 操作者输入 `system`,或资源类型选 `posts` + 关键字 `weekly-2026-w46` |
| 插件生命周期 | 关键字 `plugin-link` / `plugin-search-widget`;语义动作可筛「升级」「启用」「卸载」 |
| 误操作定位 | 关键字 `weekly-2026-w45`:1 天前的删除记录,详情含被删字段快照 |
| 越权与异常 | 结果选「失败」:403 越权、404 资源不存在、500 发布异常 |
| 登录失败告警 | 插件设置 → 填写 Webhook Secret 引用 → 启用并保存 → 「模拟 5 次登录失败」 |
## 目录结构
```
demo/
├── index.html # 页面骨架(Console 外壳 + 列表/设置/抽屉/弹窗)
├── index.html # Console 外壳 + 列表/设置/详情抽屉/模拟器
├── assets/
│ ├── audit-core.js # 核心纯函数:捕获规则、资源解析、筛选、分页、保留期(UMD,浏览器/Node 共用)
│ ├── mock-data.js # 模拟数据生成器(种子随机、确定性输出,约 142 条 + 故事线)
│ ├── app.js # 交互层(渲染、事件、模拟管线)
│ └── demo.css # 样式(视觉基调取自 @halo-dev/components:#4ccba0 / #0e1731 / #d71d1d)
│ ├── audit-core.js # 纯函数核心(UMD,浏览器/Node 共用):捕获、解析、语义动作、
│ │ # 登录判定、字段 diff、八维筛选、CSV、告警窗口
│ ├── mock-data.js # 种子随机模拟数据(约 141 条 + 7 条故事线,确定性输出)
│ ├── app.js # 交互层(渲染、筛选、历史、导出、设置、告警、模拟管线)
│ └── demo.css # 样式(视觉基调取自 @halo-dev/components)
└── test/
└── audit-core.test.mjs # 单元测试(node:test,29 个用例)
└── audit-core.test.mjs # 单元测试(node:test,56 个用例)
```
## 运行测试
@@ -66,18 +101,28 @@ demo/
node --test demo/test/audit-core.test.mjs
```
覆盖:捕获规则各分支(方法/路径/匿名/登录端点)、资源解析(集合/单资源/深层子资源/auth)、
筛选(操作者/资源类型/动作/结果/时间范围/关键字)、分页越界收敛、保留期统计、模拟数据确定性与字段完整性。
覆盖:捕获规则(HTTP / 认证端点 / 匿名 / 读操作)、资源解析(含查询串与深层子资源)、
语义动作推导与中文描述、登录结果判定(2xx / 302 / error 参数 / 401 / 失败回显)、
字段 diff(PUT / PATCH Merge / PATCH JSON Patch / POST / DELETE、元数据过滤、敏感字段脱敏、
截断、30 条封顶)、八维筛选(登录失败结果语义、时间闭区间、关键字)、分页与保留期、
CSV(BOM / CRLF / 列顺序 / 转义 / 公式注入防护 / 升序)、告警窗口(阈值、告警后重开、
成功清零、窗口过期)、模拟数据确定性与故事线完整性。
## 与真实实现的差异
| 项 | Demo | 真实插件 |
|---|---|---|
| 数据 | 页面内存中的模拟数据,刷新即重置 | `AuditLog` Extension 落库 + 索引查询 |
| 捕获 | 手动在弹窗里"发送请求"模拟 | `AfterSecurityWebFilter` 自动捕获 |
| 写入 | 直接 unshift 到数组 | `ReactiveExtensionClient` 异步直写、失败降级 |
| 设置 | 页面内存 | `settings.yaml` + ConfigMap(60s TTL 缓存) |
| 清理 | 点击按钮模拟 | 每日定时任务自动执行 |
| 捕获 | 弹窗里手动构造请求 | 双过滤器自动捕获(`/apis/**` + 认证端点) |
| 字段 diff | 与 Java 版同规则的 JS 简化实现(对象递归、数组整体比较、脱敏/截断/封顶) | `ChangeDiffEngine`(含 Halo 服务端字段更细的降噪与 JSON Pointer 解析) |
| 查询 | 前端数组筛选 | 自有查询端点(fieldSelector + 时间区间 + 模糊匹配) |
| 导出 | 浏览器 Blob 下载 | 后端全量流式 CSV(分批 200 条) |
| 设置 | 页面内存 | `settings.yaml` + ConfigMap(60s TTL) |
| 告警 | 本地阈值窗口 + JSON 预览 | Webhook JSON POST + SSRF 防护 + Secret 存储地址 |
| 系统变更 | 手动模拟 | `ReactiveExtensionClient.watch` 全局 Watcher |
| 权限 | 未演示(本地即超管视角) | 角色模板 `role-template-audit-view`,仅 `get/list` |
UI 结构(筛选维度、列定义、详情字段、设置项)与真实插件将保持一致,确认交互合理后即可按技术方案里程碑 4 实现 Console 页面。
静态演示页与真实 Console 页面(Vue 3)共享同一套展示语义(列定义、筛选维度、
描述推导、结果徽标、字段变更展示),但真实页面源码在
[`plugin-operation-audit/ui/src/views/`](../plugin-operation-audit/ui/src/views/),由 Halo
Console 宿主渲染。
+817 -280
View File
File diff suppressed because it is too large Load Diff
+1064 -73
View File
File diff suppressed because it is too large Load Diff
+308 -79
View File
@@ -15,6 +15,8 @@
--warn-tint: rgba(217, 119, 6, 0.1);
--info: #2563eb;
--info-tint: rgba(37, 99, 235, 0.1);
--purple: #7c3aed;
--purple-tint: rgba(124, 58, 237, 0.1);
--gray-50: #f9fafb;
--gray-100: #f3f4f6;
--gray-200: #e5e7eb;
@@ -30,12 +32,16 @@
* { box-sizing: border-box; }
html, body { height: 100%; }
/* hidden 属性优先于组件的 display 声明(如 .alert-banner{display:flex}) */
[hidden] { display: none !important; }
html { height: 100%; }
body {
margin: 0;
min-height: 100vh;
display: flex;
min-width: 1080px;
min-width: 1100px;
font-size: 14px;
color: var(--gray-900);
background: var(--gray-100);
@@ -165,6 +171,8 @@ body {
.readonly-hint { color: var(--primary-dark); }
.header-actions { display: flex; align-items: center; gap: 8px; flex-shrink: 0; }
.tabs {
display: flex;
gap: 4px;
@@ -207,6 +215,13 @@ body {
padding: 14px 18px 0;
}
.card-sub {
font-size: 12.5px;
color: var(--gray-500);
line-height: 1.6;
padding: 6px 18px 0;
}
.btn {
appearance: none;
border: none;
@@ -219,12 +234,17 @@ body {
align-items: center;
gap: 6px;
transition: filter 0.15s, background 0.15s;
white-space: nowrap;
}
.btn svg {
width: 13px;
height: 13px;
fill: currentColor;
width: 14px;
height: 14px;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.btn-primary { background: var(--primary); color: #fff; }
@@ -237,6 +257,8 @@ body {
}
.btn-outline:hover { border-color: var(--primary); color: var(--primary-dark); }
.btn-sm { padding: 6px 12px; font-size: 12.5px; }
.btn-link {
appearance: none;
border: none;
@@ -244,10 +266,8 @@ body {
color: var(--primary-dark);
font-size: 13px;
cursor: pointer;
padding: 8px 4px;
align-self: flex-end;
padding: 6px 4px;
}
.btn-link:hover { text-decoration: underline; }
.icon-btn {
@@ -262,8 +282,8 @@ body {
cursor: pointer;
line-height: 1;
}
.icon-btn:hover { background: var(--gray-100); color: var(--gray-900); }
.icon-btn[disabled] { opacity: 0.35; cursor: not-allowed; }
.input {
border: 1px solid var(--gray-300);
@@ -277,12 +297,13 @@ body {
}
.input:focus,
select:focus {
select:focus,
textarea:focus {
border-color: var(--primary);
box-shadow: 0 0 0 2px var(--primary-tint);
}
select, .input { min-width: 0; }
select, .input, textarea { min-width: 0; }
select {
appearance: none;
@@ -296,8 +317,21 @@ select {
cursor: pointer;
}
textarea {
border: 1px solid var(--gray-300);
border-radius: 6px;
padding: 8px 10px;
font-family: ui-monospace, Consolas, monospace;
font-size: 12px;
line-height: 1.55;
resize: vertical;
width: 100%;
}
.hint { font-size: 12px; color: var(--gray-400); }
.muted { color: var(--gray-400); font-size: 12px; }
.mono { font-family: ui-monospace, Consolas, monospace; }
.break-all { word-break: break-all; }
/* ============ 横幅 ============ */
.banner {
@@ -305,31 +339,64 @@ select {
padding: 10px 14px;
font-size: 13px;
margin-bottom: 14px;
line-height: 1.55;
}
.banner-warn { background: var(--warn-tint); color: var(--warn); border: 1px solid rgba(217, 119, 6, 0.25); }
.banner-danger { background: var(--danger-tint); color: var(--danger); border: 1px solid rgba(215, 29, 29, 0.25); }
.alert-banner {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.alert-banner-body { flex: 1; }
.alert-banner-actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
.alert-banner-actions .btn-link { color: var(--danger); }
/* ============ 筛选栏 ============ */
.filter-bar {
display: flex;
align-items: flex-end;
gap: 12px;
.filter-card {
padding: 12px 16px;
margin-bottom: 14px;
flex-wrap: wrap;
}
.filter-item { display: flex; flex-direction: column; gap: 4px; }
.filter-item.grow { flex: 1; min-width: 180px; }
.filter-item label { font-size: 11px; color: var(--gray-500); font-weight: 600; }
.filter-item select, .filter-item .input { min-width: 120px; width: 100%; }
.filter-grid {
display: grid;
grid-template-columns: repeat(8, minmax(0, 1fr)) auto;
gap: 10px 12px;
align-items: end;
}
/* ============ 表格 ============ */
.filter-item { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.filter-item > span { font-size: 11px; color: var(--gray-500); font-weight: 600; white-space: nowrap; }
.filter-item input,
.filter-item select { width: 100%; height: 32px; font-size: 12.5px; }
.filter-actions { display: flex; gap: 8px; }
.filter-note {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 10px;
padding-top: 10px;
border-top: 1px dashed var(--gray-200);
font-size: 12px;
color: var(--gray-500);
}
/* ============ 列表 ============ */
.table-card { overflow: hidden; }
.audit-list-wrap { overflow-x: auto; }
.audit-table {
width: 100%;
min-width: 900px;
border-collapse: collapse;
table-layout: fixed;
}
.audit-table th {
@@ -337,17 +404,18 @@ select {
font-size: 12px;
font-weight: 600;
color: var(--gray-500);
padding: 10px 16px;
padding: 10px 14px;
background: var(--gray-50);
border-bottom: 1px solid var(--gray-200);
white-space: nowrap;
}
.audit-table td {
padding: 10px 16px;
padding: 9px 14px;
border-bottom: 1px solid var(--gray-100);
font-size: 13px;
vertical-align: middle;
overflow: hidden;
}
.audit-table tbody tr {
@@ -356,20 +424,20 @@ select {
}
.audit-table tbody tr:hover { background: var(--gray-50); }
.audit-table tbody tr.selected td { background: var(--primary-tint); }
@keyframes rowFlash {
0% { background: var(--primary-tint); }
100% { background: transparent; }
}
tr.row-new td { animation: rowFlash 2.8s ease-out; }
tr.row-new td { animation: rowFlash 2.6s ease-out; }
.td-ip { color: var(--gray-500); font-variant-numeric: tabular-nums; white-space: nowrap; }
.td-time { color: var(--gray-700); font-variant-numeric: tabular-nums; white-space: nowrap; }
.td-ip { color: var(--gray-500); font-variant-numeric: tabular-nums; }
.cell-user { display: flex; align-items: center; gap: 8px; }
.cell-user { display: flex; align-items: center; gap: 8px; min-width: 0; }
.user-lines { min-width: 0; }
.u-name { font-size: 13px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.u-time { font-size: 11.5px; color: var(--gray-400); font-variant-numeric: tabular-nums; white-space: nowrap; }
/* 动作徽标 */
.method {
@@ -384,10 +452,17 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
.m-post { background: var(--info-tint); color: var(--info); }
.m-put { background: var(--warn-tint); color: var(--warn); }
.m-delete { background: var(--danger-tint); color: var(--danger); }
.m-patch { background: rgba(124, 58, 237, 0.1); color: #6d28d9; }
.m-patch { background: var(--purple-tint); color: var(--purple); }
.m-get { background: var(--gray-100); color: var(--gray-500); }
/* 资源列 */
.res-line {
display: flex;
align-items: center;
gap: 6px;
overflow: hidden;
white-space: nowrap;
}
.rt {
display: inline-block;
font-size: 11px;
@@ -396,29 +471,64 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
background: var(--gray-100);
border-radius: 4px;
padding: 2px 7px;
margin-right: 8px;
}
.rn { color: var(--gray-500); font-size: 12.5px; word-break: break-all; }
/* 结果徽标 */
.result {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12.5px;
font-weight: 500;
font-variant-numeric: tabular-nums;
}
.result i {
width: 7px;
height: 7px;
border-radius: 50%;
flex-shrink: 0;
}
.result.ok { color: #16a34a; }
.result.ok i { background: #16a34a; }
.result.fail { color: var(--danger); }
.result.fail i { background: var(--danger); }
.rn {
color: var(--gray-700);
font-size: 12.5px;
overflow: hidden;
text-overflow: ellipsis;
}
.history-link {
flex-shrink: 0;
font-size: 11.5px;
color: var(--primary-dark);
text-decoration: none;
cursor: pointer;
}
.history-link:hover { text-decoration: underline; }
.path-line {
margin-top: 2px;
font-family: ui-monospace, Consolas, monospace;
font-size: 11px;
color: var(--gray-400);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* 描述列 */
.action-desc {
display: inline-block;
max-width: 100%;
font-size: 12.5px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
.changes-hint {
display: inline-block;
margin-left: 4px;
padding: 1px 5px;
border-radius: 4px;
font-size: 10.5px;
color: var(--warn);
background: var(--warn-tint);
vertical-align: middle;
}
/* 结果徽标 */
.status-badge {
display: inline-block;
padding: 2px 7px;
border-radius: 4px;
font-size: 11.5px;
font-weight: 600;
font-family: ui-monospace, Consolas, monospace;
}
.status-ok { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
.status-fail { color: var(--danger); background: rgba(215, 29, 29, 0.12); }
/* 空状态 */
.empty-state {
@@ -444,11 +554,11 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
.pg-right { display: flex; align-items: center; gap: 8px; }
.pg-right select { padding: 5px 24px 5px 8px; font-size: 12.5px; }
.icon-btn[disabled] { opacity: 0.35; cursor: not-allowed; }
.pg-page { font-size: 12.5px; color: var(--gray-500); font-variant-numeric: tabular-nums; }
/* ============ 设置页 ============ */
#panel-settings .settings-card { max-width: 780px; }
.settings-card { margin-bottom: 16px; padding-bottom: 6px; }
#panel-settings .settings-card { max-width: 820px; }
.settings-card { margin-bottom: 16px; padding-bottom: 4px; }
.setting-row {
display: flex;
@@ -459,11 +569,18 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
border-bottom: 1px solid var(--gray-100);
}
.setting-text { max-width: 640px; }
.setting-text { max-width: 620px; }
.s-name { font-size: 14px; font-weight: 600; margin-bottom: 4px; }
.s-desc { font-size: 12.5px; color: var(--gray-500); line-height: 1.5; }
.s-desc { font-size: 12.5px; color: var(--gray-500); line-height: 1.55; }
.s-desc code {
background: var(--gray-100);
border-radius: 4px;
padding: 1px 5px;
font-size: 11.5px;
}
.input.num { width: 90px; text-align: center; }
.input.num { width: 96px; text-align: center; flex-shrink: 0; }
.input.secret-input { width: 280px; flex-shrink: 0; }
.settings-actions {
display: flex;
@@ -480,7 +597,16 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
}
.clean-stats .num-warn { color: var(--danger); font-weight: 600; }
.settings-card .btn { margin: 0 18px 16px; }
.alert-preview {
margin: 0 18px 16px;
padding: 12px;
background: var(--secondary);
color: #d1fae5;
border-radius: 6px;
font-size: 11.5px;
line-height: 1.55;
overflow-x: auto;
}
/* 开关 */
.switch { position: relative; display: inline-block; width: 40px; height: 22px; flex-shrink: 0; }
@@ -525,7 +651,7 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
flex-shrink: 0;
}
.avatar.sm { width: 22px; height: 22px; font-size: 10px; }
.avatar.sm { width: 24px; height: 24px; font-size: 11px; }
.c-a { background: #4ccba0; }
.c-b { background: #6366f1; }
@@ -545,8 +671,8 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
position: fixed;
top: 0;
right: 0;
width: 440px;
max-width: 92vw;
width: 480px;
max-width: 94vw;
height: 100vh;
background: #fff;
z-index: 50;
@@ -571,7 +697,13 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
}
.drawer-title { font-size: 16px; font-weight: 700; }
.drawer-sub { font-size: 12px; color: var(--gray-400); margin-top: 3px; font-family: ui-monospace, Consolas, monospace; }
.drawer-sub {
font-size: 11.5px;
color: var(--gray-400);
margin-top: 3px;
font-family: ui-monospace, Consolas, monospace;
word-break: break-all;
}
.readonly-banner {
background: var(--primary-tint);
@@ -586,24 +718,26 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
.detail-list { margin: 0; }
.detail-list .d-row {
padding: 9px 0;
display: flex;
gap: 12px;
padding: 8px 0;
border-bottom: 1px dashed var(--gray-200);
}
.detail-list dt {
font-size: 11.5px;
flex: 0 0 5.5rem;
font-size: 12px;
color: var(--gray-500);
font-weight: 600;
margin-bottom: 5px;
padding-top: 1px;
}
.detail-list dd {
flex: 1;
margin: 0;
font-size: 13px;
font-size: 12.5px;
word-break: break-all;
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.path-code {
@@ -617,9 +751,48 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
line-height: 1.6;
}
.ua { font-size: 12px; color: var(--gray-500); line-height: 1.6; }
.ua { font-size: 11.5px; color: var(--gray-500); line-height: 1.6; }
.raw-json { margin-top: 16px; }
.changes { margin-top: 18px; }
.changes-title {
font-size: 13px;
font-weight: 600;
color: var(--gray-900);
margin: 0 0 6px;
}
.change-row {
display: flex;
gap: 10px;
padding: 8px 0;
border-bottom: 1px dashed var(--gray-200);
}
.change-badge {
flex: 0 0 auto;
align-self: flex-start;
margin-top: 1px;
padding: 1px 6px;
border-radius: 4px;
font-size: 11px;
font-weight: 600;
}
.change-added { color: #0f766e; background: rgba(76, 203, 160, 0.15); }
.change-updated { color: var(--warn); background: var(--warn-tint); }
.change-removed { color: var(--danger); background: var(--danger-tint); }
.change-body { flex: 1; min-width: 0; }
.change-field { font-size: 12px; color: var(--gray-900); word-break: break-all; }
.change-values {
display: flex;
align-items: baseline;
flex-wrap: wrap;
gap: 5px;
margin-top: 2px;
font-size: 12px;
color: var(--gray-700);
}
.change-old { color: var(--danger); text-decoration: line-through; }
.change-arrow { color: var(--gray-400); flex-shrink: 0; }
.raw-json { margin-top: 18px; }
.raw-json summary {
font-size: 12.5px;
color: var(--gray-500);
@@ -631,11 +804,12 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
.raw-json pre {
background: var(--secondary);
color: #d1fae5;
font-size: 11.5px;
font-size: 11px;
border-radius: 6px;
padding: 12px;
overflow-x: auto;
line-height: 1.6;
max-height: 320px;
}
/* ============ 模拟操作弹窗 ============ */
@@ -644,8 +818,10 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 520px;
max-width: 92vw;
width: 680px;
max-width: 94vw;
max-height: 90vh;
overflow-y: auto;
background: #fff;
border-radius: 10px;
z-index: 50;
@@ -656,7 +832,7 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
.modal[hidden] { display: none; }
@keyframes popIn {
from { transform: translate(-50%, -50%) scale(0.96); opacity: 0; }
from { transform: translate(-50%, -50%) scale(0.97); opacity: 0; }
to { transform: translate(-50%, -50%) scale(1); opacity: 1; }
}
@@ -674,7 +850,7 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
font-size: 12.5px;
color: var(--gray-500);
line-height: 1.6;
margin: 8px 0 14px;
margin: 8px 0 12px;
}
.modal-sub code {
@@ -684,9 +860,35 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
font-size: 11.5px;
}
.field { display: flex; flex-direction: column; gap: 5px; margin-bottom: 12px; flex: 1; }
.seg-tabs {
display: inline-flex;
background: var(--gray-100);
border-radius: 7px;
padding: 3px;
margin-bottom: 14px;
}
.seg-tab {
appearance: none;
border: none;
background: none;
padding: 6px 14px;
font-size: 12.5px;
font-weight: 500;
color: var(--gray-500);
border-radius: 5px;
cursor: pointer;
}
.seg-tab.active {
background: #fff;
color: var(--gray-900);
font-weight: 600;
box-shadow: var(--shadow);
}
.field { display: flex; flex-direction: column; gap: 5px; margin-bottom: 12px; flex: 1; min-width: 0; }
.field label { font-size: 12px; color: var(--gray-500); font-weight: 600; }
.field select, .field .input { width: 100%; }
.field textarea { width: 100%; }
.field-row { display: flex; gap: 12px; }
@@ -710,7 +912,13 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 6px;
/* 弹窗内容超高时操作按钮始终可见 */
position: sticky;
bottom: -20px;
margin: 6px -22px -20px;
padding: 12px 22px 20px;
border-top: 1px solid var(--gray-100);
background: #fff;
}
/* ============ Toast ============ */
@@ -729,9 +937,30 @@ tr.row-new td { animation: rowFlash 2.6s ease-out; }
pointer-events: none;
transition: opacity 0.25s, transform 0.25s;
z-index: 100;
max-width: 60vw;
max-width: 70vw;
}
.toast.show { opacity: 1; transform: translate(-50%, 0); }
.toast.ok { background: var(--primary-dark); }
.toast.warn { background: #92400e; }
/* ============ 响应式(演示页以桌面为主,窄屏保证可用) ============ */
@media (max-width: 1400px) {
.filter-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.filter-actions { grid-column: 1 / -1; }
}
@media (max-width: 1180px) {
body { min-width: 900px; }
.page-header { flex-direction: column; }
.header-actions { align-self: flex-end; }
}
@media (max-width: 760px) {
body { min-width: 0; }
.sidebar { display: none; }
.main { padding: 16px 14px 32px; }
.filter-grid { grid-template-columns: minmax(0, 1fr); }
.field-row { flex-direction: column; gap: 0; }
.modal { width: 94vw; }
}
+592 -117
View File
@@ -1,9 +1,18 @@
/**
* 操作审计 · 模拟数据生成器(种子随机,确定性输出)
*
* 记录字段与产品设计 4.1 表格一一对应;resourceType/resourceName 通过
* AuditCore.resolveResource 从路径解析得出(模拟真实捕获管线)。
* 内置若干"故事线"数据:登录爆破、越权 403、服务端 500 等,便于验证筛选场景。
* 记录字段与插件 spec 一致:username / attemptedUsername / method / action /
* resourceType / resourceName / path / statusCode / remoteIp / userAgent / changes。
* 资源解析、语义动作、登录结果与字段 diff 全部经 AuditCore 按真实捕获管线推导,
* 便于在演示页复现「谁改了什么」而不仅是「谁点了什么」。
*
* 内置故事线(固定时间锚点,可直接按演示页提示复现):
* 1. 排查「hello-halo 这篇文章谁改过」(多用户多次编辑,含字段 diff)
* 2. 登录爆破回溯(同一 IP、无差别撞库,含失败回显页)
* 3. 忘记密码后登录成功(失败 → 成功清零)
* 4. 定时发布(系统内部变更,执行者「系统」、无 IP/UA)
* 5. 插件生命周期(升级 / 停用 / 卸载,含字段 diff)
* 6. 越权与异常(403 / 404 / 500)
*/
(function (root, factory) {
if (typeof module === 'object' && module.exports) {
@@ -16,7 +25,7 @@
var DAY = 86400000;
var MIN = 60000;
var BASE_COUNT = 128; // 随机生成的基础记录条数
var BASE_COUNT = 116;
// ---------- 种子随机 ----------
function mulberry32(seed) {
@@ -38,10 +47,17 @@
function hex(r, n) {
var s = '';
var chars = '0123456789abcdef';
for (var i = 0; i < n; i++) s += chars[rint(r, 0, 15)];
for (var i = 0; i < n; i++) {
s += chars[rint(r, 0, 15)];
}
return s;
}
/** 演示用的一次性假口令(运行时生成,非真实凭据;仅用于验证敏感字段脱敏)。 */
function demoSecret(r) {
return 'demo-only-' + hex(r, 12);
}
// ---------- 基础素材 ----------
var UAS = {
chrome: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.2151.97 Safari/537.36',
@@ -52,156 +68,615 @@
};
var USERS = {
'guichumo': { ips: ['192.168.1.23', '116.24.65.187'], uas: ['chrome', 'edge'] },
guichumo: { ips: ['192.168.1.23', '116.24.65.187'], uas: ['chrome', 'edge'] },
'editor.zhang': { ips: ['116.24.65.201'], uas: ['edge', 'firefox'] },
'writer.li': { ips: ['120.79.10.45'], uas: ['safari', 'chrome'] }
};
var SLUGS = ['hello-halo', 'self-host-guide', 'weekly-2026-w46', 'reading-notes-11', 'plugin-dev-diary', 'spring-festival-2026'];
var PLUGINS = ['plugin-search-widget', 'plugin-comment-widget', 'plugin-sitemap', 'plugin-links'];
function postPath(r) { return '/apis/content.halo.run/v1alpha1/posts/' + pick(r, SLUGS); }
function publishPath(r) { return '/apis/api.content.halo.run/v1alpha1/posts/' + pick(r, SLUGS) + '/publish'; }
function commentPath(r) { return '/apis/content.halo.run/v1alpha1/comments/comment-' + hex(r, 6); }
function approvePath(r) { return '/apis/api.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/approve'; }
function replyPath(r) { return '/apis/api.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/reply'; }
function attachPath(r) { return '/apis/storage.halo.run/v1alpha1/attachments/attachment-' + hex(r, 6); }
// [权重, 操作者, 方法, 路径函数, 状态码]
var ACTIONS = [
[16, 'guichumo', 'PUT', postPath, 200],
[10, 'guichumo', 'POST', publishPath, 200],
[6, 'guichumo', 'POST', function () { return '/apis/content.halo.run/v1alpha1/posts'; }, 201],
[5, 'guichumo', 'PUT', function () { return '/apis/v1alpha1/configmaps/system'; }, 200],
[4, 'guichumo', 'PUT', function (r) { return '/apis/plugin.halo.run/v1alpha1/plugins/' + pick(r, PLUGINS); }, 200],
[4, 'guichumo', 'POST', function () { return '/apis/storage.halo.run/v1alpha1/attachments'; }, 201],
[4, 'guichumo', 'DELETE', attachPath, 204],
[3, 'guichumo', 'DELETE', commentPath, 204],
[3, 'guichumo', 'PUT', function () { return '/apis/v1alpha1/roles/role-template-editor'; }, 200],
[2, 'guichumo', 'POST', function () { return '/login'; }, 200],
[2, 'guichumo', 'POST', function () { return '/logout'; }, 200],
[12, 'editor.zhang', 'PUT', postPath, 200],
[6, 'editor.zhang', 'POST', function () { return '/apis/content.halo.run/v1alpha1/posts'; }, 201],
[2, 'editor.zhang', 'POST', function () { return '/login'; }, 200],
[2, 'editor.zhang', 'POST', function () { return '/apis/storage.halo.run/v1alpha1/attachments'; }, 201],
[8, 'writer.li', 'PUT', postPath, 200],
[6, 'writer.li', 'POST', approvePath, 200],
[3, 'writer.li', 'POST', replyPath, 200],
[2, 'writer.li', 'POST', function () { return '/login'; }, 200]
var POSTS = [
{ name: 'hello-halo', title: '你好,Halo', summary: '从零开始搭建自己的写作空间。' },
{ name: 'self-host-guide', title: '自托管指南', summary: '用 Docker 部署 Halo 的完整步骤。' },
{ name: 'reading-notes-11', title: '读书笔记 #11', summary: '本周读完的三本书。' },
{ name: 'plugin-dev-diary', title: '插件开发日志', summary: '从脚手架到上架。' },
{ name: 'weekly-2026-w46', title: '每周摘要 · 2026 W46', summary: '站点一周动态。' },
{ name: 'spring-festival-2026', title: '春节计划', summary: '假期更新安排。' }
];
var TOTAL_WEIGHT = ACTIONS.reduce(function (sum, a) { return sum + a[0]; }, 0);
var PLUGINS = [
{ name: 'plugin-search-widget', displayName: '搜索组件', version: { old: '1.2.0', next: '1.3.0' } },
{ name: 'plugin-comment-widget', displayName: '评论组件', version: { old: '1.5.0', next: '1.6.0' } },
{ name: 'plugin-sitemap', displayName: 'Sitemap', version: { old: '1.0.4', next: '1.0.5' } },
{ name: 'plugin-links', displayName: '友情链接', version: { old: '2.1.1', next: '2.2.0' } }
];
function userCtx(r, name) {
var u = USERS[name];
// ---------- 文档快照(diff 用,结构贴近 Halo 扩展模型)----------
function postDoc(entry, patch) {
var spec = {
title: entry.title,
slug: entry.name,
visible: 'PUBLIC',
publish: true,
pinned: false,
allowComment: true,
summary: entry.summary
};
Object.keys(patch || {}).forEach(function (key) {
spec[key] = patch[key];
});
return {
username: name,
remoteIp: pick(r, u.ips),
userAgent: UAS[pick(r, u.uas)]
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Post',
metadata: {
name: entry.name,
labels: { 'content.halo.run/pinned': 'false' },
annotations: { 'content.halo.run/permalink-pattern': '/archives/:slug' },
version: 128,
creationTimestamp: '2026-10-01T08:00:00Z'
},
spec: spec,
status: { phase: 'PUBLISHED', permalink: '/archives/' + entry.name }
};
}
function rec(timestamp, username, method, path, statusCode, remoteIp, userAgent) {
var res = AuditCore.resolveResource(path);
function commentDoc(name, approved) {
return {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Comment',
metadata: { name: name, version: 7 },
spec: {
raw: '写得很好,收藏了。',
owner: { displayName: '访客' + name.slice(-4), kind: 'Email' },
approved: approved,
hidden: false,
allowNotification: true
}
};
}
function pluginDoc(plugin, enabled, version) {
return {
apiVersion: 'plugin.halo.run/v1alpha1',
kind: 'Plugin',
metadata: { name: plugin.name, labels: { 'plugin.halo.run/plugin-name': plugin.name } },
spec: {
displayName: plugin.displayName,
version: version,
enabled: enabled,
author: { name: 'halo-sigs' },
requires: '>=2.20.0'
},
status: { phase: enabled ? 'STARTED' : 'DISABLED' }
};
}
// ---------- 记录组装 ----------
function recCtx(r, username) {
var u = USERS[username] || USERS.guichumo;
return {
id: null,
timestamp: timestamp,
username: username,
method: AuditCore.normalizeMethod(method),
path: path,
resourceType: res.resourceType,
resourceName: res.resourceName,
statusCode: statusCode,
remoteIp: remoteIp,
userAgent: userAgent
remoteIp: pick(r, u.ips),
userAgent: UAS[pick(r, u.uas)],
authenticated: true
};
}
function make(overrides) {
return AuditCore.buildRecord(Object.assign({
statusCode: 200,
authenticated: true,
recordChanges: true
}, overrides));
}
function postPath(name) { return '/apis/content.halo.run/v1alpha1/posts/' + name; }
function postsPath() { return '/apis/content.halo.run/v1alpha1/posts'; }
function commentPath(name) { return '/apis/content.halo.run/v1alpha1/comments/' + name; }
function pluginPath(name) { return '/apis/plugin.halo.run/v1alpha1/plugins/' + name; }
/**
* 基础操作集:[权重, 构造函数(r) → 记录输入]
* 每次构造经过 buildRecord:资源解析、语义动作、登录结果、字段 diff 与插件一致。
*/
var ACTIONS = [
[16, function (r) {
var entry = pick(r, POSTS);
var ctx = recCtx(r, pick(r, ['guichumo', 'editor.zhang', 'writer.li']));
return Object.assign(ctx, {
method: 'PUT',
path: postPath(entry.name),
previous: postDoc(entry),
body: postDoc(entry, {
title: entry.title + '(修订)',
summary: entry.summary + ' 已补充示例。'
})
});
}],
[9, function (r) {
var entry = pick(r, POSTS);
var ctx = recCtx(r, pick(r, ['guichumo', 'editor.zhang']));
return Object.assign(ctx, {
method: 'POST',
path: postPath(entry.name) + '/publish'
});
}],
[7, function (r) {
var ctx = recCtx(r, 'guichumo');
var slug = 'draft-' + hex(r, 5);
return Object.assign(ctx, {
method: 'POST',
path: postsPath(),
statusCode: 201,
body: {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Post',
metadata: { name: slug },
spec: { title: '草稿 · ' + slug, slug: slug, visible: 'PUBLIC', publish: false }
}
});
}],
[6, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/api.console.halo.run/v1alpha1/configmaps/system',
previous: {
apiVersion: 'v1alpha1',
kind: 'ConfigMap',
metadata: { name: 'system', version: 9 },
data: { theme: 'theme-earth', locale: 'zh-CN' }
},
body: {
apiVersion: 'v1alpha1',
kind: 'ConfigMap',
metadata: { name: 'system', version: 10 },
data: { theme: 'theme-earth', locale: 'zh-CN', 'site.title': '青竹小站' }
}
});
}],
[5, function (r) {
var plugin = pick(r, PLUGINS);
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: pluginPath(plugin.name) + '/activation',
previous: pluginDoc(plugin, false, plugin.version.old),
body: pluginDoc(plugin, true, plugin.version.old)
});
}],
[5, function (r) {
var ctx = recCtx(r, pick(r, ['editor.zhang', 'writer.li']));
var name = 'attachment-' + hex(r, 6);
return Object.assign(ctx, {
method: 'POST',
path: '/apis/storage.halo.run/v1alpha1/attachments',
statusCode: 201,
body: {
apiVersion: 'storage.halo.run/v1alpha1',
kind: 'Attachment',
metadata: { name: name },
spec: { displayName: 'cover-' + hex(r, 4) + '.png', mediaType: 'image/png', size: rint(r, 80, 640) * 1024 }
}
});
}],
[3, function (r) {
var ctx = recCtx(r, 'editor.zhang');
var name = 'attachment-' + hex(r, 6);
return Object.assign(ctx, {
method: 'DELETE',
path: '/apis/storage.halo.run/v1alpha1/attachments/' + name,
statusCode: 204,
previous: {
apiVersion: 'storage.halo.run/v1alpha1',
kind: 'Attachment',
metadata: { name: name },
spec: { displayName: 'old-cover.png', mediaType: 'image/png', size: 245760 }
}
});
}],
[4, function (r) {
var ctx = recCtx(r, 'writer.li');
return Object.assign(ctx, {
method: 'POST',
path: '/apis/api.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/reply',
body: {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Reply',
metadata: { name: 'reply-' + hex(r, 4) },
spec: { raw: '感谢支持,已更新示例。', quoteReply: 'comment-' + hex(r, 4) }
}
});
}],
[3, function (r) {
var ctx = recCtx(r, 'editor.zhang');
var name = 'comment-' + hex(r, 6);
return Object.assign(ctx, {
method: 'DELETE',
path: commentPath(name),
statusCode: 204,
previous: commentDoc(name, true)
});
}],
[3, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/api.console.halo.run/v1alpha1/roles/role-template-editor',
previous: {
apiVersion: 'v1alpha1',
kind: 'Role',
metadata: { name: 'role-template-editor', labels: { 'rbac.authorization.halo.run/display-name': '编辑' } },
rules: [{ apiGroups: ['content.halo.run'], resources: ['posts'], verbs: ['get', 'list', 'create', 'update'] }]
},
body: {
apiVersion: 'v1alpha1',
kind: 'Role',
metadata: { name: 'role-template-editor', labels: { 'rbac.authorization.halo.run/display-name': '编辑' } },
rules: [{ apiGroups: ['content.halo.run'], resources: ['posts'], verbs: ['get', 'list', 'create', 'update', 'delete'] }]
}
});
}],
[2, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'POST',
path: '/apis/api.console.halo.run/v1alpha1/users',
statusCode: 201,
body: {
apiVersion: 'v1alpha1',
kind: 'User',
metadata: { name: 'alice-' + hex(r, 4) },
spec: {
displayName: 'Alice',
email: 'alice-' + hex(r, 3) + '@example.com',
// 运行时生成的假口令:用于验证 spec.password 在 diff 中被脱敏
password: demoSecret(r),
roles: ['role-template-author']
}
}
});
}],
[2, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/api.console.halo.run/v1alpha1/users/guichumo/password',
previous: {
apiVersion: 'v1alpha1',
kind: 'User',
metadata: { name: 'guichumo' },
spec: { password: demoSecret(r) }
},
body: {
apiVersion: 'v1alpha1',
kind: 'User',
metadata: { name: 'guichumo' },
spec: { password: demoSecret(r) }
}
});
}],
[2, function (r) {
var ctx = recCtx(r, 'writer.li');
return Object.assign(ctx, {
method: 'POST',
path: '/apis/content.halo.run/v1alpha1/comments/comment-' + hex(r, 6) + '/approve'
});
}],
[2, function (r) {
var ctx = recCtx(r, 'editor.zhang');
return Object.assign(ctx, {
method: 'POST',
path: '/apis/api.console.halo.run/v1alpha1/categories',
statusCode: 201,
body: {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Category',
metadata: { name: 'category-' + hex(r, 4) },
spec: { displayName: '技术随笔', slug: 'tech-notes', priority: 10 }
}
});
}],
[2, function (r) {
var ctx = recCtx(r, 'editor.zhang');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/theme.halo.run/v1alpha1/themes/theme-earth/activation'
});
}],
[1, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/api.halo.run/v1alpha1/settings/basic'
});
}],
[1, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'POST',
path: '/apis/api.halo.run/v1alpha1/tags',
statusCode: 201,
body: {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Tag',
metadata: { name: 'tag-' + hex(r, 4) },
spec: { displayName: 'Halo', slug: 'halo' }
}
});
}],
[1, function (r) {
var ctx = recCtx(r, 'guichumo');
return Object.assign(ctx, {
method: 'PUT',
path: '/apis/api.halo.run/v1alpha1/menus/menu-primary',
previous: {
apiVersion: 'v1alpha1',
kind: 'Menu',
metadata: { name: 'menu-primary' },
spec: { displayName: '主菜单', menuItems: ['/archives', '/categories'] }
},
body: {
apiVersion: 'v1alpha1',
kind: 'Menu',
metadata: { name: 'menu-primary' },
spec: { displayName: '主菜单', menuItems: ['/archives', '/categories', '/about'] }
}
});
}]
];
var TOTAL_WEIGHT = ACTIONS.reduce(function (sum, item) { return sum + item[0]; }, 0);
/**
* 生成模拟审计日志(按时间倒序,id 从旧到新递增)
* @param {number} [now] 当前时间戳(默认 Date.now()),测试传固定值保证确定性
* @returns {Array}
*/
function generateLogs(now) {
if (typeof now !== 'number') now = Date.now();
var r = mulberry32(20261121);
if (typeof now !== 'number') {
now = Date.now();
}
var r = mulberry32(20261122);
var logs = [];
// 基础记录:均匀散布在近 90 天
for (var i = 0; i < BASE_COUNT; i++) {
var roll = r() * TOTAL_WEIGHT;
var action = ACTIONS[0];
for (var j = 0; j < ACTIONS.length; j++) {
roll -= ACTIONS[j][0];
if (roll <= 0) { action = ACTIONS[j]; break; }
}
var ctx = userCtx(r, action[1]);
var time = now - rint(r, 5 * MIN, 90 * DAY);
logs.push(rec(
new Date(time).toISOString(), ctx.username,
action[2], action[3](r), action[4],
ctx.remoteIp, ctx.userAgent
));
function add(record) {
logs.push(record);
return record;
}
// ---- 故事线(固定时间锚点)----
// ---- 基础记录:均匀散布在近 90 天 ----
for (var i = 0; i < BASE_COUNT; i++) {
var roll = r() * TOTAL_WEIGHT;
var action = ACTIONS[0][1];
for (var j = 0; j < ACTIONS.length; j++) {
roll -= ACTIONS[j][0];
if (roll <= 0) {
action = ACTIONS[j][1];
break;
}
}
var input = action(r);
input.timestamp = new Date(now - rint(r, 5 * MIN, 90 * DAY)).toISOString();
add(make(input));
}
// 1. 攻击者爆破登录:20 天前,同一 IP 6 次失败,UA 为 python-requests
var burstBase = now - 20 * DAY - 3600 * 1000 * 3; // 约 20 天前的凌晨
[0, 41, 88, 135, 210, 400].forEach(function (off) {
logs.push(rec(
new Date(burstBase + off * 1000).toISOString(), '未知用户',
'POST', '/login', 401, '203.0.113.66', UAS.bot
));
// ---- 故事线 1:排查「hello-halo 这篇文章谁改过」 ----
var hello = POSTS[0];
add(make({
username: 'editor.zhang',
remoteIp: '116.24.65.201',
userAgent: UAS.edge,
method: 'PUT',
path: postPath(hello.name),
timestamp: new Date(now - 6 * DAY - 3 * 3600 * 1000).toISOString(),
previous: postDoc(hello),
body: postDoc(hello, { title: '你好,Halo(补充开箱截图)', summary: '从零开始搭建自己的写作空间,附开箱截图。' })
}));
add(make({
username: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'PUT',
path: postPath(hello.name),
timestamp: new Date(now - 2 * DAY - 5 * 3600 * 1000).toISOString(),
previous: postDoc(hello, { title: '你好,Halo(补充开箱截图)' }),
body: postDoc(hello, { title: '你好,Halo', summary: '从零开始搭建自己的写作空间。', visible: 'PRIVATE' })
}));
add(make({
username: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'PUT',
path: postPath(hello.name),
timestamp: new Date(now - 2 * DAY - 2 * 3600 * 1000).toISOString(),
previous: postDoc(hello, { visible: 'PRIVATE' }),
body: postDoc(hello, { visible: 'PUBLIC', pinned: true })
}));
// ---- 故事线 2:登录爆破回溯(同一 IP 无差别撞库 + 失败回显) ----
var burstBase = now - 20 * DAY - 3 * 3600 * 1000;
var attackAccounts = ['admin', 'root', 'oracle', 'test', 'admin', 'postgres'];
attackAccounts.forEach(function (account, idx) {
add(make({
method: 'POST',
path: '/login',
statusCode: 302,
location: '/login?error=invalid-credential&method=form',
attemptedUsername: account,
remoteIp: '203.0.113.66',
userAgent: UAS.bot,
timestamp: new Date(burstBase + [0, 41, 88, 135, 210, 400][idx] * 1000).toISOString()
}));
});
// 浏览器随后渲染失败回显页(GET,HTTP 200):审计标注 login-failure,红色「失败」
add(make({
method: 'GET',
path: '/login?error=invalid-credential&method=form',
statusCode: 200,
remoteIp: '203.0.113.66',
userAgent: UAS.bot,
timestamp: new Date(burstBase + 401 * 1000).toISOString()
}));
// 2. 站长忘记密码:12 天前输错两次后登录成功
var b2 = now - 12 * DAY - 3600 * 1000 * 10;
[[0, 401], [97, 401], [180, 200]].forEach(function (pair) {
var ctx = { remoteIp: '192.168.1.23', userAgent: UAS.chrome };
logs.push(rec(
new Date(b2 + pair[0] * 1000).toISOString(),
pair[1] === 200 ? 'guichumo' : '未知用户',
'POST', '/login', pair[1], ctx.remoteIp, ctx.userAgent
));
// ---- 故事线 3:忘记密码(失败两次后成功) ----
var retryBase = now - 12 * DAY - 10 * 3600 * 1000;
[
{ at: 0, account: 'guichumo', ok: false },
{ at: 97, account: 'guichumo', ok: false },
{ at: 180, account: 'guichumo', ok: true }
].forEach(function (step) {
add(make({
username: 'guichumo',
method: 'POST',
path: '/login',
statusCode: 302,
location: step.ok ? '/uc' : '/login?error=bad-credentials&method=form',
attemptedUsername: step.account,
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
timestamp: new Date(retryBase + step.at * 1000).toISOString()
}));
});
add(make({
username: 'guichumo',
method: 'POST',
path: '/login',
statusCode: 302,
location: '/challenges/two-factor/totp',
attemptedUsername: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
timestamp: new Date(now - 9 * DAY - 8 * 3600 * 1000).toISOString()
}));
add(make({
username: 'guichumo',
method: 'POST',
path: '/logout',
statusCode: 302,
location: '/login?logout',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
timestamp: new Date(now - 4 * DAY - 11 * 3600 * 1000).toISOString()
}));
// 3. 越权尝试:8 天前 editor.zhang 尝试修改系统设置被拒绝
logs.push(rec(
new Date(now - 8 * DAY - 3600 * 1000 * 14).toISOString(), 'editor.zhang',
'PUT', '/apis/v1alpha1/configmaps/system', 403, '116.24.65.201', UAS.edge
));
// ---- 故事线 4:定时发布(系统内部变更:无 IP/UA,执行者「系统」) ----
add(AuditCore.buildSystemRecord({
id: 'auditlog-system-0001',
timestamp: new Date(now - DAY - 5 * 3600 * 1000).toISOString(),
method: 'PUT',
resourceType: 'posts',
resourceName: 'weekly-2026-w46',
path: '/apis/content.halo.run/v1alpha1/posts/weekly-2026-w46',
changes: [
{ field: 'spec.publish', changeType: 'UPDATED', oldValue: 'false', newValue: 'true' },
{ field: 'spec.publishTime', changeType: 'ADDED', oldValue: null, newValue: '2026-11-21T02:00:00Z' }
]
}));
add(AuditCore.buildSystemRecord({
id: 'auditlog-system-0002',
timestamp: new Date(now - 3 * DAY - 4 * 3600 * 1000).toISOString(),
method: 'DELETE',
resourceType: 'posts',
resourceName: 'draft-night-notes',
path: '/apis/content.halo.run/v1alpha1/posts/draft-night-notes',
changes: [
{ field: 'spec.title', changeType: 'REMOVED', oldValue: '夜间随笔(未发布)', newValue: null },
{ field: 'metadata.name', changeType: 'REMOVED', oldValue: 'draft-night-notes', newValue: null }
]
}));
// 4. 权限不足:5 天前 writer.li 尝试删除评论被拒绝
logs.push(rec(
new Date(now - 5 * DAY - 3600 * 1000 * 9).toISOString(), 'writer.li',
'DELETE', '/apis/content.halo.run/v1alpha1/comments/comment-a3f802', 403, '120.79.10.45', UAS.safari
));
// ---- 故事线 5:插件生命周期(升级 / 停用 / 卸载) ----
var search = PLUGINS[0];
add(make({
username: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'PUT',
path: pluginPath(search.name) + '/upgrade',
previous: pluginDoc(search, true, search.version.old),
body: pluginDoc(search, true, search.version.next),
timestamp: new Date(now - 7 * DAY - 6 * 3600 * 1000).toISOString()
}));
add(make({
username: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'PUT',
path: pluginPath(search.name) + '/activation',
previous: pluginDoc(search, true, search.version.next),
body: pluginDoc(search, false, search.version.next),
timestamp: new Date(now - 6 * DAY - 9 * 3600 * 1000).toISOString()
}));
var links = PLUGINS[3];
add(make({
username: 'guichumo',
remoteIp: '116.24.65.187',
userAgent: UAS.edge,
method: 'DELETE',
path: pluginPath(links.name) + '/uninstall',
statusCode: 204,
previous: pluginDoc(links, true, links.version.next),
timestamp: new Date(now - 1 * DAY - 7 * 3600 * 1000).toISOString()
}));
// 5. 资源不存在:3 天前删除一个已不存在的附件
logs.push(rec(
new Date(now - 3 * DAY - 3600 * 1000 * 20).toISOString(), 'guichumo',
'DELETE', '/apis/storage.halo.run/v1alpha1/attachments/attachment-dead42', 404, '192.168.1.23', UAS.chrome
));
// ---- 故事线 6:越权与异常 ----
add(make({
username: 'editor.zhang',
remoteIp: '116.24.65.201',
userAgent: UAS.edge,
method: 'PUT',
path: '/apis/api.console.halo.run/v1alpha1/configmaps/system',
statusCode: 403,
timestamp: new Date(now - 8 * DAY - 14 * 3600 * 1000).toISOString()
}));
add(make({
username: 'writer.li',
remoteIp: '120.79.10.45',
userAgent: UAS.safari,
method: 'DELETE',
path: commentPath('comment-a3f802'),
statusCode: 403,
timestamp: new Date(now - 5 * DAY - 9 * 3600 * 1000).toISOString()
}));
add(make({
username: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'DELETE',
path: '/apis/storage.halo.run/v1alpha1/attachments/attachment-dead42',
statusCode: 404,
timestamp: new Date(now - 3 * DAY - 20 * 3600 * 1000).toISOString()
}));
add(make({
username: 'writer.li',
remoteIp: '120.79.10.45',
userAgent: UAS.chrome,
method: 'POST',
path: '/apis/api.content.halo.run/v1alpha1/posts/self-host-guide/publish',
statusCode: 500,
timestamp: new Date(now - 2 * DAY - 6 * 3600 * 1000).toISOString()
}));
// 6. 服务端异常:2 天前发布文章返回 500
logs.push(rec(
new Date(now - 2 * DAY - 3600 * 1000 * 6).toISOString(), 'writer.li',
'POST', '/apis/api.content.halo.run/v1alpha1/posts/self-host-guide/publish', 500, '120.79.10.45', UAS.chrome
));
// ---- 故事线 7:误操作定位(删除文章,含字段 diff) ----
var deleted = { name: 'weekly-2026-w45', title: '每周摘要 · 2026 W45', summary: '站点一周动态。' };
add(make({
username: 'guichumo',
remoteIp: '192.168.1.23',
userAgent: UAS.chrome,
method: 'DELETE',
path: postPath(deleted.name),
statusCode: 204,
previous: postDoc(deleted),
timestamp: new Date(now - DAY - 2 * 3600 * 1000).toISOString()
}));
// 7. 误操作定位:1 天前删除了一篇文章
logs.push(rec(
new Date(now - DAY - 3600 * 1000 * 2).toISOString(), 'guichumo',
'DELETE', '/apis/content.halo.run/v1alpha1/posts/weekly-2026-w45', 204, '192.168.1.23', UAS.chrome
));
// 排序 + 分配 id(最新记录 id 数字最大)
// ---- 排序 + 分配记录标识(最新记录编号最大) ----
logs.sort(function (a, b) {
return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();
});
logs.forEach(function (l, idx) {
l.id = 'audit-' + String(logs.length - idx).padStart(4, '0');
logs.forEach(function (log, idx) {
if (!log.id || log.id.indexOf('auditlog-system-') !== 0) {
log.id = 'auditlog-' + String(logs.length - idx).padStart(4, '0');
}
});
return logs;
}
+288 -101
View File
@@ -66,12 +66,23 @@
<div class="page-header">
<div>
<h1>操作审计</h1>
<p class="page-sub">谁 · 在什么时候 · 对什么资源 · 做了什么操作 · 结果如何 <span class="readonly-hint">(只读,不可篡改)</span></p>
<p class="page-sub">谁 · 在什么时候 · 对什么资源 · 做了什么操作 · 结果如何 · 改了什么
<span class="readonly-hint">(只读,不可篡改)</span></p>
</div>
<div class="header-actions">
<button class="btn btn-outline" id="btn-export" title="按当前筛选条件导出全部记录(UTF-8 BOM CSV)">
<svg viewBox="0 0 24 24"><path d="M12 3v12m0 0 4-4m-4 4-4-4M5 20h14"/></svg>
导出
</button>
<button class="btn btn-outline" id="btn-refresh" title="按当前筛选重新查询">
<svg viewBox="0 0 24 24"><path d="M20 12a8 8 0 1 1-2.3-5.6M20 4v4h-4"/></svg>
刷新
</button>
<button class="btn btn-primary" id="btn-simulate">
<svg viewBox="0 0 24 24"><path d="M6 4.5v15l12-7.5z"/></svg>
模拟一次操作
</button>
</div>
<button class="btn btn-outline" id="btn-simulate">
<svg viewBox="0 0 24 24"><path d="M6 4.5v15l12-7.5z"/></svg>
模拟一次操作
</button>
</div>
<div class="tabs" id="tabs">
@@ -83,68 +94,101 @@
<b>审计已关闭。</b>当前期间内发生的后台操作不会写入审计日志,重新开启后恢复记录。
</div>
<!-- 登录失败告警横幅(达到阈值时出现) -->
<div class="banner banner-danger alert-banner" id="alert-banner" hidden>
<div class="alert-banner-body">
<b>登录失败告警已触发。</b>
<span id="alert-banner-text"></span>
</div>
<div class="alert-banner-actions">
<button class="btn-link" id="alert-banner-view">只看失败记录</button>
<button class="icon-btn" id="alert-banner-close" title="关闭">✕</button>
</div>
</div>
<!-- ---- 审计日志 ---- -->
<section id="panel-logs">
<div class="filter-bar card">
<div class="filter-item">
<label for="f-operator">操作者</label>
<select id="f-operator"><option value="">全部</option></select>
<div class="card filter-card">
<div class="filter-grid">
<label class="filter-item">
<span>操作者</span>
<input id="f-operator" type="text" placeholder="用户名,精确匹配" autocomplete="off">
</label>
<label class="filter-item">
<span>资源类型</span>
<select id="f-type"><option value="">全部</option></select>
</label>
<label class="filter-item">
<span>动作</span>
<select id="f-method">
<option value="">全部</option>
<option value="POST">POST</option>
<option value="PUT">PUT</option>
<option value="DELETE">DELETE</option>
<option value="PATCH">PATCH</option>
</select>
</label>
<label class="filter-item">
<span>语义动作</span>
<select id="f-action"><option value="">全部</option></select>
</label>
<label class="filter-item">
<span>结果</span>
<select id="f-result">
<option value="">全部</option>
<option value="success">成功</option>
<option value="failure">失败</option>
</select>
</label>
<label class="filter-item">
<span>关键字</span>
<input id="f-keyword" type="search" placeholder="资源名称 / 路径" autocomplete="off">
</label>
<label class="filter-item">
<span>开始时间</span>
<input id="f-start" type="datetime-local">
</label>
<label class="filter-item">
<span>结束时间</span>
<input id="f-end" type="datetime-local">
</label>
<div class="filter-actions">
<button class="btn btn-primary btn-sm" id="btn-apply">查询</button>
<button class="btn btn-outline btn-sm" id="btn-reset">重置</button>
</div>
</div>
<div class="filter-item">
<label for="f-type">资源类型</label>
<select id="f-type"><option value="">全部</option></select>
<div class="filter-note" id="filter-note" hidden>
<span id="filter-note-text"></span>
<button class="btn-link" id="btn-clear">✕ 清除筛选</button>
</div>
<div class="filter-item">
<label for="f-method">动作</label>
<select id="f-method"><option value="">全部</option></select>
</div>
<div class="filter-item">
<label for="f-result">结果</label>
<select id="f-result">
<option value="">全部</option>
<option value="success">成功</option>
<option value="failure">失败</option>
</select>
</div>
<div class="filter-item">
<label for="f-time">时间范围</label>
<select id="f-time">
<option value="all">全部时间</option>
<option value="24h">近 24 小时</option>
<option value="7d">近 7 天</option>
<option value="30d">近 30 天</option>
</select>
</div>
<div class="filter-item grow">
<label for="f-keyword">关键字</label>
<input id="f-keyword" type="search" placeholder="资源名称 / 路径,如 hello-halo" autocomplete="off">
</div>
<button class="btn-link" id="btn-clear" hidden>✕ 清除筛选</button>
</div>
<div class="card table-card">
<table class="audit-table">
<thead>
<tr>
<th style="width:170px">时间</th>
<th style="width:150px">操作者</th>
<th style="width:90px">动作</th>
<th>资源</th>
<th style="width:110px">结果</th>
<th style="width:140px">来源 IP</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
<div class="audit-list-wrap">
<table class="audit-table">
<thead>
<tr>
<th style="width:190px">操作者 / 时间</th>
<th style="width:76px">动作</th>
<th style="width:300px">资源 / 路径</th>
<th style="width:130px">描述</th>
<th style="width:84px">结果</th>
<th style="width:120px">IP</th>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
</div>
<div class="pagination">
<span class="pg-info" id="pg-info"></span>
<span class="pg-right">
<select id="pg-size" title="每页条数">
<option value="10">10 条/页</option>
<option value="20">20 条/页</option>
<option value="20" selected>20 条/页</option>
<option value="50">50 条/页</option>
</select>
<button class="icon-btn" id="pg-prev" title="上一页">‹</button>
<span class="pg-page" id="pg-page">1 / 1</span>
<button class="icon-btn" id="pg-next" title="下一页">›</button>
</span>
</div>
@@ -154,34 +198,110 @@
<!-- ---- 插件设置 ---- -->
<section id="panel-settings" hidden>
<div class="card settings-card">
<div class="card-title">基本设置</div>
<div class="card-title">审计设置</div>
<div class="card-sub">对应 settings.yaml 的 audit 分组,Console 自动渲染;演示页保存在内存中。</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">审计开关</div>
<div class="s-desc">开启后,已登录用户对后台 API(/apis/**)的写操作与登录/登出事件将被记录(对应 settings.yaml,Console 自动渲染)</div>
<div class="s-name">启用审计</div>
<div class="s-desc">关闭后不再记录新的操作审计日志,已有记录仍可查询</div>
</div>
<label class="switch">
<input type="checkbox" id="set-enabled" checked>
<span class="slider"></span>
</label>
</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">记录字段变更</div>
<div class="s-desc">对成功的新建/修改/删除操作记录字段级新旧值(敏感字段自动脱敏),关闭后仅记录操作元信息</div>
</div>
<label class="switch">
<input type="checkbox" id="set-record-changes" checked>
<span class="slider"></span>
</label>
</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">记录系统内部变更</div>
<div class="s-desc">记录定时发布等非页面操作触发的资源变更(执行者记为「系统」),关闭后仅记录页面/API 操作</div>
</div>
<label class="switch">
<input type="checkbox" id="set-record-system" checked>
<span class="slider"></span>
</label>
</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">保留天数</div>
<div class="s-desc">超过保留期的记录由每日定时任务自动清理,无需人工干预(默认 90 天,最小 7 天)</div>
<div class="s-desc">超过保留期的审计记录将在每日自动清理(最小 7 天,默认 90 天)</div>
</div>
<input type="number" id="set-retention" class="input num" min="7" max="365" value="90">
<input type="number" id="set-retention" class="input num" min="7" step="1" value="90">
</div>
<div class="settings-actions">
<button class="btn btn-primary" id="btn-save-settings">保存设置</button>
<span class="hint">Demo 仅保存在当前页面内存中,刷新后恢复默认</span>
</div>
</div>
<div class="card settings-card">
<div class="card-title">告警通知</div>
<div class="card-sub">独立于审计开关。Webhook 地址凭据只存于 Halo Secret,设置仅保存 Secret 引用;演示页不发起真实网络请求。</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">启用登录失败告警</div>
<div class="s-desc">统计窗口内登录失败达到触发阈值时向 Webhook 地址推送 JSON 告警(默认关闭)</div>
</div>
<label class="switch">
<input type="checkbox" id="set-alert-enabled">
<span class="slider"></span>
</label>
</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">Webhook 地址(Secret)</div>
<div class="s-desc">选择或创建存放 Webhook 地址的 Secret(键 <code>webhookUrl</code>)。地址仅在服务端读取,可含 access_token 等凭据</div>
</div>
<input type="text" id="set-alert-secret" class="input secret-input" placeholder="operation-audit-webhook">
</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">触发阈值(次)</div>
<div class="s-desc">统计窗口内累计登录失败达到该次数即触发一次告警(默认 5)</div>
</div>
<input type="number" id="set-alert-threshold" class="input num" min="1" step="1" value="5">
</div>
<div class="setting-row">
<div class="setting-text">
<div class="s-name">统计窗口(分钟)</div>
<div class="s-desc">失败次数的累计窗口;告警后窗口重开,登录成功立即清零(默认 5)</div>
</div>
<input type="number" id="set-alert-window" class="input num" min="1" step="1" value="5">
</div>
<div class="settings-actions">
<button class="btn btn-outline" id="btn-test-alert">发送测试告警</button>
<button class="btn btn-outline" id="btn-simulate-alert">模拟 5 次登录失败</button>
<span class="hint">推送 type: "test" 的测试消息,演示页仅预览 JSON 负载</span>
</div>
<pre class="alert-preview" id="alert-test-output" hidden></pre>
</div>
<div class="card settings-card">
<div class="card-title">清理预览</div>
<div class="clean-stats" id="clean-stats"></div>
<button class="btn btn-outline" id="btn-clean">模拟一次清理</button>
<div class="settings-actions">
<button class="btn btn-outline" id="btn-clean">模拟一次清理</button>
<span class="hint">真实插件由每日定时任务自动执行</span>
</div>
</div>
</section>
</main>
@@ -197,55 +317,122 @@
<span>模拟一次后台操作</span>
<button class="icon-btn" id="modal-close">✕</button>
</div>
<p class="modal-sub">选择操作者与方法、输入请求路径后发送,Demo 将按技术方案 D1 的捕获规则(<code>/apis/**</code> 写操作 + <code>/login</code>、<code>/logout</code>)判断是否写入审计日志。</p>
<p class="modal-sub">
演示页按真实捕获管线逐步判定:<b>捕获规则</b>(<code>/apis/**</code> 写操作、<code>/login</code>、<code>/logout</code>)
→ <b>资源解析</b> → <b>登录结果</b>(302 重定向目标判定)→ <b>语义动作标注</b> → <b>字段级 diff</b>。
</p>
<div class="field-row">
<div class="field">
<label for="sim-user">操作者</label>
<select id="sim-user">
<option value="guichumo">guichumo</option>
<option value="editor.zhang">editor.zhang</option>
<option value="writer.li">writer.li</option>
<option value="__anon__">匿名访客</option>
</select>
<div class="seg-tabs" id="sim-tabs">
<button class="seg-tab active" data-sim-tab="http">页面 / API 操作</button>
<button class="seg-tab" data-sim-tab="system">系统内部变更</button>
</div>
<div id="sim-http-fields">
<div class="field-row">
<div class="field">
<label for="sim-user">操作者</label>
<select id="sim-user">
<option value="guichumo">guichumo</option>
<option value="editor.zhang">editor.zhang</option>
<option value="writer.li">writer.li</option>
<option value="__anon__">匿名访客</option>
</select>
</div>
<div class="field">
<label for="sim-method">HTTP 方法</label>
<select id="sim-method">
<option>GET</option>
<option>POST</option>
<option selected>PUT</option>
<option>DELETE</option>
<option>PATCH</option>
</select>
</div>
</div>
<div class="field">
<label for="sim-method">HTTP 方法</label>
<select id="sim-method">
<option>GET</option>
<option>POST</option>
<option>PUT</option>
<option>DELETE</option>
<option>PATCH</option>
</select>
<label for="sim-path">请求路径</label>
<input id="sim-path" type="text" placeholder="/apis/content.halo.run/v1alpha1/posts/hello-halo" autocomplete="off" spellcheck="false">
</div>
<div class="field-row">
<div class="field">
<label for="sim-status">响应状态</label>
<select id="sim-status">
<option value="200" selected>200 成功</option>
<option value="201">201 创建成功</option>
<option value="204">204 删除成功</option>
<option value="302">302 重定向(登录用)</option>
<option value="400">400 请求错误</option>
<option value="401">401 未认证</option>
<option value="403">403 权限不足</option>
<option value="404">404 资源不存在</option>
<option value="500">500 服务端异常</option>
</select>
</div>
<div class="field">
<label for="sim-location">重定向目标(仅 /login)</label>
<input id="sim-location" type="text" placeholder="成功后为 /uc;失败含 error 参数" autocomplete="off">
</div>
</div>
<div class="field-row">
<div class="field">
<label for="sim-attempted">尝试的用户名(登录请求)</label>
<input id="sim-attempted" type="text" placeholder="如 admin,可留空" autocomplete="off">
</div>
<div class="field">
<label for="sim-prev">写入前资源(JSON,可选)</label>
<input id="sim-prev-note" type="text" value="由内置快照自动提供" disabled>
</div>
</div>
<div class="field">
<label for="sim-body">请求体 JSON(可选,用于字段 diff;敏感字段自动脱敏)</label>
<textarea id="sim-body" rows="4" spellcheck="false" placeholder='{"apiVersion":"content.halo.run/v1alpha1","kind":"Post","metadata":{"name":"hello-halo"},"spec":{"title":"新标题"}}'></textarea>
</div>
<div class="presets">
<button class="chip" data-preset='{"user":"editor.zhang","method":"PUT","path":"/apis/content.halo.run/v1alpha1/posts/hello-halo","status":200,"snapshot":"post","body":{"apiVersion":"content.halo.run/v1alpha1","kind":"Post","metadata":{"name":"hello-halo","labels":{"content.halo.run/pinned":"false"}},"spec":{"title":"你好,Halo(Demo 修改)","slug":"hello-halo","visible":"PUBLIC","publish":true,"pinned":false,"allowComment":true,"summary":"从零开始搭建自己的写作空间。"}}}'>编辑文章(含 diff)</button>
<button class="chip" data-preset='{"user":"guichumo","method":"POST","path":"/apis/api.content.halo.run/v1alpha1/posts/reading-notes-11/publish","status":200}'>发布文章</button>
<button class="chip" data-preset='{"user":"guichumo","method":"POST","path":"/apis/plugin.halo.run/v1alpha1/plugins/plugin-search-widget/upgrade","status":200,"snapshot":"plugin","body":{"apiVersion":"plugin.halo.run/v1alpha1","kind":"Plugin","metadata":{"name":"plugin-search-widget"},"spec":{"displayName":"搜索组件","version":"1.4.0","enabled":true,"requires":">=2.20.0"}}}'>升级插件(含 diff)</button>
<button class="chip" data-preset='{"user":"guichumo","method":"PUT","path":"/apis/api.console.halo.run/v1alpha1/users/guichumo/password","status":200,"body":{"apiVersion":"v1alpha1","kind":"User","metadata":{"name":"guichumo"},"spec":{"displayName":"guichumo","email":"guichumo@example.com","roles":["role-template-author"],"password":"runtime-demo-value"}}}'>修改密码(脱敏)</button>
<button class="chip" data-preset='{"user":"__anon__","method":"POST","path":"/login","status":302,"location":"/login?error=invalid-credential&method=form","attempted":"admin"}'>登录失败(表单 302)</button>
<button class="chip" data-preset='{"user":"__anon__","method":"POST","path":"/login","status":302,"location":"/uc","attempted":"guichumo"}'>登录成功(302 → /uc)</button>
<button class="chip" data-preset='{"user":"__anon__","method":"GET","path":"/login?error=invalid-credential&method=form","status":200}'>登录失败回显(GET 200)</button>
<button class="chip" data-preset='{"user":"guichumo","method":"GET","path":"/apis/api.content.halo.run/v1alpha1/posts","status":200}'>查询文章列表(读,不记录)</button>
</div>
</div>
<div class="field">
<label for="sim-path">请求路径</label>
<input id="sim-path" type="text" placeholder="/apis/content.halo.run/v1alpha1/posts/hello-halo" autocomplete="off" spellcheck="false">
</div>
<div class="presets">
<button class="chip" data-preset='{"user":"guichumo","method":"PUT","path":"/apis/content.halo.run/v1alpha1/posts/hello-halo","status":200}'>编辑文章</button>
<button class="chip" data-preset='{"user":"guichumo","method":"POST","path":"/apis/api.content.halo.run/v1alpha1/posts/reading-notes-11/publish","status":200}'>发布文章</button>
<button class="chip" data-preset='{"user":"editor.zhang","method":"POST","path":"/apis/api.halo.run/v1alpha1/comments/comment-8fa2c1/approve","status":200}'>审核评论</button>
<button class="chip" data-preset='{"user":"__anon__","method":"POST","path":"/login","status":401}'>登录失败</button>
<button class="chip" data-preset='{"user":"guichumo","method":"GET","path":"/apis/api.content.halo.run/v1alpha1/posts","status":200}'>查询文章列表(读)</button>
</div>
<div class="field">
<label for="sim-status">模拟响应</label>
<select id="sim-status">
<option value="200">200 成功</option>
<option value="201">201 创建成功</option>
<option value="204">204 删除成功</option>
<option value="400">400 请求错误</option>
<option value="401">401 未认证</option>
<option value="403">403 权限不足</option>
<option value="404">404 资源不存在</option>
<option value="500">500 服务端异常</option>
</select>
<div id="sim-system-fields" hidden>
<div class="field-row">
<div class="field">
<label for="sys-method">事件类型</label>
<select id="sys-method">
<option value="PUT">更新(PUT 语义)</option>
<option value="DELETE">删除(DELETE 语义)</option>
</select>
</div>
<div class="field">
<label for="sys-type">资源类型</label>
<select id="sys-type"></select>
</div>
</div>
<div class="field">
<label for="sys-name">资源名称</label>
<input id="sys-name" type="text" value="weekly-2026-w46" autocomplete="off">
</div>
<div class="field">
<label for="sys-changes">字段变更(JSON 数组)</label>
<textarea id="sys-changes" rows="4" spellcheck="false">[
{"field":"spec.publish","changeType":"UPDATED","oldValue":"false","newValue":"true"},
{"field":"spec.publishTime","changeType":"ADDED","oldValue":null,"newValue":"2026-11-22T02:00:00Z"}
]</textarea>
</div>
<div class="presets">
<button class="chip" data-sys-preset='{"method":"PUT","type":"posts","name":"weekly-2026-w46","changes":[{"field":"spec.publish","changeType":"UPDATED","oldValue":"false","newValue":"true"},{"field":"spec.publishTime","changeType":"ADDED","oldValue":null,"newValue":"2026-11-22T02:00:00Z"}]}'>定时发布文章</button>
<button class="chip" data-sys-preset='{"method":"DELETE","type":"posts","name":"draft-night-notes","changes":[{"field":"spec.title","changeType":"REMOVED","oldValue":"夜间随笔(未发布)","newValue":null}]}'>清理未发布草稿</button>
</div>
</div>
<div class="modal-actions">
+605 -139
View File
@@ -2,199 +2,616 @@
* 操作审计 Demo · 核心逻辑单元测试
*
* 运行:node --test demo/test/audit-core.test.mjs
* 覆盖对象(与技术方案第 7 节测试策略对应):
* - shouldCapture 捕获规则(D1)
* - resolveResource 资源解析(5.2)
* - applyFilters 筛选(产品设计 4.2)
* - paginate 分页
* - countExpired 保留期清理(D5)
* - MockData 模拟数据生成器(确定性、字段完整性)
* 覆盖对象(与插件当前实现一一对应):
* - shouldCapture 捕获规则(CaptureRule / 认证端点链首捕获)
* - resolveResource 资源解析(ResourceResolver)
* - deriveAction 语义动作标注 + describeOperation 中文描述
* - classifyLogin 登录结果判定(LoginOutcome:302 重定向目标判定)
* - diffObjects 字段级变更 diff(PUT/PATCH/POST/DELETE、脱敏、截断、封顶)
* - applyFilters 八维筛选(含登录失败结果语义)
* - toCsv CSV 导出(BOM/CRLF/转义/公式注入防护)
* - 告警窗口 登录失败告警(阈值、告警后重开、成功清零)
* - MockData 模拟数据(确定性、字段完整性、故事线)
*/
import { createRequire } from 'node:module';
import { test } from 'node:test';
import assert from 'node:assert/strict';
const require = createRequire(import.meta.url);
const AuditCore = require('../assets/audit-core.js');
const C = require('../assets/audit-core.js');
const MockData = require('../assets/mock-data.js');
// ---------------- shouldCapture(D1 捕获规则) ----------------
test('shouldCapture: 已登录用户对 /apis/** 的写操作应记录', () => {
assert.deepEqual(
AuditCore.shouldCapture({ method: 'POST', path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true }),
{ captured: true, reason: '已登录用户对 /apis/** 的写操作,予以记录' }
);
assert.equal(AuditCore.shouldCapture({ method: 'put', path: '/apis/v1alpha1/configmaps/system', authenticated: true }).captured, true);
assert.equal(AuditCore.shouldCapture({ method: 'DELETE', path: '/apis/content.halo.run/v1alpha1/posts/x', authenticated: true }).captured, true);
assert.equal(AuditCore.shouldCapture({ method: 'PATCH', path: '/apis/v1alpha1/users/x', authenticated: true }).captured, true);
// ---------------- shouldCapture(捕获规则) ----------------
test('shouldCapture: 已登录用户对 /apis/** 的写操作应记录(http 通道)', () => {
for (const method of ['POST', 'PUT', 'DELETE', 'PATCH']) {
const r = C.shouldCapture({ method, path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true });
assert.equal(r.captured, true, method);
assert.equal(r.channel, 'http');
assert.match(r.reason, /写操作/);
}
});
test('shouldCapture: 读操作不记录', () => {
for (const method of ['GET', 'HEAD', 'OPTIONS']) {
const r = AuditCore.shouldCapture({ method, path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true });
assert.equal(r.captured, false, method + ' 不应被记录');
const r = C.shouldCapture({ method, path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true });
assert.equal(r.captured, false, method);
assert.match(r.reason, /写操作/);
}
});
test('shouldCapture: /apis/** 下匿名请求不记录(401/403 场景)', () => {
const r = AuditCore.shouldCapture({ method: 'POST', path: '/apis/content.halo.run/v1alpha1/posts', authenticated: false });
const r = C.shouldCapture({ method: 'POST', path: '/apis/content.halo.run/v1alpha1/posts', authenticated: false });
assert.equal(r.captured, false);
assert.match(r.reason, /匿名/);
});
test('shouldCapture: 登录/登出端点始终记录(含匿名登录尝试)', () => {
assert.equal(AuditCore.shouldCapture({ method: 'POST', path: '/login', authenticated: false }).captured, true);
assert.equal(AuditCore.shouldCapture({ method: 'POST', path: '/logout', authenticated: true }).captured, true);
test('shouldCapture: 认证端点始终记录(含查询串与匿名登录尝试)', () => {
assert.deepEqual(
C.shouldCapture({ method: 'POST', path: '/login', authenticated: false }),
{
captured: true,
channel: 'auth',
reason: '认证端点始终记录(登录/登出,含登录失败与失败回显)'
}
);
assert.equal(C.shouldCapture({ method: 'POST', path: '/logout', authenticated: true }).channel, 'auth');
assert.equal(C.shouldCapture({ method: 'GET', path: '/login?error=invalid-credential', authenticated: false }).captured, true);
});
test('shouldCapture: /apis/** 之外的普通路径不记录', () => {
const r = AuditCore.shouldCapture({ method: 'POST', path: '/console/posts', authenticated: true });
const r = C.shouldCapture({ method: 'POST', path: '/console/posts', authenticated: true });
assert.equal(r.captured, false);
assert.match(r.reason, /捕获范围/);
});
test('shouldCapture: 路径匹配 /apis/ 前缀但匿名时,匿名规则优先于方法规则(与 D1 描述一致)', () => {
// GET + 匿名:期望原因是"匿名",而非"读操作"
const r = AuditCore.shouldCapture({ method: 'GET', path: '/apis/v1alpha1/posts', authenticated: false });
test('shouldCapture: 匿名规则优先于读操作规则(与后端一致)', () => {
const r = C.shouldCapture({ method: 'GET', path: '/apis/v1alpha1/posts', authenticated: false });
assert.equal(r.captured, false);
assert.match(r.reason, /匿名/);
});
// ---------------- resolveResource(5.2 资源解析) ----------------
test('resolveResource: 单资源路径 → plural + name', () => {
// ---------------- resolveResource(资源解析) ----------------
test('resolveResource: 单资源 / 集合 / 深层子资源', () => {
assert.deepEqual(
AuditCore.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz'),
C.resolveResource('/apis/content.halo.run/v1alpha1/posts/xyz'),
{ resourceType: 'posts', resourceName: 'xyz' }
);
});
test('resolveResource: 集合路径 → 仅 plural', () => {
assert.deepEqual(
AuditCore.resolveResource('/apis/content.halo.run/v1alpha1/posts'),
{ resourceType: 'posts', resourceName: '' }
C.resolveResource('/apis/content.halo.run/v1alpha1/posts'),
{ resourceType: 'posts', resourceName: null }
);
});
test('resolveResource: 更深层子资源取前两段,完整路径由 path 兜底', () => {
assert.deepEqual(
AuditCore.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz/publish'),
C.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz/publish'),
{ resourceType: 'posts', resourceName: 'xyz' }
);
assert.deepEqual(
C.resolveResource('/apis/plugin.halo.run/v1alpha1/plugins/plugin-search-widget/upgrade'),
{ resourceType: 'plugins', resourceName: 'plugin-search-widget' }
);
});
test('resolveResource: /login、/logout → auth', () => {
assert.deepEqual(AuditCore.resolveResource('/login'), { resourceType: 'auth', resourceName: '' });
assert.deepEqual(AuditCore.resolveResource('/logout'), { resourceType: 'auth', resourceName: '' });
test('resolveResource: 查询串不影响解析(/login?error=... → auth)', () => {
assert.deepEqual(
C.resolveResource('/login?error=invalid-credential&method=form'),
{ resourceType: 'auth', resourceName: null }
);
assert.deepEqual(C.resolveResource('/logout'), { resourceType: 'auth', resourceName: null });
});
test('resolveResource: 非 /apis 路径与畸形路径 → other', () => {
assert.equal(AuditCore.resolveResource('/console').resourceType, 'other');
assert.equal(AuditCore.resolveResource('/apis/only-group').resourceType, 'other');
assert.equal(C.resolveResource('/console').resourceType, 'other');
assert.equal(C.resolveResource('/apis/only-group').resourceType, 'other');
assert.equal(C.resolveResource('').resourceType, 'other');
});
// ---------------- isSuccess / applyFilters(4.2 筛选) ----------------
// ---------------- deriveAction / describeOperation ----------------
test('deriveAction: 登录/登出/失败回显', () => {
assert.equal(C.deriveAction('POST', 'auth', '/login'), 'login');
assert.equal(C.deriveAction('GET', 'auth', '/login?error=invalid-credential'), 'login-failure');
assert.equal(C.deriveAction('POST', 'auth', '/logout'), 'logout');
assert.equal(C.deriveAction('POST', 'auth', '/login?continue=/uc'), 'login');
});
test('deriveAction: 子动作段优先于 HTTP 方法', () => {
assert.equal(C.deriveAction('PUT', 'posts', '/apis/api.content.halo.run/v1alpha1/posts/x/publish'), 'publish');
assert.equal(C.deriveAction('PUT', 'posts', '/apis/content.halo.run/v1alpha1/posts/x/restore'), 'restore');
assert.equal(C.deriveAction('DELETE', 'comments', '/apis/content.halo.run/v1alpha1/comments/x/recycle'), 'recycle');
assert.equal(C.deriveAction('POST', 'plugins', '/apis/plugin.halo.run/v1alpha1/plugins/x/activation'), 'enable');
assert.equal(C.deriveAction('PUT', 'plugins', '/apis/plugin.halo.run/v1alpha1/plugins/x/upgrade'), 'upgrade');
assert.equal(C.deriveAction('DELETE', 'plugins', '/apis/plugin.halo.run/v1alpha1/plugins/x/uninstall'), 'uninstall');
assert.equal(C.deriveAction('POST', 'users', '/apis/api.console.halo.run/v1alpha1/users/x/resetpassword'), 'resetpassword');
});
test('deriveAction: 未识别子动作回退 method 映射,未知方法返回 null', () => {
assert.equal(C.deriveAction('POST', 'posts', '/apis/content.halo.run/v1alpha1/posts/x/unknown'), 'create');
assert.equal(C.deriveAction('GET', 'posts', '/apis/content.halo.run/v1alpha1/posts'), 'view');
assert.equal(C.deriveAction('TRACE', 'posts', '/apis/content.halo.run/v1alpha1/posts'), null);
});
test('describeOperation: 语义动作 → 中文短语(列表/详情/导出共用)', () => {
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login' }), '登录');
assert.equal(C.describeOperation({ method: 'GET', resourceType: 'auth', path: '/login?error=x', action: 'login-failure' }), '登录失败');
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'posts', path: '/apis/api.content.halo.run/v1alpha1/posts/x/publish', action: 'publish' }), '发布文章');
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'plugins', path: '/apis/plugin.halo.run/v1alpha1/plugins/x/activation', action: 'enable' }), '启用插件');
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'themes', path: '/apis/theme.halo.run/v1alpha1/themes/x/activation', action: 'enable' }), '启用主题');
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'users', path: '/apis/v1alpha1/users/x/password', action: 'password' }), '修改密码');
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'comments', path: '/apis/x/v1alpha1/comments/x/reply', action: 'reply' }), '回复评论');
});
test('describeOperation: 历史记录无 action 时现场推导;未识别回退 method 动词', () => {
assert.equal(C.describeOperation({ method: 'PUT', resourceType: 'posts', path: '/apis/content.halo.run/v1alpha1/posts/x' }), '修改文章');
assert.equal(C.describeOperation({ method: 'POST', resourceType: 'unknowns', path: '/apis/x/v1alpha1/unknowns' }), '新建unknowns');
});
// ---------------- classifyLogin(登录结果判定) ----------------
test('classifyLogin: POST /login 的 2xx/302/401 判定', () => {
assert.deepEqual(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 200 }), { attempt: true, failure: false, echo: false });
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/uc' }).failure, false);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/challenges/two-factor/totp' }).failure, false);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login?error=invalid-credential&method=form' }).failure, true);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 302, location: '/login?error&method=form' }).failure, true);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: 401 }).failure, true);
assert.equal(C.classifyLogin({ method: 'POST', path: '/login', statusCode: null }).failure, true);
});
test('classifyLogin: 失败回显页(GET /login?error=...,HTTP 200)判为失败', () => {
const echo = C.classifyLogin({ method: 'GET', path: '/login?error=invalid-credential&method=form', statusCode: 200 });
assert.deepEqual(echo, { attempt: false, failure: true, echo: true });
const page = C.classifyLogin({ method: 'GET', path: '/login', statusCode: 200 });
assert.deepEqual(page, { attempt: false, failure: false, echo: false });
});
// ---------------- 结果徽标 / 登录失败标注 ----------------
test('resultBadge: 登录失败即使 200/302 也显示「失败」', () => {
assert.deepEqual(
C.resultBadge({ method: 'GET', resourceType: 'auth', path: '/login?error=x', action: 'login-failure', statusCode: 200 }),
{ text: '失败', class: 'status-fail' }
);
assert.deepEqual(
C.resultBadge({ method: 'POST', resourceType: 'auth', path: '/login', action: 'login', statusCode: 302 }),
{ text: '302', class: 'status-ok' }
);
assert.deepEqual(
C.resultBadge({ method: 'DELETE', resourceType: 'posts', path: '/apis/x/v1alpha1/posts/x', action: 'delete', statusCode: 403 }),
{ text: '403', class: 'status-fail' }
);
});
test('isLoginFailure / isSuccessRecord: 兼容历史记录(无 action 时按路径推导)', () => {
assert.equal(C.isLoginFailure({ method: 'GET', resourceType: 'auth', path: '/login?error=x', statusCode: 200 }), true);
assert.equal(C.isLoginFailure({ method: 'POST', resourceType: 'auth', path: '/login', statusCode: 302 }), false);
assert.equal(C.isSuccessRecord({ action: 'login-failure', statusCode: 200 }), false);
assert.equal(C.isSuccessRecord({ action: 'login', statusCode: 302 }), true);
});
test('displayUsername: unknown → 未知用户,system → 系统', () => {
assert.equal(C.displayUsername('unknown'), '未知用户');
assert.equal(C.displayUsername('system'), '系统');
assert.equal(C.displayUsername(''), '未知用户');
assert.equal(C.displayUsername('guichumo'), 'guichumo');
});
// ---------------- diffObjects(字段级变更) ----------------
test('diffObjects: POST 全量新增,跳过 apiVersion/kind/status,metadata 仅保留可写键', () => {
const changes = C.diffObjects('POST', null, {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Post',
metadata: { name: 'hello', version: 3, labels: { a: 'b' }, annotations: { c: 'd' } },
spec: { title: '标题', publish: false },
status: { phase: 'DRAFT' }
});
const fields = changes.map(c => c.field);
assert.ok(fields.includes('metadata.name'));
assert.ok(fields.includes('metadata.labels.a'));
assert.ok(!fields.includes('apiVersion'));
assert.ok(!fields.includes('kind'));
assert.ok(!fields.includes('status.phase'));
assert.ok(!fields.some(f => f.includes('metadata.version')));
assert.ok(changes.every(c => c.changeType === 'ADDED'));
});
test('diffObjects: PUT 计算新增/修改/删除', () => {
const changes = C.diffObjects('PUT',
{ apiVersion: 'v1', kind: 'K', metadata: { name: 'x' }, spec: { title: '旧', cover: 'a.png', pinned: false } },
{ apiVersion: 'v1', kind: 'K', metadata: { name: 'x' }, spec: { title: '新', pinned: false, summary: '新增' } }
);
const byField = Object.fromEntries(changes.map(c => [c.field, c]));
assert.equal(byField['spec.title'].changeType, 'UPDATED');
assert.equal(byField['spec.title'].oldValue, '旧');
assert.equal(byField['spec.title'].newValue, '新');
assert.equal(byField['spec.cover'].changeType, 'REMOVED');
assert.equal(byField['spec.summary'].changeType, 'ADDED');
assert.equal(byField['spec.summary'].oldValue, null);
});
test('diffObjects: DELETE 全量移除', () => {
const changes = C.diffObjects('DELETE', {
apiVersion: 'content.halo.run/v1alpha1',
kind: 'Post',
metadata: { name: 'weekly' },
spec: { title: '每周摘要' },
status: { phase: 'PUBLISHED' }
}, null);
assert.ok(changes.length > 0);
assert.ok(changes.every(c => c.changeType === 'REMOVED'));
assert.ok(changes.some(c => c.field === 'spec.title' && c.oldValue === '每周摘要'));
assert.ok(!changes.some(c => c.field.startsWith('status')));
});
test('diffObjects: PATCH Merge Patch 仅比较 body 中字段,显式 null 视为删除', () => {
const changes = C.diffObjects('PATCH',
{ metadata: { name: 'x' }, spec: { title: '旧', summary: '保留', cover: 'a.png' } },
{ spec: { title: '新', cover: null } }
);
const fields = changes.map(c => c.field);
assert.deepEqual(fields, ['spec.title', 'spec.cover']);
const cover = changes.find(c => c.field === 'spec.cover');
assert.equal(cover.changeType, 'REMOVED');
assert.ok(!fields.includes('spec.summary'), 'body 未携带的字段视为未变更');
});
test('diffObjects: PATCH JSON Patch(RFC 6902)', () => {
const changes = C.diffObjects('PATCH',
{ metadata: { name: 'x' }, spec: { title: '旧', cover: 'a.png' } },
[
{ op: 'replace', path: '/spec/title', value: '新' },
{ op: 'remove', path: '/spec/cover' },
{ op: 'add', path: '/spec/summary', value: '摘要' }
]
);
const byField = Object.fromEntries(changes.map(c => [c.field, c]));
assert.equal(byField['spec.title'].changeType, 'UPDATED');
assert.equal(byField['spec.cover'].changeType, 'REMOVED');
assert.equal(byField['spec.summary'].changeType, 'ADDED');
});
test('diffObjects: 敏感字段脱敏(password / token / secret / credential)', () => {
const changes = C.diffObjects('POST', null, {
apiVersion: 'v1alpha1',
kind: 'User',
metadata: { name: 'alice' },
spec: { displayName: 'Alice', password: 'plain-text-value' },
annotations: { 'x-token': 'token-value' }
});
const password = changes.find(c => c.field === 'spec.password');
const displayName = changes.find(c => c.field === 'spec.displayName');
assert.equal(password.newValue, '******');
assert.equal(displayName.newValue, 'Alice');
const updated = C.diffObjects('PUT',
{ spec: { password: 'old-value' } },
{ spec: { password: 'new-value' } }
);
assert.equal(updated[0].oldValue, '******');
assert.equal(updated[0].newValue, '******');
assert.equal(C.isSensitiveField('metadata.annotations.x-credential'), true);
assert.equal(C.isSensitiveField('spec.title'), false);
});
test('diffObjects: 超长值截断、变更条数封顶 30 + 汇总条', () => {
const long = 'x'.repeat(260);
const changes = C.diffObjects('PUT', { spec: { text: 'old' } }, { spec: { text: long } });
assert.ok(changes[0].newValue.endsWith('…(截断)'));
assert.ok(changes[0].newValue.length <= 210);
const before = { spec: {} };
const after = { spec: {} };
for (let i = 0; i < 40; i++) {
before.spec['k' + i] = 'a';
after.spec['k' + i] = 'b';
}
const capped = C.diffObjects('PUT', before, after);
assert.equal(capped.length, 31);
assert.equal(capped[30].field, '…');
assert.match(capped[30].newValue, /仅记录前 30 处(共 40 处)/);
});
test('diffObjects: 无变更 / 无法计算返回 null', () => {
assert.equal(C.diffObjects('PUT', { spec: { a: 1 } }, { spec: { a: 1 } }), null);
assert.equal(C.diffObjects('POST', null, null), null);
assert.equal(C.diffObjects('PUT', null, { spec: {} }), null);
assert.equal(C.diffObjects('GET', { a: 1 }, { a: 2 }), null);
});
test('formatChanges: 紧凑中文摘要供 CSV「变更」列使用', () => {
const text = C.formatChanges([
{ field: 'spec.title', changeType: 'UPDATED', oldValue: '旧', newValue: '新' },
{ field: 'spec.cover', changeType: 'ADDED', oldValue: null, newValue: 'a.png' },
{ field: 'spec.slug', changeType: 'REMOVED', oldValue: 'old', newValue: null }
]);
assert.equal(text, '修改 spec.title:旧 → 新;新增 spec.cover:a.png;删除 spec.slug:old');
assert.equal(C.formatChanges(null), '');
assert.equal(C.changeTypeLabel('ADDED'), '新增');
assert.equal(C.changeValueDisplay(null), '∅');
});
// ---------------- buildRecord / buildSystemRecord ----------------
test('buildRecord: HTTP 写操作推导资源、语义动作与操作者', () => {
const record = C.buildRecord({
method: 'put',
path: '/apis/api.content.halo.run/v1alpha1/posts/x/publish',
username: 'editor.zhang',
statusCode: 200,
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(record.username, 'editor.zhang');
assert.equal(record.method, 'PUT');
assert.equal(record.action, 'publish');
assert.equal(record.resourceType, 'posts');
assert.equal(record.resourceName, 'x');
assert.equal(C.describeOperation(record), '发布文章');
assert.equal(record.changes, null, '未提供请求体时不计算 diff');
});
test('buildRecord: 登录请求操作者记「未知用户」,失败标注 login-failure', () => {
const failure = C.buildRecord({
method: 'POST',
path: '/login',
username: 'guichumo',
statusCode: 302,
location: '/login?error=invalid-credential&method=form',
attemptedUsername: 'admin',
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(failure.username, 'unknown');
assert.equal(failure.attemptedUsername, 'admin');
assert.equal(failure.action, 'login-failure');
assert.equal(C.resultBadge(failure).text, '失败');
const success = C.buildRecord({
method: 'POST',
path: '/login',
statusCode: 302,
location: '/uc',
attemptedUsername: 'guichumo',
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(success.action, 'login');
assert.equal(C.resultBadge(success).text, '302');
});
test('buildRecord: 仅 2xx 且 recordChanges 开启时计算 diff', () => {
const body = { spec: { title: '新' } };
const previous = { spec: { title: '旧' } };
const ok = C.buildRecord({
method: 'PUT',
path: '/apis/content.halo.run/v1alpha1/posts/x',
username: 'guichumo',
statusCode: 200,
previous,
body,
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(ok.changes.length, 1);
const failed = C.buildRecord({
method: 'PUT',
path: '/apis/content.halo.run/v1alpha1/posts/x',
username: 'guichumo',
statusCode: 403,
previous,
body,
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(failed.changes, null);
const disabled = C.buildRecord({
method: 'PUT',
path: '/apis/content.halo.run/v1alpha1/posts/x',
username: 'guichumo',
statusCode: 200,
previous,
body,
recordChanges: false,
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(disabled.changes, null);
});
test('buildSystemRecord: 执行者 system、无 IP/UA、状态恒 200', () => {
const record = C.buildSystemRecord({
method: 'PUT',
resourceType: 'posts',
resourceName: 'weekly',
path: '/apis/content.halo.run/v1alpha1/posts/weekly',
changes: [{ field: 'spec.publish', changeType: 'UPDATED', oldValue: 'false', newValue: 'true' }],
timestamp: '2026-11-21T10:00:00Z'
});
assert.equal(record.username, 'system');
assert.equal(C.displayUsername(record.username), '系统');
assert.equal(record.statusCode, 200);
assert.equal(record.remoteIp, null);
assert.equal(record.userAgent, null);
assert.equal(record.action, 'update');
assert.equal(C.describeOperation(record), '修改文章');
assert.equal(record.changes.length, 1);
});
test('toWire: 扁平记录 → AuditLog Extension JSON', () => {
const record = C.buildRecord({
method: 'POST',
path: '/apis/content.halo.run/v1alpha1/posts',
username: 'guichumo',
statusCode: 201,
body: { spec: { title: '新文章' } },
timestamp: '2026-11-21T10:00:00Z'
});
record.id = 'auditlog-0001';
const wire = C.toWire(record);
assert.equal(wire.apiVersion, 'audit.guichumo.com/v1alpha1');
assert.equal(wire.kind, 'AuditLog');
assert.equal(wire.metadata.name, 'auditlog-0001');
assert.equal(wire.metadata.creationTimestamp, '2026-11-21T10:00:00Z');
assert.equal(wire.spec.method, 'POST');
assert.equal(wire.spec.action, 'create');
assert.ok(Array.isArray(wire.spec.changes));
});
// ---------------- applyFilters(八维筛选) ----------------
const NOW = new Date('2026-11-21T12:00:00Z').getTime();
function fixture() {
return [
{ id: 'a1', timestamp: '2026-11-21T10:00:00Z', username: 'guichumo', method: 'PUT', path: '/apis/content.halo.run/v1alpha1/posts/hello', resourceType: 'posts', resourceName: 'hello', statusCode: 200 },
{ id: 'a2', timestamp: '2026-11-21T09:00:00Z', username: 'editor.zhang', method: 'POST', path: '/apis/api.content.halo.run/v1alpha1/posts/hello/publish', resourceType: 'posts', resourceName: 'hello', statusCode: 500 },
{ id: 'a3', timestamp: '2026-11-20T08:00:00Z', username: 'guichumo', method: 'POST', path: '/login', resourceType: 'auth', resourceName: '', statusCode: 401 },
{ id: 'a4', timestamp: '2026-11-10T08:00:00Z', username: 'writer.li', method: 'PUT', path: '/apis/v1alpha1/configmaps/system', resourceType: 'configmaps', resourceName: 'system', statusCode: 200 }
{ id: 'a1', timestamp: '2026-11-21T10:00:00Z', username: 'guichumo', method: 'PUT', path: '/apis/content.halo.run/v1alpha1/posts/hello', resourceType: 'posts', resourceName: 'hello', statusCode: 200, action: 'update' },
{ id: 'a2', timestamp: '2026-11-21T09:00:00Z', username: 'editor.zhang', method: 'POST', path: '/apis/api.content.halo.run/v1alpha1/posts/hello/publish', resourceType: 'posts', resourceName: 'hello', statusCode: 500, action: 'publish' },
{ id: 'a3', timestamp: '2026-11-20T08:00:00Z', username: 'unknown', method: 'GET', path: '/login?error=x', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'login-failure' },
{ id: 'a4', timestamp: '2026-11-21T11:30:00Z', username: 'guichumo', method: 'POST', path: '/login', resourceType: 'auth', resourceName: null, statusCode: 302, action: 'login' },
{ id: 'a5', timestamp: '2026-11-10T08:00:00Z', username: 'writer.li', method: 'PUT', path: '/apis/v1alpha1/configmaps/system', resourceType: 'configmaps', resourceName: 'system', statusCode: 403, action: 'update' }
];
}
test('applyFilters: 按操作者筛选', () => {
const out = AuditCore.applyFilters(fixture(), { operator: 'guichumo', now: NOW });
assert.deepEqual(out.map(l => l.id), ['a1', 'a3']);
test('applyFilters: 操作者 / 资源类型 / 动作 / 语义动作', () => {
assert.deepEqual(C.applyFilters(fixture(), { operator: 'guichumo' }).map(l => l.id), ['a4', 'a1']);
assert.deepEqual(C.applyFilters(fixture(), { resourceType: 'posts' }).map(l => l.id), ['a1', 'a2']);
assert.deepEqual(C.applyFilters(fixture(), { method: 'post' }).map(l => l.id), ['a4', 'a2']);
assert.deepEqual(C.applyFilters(fixture(), { action: 'login-failure' }).map(l => l.id), ['a3']);
});
test('applyFilters: 按资源类型筛选', () => {
const out = AuditCore.applyFilters(fixture(), { resourceType: 'posts', now: NOW });
assert.deepEqual(out.map(l => l.id), ['a1', 'a2']);
});
test('applyFilters: 按动作筛选(方法名大小写不敏感)', () => {
const post = AuditCore.applyFilters(fixture(), { method: 'POST', now: NOW });
assert.deepEqual(post.map(l => l.id), ['a2', 'a3']);
const put = AuditCore.applyFilters(fixture(), { method: 'put', now: NOW });
assert.deepEqual(put.map(l => l.id), ['a1', 'a4']);
});
test('applyFilters: 动作 + 结果组合', () => {
const out = AuditCore.applyFilters(fixture(), { method: 'POST', result: 'failure', now: NOW });
assert.deepEqual(out.map(l => l.id), ['a2', 'a3']);
});
test('applyFilters: 按结果筛选(成功/失败)', () => {
const ok = AuditCore.applyFilters(fixture(), { result: 'success', now: NOW });
assert.deepEqual(ok.map(l => l.id), ['a1', 'a4']);
const bad = AuditCore.applyFilters(fixture(), { result: 'failure', now: NOW });
assert.deepEqual(bad.map(l => l.id), ['a2', 'a3']);
});
test('applyFilters: 时间范围(24h 只含今天、30d 含上周)', () => {
const day = AuditCore.applyFilters(fixture(), { timeRange: '24h', now: NOW });
assert.deepEqual(day.map(l => l.id), ['a1', 'a2']);
const month = AuditCore.applyFilters(fixture(), { timeRange: '30d', now: NOW });
assert.deepEqual(month.map(l => l.id), ['a1', 'a2', 'a3', 'a4']);
test('applyFilters: 结果语义(登录失败 200 计失败;登录成功 302 计成功)', () => {
const success = C.applyFilters(fixture(), { result: 'success' }).map(l => l.id);
assert.deepEqual(success, ['a4', 'a1']);
const failure = C.applyFilters(fixture(), { result: 'failure' }).map(l => l.id);
assert.deepEqual(failure, ['a2', 'a3', 'a5']);
});
test('applyFilters: 关键字匹配资源名称与路径', () => {
const out = AuditCore.applyFilters(fixture(), { keyword: 'hello', now: NOW });
assert.deepEqual(out.map(l => l.id), ['a1', 'a2']);
const byPath = AuditCore.applyFilters(fixture(), { keyword: 'configmaps', now: NOW });
assert.deepEqual(byPath.map(l => l.id), ['a4']);
assert.deepEqual(C.applyFilters(fixture(), { keyword: 'hello' }).map(l => l.id), ['a1', 'a2']);
assert.deepEqual(C.applyFilters(fixture(), { keyword: 'configmaps' }).map(l => l.id), ['a5']);
assert.deepEqual(C.applyFilters(fixture(), { keyword: 'LOGIN' }).map(l => l.id), ['a4', 'a3']);
});
test('applyFilters: 组合条件', () => {
const out = AuditCore.applyFilters(fixture(), { resourceType: 'posts', result: 'failure', now: NOW });
test('applyFilters: 起止时间闭区间', () => {
const out = C.applyFilters(fixture(), {
startTime: '2026-11-21T10:00:00Z',
endTime: '2026-11-21T11:30:00Z'
});
assert.deepEqual(out.map(l => l.id), ['a4', 'a1']);
});
test('applyFilters: 组合条件、时间倒序、不修改入参', () => {
const out = C.applyFilters(fixture(), { resourceType: 'posts', result: 'failure' });
assert.deepEqual(out.map(l => l.id), ['a2']);
});
test('applyFilters: 结果按时间倒序排列', () => {
const out = AuditCore.applyFilters(fixture(), { now: NOW });
assert.deepEqual(out.map(l => l.id), ['a1', 'a2', 'a3', 'a4']);
});
test('applyFilters: 不修改入参数组', () => {
const logs = fixture();
AuditCore.applyFilters(logs, { now: NOW });
assert.equal(logs.length, 4);
C.applyFilters(logs, {});
assert.equal(logs.length, 5);
assert.deepEqual(C.applyFilters(fixture(), {}).map(l => l.id), ['a4', 'a1', 'a2', 'a3', 'a5']);
});
// ---------------- paginate ----------------
test('paginate: 基础分页与元信息', () => {
// ---------------- paginate / countExpired ----------------
test('paginate: 分页与越界收敛', () => {
const items = Array.from({ length: 25 }, (_, i) => i);
const p = AuditCore.paginate(items, 2, 10);
const p = C.paginate(items, 2, 10);
assert.equal(p.total, 25);
assert.equal(p.pages, 3);
assert.equal(p.page, 2);
assert.deepEqual(p.items, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
assert.equal(C.paginate(items, 99, 10).page, 3);
assert.equal(C.paginate(items, 0, 10).page, 1);
assert.deepEqual(C.paginate([], 1, 20), { items: [], total: 0, pages: 1, page: 1 });
});
test('paginate: 页码越界自动收敛', () => {
const items = Array.from({ length: 15 }, (_, i) => i);
assert.equal(AuditCore.paginate(items, 99, 10).page, 2);
assert.equal(AuditCore.paginate(items, 0, 10).page, 1);
});
test('paginate: 空结果时仍返回 1 页', () => {
const p = AuditCore.paginate([], 1, 10);
assert.deepEqual({ total: p.total, pages: p.pages, items: p.items }, { total: 0, pages: 1, items: [] });
});
// ---------------- countExpired(D5 保留期清理) ----------------
test('countExpired: 统计超过保留期的记录', () => {
const logs = fixture(); // NOW 为 2026-11-21,a4 是 11-10
assert.equal(AuditCore.countExpired(logs, 5, NOW), 1); // a4 过期
assert.equal(AuditCore.countExpired(logs, 90, NOW), 0); // 全部在保留期内
assert.equal(C.countExpired(fixture(), 5, NOW), 1);
assert.equal(C.countExpired(fixture(), 90, NOW), 0);
});
// ---------------- CSV 导出 ----------------
test('toCsv: UTF-8 BOM + CRLF + 表头列顺序', () => {
const csv = C.toCsv([fixture()[0]]);
assert.ok(csv.startsWith('\uFEFF操作时间,操作者,尝试用户,动作,资源类型,资源名称,路径,操作描述,变更,结果,状态码,来源IP,User-Agent\r\n'));
assert.ok(csv.endsWith('\r\n'));
});
test('toCsv: 记录按时间升序输出,结果/描述/变更列与界面一致', () => {
const logs = [
{ id: 'b', timestamp: '2026-11-21T10:00:00Z', username: 'guichumo', method: 'PUT', path: '/apis/x/v1alpha1/posts/b', resourceType: 'posts', resourceName: 'b', statusCode: 200, action: 'publish', attemptedUsername: null, remoteIp: '1.1.1.1', userAgent: 'UA' },
{ id: 'a', timestamp: '2026-11-20T10:00:00Z', username: 'unknown', method: 'GET', path: '/login?error=x', resourceType: 'auth', resourceName: null, statusCode: 200, action: 'login-failure', attemptedUsername: 'admin', remoteIp: '2.2.2.2', userAgent: 'bot' }
];
const lines = C.toCsv(logs).split('\r\n');
assert.equal(lines.length, 4, '表头 + 2 行 + 末尾空行');
assert.match(lines[1], /^2026-11-20 18:00:00,未知用户,admin,GET,auth,,/);
assert.match(lines[1], /登录失败,.*失败,200,2\.2\.2\.2,bot$/);
assert.match(lines[2], /发布文章,.*成功,200,1\.1\.1\.1,UA$/);
});
test('toCsv: 引号/逗号/换行转义与公式注入防护', () => {
assert.equal(C.csvEscape('a,b'), '"a,b"');
assert.equal(C.csvEscape('say "hi"'), '"say ""hi"""');
assert.equal(C.csvEscape('line1\nline2'), '"line1\nline2"');
assert.equal(C.csvEscape('=SUM(A1)'), "'=SUM(A1)");
assert.equal(C.csvEscape('+1'), "'+1");
assert.equal(C.csvEscape('@cmd'), "'@cmd");
assert.equal(C.csvEscape(null), '');
});
// ---------------- 登录失败告警窗口 ----------------
test('createLoginFailureTracker: 未开启时只维护清零语义,不产生负载', () => {
const tracker = C.createLoginFailureTracker({ enabled: false, thresholdCount: 2, windowMinutes: 5 });
assert.equal(tracker.record({ success: false, time: NOW }), null);
assert.equal(tracker.record({ success: false, time: NOW + 1000 }), null);
assert.deepEqual(tracker.snapshot(), { count: 0, windowStart: null });
});
test('createLoginFailureTracker: 达到阈值触发一次告警,之后窗口重开', () => {
const tracker = C.createLoginFailureTracker({ enabled: true, thresholdCount: 3, windowMinutes: 5 });
assert.equal(tracker.record({ success: false, time: NOW, remoteIp: '1.2.3.4', attemptedUsername: 'admin' }), null);
assert.equal(tracker.record({ success: false, time: NOW + 1000 }), null);
const alert = tracker.record({ success: false, time: NOW + 2000, remoteIp: '1.2.3.4', userAgent: 'bot', attemptedUsername: 'admin' });
assert.ok(alert);
assert.equal(alert.failures, 3);
assert.equal(alert.windowMinutes, 5);
assert.equal(alert.remoteIp, '1.2.3.4');
assert.equal(alert.attemptedUsername, 'admin');
assert.deepEqual(tracker.snapshot(), { count: 0, windowStart: NOW + 2000 });
// 告警后需重新累计到阈值
assert.equal(tracker.record({ success: false, time: NOW + 3000 }), null);
});
test('createLoginFailureTracker: 登录成功清零、窗口过期重新计数', () => {
const tracker = C.createLoginFailureTracker({ enabled: true, thresholdCount: 3, windowMinutes: 5 });
tracker.record({ success: false, time: NOW });
tracker.record({ success: false, time: NOW + 1000 });
assert.equal(tracker.record({ success: true, time: NOW + 2000 }), null);
assert.deepEqual(tracker.snapshot(), { count: 0, windowStart: null });
tracker.record({ success: false, time: NOW + 3000 });
tracker.record({ success: false, time: NOW + 4000 });
assert.equal(tracker.record({ success: false, time: NOW + 5 * 60000 + 4000 }), null, '超过窗口后重新计数,不应触发');
assert.equal(tracker.snapshot().count, 1);
});
test('alertPayload: 通用 JSON 结构与测试消息', () => {
const real = C.alertPayload({
failures: 5,
windowMinutes: 5,
remoteIp: '1.2.3.4',
userAgent: 'Mozilla/5.0',
attemptedUsername: 'admin',
timestamp: '2026-11-21T12:34:56Z'
});
assert.equal(real.type, 'login-failure');
assert.match(real.title, /登录失败/);
assert.match(real.content, /5 分钟内出现 5 次登录失败/);
assert.match(real.content, /admin/);
assert.deepEqual(real.data, {
failures: 5,
windowMinutes: 5,
remoteIp: '1.2.3.4',
userAgent: 'Mozilla/5.0',
attemptedUsername: 'admin'
});
const testPayload = C.alertPayload({ timestamp: '2026-11-21T12:34:56Z' }, 'test');
assert.equal(testPayload.type, 'test');
assert.match(testPayload.title, /测试/);
assert.match(testPayload.content, /测试告警/);
});
// ---------------- MockData 模拟数据 ----------------
const FIXED_NOW = new Date('2026-11-21T12:00:00Z').getTime();
const REQUIRED_FIELDS = ['id', 'timestamp', 'username', 'method', 'path', 'resourceType', 'resourceName', 'statusCode', 'remoteIp', 'userAgent'];
const REQUIRED_FIELDS = [
'id', 'timestamp', 'username', 'attemptedUsername', 'method', 'action',
'resourceType', 'resourceName', 'path', 'statusCode', 'remoteIp', 'userAgent', 'changes'
];
test('MockData.generateLogs: 同一种子两次生成结果完全一致(确定性)', () => {
const a = MockData.generateLogs(FIXED_NOW);
@@ -207,44 +624,93 @@ test('MockData.generateLogs: 记录数量充足且字段完整', () => {
assert.ok(logs.length >= 120, '应有 120+ 条记录,实际 ' + logs.length);
for (const log of logs) {
for (const field of REQUIRED_FIELDS) {
assert.ok(log[field] !== undefined && log[field] !== null, `记录 ${log.id} 缺少字段 ${field}`);
assert.ok(Object.prototype.hasOwnProperty.call(log, field), `记录 ${log.id} 缺少字段 ${field}`);
}
}
});
test('MockData.generateLogs: 按时间倒序且 id 唯一', () => {
const logs = MockData.generateLogs(FIXED_NOW);
const ids = new Set(logs.map(l => l.id));
assert.equal(ids.size, logs.length, 'id 应唯一');
assert.equal(new Set(logs.map(l => l.id)).size, logs.length, 'id 应唯一');
for (let i = 1; i < logs.length; i++) {
const prev = new Date(logs[i - 1].timestamp).getTime();
const curr = new Date(logs[i].timestamp).getTime();
assert.ok(prev >= curr, `第 ${i} 条时间应不晚于下一条`);
assert.ok(new Date(logs[i - 1].timestamp).getTime() >= new Date(logs[i].timestamp).getTime());
}
});
test('MockData.generateLogs: 包含登录审计与"未知用户"记录(产品设计 4.1)', () => {
const logs = MockData.generateLogs(FIXED_NOW);
assert.ok(logs.some(l => l.resourceType === 'auth' && l.statusCode === 200), '应有登录成功记录');
assert.ok(logs.some(l => l.resourceType === 'auth' && l.username === '未知用户'), '应有登录失败记"未知用户"的记录');
});
test('MockData.generateLogs: 资源解析结果与 resolveResource 规则一致(模拟真实管线)', () => {
test('MockData.generateLogs: 资源解析与语义动作与捕获管线一致', () => {
const logs = MockData.generateLogs(FIXED_NOW);
for (const log of logs) {
const expect = AuditCore.resolveResource(log.path);
assert.equal(log.resourceType, expect.resourceType, log.path);
assert.equal(log.resourceName, expect.resourceName, log.path);
const resolved = C.resolveResource(log.path);
assert.equal(log.resourceType, resolved.resourceType, log.path);
assert.equal(log.resourceName, resolved.resourceName, log.path);
if (log.action) {
assert.equal(typeof log.action, 'string');
}
if (log.changes) {
for (const change of log.changes) {
assert.ok(change.field, '变更条目应含 field');
assert.ok(['ADDED', 'UPDATED', 'REMOVED'].includes(change.changeType));
}
}
}
});
test('MockData.generateLogs: 覆盖全部捕获方法与失败场景', () => {
test('MockData.generateLogs: 覆盖登录失败(302 重定向与 GET 回显 200)', () => {
const logs = MockData.generateLogs(FIXED_NOW);
const methods = new Set(logs.map(l => l.method));
for (const m of ['POST', 'PUT', 'DELETE']) {
assert.ok(methods.has(m), '应包含 ' + m + ' 操作');
assert.ok(logs.some(l => l.action === 'login-failure' && l.method === 'POST' && l.statusCode === 302));
assert.ok(logs.some(l => l.action === 'login-failure' && l.method === 'GET' && l.statusCode === 200));
assert.ok(logs.some(l => l.action === 'login' && l.method === 'POST' && l.statusCode === 302));
assert.ok(logs.some(l => l.method === 'POST' && l.path === '/login' && l.username === 'unknown'));
assert.ok(logs.some(l => l.attemptedUsername === 'admin'));
});
test('MockData.generateLogs: 覆盖系统内部变更(执行者「系统」、无 IP/UA)', () => {
const logs = MockData.generateLogs(FIXED_NOW);
const systemLogs = logs.filter(l => l.username === 'system');
assert.ok(systemLogs.length >= 2);
for (const log of systemLogs) {
assert.equal(log.statusCode, 200);
assert.equal(log.remoteIp, null);
assert.equal(log.userAgent, null);
assert.ok(['update', 'delete'].includes(log.action));
assert.ok(log.changes && log.changes.length > 0);
}
assert.ok(logs.some(l => !AuditCore.isSuccess(l.statusCode)), '应包含失败操作记录');
assert.ok(logs.some(l => l.statusCode === 403), '应包含越权 403 记录');
assert.ok(logs.some(l => l.statusCode === 500), '应包含服务端 500 记录');
});
test('MockData.generateLogs: 故事线「hello-halo 谁改过」可回溯', () => {
const logs = MockData.generateLogs(FIXED_NOW);
const helloEdits = logs.filter(l => l.resourceType === 'posts' && l.resourceName === 'hello-halo' && l.method === 'PUT');
assert.ok(helloEdits.length >= 3);
assert.ok(helloEdits.some(l => l.username === 'editor.zhang'));
assert.ok(helloEdits.some(l => l.username === 'guichumo'));
assert.ok(helloEdits.some(l => l.changes && l.changes.some(c => c.field === 'spec.title')));
});
test('MockData.generateLogs: 覆盖插件生命周期、越权与误删', () => {
const logs = MockData.generateLogs(FIXED_NOW);
const actions = new Set(logs.map(l => l.action));
assert.ok(actions.has('upgrade'));
assert.ok(actions.has('enable'));
assert.ok(actions.has('uninstall'));
assert.ok(logs.some(l => l.statusCode === 403));
assert.ok(logs.some(l => l.statusCode === 404));
assert.ok(logs.some(l => l.statusCode === 500));
const deleted = logs.find(l => l.method === 'DELETE' && l.resourceName === 'weekly-2026-w45');
assert.ok(deleted);
assert.ok(deleted.changes && deleted.changes.length > 0, '误删文章应带字段快照');
});
test('MockData.generateLogs: 字段变更覆盖新增/修改/删除且敏感字段已脱敏', () => {
const logs = MockData.generateLogs(FIXED_NOW);
const allChanges = logs.flatMap(l => l.changes || []);
const types = new Set(allChanges.map(c => c.changeType));
assert.ok(types.has('ADDED'));
assert.ok(types.has('UPDATED'));
assert.ok(types.has('REMOVED'));
for (const change of allChanges) {
if (C.isSensitiveField(change.field)) {
assert.ok([change.oldValue, change.newValue].every(v => v == null || v === '******'),
'敏感字段不得落库明文:' + change.field);
}
}
});

Before

Width:  |  Height:  |  Size: 162 KiB

After

Width:  |  Height:  |  Size: 162 KiB

Before

Width:  |  Height:  |  Size: 144 KiB

After

Width:  |  Height:  |  Size: 144 KiB

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 51 KiB

Before

Width:  |  Height:  |  Size: 48 KiB

After

Width:  |  Height:  |  Size: 48 KiB

Before

Width:  |  Height:  |  Size: 134 KiB

After

Width:  |  Height:  |  Size: 134 KiB

@@ -143,6 +143,7 @@ Artifact path and SHA-256:
## 参考链接
- [发布验收待办完成记录](./operation-audit-release-todos-completion.md)
- [插件发布验收清单(本地存档)](./plugin-release-checklist.md)
- [Halo 官方插件清单文档](https://docs.halo.run/developer-guide/plugin/basics/manifest.md)
- [Halo 官方 UI 构建输出格式](https://docs.halo.run/developer-guide/plugin/basics/ui/build.md)
@@ -0,0 +1,104 @@
# 操作审计插件发布验收待办完成记录
> 对 [验收清单确认报告](./operation-audit-release-checklist-review.md)(首轮确认)列出的
> 6 项待办的执行总结。逐项实测证据的完整记录见
> [测试报告第四轮](./operation-audit-test-report.md)。
>
> - 完成日期:2026-11-22
> - 制品基线:`plugin-operation-audit/build/libs/plugin-operation-audit-0.1.0.jar`
> (commit `81693e4` 干净构建)
> - 最终状态:**发布就绪**,tag `v0.1.0`(本地,指向 commit `5d05d63`)
## 一、待办完成总览
首轮确认报告的 6 项待办(2×P0、2×P1、2×P2)全部补齐并复测通过:
| 优先级 | 待办 | 完成方式与结果 | Commit |
| --- | --- | --- | --- |
| P0 | 以正式版本号(非 SNAPSHOT)重新干净构建,复查三处一致 | `clean build -Pversion=0.1.0` 全绿;JAR 文件名 / JAR 内 `plugin.yaml` `spec.version` / Manifest `Implementation-Version` 三处均为 0.1.0 | `81693e4` |
| P0 | 补 CI/CD 工作流 | `.github/workflows/ci.yml` + `cd.yml` 复用官方 `halo-sigs/reusable-workflows@v5` | `44eca75` |
| P1 | 补卸载(uninstall)测试 | 对齐 Console「卸载并删除配置」真实流程实测通过(详见[测试报告](./operation-audit-test-report.md)第四轮) | `753de51` |
| P1 | 2.26.0 最低版本下探实测 | 官方 2.26.0 发布 JAR 全新实例关键路径全部通过(详见[测试报告](./operation-audit-test-report.md)) | `5d05d63` |
| P1 | 发布制品 SHA-256 与发布证据块 | SHA-256 已记录于确认报告[发布证据块](./operation-audit-release-checklist-review.md) | `5d05d63` |
| P2 | 补 `plugin.yaml` 元数据 | `logo.svg` 内置 + `homepage` / `repo` / `issues` / `author.website` / `license.url`(URL 逐一可达性验证) | `81693e4` |
| P2 | UI 输出目录迁移 `ui/` | `processUiResources` 输出至 `resources/main/ui`,JAR 内 `ui/ui-plugin.json` 入口/样式齐备 | `81693e4` |
## 二、关键执行细节
### 1. 正式版本构建与三处一致复查
- `JAVA_HOME="C:/Program Files/Java/jdk-21.0.10" ./gradlew clean build -Pversion=0.1.0`
全绿(后端 + UI 全部检查);
- 复查:`plugin-operation-audit-0.1.0.jar` ↔ `unzip -p … plugin.yaml` 中
`spec.version: "0.1.0"` ↔ Manifest `Implementation-Version: 0.1.0` 一致;
- 制品 SHA-256:`3d2a2ad4…db563`(完整值见确认报告发布证据块)。
### 2. CI/CD 工作流
- CI(push/PR → master):官方可复用工作流 `plugin-ci.yaml@v5`,执行
`./gradlew clean build`(全部测试,不可跳过);
- CD(GitHub Release published):`plugin-cd.yaml@v5`,自动
`./gradlew clean build -x check -Pversion=${tag 去 v 前缀}`,保证 tag ↔ JAR 名 ↔
`spec.version` 一致;`artifacts-path` 限定 `plugin-operation-audit/build/libs`;
`skip-appstore-release: true`(首次上架审核通过前不同步应用市场);
- 适配本仓库布局:官方工作流从仓库根执行 `./gradlew`,而 Gradle 构建根在
`plugin-operation-audit/` 子目录——根目录 `gradlew` / `gradlew.bat` 为转发脚本,
经 `build-args: "-p plugin-operation-audit"` 指定项目目录(委托链路已本地验证);
UI 子项目使用 npm(无 pnpm-lock.yaml),故 `skip-node-setup: true`。
### 3. 卸载(uninstall)生命周期实测(Halo 2.26.1 烟测实例)
- 流程对齐 Console「卸载并删除配置」分支(先经 Halo 2.26.1 源码考证
`use-plugin.ts` 与 `PluginReconciler#cleanupResources`):
停用 → `DELETE` Plugin CR(finalizer 约 24s 清理)→ 删 Setting → 删 ConfigMap;
- 核对结果:CR / JAR / Setting / ConfigMap / RoleTemplate 全部清理;
审计数据保留(重装后 169 → 172 条回归);停用期间 pf4j `disabled.txt`
写入的残留被 Halo 重装启动时自动清除;
- 唯一残留:宿主侧 RoleBinding 孤儿绑定(Halo 平台行为,RoleTemplate 已删、
无授权效果,记录备查)。
### 4. 2.26.0 最低版本下探实测
- 实例:官方 2.26.0 发布 JAR(下载件 sha256 与官方 `.sha256` 逐字符一致),
一次性全新数据目录,测试后停用丢弃;
- 关键路径全部通过:setup / admin 登录(RSA + CSRF 契约)/ install / enable
(STARTED)/ 审计捕获 / query / export / 匿名拒绝 / `ui/` ESM bundle 下发 /
实例日志 0 ERROR;
- 行为差异实测记录:2.26.0 的登录失败返回 **401 JSON**(2.26.1 为
302 → `?error=` 参数),插件认证端点过滤器在两种形态下均正确标注
`login-failure` 语义动作;
- 至此 `spec.requires >=2.26.0` 的实测验证完成(2.26.1 为当前版本复验)。
### 5. manifest 元数据与 ui/ 迁移
- `logo.svg` 置于 `src/main/resources/`(官方插件同款相对路径引用方式);
- `homepage` / `repo` / `issues` 指向仓库托管地址(逐一 curl 验证 200);
- `ui/` 目录为 Halo ≥2.25.0 官方规范输出位置(`console/` 为旧项目兼容回退);
迁移同时清理旧构建残留的 `console/` 目录,防止过期产物入 JAR。
## 三、提交记录
```
5d05d63 docs: 发布验收全部待办完成——2.26.0 下探通过,验收报告更新为发布就绪
753de51 docs: 测试报告补卸载(uninstall)生命周期实测记录
44eca75 ci: 发布验收 P0 项——补齐 CI/CD 工作流
81693e4 chore: 发布验收 P2 项——UI 产物迁至 ui/,补齐 manifest 元数据
tag: v0.1.0 → 5d05d63(本地 annotated tag)
```
## 四、剩余发布动作(发布操作,非验收缺口)
1. 推送 master 与 tag `v0.1.0`;
2. 在代码托管平台创建 GitHub Release(tag `v0.1.0`)——CD 工作流自动构建并
把 JAR 上传为 Release 资产;
3. 发布 commit 的 CI 必须绿色(CD 带 `-x check`,不能替代 CI 与测试);
4. 应用市场首次审核通过后,再按官方发布文档配置 `app-id` 与最小权限的
`HALO_PAT` 令牌开启自动同步。
## 五、环境备注
- Docker Hub 在本机不可达(registry 连接超时),2.26.0 实例改用官方独立 JAR
(经 GitHub release 镜像加速下载,官方 SHA-256 校验通过);
- 本机 `JAVA_HOME` 指向 jre7,所有 Gradle 调用需临时覆盖为 JDK 21;
- 全部测试实例均为一次性数据目录(`workdir` / `workdir-260`),与生产数据无任何
关联,测试完成后停用。
+4 -4
View File
@@ -101,7 +101,7 @@ Known limitations: 见文末"未覆盖项"
### 浏览器级 UI 验证(桌面 + 窄屏人工检查)
使用真实浏览器登录 Console 逐项检查,截图存于仓库 `gui-test-screenshots/`:
使用真实浏览器登录 Console 逐项检查,截图存于仓库 `docs/assets/gui-test-screenshots/`:
- 菜单入口:`plugin` 分组下出现「操作审计」,选中态高亮正确(t1);
- 列表页(1280px):筛选区(操作者/资源类型/动作/语义动作/结果/关键字/起止时间)、
@@ -404,9 +404,9 @@ Known limitations: 2.26.0 最低版本下探已于本节补充执
## 附:测试环境残留与清理
- 测试实例保留运行于 `http://127.0.0.1:8099`(admin / Sm0keTest2026,
- 测试实例保留运行于 `http://127.0.0.1:8099`(admin / 测试密码已脱敏,
数据目录 `C:/Users/Windows11/.halo-smoke-test/workdir`,可丢弃,与生产数据无任何关联);
- 第三轮联调中将 auditor3 密码重置为 `AuditR3.2026`(供只读角色矩阵复测),
- 第三轮联调中重置了 auditor3 密码(测试凭据已脱敏,供只读角色矩阵复测),
残留测试用户 auditor3(role-template-audit-view)保留于实例中;
- 已恢复干净版插件 JAR 并确认无诊断日志残留(重启后 0 条 AUDIT-DIAG);
- 源码工作区干净,仅新增截图证据目录 `gui-test-screenshots/`(未纳入版本控制)。
- 源码工作区干净,截图证据已归档至 `docs/assets/gui-test-screenshots/` 并纳入版本控制。