- 列表/筛选对齐真实 Console:八维筛选、语义动作中文描述、登录失败结果语义 - 详情抽屉展示字段级 diff(脱敏/截断/封顶)与 AuditLog Extension 原始 JSON - 新增行内「历史」快捷、按筛选条件导出 UTF-8 BOM CSV - 设置页覆盖审计开关/字段变更/系统变更/保留期与登录失败告警(含测试与模拟触发) - 模拟器支持 HTTP 捕获管线与系统内部变更两条通道 - 核心纯函数重写并扩充至 56 个单元用例
1150 lines
38 KiB
JavaScript
1150 lines
38 KiB
JavaScript
/**
|
||
* 操作审计 · 核心纯函数(浏览器与 Node 测试共用)
|
||
*
|
||
* 与插件当前实现保持一致(单一事实来源:后端 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 / 网络能力,仅做纯计算,便于单元测试。
|
||
*/
|
||
(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_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]);
|
||
});
|
||
}
|
||
|
||
// ---------------------------------------------------------------- 捕获与解析
|
||
|
||
/**
|
||
* 捕获规则(CaptureRule + AuthEndpointAuditWebFilter):
|
||
* - /apis/** 下已登录用户的写操作(POST/PUT/DELETE/PATCH);
|
||
* - /login、/logout 认证端点始终记录(链首过滤器捕获,含登录失败与失败回显);
|
||
* - /apis/** 下认证后仍为匿名主体的请求不记录(401/403 场景)。
|
||
*
|
||
* @param {{method: string, path: string, authenticated: boolean}} options
|
||
* @returns {{captured: boolean, channel: 'auth'|'http'|'none', reason: string}}
|
||
*/
|
||
function shouldCapture(options) {
|
||
var method = normalizeMethod(options && options.method);
|
||
var fullPath = String((options && options.path) || '').trim();
|
||
var clean = pathWithoutQuery(fullPath);
|
||
var authenticated = !!(options && options.authenticated);
|
||
|
||
if (AUTH_ENDPOINTS.indexOf(clean) !== -1) {
|
||
return {
|
||
captured: true,
|
||
channel: 'auth',
|
||
reason: '认证端点始终记录(登录/登出,含登录失败与失败回显)'
|
||
};
|
||
}
|
||
if (clean.indexOf('/apis/') !== 0) {
|
||
return {
|
||
captured: false,
|
||
channel: 'none',
|
||
reason: '路径不在捕获范围(仅 /apis/** 写操作与 /login、/logout)'
|
||
};
|
||
}
|
||
if (!authenticated) {
|
||
return {
|
||
captured: false,
|
||
channel: 'none',
|
||
reason: '匿名请求不记录(认证后仍为匿名主体的 401/403 场景)'
|
||
};
|
||
}
|
||
if (WRITE_METHODS.indexOf(method) === -1) {
|
||
return {
|
||
captured: false,
|
||
channel: 'none',
|
||
reason: '仅记录写操作(POST/PUT/DELETE/PATCH),读操作不记录'
|
||
};
|
||
}
|
||
return {
|
||
captured: true,
|
||
channel: 'http',
|
||
reason: '已登录用户对 /apis/** 的写操作,予以记录'
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 资源解析(ResourceResolver):
|
||
* /apis/{group}/{version}/{plural}[/{name}][/...] → plural / name
|
||
* /login、/logout → auth;其余 → other。
|
||
*/
|
||
function resolveResource(path) {
|
||
var clean = pathWithoutQuery(path);
|
||
if (AUTH_ENDPOINTS.indexOf(clean) !== -1) {
|
||
return { resourceType: 'auth', resourceName: null };
|
||
}
|
||
if (clean.indexOf('/apis/') !== 0) {
|
||
return { resourceType: 'other', resourceName: null };
|
||
}
|
||
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: null };
|
||
}
|
||
return { resourceType: segs[3], resourceName: segs.length >= 5 && segs[4] ? segs[4] : null };
|
||
}
|
||
|
||
/** 推导语义动作键(与 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;
|
||
}
|
||
|
||
/**
|
||
* 结果徽标:登录失败(HTTP 可能为 200/302)显示「失败」,
|
||
* 其余按状态码(2xx/3xx 绿、其余红)。
|
||
*/
|
||
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 (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;
|
||
}
|
||
}
|
||
return true;
|
||
}).sort(function (a, b) {
|
||
return new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime();
|
||
});
|
||
}
|
||
|
||
/** 分页(page 从 1 开始,越界自动收敛)。 */
|
||
function paginate(items, page, size) {
|
||
var total = items.length;
|
||
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) * pageSize;
|
||
return {
|
||
items: items.slice(start, start + pageSize),
|
||
total: total,
|
||
pages: pages,
|
||
page: current
|
||
};
|
||
}
|
||
|
||
/** 保留期清理:统计超过保留天数的记录条数。 */
|
||
function countExpired(logs, retentionDays, now) {
|
||
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_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,
|
||
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,
|
||
csvEscape: csvEscape,
|
||
toCsv: toCsv,
|
||
createLoginFailureTracker: createLoginFailureTracker,
|
||
alertPayload: alertPayload
|
||
};
|
||
});
|