/** * 操作审计 · 核心纯函数(浏览器与 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 }; });