chore: 恢复 demo 演示与设计文档入库
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
# 操作审计插件 · Console UI Demo
|
||||
|
||||
> 对应文档:[operation-audit-design.md](../docs/operation-audit-design.md)(产品设计)· [operation-audit-tech-design.md](../docs/operation-audit-tech-design.md)(技术方案)
|
||||
>
|
||||
> **纯前端静态 Demo,无任何后端与构建依赖**,用于在开发真实插件前验证界面布局与操作流程是否合理。
|
||||
|
||||
## 快速开始
|
||||
|
||||
直接双击打开 [demo/index.html](./index.html) 即可(全部为经典 `<script>`,`file://` 下可运行)。
|
||||
|
||||
也可以起一个本地静态服务:
|
||||
|
||||
```bash
|
||||
cd demo
|
||||
python -m http.server 8721
|
||||
# 访问 http://127.0.0.1:8721/
|
||||
```
|
||||
|
||||
## 演示了什么
|
||||
|
||||
模拟 Halo Console 外壳(左侧菜单新增"操作审计"插件入口),包含两个页面:
|
||||
|
||||
### 审计日志(产品设计 4.2)
|
||||
|
||||
- 列表:时间、操作者、动作(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)
|
||||
|
||||
- 审计开关:关闭后日志页出现横幅,新操作不再记录
|
||||
- 保留天数:修改后"清理预览"实时计算待清理条数,可点击"模拟一次清理"体验定时清理效果
|
||||
|
||||
### 模拟一次操作(技术方案 D1 / 5.1 / 5.2)
|
||||
|
||||
右上角"模拟一次操作"按钮可模拟任意后台请求,Demo 按真实捕获管线逐步判定:
|
||||
|
||||
1. `shouldCapture`:是否命中捕获规则(`/apis/**` 写操作 + `/login`、`/logout`;匿名请求不记录)
|
||||
2. `resolveResource`:从路径解析资源类型与名称
|
||||
3. 命中则生成审计记录置顶高亮;未命中则用 toast 解释原因(读操作 / 匿名 / 路径不匹配)
|
||||
|
||||
预设按钮包含"登录失败""查询文章列表(读)"等例子,可直观验证规则边界(登录失败记"未知用户")。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
demo/
|
||||
├── index.html # 页面骨架(Console 外壳 + 列表/设置/抽屉/弹窗)
|
||||
├── assets/
|
||||
│ ├── audit-core.js # 核心纯函数:捕获规则、资源解析、筛选、分页、保留期(UMD,浏览器/Node 共用)
|
||||
│ ├── mock-data.js # 模拟数据生成器(种子随机、确定性输出,约 142 条 + 故事线)
|
||||
│ ├── app.js # 交互层(渲染、事件、模拟管线)
|
||||
│ └── demo.css # 样式(视觉基调取自 @halo-dev/components:#4ccba0 / #0e1731 / #d71d1d)
|
||||
└── test/
|
||||
└── audit-core.test.mjs # 单元测试(node:test,29 个用例)
|
||||
```
|
||||
|
||||
## 运行测试
|
||||
|
||||
```bash
|
||||
node --test demo/test/audit-core.test.mjs
|
||||
```
|
||||
|
||||
覆盖:捕获规则各分支(方法/路径/匿名/登录端点)、资源解析(集合/单资源/深层子资源/auth)、
|
||||
筛选(操作者/资源类型/动作/结果/时间范围/关键字)、分页越界收敛、保留期统计、模拟数据确定性与字段完整性。
|
||||
|
||||
## 与真实实现的差异
|
||||
|
||||
| 项 | Demo | 真实插件 |
|
||||
|---|---|---|
|
||||
| 数据 | 页面内存中的模拟数据,刷新即重置 | `AuditLog` Extension 落库 + 索引查询 |
|
||||
| 捕获 | 手动在弹窗里"发送请求"模拟 | `AfterSecurityWebFilter` 自动捕获 |
|
||||
| 写入 | 直接 unshift 到数组 | `ReactiveExtensionClient` 异步直写、失败降级 |
|
||||
| 设置 | 页面内存 | `settings.yaml` + ConfigMap(60s TTL 缓存) |
|
||||
| 清理 | 点击按钮模拟 | 每日定时任务自动执行 |
|
||||
| 权限 | 未演示(本地即超管视角) | 角色模板 `role-template-audit-view`,仅 `get/list` |
|
||||
|
||||
UI 结构(筛选维度、列定义、详情字段、设置项)与真实插件将保持一致,确认交互合理后即可按技术方案里程碑 4 实现 Console 页面。
|
||||
@@ -0,0 +1,439 @@
|
||||
/**
|
||||
* 操作审计 Console UI Demo · 交互层(无框架,模拟 Halo Console 插件页)
|
||||
*
|
||||
* 数据流模拟真实插件的捕获管线:
|
||||
* 请求(method/path/user) → AuditCore.shouldCapture 判定 → AuditCore.resolveResource 解析
|
||||
* → 生成审计记录 → 渲染到列表
|
||||
* 全部数据保存在页面内存中,刷新即重置。
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var $ = function (sel) { return document.querySelector(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: '', result: '', timeRange: 'all', keyword: '' };
|
||||
|
||||
// ---------- 工具 ----------
|
||||
function esc(s) {
|
||||
return String(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);
|
||||
}
|
||||
|
||||
function methodBadge(method) {
|
||||
return '<span class="method m-' + esc(method.toLowerCase()) + '">' + esc(method) + '</span>';
|
||||
}
|
||||
|
||||
function resultBadge(code) {
|
||||
var ok = AuditCore.isSuccess(code);
|
||||
return '<span class="result ' + (ok ? 'ok' : 'fail') + '"><i></i>' + code + ' ' + (ok ? '成功' : '失败') + '</span>';
|
||||
}
|
||||
|
||||
// ---------- 渲染 ----------
|
||||
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
|
||||
});
|
||||
}
|
||||
|
||||
function activeFilterCount() {
|
||||
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;
|
||||
}
|
||||
|
||||
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 = '<option value="">全部</option>' + Object.keys(operators).sort().map(function (u) {
|
||||
return '<option value="' + esc(u) + '"' + (state.filters.operator === u ? ' selected' : '') + '>' + esc(u) + '</option>';
|
||||
}).join('');
|
||||
typeSel.innerHTML = '<option value="">全部</option>' + Object.keys(types).sort().map(function (t) {
|
||||
return '<option value="' + esc(t) + '"' + (state.filters.resourceType === t ? ' selected' : '') + '>' + esc(t) + '</option>';
|
||||
}).join('');
|
||||
// 动作选项与捕获规则一致:POST/PUT/DELETE/PATCH(AuditCore.WRITE_METHODS)
|
||||
$('#f-method').innerHTML = '<option value="">全部</option>' + AuditCore.WRITE_METHODS.map(function (m) {
|
||||
return '<option value="' + m + '"' + (state.filters.method === m ? ' selected' : '') + '>' + m + '</option>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
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 = '<tr><td colspan="6"><div class="empty-state">' +
|
||||
'<div class="es-icon">🔍</div>' +
|
||||
'<p>未找到匹配的审计记录</p>' +
|
||||
(activeFilterCount() ? '<button class="btn-link" id="empty-clear">清除全部筛选</button>' : '') +
|
||||
'</div></td></tr>';
|
||||
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 '<tr data-id="' + rec.id + '" class="' + cls.join(' ') + '">' +
|
||||
'<td class="td-time">' + fmtTime(rec.timestamp) + '</td>' +
|
||||
'<td><span class="cell-user"><span class="avatar sm ' + avCls(rec.username) + '">' + esc(initial(rec.username)) + '</span>' + esc(rec.username) + '</span></td>' +
|
||||
'<td>' + methodBadge(rec.method) + '</td>' +
|
||||
'<td><span class="rt">' + esc(rec.resourceType) + '</span>' +
|
||||
(rec.resourceName ? '<span class="rn">' + esc(rec.resourceName) + '</span>' : '<span class="muted">(集合级操作)</span>') +
|
||||
'</td>' +
|
||||
'<td>' + resultBadge(rec.statusCode) + '</td>' +
|
||||
'<td class="td-ip">' + esc(rec.remoteIp) + '</td>' +
|
||||
'</tr>';
|
||||
}).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 =
|
||||
'当前共 <b>' + logs.length + '</b> 条记录,最早一条:<b>' + (earliest ? fmtDate(earliest) : '—') + '</b>。<br>' +
|
||||
'按保留期 <b>' + state.settings.retentionDays + '</b> 天计算,下次定时清理预计删除 ' +
|
||||
(expired > 0 ? '<span class="num-warn">' + expired + ' 条</span>' : '<b>0 条</b>') + '。';
|
||||
}
|
||||
|
||||
function renderTabs() {
|
||||
document.querySelectorAll('.tab').forEach(function (t) {
|
||||
t.classList.toggle('active', t.getAttribute('data-tab') === state.tab);
|
||||
});
|
||||
$('#panel-logs').hidden = state.tab !== 'logs';
|
||||
$('#panel-settings').hidden = state.tab !== 'settings';
|
||||
}
|
||||
|
||||
function renderAll() {
|
||||
renderBanner();
|
||||
renderFilterOptions();
|
||||
renderTable();
|
||||
renderSettings();
|
||||
renderTabs();
|
||||
}
|
||||
|
||||
// ---------- 详情抽屉 ----------
|
||||
function openDetail(id) {
|
||||
var rec = null;
|
||||
for (var i = 0; i < state.logs.length; i++) {
|
||||
if (state.logs[i].id === id) { rec = state.logs[i]; break; }
|
||||
}
|
||||
if (!rec) return;
|
||||
state.detailId = id;
|
||||
|
||||
var row = function (dt, dd) {
|
||||
return '<div class="d-row"><dt>' + dt + '</dt><dd>' + dd + '</dd></div>';
|
||||
};
|
||||
|
||||
var drawer = $('#drawer');
|
||||
drawer.innerHTML =
|
||||
'<div class="drawer-head">' +
|
||||
'<div><div class="drawer-title">审计记录详情</div><div class="drawer-sub">' + esc(rec.id) + '</div></div>' +
|
||||
'<button class="icon-btn" id="drawer-close" title="关闭">✕</button>' +
|
||||
'</div>' +
|
||||
'<div class="readonly-banner">🛡️ 审计记录为只读,不提供任何修改或删除入口(设计原则 3 · 技术方案 D4)</div>' +
|
||||
'<dl class="detail-list">' +
|
||||
row('时间', esc(fmtTime(rec.timestamp))) +
|
||||
row('操作者', '<span class="avatar sm ' + avCls(rec.username) + '">' + esc(initial(rec.username)) + '</span>' + esc(rec.username)) +
|
||||
row('动作', methodBadge(rec.method)) +
|
||||
row('资源类型', '<span class="rt">' + esc(rec.resourceType) + '</span>') +
|
||||
row('资源名称', rec.resourceName ? esc(rec.resourceName) : '<span class="muted">(集合级操作,无具体资源名)</span>') +
|
||||
row('完整路径', '<code class="path-code">' + esc(rec.path) + '</code>') +
|
||||
row('结果', resultBadge(rec.statusCode)) +
|
||||
row('来源 IP', esc(rec.remoteIp)) +
|
||||
row('User-Agent', '<span class="ua">' + esc(rec.userAgent) + '</span>') +
|
||||
'</dl>' +
|
||||
'<details class="raw-json"><summary>原始记录(JSON)</summary><pre>' + esc(JSON.stringify(rec, null, 2)) + '</pre></details>';
|
||||
|
||||
drawer.hidden = false;
|
||||
$('#drawer-overlay').hidden = false;
|
||||
renderTable();
|
||||
$('#drawer-close').addEventListener('click', closeDetail);
|
||||
}
|
||||
|
||||
function closeDetail() {
|
||||
state.detailId = null;
|
||||
$('#drawer').hidden = true;
|
||||
$('#drawer-overlay').hidden = true;
|
||||
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;
|
||||
});
|
||||
return 'audit-' + String(max + 1).padStart(4, '0');
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
if (!path) { toast('请填写请求路径', 'warn'); return; }
|
||||
|
||||
var authenticated = user !== '__anon__';
|
||||
|
||||
if (!state.settings.enabled) {
|
||||
toast('审计开关已关闭,本次操作未记录', 'warn');
|
||||
return;
|
||||
}
|
||||
|
||||
var rule = AuditCore.shouldCapture({ method: method, path: path, authenticated: authenticated });
|
||||
if (!rule.captured) {
|
||||
toast('未记录:' + rule.reason, 'warn');
|
||||
return;
|
||||
}
|
||||
|
||||
// 组装审计记录(与真实管线一致:规则判定 → 资源解析 → 落一条记录)
|
||||
var isAuthPath = path === '/login' || path === '/logout';
|
||||
var username = authenticated ? user : '未知用户';
|
||||
if (isAuthPath && status >= 400) username = '未知用户'; // 登录失败记"未知用户"(产品设计已知局限)
|
||||
|
||||
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 openModal() {
|
||||
$('#modal').hidden = false;
|
||||
$('#modal-overlay').hidden = false;
|
||||
$('#sim-path').focus();
|
||||
}
|
||||
|
||||
function closeModal() {
|
||||
$('#modal').hidden = true;
|
||||
$('#modal-overlay').hidden = true;
|
||||
}
|
||||
|
||||
// ---------- 事件绑定 ----------
|
||||
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 = '';
|
||||
state.page = 1;
|
||||
renderTable();
|
||||
}
|
||||
|
||||
function bindEvents() {
|
||||
// 侧边栏占位项
|
||||
document.querySelectorAll('[data-demo]').forEach(function (el) {
|
||||
el.addEventListener('click', function (e) {
|
||||
e.preventDefault();
|
||||
toast('Demo 演示:此页面为 Halo Console 既有页面,未实现');
|
||||
});
|
||||
});
|
||||
|
||||
// Tab 切换
|
||||
document.querySelectorAll('.tab').forEach(function (t) {
|
||||
t.addEventListener('click', function () { switchTab(t.getAttribute('data-tab')); });
|
||||
});
|
||||
|
||||
// 筛选
|
||||
$('#f-operator').addEventListener('change', function (e) {
|
||||
state.filters.operator = e.target.value; state.page = 1; renderTable();
|
||||
});
|
||||
$('#f-type').addEventListener('change', function (e) {
|
||||
state.filters.resourceType = e.target.value; state.page = 1; renderTable();
|
||||
});
|
||||
$('#f-method').addEventListener('change', function (e) {
|
||||
state.filters.method = e.target.value; state.page = 1; renderTable();
|
||||
});
|
||||
$('#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();
|
||||
});
|
||||
$('#btn-clear').addEventListener('click', clearFilters);
|
||||
|
||||
// 分页
|
||||
$('#pg-size').addEventListener('change', function (e) {
|
||||
state.size = parseInt(e.target.value, 10); state.page = 1; renderTable();
|
||||
});
|
||||
$('#pg-prev').addEventListener('click', function () { state.page--; renderTable(); });
|
||||
$('#pg-next').addEventListener('click', function () { state.page++; 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-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();
|
||||
});
|
||||
document.querySelectorAll('#modal .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);
|
||||
$('#sim-path').focus();
|
||||
});
|
||||
});
|
||||
|
||||
// Esc 关闭抽屉/弹窗
|
||||
document.addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Escape') {
|
||||
if (!$('#modal').hidden) closeModal();
|
||||
else if (!$('#drawer').hidden) closeDetail();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- 启动 ----------
|
||||
state.logs = MockData.generateLogs();
|
||||
bindEvents();
|
||||
renderAll();
|
||||
})();
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* 操作审计 · 核心纯函数(浏览器与 Node 测试共用)
|
||||
*
|
||||
* 对应文档:
|
||||
* - 技术方案 D1 捕获规则(shouldCapture)
|
||||
* - 技术方案 5.2 资源解析规则(resolveResource)
|
||||
* - 产品设计 4.2 筛选维度(applyFilters)
|
||||
* - 技术方案 D5 保留期清理(countExpired)
|
||||
*
|
||||
* 本文件不依赖任何 DOM / 网络能力,仅做纯计算,便于单元测试。
|
||||
*/
|
||||
(function (root, factory) {
|
||||
if (typeof module === 'object' && module.exports) {
|
||||
module.exports = factory();
|
||||
} else {
|
||||
root.AuditCore = factory();
|
||||
}
|
||||
})(typeof self !== 'undefined' ? self : this, function () {
|
||||
'use strict';
|
||||
|
||||
var WRITE_METHODS = ['POST', 'PUT', 'DELETE', 'PATCH'];
|
||||
var AUTH_PATHS = ['/login', '/logout'];
|
||||
|
||||
function normalizeMethod(method) {
|
||||
return String(method || '').trim().toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* 捕获规则(技术方案 D1):
|
||||
* - /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 中向用户解释判定依据
|
||||
*/
|
||||
function shouldCapture(options) {
|
||||
var method = normalizeMethod(options && options.method);
|
||||
var path = String((options && options.path) || '').trim();
|
||||
var authenticated = !!(options && options.authenticated);
|
||||
|
||||
if (AUTH_PATHS.indexOf(path) !== -1) {
|
||||
return { captured: true, reason: '登录/登出事件,始终记录' };
|
||||
}
|
||||
if (path.indexOf('/apis/') !== 0) {
|
||||
return { captured: false, reason: '路径不在捕获范围(仅 /apis/** 与 /login、/logout)' };
|
||||
}
|
||||
if (!authenticated) {
|
||||
return { captured: false, reason: '匿名请求不记录(认证后仍为匿名主体的 401/403 场景)' };
|
||||
}
|
||||
if (WRITE_METHODS.indexOf(method) === -1) {
|
||||
return { captured: false, reason: '仅记录写操作(POST/PUT/DELETE/PATCH),读操作不记录' };
|
||||
}
|
||||
return { captured: true, 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"
|
||||
*/
|
||||
function resolveResource(path) {
|
||||
var p = String(path || '').trim();
|
||||
if (AUTH_PATHS.indexOf(p) !== -1) {
|
||||
return { resourceType: 'auth', resourceName: '' };
|
||||
}
|
||||
if (p.indexOf('/apis/') !== 0) {
|
||||
return { resourceType: 'other', resourceName: '' };
|
||||
}
|
||||
// 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; });
|
||||
if (segs.length < 4) {
|
||||
return { resourceType: 'other', resourceName: '' };
|
||||
}
|
||||
return { resourceType: segs[3], resourceName: segs[4] || '' };
|
||||
}
|
||||
|
||||
/** 结果判定:2xx/3xx 视为成功 */
|
||||
function isSuccess(statusCode) {
|
||||
return statusCode > 0 && statusCode < 400;
|
||||
}
|
||||
|
||||
/**
|
||||
* 筛选(产品设计 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
|
||||
*/
|
||||
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;
|
||||
|
||||
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 (keyword) {
|
||||
var hay = (log.resourceName + ' ' + log.path).toLowerCase();
|
||||
if (hay.indexOf(keyword) === -1) return false;
|
||||
}
|
||||
return true;
|
||||
}).sort(function (a, b) {
|
||||
return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页(page 从 1 开始,越界自动收敛到合法页码)
|
||||
* @returns {{items: Array, total: number, pages: number, page: number}}
|
||||
*/
|
||||
function paginate(items, page, size) {
|
||||
var total = items.length;
|
||||
var pages = Math.max(1, Math.ceil(total / size));
|
||||
var current = Math.min(Math.max(1, page || 1), pages);
|
||||
var start = (current - 1) * size;
|
||||
return {
|
||||
items: items.slice(start, start + size),
|
||||
total: total,
|
||||
pages: pages,
|
||||
page: current
|
||||
};
|
||||
}
|
||||
|
||||
/** 保留期清理(技术方案 D5):统计超过保留天数的记录条数 */
|
||||
function countExpired(logs, retentionDays, now) {
|
||||
var cutoff = now - retentionDays * 86400 * 1000;
|
||||
return logs.filter(function (log) {
|
||||
return new Date(log.timestamp).getTime() < cutoff;
|
||||
}).length;
|
||||
}
|
||||
|
||||
return {
|
||||
WRITE_METHODS: WRITE_METHODS,
|
||||
AUTH_PATHS: AUTH_PATHS,
|
||||
normalizeMethod: normalizeMethod,
|
||||
shouldCapture: shouldCapture,
|
||||
resolveResource: resolveResource,
|
||||
isSuccess: isSuccess,
|
||||
applyFilters: applyFilters,
|
||||
paginate: paginate,
|
||||
countExpired: countExpired
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,737 @@
|
||||
/* =========================================================
|
||||
* 操作审计 Console UI Demo · 样式
|
||||
* 视觉基调取自 Halo Console(@halo-dev/components):
|
||||
* primary #4ccba0 / secondary #0e1731 / danger #d71d1d
|
||||
* ========================================================= */
|
||||
|
||||
:root {
|
||||
--primary: #4ccba0;
|
||||
--primary-dark: #2ea27f;
|
||||
--primary-tint: rgba(76, 203, 160, 0.12);
|
||||
--secondary: #0e1731;
|
||||
--danger: #d71d1d;
|
||||
--danger-tint: rgba(215, 29, 29, 0.08);
|
||||
--warn: #b45309;
|
||||
--warn-tint: rgba(217, 119, 6, 0.1);
|
||||
--info: #2563eb;
|
||||
--info-tint: rgba(37, 99, 235, 0.1);
|
||||
--gray-50: #f9fafb;
|
||||
--gray-100: #f3f4f6;
|
||||
--gray-200: #e5e7eb;
|
||||
--gray-300: #d1d5db;
|
||||
--gray-400: #9ca3af;
|
||||
--gray-500: #6b7280;
|
||||
--gray-700: #374151;
|
||||
--gray-900: #111827;
|
||||
--radius: 8px;
|
||||
--shadow: 0 1px 3px rgba(14, 23, 49, 0.06), 0 1px 2px rgba(14, 23, 49, 0.04);
|
||||
--shadow-lg: 0 10px 30px rgba(14, 23, 49, 0.18);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html, body { height: 100%; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
min-width: 1080px;
|
||||
font-size: 14px;
|
||||
color: var(--gray-900);
|
||||
background: var(--gray-100);
|
||||
font-family: system-ui, -apple-system, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
|
||||
}
|
||||
|
||||
/* ============ 左侧导航 ============ */
|
||||
.sidebar {
|
||||
width: 232px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #fff;
|
||||
border-right: 1px solid var(--gray-200);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
height: 100vh;
|
||||
}
|
||||
|
||||
.logo-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 14px 16px;
|
||||
height: 56px;
|
||||
border-bottom: 1px solid var(--gray-100);
|
||||
}
|
||||
|
||||
.logo-mark { width: 26px; height: 26px; }
|
||||
|
||||
.logo-text {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.5px;
|
||||
}
|
||||
|
||||
.demo-badge {
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
color: var(--primary-dark);
|
||||
background: var(--primary-tint);
|
||||
border-radius: 999px;
|
||||
padding: 2px 8px;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.nav-scroll { flex: 1; overflow-y: auto; padding: 8px; }
|
||||
|
||||
.nav-group {
|
||||
font-size: 11px;
|
||||
color: var(--gray-400);
|
||||
padding: 14px 12px 4px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 1px;
|
||||
}
|
||||
|
||||
.nav-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
height: 38px;
|
||||
padding: 0 12px;
|
||||
margin: 1px 0;
|
||||
border-radius: 6px;
|
||||
color: var(--gray-700);
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
|
||||
.nav-item svg {
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
fill: none;
|
||||
stroke: currentColor;
|
||||
stroke-width: 1.7;
|
||||
stroke-linecap: round;
|
||||
stroke-linejoin: round;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.nav-item:hover { background: var(--gray-100); }
|
||||
|
||||
.nav-item.active {
|
||||
background: var(--primary-tint);
|
||||
color: var(--primary-dark);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sidebar-footer {
|
||||
border-top: 1px solid var(--gray-100);
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.user-chip { display: flex; align-items: center; gap: 10px; }
|
||||
|
||||
.user-meta { display: flex; flex-direction: column; line-height: 1.3; }
|
||||
.user-meta b { font-size: 13px; }
|
||||
.user-meta small { font-size: 11px; color: var(--gray-500); }
|
||||
|
||||
/* ============ 主内容区 ============ */
|
||||
.main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 24px 28px 40px;
|
||||
}
|
||||
|
||||
.page-header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.page-header h1 {
|
||||
margin: 0;
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.page-sub {
|
||||
margin: 4px 0 0;
|
||||
color: var(--gray-500);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.readonly-hint { color: var(--primary-dark); }
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
margin: 18px 0 14px;
|
||||
border-bottom: 1px solid var(--gray-200);
|
||||
}
|
||||
|
||||
.tab {
|
||||
appearance: none;
|
||||
border: none;
|
||||
background: none;
|
||||
padding: 8px 14px;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--gray-500);
|
||||
cursor: pointer;
|
||||
border-bottom: 2px solid transparent;
|
||||
margin-bottom: -1px;
|
||||
}
|
||||
|
||||
.tab:hover { color: var(--gray-900); }
|
||||
|
||||
.tab.active {
|
||||
color: var(--primary-dark);
|
||||
border-bottom-color: var(--primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ============ 卡片 / 通用 ============ */
|
||||
.card {
|
||||
background: #fff;
|
||||
border: 1px solid var(--gray-200);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.card-title {
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
padding: 14px 18px 0;
|
||||
}
|
||||
|
||||
.btn {
|
||||
appearance: none;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
padding: 8px 16px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
transition: filter 0.15s, background 0.15s;
|
||||
}
|
||||
|
||||
.btn svg {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
fill: currentColor;
|
||||
}
|
||||
|
||||
.btn-primary { background: var(--primary); color: #fff; }
|
||||
.btn-primary:hover { filter: brightness(0.94); }
|
||||
|
||||
.btn-outline {
|
||||
background: #fff;
|
||||
color: var(--gray-700);
|
||||
border: 1px solid var(--gray-300);
|
||||
}
|
||||
.btn-outline:hover { border-color: var(--primary); color: var(--primary-dark); }
|
||||
|
||||
.btn-link {
|
||||
appearance: none;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--primary-dark);
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
padding: 8px 4px;
|
||||
align-self: flex-end;
|
||||
}
|
||||
|
||||
.btn-link:hover { text-decoration: underline; }
|
||||
|
||||
.icon-btn {
|
||||
appearance: none;
|
||||
border: none;
|
||||
background: none;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 6px;
|
||||
font-size: 16px;
|
||||
color: var(--gray-500);
|
||||
cursor: pointer;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.icon-btn:hover { background: var(--gray-100); color: var(--gray-900); }
|
||||
|
||||
.input {
|
||||
border: 1px solid var(--gray-300);
|
||||
border-radius: 6px;
|
||||
padding: 7px 10px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
outline: none;
|
||||
transition: border-color 0.15s, box-shadow 0.15s;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.input:focus,
|
||||
select:focus {
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 2px var(--primary-tint);
|
||||
}
|
||||
|
||||
select, .input { min-width: 0; }
|
||||
|
||||
select {
|
||||
appearance: none;
|
||||
border: 1px solid var(--gray-300);
|
||||
border-radius: 6px;
|
||||
padding: 7px 28px 7px 10px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
background: #fff url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%236b7280' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E") no-repeat right 10px center;
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.hint { font-size: 12px; color: var(--gray-400); }
|
||||
.muted { color: var(--gray-400); font-size: 12px; }
|
||||
|
||||
/* ============ 横幅 ============ */
|
||||
.banner {
|
||||
border-radius: var(--radius);
|
||||
padding: 10px 14px;
|
||||
font-size: 13px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.banner-warn { background: var(--warn-tint); color: var(--warn); border: 1px solid rgba(217, 119, 6, 0.25); }
|
||||
|
||||
/* ============ 筛选栏 ============ */
|
||||
.filter-bar {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 12px;
|
||||
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%; }
|
||||
|
||||
/* ============ 表格 ============ */
|
||||
.table-card { overflow: hidden; }
|
||||
|
||||
.audit-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
.audit-table th {
|
||||
text-align: left;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--gray-500);
|
||||
padding: 10px 16px;
|
||||
background: var(--gray-50);
|
||||
border-bottom: 1px solid var(--gray-200);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.audit-table td {
|
||||
padding: 10px 16px;
|
||||
border-bottom: 1px solid var(--gray-100);
|
||||
font-size: 13px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.audit-table tbody tr {
|
||||
cursor: pointer;
|
||||
transition: background 0.12s;
|
||||
}
|
||||
|
||||
.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.6s ease-out; }
|
||||
|
||||
.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; }
|
||||
|
||||
/* 动作徽标 */
|
||||
.method {
|
||||
display: inline-block;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
font-family: ui-monospace, Consolas, monospace;
|
||||
padding: 2px 8px;
|
||||
border-radius: 5px;
|
||||
letter-spacing: 0.4px;
|
||||
}
|
||||
.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-get { background: var(--gray-100); color: var(--gray-500); }
|
||||
|
||||
/* 资源列 */
|
||||
.rt {
|
||||
display: inline-block;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--gray-700);
|
||||
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); }
|
||||
|
||||
/* 空状态 */
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 48px 0 40px;
|
||||
color: var(--gray-500);
|
||||
}
|
||||
.empty-state .es-icon { font-size: 30px; margin-bottom: 8px; }
|
||||
.empty-state p { margin: 4px 0; }
|
||||
.empty-state .btn-link { padding: 4px 8px; }
|
||||
|
||||
/* 分页 */
|
||||
.pagination {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 10px 16px;
|
||||
border-top: 1px solid var(--gray-200);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.pg-info { font-size: 12.5px; color: var(--gray-500); }
|
||||
|
||||
.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; }
|
||||
|
||||
/* ============ 设置页 ============ */
|
||||
#panel-settings .settings-card { max-width: 780px; }
|
||||
.settings-card { margin-bottom: 16px; padding-bottom: 6px; }
|
||||
|
||||
.setting-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
padding: 16px 18px;
|
||||
border-bottom: 1px solid var(--gray-100);
|
||||
}
|
||||
|
||||
.setting-text { max-width: 640px; }
|
||||
.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; }
|
||||
|
||||
.input.num { width: 90px; text-align: center; }
|
||||
|
||||
.settings-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
padding: 14px 18px 16px;
|
||||
}
|
||||
|
||||
.clean-stats {
|
||||
padding: 14px 18px;
|
||||
font-size: 13px;
|
||||
color: var(--gray-700);
|
||||
line-height: 1.7;
|
||||
}
|
||||
.clean-stats .num-warn { color: var(--danger); font-weight: 600; }
|
||||
|
||||
.settings-card .btn { margin: 0 18px 16px; }
|
||||
|
||||
/* 开关 */
|
||||
.switch { position: relative; display: inline-block; width: 40px; height: 22px; flex-shrink: 0; }
|
||||
.switch input { opacity: 0; width: 0; height: 0; }
|
||||
|
||||
.slider {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: var(--gray-300);
|
||||
border-radius: 999px;
|
||||
transition: background 0.2s;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.slider::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
left: 3px;
|
||||
top: 3px;
|
||||
border-radius: 50%;
|
||||
background: #fff;
|
||||
transition: transform 0.2s;
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
|
||||
.switch input:checked + .slider { background: var(--primary); }
|
||||
.switch input:checked + .slider::before { transform: translateX(18px); }
|
||||
|
||||
/* ============ 头像 ============ */
|
||||
.avatar {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 50%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: #fff;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.avatar.sm { width: 22px; height: 22px; font-size: 10px; }
|
||||
|
||||
.c-a { background: #4ccba0; }
|
||||
.c-b { background: #6366f1; }
|
||||
.c-c { background: #f59e0b; }
|
||||
.c-d { background: #ec4899; }
|
||||
.c-e { background: #0ea5e9; }
|
||||
|
||||
/* ============ 详情抽屉 ============ */
|
||||
.overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(14, 23, 49, 0.4);
|
||||
z-index: 40;
|
||||
}
|
||||
|
||||
.drawer {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
width: 440px;
|
||||
max-width: 92vw;
|
||||
height: 100vh;
|
||||
background: #fff;
|
||||
z-index: 50;
|
||||
box-shadow: var(--shadow-lg);
|
||||
overflow-y: auto;
|
||||
padding: 20px 22px 28px;
|
||||
}
|
||||
|
||||
@keyframes slideIn {
|
||||
from { transform: translateX(60px); opacity: 0; }
|
||||
to { transform: translateX(0); opacity: 1; }
|
||||
}
|
||||
|
||||
.drawer[hidden] { display: none; }
|
||||
.drawer { animation: slideIn 0.25s ease-out; }
|
||||
|
||||
.drawer-head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.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; }
|
||||
|
||||
.readonly-banner {
|
||||
background: var(--primary-tint);
|
||||
color: var(--primary-dark);
|
||||
font-size: 12.5px;
|
||||
border-radius: 6px;
|
||||
padding: 9px 12px;
|
||||
margin-bottom: 16px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.detail-list { margin: 0; }
|
||||
|
||||
.detail-list .d-row {
|
||||
padding: 9px 0;
|
||||
border-bottom: 1px dashed var(--gray-200);
|
||||
}
|
||||
|
||||
.detail-list dt {
|
||||
font-size: 11.5px;
|
||||
color: var(--gray-500);
|
||||
font-weight: 600;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.detail-list dd {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
word-break: break-all;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.path-code {
|
||||
display: block;
|
||||
font-family: ui-monospace, Consolas, 'Courier New', monospace;
|
||||
font-size: 12px;
|
||||
background: var(--gray-100);
|
||||
border-radius: 5px;
|
||||
padding: 7px 9px;
|
||||
word-break: break-all;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.ua { font-size: 12px; color: var(--gray-500); line-height: 1.6; }
|
||||
|
||||
.raw-json { margin-top: 16px; }
|
||||
.raw-json summary {
|
||||
font-size: 12.5px;
|
||||
color: var(--gray-500);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
.raw-json summary:hover { color: var(--gray-900); }
|
||||
|
||||
.raw-json pre {
|
||||
background: var(--secondary);
|
||||
color: #d1fae5;
|
||||
font-size: 11.5px;
|
||||
border-radius: 6px;
|
||||
padding: 12px;
|
||||
overflow-x: auto;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* ============ 模拟操作弹窗 ============ */
|
||||
.modal {
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 520px;
|
||||
max-width: 92vw;
|
||||
background: #fff;
|
||||
border-radius: 10px;
|
||||
z-index: 50;
|
||||
box-shadow: var(--shadow-lg);
|
||||
padding: 18px 22px 20px;
|
||||
}
|
||||
|
||||
.modal[hidden] { display: none; }
|
||||
|
||||
@keyframes popIn {
|
||||
from { transform: translate(-50%, -50%) scale(0.96); opacity: 0; }
|
||||
to { transform: translate(-50%, -50%) scale(1); opacity: 1; }
|
||||
}
|
||||
|
||||
.modal { animation: popIn 0.2s ease-out; }
|
||||
|
||||
.modal-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.modal-sub {
|
||||
font-size: 12.5px;
|
||||
color: var(--gray-500);
|
||||
line-height: 1.6;
|
||||
margin: 8px 0 14px;
|
||||
}
|
||||
|
||||
.modal-sub code {
|
||||
background: var(--gray-100);
|
||||
border-radius: 4px;
|
||||
padding: 1px 5px;
|
||||
font-size: 11.5px;
|
||||
}
|
||||
|
||||
.field { display: flex; flex-direction: column; gap: 5px; margin-bottom: 12px; flex: 1; }
|
||||
.field label { font-size: 12px; color: var(--gray-500); font-weight: 600; }
|
||||
.field select, .field .input { width: 100%; }
|
||||
|
||||
.field-row { display: flex; gap: 12px; }
|
||||
|
||||
.presets { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 14px; }
|
||||
|
||||
.chip {
|
||||
appearance: none;
|
||||
border: 1px solid var(--gray-300);
|
||||
background: #fff;
|
||||
border-radius: 999px;
|
||||
padding: 5px 12px;
|
||||
font-size: 12px;
|
||||
color: var(--gray-700);
|
||||
cursor: pointer;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
|
||||
.chip:hover { border-color: var(--primary); color: var(--primary-dark); background: var(--primary-tint); }
|
||||
|
||||
.modal-actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 10px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
/* ============ Toast ============ */
|
||||
.toast {
|
||||
position: fixed;
|
||||
top: 22px;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -8px);
|
||||
background: var(--secondary);
|
||||
color: #fff;
|
||||
font-size: 13px;
|
||||
padding: 10px 18px;
|
||||
border-radius: 8px;
|
||||
box-shadow: var(--shadow-lg);
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transition: opacity 0.25s, transform 0.25s;
|
||||
z-index: 100;
|
||||
max-width: 60vw;
|
||||
}
|
||||
|
||||
.toast.show { opacity: 1; transform: translate(-50%, 0); }
|
||||
.toast.ok { background: var(--primary-dark); }
|
||||
.toast.warn { background: #92400e; }
|
||||
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* 操作审计 · 模拟数据生成器(种子随机,确定性输出)
|
||||
*
|
||||
* 记录字段与产品设计 4.1 表格一一对应;resourceType/resourceName 通过
|
||||
* AuditCore.resolveResource 从路径解析得出(模拟真实捕获管线)。
|
||||
* 内置若干"故事线"数据:登录爆破、越权 403、服务端 500 等,便于验证筛选场景。
|
||||
*/
|
||||
(function (root, factory) {
|
||||
if (typeof module === 'object' && module.exports) {
|
||||
module.exports = factory(require('./audit-core.js'));
|
||||
} else {
|
||||
root.MockData = factory(root.AuditCore);
|
||||
}
|
||||
})(typeof self !== 'undefined' ? self : this, function (AuditCore) {
|
||||
'use strict';
|
||||
|
||||
var DAY = 86400000;
|
||||
var MIN = 60000;
|
||||
var BASE_COUNT = 128; // 随机生成的基础记录条数
|
||||
|
||||
// ---------- 种子随机 ----------
|
||||
function mulberry32(seed) {
|
||||
var a = seed >>> 0;
|
||||
return function () {
|
||||
a |= 0;
|
||||
a = (a + 0x6D2B79F5) | 0;
|
||||
var t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
function rint(r, min, max) {
|
||||
return Math.floor(r() * (max - min + 1)) + min;
|
||||
}
|
||||
function pick(r, arr) {
|
||||
return arr[rint(r, 0, arr.length - 1)];
|
||||
}
|
||||
function hex(r, n) {
|
||||
var s = '';
|
||||
var chars = '0123456789abcdef';
|
||||
for (var i = 0; i < n; i++) s += chars[rint(r, 0, 15)];
|
||||
return s;
|
||||
}
|
||||
|
||||
// ---------- 基础素材 ----------
|
||||
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',
|
||||
edge: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.2151.97 Safari/537.36 Edg/119.0.2151.97',
|
||||
firefox: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0',
|
||||
safari: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15',
|
||||
bot: 'python-requests/2.31.0'
|
||||
};
|
||||
|
||||
var USERS = {
|
||||
'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 TOTAL_WEIGHT = ACTIONS.reduce(function (sum, a) { return sum + a[0]; }, 0);
|
||||
|
||||
function userCtx(r, name) {
|
||||
var u = USERS[name];
|
||||
return {
|
||||
username: name,
|
||||
remoteIp: pick(r, u.ips),
|
||||
userAgent: UAS[pick(r, u.uas)]
|
||||
};
|
||||
}
|
||||
|
||||
function rec(timestamp, username, method, path, statusCode, remoteIp, userAgent) {
|
||||
var res = AuditCore.resolveResource(path);
|
||||
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
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成模拟审计日志(按时间倒序,id 从旧到新递增)
|
||||
* @param {number} [now] 当前时间戳(默认 Date.now()),测试传固定值保证确定性
|
||||
* @returns {Array}
|
||||
*/
|
||||
function generateLogs(now) {
|
||||
if (typeof now !== 'number') now = Date.now();
|
||||
var r = mulberry32(20261121);
|
||||
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
|
||||
));
|
||||
}
|
||||
|
||||
// ---- 故事线(固定时间锚点)----
|
||||
|
||||
// 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
|
||||
));
|
||||
});
|
||||
|
||||
// 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. 越权尝试: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. 权限不足: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. 资源不存在: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. 服务端异常: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. 误操作定位: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');
|
||||
});
|
||||
return logs;
|
||||
}
|
||||
|
||||
return { generateLogs: generateLogs };
|
||||
});
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>操作审计 · Console UI Demo(Halo 插件)</title>
|
||||
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='%234ccba0' d='M12 3l7 3v6c0 4.6-3 7.6-7 9-4-1.4-7-4.4-7-9V6z'/%3E%3C/svg%3E">
|
||||
<link rel="stylesheet" href="assets/demo.css">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- ======== 左侧导航(模拟 Halo Console 外壳) ======== -->
|
||||
<aside class="sidebar">
|
||||
<div class="logo-row">
|
||||
<svg class="logo-mark" viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path fill="#4ccba0" d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm0 3.2a6.8 6.8 0 0 1 4.8 11.6c-.5-1.6-2.4-2.6-4.8-2.6s-4.3 1-4.8 2.6A6.8 6.8 0 0 1 12 5.2Z"/>
|
||||
<circle cx="12" cy="10.4" r="2.6" fill="#0e1731"/>
|
||||
</svg>
|
||||
<span class="logo-text">Halo</span>
|
||||
<span class="demo-badge">UI Demo</span>
|
||||
</div>
|
||||
|
||||
<nav class="nav-scroll">
|
||||
<div class="nav-group">内容</div>
|
||||
<a class="nav-item" href="#" data-demo>
|
||||
<svg viewBox="0 0 24 24"><rect x="3" y="3" width="7.5" height="9" rx="1.5"/><rect x="13.5" y="3" width="7.5" height="5" rx="1.5"/><rect x="13.5" y="11" width="7.5" height="10" rx="1.5"/><rect x="3" y="15" width="7.5" height="6" rx="1.5"/></svg>
|
||||
仪表盘</a>
|
||||
<a class="nav-item" href="#" data-demo>
|
||||
<svg viewBox="0 0 24 24"><path d="M6 3h9l4 4v14H6z"/><path d="M9 11h7M9 14.5h7M9 18h4.5"/></svg>
|
||||
文章</a>
|
||||
<a class="nav-item" href="#" data-demo>
|
||||
<svg viewBox="0 0 24 24"><path d="M7 3h7l4 4v14H7z"/><path d="M10 12h5M10 15.5h5"/></svg>
|
||||
页面</a>
|
||||
<a class="nav-item" href="#" data-demo>
|
||||
<svg viewBox="0 0 24 24"><path d="M21 11.5c0 4.1-4 7.5-9 7.5-1 0-2-.13-2.9-.37L4 20l1.3-3.4C3.9 15.3 3 13.5 3 11.5 3 7.4 7 4 12 4s9 3.4 9 7.5Z"/></svg>
|
||||
评论</a>
|
||||
<a class="nav-item" href="#" data-demo>
|
||||
<svg viewBox="0 0 24 24"><path d="M8 12.5 15.5 5a3.2 3.2 0 0 1 4.5 4.5l-8.8 8.8a5 5 0 0 1-7-7l8.3-8.3"/></svg>
|
||||
附件</a>
|
||||
<a class="nav-item" href="#" data-demo>
|
||||
<svg viewBox="0 0 24 24"><circle cx="12" cy="8" r="4"/><path d="M4.5 20c.8-3.6 3.9-5.5 7.5-5.5s6.7 1.9 7.5 5.5"/></svg>
|
||||
用户</a>
|
||||
<a class="nav-item" href="#" data-demo>
|
||||
<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 0 0 18c1.5 0 2-1 2-2s-.8-2-.8-3c0-1.2 1-2 2.6-2H19a2 2 0 0 0 2-2 9 9 0 0 0-9-9Z"/><circle cx="8" cy="10" r="1.2"/><circle cx="12" cy="7.5" r="1.2"/><circle cx="16" cy="10" r="1.2"/></svg>
|
||||
主题</a>
|
||||
<a class="nav-item" href="#" data-demo>
|
||||
<svg viewBox="0 0 24 24"><path d="M4 7h3l2-2h6l2 2h3v12H4z"/><circle cx="12" cy="13" r="3"/></svg>
|
||||
系统</a>
|
||||
|
||||
<div class="nav-group">插件</div>
|
||||
<a class="nav-item active" href="#" id="nav-audit">
|
||||
<svg viewBox="0 0 24 24"><path d="M12 3l7 3v6c0 4.6-3 7.6-7 9-4-1.4-7-4.4-7-9V6z"/><path d="m9 11.5 2.2 2.2L15.5 9.5"/></svg>
|
||||
操作审计</a>
|
||||
</nav>
|
||||
|
||||
<div class="sidebar-footer">
|
||||
<div class="user-chip">
|
||||
<span class="avatar c-a">G</span>
|
||||
<span class="user-meta"><b>guichumo</b><small>超级管理员</small></span>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<!-- ======== 主内容区 ======== -->
|
||||
<main class="main">
|
||||
<div class="page-header">
|
||||
<div>
|
||||
<h1>操作审计</h1>
|
||||
<p class="page-sub">谁 · 在什么时候 · 对什么资源 · 做了什么操作 · 结果如何 <span class="readonly-hint">(只读,不可篡改)</span></p>
|
||||
</div>
|
||||
<button class="btn btn-outline" id="btn-simulate">
|
||||
<svg viewBox="0 0 24 24"><path d="M6 4.5v15l12-7.5z"/></svg>
|
||||
模拟一次操作
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="tabs" id="tabs">
|
||||
<button class="tab active" data-tab="logs">审计日志</button>
|
||||
<button class="tab" data-tab="settings">插件设置</button>
|
||||
</div>
|
||||
|
||||
<div class="banner banner-warn" id="audit-off-banner" hidden>
|
||||
<b>审计已关闭。</b>当前期间内发生的后台操作不会写入审计日志,重新开启后恢复记录。
|
||||
</div>
|
||||
|
||||
<!-- ---- 审计日志 ---- -->
|
||||
<section id="panel-logs">
|
||||
<div class="filter-bar card">
|
||||
<div class="filter-item">
|
||||
<label for="f-operator">操作者</label>
|
||||
<select id="f-operator"><option value="">全部</option></select>
|
||||
</div>
|
||||
<div class="filter-item">
|
||||
<label for="f-type">资源类型</label>
|
||||
<select id="f-type"><option value="">全部</option></select>
|
||||
</div>
|
||||
<div class="filter-item">
|
||||
<label for="f-method">动作</label>
|
||||
<select id="f-method"><option value="">全部</option></select>
|
||||
</div>
|
||||
<div class="filter-item">
|
||||
<label for="f-result">结果</label>
|
||||
<select id="f-result">
|
||||
<option value="">全部</option>
|
||||
<option value="success">成功</option>
|
||||
<option value="failure">失败</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="filter-item">
|
||||
<label for="f-time">时间范围</label>
|
||||
<select id="f-time">
|
||||
<option value="all">全部时间</option>
|
||||
<option value="24h">近 24 小时</option>
|
||||
<option value="7d">近 7 天</option>
|
||||
<option value="30d">近 30 天</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="filter-item grow">
|
||||
<label for="f-keyword">关键字</label>
|
||||
<input id="f-keyword" type="search" placeholder="资源名称 / 路径,如 hello-halo" autocomplete="off">
|
||||
</div>
|
||||
<button class="btn-link" id="btn-clear" hidden>✕ 清除筛选</button>
|
||||
</div>
|
||||
|
||||
<div class="card table-card">
|
||||
<table class="audit-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:170px">时间</th>
|
||||
<th style="width:150px">操作者</th>
|
||||
<th style="width:90px">动作</th>
|
||||
<th>资源</th>
|
||||
<th style="width:110px">结果</th>
|
||||
<th style="width:140px">来源 IP</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="tbody"></tbody>
|
||||
</table>
|
||||
<div class="pagination">
|
||||
<span class="pg-info" id="pg-info"></span>
|
||||
<span class="pg-right">
|
||||
<select id="pg-size" title="每页条数">
|
||||
<option value="10">10 条/页</option>
|
||||
<option value="20">20 条/页</option>
|
||||
<option value="50">50 条/页</option>
|
||||
</select>
|
||||
<button class="icon-btn" id="pg-prev" title="上一页">‹</button>
|
||||
<button class="icon-btn" id="pg-next" title="下一页">›</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ---- 插件设置 ---- -->
|
||||
<section id="panel-settings" hidden>
|
||||
<div class="card settings-card">
|
||||
<div class="card-title">基本设置</div>
|
||||
<div class="setting-row">
|
||||
<div class="setting-text">
|
||||
<div class="s-name">审计开关</div>
|
||||
<div class="s-desc">开启后,已登录用户对后台 API(/apis/**)的写操作与登录/登出事件将被记录(对应 settings.yaml,Console 自动渲染)</div>
|
||||
</div>
|
||||
<label class="switch">
|
||||
<input type="checkbox" id="set-enabled" checked>
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div class="setting-text">
|
||||
<div class="s-name">保留天数</div>
|
||||
<div class="s-desc">超过保留期的记录由每日定时任务自动清理,无需人工干预(默认 90 天,最小 7 天)</div>
|
||||
</div>
|
||||
<input type="number" id="set-retention" class="input num" min="7" max="365" value="90">
|
||||
</div>
|
||||
<div class="settings-actions">
|
||||
<button class="btn btn-primary" id="btn-save-settings">保存设置</button>
|
||||
<span class="hint">Demo 仅保存在当前页面内存中,刷新后恢复默认</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card settings-card">
|
||||
<div class="card-title">清理预览</div>
|
||||
<div class="clean-stats" id="clean-stats"></div>
|
||||
<button class="btn btn-outline" id="btn-clean">模拟一次清理</button>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<!-- ======== 详情抽屉(只读) ======== -->
|
||||
<div class="overlay" id="drawer-overlay" hidden></div>
|
||||
<aside class="drawer" id="drawer" hidden></aside>
|
||||
|
||||
<!-- ======== 模拟操作弹窗 ======== -->
|
||||
<div class="overlay" id="modal-overlay" hidden></div>
|
||||
<div class="modal" id="modal" hidden>
|
||||
<div class="modal-head">
|
||||
<span>模拟一次后台操作</span>
|
||||
<button class="icon-btn" id="modal-close">✕</button>
|
||||
</div>
|
||||
<p class="modal-sub">选择操作者与方法、输入请求路径后发送,Demo 将按技术方案 D1 的捕获规则(<code>/apis/**</code> 写操作 + <code>/login</code>、<code>/logout</code>)判断是否写入审计日志。</p>
|
||||
|
||||
<div class="field-row">
|
||||
<div class="field">
|
||||
<label for="sim-user">操作者</label>
|
||||
<select id="sim-user">
|
||||
<option value="guichumo">guichumo</option>
|
||||
<option value="editor.zhang">editor.zhang</option>
|
||||
<option value="writer.li">writer.li</option>
|
||||
<option value="__anon__">匿名访客</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="sim-method">HTTP 方法</label>
|
||||
<select id="sim-method">
|
||||
<option>GET</option>
|
||||
<option>POST</option>
|
||||
<option>PUT</option>
|
||||
<option>DELETE</option>
|
||||
<option>PATCH</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="sim-path">请求路径</label>
|
||||
<input id="sim-path" type="text" placeholder="/apis/content.halo.run/v1alpha1/posts/hello-halo" autocomplete="off" spellcheck="false">
|
||||
</div>
|
||||
|
||||
<div class="presets">
|
||||
<button class="chip" data-preset='{"user":"guichumo","method":"PUT","path":"/apis/content.halo.run/v1alpha1/posts/hello-halo","status":200}'>编辑文章</button>
|
||||
<button class="chip" data-preset='{"user":"guichumo","method":"POST","path":"/apis/api.content.halo.run/v1alpha1/posts/reading-notes-11/publish","status":200}'>发布文章</button>
|
||||
<button class="chip" data-preset='{"user":"editor.zhang","method":"POST","path":"/apis/api.halo.run/v1alpha1/comments/comment-8fa2c1/approve","status":200}'>审核评论</button>
|
||||
<button class="chip" data-preset='{"user":"__anon__","method":"POST","path":"/login","status":401}'>登录失败</button>
|
||||
<button class="chip" data-preset='{"user":"guichumo","method":"GET","path":"/apis/api.content.halo.run/v1alpha1/posts","status":200}'>查询文章列表(读)</button>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="sim-status">模拟响应</label>
|
||||
<select id="sim-status">
|
||||
<option value="200">200 成功</option>
|
||||
<option value="201">201 创建成功</option>
|
||||
<option value="204">204 删除成功</option>
|
||||
<option value="400">400 请求错误</option>
|
||||
<option value="401">401 未认证</option>
|
||||
<option value="403">403 权限不足</option>
|
||||
<option value="404">404 资源不存在</option>
|
||||
<option value="500">500 服务端异常</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="modal-actions">
|
||||
<button class="btn btn-outline" id="sim-cancel">取消</button>
|
||||
<button class="btn btn-primary" id="sim-send">发送请求</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="toast" id="toast"></div>
|
||||
|
||||
<script src="assets/audit-core.js"></script>
|
||||
<script src="assets/mock-data.js"></script>
|
||||
<script src="assets/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,250 @@
|
||||
/**
|
||||
* 操作审计 Demo · 核心逻辑单元测试
|
||||
*
|
||||
* 运行:node --test demo/test/audit-core.test.mjs
|
||||
* 覆盖对象(与技术方案第 7 节测试策略对应):
|
||||
* - shouldCapture 捕获规则(D1)
|
||||
* - resolveResource 资源解析(5.2)
|
||||
* - applyFilters 筛选(产品设计 4.2)
|
||||
* - paginate 分页
|
||||
* - countExpired 保留期清理(D5)
|
||||
* - MockData 模拟数据生成器(确定性、字段完整性)
|
||||
*/
|
||||
import { createRequire } from 'node:module';
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const AuditCore = require('../assets/audit-core.js');
|
||||
const MockData = require('../assets/mock-data.js');
|
||||
|
||||
// ---------------- shouldCapture(D1 捕获规则) ----------------
|
||||
test('shouldCapture: 已登录用户对 /apis/** 的写操作应记录', () => {
|
||||
assert.deepEqual(
|
||||
AuditCore.shouldCapture({ method: 'POST', path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true }),
|
||||
{ captured: true, reason: '已登录用户对 /apis/** 的写操作,予以记录' }
|
||||
);
|
||||
assert.equal(AuditCore.shouldCapture({ method: 'put', path: '/apis/v1alpha1/configmaps/system', authenticated: true }).captured, true);
|
||||
assert.equal(AuditCore.shouldCapture({ method: 'DELETE', path: '/apis/content.halo.run/v1alpha1/posts/x', authenticated: true }).captured, true);
|
||||
assert.equal(AuditCore.shouldCapture({ method: 'PATCH', path: '/apis/v1alpha1/users/x', authenticated: true }).captured, true);
|
||||
});
|
||||
|
||||
test('shouldCapture: 读操作不记录', () => {
|
||||
for (const method of ['GET', 'HEAD', 'OPTIONS']) {
|
||||
const r = AuditCore.shouldCapture({ method, path: '/apis/content.halo.run/v1alpha1/posts', authenticated: true });
|
||||
assert.equal(r.captured, false, method + ' 不应被记录');
|
||||
assert.match(r.reason, /写操作/);
|
||||
}
|
||||
});
|
||||
|
||||
test('shouldCapture: /apis/** 下匿名请求不记录(401/403 场景)', () => {
|
||||
const r = AuditCore.shouldCapture({ method: 'POST', path: '/apis/content.halo.run/v1alpha1/posts', authenticated: false });
|
||||
assert.equal(r.captured, false);
|
||||
assert.match(r.reason, /匿名/);
|
||||
});
|
||||
|
||||
test('shouldCapture: 登录/登出端点始终记录(含匿名登录尝试)', () => {
|
||||
assert.equal(AuditCore.shouldCapture({ method: 'POST', path: '/login', authenticated: false }).captured, true);
|
||||
assert.equal(AuditCore.shouldCapture({ method: 'POST', path: '/logout', authenticated: true }).captured, true);
|
||||
});
|
||||
|
||||
test('shouldCapture: /apis/** 之外的普通路径不记录', () => {
|
||||
const r = AuditCore.shouldCapture({ method: 'POST', path: '/console/posts', authenticated: true });
|
||||
assert.equal(r.captured, false);
|
||||
assert.match(r.reason, /捕获范围/);
|
||||
});
|
||||
|
||||
test('shouldCapture: 路径匹配 /apis/ 前缀但匿名时,匿名规则优先于方法规则(与 D1 描述一致)', () => {
|
||||
// GET + 匿名:期望原因是"匿名",而非"读操作"
|
||||
const r = AuditCore.shouldCapture({ method: 'GET', path: '/apis/v1alpha1/posts', authenticated: false });
|
||||
assert.equal(r.captured, false);
|
||||
assert.match(r.reason, /匿名/);
|
||||
});
|
||||
|
||||
// ---------------- resolveResource(5.2 资源解析) ----------------
|
||||
test('resolveResource: 单资源路径 → plural + name', () => {
|
||||
assert.deepEqual(
|
||||
AuditCore.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz'),
|
||||
{ resourceType: 'posts', resourceName: 'xyz' }
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveResource: 集合路径 → 仅 plural', () => {
|
||||
assert.deepEqual(
|
||||
AuditCore.resolveResource('/apis/content.halo.run/v1alpha1/posts'),
|
||||
{ resourceType: 'posts', resourceName: '' }
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveResource: 更深层子资源取前两段,完整路径由 path 兜底', () => {
|
||||
assert.deepEqual(
|
||||
AuditCore.resolveResource('/apis/api.content.halo.run/v1alpha1/posts/xyz/publish'),
|
||||
{ resourceType: 'posts', resourceName: 'xyz' }
|
||||
);
|
||||
});
|
||||
|
||||
test('resolveResource: /login、/logout → auth', () => {
|
||||
assert.deepEqual(AuditCore.resolveResource('/login'), { resourceType: 'auth', resourceName: '' });
|
||||
assert.deepEqual(AuditCore.resolveResource('/logout'), { resourceType: 'auth', resourceName: '' });
|
||||
});
|
||||
|
||||
test('resolveResource: 非 /apis 路径与畸形路径 → other', () => {
|
||||
assert.equal(AuditCore.resolveResource('/console').resourceType, 'other');
|
||||
assert.equal(AuditCore.resolveResource('/apis/only-group').resourceType, 'other');
|
||||
});
|
||||
|
||||
// ---------------- isSuccess / applyFilters(4.2 筛选) ----------------
|
||||
const NOW = new Date('2026-11-21T12:00:00Z').getTime();
|
||||
|
||||
function fixture() {
|
||||
return [
|
||||
{ id: 'a1', timestamp: '2026-11-21T10:00:00Z', username: 'guichumo', method: 'PUT', path: '/apis/content.halo.run/v1alpha1/posts/hello', resourceType: 'posts', resourceName: 'hello', statusCode: 200 },
|
||||
{ id: 'a2', timestamp: '2026-11-21T09:00:00Z', username: 'editor.zhang', method: 'POST', path: '/apis/api.content.halo.run/v1alpha1/posts/hello/publish', resourceType: 'posts', resourceName: 'hello', statusCode: 500 },
|
||||
{ id: 'a3', timestamp: '2026-11-20T08:00:00Z', username: 'guichumo', method: 'POST', path: '/login', resourceType: 'auth', resourceName: '', statusCode: 401 },
|
||||
{ id: 'a4', timestamp: '2026-11-10T08:00:00Z', username: 'writer.li', method: 'PUT', path: '/apis/v1alpha1/configmaps/system', resourceType: 'configmaps', resourceName: 'system', statusCode: 200 }
|
||||
];
|
||||
}
|
||||
|
||||
test('applyFilters: 按操作者筛选', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { operator: 'guichumo', now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a1', 'a3']);
|
||||
});
|
||||
|
||||
test('applyFilters: 按资源类型筛选', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { resourceType: 'posts', now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a1', 'a2']);
|
||||
});
|
||||
|
||||
test('applyFilters: 按动作筛选(方法名大小写不敏感)', () => {
|
||||
const post = AuditCore.applyFilters(fixture(), { method: 'POST', now: NOW });
|
||||
assert.deepEqual(post.map(l => l.id), ['a2', 'a3']);
|
||||
const put = AuditCore.applyFilters(fixture(), { method: 'put', now: NOW });
|
||||
assert.deepEqual(put.map(l => l.id), ['a1', 'a4']);
|
||||
});
|
||||
|
||||
test('applyFilters: 动作 + 结果组合', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { method: 'POST', result: 'failure', now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a2', 'a3']);
|
||||
});
|
||||
|
||||
test('applyFilters: 按结果筛选(成功/失败)', () => {
|
||||
const ok = AuditCore.applyFilters(fixture(), { result: 'success', now: NOW });
|
||||
assert.deepEqual(ok.map(l => l.id), ['a1', 'a4']);
|
||||
const bad = AuditCore.applyFilters(fixture(), { result: 'failure', now: NOW });
|
||||
assert.deepEqual(bad.map(l => l.id), ['a2', 'a3']);
|
||||
});
|
||||
|
||||
test('applyFilters: 时间范围(24h 只含今天、30d 含上周)', () => {
|
||||
const day = AuditCore.applyFilters(fixture(), { timeRange: '24h', now: NOW });
|
||||
assert.deepEqual(day.map(l => l.id), ['a1', 'a2']);
|
||||
const month = AuditCore.applyFilters(fixture(), { timeRange: '30d', now: NOW });
|
||||
assert.deepEqual(month.map(l => l.id), ['a1', 'a2', 'a3', 'a4']);
|
||||
});
|
||||
|
||||
test('applyFilters: 关键字匹配资源名称与路径', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { keyword: 'hello', now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a1', 'a2']);
|
||||
const byPath = AuditCore.applyFilters(fixture(), { keyword: 'configmaps', now: NOW });
|
||||
assert.deepEqual(byPath.map(l => l.id), ['a4']);
|
||||
});
|
||||
|
||||
test('applyFilters: 组合条件', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { resourceType: 'posts', result: 'failure', now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a2']);
|
||||
});
|
||||
|
||||
test('applyFilters: 结果按时间倒序排列', () => {
|
||||
const out = AuditCore.applyFilters(fixture(), { now: NOW });
|
||||
assert.deepEqual(out.map(l => l.id), ['a1', 'a2', 'a3', 'a4']);
|
||||
});
|
||||
|
||||
test('applyFilters: 不修改入参数组', () => {
|
||||
const logs = fixture();
|
||||
AuditCore.applyFilters(logs, { now: NOW });
|
||||
assert.equal(logs.length, 4);
|
||||
});
|
||||
|
||||
// ---------------- paginate ----------------
|
||||
test('paginate: 基础分页与元信息', () => {
|
||||
const items = Array.from({ length: 25 }, (_, i) => i);
|
||||
const p = AuditCore.paginate(items, 2, 10);
|
||||
assert.equal(p.total, 25);
|
||||
assert.equal(p.pages, 3);
|
||||
assert.equal(p.page, 2);
|
||||
assert.deepEqual(p.items, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
|
||||
});
|
||||
|
||||
test('paginate: 页码越界自动收敛', () => {
|
||||
const items = Array.from({ length: 15 }, (_, i) => i);
|
||||
assert.equal(AuditCore.paginate(items, 99, 10).page, 2);
|
||||
assert.equal(AuditCore.paginate(items, 0, 10).page, 1);
|
||||
});
|
||||
|
||||
test('paginate: 空结果时仍返回 1 页', () => {
|
||||
const p = AuditCore.paginate([], 1, 10);
|
||||
assert.deepEqual({ total: p.total, pages: p.pages, items: p.items }, { total: 0, pages: 1, items: [] });
|
||||
});
|
||||
|
||||
// ---------------- countExpired(D5 保留期清理) ----------------
|
||||
test('countExpired: 统计超过保留期的记录', () => {
|
||||
const logs = fixture(); // NOW 为 2026-11-21,a4 是 11-10
|
||||
assert.equal(AuditCore.countExpired(logs, 5, NOW), 1); // a4 过期
|
||||
assert.equal(AuditCore.countExpired(logs, 90, NOW), 0); // 全部在保留期内
|
||||
});
|
||||
|
||||
// ---------------- MockData 模拟数据 ----------------
|
||||
const FIXED_NOW = new Date('2026-11-21T12:00:00Z').getTime();
|
||||
const REQUIRED_FIELDS = ['id', 'timestamp', 'username', 'method', 'path', 'resourceType', 'resourceName', 'statusCode', 'remoteIp', 'userAgent'];
|
||||
|
||||
test('MockData.generateLogs: 同一种子两次生成结果完全一致(确定性)', () => {
|
||||
const a = MockData.generateLogs(FIXED_NOW);
|
||||
const b = MockData.generateLogs(FIXED_NOW);
|
||||
assert.equal(JSON.stringify(a), JSON.stringify(b));
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 记录数量充足且字段完整', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
assert.ok(logs.length >= 120, '应有 120+ 条记录,实际 ' + logs.length);
|
||||
for (const log of logs) {
|
||||
for (const field of REQUIRED_FIELDS) {
|
||||
assert.ok(log[field] !== undefined && log[field] !== null, `记录 ${log.id} 缺少字段 ${field}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 按时间倒序且 id 唯一', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
const ids = new Set(logs.map(l => l.id));
|
||||
assert.equal(ids.size, logs.length, 'id 应唯一');
|
||||
for (let i = 1; i < logs.length; i++) {
|
||||
const prev = new Date(logs[i - 1].timestamp).getTime();
|
||||
const curr = new Date(logs[i].timestamp).getTime();
|
||||
assert.ok(prev >= curr, `第 ${i} 条时间应不晚于下一条`);
|
||||
}
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 包含登录审计与"未知用户"记录(产品设计 4.1)', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
assert.ok(logs.some(l => l.resourceType === 'auth' && l.statusCode === 200), '应有登录成功记录');
|
||||
assert.ok(logs.some(l => l.resourceType === 'auth' && l.username === '未知用户'), '应有登录失败记"未知用户"的记录');
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 资源解析结果与 resolveResource 规则一致(模拟真实管线)', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
for (const log of logs) {
|
||||
const expect = AuditCore.resolveResource(log.path);
|
||||
assert.equal(log.resourceType, expect.resourceType, log.path);
|
||||
assert.equal(log.resourceName, expect.resourceName, log.path);
|
||||
}
|
||||
});
|
||||
|
||||
test('MockData.generateLogs: 覆盖全部捕获方法与失败场景', () => {
|
||||
const logs = MockData.generateLogs(FIXED_NOW);
|
||||
const methods = new Set(logs.map(l => l.method));
|
||||
for (const m of ['POST', 'PUT', 'DELETE']) {
|
||||
assert.ok(methods.has(m), '应包含 ' + m + ' 操作');
|
||||
}
|
||||
assert.ok(logs.some(l => !AuditCore.isSuccess(l.statusCode)), '应包含失败操作记录');
|
||||
assert.ok(logs.some(l => l.statusCode === 403), '应包含越权 403 记录');
|
||||
assert.ok(logs.some(l => l.statusCode === 500), '应包含服务端 500 记录');
|
||||
});
|
||||
Reference in New Issue
Block a user