diff --git a/README.md b/README.md index 62097dc..55a4def 100644 --- a/README.md +++ b/README.md @@ -63,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 个用例 ``` ## 相关文档 @@ -78,7 +79,7 @@ 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 之后的候选能力) | diff --git a/demo/README.md b/demo/README.md index ec9b63a..2e2adc8 100644 --- a/demo/README.md +++ b/demo/README.md @@ -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 宿主渲染。 diff --git a/demo/assets/app.js b/demo/assets/app.js index d522902..6fc6cfb 100644 --- a/demo/assets/app.js +++ b/demo/assets/app.js @@ -2,181 +2,378 @@ * 操作审计 Console UI Demo · 交互层(无框架,模拟 Halo Console 插件页) * * 数据流模拟真实插件的捕获管线: - * 请求(method/path/user) → AuditCore.shouldCapture 判定 → AuditCore.resolveResource 解析 - * → 生成审计记录 → 渲染到列表 + * 请求(method/path/user/status/location) → AuditCore.shouldCapture 判定 + * → AuditCore.resolveResource 解析 → 登录结果判定 → 语义动作标注 + * → AuditCore.diffObjects 字段 diff → 生成审计记录 → 渲染到列表 + * + * 系统内部变更单独走「扩展模型 Watcher」通道(执行者「系统」、无 IP/UA)。 * 全部数据保存在页面内存中,刷新即重置。 */ (function () { 'use strict'; + var C = window.AuditCore; + var $ = function (sel) { return document.querySelector(sel); }; + var $$ = function (sel) { return Array.prototype.slice.call(document.querySelectorAll(sel)); }; // ---------- 状态 ---------- - var state = { - logs: [], - filters: { operator: '', resourceType: '', method: '', result: '', timeRange: 'all', keyword: '' }, - page: 1, - size: 10, - tab: 'logs', - settings: { enabled: true, retentionDays: 90 }, - detailId: null, - highlightId: null + var DEFAULT_FILTERS = { + operator: '', + resourceType: '', + method: '', + action: '', + result: '', + keyword: '', + startTime: '', + endTime: '' }; - var DEFAULT_FILTERS = { operator: '', resourceType: '', method: '', result: '', timeRange: 'all', keyword: '' }; + var state = { + logs: [], + filters: Object.assign({}, DEFAULT_FILTERS), + page: 1, + size: 20, + tab: 'logs', + settings: { + enabled: true, + recordChanges: true, + recordSystemChanges: true, + retentionDays: 90 + }, + alertSettings: { + enabled: false, + webhookSecretName: '', + thresholdCount: 5, + windowMinutes: 5 + }, + alertTracker: null, + lastAlert: null, + detailId: null, + highlightId: null, + simTab: 'http', + simPrevious: null + }; // ---------- 工具 ---------- function esc(s) { - return String(s).replace(/[&<>"']/g, function (c) { + return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); } - function fmtTime(iso) { - var d = new Date(iso); - function p(n) { return n < 10 ? '0' + n : '' + n; } - return d.getFullYear() + '-' + p(d.getMonth() + 1) + '-' + p(d.getDate()) + - ' ' + p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds()); - } - - function fmtDate(iso) { - return fmtTime(iso).slice(0, 10); - } - - function avCls(name) { - var sum = 0; - String(name).split('').forEach(function (c) { sum += c.charCodeAt(0); }); - return 'c-' + 'abcde'[sum % 5]; - } - - function initial(name) { - return String(name).charAt(0).toUpperCase(); - } - - var toastTimer = null; function toast(msg, type) { var el = $('#toast'); el.textContent = msg; el.className = 'toast show ' + (type || ''); - clearTimeout(toastTimer); - toastTimer = setTimeout(function () { el.classList.remove('show'); }, 2800); + clearTimeout(toast._timer); + toast._timer = setTimeout(function () { el.classList.remove('show'); }, 3200); } function methodBadge(method) { - return '' + esc(method) + ''; + return '' + esc(method) + ''; } - function resultBadge(code) { - var ok = AuditCore.isSuccess(code); - return '' + code + ' ' + (ok ? '成功' : '失败') + ''; + function avatar(username) { + var name = C.displayUsername(username); + var initial = username === 'system' ? '系' : (username === 'unknown' ? '?' : name.charAt(0).toUpperCase()); + var sum = 0; + name.split('').forEach(function (ch) { sum += ch.charCodeAt(0); }); + return '' + esc(initial) + ''; + } + + function parseTime(value) { + if (!value) { + return null; + } + var ms = new Date(value).getTime(); + return isNaN(ms) ? null : ms; } - // ---------- 渲染 ---------- function filteredLogs() { - var f = state.filters; - return AuditCore.applyFilters(state.logs, { - operator: f.operator, - resourceType: f.resourceType, - method: f.method, - result: f.result, - timeRange: f.timeRange, - keyword: f.keyword - }); + return C.applyFilters(state.logs, state.filters); } - function activeFilterCount() { + function activeFilterLabels() { var f = state.filters; - var n = 0; - ['operator', 'resourceType', 'method', 'result'].forEach(function (k) { - if (f[k]) n++; - }); - if (f.timeRange && f.timeRange !== 'all') n++; // 'all' 为默认值,不算激活的筛选 - if (String(f.keyword).trim()) n++; - return n; + var labels = []; + if (f.operator) { labels.push('操作者=' + f.operator); } + if (f.resourceType) { labels.push('资源类型=' + f.resourceType); } + if (f.method) { labels.push('动作=' + f.method); } + if (f.action) { + var action = C.SEMANTIC_ACTIONS.filter(function (a) { return a.value === f.action; })[0]; + labels.push('语义动作=' + (action ? action.label : f.action)); + } + if (f.result) { labels.push('结果=' + (f.result === 'success' ? '成功' : '失败')); } + if (f.keyword) { labels.push('关键字=' + f.keyword); } + if (f.startTime) { labels.push('开始=' + f.startTime.replace('T', ' ')); } + if (f.endTime) { labels.push('结束=' + f.endTime.replace('T', ' ')); } + return labels; } + // ---------- 资源快照(字段 diff 的「写入前状态」)---------- + var POST_TITLES = { + 'hello-halo': '你好,Halo', + 'self-host-guide': '自托管指南', + 'reading-notes-11': '读书笔记 #11', + 'plugin-dev-diary': '插件开发日志', + 'weekly-2026-w46': '每周摘要 · 2026 W46', + 'weekly-2026-w45': '每周摘要 · 2026 W45', + 'spring-festival-2026': '春节计划' + }; + + var PLUGIN_VERSIONS = { + 'plugin-search-widget': '1.3.0', + 'plugin-comment-widget': '1.6.0', + 'plugin-sitemap': '1.0.5', + 'plugin-links': '2.2.0' + }; + + /** 运行时生成的演示假口令(非真实凭据,仅用于验证敏感字段脱敏)。 */ + function demoOnlySecret() { + return 'demo-only-' + Math.random().toString(16).slice(2, 14); + } + + function postSnapshot(name) { + return { + apiVersion: 'content.halo.run/v1alpha1', + kind: 'Post', + metadata: { name: name, labels: { 'content.halo.run/pinned': 'false' } }, + spec: { + title: POST_TITLES[name] || name, + slug: name, + visible: 'PUBLIC', + publish: true, + pinned: false, + allowComment: true, + summary: '演示用资源快照。' + } + }; + } + + function pluginSnapshot(name) { + return { + apiVersion: 'plugin.halo.run/v1alpha1', + kind: 'Plugin', + metadata: { name: name }, + spec: { + displayName: name, + version: PLUGIN_VERSIONS[name] || '1.0.0', + enabled: true, + requires: '>=2.20.0' + } + }; + } + + function userSnapshot(name) { + return { + apiVersion: 'v1alpha1', + kind: 'User', + metadata: { name: name }, + spec: { + displayName: name, + email: name + '@example.com', + password: demoOnlySecret(), + roles: ['role-template-author'] + } + }; + } + + function snapshotFor(path) { + var clean = C.pathWithoutQuery(path); + var m; + if ((m = clean.match(/\/posts\/([^/]+)$/))) { return postSnapshot(m[1]); } + if ((m = clean.match(/\/plugins\/([^/]+)/))) { return pluginSnapshot(m[1]); } + if ((m = clean.match(/\/users\/([^/]+)\/(?:password|resetpassword)$/))) { return userSnapshot(m[1]); } + if ((m = clean.match(/\/users\/([^/]+)$/))) { return userSnapshot(m[1]); } + if ((m = clean.match(/\/configmaps\/([^/]+)$/))) { + return { + apiVersion: 'v1alpha1', + kind: 'ConfigMap', + metadata: { name: m[1] }, + data: { theme: 'theme-earth', locale: 'zh-CN' } + }; + } + return null; + } + + function rememberSnapshot(record, body) { + var clean = C.pathWithoutQuery(record.path); + var m; + if (record.statusCode < 200 || record.statusCode >= 300) { + return; + } + if (record.method === 'DELETE') { + state.snapshots[clean] = null; + return; + } + if (!body) { + return; + } + // 按完整路径记住最新资源状态,后续编辑同一资源可直接算出字段 diff + state.snapshots[clean] = body; + } + + state.snapshots = {}; + + // ---------- 渲染:筛选 ---------- function renderFilterOptions() { - var operators = {}; - var types = {}; - state.logs.forEach(function (l) { - operators[l.username] = true; - types[l.resourceType] = true; - }); - var opSel = $('#f-operator'); var typeSel = $('#f-type'); - opSel.innerHTML = '' + Object.keys(operators).sort().map(function (u) { - return ''; + typeSel.innerHTML = '' + C.RESOURCE_TYPES.map(function (type) { + var label = C.RESOURCE_LABELS[type] || type; + return ''; }).join(''); - typeSel.innerHTML = '' + Object.keys(types).sort().map(function (t) { - return ''; + + var actionSel = $('#f-action'); + actionSel.innerHTML = '' + C.SEMANTIC_ACTIONS.map(function (action) { + return ''; }).join(''); - // 动作选项与捕获规则一致:POST/PUT/DELETE/PATCH(AuditCore.WRITE_METHODS) - $('#f-method').innerHTML = '' + AuditCore.WRITE_METHODS.map(function (m) { - return ''; + + var sysType = $('#sys-type'); + sysType.innerHTML = C.RESOURCE_TYPES.map(function (type) { + return ''; }).join(''); + + syncFilterInputs(); + } + + function syncFilterInputs() { + var f = state.filters; + $('#f-operator').value = f.operator; + $('#f-type').value = f.resourceType; + $('#f-method').value = f.method; + $('#f-action').value = f.action; + $('#f-result').value = f.result; + $('#f-keyword').value = f.keyword; + $('#f-start').value = f.startTime; + $('#f-end').value = f.endTime; + } + + function readFilterInputs() { + state.filters = { + operator: $('#f-operator').value.trim(), + resourceType: $('#f-type').value, + method: $('#f-method').value, + action: $('#f-action').value, + result: $('#f-result').value, + keyword: $('#f-keyword').value.trim(), + startTime: $('#f-start').value, + endTime: $('#f-end').value + }; + } + + function renderFilterNote() { + var labels = activeFilterLabels(); + $('#filter-note').hidden = labels.length === 0; + $('#filter-note-text').textContent = '筛选中:' + labels.join(' · '); + } + + // ---------- 渲染:列表 ---------- + function resultCell(log) { + var badge = C.resultBadge(log); + return '' + esc(badge.text) + ''; + } + + function changesHint(log) { + var count = log.changes ? log.changes.length : 0; + return count ? '变更 ' + count + '' : ''; + } + + function renderTable() { + var filtered = filteredLogs(); + var paged = C.paginate(filtered, state.page, state.size); + state.page = paged.page; + var tbody = $('#tbody'); + + if (paged.total === 0) { + var active = activeFilterLabels().length > 0; + tbody.innerHTML = '
' + + '
🔍
' + + '

' + (active ? '没有匹配当前筛选条件的记录' : '暂无审计记录') + '

' + + '

' + (active + ? '可调整筛选条件,或清除筛选查看全部记录' + : '插件启用后,后台写操作与登录事件会自动记录在这里') + '

' + + '' + + '
'; + $('#empty-clear').addEventListener('click', active ? clearFilters : renderAll); + } else { + tbody.innerHTML = paged.items.map(function (log) { + var classes = []; + if (state.detailId === log.id) { classes.push('selected'); } + if (state.highlightId === log.id) { classes.push('row-new'); } + var resource = '' + esc(log.resourceType) + ''; + if (log.resourceName) { + resource += '/ ' + esc(log.resourceName) + '' + + '历史'; + } else { + resource += '集合级操作'; + } + return '' + + '
' + avatar(log.username) + + '
' + esc(C.displayUsername(log.username)) + '
' + + '
' + esc(C.formatTime(log.timestamp)) + '
' + + '' + methodBadge(log.method) + '' + + '
' + resource + '
' + + '
' + esc(log.path) + '
' + + '' + + esc(C.describeOperation(log)) + '' + changesHint(log) + '' + + '' + resultCell(log) + '' + + '' + (log.remoteIp ? esc(log.remoteIp) : '—') + '' + + ''; + }).join(''); + + tbody.querySelectorAll('tr[data-id]').forEach(function (tr) { + tr.addEventListener('click', function () { openDetail(tr.getAttribute('data-id')); }); + }); + tbody.querySelectorAll('[data-history]').forEach(function (link) { + link.addEventListener('click', function (event) { + event.stopPropagation(); + viewResourceHistory(link.getAttribute('data-history')); + }); + }); + } + + $('#pg-info').textContent = '共 ' + paged.total + ' 条记录'; + $('#pg-page').textContent = paged.page + ' / ' + paged.pages; + $('#pg-prev').disabled = paged.page <= 1; + $('#pg-next').disabled = paged.page >= paged.pages; + $('#btn-clear').hidden = activeFilterLabels().length === 0; + renderFilterNote(); + } + + // ---------- 渲染:设置 ---------- + function renderSettings() { + var s = state.settings; + var a = state.alertSettings; + $('#set-enabled').checked = s.enabled; + $('#set-record-changes').checked = s.recordChanges; + $('#set-record-system').checked = s.recordSystemChanges; + $('#set-retention').value = s.retentionDays; + $('#set-alert-enabled').checked = a.enabled; + $('#set-alert-secret').value = a.webhookSecretName; + $('#set-alert-threshold').value = a.thresholdCount; + $('#set-alert-window').value = a.windowMinutes; + + var expired = C.countExpired(state.logs, s.retentionDays, Date.now()); + var earliest = state.logs.length + ? new Date(Math.min.apply(null, state.logs.map(function (log) { + return new Date(log.timestamp).getTime(); + }))) + : null; + $('#clean-stats').innerHTML = + '当前共 ' + state.logs.length + ' 条记录,最早一条:' + + (earliest ? esc(C.formatTime(earliest.toISOString())) : '—') + '。
' + + '按保留期 ' + s.retentionDays + ' 天计算,下次定时清理预计删除 ' + + (expired > 0 ? '' + expired + ' 条' : '0 条') + '。'; } function renderBanner() { $('#audit-off-banner').hidden = state.settings.enabled; } - function renderTable() { - var filtered = filteredLogs(); - var paged = AuditCore.paginate(filtered, state.page, state.size); - var tbody = $('#tbody'); - - if (paged.total === 0) { - tbody.innerHTML = '
' + - '
🔍
' + - '

未找到匹配的审计记录

' + - (activeFilterCount() ? '' : '') + - '
'; - var emptyClear = $('#empty-clear'); - if (emptyClear) emptyClear.addEventListener('click', clearFilters); - } else { - tbody.innerHTML = paged.items.map(function (rec) { - var cls = []; - if (state.detailId === rec.id) cls.push('selected'); - if (state.highlightId === rec.id) cls.push('row-new'); - return '' + - '' + fmtTime(rec.timestamp) + '' + - '' + esc(initial(rec.username)) + '' + esc(rec.username) + '' + - '' + methodBadge(rec.method) + '' + - '' + esc(rec.resourceType) + '' + - (rec.resourceName ? '' + esc(rec.resourceName) + '' : '(集合级操作)') + - '' + - '' + resultBadge(rec.statusCode) + '' + - '' + esc(rec.remoteIp) + '' + - ''; - }).join(''); - tbody.querySelectorAll('tr[data-id]').forEach(function (tr) { - tr.addEventListener('click', function () { openDetail(tr.getAttribute('data-id')); }); - }); - } - - $('#pg-info').textContent = '共 ' + paged.total + ' 条 · 第 ' + paged.page + ' / ' + paged.pages + ' 页'; - $('#pg-prev').disabled = paged.page <= 1; - $('#pg-next').disabled = paged.page >= paged.pages; - - $('#btn-clear').hidden = activeFilterCount() === 0; - } - - function renderSettings() { - $('#set-enabled').checked = state.settings.enabled; - $('#set-retention').value = state.settings.retentionDays; - - var logs = state.logs; - var expired = AuditCore.countExpired(logs, state.settings.retentionDays, Date.now()); - var earliest = logs.length ? logs[logs.length - 1].timestamp : null; - $('#clean-stats').innerHTML = - '当前共 ' + logs.length + ' 条记录,最早一条:' + (earliest ? fmtDate(earliest) : '—') + '。
' + - '按保留期 ' + state.settings.retentionDays + ' 天计算,下次定时清理预计删除 ' + - (expired > 0 ? '' + expired + ' 条' : '0 条') + '。'; - } - function renderTabs() { - document.querySelectorAll('.tab').forEach(function (t) { - t.classList.toggle('active', t.getAttribute('data-tab') === state.tab); + $$('.tab').forEach(function (tab) { + tab.classList.toggle('active', tab.getAttribute('data-tab') === state.tab); }); $('#panel-logs').hidden = state.tab !== 'logs'; $('#panel-settings').hidden = state.tab !== 'settings'; @@ -184,44 +381,82 @@ function renderAll() { renderBanner(); - renderFilterOptions(); renderTable(); renderSettings(); renderTabs(); + renderAlertBanner(); } // ---------- 详情抽屉 ---------- - function openDetail(id) { - var rec = null; + function findLog(id) { for (var i = 0; i < state.logs.length; i++) { - if (state.logs[i].id === id) { rec = state.logs[i]; break; } + if (state.logs[i].id === id) { return state.logs[i]; } } - if (!rec) return; + return null; + } + + function detailRow(label, valueHtml) { + return '
' + esc(label) + '
' + valueHtml + '
'; + } + + function changeRow(change) { + var badge = change.changeType === 'ADDED' ? 'change-added' + : change.changeType === 'REMOVED' ? 'change-removed' : 'change-updated'; + var values; + if (change.changeType === 'ADDED') { + values = '' + esc(C.changeValueDisplay(change.newValue)) + ''; + } else if (change.changeType === 'REMOVED') { + values = '' + esc(C.changeValueDisplay(change.oldValue)) + ''; + } else { + values = '' + esc(C.changeValueDisplay(change.oldValue)) + '' + + '→' + + '' + esc(C.changeValueDisplay(change.newValue)) + ''; + } + return '
' + + '' + esc(C.changeTypeLabel(change.changeType)) + '' + + '
' + esc(change.field) + '
' + + '
' + values + '
'; + } + + function openDetail(id) { + var log = findLog(id); + if (!log) { return; } state.detailId = id; - var row = function (dt, dd) { - return '
' + dt + '
' + dd + '
'; - }; + var changes = log.changes || []; + var badge = C.resultBadge(log); + var details = + detailRow('操作者', avatar(log.username) + ' ' + esc(C.displayUsername(log.username))) + + (log.attemptedUsername ? detailRow('尝试用户', '' + esc(log.attemptedUsername) + '') : '') + + detailRow('描述', esc(C.describeOperation(log))) + + detailRow('动作', methodBadge(log.method)) + + detailRow('资源', esc(log.resourceType) + (log.resourceName ? ' / ' + esc(log.resourceName) : ' (集合级操作)')) + + detailRow('结果', '' + esc(badge.text) + '' + + ' 状态码 ' + esc(log.statusCode) + '') + + detailRow('路径', '' + esc(log.path) + '') + + detailRow('时间', esc(C.formatTime(log.timestamp))) + + detailRow('来源 IP', log.remoteIp ? '' + esc(log.remoteIp) + '' : '—(系统内部变更无 IP)') + + detailRow('User-Agent', log.userAgent ? '' + esc(log.userAgent) + '' : '—') + + detailRow('记录标识', '' + esc(log.id) + ''); + + var changesHtml = ''; + if (changes.length) { + changesHtml = '

字段变更(' + changes.length + ')

' + + changes.map(changeRow).join('') + '
'; + } var drawer = $('#drawer'); drawer.innerHTML = '
' + - '
审计记录详情
' + esc(rec.id) + '
' + - '' + + '
审计记录详情
' + + esc(C.formatTime(log.timestamp)) + ' · ' + esc(log.id) + '
' + + '' + '
' + - '
🛡️ 审计记录为只读,不提供任何修改或删除入口(设计原则 3 · 技术方案 D4)
' + - '
' + - row('时间', esc(fmtTime(rec.timestamp))) + - row('操作者', '' + esc(initial(rec.username)) + '' + esc(rec.username)) + - row('动作', methodBadge(rec.method)) + - row('资源类型', '' + esc(rec.resourceType) + '') + - row('资源名称', rec.resourceName ? esc(rec.resourceName) : '(集合级操作,无具体资源名)') + - row('完整路径', '' + esc(rec.path) + '') + - row('结果', resultBadge(rec.statusCode)) + - row('来源 IP', esc(rec.remoteIp)) + - row('User-Agent', '' + esc(rec.userAgent) + '') + - '
' + - '
原始记录(JSON)
' + esc(JSON.stringify(rec, null, 2)) + '
'; + '
🛡️ 审计记录只读,不提供任何修改或删除入口
' + + '
' + details + '
' + + changesHtml + + '
原始数据(AuditLog Extension JSON)' + + '
' + esc(JSON.stringify(C.toWire(log), null, 2)) + '
'; drawer.hidden = false; $('#drawer-overlay').hidden = false; @@ -236,71 +471,91 @@ renderTable(); } - // ---------- 模拟一次操作 ---------- - function nextLogId() { - var max = 0; - state.logs.forEach(function (l) { - var n = parseInt(String(l.id).replace('audit-', ''), 10); - if (n > max) max = n; + // ---------- 资源历史快捷 ---------- + function viewResourceHistory(id) { + var log = findLog(id); + if (!log || !log.resourceName) { return; } + state.filters = Object.assign({}, DEFAULT_FILTERS, { + resourceType: log.resourceType, + keyword: log.resourceName }); - return 'audit-' + String(max + 1).padStart(4, '0'); + state.page = 1; + syncFilterInputs(); + renderTable(); + window.scrollTo({ top: 0, behavior: 'smooth' }); + toast('已按「' + log.resourceType + ' / ' + log.resourceName + '」筛选历史操作', 'ok'); } - function simulateSend() { - var user = $('#sim-user').value; - var method = $('#sim-method').value; - var path = String($('#sim-path').value).trim(); - var status = parseInt($('#sim-status').value, 10); + // ---------- CSV 导出 ---------- + function two(n) { return n < 10 ? '0' + n : String(n); } - if (!path) { toast('请填写请求路径', 'warn'); return; } - - var authenticated = user !== '__anon__'; - - if (!state.settings.enabled) { - toast('审计开关已关闭,本次操作未记录', 'warn'); + function exportLogs() { + var logs = filteredLogs(); + if (!logs.length) { + toast('当前筛选条件下没有可导出的记录', 'warn'); return; } + var csv = C.toCsv(logs); + var blob = new Blob([csv], { type: 'text/csv;charset=utf-8' }); + var now = new Date(); + var filename = 'audit-logs-' + now.getFullYear() + two(now.getMonth() + 1) + + two(now.getDate()) + '-' + two(now.getHours()) + two(now.getMinutes()) + + two(now.getSeconds()) + '.csv'; + var url = URL.createObjectURL(blob); + var anchor = document.createElement('a'); + anchor.href = url; + anchor.download = filename; + anchor.click(); + URL.revokeObjectURL(url); + toast('已导出 ' + logs.length + ' 条记录:' + filename + '(UTF-8 BOM)', 'ok'); + } - var rule = AuditCore.shouldCapture({ method: method, path: path, authenticated: authenticated }); - if (!rule.captured) { - toast('未记录:' + rule.reason, 'warn'); + // ---------- 登录失败告警 ---------- + function rebuildAlertTracker() { + state.alertTracker = C.createLoginFailureTracker(state.alertSettings); + } + + function showAlert(payload) { + state.lastAlert = payload; + var text = payload.windowMinutes + ' 分钟内出现 ' + payload.failures + + ' 次登录失败 · 来源 ' + (payload.remoteIp || '未知') + + ' · 尝试账号 ' + (payload.attemptedUsername || '未知'); + $('#alert-banner-text').textContent = text; + $('#alert-banner').hidden = false; + window.scrollTo({ top: 0, behavior: 'smooth' }); + toast('登录失败告警已触发,Webhook 负载见「插件设置 → 告警通知」', 'warn'); + renderAlertBannerJson(); + } + + function renderAlertBannerJson() { + var output = $('#alert-test-output'); + if (!state.lastAlert || !state.alertSettings.enabled) { return; } + output.hidden = false; + output.textContent = JSON.stringify(C.alertPayload(state.lastAlert, 'login-failure'), null, 2); + } - // 组装审计记录(与真实管线一致:规则判定 → 资源解析 → 落一条记录) - var isAuthPath = path === '/login' || path === '/logout'; - var username = authenticated ? user : '未知用户'; - if (isAuthPath && status >= 400) username = '未知用户'; // 登录失败记"未知用户"(产品设计已知局限) + function renderAlertBanner() { + $('#alert-banner').hidden = !state.lastAlert; + } - var record = { - id: nextLogId(), - timestamp: new Date().toISOString(), - username: username, - method: AuditCore.normalizeMethod(method), - path: path, - resourceType: AuditCore.resolveResource(path).resourceType, - resourceName: AuditCore.resolveResource(path).resourceName, - statusCode: status, - remoteIp: '192.168.1.66', - userAgent: 'OperationAuditDemo/1.0 (Playground)' - }; - - state.logs.unshift(record); - state.highlightId = record.id; - setTimeout(function () { state.highlightId = null; }, 3000); - - // 重置筛选与页码,确保新记录可见(同时恢复筛选控件的显示值) - clearFilters(); - if (state.tab !== 'logs') switchTab('logs'); - renderAll(); - - closeModal(); - toast('已捕获并记录审计日志:' + record.resourceType + (record.resourceName ? ' / ' + record.resourceName : ''), 'ok'); + // ---------- 模拟操作 ---------- + function switchSimTab(tab) { + state.simTab = tab; + $$('#sim-tabs .seg-tab').forEach(function (btn) { + btn.classList.toggle('active', btn.getAttribute('data-sim-tab') === tab); + }); + $('#sim-http-fields').hidden = tab !== 'http'; + $('#sim-system-fields').hidden = tab !== 'system'; + $('#sim-send').textContent = tab === 'system' ? '写入系统变更' : '发送请求'; } function openModal() { $('#modal').hidden = false; $('#modal-overlay').hidden = false; + state.simPrevious = null; + switchSimTab('http'); $('#sim-path').focus(); } @@ -309,131 +564,413 @@ $('#modal-overlay').hidden = true; } - // ---------- 事件绑定 ---------- + function readJson(text, label) { + var trimmed = String(text || '').trim(); + if (!trimmed) { + return { ok: true, value: null }; + } + try { + return { ok: true, value: JSON.parse(trimmed) }; + } catch (e) { + toast(label + ' 不是合法 JSON:' + e.message, 'warn'); + return { ok: false }; + } + } + + function sendHttpSimulation() { + if (!state.settings.enabled) { + toast('审计开关已关闭,本次操作未记录', 'warn'); + closeModal(); + return; + } + var user = $('#sim-user').value; + var method = C.normalizeMethod($('#sim-method').value); + var path = String($('#sim-path').value || '').trim(); + var status = parseInt($('#sim-status').value, 10); + var location = String($('#sim-location').value || '').trim(); + var attempted = String($('#sim-attempted').value || '').trim(); + if (!path) { + toast('请填写请求路径', 'warn'); + return; + } + + var authenticated = user !== '__anon__'; + var rule = C.shouldCapture({ method: method, path: path, authenticated: authenticated }); + if (!rule.captured) { + toast('未记录:' + rule.reason, 'warn'); + closeModal(); + return; + } + + var bodyResult = readJson($('#sim-body').value, '请求体'); + if (!bodyResult.ok) { + return; + } + + var fullPath = C.pathWithoutQuery(path); + var previous = state.simPrevious || state.snapshots[fullPath] || snapshotFor(path); + var record = C.buildRecord({ + method: method, + path: path, + username: authenticated ? user : 'unknown', + authenticated: authenticated, + statusCode: status, + location: location, + attemptedUsername: attempted || null, + body: bodyResult.value, + previous: previous, + recordChanges: state.settings.recordChanges, + remoteIp: authenticated ? '192.168.1.66' : '203.0.113.9', + userAgent: authenticated + ? 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) OperationAuditDemo/2.0' + : 'python-requests/2.31.0' + }); + + state.logs.unshift(record); + state.highlightId = record.id; + setTimeout(function () { state.highlightId = null; }, 3000); + + // 登录尝试回调告警服务(独立于审计记录):成功清零、失败累计、达阈值告警 + var login = C.classifyLogin({ method: method, path: path, statusCode: status, location: location }); + if (login.attempt) { + var alert = state.alertTracker.record({ + success: !login.failure, + remoteIp: record.remoteIp, + userAgent: record.userAgent, + attemptedUsername: attempted || null + }); + if (alert) { + showAlert(alert); + } + } + + if (record.statusCode >= 200 && record.statusCode < 300) { + rememberSnapshot(record, bodyResult.value); + } + + clearFilters(); + if (state.tab !== 'logs') { switchTab('logs'); } + renderAll(); + closeModal(); + + var message = '已记录:' + C.describeOperation(record) + + (record.changes && record.changes.length ? '(字段变更 ' + record.changes.length + ' 处)' : ''); + if (login.failure && C.describeOperation(record) !== '登录失败') { + message += ' · 登录失败'; + } + toast(message, login.failure ? 'warn' : 'ok'); + } + + function sendSystemSimulation() { + if (!state.settings.enabled) { + toast('审计开关已关闭,本次系统变更未记录', 'warn'); + closeModal(); + return; + } + if (!state.settings.recordSystemChanges) { + toast('「记录系统内部变更」已关闭,本次变更未记录', 'warn'); + closeModal(); + return; + } + var method = $('#sys-method').value; + var type = $('#sys-type').value; + var name = String($('#sys-name').value || '').trim(); + if (!name) { + toast('请填写资源名称', 'warn'); + return; + } + var parsed = readJson($('#sys-changes').value, '字段变更'); + if (!parsed.ok) { + return; + } + if (!Array.isArray(parsed.value) || !parsed.value.length) { + toast('字段变更需为非空 JSON 数组', 'warn'); + return; + } + for (var i = 0; i < parsed.value.length; i++) { + if (!parsed.value[i] || !parsed.value[i].field) { + toast('字段变更条目缺少 field', 'warn'); + return; + } + } + + var record = C.buildSystemRecord({ + method: method, + resourceType: type, + resourceName: name, + path: '/apis/content.halo.run/v1alpha1/' + type + '/' + name, + changes: parsed.value + }); + state.logs.unshift(record); + state.highlightId = record.id; + setTimeout(function () { state.highlightId = null; }, 3000); + + clearFilters(); + if (state.tab !== 'logs') { switchTab('logs'); } + renderAll(); + closeModal(); + toast('已补记系统内部变更:' + C.describeOperation(record) + '(执行者:系统)', 'ok'); + } + + // ---------- 设置动作 ---------- + function saveSettings() { + var days = parseInt($('#set-retention').value, 10); + if (isNaN(days) || days < 7) { + toast('保留天数需不小于 7 天', 'warn'); + return; + } + var threshold = parseInt($('#set-alert-threshold').value, 10); + var windowMinutes = parseInt($('#set-alert-window').value, 10); + if (isNaN(threshold) || threshold < 1 || isNaN(windowMinutes) || windowMinutes < 1) { + toast('告警阈值与统计窗口需为正整数', 'warn'); + return; + } + state.settings = { + enabled: $('#set-enabled').checked, + recordChanges: $('#set-record-changes').checked, + recordSystemChanges: $('#set-record-system').checked, + retentionDays: days + }; + state.alertSettings = { + enabled: $('#set-alert-enabled').checked, + webhookSecretName: $('#set-alert-secret').value.trim(), + thresholdCount: threshold, + windowMinutes: windowMinutes + }; + rebuildAlertTracker(); + renderAll(); + toast('设置已保存(Demo 模拟 ConfigMap 写入,真实插件 60s TTL 生效)', 'ok'); + } + + function testAlert() { + // 按当前表单值生成预览(真实插件读取已保存的 Secret;演示页不发起网络请求) + var secretName = $('#set-alert-secret').value.trim(); + if (!secretName) { + toast('请先填写存放 Webhook 地址的 Secret 引用', 'warn'); + return; + } + var enabled = $('#set-alert-enabled').checked; + var threshold = parseInt($('#set-alert-threshold').value, 10); + var windowMinutes = parseInt($('#set-alert-window').value, 10); + if (isNaN(threshold) || threshold < 1 || isNaN(windowMinutes) || windowMinutes < 1) { + toast('告警阈值与统计窗口需为正整数', 'warn'); + return; + } + if (!enabled) { + toast('登录失败告警当前未启用;测试仍可验证 Webhook 配置', 'warn'); + } + var payload = { + failures: threshold, + windowMinutes: windowMinutes, + remoteIp: '203.0.113.66', + userAgent: 'python-requests/2.31.0', + attemptedUsername: 'admin', + timestamp: new Date().toISOString() + }; + var json = C.alertPayload(payload, 'test'); + var output = $('#alert-test-output'); + output.hidden = false; + output.textContent = JSON.stringify(json, null, 2); + toast('测试告警已生成(演示页不发起真实网络请求)', 'ok'); + } + + function simulateAlertBurst() { + if (!state.alertSettings.enabled) { + toast('请先开启「登录失败告警」并保存设置', 'warn'); + return; + } + var threshold = state.alertSettings.thresholdCount; + var alert = null; + for (var i = 0; i < threshold; i++) { + var record = C.buildRecord({ + method: 'POST', + path: '/login', + statusCode: 302, + location: '/login?error=invalid-credential&method=form', + attemptedUsername: 'admin', + remoteIp: '203.0.113.66', + userAgent: 'python-requests/2.31.0', + timestamp: new Date(Date.now() - (threshold - i) * 1000).toISOString() + }); + state.logs.unshift(record); + var result = state.alertTracker.record({ + success: false, + remoteIp: record.remoteIp, + userAgent: record.userAgent, + attemptedUsername: 'admin' + }); + if (result) { + alert = result; + } + } + if (alert) { + showAlert(alert); + } + clearFilters(); + renderAll(); + toast(alert + ? '已模拟 ' + threshold + ' 次登录失败并触发告警' + : '已模拟 ' + threshold + ' 次登录失败,未达到当前阈值', alert ? 'warn' : 'ok'); + } + + function runCleanup() { + var cutoff = Date.now() - state.settings.retentionDays * 86400000; + var before = state.logs.length; + state.logs = state.logs.filter(function (log) { + return new Date(log.timestamp).getTime() >= cutoff; + }); + var removed = before - state.logs.length; + state.page = 1; + renderAll(); + toast(removed > 0 ? '清理完成:已删除 ' + removed + ' 条过期记录' : '没有需要清理的过期记录', 'ok'); + } + + // ---------- 事件 ---------- function switchTab(tab) { state.tab = tab; renderTabs(); } - function clearFilters() { - state.filters = Object.assign({}, DEFAULT_FILTERS); - $('#f-operator').value = ''; - $('#f-type').value = ''; - $('#f-method').value = ''; - $('#f-result').value = ''; - $('#f-time').value = 'all'; - $('#f-keyword').value = ''; + function applyFiltersAndRender() { + readFilterInputs(); state.page = 1; renderTable(); } + function clearFilters() { + state.filters = Object.assign({}, DEFAULT_FILTERS); + state.page = 1; + syncFilterInputs(); + renderTable(); + } + function bindEvents() { - // 侧边栏占位项 - document.querySelectorAll('[data-demo]').forEach(function (el) { + $$('[data-demo]').forEach(function (el) { el.addEventListener('click', function (e) { e.preventDefault(); - toast('Demo 演示:此页面为 Halo Console 既有页面,未实现'); + toast('演示页:此页面为 Halo Console 既有页面,未实现'); }); }); - // Tab 切换 - document.querySelectorAll('.tab').forEach(function (t) { - t.addEventListener('click', function () { switchTab(t.getAttribute('data-tab')); }); + $('#nav-audit').addEventListener('click', function (e) { + e.preventDefault(); + switchTab('logs'); }); - // 筛选 - $('#f-operator').addEventListener('change', function (e) { - state.filters.operator = e.target.value; state.page = 1; renderTable(); + $$('.tab').forEach(function (tab) { + tab.addEventListener('click', function () { switchTab(tab.getAttribute('data-tab')); }); }); - $('#f-type').addEventListener('change', function (e) { - state.filters.resourceType = e.target.value; state.page = 1; renderTable(); + + // 筛选:下拉即时生效,文本/时间用「查询」或回车 + ['#f-type', '#f-method', '#f-action', '#f-result'].forEach(function (sel) { + $(sel).addEventListener('change', applyFiltersAndRender); }); - $('#f-method').addEventListener('change', function (e) { - state.filters.method = e.target.value; state.page = 1; renderTable(); + ['#f-start', '#f-end'].forEach(function (sel) { + $(sel).addEventListener('change', applyFiltersAndRender); }); - $('#f-result').addEventListener('change', function (e) { - state.filters.result = e.target.value; state.page = 1; renderTable(); - }); - $('#f-time').addEventListener('change', function (e) { - state.filters.timeRange = e.target.value; state.page = 1; renderTable(); - }); - $('#f-keyword').addEventListener('input', function (e) { - state.filters.keyword = e.target.value; state.page = 1; renderTable(); + ['#f-operator', '#f-keyword'].forEach(function (sel) { + $(sel).addEventListener('keydown', function (e) { + if (e.key === 'Enter') { applyFiltersAndRender(); } + }); }); + $('#btn-apply').addEventListener('click', applyFiltersAndRender); + $('#btn-reset').addEventListener('click', clearFilters); $('#btn-clear').addEventListener('click', clearFilters); // 分页 $('#pg-size').addEventListener('change', function (e) { - state.size = parseInt(e.target.value, 10); state.page = 1; renderTable(); + state.size = parseInt(e.target.value, 10); + state.page = 1; + renderTable(); + }); + $('#pg-prev').addEventListener('click', function () { + state.page -= 1; + renderTable(); + }); + $('#pg-next').addEventListener('click', function () { + state.page += 1; + renderTable(); }); - $('#pg-prev').addEventListener('click', function () { state.page--; renderTable(); }); - $('#pg-next').addEventListener('click', function () { state.page++; renderTable(); }); - // 详情抽屉 + // 顶栏 + $('#btn-export').addEventListener('click', exportLogs); + $('#btn-refresh').addEventListener('click', function () { + readFilterInputs(); + renderAll(); + toast('已按当前筛选刷新(演示数据未变化)', 'ok'); + }); + $('#btn-simulate').addEventListener('click', openModal); + + // 告警横幅 + $('#alert-banner-close').addEventListener('click', function () { + $('#alert-banner').hidden = true; + state.lastAlert = null; + }); + $('#alert-banner-view').addEventListener('click', function () { + state.filters = Object.assign({}, DEFAULT_FILTERS, { result: 'failure' }); + state.page = 1; + syncFilterInputs(); + switchTab('logs'); + renderTable(); + }); + + // 详情 $('#drawer-overlay').addEventListener('click', closeDetail); // 设置 - $('#btn-save-settings').addEventListener('click', function () { - var days = parseInt($('#set-retention').value, 10); - if (isNaN(days) || days < 7 || days > 365) { - toast('保留天数需在 7 ~ 365 之间', 'warn'); - return; - } - state.settings.enabled = $('#set-enabled').checked; - state.settings.retentionDays = days; - renderAll(); - toast('设置已保存(Demo 模拟,对应 ConfigMap 写入)', 'ok'); - }); - $('#set-retention').addEventListener('input', function (e) { - var days = parseInt(e.target.value, 10); - if (!isNaN(days) && days >= 7 && days <= 365) { - state.settings.retentionDays = days; - renderSettings(); - } - }); - $('#btn-clean').addEventListener('click', function () { - var before = state.logs.length; - var cutoff = Date.now() - state.settings.retentionDays * 86400 * 1000; - state.logs = state.logs.filter(function (l) { - return new Date(l.timestamp).getTime() >= cutoff; - }); - var removed = before - state.logs.length; - state.page = 1; - renderAll(); - toast(removed > 0 ? '清理完成:已删除 ' + removed + ' 条过期记录' : '没有需要清理的过期记录', 'ok'); - }); + $('#btn-save-settings').addEventListener('click', saveSettings); + $('#btn-test-alert').addEventListener('click', testAlert); + $('#btn-simulate-alert').addEventListener('click', simulateAlertBurst); + $('#btn-clean').addEventListener('click', runCleanup); - // 模拟操作 - $('#btn-simulate').addEventListener('click', openModal); + // 模拟器 $('#modal-close').addEventListener('click', closeModal); $('#sim-cancel').addEventListener('click', closeModal); $('#modal-overlay').addEventListener('click', closeModal); - $('#sim-send').addEventListener('click', simulateSend); - $('#sim-path').addEventListener('keydown', function (e) { - if (e.key === 'Enter') simulateSend(); + $('#sim-send').addEventListener('click', function () { + if (state.simTab === 'system') { sendSystemSimulation(); } else { sendHttpSimulation(); } }); - document.querySelectorAll('#modal .chip').forEach(function (chip) { + $$('#sim-tabs .seg-tab').forEach(function (btn) { + btn.addEventListener('click', function () { switchSimTab(btn.getAttribute('data-sim-tab')); }); + }); + $('#sim-path').addEventListener('keydown', function (e) { + if (e.key === 'Enter') { sendHttpSimulation(); } + }); + $$('#sim-http-fields .chip').forEach(function (chip) { chip.addEventListener('click', function () { - var p = JSON.parse(chip.getAttribute('data-preset')); - $('#sim-user').value = p.user; - $('#sim-method').value = p.method; - $('#sim-path').value = p.path; - $('#sim-status').value = String(p.status); + var preset = JSON.parse(chip.getAttribute('data-preset')); + $('#sim-user').value = preset.user || 'guichumo'; + $('#sim-method').value = preset.method || 'PUT'; + $('#sim-path').value = preset.path || ''; + $('#sim-status').value = String(preset.status || 200); + $('#sim-location').value = preset.location || ''; + $('#sim-attempted').value = preset.attempted || ''; + $('#sim-body').value = preset.body ? JSON.stringify(preset.body, null, 2) : ''; + state.simPrevious = preset.snapshot ? snapshotFor(preset.path) : null; $('#sim-path').focus(); }); }); + $$('#sim-system-fields .chip').forEach(function (chip) { + chip.addEventListener('click', function () { + var preset = JSON.parse(chip.getAttribute('data-sys-preset')); + $('#sys-method').value = preset.method; + $('#sys-type').value = preset.type; + $('#sys-name').value = preset.name; + $('#sys-changes').value = JSON.stringify(preset.changes, null, 2); + }); + }); - // Esc 关闭抽屉/弹窗 document.addEventListener('keydown', function (e) { - if (e.key === 'Escape') { - if (!$('#modal').hidden) closeModal(); - else if (!$('#drawer').hidden) closeDetail(); - } + if (e.key !== 'Escape') { return; } + if (!$('#modal').hidden) { closeModal(); } + else if (!$('#drawer').hidden) { closeDetail(); } }); } // ---------- 启动 ---------- state.logs = MockData.generateLogs(); + rebuildAlertTracker(); + renderFilterOptions(); bindEvents(); renderAll(); })(); diff --git a/demo/assets/audit-core.js b/demo/assets/audit-core.js index f4723ce..e134987 100644 --- a/demo/assets/audit-core.js +++ b/demo/assets/audit-core.js @@ -1,11 +1,15 @@ /** * 操作审计 · 核心纯函数(浏览器与 Node 测试共用) * - * 对应文档: - * - 技术方案 D1 捕获规则(shouldCapture) - * - 技术方案 5.2 资源解析规则(resolveResource) - * - 产品设计 4.2 筛选维度(applyFilters) - * - 技术方案 D5 保留期清理(countExpired) + * 与插件当前实现保持一致(单一事实来源:后端 Java 与 Console UI 的同名逻辑): + * - 捕获规则(CaptureRule / AuthEndpointAuditWebFilter) + * - 资源解析(ResourceResolver) + * - 语义动作标注与中文描述(OperationDescription / ui/src/utils/audit.ts) + * - 登录结果判定(LoginOutcome:表单登录成败均为 302,以重定向目标 error 参数区分) + * - 字段级变更 diff(ChangeDiffEngine:PUT/PATCH/POST/DELETE 语义、脱敏、截断、封顶) + * - 查询筛选(AuditLogFilters:八维筛选 + 登录失败结果语义) + * - CSV 导出(AuditLogCsvExporter:BOM、列顺序、公式注入防护) + * - 登录失败告警(LoginFailureAlertService:阈值窗口、告警后窗口重开、成功后清零) * * 本文件不依赖任何 DOM / 网络能力,仅做纯计算,便于单元测试。 */ @@ -19,99 +23,909 @@ 'use strict'; var WRITE_METHODS = ['POST', 'PUT', 'DELETE', 'PATCH']; - var AUTH_PATHS = ['/login', '/logout']; + var AUTH_ENDPOINTS = ['/login', '/logout']; + var LOGIN_FAILURE_ACTION = 'login-failure'; + + /** 资源类型(与 AuditLogList.vue 的筛选下拉一致) */ + var RESOURCE_TYPES = [ + 'posts', 'singlepages', 'comments', 'replies', 'users', 'roles', 'auth', + 'settings', 'configmaps', 'plugins', 'themes', 'attachments', 'menus', + 'categories', 'tags' + ]; + + /** 资源类型的中文展示名(描述用;未知类型回退原始值)。 */ + var RESOURCE_LABELS = { + posts: '文章', + singlepages: '页面', + comments: '评论', + replies: '回复', + users: '用户', + roles: '角色', + settings: '设置', + configmaps: '配置', + plugins: '插件', + themes: '主题', + attachments: '附件', + menus: '菜单', + categories: '分类', + tags: '标签' + }; + + /** 动作方法的基础动词(未知方法回退原始值)。 */ + var METHOD_VERBS = { POST: '新建', PUT: '修改', PATCH: '修改', DELETE: '删除', GET: '查看' }; + + /** 动作方法 → 语义动作键。 */ + var METHOD_ACTIONS = { POST: 'create', PUT: 'update', PATCH: 'update', DELETE: 'delete', GET: 'view' }; + + /** 子资源动作段 → 语义动作键(activation 与 enable 归并)。 */ + var SEGMENT_ACTIONS = { + publish: 'publish', + unpublish: 'unpublish', + recycle: 'recycle', + restore: 'restore', + enable: 'enable', + activation: 'enable', + disable: 'disable', + upgrade: 'upgrade', + uninstall: 'uninstall', + reload: 'reload', + reply: 'reply', + recalculate: 'recalculate', + password: 'password', + resetpassword: 'resetpassword' + }; + + /** 语义动作键 → 完整短语(不拼资源名)。 */ + var ACTION_PHRASES = { + login: '登录', + 'login-failure': '登录失败', + logout: '登出', + auth: '认证操作', + password: '修改密码', + resetpassword: '重置密码' + }; + + /** 语义动作键 → 动词(与资源中文名拼接,如 publish + 文章 = 发布文章)。 */ + var ACTION_VERBS = { + create: '新建', + update: '修改', + delete: '删除', + view: '查看', + publish: '发布', + unpublish: '取消发布', + recycle: '移入回收站', + restore: '恢复', + enable: '启用', + disable: '停用', + upgrade: '升级', + uninstall: '卸载', + reload: '重载', + reply: '回复', + recalculate: '重新统计' + }; + + /** 语义动作筛选选项(view 不会被捕获,不列入)。 */ + var SEMANTIC_ACTIONS = [ + { value: 'login', label: '登录' }, + { value: 'login-failure', label: '登录失败' }, + { value: 'logout', label: '登出' }, + { value: 'auth', label: '认证操作' }, + { value: 'create', label: '新建' }, + { value: 'update', label: '修改' }, + { value: 'delete', label: '删除' }, + { value: 'publish', label: '发布' }, + { value: 'unpublish', label: '取消发布' }, + { value: 'recycle', label: '移入回收站' }, + { value: 'restore', label: '恢复' }, + { value: 'enable', label: '启用' }, + { value: 'disable', label: '停用' }, + { value: 'upgrade', label: '升级' }, + { value: 'uninstall', label: '卸载' }, + { value: 'reload', label: '重载' }, + { value: 'reply', label: '回复' }, + { value: 'recalculate', label: '重新统计' }, + { value: 'password', label: '修改密码' }, + { value: 'resetpassword', label: '重置密码' } + ]; + + var CHANGE_TYPE_LABELS = { ADDED: '新增', UPDATED: '修改', REMOVED: '删除' }; + var MAX_CHANGES = 30; + var MAX_VALUE_LENGTH = 200; + var REDACTED_VALUE = '******'; + var TRUNCATION_SUFFIX = '…(截断)'; + var OVERFLOW_FIELD = '…'; + var ROOT_SKIPPED_KEYS = ['apiVersion', 'kind', 'status']; + var METADATA_INCLUDED_KEYS = ['name', 'labels', 'annotations']; + var SENSITIVE_FIELD = /password|passwd|secret|token|credential/i; + + // ---------------------------------------------------------------- 基础工具 function normalizeMethod(method) { return String(method || '').trim().toUpperCase(); } + function pathWithoutQuery(path) { + var p = String(path || '').trim(); + var idx = p.indexOf('?'); + return idx >= 0 ? p.slice(0, idx) : p; + } + + /** 查询串是否含 error 参数(可为无值形式 error)。 */ + function hasErrorParam(fullPath) { + var p = String(fullPath || ''); + var idx = p.indexOf('?'); + if (idx < 0) { + return false; + } + return p.slice(idx + 1).split('&').some(function (pair) { + var eq = pair.indexOf('='); + return (eq < 0 ? pair : pair.slice(0, eq)) === 'error'; + }); + } + + function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); + } + + function deepEqual(a, b) { + if (a === b) { + return true; + } + if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') { + return false; + } + var aArr = Array.isArray(a); + if (aArr !== Array.isArray(b)) { + return false; + } + if (aArr) { + if (a.length !== b.length) { + return false; + } + for (var i = 0; i < a.length; i++) { + if (!deepEqual(a[i], b[i])) { + return false; + } + } + return true; + } + var ka = Object.keys(a); + var kb = Object.keys(b); + if (ka.length !== kb.length) { + return false; + } + return ka.every(function (key) { + return Object.prototype.hasOwnProperty.call(b, key) && deepEqual(a[key], b[key]); + }); + } + + // ---------------------------------------------------------------- 捕获与解析 + /** - * 捕获规则(技术方案 D1): - * - /apis/** 下已登录用户的写操作(POST/PUT/DELETE/PATCH) - * - 或路径精确匹配 /login、/logout(登录事件始终记录,即使匿名) - * - /apis/** 下认证后仍为匿名主体的请求不记录(401/403 场景) + * 捕获规则(CaptureRule + AuthEndpointAuditWebFilter): + * - /apis/** 下已登录用户的写操作(POST/PUT/DELETE/PATCH); + * - /login、/logout 认证端点始终记录(链首过滤器捕获,含登录失败与失败回显); + * - /apis/** 下认证后仍为匿名主体的请求不记录(401/403 场景)。 * * @param {{method: string, path: string, authenticated: boolean}} options - * @returns {{captured: boolean, reason: string}} reason 用于 Demo 中向用户解释判定依据 + * @returns {{captured: boolean, channel: 'auth'|'http'|'none', reason: string}} */ function shouldCapture(options) { var method = normalizeMethod(options && options.method); - var path = String((options && options.path) || '').trim(); + var fullPath = String((options && options.path) || '').trim(); + var clean = pathWithoutQuery(fullPath); var authenticated = !!(options && options.authenticated); - if (AUTH_PATHS.indexOf(path) !== -1) { - return { captured: true, reason: '登录/登出事件,始终记录' }; + if (AUTH_ENDPOINTS.indexOf(clean) !== -1) { + return { + captured: true, + channel: 'auth', + reason: '认证端点始终记录(登录/登出,含登录失败与失败回显)' + }; } - if (path.indexOf('/apis/') !== 0) { - return { captured: false, reason: '路径不在捕获范围(仅 /apis/** 与 /login、/logout)' }; + if (clean.indexOf('/apis/') !== 0) { + return { + captured: false, + channel: 'none', + reason: '路径不在捕获范围(仅 /apis/** 写操作与 /login、/logout)' + }; } if (!authenticated) { - return { captured: false, reason: '匿名请求不记录(认证后仍为匿名主体的 401/403 场景)' }; + return { + captured: false, + channel: 'none', + reason: '匿名请求不记录(认证后仍为匿名主体的 401/403 场景)' + }; } if (WRITE_METHODS.indexOf(method) === -1) { - return { captured: false, reason: '仅记录写操作(POST/PUT/DELETE/PATCH),读操作不记录' }; + return { + captured: false, + channel: 'none', + reason: '仅记录写操作(POST/PUT/DELETE/PATCH),读操作不记录' + }; } - return { captured: true, reason: '已登录用户对 /apis/** 的写操作,予以记录' }; + return { + captured: true, + channel: 'http', + reason: '已登录用户对 /apis/** 的写操作,予以记录' + }; } /** - * 资源解析(技术方案 5.2,通用规则,不追求语义完美): - * /apis/{group}/{version}/{plural} → resourceType = plural,resourceName 为空 - * /apis/{group}/{version}/{plural}/{name} → resourceType = plural,resourceName = name - * 更深层子资源 → 取前两段(完整路径由 path 字段兜底) - * /login、/logout → resourceType = "auth" - * 其他 → resourceType = "other" + * 资源解析(ResourceResolver): + * /apis/{group}/{version}/{plural}[/{name}][/...] → plural / name + * /login、/logout → auth;其余 → other。 */ function resolveResource(path) { - var p = String(path || '').trim(); - if (AUTH_PATHS.indexOf(p) !== -1) { - return { resourceType: 'auth', resourceName: '' }; + var clean = pathWithoutQuery(path); + if (AUTH_ENDPOINTS.indexOf(clean) !== -1) { + return { resourceType: 'auth', resourceName: null }; } - if (p.indexOf('/apis/') !== 0) { - return { resourceType: 'other', resourceName: '' }; + if (clean.indexOf('/apis/') !== 0) { + return { resourceType: 'other', resourceName: null }; } - // segs[0]='apis',segs[1]=group,segs[2]=version,segs[3]=plural,segs[4]=name - var segs = p.split('/').filter(function (s) { return s.length > 0; }); + var segs = clean.split('/').filter(function (s) { return s.length > 0; }); + // segs: [apis, group, version, plural, name, ...] if (segs.length < 4) { - return { resourceType: 'other', resourceName: '' }; + return { resourceType: 'other', resourceName: null }; } - return { resourceType: segs[3], resourceName: segs[4] || '' }; + return { resourceType: segs[3], resourceName: segs.length >= 5 && segs[4] ? segs[4] : null }; } - /** 结果判定:2xx/3xx 视为成功 */ - function isSuccess(statusCode) { - return statusCode > 0 && statusCode < 400; + /** 推导语义动作键(与 OperationDescription.actionOf / deriveAction 一致)。 */ + function deriveAction(method, resourceType, path) { + var clean = pathWithoutQuery(path); + if (clean === '/login') { + return hasErrorParam(path) ? LOGIN_FAILURE_ACTION : 'login'; + } + if (clean === '/logout') { + return 'logout'; + } + if (resourceType === 'auth') { + return 'auth'; + } + var segments = clean.split('/').filter(Boolean); + if (segments.length >= 6) { + var action = SEGMENT_ACTIONS[segments[5].toLowerCase()]; + if (action) { + return action; + } + } + return METHOD_ACTIONS[normalizeMethod(method)] || null; + } + + /** 由语义动作键推导中文短语;未识别返回 null(调用方回退 method 推导)。 */ + function describeFromAction(action, resourceType) { + if (!action) { + return null; + } + var phrase = ACTION_PHRASES[action]; + if (phrase) { + return phrase; + } + var verb = ACTION_VERBS[action]; + return verb ? verb + (RESOURCE_LABELS[resourceType] || resourceType) : null; + } + + /** 操作中文描述(优先落库语义动作,历史记录现场推导)。 */ + function describeOperation(spec) { + spec = spec || {}; + var action = spec.action || deriveAction(spec.method, spec.resourceType, spec.path); + var fromAction = describeFromAction(action, spec.resourceType); + if (fromAction) { + return fromAction; + } + var label = RESOURCE_LABELS[spec.resourceType] || spec.resourceType; + var verb = METHOD_VERBS[normalizeMethod(spec.method)] || spec.method; + return verb + label; + } + + /** 结果语义:2xx/3xx 成功。 */ + function isSuccessful(statusCode) { + return statusCode != null && statusCode >= 200 && statusCode < 400; + } + + /** 是否为登录失败记录(优先落库标注,回退路径推导)。 */ + function isLoginFailure(spec) { + spec = spec || {}; + var action = spec.action || deriveAction(spec.method, spec.resourceType, spec.path); + return action === LOGIN_FAILURE_ACTION; } /** - * 筛选(产品设计 4.2 + 动作维度):按操作者、资源类型、动作、结果、时间范围; - * keyword 对资源名称/路径模糊匹配。 - * 返回按时间倒序的新数组,不修改入参。 - * - * @param {Array} logs - * @param {{operator?: string, resourceType?: string, method?: string, result?: 'success'|'failure'|'', - * timeRange?: '24h'|'7d'|'30d'|'all', keyword?: string, now?: number}} f + * 结果徽标:登录失败(HTTP 可能为 200/302)显示「失败」, + * 其余按状态码(2xx/3xx 绿、其余红)。 */ - function applyFilters(logs, f) { - f = f || {}; - var now = typeof f.now === 'number' ? f.now : Date.now(); - var keyword = String(f.keyword || '').trim().toLowerCase(); - var method = normalizeMethod(f.method); - var cutoff = null; - if (f.timeRange === '24h') cutoff = now - 24 * 3600 * 1000; - else if (f.timeRange === '7d') cutoff = now - 7 * 86400 * 1000; - else if (f.timeRange === '30d') cutoff = now - 30 * 86400 * 1000; + function resultBadge(spec) { + if (isLoginFailure(spec)) { + return { text: '失败', class: 'status-fail' }; + } + return { + text: String(spec && spec.statusCode), + class: isSuccessful(spec && spec.statusCode) ? 'status-ok' : 'status-fail' + }; + } + + /** 展示用操作者名:unknown → 未知用户,system → 系统。 */ + function displayUsername(username) { + if (!username || username === 'unknown') { + return '未知用户'; + } + if (username === 'system') { + return '系统'; + } + return username; + } + + function pad2(n) { + return n < 10 ? '0' + n : String(n); + } + + /** 本地时区 YYYY-MM-DD HH:mm:ss(与界面/导出一致)。 */ + function formatTime(iso) { + if (!iso) { + return ''; + } + var d = new Date(iso); + if (isNaN(d.getTime())) { + return String(iso); + } + return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()) + + ' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes()) + ':' + pad2(d.getSeconds()); + } + + // ---------------------------------------------------------------- 登录结果判定 + + /** + * 登录结果判定(LoginOutcome): + * - POST /login:2xx 成功;3xx 看重定向目标是否含 error 参数;其余失败; + * - GET /login?error=...:登录失败回显(HTTP 200 但语义为失败); + * - 其他请求不算登录尝试。 + * + * @returns {{attempt: boolean, failure: boolean, echo: boolean}} + */ + function classifyLogin(input) { + input = input || {}; + var method = normalizeMethod(input.method); + var fullPath = String(input.path || ''); + var clean = pathWithoutQuery(fullPath); + var attempt = method === 'POST' && clean === '/login'; + var echo = method === 'GET' && clean === '/login' && hasErrorParam(fullPath); + + if (attempt) { + var status = input.statusCode; + var failure; + if (status == null) { + failure = true; + } else if (status >= 200 && status < 300) { + failure = false; + } else if (status >= 300 && status < 400) { + failure = hasErrorParam(input.location); + } else { + failure = true; + } + return { attempt: true, failure: failure, echo: false }; + } + return { attempt: false, failure: echo, echo: echo }; + } + + // ---------------------------------------------------------------- 字段级变更 diff + + /** 字段路径任一段命中敏感片段即脱敏(与 ChangeDiffEngine.isSensitiveField 一致)。 */ + function isSensitiveField(field) { + return String(field || '').split('.').some(function (segment) { + return SENSITIVE_FIELD.test(segment); + }); + } + + /** 单值格式化:脱敏、对象/数组紧凑 JSON、200 字符截断。 */ + function formatValue(value, sensitive) { + if (value === undefined || value === null) { + return null; + } + if (sensitive) { + return REDACTED_VALUE; + } + var text; + if (typeof value === 'string') { + text = value; + } else if (typeof value === 'number' || typeof value === 'boolean') { + text = String(value); + } else { + text = JSON.stringify(value); + } + if (text.length > MAX_VALUE_LENGTH) { + text = text.slice(0, MAX_VALUE_LENGTH) + TRUNCATION_SUFFIX; + } + return text; + } + + function addEntry(out, field, changeType, oldValue, newValue) { + var resolvedField = field || '(请求体)'; + var sensitive = isSensitiveField(resolvedField); + out.push({ + field: resolvedField, + changeType: changeType, + oldValue: formatValue(oldValue, sensitive), + newValue: formatValue(newValue, sensitive) + }); + } + + function filterMetadata(node) { + if (!isPlainObject(node)) { + return node; + } + var out = {}; + METADATA_INCLUDED_KEYS.forEach(function (key) { + if (Object.prototype.hasOwnProperty.call(node, key)) { + out[key] = node[key]; + } + }); + return out; + } + + function expandAdded(path, node, depth, out) { + if (!isPlainObject(node) || depth >= 16) { + addEntry(out, path, 'ADDED', null, node); + return; + } + Object.keys(node).forEach(function (key) { + if (!path && ROOT_SKIPPED_KEYS.indexOf(key) !== -1) { + return; + } + var childPath = path ? path + '.' + key : key; + var value = node[key]; + if (value === null || value === undefined) { + return; + } + if (!path && key === 'metadata') { + value = filterMetadata(value); + } + expandAdded(childPath, value, depth + 1, out); + }); + } + + function expandRemoved(path, node, depth, out) { + if (!isPlainObject(node) || depth >= 16) { + addEntry(out, path, 'REMOVED', node, null); + return; + } + Object.keys(node).forEach(function (key) { + if (!path && ROOT_SKIPPED_KEYS.indexOf(key) !== -1) { + return; + } + var childPath = path ? path + '.' + key : key; + var value = node[key]; + if (value === null || value === undefined) { + return; + } + if (!path && key === 'metadata') { + value = filterMetadata(value); + } + expandRemoved(childPath, value, depth + 1, out); + }); + } + + function collectObjectDiff(path, oldObj, newObj, removals, depth, out) { + var keys = Object.keys(newObj); + Object.keys(oldObj).forEach(function (key) { + if (keys.indexOf(key) === -1) { + keys.push(key); + } + }); + keys.forEach(function (key) { + if (!path && ROOT_SKIPPED_KEYS.indexOf(key) !== -1) { + return; + } + var childPath = path ? path + '.' + key : key; + var oldValue = oldObj[key]; + var newValue = newObj[key]; + + if (oldValue === undefined && newValue === undefined) { + return; + } + if (oldValue === undefined) { + if (newValue === null) { + return; + } + expandAdded(childPath, newValue, depth + 1, out); + return; + } + if (newValue === undefined) { + if (!removals || oldValue === null) { + return; + } + expandRemoved(childPath, oldValue, depth + 1, out); + return; + } + if (newValue === null || oldValue === null) { + if (oldValue === null && newValue === null) { + return; + } + if (newValue === null) { + if (removals) { + addEntry(out, childPath, 'UPDATED', oldValue, null); + } else { + addEntry(out, childPath, 'REMOVED', oldValue, null); + } + return; + } + expandAdded(childPath, newValue, depth + 1, out); + return; + } + if (isPlainObject(oldValue) && isPlainObject(newValue)) { + var ov = oldValue; + var nv = newValue; + if (!path && key === 'metadata') { + ov = filterMetadata(ov); + nv = filterMetadata(nv); + } + collectValueDiff(childPath, ov, nv, removals, depth + 1, out); + return; + } + if (!deepEqual(oldValue, newValue)) { + addEntry(out, childPath, 'UPDATED', oldValue, newValue); + } + }); + } + + function collectValueDiff(path, oldValue, newValue, removals, depth, out) { + var oldContainer = isPlainObject(oldValue) || oldValue === undefined; + var newContainer = isPlainObject(newValue) || newValue === undefined; + if (depth < 16 && oldContainer && newContainer) { + collectObjectDiff(path, oldValue || {}, newValue || {}, removals, depth, out); + return; + } + if (deepEqual(oldValue, newValue)) { + return; + } + if (oldValue === undefined) { + addEntry(out, path, 'ADDED', null, newValue); + return; + } + if (newValue === undefined) { + if (removals) { + addEntry(out, path, 'REMOVED', oldValue, null); + } + return; + } + addEntry(out, path, 'UPDATED', oldValue, newValue); + } + + /** JSON Pointer(/spec/title,含 ~0/~1 转义)→ 字段路径(spec.title)。 */ + function pointerToField(pointer) { + if (!pointer) { + return ''; + } + return pointer.slice(1).split('/').map(function (segment) { + return segment.replace(/~1/g, '/').replace(/~0/g, '~'); + }).join('.'); + } + + /** 按 JSON Pointer 取旧值;不存在返回 undefined。 */ + function valueAtPointer(node, pointer) { + if (!pointer) { + return node; + } + var current = node; + var segments = pointer.slice(1).split('/'); + for (var i = 0; i < segments.length; i++) { + var key = segments[i].replace(/~1/g, '/').replace(/~0/g, '~'); + if (current == null || typeof current !== 'object') { + return undefined; + } + if (!Object.prototype.hasOwnProperty.call(current, key)) { + return undefined; + } + current = current[key]; + } + return current; + } + + function capChanges(changes) { + if (changes.length <= MAX_CHANGES) { + return changes; + } + var capped = changes.slice(0, MAX_CHANGES); + capped.push({ + field: OVERFLOW_FIELD, + changeType: 'UPDATED', + oldValue: null, + newValue: '变更过多,仅记录前 ' + MAX_CHANGES + ' 处(共 ' + changes.length + ' 处)' + }); + return capped; + } + + function jsonPatchEntries(oldNode, patchOps) { + var out = []; + patchOps.forEach(function (op) { + if (!op || typeof op !== 'object') { + return; + } + var pointer = String(op.path || ''); + var field = pointer ? pointerToField(pointer) : '(请求体)'; + var oldValue = valueAtPointer(oldNode, pointer); + if (op.op === 'replace' || op.op === 'add') { + addEntry(out, field, oldValue === undefined ? 'ADDED' : 'UPDATED', oldValue, op.value); + } else if (op.op === 'remove') { + if (oldValue !== undefined) { + addEntry(out, field, 'REMOVED', oldValue, null); + } + } else { + // move/copy/test 等少见操作:整条 op 落库兜底 + addEntry(out, field, 'UPDATED', null, op); + } + }); + return capChanges(out); + } + + /** + * 计算字段级变更列表(ChangeDiffEngine.compute): + * - POST:所有字段新增; + * - DELETE:所有字段删除; + * - PUT:整体替换(新增/修改/删除全量); + * - PATCH:数组 body 视为 JSON Patch(RFC 6902),对象 body 视为 Merge Patch + * (仅比较 body 中出现的字段,显式 null 视为删除)。 + * 根级跳过 apiVersion/kind/status,metadata 仅保留 name/labels/annotations。 + * + * @returns {Array|null} 无变更或无法计算返回 null + */ + function diffObjects(method, oldNode, newNode) { + var normalized = normalizeMethod(method); + var changes = null; + if (normalized === 'POST') { + changes = newNode == null ? null : []; + if (changes) { + expandAdded('', newNode, 0, changes); + } + } else if (normalized === 'DELETE') { + changes = oldNode == null ? null : []; + if (changes) { + expandRemoved('', oldNode, 0, changes); + } + } else if (normalized === 'PUT') { + if (oldNode == null || newNode == null) { + return null; + } + changes = []; + collectValueDiff('', oldNode, newNode, true, 0, changes); + } else if (normalized === 'PATCH') { + if (oldNode == null || newNode == null) { + return null; + } + if (Array.isArray(newNode)) { + return jsonPatchEntries(oldNode, newNode); + } + changes = []; + collectValueDiff('', oldNode, newNode, false, 0, changes); + } else { + return null; + } + if (!changes || changes.length === 0) { + return null; + } + return capChanges(changes); + } + + /** 变更列表的紧凑中文摘要(CSV「变更」列)。 */ + function formatChanges(changes) { + if (!changes || !changes.length) { + return ''; + } + return changes.map(function (change) { + if (change.field === OVERFLOW_FIELD) { + return change.newValue || ''; + } + var oldValue = displayValue(change.oldValue); + var newValue = displayValue(change.newValue); + if (change.changeType === 'ADDED') { + return '新增 ' + change.field + ':' + newValue; + } + if (change.changeType === 'REMOVED') { + return '删除 ' + change.field + ':' + oldValue; + } + return '修改 ' + change.field + ':' + oldValue + ' → ' + newValue; + }).join(';'); + } + + function displayValue(value) { + return value == null || value === '' ? '-' : value; + } + + function changeTypeLabel(changeType) { + return CHANGE_TYPE_LABELS[changeType] || (changeType || '修改'); + } + + /** 变更值展示:缺失一侧显示 ∅(字段不存在)。 */ + function changeValueDisplay(value) { + return value == null || value === '' ? '∅' : value; + } + + // ---------------------------------------------------------------- 记录组装 + + var idSeq = 0; + + function nextId(now) { + idSeq += 1; + return 'auditlog-' + (now != null ? now : Date.now()) + '-' + idSeq; + } + + /** + * 按真实捕获管线组装一条审计记录: + * 捕获判定之外的步骤——资源解析 → 登录结果 → 语义动作标注 → 字段 diff。 + * + * @param {object} input {method,path,username,statusCode,location,authenticated, + * attemptedUsername,body,previous,recordChanges,remoteIp,userAgent,timestamp,id} + * @returns {object} 扁平记录(演示内部形态;toWire 转为 Extension JSON) + */ + function buildRecord(input) { + input = input || {}; + var method = normalizeMethod(input.method); + var fullPath = String(input.path || ''); + var clean = pathWithoutQuery(fullPath); + var resolved = resolveResource(fullPath); + var login = classifyLogin({ + method: method, + path: fullPath, + statusCode: input.statusCode, + location: input.location + }); + var authEndpoint = AUTH_ENDPOINTS.indexOf(clean) !== -1; + // 认证端点由 Security 链首过滤器捕获,无认证上下文:操作者统一记「未知用户」, + // 登录尝试的账号由请求体白名单提取(attemptedUsername)。 + var username = authEndpoint ? 'unknown' : (input.username || 'unknown'); + var action = login.failure ? LOGIN_FAILURE_ACTION + : deriveAction(method, resolved.resourceType, fullPath); + + var changes = null; + if (!authEndpoint && input.recordChanges !== false && + input.statusCode != null && input.statusCode >= 200 && input.statusCode < 300) { + changes = diffObjects(method, input.previous, input.body); + } + + var timestamp = input.timestamp || new Date().toISOString(); + return { + id: input.id || nextId(new Date(timestamp).getTime() || Date.now()), + timestamp: timestamp, + username: username, + attemptedUsername: input.attemptedUsername || null, + method: method, + action: action, + resourceType: resolved.resourceType, + resourceName: resolved.resourceName, + path: fullPath, + statusCode: input.statusCode, + remoteIp: input.remoteIp || null, + userAgent: input.userAgent || null, + changes: changes + }; + } + + /** + * 系统内部变更记录(InternalChangeWatcher + AuditRecorder.recordSystemChange): + * 执行者 system、方法取事件类型 PUT/DELETE、状态恒 200、无 IP/UA。 + */ + function buildSystemRecord(input) { + input = input || {}; + var method = normalizeMethod(input.method || 'PUT'); + var timestamp = input.timestamp || new Date().toISOString(); + return { + id: input.id || nextId(new Date(timestamp).getTime() || Date.now()), + timestamp: timestamp, + username: 'system', + attemptedUsername: null, + method: method, + action: deriveAction(method, input.resourceType, input.path), + resourceType: input.resourceType, + resourceName: input.resourceName || null, + path: input.path || '', + statusCode: 200, + remoteIp: null, + userAgent: null, + changes: input.changes && input.changes.length ? capChanges(normalizeChanges(input.changes)) : null + }; + } + + /** 校验并规整外部传入的变更条目(只保留类型与字符串值)。 */ + function normalizeChanges(changes) { + return changes.map(function (change) { + return { + field: String(change.field || ''), + changeType: change.changeType || 'UPDATED', + oldValue: change.oldValue == null ? null : String(change.oldValue), + newValue: change.newValue == null ? null : String(change.newValue) + }; + }); + } + + /** 扁平记录 → Halo Extension JSON(详情抽屉「原始数据」展示用)。 */ + function toWire(record) { + var spec = { + username: record.username, + method: record.method, + action: record.action, + resourceType: record.resourceType, + resourceName: record.resourceName, + path: record.path, + statusCode: record.statusCode, + remoteIp: record.remoteIp, + userAgent: record.userAgent + }; + if (record.attemptedUsername) { + spec.attemptedUsername = record.attemptedUsername; + } + if (record.changes && record.changes.length) { + spec.changes = record.changes; + } + return { + apiVersion: 'audit.guichumo.com/v1alpha1', + kind: 'AuditLog', + metadata: { + name: record.id, + creationTimestamp: record.timestamp + }, + spec: spec + }; + } + + // ---------------------------------------------------------------- 查询与分页 + + function toMs(value) { + if (value == null || value === '') { + return null; + } + var ms = typeof value === 'number' ? value : new Date(value).getTime(); + return isNaN(ms) ? null : ms; + } + + /** 结果判定:success = 2xx/3xx 且非登录失败;failure = 其余。 */ + function isSuccessRecord(log) { + return !isLoginFailure(log) && isSuccessful(log && log.statusCode); + } + + /** + * 八维筛选(AuditLogFilters):操作者、资源类型、动作、语义动作、结果、 + * 关键字(资源名称/路径)、起止时间(闭区间)。返回时间倒序的新数组。 + */ + function applyFilters(logs, filters) { + filters = filters || {}; + var operator = String(filters.operator || '').trim(); + var keyword = String(filters.keyword || '').trim().toLowerCase(); + var method = normalizeMethod(filters.method); + var startCutoff = toMs(filters.startTime); + var endCutoff = toMs(filters.endTime); return logs.filter(function (log) { - if (f.operator && log.username !== f.operator) return false; - if (f.resourceType && log.resourceType !== f.resourceType) return false; - if (method && log.method !== method) return false; - if (f.result === 'success' && !isSuccess(log.statusCode)) return false; - if (f.result === 'failure' && isSuccess(log.statusCode)) return false; - if (cutoff !== null && new Date(log.timestamp).getTime() < cutoff) return false; + if (operator && log.username !== operator) { + return false; + } + if (filters.resourceType && log.resourceType !== filters.resourceType) { + return false; + } + if (method && normalizeMethod(log.method) !== method) { + return false; + } + if (filters.action && log.action !== filters.action) { + return false; + } + if (filters.result === 'success' && !isSuccessRecord(log)) { + return false; + } + if (filters.result === 'failure' && isSuccessRecord(log)) { + return false; + } + var time = new Date(log.timestamp).getTime(); + if (startCutoff !== null && time < startCutoff) { + return false; + } + if (endCutoff !== null && time > endCutoff) { + return false; + } if (keyword) { - var hay = (log.resourceName + ' ' + log.path).toLowerCase(); - if (hay.indexOf(keyword) === -1) return false; + var hay = ((log.resourceName || '') + ' ' + (log.path || '')).toLowerCase(); + if (hay.indexOf(keyword) === -1) { + return false; + } } return true; }).sort(function (a, b) { @@ -119,40 +933,217 @@ }); } - /** - * 分页(page 从 1 开始,越界自动收敛到合法页码) - * @returns {{items: Array, total: number, pages: number, page: number}} - */ + /** 分页(page 从 1 开始,越界自动收敛)。 */ function paginate(items, page, size) { var total = items.length; - var pages = Math.max(1, Math.ceil(total / size)); + var pageSize = size > 0 ? size : 20; + var pages = Math.max(1, Math.ceil(total / pageSize)); var current = Math.min(Math.max(1, page || 1), pages); - var start = (current - 1) * size; + var start = (current - 1) * pageSize; return { - items: items.slice(start, start + size), + items: items.slice(start, start + pageSize), total: total, pages: pages, page: current }; } - /** 保留期清理(技术方案 D5):统计超过保留天数的记录条数 */ + /** 保留期清理:统计超过保留天数的记录条数。 */ function countExpired(logs, retentionDays, now) { - var cutoff = now - retentionDays * 86400 * 1000; + var baseline = typeof now === 'number' ? now : Date.now(); + var cutoff = baseline - retentionDays * 86400000; return logs.filter(function (log) { return new Date(log.timestamp).getTime() < cutoff; }).length; } + // ---------------------------------------------------------------- CSV 导出 + + var CSV_HEADER = [ + '操作时间', '操作者', '尝试用户', '动作', '资源类型', '资源名称', '路径', + '操作描述', '变更', '结果', '状态码', '来源IP', 'User-Agent' + ]; + + /** + * CSV 字段转义(与 AuditLogCsvExporter.escape 一致): + * 含逗号/引号/换行加引号、内部引号翻倍;以 =、+、-、@、Tab、CR 开头 + * 加单引号前缀(公式注入防护)。 + */ + function csvEscape(value) { + if (value == null || value === '') { + return ''; + } + var text = String(value); + var first = text.charAt(0); + if (first === '=' || first === '+' || first === '-' || first === '@' || + first === '\t' || first === '\r') { + text = "'" + text; + } + if (/[",\n\r]/.test(text)) { + return '"' + text.replace(/"/g, '""') + '"'; + } + return text; + } + + /** + * 全量 CSV(UTF-8 BOM + CRLF,Excel/WPS 直开不乱码)。 + * 记录按时间升序输出(与后端导出分批遍历顺序一致)。 + */ + function toCsv(logs) { + var sorted = logs.slice().sort(function (a, b) { + return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(); + }); + var lines = [CSV_HEADER.map(csvEscape).join(',')]; + sorted.forEach(function (log) { + var badge = resultBadge(log); + lines.push([ + csvEscape(formatTime(log.timestamp)), + csvEscape(displayUsername(log.username)), + csvEscape(log.attemptedUsername), + csvEscape(log.method), + csvEscape(log.resourceType), + csvEscape(log.resourceName), + csvEscape(log.path), + csvEscape(describeOperation(log)), + csvEscape(formatChanges(log.changes)), + csvEscape(badge.text === '失败' ? '失败' : (isSuccessRecord(log) ? '成功' : '失败')), + csvEscape(log.statusCode == null ? null : String(log.statusCode)), + csvEscape(log.remoteIp), + csvEscape(log.userAgent) + ].join(',')); + }); + return '\uFEFF' + lines.join('\r\n') + '\r\n'; + } + + // ---------------------------------------------------------------- 登录失败告警 + + /** + * 创建登录失败告警追踪器(LoginFailureAlertService 的阈值窗口模型): + * - 统计窗口内失败数达到阈值 → 返回一次告警负载,并重开窗口(防轰炸); + * - 登录成功立即清零(无论是否开启告警); + * - 未开启告警时只维护清零语义,不产生负载。 + * + * @param {{enabled: boolean, thresholdCount: number, windowMinutes: number}} config + */ + function createLoginFailureTracker(config) { + config = config || {}; + var enabled = !!config.enabled; + var threshold = config.thresholdCount >= 1 ? Math.floor(config.thresholdCount) : 5; + var windowMinutes = config.windowMinutes >= 1 ? Math.floor(config.windowMinutes) : 5; + var windowMs = windowMinutes * 60000; + var count = 0; + var windowStart = null; + + return { + record: function (event) { + event = event || {}; + var now = typeof event.time === 'number' ? event.time : Date.now(); + if (event.success) { + count = 0; + windowStart = null; + return null; + } + if (!enabled) { + return null; + } + if (windowStart === null || now - windowStart > windowMs) { + count = 0; + windowStart = now; + } + count += 1; + if (count < threshold) { + return null; + } + var payload = { + failures: count, + windowMinutes: windowMinutes, + remoteIp: event.remoteIp || null, + userAgent: event.userAgent || null, + attemptedUsername: event.attemptedUsername || null, + timestamp: new Date(now).toISOString() + }; + // 告警后窗口重开:下一次告警需重新累计到阈值 + count = 0; + windowStart = now; + return payload; + }, + snapshot: function () { + return { count: count, windowStart: windowStart }; + } + }; + } + + /** + * 告警负载(通用 JSON,与插件 README 的负载结构一致)。 + * @param {'login-failure'|'test'} type + */ + function alertPayload(payload, type) { + payload = payload || {}; + var resolvedType = type === 'test' ? 'test' : 'login-failure'; + var windowMinutes = payload.windowMinutes || 5; + var timestamp = payload.timestamp || new Date().toISOString(); + var content; + if (resolvedType === 'test') { + content = '这是一条操作审计测试告警,收到即表示 Webhook 配置可用。'; + } else { + content = windowMinutes + ' 分钟内出现 ' + payload.failures + ' 次登录失败,' + + '最近一次来自 ' + (payload.remoteIp || '未知地址') + ',尝试的账号:' + + (payload.attemptedUsername || '未知') + '。可在 Console「操作审计」查看详情。'; + } + return { + type: resolvedType, + title: resolvedType === 'test' ? '操作审计测试告警' : '操作审计告警:登录失败', + content: content, + timestamp: timestamp, + data: { + failures: payload.failures != null ? payload.failures : 0, + windowMinutes: windowMinutes, + remoteIp: payload.remoteIp || null, + userAgent: payload.userAgent || null, + attemptedUsername: payload.attemptedUsername || null + } + }; + } + + // ---------------------------------------------------------------- 导出 + return { WRITE_METHODS: WRITE_METHODS, - AUTH_PATHS: AUTH_PATHS, + AUTH_ENDPOINTS: AUTH_ENDPOINTS, + LOGIN_FAILURE_ACTION: LOGIN_FAILURE_ACTION, + RESOURCE_TYPES: RESOURCE_TYPES, + RESOURCE_LABELS: RESOURCE_LABELS, + SEMANTIC_ACTIONS: SEMANTIC_ACTIONS, + CSV_HEADER: CSV_HEADER, + MAX_CHANGES: MAX_CHANGES, normalizeMethod: normalizeMethod, + pathWithoutQuery: pathWithoutQuery, + hasErrorParam: hasErrorParam, shouldCapture: shouldCapture, resolveResource: resolveResource, - isSuccess: isSuccess, + deriveAction: deriveAction, + describeOperation: describeOperation, + isSuccessful: isSuccessful, + isLoginFailure: isLoginFailure, + isSuccessRecord: isSuccessRecord, + resultBadge: resultBadge, + displayUsername: displayUsername, + formatTime: formatTime, + classifyLogin: classifyLogin, + diffObjects: diffObjects, + formatChanges: formatChanges, + changeTypeLabel: changeTypeLabel, + changeValueDisplay: changeValueDisplay, + isSensitiveField: isSensitiveField, + buildRecord: buildRecord, + buildSystemRecord: buildSystemRecord, + toWire: toWire, applyFilters: applyFilters, paginate: paginate, - countExpired: countExpired + countExpired: countExpired, + csvEscape: csvEscape, + toCsv: toCsv, + createLoginFailureTracker: createLoginFailureTracker, + alertPayload: alertPayload }; }); diff --git a/demo/assets/demo.css b/demo/assets/demo.css index 558d0c7..9c2338f 100644 --- a/demo/assets/demo.css +++ b/demo/assets/demo.css @@ -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; } +} diff --git a/demo/assets/mock-data.js b/demo/assets/mock-data.js index 95c6c9b..137b288 100644 --- a/demo/assets/mock-data.js +++ b/demo/assets/mock-data.js @@ -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; } diff --git a/demo/index.html b/demo/index.html index 04064ba..0d57e09 100644 --- a/demo/index.html +++ b/demo/index.html @@ -66,12 +66,23 @@
@@ -83,68 +94,101 @@ 审计已关闭。当前期间内发生的后台操作不会写入审计日志,重新开启后恢复记录。
+ + +
-
-
- - +
+
+ + + + + + + + +
+ + +
-
- - + -
- - -
-
- - -
-
- - -
-
- - -
-
- - - - - - - - - - - - -
时间操作者动作资源结果来源 IP
+
+ + + + + + + + + + + + +
操作者 / 时间动作资源 / 路径描述结果IP
+
@@ -154,34 +198,110 @@ @@ -197,55 +317,122 @@ 模拟一次后台操作
- + -
-
- - +
+ + +
+ +
+
+
+ + +
+
+ + +
+
- - + + +
+ +
+
+ + +
+
+ + +
+
+ +
+
+ + +
+
+ + +
+
+ +
+ + +
+ +
+ + + + + + + +
-
- - -
- -
- - - - - -
- -
- - +