diff --git a/.trae/documents/audit-log-feature.md b/.trae/documents/audit-log-feature.md deleted file mode 100644 index 392259b6d..000000000 --- a/.trae/documents/audit-log-feature.md +++ /dev/null @@ -1,437 +0,0 @@ -# 审计日志功能实施计划(MVP 版本) - -## 一、摘要 - -为 Certd 系统增加基础审计日志功能,记录用户关键操作(流水线增删改/执行、授权管理、站点监控、通知设置、API密钥、用户管理、角色权限、项目管理、系统设置等),支持管理员和用户分别在管理后台和用户端查看操作日志。 - -**关键发现**:`cd_audit_log` 表已通过数据库迁移 v10038 创建,`AuditLogEntity` 实体已定义,字段完整可直接使用,写入和查询功能完全未实现。 - -> **MVP 范围**:仅实现简要记录(谁在何时对什么做了什么),流水线差异对比(diffContent)后续版本再补充。 - -## 二、当前状态分析 - -### 已存在的基础设施 - -| 组件 | 路径 | 状态 | -|------|------|------| -| 审计日志表 | `cd_audit_log`(迁移 v10038__admin_mode.sql) | ✅ 已创建 | -| 审计日志实体 | `packages/ui/certd-server/src/modules/sys/enterprise/entity/audit-log.ts` | ✅ 已定义 | -| BaseService 钩子 | `BaseService.modifyAfter(data)` | ✅ 已预留(空实现) | - -### 审计日志表字段 - -| 字段 | 类型 | 说明 | -|------|------|------| -| `id` | number (PK) | 主键 | -| `userId` | number | 操作人ID | -| `userName` | string(128) | 操作人用户名 | -| `projectId` | number | 项目ID(企业模式) | -| `projectName` | string(512) | 项目名称 | -| `type` | string(128) | 操作模块类型 | -| `action` | string(128) | 操作动作 | -| `content` | text | 操作内容摘要描述 | -| `ipAddress` | string(128) | 操作人IP | -| `createTime` | Date | 创建时间 | -| `updateTime` | Date | 修改时间 | - -**无新增字段**,直接使用现有表结构。 - -### `ctx.user` 可用字段 - -JWT 登录路径:`{ id, username, roles }` -OpenKey 认证路径:`{ id, roles, projectId }`(**无 username**) - -> **注意**:审计时若需 username 而 ctx.user.username 不存在,需要通过 userId 查询 UserEntity 获取。 - -## 三、需求范围 - -### 审计类型(type)与动作(action) - -| 序号 | 模块 | type | action | 说明 | -|------|------|------|--------|------| -| 1 | 流水线 | `pipeline` | `add`/`update`/`delete`/`execute`/`cancel`/`batchDelete`/`batchUpdate` | 记录流水线的增删改、手动执行、取消、批量操作 | -| 2 | 授权管理 | `access` | `add`/`update`/`delete` | 记录云厂商授权凭据的增删改 | -| 3 | 站点监控 | `monitor` | `add`/`update`/`delete`/`batchDelete` | 记录站点证书监控的增删改 | -| 4 | 通知设置 | `notification` | `add`/`update`/`delete` | 记录通知配置的增删改 | -| 5 | API密钥 | `openKey` | `add`/`update`/`delete` | 记录开放接口密钥的增删改 | -| 6 | 用户管理 | `user` | `add`/`update`/`delete` | 记录系统管理员对用户的增删改 | -| 7 | 角色管理 | `role` | `add`/`update`/`delete` | 记录角色的增删改 | -| 8 | 权限管理 | `permission` | `add`/`update`/`delete` | 记录权限的增删改 | -| 9 | 项目管理 | `project` | `add`/`update`/`delete`/`disable` | 记录项目的增删改/启停 | -| 10 | 系统设置 | `settings` | `update` | 记录系统配置的修改 | - -### 关键策略 - -- **存储**:仅数据库(使用已有 `cd_audit_log` 表,无新增字段/迁移) -- **粒度**:简要记录(谁对什么做了什么),无差异对比 -- **保留策略**:按 90 天自动清理(硬编码,不提供配置界面,后续迭代再补配置) -- **前端**:管理后台(`/sys/audit` 查看全部) + 用户端(`/certd/audit` 仅查看自己的) - -## 四、实施方案 - -### 4.1 后端:新增文件 - -#### 4.1.1 AuditService - -**文件**:`packages/ui/certd-server/src/modules/sys/enterprise/service/audit-service.ts` - -```typescript -@Provide() -export class AuditService { - @Inject() - dataSourceManager: TypeORMDataSourceManager; - - getRepository(): Repository { - return this.dataSourceManager.getDataSource('default').getRepository(AuditLogEntity); - } - - // 写入审计日志 - async log(params: { - userId: number; - type: string; - action: string; - content: string; - username?: string; - projectId?: number; - projectName?: string; - ipAddress?: string; - }): Promise; - - // 分页查询 - async page(pageReq: PageReq): Promise; - - // 删除指定天数之前的日志 - async cleanExpired(retentionDays: number): Promise; -} -``` - -**关键实现细节**: -- `log()` 中若 `username` 为空,通过 `userId` 查 `UserEntity` 获取,查询失败也写入(username留空) -- `log()` 用 try-catch 包裹,写入失败仅 log error,不影响主业务 -- `page()` 不做额外过滤,由 Controller 层控制 userId 过滤逻辑 -- `cleanExpired()` 直接 DELETE WHERE `create_time < now - retentionDays` - -#### 4.1.2 审计日志 Controller(管理后台) - -**文件**:`packages/ui/certd-server/src/controller/sys/audit/audit-controller.ts` - -路由前缀:`/api/sys/audit` - -```typescript -@Provide() -@ApiTags(['audit']) -@Controller('/api/sys/audit') -export class SysAuditLogController { - @Inject() - auditService: AuditService; - - // POST /page - 分页查询(不过滤 userId,支持 type/action/userId/时间范围 筛选) - // POST /delete - 删除单条日志 - // POST /clean - 手动清理过期日志 -} -``` - -权限:`sys:settings:view`(查看)/ `sys:settings:edit`(删除/清理) - -#### 4.1.3 审计日志 Controller(用户端) - -**文件**:`packages/ui/certd-server/src/controller/user/audit/audit-controller.ts` - -路由前缀:`/api/pi/audit` - -```typescript -@Provide() -@ApiTags(['audit']) -@Controller('/api/pi/audit') -export class AuditLogController extends BaseController { - @Inject() - auditService: AuditService; - - // POST /page - 分页查询(自动过滤当前 userId) -} -``` - -权限:`authOnly` - -#### 4.1.4 审计日志清理 Cron 任务 - -在 `AuditService` 中注册 cron:每天凌晨 3:00 执行,保留 90 天。 - -> 清理注册方式参考 `PipelineService` 中的 `this.cron.register()` 模式。 - -### 4.2 后端:修改现有文件 - -在以下 Controller 中注入 `AuditService` 并在关键方法中调用 `this.auditService.log(...)`。 - -#### 4.2.1 PipelineController(流水线) - -**文件**:`packages/ui/certd-server/src/controller/user/pipeline/pipeline-controller.ts` - -| 方法 | 审计 action | content 模板 | -|------|------------|-------------| -| `save` (新增, bean.id ≤ 0) | `add` | `创建了流水线「{title}」(ID:{id})` | -| `save` (修改, bean.id > 0) | `update` | `修改了流水线「{title}」(ID:{id})` | -| `delete` | `delete` | `删除了流水线(ID:{id})` | -| `trigger` | `execute` | `手动执行了流水线「{title}」(ID:{id})` | -| `cancel` | `cancel` | `取消了流水线执行(historyId:{historyId})` | -| `batchDelete` | `batchDelete` | `批量删除了{count}条流水线` | -| `batchUpdateGroup` | `batchUpdate` | `批量修改了{count}条流水线分组` | -| `batchUpdateTrigger` | `batchUpdate` | `批量修改了{count}条流水线触发器` | -| `batchUpdateNotification` | `batchUpdate` | `批量修改了{count}条流水线通知` | -| `batchUpdateCertApplyOptions` | `batchUpdate` | `批量修改了{count}条流水线证书申请配置` | -| `batchRerun` | `execute` | `批量重新执行了{count}条流水线` | -| `batchTransfer` | `batchUpdate` | `批量迁移了{count}条流水线` | -| `refreshWebhookKey` | `update` | `刷新了流水线(ID:{id})的Webhook密钥` | - -**接入方式**:在方法末尾、返回 `this.ok(...)` 之前调用 `this.auditService.log(...)`。对 `save` 方法,根据 `bean.id > 0` 区分 add/update。对 `delete`/`trigger`/`cancel` 等方法,由于方法签名限制,content 中尽量使用已有变量,查不到标题就用 ID 描述。 - -#### 4.2.2 AccessController(授权管理) - -**文件**:`packages/ui/certd-server/src/controller/user/pipeline/access-controller.ts` - -| 方法 | 审计 action | content 模板 | -|------|------------|-------------| -| `add` | `add` | `新增了授权「{name}」(ID:{id}, 类型:{type})` | -| `update` | `update` | `修改了授权「{name}」(ID:{id})` | -| `delete` | `delete` | `删除了授权(ID:{id})` | - -#### 4.2.3 SiteInfoController(站点监控) - -**文件**:`packages/ui/certd-server/src/controller/user/monitor/site-info-controller.ts` - -| 方法 | 审计 action | content 模板 | -|------|------------|-------------| -| `add` | `add` | `新增了站点监控「{name}」(ID:{id}, 域名:{domain})` | -| `update` | `update` | `修改了站点监控「{name}」(ID:{id})` | -| `delete` | `delete` | `删除了站点监控(ID:{id})` | -| `batchDelete` | `batchDelete` | `批量删除了{count}条站点监控` | - -#### 4.2.4 NotificationController(通知设置) - -**文件**:`packages/ui/certd-server/src/controller/user/pipeline/notification-controller.ts` - -| 方法 | 审计 action | content 模板 | -|------|------------|-------------| -| `add` | `add` | `新增了通知配置「{name}」(ID:{id}, 类型:{type})` | -| `update` | `update` | `修改了通知配置「{name}」(ID:{id})` | -| `delete` | `delete` | `删除了通知配置(ID:{id})` | - -#### 4.2.5 OpenKeyController(API密钥) - -**文件**:`packages/ui/certd-server/src/controller/user/open/open-key-controller.ts` - -| 方法 | 审计 action | content 模板 | -|------|------------|-------------| -| `add` | `add` | `新增了API密钥(ID:{id}, scope:{scope})` | -| `update` | `update` | `修改了API密钥(ID:{id})` | -| `delete` | `delete` | `删除了API密钥(ID:{id})` | - -#### 4.2.6 UserController(用户管理 - 管理后台) - -**文件**:`packages/ui/certd-server/src/controller/sys/authority/user-controller.ts` - -| 方法 | 审计 action | content 模板 | -|------|------------|-------------| -| `add` | `add` | `新增了用户「{username}」(ID:{id})` | -| `update` | `update` | `修改了用户「{username}」(ID:{id})` | -| `delete` | `delete` | `删除了用户(ID:{id})` | - -#### 4.2.7 RoleController(角色管理 - 管理后台) - -**文件**:`packages/ui/certd-server/src/controller/sys/authority/role-controller.ts` - -| 方法 | 审计 action | content 模板 | -|------|------------|-------------| -| `add` | `add` | `新增了角色「{name}」(ID:{id})` | -| `update` | `update` | `修改了角色「{name}」(ID:{id})` | -| `delete` | `delete` | `删除了角色(ID:{id})` | - -#### 4.2.8 PermissionController(权限管理 - 管理后台) - -**文件**:`packages/ui/certd-server/src/controller/sys/authority/permission-controller.ts` - -| 方法 | 审计 action | content 模板 | -|------|------------|-------------| -| `add` | `add` | `新增了权限「{name}」(ID:{id})` | -| `update` | `update` | `修改了权限「{name}」(ID:{id})` | -| `delete` | `delete` | `删除了权限(ID:{id})` | - -#### 4.2.9 ProjectController(项目管理 - 管理后台) - -**文件**:`packages/ui/certd-server/src/controller/sys/enterprise/project-controller.ts` - -| 方法 | 审计 action | content 模板 | -|------|------------|-------------| -| `add` | `add` | `新增了项目「{name}」(ID:{id})` | -| `update` | `update` | `修改了项目「{name}」(ID:{id})` | -| `delete` | `delete` | `删除了项目(ID:{id})` | -| `setDisabled` | `disable` | `{启用\|禁用了}项目「{name}」(ID:{id})` | - -#### 4.2.10 系统设置 Controller - -- **SysSettingsController**:`save` → `type=settings, action=update, content=修改了系统设置` -- **SysSafeSettingsController**:`save` → `type=settings, action=update, content=修改了安全设置` - -### 4.3 后端:数据库迁移 - -**无需新增迁移**。使用已有 `cd_audit_log` 表,无新增字段。 - -### 4.4 后端:通用辅助 - -#### 4.4.1 审计日志提取 helper - -创建一个轻量的提取函数,减少 Controller 中的重复代码: - -```typescript -// 在 controller 中各方法调用示例 -async add(@Body(ALL) bean: XxxEntity) { - const result = await this.service.add(bean); - await this.auditService.log({ - userId: this.getUserId(), - username: this.ctx.user?.username, - type: 'xxx', - action: 'add', - content: `新增了xxx「${bean.name}」(ID:${result.id})`, - ipAddress: this.ctx.ip, - }); - return this.ok(result); -} -``` - -### 4.5 前端:新增文件 - -#### 4.5.1 用户端审计日志页 - -``` -packages/ui/certd-client/src/views/certd/audit/ -├── api.ts -├── crud.tsx -└── index.vue -``` - -- **路由**:`/certd/audit` -- **菜单位置**:放在「设置」子菜单中 -- **权限**:`authOnly` -- **功能**:展示当前用户的操作日志,支持按 type/action/时间范围 筛选 -- **列**:操作时间、操作类型(type)、动作(action)、内容(content)、IP地址 - -#### 4.5.2 管理后台审计日志页 - -``` -packages/ui/certd-client/src/views/sys/audit/ -├── api.ts -├── crud.tsx -└── index.vue -``` - -- **路由**:`/sys/audit` -- **菜单位置**:放在「系统管理」菜单中 -- **权限**:`sys:settings:view` -- **功能**:展示所有用户的操作日志,支持按 userId/type/action/时间范围 筛选 -- **列**:操作时间、操作人(userName)、操作类型(type)、动作(action)、内容(content)、IP地址 -- **额外操作**:删除单条、手动清理过期日志按钮(需 `sys:settings:edit` 权限) - -#### 4.5.3 路由配置 - -**修改** `packages/ui/certd-client/src/router/source/modules/certd.ts`,在 settings children 中添加: - -```typescript -{ - title: "certd.auditLog", - name: "AuditLog", - path: "/certd/audit", - component: "/certd/audit/index.vue", - meta: { - icon: "ion:document-text-outline", - auth: true, - keepAlive: true, - }, -} -``` - -**修改** `packages/ui/certd-client/src/router/source/modules/sys.ts`,在 SysRoot children 中添加: - -```typescript -{ - title: "certd.sysResources.auditLog", - name: "SysAuditLog", - path: "/sys/audit", - component: "/sys/audit/index.vue", - meta: { - icon: "ion:document-text-outline", - permission: "sys:settings:view", - keepAlive: true, - auth: true, - }, -} -``` - -#### 4.5.4 国际化 - -在 `packages/ui/certd-client/src/locales/` 的语言包中添加: - -```json -{ - "certd.auditLog": "操作日志", - "certd.sysResources.auditLog": "操作日志", - "audit.type": "操作类型", - "audit.action": "操作动作", - "audit.content": "内容", - "audit.ipAddress": "IP地址", - "audit.userName": "操作人", - "audit.createTime": "操作时间", - "audit.cleanExpired": "清理过期日志" -} -``` - -## 五、实现顺序 - -1. **Phase 1:AuditService** - - 创建 `AuditService`(`log`、`page`、`cleanExpired` 方法) - - 注册审计日志清理 cron(默认保留 90 天) - -2. **Phase 2:Controller 接入** - - `SysAuditLogController` + `AuditLogController`(日志查询接口) - - 逐个 Controller 接入审计日志: - - PipelineController - - AccessController - - SiteInfoController - - NotificationController - - OpenKeyController - - 管理后台 User/Role/Permission/Project/Settings Controllers - -3. **Phase 3:前端** - - 用户端 `/certd/audit` 页面 - - 管理后台 `/sys/audit` 页面 - - 路由 + 国际化 - -4. **Phase 4:测试** - - AuditService 单元测试 - - 验证各模块操作是否正确写入日志 - -## 六、验证步骤 - -### 后端 - -1. 运行单元测试:`cd packages/ui/certd-server && npm run test:unit` -2. 手动验证: - - 创建/修改/删除流水线 → 检查 `cd_audit_log` 表 - - 手动触发流水线 → 检查 execute 记录 - - 增删改授权/监控/通知/密钥 → 检查对应记录 - - 管理后台用户/角色/权限/项目/设置操作 → 检查记录 - -### 前端 - -1. 用户端 `/certd/audit` → 仅显示当前用户日志 -2. 管理后台 `/sys/audit` → 显示全部日志,支持筛选和清理 -3. 运行 ESLint/Prettier - -## 七、注意事项 - -1. **不记录敏感数据**:content 中不记录密码、密钥等敏感信息 -2. **不记录查询操作**:仅记录变更操作(add/update/delete/execute),不记录 page/list/info -3. **异常不影响主流程**:审计日志写入失败用 try-catch 包裹,仅 log error -4. **username 兼容性**:JWT 路径下 `ctx.user.username` 有值;OpenKey 路径下需从 UserService 查询 -5. **事务隔离**:审计日志独立写入,避免主业务事务回滚时丢失 -6. **批量操作**:批量操作一条审计记录记录概要信息,不为每个对象单独记录 -7. **后续迭代预留**:diffContent 字段和系统设置中的审计配置项在后续版本补充,本次不做迁移 diff --git a/.trae/documents/plugin-on-demand-dependency-loading.md b/.trae/documents/plugin-on-demand-dependency-loading.md deleted file mode 100644 index 62c4bbfba..000000000 --- a/.trae/documents/plugin-on-demand-dependency-loading.md +++ /dev/null @@ -1,412 +0,0 @@ -# 插件依赖按需加载方案 - -## 背景与目标 - -### 当前问题 -- `packages/ui/certd-server/node_modules` 包含 50+ 个插件的所有依赖,体积庞大 -- 大量云厂商 SDK(AWS、阿里云、腾讯云、华为云等)只在特定插件中使用 -- 用户通常只使用少数几个插件,但必须安装所有依赖 - -### 目标 -实现依赖的按需下载和加载: -1. 插件依赖独立管理,不占用主 `node_modules` 空间 -2. 只有当用户首次使用某插件时,才动态下载该插件需要的依赖 -3. 依赖安装完成后,通过 `await import()` 从独立路径加载 -4. 保持现有插件代码的最小改动 - -## 当前架构分析 - -### 插件加载机制 -- 插件位于 `packages/ui/certd-server/src/plugins/` 下(50+ 个插件目录) -- `AutoLoadPlugins` 类在启动时扫描 `dist/plugins` 目录并动态导入 -- 插件注册到不同的 registry:`accessRegistry`, `pluginRegistry`, `dnsProviderRegistry` 等 -- 插件代码已经使用 `await import()` 进行懒加载(如 `await import("@aws-sdk/client-acm")`) - -### 重型依赖分布 -从 `packages/ui/certd-server/package.json` 分析,以下依赖体积大且仅特定插件使用: - -**云厂商 SDK(按插件分组):** -- **AWS 插件**:`@aws-sdk/client-acm`, `@aws-sdk/client-cloudfront`, `@aws-sdk/client-iam`, `@aws-sdk/client-route-53`, `@aws-sdk/client-s3`, `@aws-sdk/client-sts` -- **阿里云插件**:`@alicloud/openapi-client`, `@alicloud/pop-core`, `@alicloud/tea-typescript`, `@alicloud/fc20230330` 等 -- **腾讯云插件**:`tencentcloud-sdk-nodejs`, `cos-nodejs-sdk-v5` -- **华为云插件**:`@huaweicloud/huaweicloud-sdk-cdn`, `@huaweicloud/huaweicloud-sdk-core` 等 -- **Azure 插件**:`@azure/arm-dns`, `@azure/identity` -- **Google Cloud 插件**:`@google-cloud/dns`, `@google-cloud/publicca` -- **火山引擎插件**:`@volcengine/openapi`, `@volcengine/tos-sdk` - -**网络/工具库:** -- `ssh2`, `socks`, `socks-proxy-agent`(SSH 相关插件) -- `ali-oss`, `qiniu`, `basic-ftp`(存储/传输插件) -- `nodemailer`(邮件通知插件) - -**通用依赖(保留在主 package.json):** -- `@midwayjs/*` 系列(框架核心) -- `@certd/*` 系列(项目内部包) -- `axios`, `lodash-es`, `dayjs`, `js-yaml` 等基础工具 - -## 设计方案 - -### 架构概览 - -``` -packages/ui/certd-server/ -├── package.json # 主依赖(框架、通用工具) -├── node_modules/ # 主依赖安装目录 -├── optional-deps/ # 新增:可选依赖管理目录 -│ ├── package.json # 可选依赖总配置(用于 pnpm install) -│ ├── pnpm-lock.yaml # 可选依赖锁文件 -│ └── node_modules/ # 可选依赖安装目录 -├── src/ -│ └── modules/ -│ └── dependency/ # 新增:依赖管理模块 -│ ├── dependency-manager.ts # 核心:依赖管理器 -│ ├── dependency-registry.ts # 依赖注册表(插件 -> 依赖映射) -│ └── types.ts # 类型定义 -``` - -### 核心组件 - -#### 1. 依赖管理器(DependencyManager) - -**职责:** -- 检查依赖是否已安装 -- 动态执行 `pnpm install` 安装缺失依赖 -- 提供从 `optional-deps/node_modules` 加载依赖的方法 -- 并发控制:避免多个插件同时触发安装 - -**关键方法:** -```typescript -class DependencyManager { - // 确保依赖已安装,返回依赖模块 - async ensureAndImport(packageName: string): Promise - - // 检查依赖是否已安装 - async isInstalled(packageName: string): Promise - - // 安装依赖(带锁,避免并发) - async installDependencies(packages: string[]): Promise - - // 从 optional-deps/node_modules 加载依赖 - async loadModule(packageName: string): Promise -} -``` - -**实现要点:** -- 使用文件锁(如 `proper-lockfile`)防止并发安装 -- 安装前检查 `optional-deps/node_modules/{packageName}` 是否存在 -- 安装命令:`pnpm install --dir optional-deps --ignore-workspace` -- 加载时使用绝对路径:`import('file:///absolute/path/to/optional-deps/node_modules/package')` - -#### 2. 依赖注册表(DependencyRegistry) - -**职责:** -- 维护插件名称到依赖列表的映射 -- 提供依赖查询接口 - -**数据结构:** -```typescript -interface PluginDependencyConfig { - pluginName: string; - dependencies: { - packageName: string; - version: string; - optional?: boolean; // 是否可选(安装失败不阻塞) - }[]; -} - -// 示例注册 -dependencyRegistry.register('plugin-aws', [ - { packageName: '@aws-sdk/client-acm', version: '^3.964.0' }, - { packageName: '@aws-sdk/client-cloudfront', version: '^3.964.0' }, - { packageName: '@aws-sdk/client-route-53', version: '^3.964.0' }, -]); -``` - -#### 3. 插件集成 - -**改造现有插件代码:** - -改造前(`plugin-aws/libs/aws-client.ts`): -```typescript -const { ACMClient, ImportCertificateCommand } = await import("@aws-sdk/client-acm"); -``` - -改造后: -```typescript -import { DependencyManager } from "../../../modules/dependency/dependency-manager.js"; - -const depManager = new DependencyManager(); -const { ACMClient, ImportCertificateCommand } = await depManager.ensureAndImport("@aws-sdk/client-acm"); -``` - -**简化方案(推荐):** - -创建辅助函数,减少改动量: -```typescript -// src/modules/dependency/import-helper.ts -export async function importOptionalDep(packageName: string): Promise { - const depManager = new DependencyManager(); - return await depManager.ensureAndImport(packageName); -} - -// 插件中使用 -import { importOptionalDep } from "../../../modules/dependency/import-helper.js"; -const { ACMClient } = await importOptionalDep("@aws-sdk/client-acm"); -``` - -### 实施步骤 - -#### 阶段一:基础设施搭建 -1. 创建 `optional-deps/` 目录结构 -2. 生成 `optional-deps/package.json`(包含所有可选依赖) -3. 实现 `DependencyManager` 核心逻辑 -4. 实现依赖安装锁机制 -5. 编写单元测试 - -#### 阶段二:依赖迁移 -6. 从主 `package.json` 移除可选依赖 -7. 将依赖添加到 `optional-deps/package.json` -8. 创建依赖注册表,映射插件到依赖 - -#### 阶段三:插件改造 -9. 创建 `import-helper.ts` 辅助函数 -10. 逐步改造插件代码,使用 `importOptionalDep` 加载依赖 -11. 优先改造重型依赖(AWS、阿里云、腾讯云等) - -#### 阶段四:测试与优化 -12. 端到端测试:验证依赖按需安装和加载 -13. 性能优化:缓存已加载的模块 -14. 错误处理:安装失败时的降级策略 -15. 文档:编写使用说明和迁移指南 - -## 关键技术决策 - -### 1. 依赖分组策略 -**选择:按插件分组** -- 每个插件声明自己需要的依赖 -- 优点:职责清晰,易于维护 -- 缺点:可能有重复依赖(但 pnpm 会去重) - -**备选:按功能分组** -- 将依赖按功能分组(如 "aws-deps", "aliyun-deps") -- 优点:更细粒度控制 -- 缺点:增加复杂度 - -### 2. 安装触发时机 -**选择:首次使用时触发** -- 在插件的 `execute()` 或 `getClient()` 方法中触发安装 -- 优点:真正的按需加载 -- 缺点:首次使用有延迟 - -**备选:启动时预检查** -- 启动时扫描启用的插件,预安装依赖 -- 优点:避免运行时延迟 -- 缺点:可能安装不需要的依赖 - -### 3. 依赖路径解析 -**选择:使用绝对路径 + `file://` 协议** -```typescript -const modulePath = path.resolve(__dirname, '../../optional-deps/node_modules', packageName); -return await import(`file://${modulePath}/index.js`); -``` - -**原因:** -- Node.js ESM 要求明确的 URL 格式 -- 避免模块解析冲突 - -### 4. 并发控制 -**选择:文件锁 + 内存锁双重保护** -- 使用 `proper-lockfile` 锁定 `optional-deps/` 目录 -- 内存中使用 `Map` 记录正在安装的依赖 -- 避免多个插件同时触发安装 - -### 5. 错误处理 -**策略:** -- 安装失败时记录日志,抛出明确的错误信息 -- 提供手动安装命令提示:`请运行: cd optional-deps && pnpm install` -- 支持降级:某些非核心依赖安装失败时,插件可以部分功能可用 - -## 验证方案 - -### 单元测试 -1. 测试 `DependencyManager.isInstalled()` 正确检测依赖状态 -2. 测试 `DependencyManager.installDependencies()` 成功安装依赖 -3. 测试并发安装时的锁机制 -4. 测试从 `optional-deps/node_modules` 加载模块 - -### 集成测试 -1. 清空 `optional-deps/node_modules` -2. 启动服务,验证不触发安装 -3. 调用 AWS 插件,验证触发安装并成功加载 -4. 再次调用,验证不重复安装 -5. 验证主 `node_modules` 体积减少 - -### 性能测试 -1. 测量首次安装依赖的耗时 -2. 测量后续加载的耗时(应该与正常 import 相近) -3. 对比改造前后的 `node_modules` 大小 - -## 风险与挑战 - -### 1. 首次使用延迟 -**风险:** 用户首次使用插件时需要等待依赖安装(可能几十秒) -**缓解:** -- 在 UI 上显示安装进度 -- 提供预安装命令:`pnpm run install-optional-deps` -- 文档说明首次使用会有延迟 - -### 2. 离线环境 -**风险:** 离线环境无法下载依赖 -**缓解:** -- 提供完整安装包(包含所有可选依赖) -- 支持手动复制 `node_modules` - -### 3. 版本冲突 -**风险:** 可选依赖与主依赖版本冲突 -**缓解:** -- 使用 `--ignore-workspace` 隔离安装 -- 定期同步主依赖版本 - -### 4. TypeScript 类型 -**风险:** 动态导入的类型推断 -**缓解:** -- 保留 `@types/*` 在主 `devDependencies` -- 使用泛型和类型断言 - -## 预期收益 - -1. **空间节省:** 主 `node_modules` 体积减少 60-70%(估算) -2. **安装速度:** 初始 `pnpm install` 速度提升 3-5 倍 -3. **用户体验:** 不使用的插件不占用空间,按需加载 -4. **维护性:** 依赖分组清晰,易于管理 - -## 后续优化 - -1. **依赖预热:** 在后台预安装常用插件依赖 -2. **依赖缓存:** 支持从 CDN 或本地缓存安装 -3. **依赖更新:** 提供命令批量更新可选依赖 -4. **插件市场:** 支持从远程下载插件及其依赖配置 - -## 附录:依赖分类清单 - -### 可选依赖(迁移到 optional-deps/package.json) - -**AWS 相关(plugin-aws, plugin-aws-cn):** -```json -{ - "@aws-sdk/client-acm": "^3.964.0", - "@aws-sdk/client-cloudfront": "^3.964.0", - "@aws-sdk/client-iam": "^3.964.0", - "@aws-sdk/client-route-53": "^3.964.0", - "@aws-sdk/client-s3": "^3.964.0", - "@aws-sdk/client-sts": "^3.990.0" -} -``` - -**阿里云相关(plugin-aliyun, plugin-lib/aliyun):** -```json -{ - "@alicloud/fc20230330": "^4.1.7", - "@alicloud/openapi-client": "^0.4.12", - "@alicloud/openapi-util": "^0.3.2", - "@alicloud/pop-core": "^1.7.10", - "@alicloud/sts-sdk": "^1.0.2", - "@alicloud/tea-typescript": "^1.8.0", - "@alicloud/tea-util": "^1.4.10", - "ali-oss": "^6.21.0" -} -``` - -**腾讯云相关(plugin-tencent, plugin-lib/tencent):** -```json -{ - "tencentcloud-sdk-nodejs": "^4.1.112", - "cos-nodejs-sdk-v5": "^2.14.6" -} -``` - -**华为云相关(plugin-huawei):** -```json -{ - "@huaweicloud/huaweicloud-sdk-cdn": "3.1.185", - "@huaweicloud/huaweicloud-sdk-core": "3.1.185", - "@huaweicloud/huaweicloud-sdk-elb": "3.1.185", - "@huaweicloud/huaweicloud-sdk-iam": "3.1.185", - "esdk-obs-nodejs": "^3.25.6" -} -``` - -**Azure 相关(plugin-azure):** -```json -{ - "@azure/arm-dns": "^5.1.0", - "@azure/identity": "^4.13.1" -} -``` - -**Google Cloud 相关(plugin-google, plugin-cert/google):** -```json -{ - "@google-cloud/dns": "^5.3.1", - "@google-cloud/publicca": "^1.3.0" -} -``` - -**火山引擎相关(plugin-volcengine):** -```json -{ - "@volcengine/openapi": "^1.28.1", - "@volcengine/tos-sdk": "^2.9.1" -} -``` - -**SSH/网络相关(plugin-host, plugin-lib/ssh):** -```json -{ - "ssh2": "^1.17.0", - "socks": "^2.8.3", - "socks-proxy-agent": "^8.0.4", - "basic-ftp": "^5.0.5" -} -``` - -**其他存储/传输(plugin-qiniu, plugin-lib/qiniu):** -```json -{ - "qiniu": "^7.12.0" -} -``` - -**邮件通知(plugin-notification/email):** -```json -{ - "nodemailer": "^6.9.16" -} -``` - -### 主依赖(保留在主 package.json) - -**框架核心:** -- `@midwayjs/*` 系列 -- `@koa/cors` -- `typeorm`, `better-sqlite3`, `mysql2`, `pg` - -**项目内部包:** -- `@certd/*` 系列 - -**通用工具:** -- `axios`, `lodash-es`, `dayjs`, `js-yaml` -- `crypto-js`, `jsonwebtoken`, `bcryptjs` -- `reflect-metadata`, `uuid`, `nanoid` -- 等等 - -## 总结 - -本方案通过引入独立的可选依赖管理机制,实现了插件依赖的按需下载和加载。核心思路是: - -1. **隔离管理:** 在 `optional-deps/` 目录下维护独立的 `package.json` 和 `node_modules` -2. **动态安装:** 通过 `DependencyManager` 在首次使用时触发 `pnpm install` -3. **路径加载:** 使用绝对路径从独立目录加载依赖模块 -4. **最小改动:** 通过辅助函数 `importOptionalDep` 简化插件代码改造 - -该方案可以显著减少主 `node_modules` 体积,提升初始安装速度,同时保持现有架构的兼容性和可维护性。 diff --git a/AGENTS.md b/AGENTS.md index 47cc02099..c7a1b5954 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -214,4 +214,18 @@ Certd 是可私有化部署的 SSL/TLS 证书自动化管理平台,提供 Web ### 旧版数据兼容 -- 新增插件参数时,必须要考虑旧版数据兼容,比如新增一个deployType参数,有两种值:`default`和`custom`,需要在使用时判空,走旧版逻辑。 \ No newline at end of file +- 新增插件参数时,必须要考虑旧版数据兼容,比如新增一个deployType参数,有两种值:`default`和`custom`,需要在使用时判空,走旧版逻辑。 + +## 前端路由与国际化 + +- 路由 `meta.title` 是 **i18n 国际化 key**,必须在 `src/locales/langs/zh-CN/` 和 `src/locales/langs/en-US/` 对应的模块文件中添加翻译。 +- 示例:路由 `title: "certd.auditLog"` 需要在中英 locales 文件中有对应 key(`"certd.auditLog": "操作日志"` / `"certd.auditLog": "Audit Log"`)。 +- 菜单通过路由自动生成,需设置 `meta.isMenu: true` 才会出现在左侧菜单。 +- Plus 版功能菜单需设置 `meta.show: () => { const settingStore = useSettingStore(); return settingStore.isPlus; }`。 + +## 审计日志 + +- 审计日志是 Plus 版功能,非 Plus 版不会写入。 +- Controller 继承 `BaseController`,通过 `this.auditLog({ content: "xxx" })` 记录日志。 +- `getAuditType()` 返回类型常量,中间件自动从 ctx.path 判定 scope(`/api/sys/` → system,其他 → user)。 +- 操作日志有系统级(scope=system)和用户级(scope=user)区分。 \ No newline at end of file diff --git a/packages/libs/lib-server/src/basic/audit.test.ts b/packages/libs/lib-server/src/basic/audit.test.ts new file mode 100644 index 000000000..10ebe7eec --- /dev/null +++ b/packages/libs/lib-server/src/basic/audit.test.ts @@ -0,0 +1,35 @@ +/// + +import assert from "node:assert/strict"; +import { AuditLogContext } from "./audit.js"; + +// AuditLog decorator and getAuditLogOptions are removed since auditLog() +// now signals audit intent directly via ctx.auditLog.enabled + +describe("AuditLogContext type", () => { + it("supports enabled flag", () => { + const ctx: AuditLogContext = { + type: "pipeline", + action: "删除流水线", + append: ["ID:5"], + content: "删除了流水线(ID:5)", + projectId: 3, + projectName: "默认项目", + enabled: true, + }; + + assert.equal(ctx.enabled, true); + assert.equal(ctx.type, "pipeline"); + assert.equal(ctx.content, "删除了流水线(ID:5)"); + assert.equal(ctx.projectId, 3); + }); + + it("works with minimal fields", () => { + const ctx: AuditLogContext = { + enabled: true, + append: ["提交2条"], + }; + + assert.equal(ctx.enabled, true); + }); +}); diff --git a/packages/libs/lib-server/src/basic/audit.ts b/packages/libs/lib-server/src/basic/audit.ts new file mode 100644 index 000000000..f86a62fc4 --- /dev/null +++ b/packages/libs/lib-server/src/basic/audit.ts @@ -0,0 +1,21 @@ +export type AuditLogOptions = { + type?: string; + action?: string; + content?: string; + template?: string; + disabled?: boolean; +}; + +export type AuditLogContext = { + type?: string; + action?: string; + append?: string | string[]; + content?: string; + projectId?: number; + projectName?: string; + enabled?: boolean; + allowAnonymous?: boolean; + scope?: string; + userId?: number; + username?: string; +}; diff --git a/packages/libs/lib-server/src/basic/base-controller.ts b/packages/libs/lib-server/src/basic/base-controller.ts index 795de3dd1..b9f5b7f10 100644 --- a/packages/libs/lib-server/src/basic/base-controller.ts +++ b/packages/libs/lib-server/src/basic/base-controller.ts @@ -3,6 +3,7 @@ import type { IMidwayContainer } from "@midwayjs/core"; import * as koa from "@midwayjs/koa"; import { Constants } from "./constants.js"; import { isEnterprise } from "./mode.js"; +import type { AuditLogContext } from "./audit.js"; export abstract class BaseController { @Inject() @@ -128,17 +129,42 @@ export abstract class BaseController { return { projectId, userId }; } - async auditLog(bean: { type: string; action: string; content: string; projectId?: number; projectName?: string }) { - const auditService: any = await this.applicationContext.getAsync("auditService"); - await auditService.log({ - userId: this.getUserId(), - type: bean.type, - action: bean.action, - content: bean.content, - username: this.ctx.user?.username, - projectId: bean.projectId, - projectName: bean.projectName, - ipAddress: this.ctx.ip, - }); + getAuditType(): string { + return "unknown"; + } + + auditLog(bean: { type?: string; action?: string; content?: string; append?: string | string[]; projectId?: number; userId?: number; username?: string } = {}) { + const auditLog = this.ensureAuditLogContext(); + auditLog.enabled = true; + if (bean.userId != null) { + auditLog.userId = bean.userId; + } + if (bean.username != null) { + auditLog.username = bean.username; + } + if (bean.type != null) { + auditLog.type = bean.type; + } + if (bean.action != null) { + auditLog.action = bean.action; + } + if (bean.projectId != null) { + auditLog.projectId = bean.projectId; + } + if (bean.content) { + auditLog.content = bean.content; + } + if (bean.append) { + const items = Array.isArray(bean.append) ? bean.append : [bean.append]; + const old = Array.isArray(auditLog.append) ? auditLog.append : auditLog.append ? [auditLog.append] : []; + auditLog.append = [...old, ...items].filter(item => item && String(item).trim()); + } + } + + private ensureAuditLogContext(): AuditLogContext { + if (!this.ctx.auditLog) { + this.ctx.auditLog = {}; + } + return this.ctx.auditLog; } } diff --git a/packages/libs/lib-server/src/basic/base-service.ts b/packages/libs/lib-server/src/basic/base-service.ts index ca83591df..9538c4861 100644 --- a/packages/libs/lib-server/src/basic/base-service.ts +++ b/packages/libs/lib-server/src/basic/base-service.ts @@ -279,7 +279,7 @@ export abstract class BaseService { return item != null && item != ""; }); } - async batchDelete(ids: number[], userId: number, projectId?: number) { + async batchDelete(ids: number[], userId: number, projectId?: number): Promise { ids = this.filterIds(ids); if (userId != null) { const userProjectQuery = this.buildUserProjectQuery(userId, projectId); @@ -295,6 +295,7 @@ export abstract class BaseService { } await this.delete(ids); + return ids.length; } async findOne(options: FindOneOptions) { diff --git a/packages/libs/lib-server/src/basic/constants.ts b/packages/libs/lib-server/src/basic/constants.ts index 73de33205..9ae39c62b 100644 --- a/packages/libs/lib-server/src/basic/constants.ts +++ b/packages/libs/lib-server/src/basic/constants.ts @@ -1,21 +1,21 @@ export const Constants = { - dataDir: './data', + dataDir: "./data", role: { defaultUser: 3, }, per: { //无需登录 - guest: '_guest_', + guest: "_guest_", //无需登录 - anonymous: '_guest_', + anonymous: "_guest_", //无需登录,有 token 时解析当前用户 - guestOptionalAuth: '_guestOptionalAuth_', + guestOptionalAuth: "_guestOptionalAuth_", //仅需要登录 - authOnly: '_authOnly_', + authOnly: "_authOnly_", //仅需要登录 - loginOnly: '_authOnly_', + loginOnly: "_authOnly_", - open: '_open_', + open: "_open_", }, res: { serverError(message: string) { @@ -26,102 +26,102 @@ export const Constants = { }, error: { code: 1, - message: 'Internal server error', + message: "Internal server error", }, success: { code: 0, - message: 'success', + message: "success", }, validation: { code: 10, - message: '参数错误', + message: "参数错误", }, needvip: { code: 88, - message: '需要VIP', + message: "需要VIP", }, needsuite: { code: 89, - message: '需要购买或升级套餐', + message: "需要购买或升级套餐", }, loginError: { code: 2, - message: '登录失败', + message: "登录失败", }, codeError: { code: 3, - message: '验证码错误', + message: "验证码错误", }, auth: { code: 401, - message: '您还未登录或token已过期', + message: "您还未登录或token已过期", }, permission: { code: 402, - message: '您没有权限', + message: "您没有权限", }, param: { code: 400, - message: '参数错误', + message: "参数错误", }, notFound: { code: 404, - message: '页面/文件/资源不存在', + message: "页面/文件/资源不存在", }, preview: { code: 10001, - message: '对不起,预览环境不允许修改此数据', + message: "对不起,预览环境不允许修改此数据", }, - siteOff:{ + siteOff: { code: 10010, - message: '站点已关闭', + message: "站点已关闭", }, - need2fa:{ + need2fa: { code: 10020, - message: '需要2FA认证', + message: "需要2FA认证", }, openKeyError: { code: 20000, - message: 'ApiToken错误', + message: "ApiToken错误", }, openKeySignError: { code: 20001, - message: 'ApiToken签名错误', + message: "ApiToken签名错误", }, openKeyExpiresError: { code: 20002, - message: 'ApiToken时间戳错误', + message: "ApiToken时间戳错误", }, openKeySignTypeError: { code: 20003, - message: 'ApiToken签名类型不支持', + message: "ApiToken签名类型不支持", }, openParamError: { code: 20010, - message: '请求参数错误', + message: "请求参数错误", }, openCertNotFound: { code: 20011, - message: '证书不存在', + message: "证书不存在", }, openCertNotReady: { code: 20012, - message: '证书还未生成', + message: "证书还未生成", }, openCertApplying: { code: 20013, - message: '证书正在申请中,请稍后重新获取', + message: "证书正在申请中,请稍后重新获取", }, - openDomainNoVerifier:{ + openDomainNoVerifier: { code: 20014, - message: '域名校验方式未配置', + message: "域名校验方式未配置", }, openEmailNotFound: { code: 20021, - message: '用户邮箱还未配置', + message: "用户邮箱还未配置", }, }, systemUserId: 0, // 系统级别userid固定为0 - enterpriseUserId: -1 // 企业模式用户id固定为-1 + enterpriseUserId: -1, // 企业模式用户id固定为-1 }; diff --git a/packages/libs/lib-server/src/basic/exception/login-error-exception.ts b/packages/libs/lib-server/src/basic/exception/login-error-exception.ts index b84892f55..373790c6c 100644 --- a/packages/libs/lib-server/src/basic/exception/login-error-exception.ts +++ b/packages/libs/lib-server/src/basic/exception/login-error-exception.ts @@ -1,12 +1,14 @@ -import { Constants } from '../constants.js'; -import { BaseException } from './base-exception.js'; +import { Constants } from "../constants.js"; +import { BaseException } from "./base-exception.js"; /** * 通用异常 */ export class LoginErrorException extends BaseException { leftCount: number; - constructor(message, leftCount: number) { - super('LoginErrorException', Constants.res.loginError.code, message ? message : Constants.res.loginError.message); + userId?: number; + constructor(message, leftCount: number, userId?: number) { + super("LoginErrorException", Constants.res.loginError.code, message ? message : Constants.res.loginError.message); this.leftCount = leftCount; + this.userId = userId; } } diff --git a/packages/libs/lib-server/src/basic/index.ts b/packages/libs/lib-server/src/basic/index.ts index d012ec35c..742df5d30 100644 --- a/packages/libs/lib-server/src/basic/index.ts +++ b/packages/libs/lib-server/src/basic/index.ts @@ -1,8 +1,9 @@ -export * from './base-controller.js'; -export * from './constants.js'; -export * from './crud-controller.js'; -export * from './enum-item.js'; -export * from './exception/index.js'; -export * from './result.js'; -export * from './base-service.js'; -export * from "./mode.js" \ No newline at end of file +export * from "./base-controller.js"; +export * from "./constants.js"; +export * from "./crud-controller.js"; +export * from "./enum-item.js"; +export * from "./exception/index.js"; +export * from "./result.js"; +export * from "./base-service.js"; +export * from "./audit.js"; +export * from "./mode.js"; diff --git a/packages/libs/lib-server/src/basic/mode.ts b/packages/libs/lib-server/src/basic/mode.ts index 2f8318150..cf5768d27 100644 --- a/packages/libs/lib-server/src/basic/mode.ts +++ b/packages/libs/lib-server/src/basic/mode.ts @@ -1,12 +1,12 @@ -let adminMode = "saas" +let adminMode = "saas"; -export function setAdminMode(mode:string = "saas"){ - adminMode = mode +export function setAdminMode(mode: string = "saas") { + adminMode = mode; } -export function getAdminMode(){ - return adminMode +export function getAdminMode() { + return adminMode; } -export function isEnterprise(){ - return adminMode === "enterprise" -} \ No newline at end of file +export function isEnterprise() { + return adminMode === "enterprise"; +} diff --git a/packages/ui/certd-client/src/locales/langs/en-US/certd.ts b/packages/ui/certd-client/src/locales/langs/en-US/certd.ts index 14b260b56..e5a138949 100644 --- a/packages/ui/certd-client/src/locales/langs/en-US/certd.ts +++ b/packages/ui/certd-client/src/locales/langs/en-US/certd.ts @@ -19,7 +19,6 @@ import sysauthority from "./certd/sys-authority"; import syscname from "./certd/sys-cname"; import tutorial from "./certd/tutorial"; import cron from "./certd/cron"; -import audit from "./certd/audit"; // Note: @ is reserved in locale messages; use {'@'} when needed. export default { @@ -44,5 +43,4 @@ export default { ...syscname, ...tutorial, ...cron, - ...audit, }; diff --git a/packages/ui/certd-client/src/locales/langs/en-US/certd/audit.ts b/packages/ui/certd-client/src/locales/langs/en-US/certd/audit.ts deleted file mode 100644 index 506a56977..000000000 --- a/packages/ui/certd-client/src/locales/langs/en-US/certd/audit.ts +++ /dev/null @@ -1,4 +0,0 @@ -export default { - "certd.auditLog": "Audit Log", - "certd.sysResources.auditLog": "Audit Log", -}; diff --git a/packages/ui/certd-client/src/locales/langs/en-US/certd/navigation.ts b/packages/ui/certd-client/src/locales/langs/en-US/certd/navigation.ts index d7b0ae5e1..3db0f890f 100644 --- a/packages/ui/certd-client/src/locales/langs/en-US/certd/navigation.ts +++ b/packages/ui/certd-client/src/locales/langs/en-US/certd/navigation.ts @@ -18,6 +18,7 @@ export default { openKey: "Open API Key", notification: "Notification Settings", siteMonitorSetting: "Site Monitor Settings", + auditLog: "Audit Log", userSecurity: "Security Settings", userProfile: "Account Info", userGrant: "Grant Delegation", @@ -67,6 +68,7 @@ export default { projectJoin: "Join Project", currentProject: "Current Project", projectMemberManager: "Project Member", + auditLog: "Audit Log", domainMonitorSetting: "Domain Monitor Settings", }, }; diff --git a/packages/ui/certd-client/src/locales/langs/zh-CN/certd.ts b/packages/ui/certd-client/src/locales/langs/zh-CN/certd.ts index 14b260b56..e5a138949 100644 --- a/packages/ui/certd-client/src/locales/langs/zh-CN/certd.ts +++ b/packages/ui/certd-client/src/locales/langs/zh-CN/certd.ts @@ -19,7 +19,6 @@ import sysauthority from "./certd/sys-authority"; import syscname from "./certd/sys-cname"; import tutorial from "./certd/tutorial"; import cron from "./certd/cron"; -import audit from "./certd/audit"; // Note: @ is reserved in locale messages; use {'@'} when needed. export default { @@ -44,5 +43,4 @@ export default { ...syscname, ...tutorial, ...cron, - ...audit, }; diff --git a/packages/ui/certd-client/src/locales/langs/zh-CN/certd/audit.ts b/packages/ui/certd-client/src/locales/langs/zh-CN/certd/audit.ts deleted file mode 100644 index b6d3f9b81..000000000 --- a/packages/ui/certd-client/src/locales/langs/zh-CN/certd/audit.ts +++ /dev/null @@ -1,4 +0,0 @@ -export default { - "certd.auditLog": "操作日志", - "certd.sysResources.auditLog": "操作日志", -}; diff --git a/packages/ui/certd-client/src/locales/langs/zh-CN/certd/navigation.ts b/packages/ui/certd-client/src/locales/langs/zh-CN/certd/navigation.ts index 2c740e8ff..a6900e868 100644 --- a/packages/ui/certd-client/src/locales/langs/zh-CN/certd/navigation.ts +++ b/packages/ui/certd-client/src/locales/langs/zh-CN/certd/navigation.ts @@ -18,6 +18,7 @@ export default { openKey: "开放接口密钥", notification: "通知设置", siteMonitorSetting: "站点监控设置", + auditLog: "操作日志", userSecurity: "认证安全设置", userProfile: "账号信息", userGrant: "授权委托", @@ -67,6 +68,7 @@ export default { projectJoin: "加入项目", currentProject: "当前项目", projectMemberManager: "项目成员管理", + auditLog: "审计日志", domainMonitorSetting: "域名监控设置", jobHistory: "监控执行记录", }, diff --git a/packages/ui/certd-client/src/router/source/modules/certd.ts b/packages/ui/certd-client/src/router/source/modules/certd.ts index 4c5e0f0a8..d0e25b8df 100644 --- a/packages/ui/certd-client/src/router/source/modules/certd.ts +++ b/packages/ui/certd-client/src/router/source/modules/certd.ts @@ -296,6 +296,11 @@ export const certdResources = [ icon: "ion:document-text-outline", auth: true, keepAlive: true, + isMenu: true, + show: () => { + const settingStore = useSettingStore(); + return settingStore.isPlus; + }, }, }, { diff --git a/packages/ui/certd-client/src/router/source/modules/sys.ts b/packages/ui/certd-client/src/router/source/modules/sys.ts index 6178cd24c..cedee2f06 100644 --- a/packages/ui/certd-client/src/router/source/modules/sys.ts +++ b/packages/ui/certd-client/src/router/source/modules/sys.ts @@ -417,9 +417,13 @@ export const sysResources = [ component: "/sys/audit/index.vue", meta: { icon: "ion:document-text-outline", - permission: "sys:settings:view", keepAlive: true, auth: true, + isMenu: true, + show: () => { + const settingStore = useSettingStore(); + return settingStore.isPlus; + }, }, }, { diff --git a/packages/ui/certd-client/src/views/certd/audit/crud.tsx b/packages/ui/certd-client/src/views/certd/audit/crud.tsx index e97b1e599..e44de5e6d 100644 --- a/packages/ui/certd-client/src/views/certd/audit/crud.tsx +++ b/packages/ui/certd-client/src/views/certd/audit/crud.tsx @@ -1,4 +1,6 @@ import { CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud"; +import { useI18n } from "/src/locales"; +import { useDicts } from "../dicts"; const typeDict = dict({ url: "/pi/audit/dict", @@ -21,6 +23,8 @@ const actionDict = dict({ }); export default function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet { + const { t } = useI18n(); + const { myProjectDict } = useDicts(); const api = context.api; const pageRequest = async (query: UserPageQuery): Promise => { @@ -45,6 +49,7 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat view: { show: false }, edit: { show: false }, remove: { show: true }, + copy: { show: false }, }, }, columns: { @@ -61,7 +66,6 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat show: true, component: { name: "a-range-picker", - vModel: ["createTime_start", "createTime_end"], }, }, column: { width: 170, sorter: true }, @@ -77,17 +81,16 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat }, action: { title: "操作动作", - type: "dict-select", - dict: actionDict, + type: "text", search: { show: true }, - column: { width: 100 }, + column: { width: 200, tooltip: true }, form: { show: false }, }, content: { - title: "内容", + title: "备注", type: "text", search: { show: true }, - column: { minWidth: 300 }, + column: { width: 700, tooltip: true }, form: { show: false }, }, ipAddress: { @@ -96,6 +99,14 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat column: { width: 140 }, form: { show: false }, }, + projectId: { + title: t("certd.fields.projectName"), + type: "dict-select", + dict: myProjectDict, + form: { + show: false, + }, + }, }, }, }; diff --git a/packages/ui/certd-client/src/views/sys/audit/crud.tsx b/packages/ui/certd-client/src/views/sys/audit/crud.tsx index cb5db23e3..28b63405e 100644 --- a/packages/ui/certd-client/src/views/sys/audit/crud.tsx +++ b/packages/ui/certd-client/src/views/sys/audit/crud.tsx @@ -1,4 +1,7 @@ import { CreateCrudOptionsProps, CreateCrudOptionsRet, DelReq, UserPageQuery, UserPageRes, dict } from "@fast-crud/fast-crud"; +import { Modal } from "ant-design-vue"; +import { useI18n } from "/src/locales"; +import { useDicts } from "/@/views/certd/dicts"; const typeDict = dict({ url: "/sys/audit/dict", @@ -21,6 +24,8 @@ const actionDict = dict({ }); export default function ({ crudExpose, context }: CreateCrudOptionsProps): CreateCrudOptionsRet { + const { t } = useI18n(); + const { myProjectDict } = useDicts(); const api = context.api; const pageRequest = async (query: UserPageQuery): Promise => { @@ -31,19 +36,39 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat }; const cleanExpired = async () => { - await api.Clean(90); - crudExpose.doRefresh(); + Modal.confirm({ + title: "确认清理", + content: "确定要清理90天前的审计日志吗?此操作不可撤销。", + okText: "确认清理", + okType: "danger", + cancelText: "取消", + async onOk() { + await api.Clean(90); + crudExpose.doRefresh(); + }, + }); }; return { crudOptions: { request: { pageRequest, delRequest }, + tabs: { + name: "scope", + show: true, + dict: { + data: [ + { value: "system", label: "系统级", color: "red" }, + { value: "user", label: "用户级", color: "blue" }, + ], + }, + }, actionbar: { buttons: { add: { show: false }, clean: { text: "清理过期日志(90天)", - type: "default", + type: "primary", + danger: true, click: cleanExpired, }, }, @@ -55,12 +80,11 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat view: { show: false }, edit: { show: false }, remove: { show: true }, + copy: { show: false }, }, }, search: { - initialForm: { - sort: { prop: "id", asc: false }, - }, + initialForm: { scope: "system" }, }, columns: { id: { @@ -76,13 +100,12 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat show: true, component: { name: "a-range-picker", - vModel: ["createTime_start", "createTime_end"], }, }, column: { width: 170, sorter: true }, form: { show: false }, }, - userName: { + username: { title: "操作人", type: "text", search: { show: true }, @@ -90,7 +113,7 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat form: { show: false }, }, type: { - title: "操作类型", + title: "类型", type: "dict-select", dict: typeDict, search: { show: true }, @@ -98,18 +121,17 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat form: { show: false }, }, action: { - title: "操作动作", - type: "dict-select", - dict: actionDict, + title: "操作", + type: "text", search: { show: true }, - column: { width: 100 }, + column: { width: 200, tooltip: true }, form: { show: false }, }, content: { - title: "内容", + title: "备注", type: "text", search: { show: true }, - column: { minWidth: 300 }, + column: { width: 500, tooltip: true }, form: { show: false }, }, ipAddress: { @@ -118,6 +140,27 @@ export default function ({ crudExpose, context }: CreateCrudOptionsProps): Creat column: { width: 140 }, form: { show: false }, }, + projectId: { + title: t("certd.fields.projectName"), + type: "dict-select", + dict: myProjectDict, + form: { + show: false, + }, + }, + scope: { + title: "范围", + type: "dict-select", + dict: dict({ + data: [ + { value: "system", label: "系统级", color: "blue" }, + { value: "user", label: "用户级", color: "green" }, + ], + }), + search: { show: true }, + column: { width: 100 }, + form: { show: false }, + }, }, }, }; diff --git a/packages/ui/certd-server/db/migration-mysql/v10051__audit_log_scope.sql b/packages/ui/certd-server/db/migration-mysql/v10051__audit_log_scope.sql new file mode 100644 index 000000000..0dd358558 --- /dev/null +++ b/packages/ui/certd-server/db/migration-mysql/v10051__audit_log_scope.sql @@ -0,0 +1,2 @@ +ALTER TABLE `cd_audit_log` ADD COLUMN `scope` varchar(32) NOT NULL DEFAULT 'user'; +CREATE INDEX `index_audit_log_scope` ON `cd_audit_log` (`scope`); diff --git a/packages/ui/certd-server/db/migration-pg/v10051__audit_log_scope.sql b/packages/ui/certd-server/db/migration-pg/v10051__audit_log_scope.sql new file mode 100644 index 000000000..9dd4eb54a --- /dev/null +++ b/packages/ui/certd-server/db/migration-pg/v10051__audit_log_scope.sql @@ -0,0 +1,2 @@ +ALTER TABLE "cd_audit_log" ADD COLUMN "scope" varchar(32) NOT NULL DEFAULT ('user'); +CREATE INDEX "index_audit_log_scope" ON "cd_audit_log" ("scope"); diff --git a/packages/ui/certd-server/db/migration/v10051__audit_log_scope.sql b/packages/ui/certd-server/db/migration/v10051__audit_log_scope.sql new file mode 100644 index 000000000..9dd4eb54a --- /dev/null +++ b/packages/ui/certd-server/db/migration/v10051__audit_log_scope.sql @@ -0,0 +1,2 @@ +ALTER TABLE "cd_audit_log" ADD COLUMN "scope" varchar(32) NOT NULL DEFAULT ('user'); +CREATE INDEX "index_audit_log_scope" ON "cd_audit_log" ("scope"); diff --git a/packages/ui/certd-server/src/configuration.ts b/packages/ui/certd-server/src/configuration.ts index fda204f11..f7b4d66be 100644 --- a/packages/ui/certd-server/src/configuration.ts +++ b/packages/ui/certd-server/src/configuration.ts @@ -12,6 +12,7 @@ import cors from "@koa/cors"; import { GlobalExceptionMiddleware } from "./middleware/global-exception.js"; import { PreviewMiddleware } from "./middleware/preview.js"; import { AuthorityMiddleware } from "./middleware/authority.js"; +import { AuditLogMiddleware } from "./middleware/audit-log.js"; import { logger } from "@certd/basic"; import { ResetPasswdMiddleware } from "./middleware/reset-passwd/middleware.js"; import DefaultConfig from "./config/config.default.js"; @@ -113,6 +114,7 @@ export class MainConfiguration { PreviewMiddleware, //授权处理 AuthorityMiddleware, + AuditLogMiddleware, //resetPasswd,重置密码模式下不提供服务 ResetPasswdMiddleware, @@ -132,5 +134,6 @@ export class MainConfiguration { logger.info(text); }); logger.info("当前环境:", this.app.getEnv()); // prod + } } diff --git a/packages/ui/certd-server/src/controller/basic/login/forgot-password-controller.ts b/packages/ui/certd-server/src/controller/basic/login/forgot-password-controller.ts index 25b3c520d..787cba21a 100644 --- a/packages/ui/certd-server/src/controller/basic/login/forgot-password-controller.ts +++ b/packages/ui/certd-server/src/controller/basic/login/forgot-password-controller.ts @@ -1,8 +1,9 @@ -import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core"; +import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core"; import { BaseController, CommonException, Constants, SysSettingsService } from "@certd/lib-server"; import { CodeService } from "../../../modules/basic/service/code-service.js"; import { UserService } from "../../../modules/sys/authority/service/user-service.js"; import { LoginService } from "../../../modules/login/service/login-service.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -19,7 +20,11 @@ export class ForgotPasswordController extends BaseController { @Inject() sysSettingsService: SysSettingsService; - @Post("/forgotPassword", { description: Constants.per.guest }) + getAuditType(): string { + return AuditType.login; + } + + @Post("/forgotPassword", { description: Constants.per.guest, summary: "找回密码" }) public async forgotPassword( @Body(ALL) body: any @@ -28,15 +33,13 @@ export class ForgotPasswordController extends BaseController { if (!sysSettings.selfServicePasswordRetrievalEnabled) { throw new CommonException("暂未开启自助找回"); } - // 找回密码的验证码允许错误次数 - const maxErrorCount = 5; if (body.type === "email") { this.codeService.checkEmailCode({ verificationType: "forgotPassword", email: body.input, validateCode: body.validateCode, - maxErrorCount: maxErrorCount, + maxErrorCount: 5, throwError: true, }); } else if (body.type === "mobile") { @@ -45,14 +48,15 @@ export class ForgotPasswordController extends BaseController { mobile: body.input, phoneCode: body.phoneCode, smsCode: body.validateCode, - maxErrorCount: maxErrorCount, + maxErrorCount: 5, throwError: true, }); } else { throw new CommonException("暂不支持的找回类型,请联系管理员找回"); } - const username = await this.userService.forgotPassword(body); + const {id,username} = await this.userService.forgotPassword(body); username && this.loginService.clearCacheOnSuccess(username); + this.auditLog({ userId: id, content: "用户请求找回密码" }); return this.ok(); } } diff --git a/packages/ui/certd-server/src/controller/basic/login/login-controller.ts b/packages/ui/certd-server/src/controller/basic/login/login-controller.ts index a80eeb036..94ca404ff 100644 --- a/packages/ui/certd-server/src/controller/basic/login/login-controller.ts +++ b/packages/ui/certd-server/src/controller/basic/login/login-controller.ts @@ -1,10 +1,11 @@ -import { ALL, Body, Controller, Inject, Post, Provide, RequestIP } from "@midwayjs/core"; +import { ALL, Body, Controller, Inject, Post, Provide, RequestIP } from "@midwayjs/core"; import { LoginService } from "../../../modules/login/service/login-service.js"; import { AddonService, BaseController, Constants, SysPublicSettings, SysSettingsService } from "@certd/lib-server"; import { CodeService } from "../../../modules/basic/service/code-service.js"; import { checkComm } from "@certd/plus-core"; import { CaptchaService } from "../../../modules/basic/service/captcha-service.js"; import { PasskeyService } from "../../../modules/login/service/passkey-service.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -27,7 +28,11 @@ export class LoginController extends BaseController { @Inject() passkeyService: PasskeyService; - @Post("/login", { description: Constants.per.guest }) + getAuditType(): string { + return AuditType.login; + } + + @Post("/login", { description: Constants.per.guest, summary: "用户名密码登录" }) public async login( @Body(ALL) body: any, @@ -38,16 +43,22 @@ export class LoginController extends BaseController { if (settings.captchaEnabled === true) { await this.captchaService.doValidate({ form: body.captcha, must: false, captchaAddonId: settings.captchaAddonId, req: { remoteIp } }); } - const token = await this.loginService.loginByPassword(body); - this.writeTokenCookie(token); - return this.ok(token); + try { + const token = await this.loginService.loginByPassword(body); + this.writeTokenCookie(token); + this.auditLog({ userId: token.userId, username: body.username, content: `用户「${body.username}」登录成功` }); + return this.ok(token); + } catch (err:any) { + this.auditLog({userId:err.userId, username: body.username, content: `用户「${body.username}」登录失败` }); + throw err; + } } private writeTokenCookie(token: { expire: any; token: any }) { // this.loginService.writeTokenCookie(this.ctx,token); } - @Post("/loginBySms", { description: Constants.per.guest }) + @Post("/loginBySms", { description: Constants.per.guest, summary: "短信验证码登录" }) public async loginBySms( @Body(ALL) body: any @@ -58,31 +69,42 @@ export class LoginController extends BaseController { } checkComm(); - const token = await this.loginService.loginBySmsCode({ - phoneCode: body.phoneCode, - mobile: body.mobile, - smsCode: body.smsCode, - randomStr: body.randomStr, - inviteCode: body.inviteCode, - }); + try { + const token = await this.loginService.loginBySmsCode({ + phoneCode: body.phoneCode, + mobile: body.mobile, + smsCode: body.smsCode, + randomStr: body.randomStr, + inviteCode: body.inviteCode, + }); - this.writeTokenCookie(token); - - return this.ok(token); + this.writeTokenCookie(token); + this.auditLog({ userId: token.userId, username: body.mobile, content: `用户「${body.mobile}」短信登录成功` }); + return this.ok(token); + } catch (err) { + this.auditLog({ userId: err.userId, username: body.mobile, content: `用户「${body.mobile}」短信登录失败` }); + throw err; + } } - @Post("/loginByTwoFactor", { description: Constants.per.guest }) + @Post("/loginByTwoFactor", { description: Constants.per.guest, summary: "两步验证登录" }) public async loginByTwoFactor( @Body(ALL) body: any ) { - const token = await this.loginService.loginByTwoFactor({ - loginId: body.loginId, - verifyCode: body.verifyCode, - }); + try { + const token = await this.loginService.loginByTwoFactor({ + loginId: body.loginId, + verifyCode: body.verifyCode, + }); - this.writeTokenCookie(token); - return this.ok(token); + this.writeTokenCookie(token); + this.auditLog({ userId: token.userId, username: body.loginId, content: `用户「${body.loginId}」两步验证登录成功` }); + return this.ok(token); + } catch (err) { + this.auditLog({ userId: err.userId, username: body.loginId, content: `用户「${body.loginId}」两步验证登录失败` }); + throw err; + } } @Post("/passkey/generateAuthentication", { description: Constants.per.guest }) @@ -92,24 +114,30 @@ export class LoginController extends BaseController { return this.ok(options); } - @Post("/loginByPasskey", { description: Constants.per.guest }) + @Post("/loginByPasskey", { description: Constants.per.guest, summary: "Passkey登录" }) public async loginByPasskey( @Body(ALL) body: any ) { - const credential = body.credential; - const challenge = body.challenge; + try { + const credential = body.credential; + const challenge = body.challenge; - const token = await this.loginService.loginByPasskey( - { - credential, - challenge, - }, - this.ctx - ); + const token = await this.loginService.loginByPasskey( + { + credential, + challenge, + }, + this.ctx + ); - // this.writeTokenCookie(token); - return this.ok(token); + this.writeTokenCookie(token); + this.auditLog({ userId: token.userId, content: "用户Passkey登录成功" }); + return this.ok(token); + } catch (err) { + this.auditLog({ userId: err.userId, content: "用户Passkey登录失败" }); + throw err; + } } @Post("/logout", { description: Constants.per.authOnly }) diff --git a/packages/ui/certd-server/src/controller/basic/login/oauth-controller.ts b/packages/ui/certd-server/src/controller/basic/login/oauth-controller.ts index 8528e0ec6..18ad82d56 100644 --- a/packages/ui/certd-server/src/controller/basic/login/oauth-controller.ts +++ b/packages/ui/certd-server/src/controller/basic/login/oauth-controller.ts @@ -1,4 +1,4 @@ -import { logger, simpleNanoId, utils } from "@certd/basic"; +import { logger, simpleNanoId, utils } from "@certd/basic"; import { addonRegistry, AddonService, BaseController, Constants, SysInstallInfo, SysSettingsService } from "@certd/lib-server"; import { checkPlus } from "@certd/plus-core"; import { ALL, Body, Controller, Get, Inject, Param, Post, Provide, Query } from "@midwayjs/core"; @@ -8,6 +8,7 @@ import { LoginService } from "../../../modules/login/service/login-service.js"; import { OauthBoundService } from "../../../modules/login/service/oauth-bound-service.js"; import { AddonGetterService } from "../../../modules/pipeline/service/addon-getter-service.js"; import { UserEntity } from "../../../modules/sys/authority/entity/user.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; import { IOauthProvider } from "../../../plugins/plugin-oauth/api.js"; type OauthProviderSetting = { @@ -48,6 +49,10 @@ export class ConnectController extends BaseController { @Inject() addonService: AddonService; + getAuditType(): string { + return AuditType.login; + } + private async getOauthProvider(type: string) { const publicSettings = await this.sysSettingsService.getPublicSettings(); if (!publicSettings?.oauthEnabled) { @@ -68,12 +73,11 @@ export class ConnectController extends BaseController { }; } - @Post("/login", { description: Constants.per.guest }) + @Post("/login", { description: Constants.per.guest, summary: "第三方登录" }) public async login(@Body(ALL) body: { type: string; subtype?: string; forType?: string; from?: string }) { const oauthProvider = await this.getOauthProvider(body.type); const installInfo = await this.sysSettingsService.getSetting(SysInstallInfo); const bindUrl = installInfo?.bindUrl || ""; - //构造登录url const redirectUrl = `${bindUrl}api/oauth/callback/${body.type}`; const stateObj = { @@ -95,8 +99,6 @@ export class ConnectController extends BaseController { }); this.ctx.cookies.set("oauth_ticket", ticket, { httpOnly: true, - // secure: true, - // sameSite: "strict", }); return this.ok({ loginUrl, ticket }); } @@ -153,7 +155,7 @@ export class ConnectController extends BaseController { } } - @Post("/getLogoutUrl", { description: Constants.per.guest }) + @Post("/getLogoutUrl", { description: Constants.per.guest, summary: "第三方登出" }) public async logout(@Body(ALL) body: any) { checkPlus(); const oauthProvider = await this.getOauthProvider(body.type); @@ -195,7 +197,7 @@ export class ConnectController extends BaseController { // this.loginService.writeTokenCookie(this.ctx,token); } - @Post("/autoRegister", { description: Constants.per.guest }) + @Post("/autoRegister", { description: Constants.per.guest, summary: "第三方自动注册" }) public async autoRegister(@Body(ALL) body: { validationCode: string; type: string; inviteCode?: string }) { const validationValue = this.codeService.getValidationValue(body.validationCode); if (!validationValue) { @@ -219,12 +221,12 @@ export class ConnectController extends BaseController { const loginRes = await this.loginService.generateToken(newUser); this.writeTokenCookie(loginRes); + this.auditLog({ userId: newUser.id, content: `第三方账号自动注册,类型: ${body.type}` }); return this.ok(loginRes); } - @Post("/bind", { description: Constants.per.loginOnly }) + @Post("/bind", { description: Constants.per.loginOnly, summary: "绑定第三方账号" }) public async bind(@Body(ALL) body: any) { - //需要已登录 const userId = this.getUserId(); const validationValue = this.codeService.getValidationValue(body.validationCode); if (!validationValue) { @@ -238,17 +240,18 @@ export class ConnectController extends BaseController { type, openId, }); + this.auditLog({ userId, content: `第三方账号绑定,类型: ${body.type}` }); return this.ok(1); } - @Post("/unbind", { description: Constants.per.loginOnly }) + @Post("/unbind", { description: Constants.per.loginOnly, summary: "解绑第三方账号" }) public async unbind(@Body(ALL) body: any) { - //需要已登录 const userId = this.getUserId(); await this.oauthBoundService.unbind({ userId, type: body.type, }); + this.auditLog({ userId, content: `第三方账号解绑,类型: ${body.type}` }); return this.ok(1); } diff --git a/packages/ui/certd-server/src/controller/basic/login/register-controller.ts b/packages/ui/certd-server/src/controller/basic/login/register-controller.ts index 30faa3113..a12d54fe4 100644 --- a/packages/ui/certd-server/src/controller/basic/login/register-controller.ts +++ b/packages/ui/certd-server/src/controller/basic/login/register-controller.ts @@ -1,9 +1,10 @@ -import { ALL, Body, Controller, Inject, Post, Provide, RequestIP } from "@midwayjs/core"; +import { ALL, Body, Controller, Inject, Post, Provide, RequestIP } from "@midwayjs/core"; import { BaseController, Constants, SysSettingsService } from "@certd/lib-server"; import { RegisterType } from "../../../modules/sys/authority/service/user-service.js"; import { CodeService } from "../../../modules/basic/service/code-service.js"; import { checkComm, checkPlus } from "@certd/plus-core"; import { LoginService } from "../../../modules/login/service/login-service.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; export type RegisterReq = { type: RegisterType; @@ -31,7 +32,11 @@ export class RegisterController extends BaseController { @Inject() sysSettingsService: SysSettingsService; - @Post("/register", { description: Constants.per.guest }) + getAuditType(): string { + return AuditType.login; + } + + @Post("/register", { description: Constants.per.guest, summary: "用户注册" }) public async register( @Body(ALL) body: RegisterReq, @@ -60,6 +65,7 @@ export class RegisterController extends BaseController { password: body.password, } as any; const newUser = await this.loginService.register(body.type, registerUser, body.inviteCode); + this.auditLog({ userId: newUser.id, username: body.username, content: `用户「${body.username}」注册成功` }); return this.ok(newUser); } else if (body.type === "mobile") { if (sysPublicSettings.mobileRegisterEnabled === false) { @@ -80,6 +86,7 @@ export class RegisterController extends BaseController { password: body.password, } as any; const newUser = await this.loginService.register(body.type, registerUser, body.inviteCode); + this.auditLog({ userId: newUser.id, username: body.mobile, content: `用户「${body.mobile}」注册成功` }); return this.ok(newUser); } else if (body.type === "email") { if (sysPublicSettings.emailRegisterEnabled === false) { @@ -97,6 +104,7 @@ export class RegisterController extends BaseController { password: body.password, } as any; const newUser = await this.loginService.register(body.type, registerUser, body.inviteCode); + this.auditLog({ userId: newUser.id, username: body.email, content: `用户「${body.email}」注册成功` }); return this.ok(newUser); } } diff --git a/packages/ui/certd-server/src/controller/sys/account/account-controller.ts b/packages/ui/certd-server/src/controller/sys/account/account-controller.ts index 229c6bdf2..3588e68ff 100644 --- a/packages/ui/certd-server/src/controller/sys/account/account-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/account/account-controller.ts @@ -1,5 +1,6 @@ import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core"; import { BaseController, PlusService, SysInstallInfo, SysSettingsService } from "@certd/lib-server"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; export type PreBindUserReq = { userId: number; @@ -18,17 +19,21 @@ export class BasicController extends BaseController { @Inject() sysSettingsService: SysSettingsService; - @Post("/preBindUser", { description: "sys:settings:edit" }) + getAuditType(): string { + return AuditType.account; + } + + @Post("/preBindUser", { description: "sys:settings:edit", summary: "预绑定用户" }) public async preBindUser(@Body(ALL) body: PreBindUserReq) { - // 设置缓存内容 if (body.userId == null || body.userId <= 0) { throw new Error("用户ID不能为空"); } await this.plusService.userPreBind(body.userId); + await this.auditLog({ content: `预绑定了用户(ID:${body.userId})` }); return this.ok({}); } - @Post("/bindUser", { description: "sys:settings:edit" }) + @Post("/bindUser", { description: "sys:settings:edit", summary: "绑定用户" }) public async bindUser(@Body(ALL) body: BindUserReq) { if (body.userId == null || body.userId <= 0) { throw new Error("用户ID不能为空"); @@ -36,20 +41,23 @@ export class BasicController extends BaseController { const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo); installInfo.bindUserId = body.userId; await this.sysSettingsService.saveSetting(installInfo); + await this.auditLog({ content: `绑定了用户(ID:${body.userId})` }); return this.ok({}); } - @Post("/unbindUser", { description: "sys:settings:edit" }) + @Post("/unbindUser", { description: "sys:settings:edit", summary: "解绑用户" }) public async unbindUser() { const installInfo: SysInstallInfo = await this.sysSettingsService.getSetting(SysInstallInfo); installInfo.bindUserId = null; await this.sysSettingsService.saveSetting(installInfo); + await this.auditLog({ content: "解绑了用户" }); return this.ok({}); } - @Post("/updateLicense", { description: "sys:settings:edit" }) + @Post("/updateLicense", { description: "sys:settings:edit", summary: "更新许可证" }) public async updateLicense(@Body(ALL) body: { license: string }) { await this.plusService.updateLicense(body.license); + await this.auditLog({ content: "更新了许可证" }); return this.ok(true); } } diff --git a/packages/ui/certd-server/src/controller/sys/audit/audit-controller.ts b/packages/ui/certd-server/src/controller/sys/audit/audit-controller.ts index 514be0a56..a4ed9cdcd 100644 --- a/packages/ui/certd-server/src/controller/sys/audit/audit-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/audit/audit-controller.ts @@ -13,17 +13,20 @@ export class SysAuditLogController extends BaseController { @Post("/page", { description: Constants.per.authOnly, summary: "分页查询审计日志" }) async page(@Body(ALL) body: any) { + if (body.query?.scope) { + delete body.query.userId; + } const pageRet = await this.auditService.page(body); return this.ok(pageRet); } - @Post("/delete", { description: Constants.per.authOnly }) + @Post("/delete", { description: Constants.per.authOnly, summary: "删除审计日志" }) async delete(@Query("id") id: number) { - await this.auditService.delete(id); + await this.auditService.delete([id]); return this.ok({}); } - @Post("/clean", { description: Constants.per.authOnly }) + @Post("/clean", { description: Constants.per.authOnly, summary: "清理过期审计日志" }) async clean(@Body("retentionDays") retentionDays: number) { const count = await this.auditService.cleanExpired(retentionDays || 90); return this.ok({ deletedCount: count }); diff --git a/packages/ui/certd-server/src/controller/sys/authority/permission-controller.ts b/packages/ui/certd-server/src/controller/sys/authority/permission-controller.ts index ef016264c..67ed733f0 100644 --- a/packages/ui/certd-server/src/controller/sys/authority/permission-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/authority/permission-controller.ts @@ -1,7 +1,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core"; import { CrudController } from "@certd/lib-server"; import { PermissionService } from "../../../modules/sys/authority/service/permission-service.js"; -import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 权限资源 @@ -15,8 +15,11 @@ export class PermissionController extends CrudController { getService() { return this.service; } + getAuditType(): string { + return AuditType.permission; + } - @Post("/page", { description: "sys:auth:per:view" }) + @Post("/page", { description: "sys:auth:per:view", summary: "查询权限分页列表" }) async page( @Body(ALL) body @@ -24,48 +27,42 @@ export class PermissionController extends CrudController { return await super.page(body); } - @Post("/add", { description: "sys:auth:per:add" }) + @Post("/add", { description: "sys:auth:per:add", summary: "添加权限" }) async add( @Body(ALL) bean ) { const res = await super.add(bean); await this.auditLog({ - type: AuditType.permission, - action: AuditAction.add, content: `新增了权限「${bean.name}」(ID:${res.data})`, }); return res; } - @Post("/update", { description: "sys:auth:per:edit" }) + @Post("/update", { description: "sys:auth:per:edit", summary: "更新权限" }) async update( @Body(ALL) bean ) { const res = await super.update(bean); await this.auditLog({ - type: AuditType.permission, - action: AuditAction.update, content: `修改了权限「${bean.name}」(ID:${bean.id})`, }); return res; } - @Post("/delete", { description: "sys:auth:per:remove" }) + @Post("/delete", { description: "sys:auth:per:remove", summary: "删除权限" }) async delete( @Query("id") id: number ) { const res = await super.delete(id); await this.auditLog({ - type: AuditType.permission, - action: AuditAction.delete, content: `删除了权限(ID:${id})`, }); return res; } - @Post("/tree", { description: "sys:auth:per:view" }) + @Post("/tree", { description: "sys:auth:per:view", summary: "查询权限树" }) async tree() { const tree = await this.service.tree({}); return this.ok(tree); diff --git a/packages/ui/certd-server/src/controller/sys/authority/role-controller.ts b/packages/ui/certd-server/src/controller/sys/authority/role-controller.ts index 072ff9816..823ea8da9 100644 --- a/packages/ui/certd-server/src/controller/sys/authority/role-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/authority/role-controller.ts @@ -1,7 +1,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/core"; import { CrudController } from "@certd/lib-server"; import { RoleService } from "../../../modules/sys/authority/service/role-service.js"; -import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 系统用户 @@ -16,6 +16,10 @@ export class RoleController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.role; + } + @Post("/page", { description: "sys:auth:role:view" }) async page( @Body(ALL) @@ -30,34 +34,30 @@ export class RoleController extends CrudController { return this.ok(ret); } - @Post("/add", { description: "sys:auth:role:add" }) + @Post("/add", { description: "sys:auth:role:add", summary: "新增角色" }) async add( @Body(ALL) bean ) { const res = await super.add(bean); await this.auditLog({ - type: AuditType.role, - action: AuditAction.add, content: `新增了角色「${bean.name}」(ID:${res.data})`, }); return res; } - @Post("/update", { description: "sys:auth:role:edit" }) + @Post("/update", { description: "sys:auth:role:edit", summary: "修改角色" }) async update( @Body(ALL) bean ) { const res = await super.update(bean); await this.auditLog({ - type: AuditType.role, - action: AuditAction.update, content: `修改了角色「${bean.name}」(ID:${bean.id})`, }); return res; } - @Post("/delete", { description: "sys:auth:role:remove" }) + @Post("/delete", { description: "sys:auth:role:remove", summary: "删除角色" }) async delete( @Query("id") id: number @@ -67,8 +67,6 @@ export class RoleController extends CrudController { } const res = await super.delete(id); await this.auditLog({ - type: AuditType.role, - action: AuditAction.delete, content: `删除了角色(ID:${id})`, }); return res; @@ -97,9 +95,10 @@ export class RoleController extends CrudController { * @param roleId * @param permissionIds */ - @Post("/authz", { description: "sys:auth:role:edit" }) + @Post("/authz", { description: "sys:auth:role:edit", summary: "角色授权" }) async authz(@Body("roleId") roleId, @Body("permissionIds") permissionIds) { await this.service.authz(roleId, permissionIds); + await this.auditLog({ content: `为角色(ID:${roleId})进行了授权` }); return this.ok(null); } } diff --git a/packages/ui/certd-server/src/controller/sys/authority/user-controller.ts b/packages/ui/certd-server/src/controller/sys/authority/user-controller.ts index f669fe545..a97863650 100644 --- a/packages/ui/certd-server/src/controller/sys/authority/user-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/authority/user-controller.ts @@ -6,7 +6,7 @@ import { PermissionService } from "../../../modules/sys/authority/service/permis import { Constants } from "@certd/lib-server"; import { In } from "typeorm"; import { LoginService } from "../../../modules/login/service/login-service.js"; -import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 系统用户 @@ -25,6 +25,10 @@ export class UserController extends CrudController { @Inject() loginService: LoginService; + getAuditType(): string { + return AuditType.user; + } + getService() { return this.service; } @@ -93,35 +97,31 @@ export class UserController extends CrudController { return ret; } - @Post("/add", { description: "sys:auth:user:add" }) + @Post("/add", { description: "sys:auth:user:add", summary: "新增用户" }) async add( @Body(ALL) bean ) { const res = await super.add(bean); await this.auditLog({ - type: AuditType.user, - action: AuditAction.add, content: `新增了用户「${bean.username}」(ID:${res.data})`, }); return res; } - @Post("/update", { description: "sys:auth:user:edit" }) + @Post("/update", { description: "sys:auth:user:edit", summary: "修改用户" }) async update( @Body(ALL) bean ) { const res = await super.update(bean); await this.auditLog({ - type: AuditType.user, - action: AuditAction.update, content: `修改了用户「${bean.username}」(ID:${bean.id})`, }); return res; } - @Post("/delete", { description: "sys:auth:user:remove" }) + @Post("/delete", { description: "sys:auth:user:remove", summary: "删除用户" }) async delete( @Query("id") id: number @@ -134,8 +134,6 @@ export class UserController extends CrudController { } const res = await super.delete(id); await this.auditLog({ - type: AuditType.user, - action: AuditAction.delete, content: `删除了用户(ID:${id})`, }); return res; @@ -144,13 +142,14 @@ export class UserController extends CrudController { /** * 解除登录锁定 */ - @Post("/unlockBlock", { description: "sys:auth:user:edit" }) + @Post("/unlockBlock", { description: "sys:auth:user:edit", summary: "解锁登录锁定" }) public async unlockBlock(@Body("id") id: number) { const info = await this.service.info(id, ["password"]); this.loginService.clearCacheOnSuccess(info.username); if (info.mobile) { this.loginService.clearCacheOnSuccess(info.mobile); } + await this.auditLog({ content: `解锁了用户登录锁定(ID:${id})` }); return this.ok(info); } diff --git a/packages/ui/certd-server/src/controller/sys/cname/cname-provider-controller.ts b/packages/ui/certd-server/src/controller/sys/cname/cname-provider-controller.ts index 47e341f25..282f0245e 100644 --- a/packages/ui/certd-server/src/controller/sys/cname/cname-provider-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/cname/cname-provider-controller.ts @@ -2,6 +2,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c import { CrudController } from "@certd/lib-server"; import { merge } from "lodash-es"; import { CnameProviderService } from "../../../modules/cname/service/cname-provider-service.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 授权 @@ -16,6 +17,10 @@ export class CnameRecordController extends CrudController return this.service; } + getAuditType(): string { + return AuditType.cname; + } + @Post("/page", { description: "sys:settings:view" }) async page(@Body(ALL) body: any) { body.query = body.query ?? {}; @@ -27,7 +32,7 @@ export class CnameRecordController extends CrudController return super.list(body); } - @Post("/add", { description: "sys:settings:edit" }) + @Post("/add", { description: "sys:settings:edit", summary: "添加CNAME服务" }) async add(@Body(ALL) bean: any) { const def: any = { isDefault: false, @@ -35,13 +40,17 @@ export class CnameRecordController extends CrudController }; merge(bean, def); bean.userId = this.getUserId(); - return super.add(bean); + const res = await super.add(bean); + await this.auditLog({ content: `添加了CNAME服务(ID:${res.data})` }); + return res; } - @Post("/update", { description: "sys:settings:edit" }) + @Post("/update", { description: "sys:settings:edit", summary: "更新CNAME服务" }) async update(@Body(ALL) bean: any) { bean.userId = this.getUserId(); - return super.update(bean); + const res = await super.update(bean); + await this.auditLog({ content: `更新了CNAME服务(ID:${bean.id})` }); + return res; } @Post("/info", { description: "sys:settings:view" }) @@ -49,26 +58,31 @@ export class CnameRecordController extends CrudController return super.info(id); } - @Post("/delete", { description: "sys:settings:edit" }) + @Post("/delete", { description: "sys:settings:edit", summary: "删除CNAME服务" }) async delete(@Query("id") id: number) { - return super.delete(id); + const res = await super.delete(id); + await this.auditLog({ content: `删除了CNAME服务(ID:${id})` }); + return res; } - @Post("/deleteByIds", { description: "sys:settings:edit" }) + @Post("/deleteByIds", { description: "sys:settings:edit", summary: "批量删除CNAME服务" }) async deleteByIds(@Body("ids") ids: number[]) { const res = await this.service.delete(ids); + await this.auditLog({ content: `批量删除了${ids.length}条CNAME服务` }); return this.ok(res); } - @Post("/setDefault", { description: "sys:settings:edit" }) + @Post("/setDefault", { description: "sys:settings:edit", summary: "设置默认CNAME服务" }) async setDefault(@Body("id") id: number) { await this.service.setDefault(id); + await this.auditLog({ content: `设置了默认CNAME服务(ID:${id})` }); return this.ok(); } - @Post("/setDisabled", { description: "sys:settings:edit" }) + @Post("/setDisabled", { description: "sys:settings:edit", summary: "禁用/启用CNAME服务" }) async setDisabled(@Body("id") id: number, @Body("disabled") disabled: boolean) { await this.service.setDisabled(id, disabled); + await this.auditLog({ content: `${disabled ? "禁用" : "启用"}了CNAME服务(ID:${id})` }); return this.ok(); } } diff --git a/packages/ui/certd-server/src/controller/sys/enterprise/project-controller.ts b/packages/ui/certd-server/src/controller/sys/enterprise/project-controller.ts index 54a141322..0c0a62257 100644 --- a/packages/ui/certd-server/src/controller/sys/enterprise/project-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/enterprise/project-controller.ts @@ -3,7 +3,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c import { ProjectService } from "../../../modules/sys/enterprise/service/project-service.js"; import { ProjectEntity } from "../../../modules/sys/enterprise/entity/project.js"; import { merge } from "lodash-es"; -import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -16,22 +16,26 @@ export class SysProjectController extends CrudController { @Inject() sysSettingsService: SysSettingsService; + getAuditType(): string { + return AuditType.project; + } + getService() { return this.service; } - @Post("/page", { description: "sys:settings:view" }) + @Post("/page", { description: "sys:settings:view", summary: "查询项目分页列表" }) async page(@Body(ALL) body: any) { body.query = body.query ?? {}; return await super.page(body); } - @Post("/list", { description: "sys:settings:view" }) + @Post("/list", { description: "sys:settings:view", summary: "查询项目列表" }) async list(@Body(ALL) body: any) { return super.list(body); } - @Post("/add", { description: "sys:settings:edit" }) + @Post("/add", { description: "sys:settings:edit", summary: "添加项目" }) async add(@Body(ALL) bean: any) { const def: any = { isDefault: false, @@ -45,54 +49,49 @@ export class SysProjectController extends CrudController { adminId: bean.userId, }); await this.auditLog({ - type: AuditType.project, - action: AuditAction.add, content: `新增了项目「${bean.name}」(ID:${res.data})`, }); return res; } - @Post("/update", { description: "sys:settings:edit" }) + @Post("/update", { description: "sys:settings:edit", summary: "更新项目" }) async update(@Body(ALL) bean: any) { bean.userId = this.getUserId(); const res = await super.update(bean); await this.auditLog({ - type: AuditType.project, - action: AuditAction.update, content: `修改了项目「${bean.name}」(ID:${bean.id})`, }); return res; } - @Post("/info", { description: "sys:settings:view" }) + @Post("/info", { description: "sys:settings:view", summary: "查询项目详情" }) async info(@Query("id") id: number) { return super.info(id); } - @Post("/delete", { description: "sys:settings:edit" }) + @Post("/delete", { description: "sys:settings:edit", summary: "删除项目" }) async delete(@Query("id") id: number) { const res = await super.delete(id); await this.auditLog({ - type: AuditType.project, - action: AuditAction.delete, content: `删除了项目(ID:${id})`, }); return res; } - @Post("/deleteByIds", { description: "sys:settings:edit" }) + @Post("/deleteByIds", { description: "sys:settings:edit", summary: "批量删除项目" }) async deleteByIds(@Body("ids") ids: number[]) { const res = await this.service.delete(ids); + await this.auditLog({ + content: `批量删除了${ids.length}个项目`, + }); return this.ok(res); } - @Post("/setDisabled", { description: "sys:settings:edit" }) + @Post("/setDisabled", { description: "sys:settings:edit", summary: "禁用/启用项目" }) async setDisabled(@Body("id") id: number, @Body("disabled") disabled: boolean) { await this.service.setDisabled(id, disabled); const project = await this.service.info(id); const actionText = disabled ? "禁用了" : "启用了"; await this.auditLog({ - type: AuditType.project, - action: AuditAction.disable, content: `${actionText}项目「${project.name}」(ID:${id})`, }); return this.ok(); diff --git a/packages/ui/certd-server/src/controller/sys/enterprise/project-member-controller.ts b/packages/ui/certd-server/src/controller/sys/enterprise/project-member-controller.ts index 8998ce5ee..79357709e 100644 --- a/packages/ui/certd-server/src/controller/sys/enterprise/project-member-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/enterprise/project-member-controller.ts @@ -4,6 +4,7 @@ import { ProjectMemberEntity } from "../../../modules/sys/enterprise/entity/proj import { ProjectMemberService } from "../../../modules/sys/enterprise/service/project-member-service.js"; import { merge } from "lodash-es"; import { ProjectService } from "../../../modules/sys/enterprise/service/project-service.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -15,7 +16,6 @@ export class SysProjectMemberController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.monitor; + } + @Post("/page", { description: "sys:settings:view", summary: "管理员查询站点监控分页列表" }) async page(@Body(ALL) body: any) { body.query = body.query ?? {}; @@ -44,12 +49,16 @@ export class SysSiteInfoController extends CrudController { @Post("/delete", { description: "sys:settings:edit", summary: "管理员删除站点监控" }) async delete(@Query("id") id: number) { - return await super.delete(id); + await super.delete(id); + await this.auditLog({ content: `管理员删除了站点监控(ID:${id})` }); + return this.ok(); } @Post("/batchDelete", { description: "sys:settings:edit", summary: "管理员批量删除站点监控" }) async batchDelete(@Body("ids") ids: number[]) { + const count = ids.length; await this.service.delete(ids); + await this.auditLog({ content: `管理员批量删除了${count}条站点监控` }); return this.ok(); } } diff --git a/packages/ui/certd-server/src/controller/sys/pipeline/pipeline-controller.ts b/packages/ui/certd-server/src/controller/sys/pipeline/pipeline-controller.ts index 03719d541..43b4aa1f3 100644 --- a/packages/ui/certd-server/src/controller/sys/pipeline/pipeline-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/pipeline/pipeline-controller.ts @@ -3,6 +3,7 @@ import { CrudController } from "@certd/lib-server"; import { ApiTags } from "@midwayjs/swagger"; import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js"; import { checkPlus } from "@certd/plus-core"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; @Provide() @Controller("/api/sys/pipeline") @@ -15,6 +16,10 @@ export class SysPipelineController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.pipeline; + } + @Post("/page", { description: "sys:settings:view", summary: "管理员查询用户流水线分页列表" }) async page(@Body(ALL) body: any) { body.query = body.query ?? {}; @@ -41,13 +46,16 @@ export class SysPipelineController extends CrudController { @Post("/delete", { description: "sys:settings:edit", summary: "管理员删除用户流水线" }) async delete(@Query("id") id: number) { await this.service.delete(id); + await this.auditLog({ content: `管理员删除了用户流水线(ID:${id})` }); return this.ok(); } @Post("/batchDelete", { description: "sys:settings:edit", summary: "管理员批量删除用户流水线" }) async batchDelete(@Body("ids") ids: number[]) { checkPlus(); + const count = ids.length; await this.service.batchDelete(ids); + await this.auditLog({ content: `管理员批量删除了${count}条用户流水线` }); return this.ok(); } } diff --git a/packages/ui/certd-server/src/controller/sys/plugin/plugin-controller.ts b/packages/ui/certd-server/src/controller/sys/plugin/plugin-controller.ts index 26845c6f6..27643db08 100644 --- a/packages/ui/certd-server/src/controller/sys/plugin/plugin-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/plugin/plugin-controller.ts @@ -3,6 +3,7 @@ import { merge } from "lodash-es"; import { CrudController } from "@certd/lib-server"; import { PluginImportReq, PluginService } from "../../../modules/plugin/service/plugin-service.js"; import { CommPluginConfig, PluginConfig, PluginConfigService } from "../../../modules/plugin/service/plugin-config-service.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 插件 */ @@ -19,6 +20,10 @@ export class PluginController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.plugin; + } + @Post("/page", { description: "sys:settings:view" }) async page(@Body(ALL) body: any) { body.query = body.query ?? {}; @@ -30,19 +35,22 @@ export class PluginController extends CrudController { return super.list(body); } - @Post("/add", { description: "sys:settings:edit" }) + @Post("/add", { description: "sys:settings:edit", summary: "添加插件" }) async add(@Body(ALL) bean: any) { const def: any = { isDefault: false, disabled: false, }; merge(bean, def); - return super.add(bean); + const res = await super.add(bean); + await this.auditLog({ content: `新增了插件「${bean.name}」(ID:${res.data}, 类型:${bean.type})` }); + return res; } - @Post("/update", { description: "sys:settings:edit" }) + @Post("/update", { description: "sys:settings:edit", summary: "更新插件" }) async update(@Body(ALL) bean: any) { const res = await super.update(bean); + await this.auditLog({ content: `修改了插件「${bean.name}」(ID:${bean.id})` }); return res; } @@ -51,21 +59,25 @@ export class PluginController extends CrudController { return super.info(id); } - @Post("/delete", { description: "sys:settings:edit" }) + @Post("/delete", { description: "sys:settings:edit", summary: "删除插件" }) async delete(@Query("id") id: number) { const res = await this.service.deleteByIds([id]); + await this.auditLog({ content: `删除了插件(ID:${id})` }); return this.ok(res); } - @Post("/deleteByIds", { description: "sys:settings:edit" }) + @Post("/deleteByIds", { description: "sys:settings:edit", summary: "批量删除插件" }) async deleteByIds(@Body("ids") ids: number[]) { const res = await this.service.deleteByIds(ids); + await this.auditLog({ content: `批量删除了${ids.length}条插件` }); return this.ok(res); } - @Post("/setDisabled", { description: "sys:settings:edit" }) + @Post("/setDisabled", { description: "sys:settings:edit", summary: "禁用/启用插件" }) async setDisabled(@Body(ALL) body: { id: number; name: string; type: string; disabled: boolean }) { await this.service.setDisabled(body); + const { id, disabled } = body; + await this.auditLog({ content: `${disabled ? "禁用" : "启用"}了插件(ID:${id})` }); return this.ok(); } @Post("/getCommPluginConfigs", { description: "sys:settings:view" }) @@ -74,9 +86,10 @@ export class PluginController extends CrudController { return this.ok(res); } - @Post("/saveCommPluginConfigs", { description: "sys:settings:edit" }) + @Post("/saveCommPluginConfigs", { description: "sys:settings:edit", summary: "保存公共插件配置" }) async saveCommPluginConfigs(@Body(ALL) body: CommPluginConfig) { const res = await this.pluginConfigService.saveCommPluginConfig(body); + await this.auditLog({ content: "保存了公共插件配置" }); return this.ok(res); } @Post("/getPluginByName", { description: "sys:settings:view" }) @@ -88,19 +101,21 @@ export class PluginController extends CrudController { return this.ok(res); } - @Post("/saveSetting", { description: "sys:settings:edit" }) + @Post("/saveSetting", { description: "sys:settings:edit", summary: "保存插件设置" }) async saveSetting(@Body(ALL) body: PluginConfig) { const res = await this.pluginConfigService.savePluginConfig(body); + await this.auditLog({ content: "保存了插件设置" }); return this.ok(res); } - @Post("/import", { description: "sys:settings:edit" }) + @Post("/import", { description: "sys:settings:edit", summary: "导入插件" }) async import(@Body(ALL) body: PluginImportReq) { const res = await this.service.importPlugin(body); + await this.auditLog({ content: "导入了插件配置" }); return this.ok(res); } - @Post("/export", { description: "sys:settings:edit" }) + @Post("/export", { description: "sys:settings:edit", summary: "导出插件" }) async export(@Body("id") id: number) { const res = await this.service.exportPlugin(id); return this.ok(res); diff --git a/packages/ui/certd-server/src/controller/sys/settings/sys-safe-settings-controller.ts b/packages/ui/certd-server/src/controller/sys/settings/sys-safe-settings-controller.ts index 49b0b8a15..02e5b6297 100644 --- a/packages/ui/certd-server/src/controller/sys/settings/sys-safe-settings-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/settings/sys-safe-settings-controller.ts @@ -2,7 +2,7 @@ import { ALL, Body, Controller, Inject, Post, Provide } from "@midwayjs/core"; import { BaseController, SysSafeSetting } from "@certd/lib-server"; import { cloneDeep } from "lodash-es"; import { SafeService } from "../../../modules/sys/settings/safe-service.js"; -import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -12,6 +12,10 @@ export class SysSettingsController extends BaseController { @Inject() safeService: SafeService; + getAuditType(): string { + return AuditType.settings; + } + @Post("/get", { description: "sys:settings:view" }) async safeGet() { const res = await this.safeService.getSafeSetting(); @@ -24,8 +28,6 @@ export class SysSettingsController extends BaseController { async safeSave(@Body(ALL) body: any) { await this.safeService.saveSafeSetting(body); await this.auditLog({ - type: AuditType.settings, - action: AuditAction.update, content: "修改了安全设置", }); return this.ok({}); @@ -34,9 +36,10 @@ export class SysSettingsController extends BaseController { /** * 立即隐藏 */ - @Post("/hidden", { description: "sys:settings:edit" }) + @Post("/hidden", { description: "sys:settings:edit", summary: "立刻隐藏系统" }) async hiddenImmediate() { await this.safeService.hiddenImmediately(); + await this.auditLog({ content: "立刻隐藏了系统" }); return this.ok({}); } } diff --git a/packages/ui/certd-server/src/controller/sys/settings/sys-settings-controller.ts b/packages/ui/certd-server/src/controller/sys/settings/sys-settings-controller.ts index 7fc10a348..dd798643d 100644 --- a/packages/ui/certd-server/src/controller/sys/settings/sys-settings-controller.ts +++ b/packages/ui/certd-server/src/controller/sys/settings/sys-settings-controller.ts @@ -8,7 +8,7 @@ import { http, logger, utils } from "@certd/basic"; import { CodeService } from "../../../modules/basic/service/code-service.js"; import { SmsServiceFactory } from "../../../modules/basic/sms/factory.js"; import { RuntimeDepsService } from "../../../modules/runtime-deps/runtime-deps-service.js"; -import { AuditType, AuditAction } from "../../modules/sys/enterprise/service/audit-constants.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -32,63 +32,71 @@ export class SysSettingsController extends CrudController { return this.service; } - @Post("/page", { description: "sys:settings:view" }) + getAuditType(): string { + return AuditType.settings; + } + + @Post("/page", { description: "sys:settings:view", summary: "查询系统设置分页列表" }) async page(@Body(ALL) body) { return super.page(body); } - @Post("/list", { description: "sys:settings:view" }) + @Post("/list", { description: "sys:settings:view", summary: "查询系统设置列表" }) async list(@Body(ALL) body) { return super.list(body); } - @Post("/add", { description: "sys:settings:edit" }) + @Post("/add", { description: "sys:settings:edit", summary: "添加系统设置" }) async add(@Body(ALL) bean) { - return super.add(bean); + const res = await super.add(bean); + await this.auditLog({ content: "添加了系统设置" }); + return res; } - @Post("/update", { description: "sys:settings:edit" }) + @Post("/update", { description: "sys:settings:edit", summary: "更新系统设置" }) async update(@Body(ALL) bean) { await this.service.checkUserId(bean.id, this.getUserId()); - return super.update(bean); + const res = await super.update(bean); + await this.auditLog({ content: "更新了系统设置" }); + return res; } - @Post("/info", { description: "sys:settings:view" }) + @Post("/info", { description: "sys:settings:view", summary: "查询系统设置详情" }) async info(@Query("id") id: number) { await this.service.checkUserId(id, this.getUserId()); return super.info(id); } - @Post("/delete", { description: "sys:settings:edit" }) + @Post("/delete", { description: "sys:settings:edit", summary: "删除系统设置" }) async delete(@Query("id") id: number) { await this.service.checkUserId(id, this.getUserId()); - return super.delete(id); + const res = await super.delete(id); + await this.auditLog({ content: "删除了系统设置" }); + return res; } - @Post("/save", { description: "sys:settings:edit" }) + @Post("/save", { description: "sys:settings:edit", summary: "保存系统设置" }) async save(@Body(ALL) bean: SysSettingsEntity) { await this.service.save(bean); await this.auditLog({ - type: AuditType.settings, - action: AuditAction.update, content: "修改了系统设置", }); return this.ok({}); } - @Post("/get", { description: "sys:settings:view" }) + @Post("/get", { description: "sys:settings:view", summary: "查询系统设置" }) async get(@Query("key") key: string) { const entity = await this.service.getByKey(key); return this.ok(entity); } // savePublicSettings - @Post("/getEmailSettings", { description: "sys:settings:view" }) + @Post("/getEmailSettings", { description: "sys:settings:view", summary: "查询邮件服务器设置" }) async getEmailSettings(@Body(ALL) body) { const conf = await getEmailSettings(this.service, this.userSettingsService); return this.ok(conf); } - @Post("/getEmailTemplates", { description: "sys:settings:view" }) + @Post("/getEmailTemplates", { description: "sys:settings:view", summary: "查询邮件模板列表" }) async getEmailTemplates(@Body(ALL) body) { const conf = await getEmailSettings(this.service, this.userSettingsService); const templates = conf.templates || {}; @@ -107,15 +115,16 @@ export class SysSettingsController extends CrudController { return this.ok(proviers); } - @Post("/saveEmailSettings", { description: "sys:settings:edit" }) + @Post("/saveEmailSettings", { description: "sys:settings:edit", summary: "保存邮件服务器设置" }) async saveEmailSettings(@Body(ALL) body) { const conf = await getEmailSettings(this.service, this.userSettingsService); merge(conf, body); await this.service.saveSetting(conf); + await this.auditLog({ content: "保存了邮件服务器设置" }); return this.ok(conf); } - @Post("/getSysSettings", { description: "sys:settings:view" }) + @Post("/getSysSettings", { description: "sys:settings:view", summary: "查询系统配置" }) async getSysSettings() { const publicSettings = await this.service.getPublicSettings(); let privateSettings = await this.service.getPrivateSettings(); @@ -124,7 +133,7 @@ export class SysSettingsController extends CrudController { } // savePublicSettings - @Post("/saveSysSettings", { description: "sys:settings:edit" }) + @Post("/saveSysSettings", { description: "sys:settings:edit", summary: "保存系统设置" }) async saveSysSettings(@Body(ALL) body: { public: SysPublicSettings; private: SysPrivateSettings }) { const publicSettings = await this.service.getPublicSettings(); const privateSettings = await this.service.getPrivateSettings(); @@ -132,16 +141,18 @@ export class SysSettingsController extends CrudController { merge(privateSettings, body.private); await this.service.savePublicSettings(publicSettings); await this.service.savePrivateSettings(privateSettings); + await this.auditLog({ content: "保存了系统设置" }); return this.ok({}); } - @Post("/stopOtherUserTimer", { description: "sys:settings:edit" }) + @Post("/stopOtherUserTimer", { description: "sys:settings:edit", summary: "停止其他用户定时任务" }) async stopOtherUserTimer(@Body(ALL) body) { await this.pipelineService.stopOtherUserPipeline(1); + await this.auditLog({ content: "停止了其他用户定时任务" }); return this.ok({}); } - @Post("/testProxy", { description: "sys:settings:edit" }) + @Post("/testProxy", { description: "sys:settings:edit", summary: "测试代理" }) async testProxy(@Body(ALL) body) { const google = "https://www.google.com/"; const baidu = "https://www.baidu.com/"; @@ -179,19 +190,19 @@ export class SysSettingsController extends CrudController { }); } - @Post("/testSms", { description: "sys:settings:edit" }) + @Post("/testSms", { description: "sys:settings:edit", summary: "测试短信" }) async testSms(@Body(ALL) body) { await this.codeService.sendSmsCode(body.phoneCode, body.mobile); return this.ok({}); } - @Post("/getSmsTypeDefine", { description: "sys:settings:view" }) + @Post("/getSmsTypeDefine", { description: "sys:settings:view", summary: "查询短信类型定义" }) async getSmsTypeDefine(@Body("type") type: string) { const define = await SmsServiceFactory.getDefine(type); return this.ok(define); } - @Post("/safe/get", { description: "sys:settings:view" }) + @Post("/safe/get", { description: "sys:settings:view", summary: "查询安全设置" }) async safeGet() { const res = await this.service.getSetting(SysSafeSetting); const clone: SysSafeSetting = cloneDeep(res); @@ -199,7 +210,7 @@ export class SysSettingsController extends CrudController { return this.ok(clone); } - @Post("/safe/save", { description: "sys:settings:edit" }) + @Post("/safe/save", { description: "sys:settings:edit", summary: "保存安全设置" }) async safeSave(@Body(ALL) body: any) { if (body.hidden.openPassword) { body.hidden.openPassword = utils.hash.md5(body.hidden.openPassword); @@ -211,24 +222,26 @@ export class SysSettingsController extends CrudController { throw new Error("首次设置需要填写解锁密码"); } await this.service.saveSetting(blankSetting); + await this.auditLog({ content: "保存了安全设置" }); return this.ok({}); } - @Post("/captchaTest", { description: "sys:settings:edit" }) + @Post("/captchaTest", { description: "sys:settings:edit", summary: "测试验证码" }) async captchaTest(@Body(ALL) body: any, @RequestIP() remoteIp: string) { await this.codeService.checkCaptcha(body, { remoteIp }); return this.ok({}); } - @Post("/oauth/providers", { description: "sys:settings:view" }) + @Post("/oauth/providers", { description: "sys:settings:view", summary: "查询OAuth提供商列表" }) async oauthProviders() { const list = await addonRegistry.getDefineList("oauth"); return this.ok(list); } - @Post("/clearRuntimeDeps", { description: "sys:settings:edit" }) + @Post("/clearRuntimeDeps", { description: "sys:settings:edit", summary: "清除运行时依赖" }) async clearRuntimeDeps() { await this.runtimeDepsService.clearRuntimeDeps(); + await this.auditLog({ content: "清除了运行时依赖" }); return this.ok(true); } } diff --git a/packages/ui/certd-server/src/controller/user/addon/addon-controller.ts b/packages/ui/certd-server/src/controller/user/addon/addon-controller.ts index b7f310bff..6eefe106e 100644 --- a/packages/ui/certd-server/src/controller/user/addon/addon-controller.ts +++ b/packages/ui/certd-server/src/controller/user/addon/addon-controller.ts @@ -5,6 +5,7 @@ import { checkPlus } from "@certd/plus-core"; import { http, logger, utils } from "@certd/basic"; import { TaskServiceBuilder } from "../../../modules/pipeline/service/getter/task-service-getter.js"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * Addon @@ -24,6 +25,10 @@ export class AddonController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.addon; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询Addon分页列表" }) async page(@Body(ALL) body) { const { projectId, userId } = await this.getProjectUserIdRead(); @@ -68,7 +73,9 @@ export class AddonController extends CrudController { if (define.needPlus) { checkPlus(); } - return super.add(bean); + const res = await super.add(bean); + this.auditLog({ content: `新增了Addon「${bean.name}」(ID:${res.data}, 类型:${bean.type})` }); + return res; } @Post("/update", { description: Constants.per.authOnly, summary: "更新Addon" }) @@ -91,7 +98,9 @@ export class AddonController extends CrudController { } delete bean.userId; delete bean.projectId; - return super.update(bean); + const res = await super.update(bean); + this.auditLog({ content: `修改了Addon「${bean.name}」(ID:${bean.id})` }); + return res; } @Post("/info", { description: Constants.per.authOnly, summary: "查询Addon详情" }) @@ -103,7 +112,9 @@ export class AddonController extends CrudController { @Post("/delete", { description: Constants.per.authOnly, summary: "删除Addon" }) async delete(@Query("id") id: number) { await this.checkOwner(this.getService(), id, "write"); - return super.delete(id); + const res = await super.delete(id); + this.auditLog({ content: `删除了Addon(ID:${id})` }); + return res; } @Post("/define", { description: Constants.per.authOnly, summary: "查询Addon插件定义" }) @@ -158,6 +169,7 @@ export class AddonController extends CrudController { async setDefault(@Query("addonType") addonType: string, @Query("id") id: number) { const { projectId, userId } = await this.checkOwner(this.getService(), id, "write", true); const res = await this.service.setDefault(id, userId, addonType, projectId); + this.auditLog({ content: `设置了默认Addon(ID:${id})` }); return this.ok(res); } diff --git a/packages/ui/certd-server/src/controller/user/audit/audit-controller.ts b/packages/ui/certd-server/src/controller/user/audit/audit-controller.ts index 633b157eb..aa5c6909e 100644 --- a/packages/ui/certd-server/src/controller/user/audit/audit-controller.ts +++ b/packages/ui/certd-server/src/controller/user/audit/audit-controller.ts @@ -13,11 +13,20 @@ export class AuditLogController extends BaseController { @Post("/page", { description: Constants.per.authOnly, summary: "分页查询当前用户操作日志" }) async page(@Body(ALL) body: any) { - const userId = this.getUserId(); - if (!body.query) { - body.query = {}; + const { projectId, userId } = await this.getProjectUserIdRead(); + const query: any = { } + if (projectId) { + //如果是项目级别,排除userId参数,因为日志这里userId不是-1 ,而是实际的用户 + query.projectId = projectId; + }else{ + query.userId = userId; } - body.query.userId = userId; + body.query = { + ...body.query || {}, + ...query, + scope: "user" + } + const pageRet = await this.auditService.page(body); return this.ok(pageRet); } diff --git a/packages/ui/certd-server/src/controller/user/basic/group-controller.ts b/packages/ui/certd-server/src/controller/user/basic/group-controller.ts index ed38e427b..9ea4e7f30 100644 --- a/packages/ui/certd-server/src/controller/user/basic/group-controller.ts +++ b/packages/ui/certd-server/src/controller/user/basic/group-controller.ts @@ -3,6 +3,7 @@ import { Constants, CrudController } from "@certd/lib-server"; import { AuthService } from "../../../modules/sys/authority/service/auth-service.js"; import { GroupService } from "../../../modules/basic/service/group-service.js"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 通知 @@ -20,6 +21,10 @@ export class GroupController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.pipelineGroup; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询分组分页列表" }) async page(@Body(ALL) body: any) { const { projectId, userId } = await this.getProjectUserIdRead(); @@ -52,7 +57,9 @@ export class GroupController extends CrudController { const { projectId, userId } = await this.getProjectUserIdRead(); bean.projectId = projectId; bean.userId = userId; - return await super.add(bean); + const res = await super.add(bean); + this.auditLog({ content: `新增了分组「${bean.name}」(ID:${res.data})` }); + return res; } @Post("/update", { description: Constants.per.authOnly, summary: "更新分组" }) @@ -60,7 +67,9 @@ export class GroupController extends CrudController { await this.checkOwner(this.getService(), bean.id, "write"); delete bean.userId; delete bean.projectId; - return await super.update(bean); + const res = await super.update(bean); + this.auditLog({ content: `修改了分组「${bean.name}」(ID:${bean.id})` }); + return res; } @Post("/info", { description: Constants.per.authOnly, summary: "查询分组详情" }) async info(@Query("id") id: number) { @@ -71,7 +80,9 @@ export class GroupController extends CrudController { @Post("/delete", { description: Constants.per.authOnly, summary: "删除分组" }) async delete(@Query("id") id: number) { await this.checkOwner(this.getService(), id, "write"); - return await super.delete(id); + const res = await super.delete(id); + this.auditLog({ content: `删除了分组(ID:${id})` }); + return res; } @Post("/all", { description: Constants.per.authOnly, summary: "查询所有分组" }) diff --git a/packages/ui/certd-server/src/controller/user/cert/cert-apply-template-controller.ts b/packages/ui/certd-server/src/controller/user/cert/cert-apply-template-controller.ts index 0b3fd53e8..6d59b81d6 100644 --- a/packages/ui/certd-server/src/controller/user/cert/cert-apply-template-controller.ts +++ b/packages/ui/certd-server/src/controller/user/cert/cert-apply-template-controller.ts @@ -2,6 +2,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c import { Constants, CrudController } from "@certd/lib-server"; import { ApiTags } from "@midwayjs/swagger"; import { CertApplyTemplateService } from "../../../modules/cert/service/cert-apply-template-service.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; @Provide() @Controller("/api/cert/apply-template") @@ -14,6 +15,10 @@ export class CertApplyTemplateController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.domain; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询域名分页列表" }) async page(@Body(ALL) body: any) { const { projectId, userId } = await this.getProjectUserIdRead(); @@ -58,7 +63,9 @@ export class DomainController extends CrudController { const { projectId, userId } = await this.getProjectUserIdRead(); bean.projectId = projectId; bean.userId = userId; - return super.add(bean); + const res = await super.add(bean); + this.auditLog({ content: `新增了域名「${bean.domain}」` }); + return res; } @Post("/update", { description: Constants.per.authOnly, summary: "更新域名" }) @@ -66,7 +73,9 @@ export class DomainController extends CrudController { await this.checkOwner(this.getService(), bean.id, "write"); delete bean.userId; delete bean.projectId; - return super.update(bean); + const res = await super.update(bean); + this.auditLog({ content: `修改了域名「${bean.domain}」` }); + return res; } @Post("/info", { description: Constants.per.authOnly, summary: "查询域名详情" }) @@ -78,13 +87,16 @@ export class DomainController extends CrudController { @Post("/delete", { description: Constants.per.authOnly, summary: "删除域名" }) async delete(@Query("id") id: number) { await this.checkOwner(this.getService(), id, "write"); - return super.delete(id); + const res = await super.delete(id); + this.auditLog({ content: `删除了域名(ID:${id})` }); + return res; } @Post("/deleteByIds", { description: Constants.per.authOnly, summary: "批量删除域名" }) async deleteByIds(@Body(ALL) body: any) { const { projectId, userId } = await this.getProjectUserIdRead(); await this.service.batchDelete(body.ids, userId, projectId); + this.auditLog({ content: `批量删除了${body.ids.length}条域名` }); return this.ok(); } @@ -99,6 +111,7 @@ export class DomainController extends CrudController { projectId: projectId, }; await this.service.startDomainImportTask(req); + this.auditLog({ content: "开始了域名导入任务" }); return this.ok(); } @@ -123,6 +136,7 @@ export class DomainController extends CrudController { key, }; await this.service.deleteDomainImportTask(req); + this.auditLog({ content: "删除了域名导入任务" }); return this.ok(); } @@ -139,6 +153,7 @@ export class DomainController extends CrudController { key, }; const item = await this.service.saveDomainImportTask(req); + this.auditLog({ content: "保存了域名导入任务" }); return this.ok(item); } @@ -149,6 +164,7 @@ export class DomainController extends CrudController { userId: userId, projectId: projectId, }); + this.auditLog({ content: "开始了同步域名过期时间任务" }); return this.ok(); } @Post("/sync/expiration/status", { description: Constants.per.authOnly, summary: "查询同步域名过期时间任务状态" }) @@ -169,6 +185,7 @@ export class DomainController extends CrudController { projectId: projectId, setting: { ...body }, }); + this.auditLog({ content: "保存了域名监控设置" }); return this.ok(); } diff --git a/packages/ui/certd-server/src/controller/user/cname/cname-record-controller.ts b/packages/ui/certd-server/src/controller/user/cname/cname-record-controller.ts index 379f78f2d..6bc9587a2 100644 --- a/packages/ui/certd-server/src/controller/user/cname/cname-record-controller.ts +++ b/packages/ui/certd-server/src/controller/user/cname/cname-record-controller.ts @@ -2,6 +2,7 @@ import { ALL, Body, Controller, Inject, Post, Provide, Query } from "@midwayjs/c import { Constants, CrudController } from "@certd/lib-server"; import { CnameRecordService } from "../../../modules/cname/service/cname-record-service.js"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 授权 @@ -17,6 +18,10 @@ export class CnameRecordController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.cname; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询CNAME记录分页列表" }) async page(@Body(ALL) body: any) { const { userId, projectId } = await this.getProjectUserIdRead(); @@ -56,7 +61,9 @@ export class CnameRecordController extends CrudController { const { userId, projectId } = await this.getProjectUserIdWrite(); bean.userId = userId; bean.projectId = projectId; - return super.add(bean); + const res = await super.add(bean); + this.auditLog({ content: `新增了CNAME记录「${bean.domain}」` }); + return res; } @Post("/update", { description: Constants.per.authOnly, summary: "更新CNAME记录" }) @@ -64,7 +71,9 @@ export class CnameRecordController extends CrudController { await this.checkOwner(this.getService(), bean.id, "write"); delete bean.userId; delete bean.projectId; - return super.update(bean); + const res = await super.update(bean); + this.auditLog({ content: `修改了CNAME记录(ID:${bean.id})` }); + return res; } @Post("/info", { description: Constants.per.authOnly, summary: "查询CNAME记录详情" }) @@ -76,13 +85,16 @@ export class CnameRecordController extends CrudController { @Post("/delete", { description: Constants.per.authOnly, summary: "删除CNAME记录" }) async delete(@Query("id") id: number) { await this.checkOwner(this.getService(), id, "write"); - return super.delete(id); + const res = await super.delete(id); + this.auditLog({ content: `删除了CNAME记录(ID:${id})` }); + return res; } @Post("/deleteByIds", { description: Constants.per.authOnly, summary: "批量删除CNAME记录" }) async deleteByIds(@Body(ALL) body: any) { const { userId, projectId } = await this.getProjectUserIdWrite(); await this.service.batchDelete(body.ids, userId, projectId); + this.auditLog({ content: `批量删除了${body.ids.length}条CNAME记录` }); return this.ok(); } @Post("/getByDomain", { description: Constants.per.authOnly, summary: "根据域名获取CNAME记录" }) @@ -103,6 +115,7 @@ export class CnameRecordController extends CrudController { async resetStatus(@Body(ALL) body: { id: number }) { await this.checkOwner(this.getService(), body.id, "read"); const res = await this.service.resetStatus(body.id); + this.auditLog({ content: `重置了CNAME记录状态(ID:${body.id})` }); return this.ok(res); } @Post("/import", { description: Constants.per.authOnly, summary: "导入CNAME记录" }) @@ -114,6 +127,7 @@ export class CnameRecordController extends CrudController { domainList: body.domainList, cnameProviderId: body.cnameProviderId, }); + this.auditLog({ append: `提交${res.count}条` }); return this.ok(res); } } diff --git a/packages/ui/certd-server/src/controller/user/enterprise/project-controller.ts b/packages/ui/certd-server/src/controller/user/enterprise/project-controller.ts index a02fa4273..8ca6d866d 100644 --- a/packages/ui/certd-server/src/controller/user/enterprise/project-controller.ts +++ b/packages/ui/certd-server/src/controller/user/enterprise/project-controller.ts @@ -4,6 +4,7 @@ import { AuthService } from "../../../modules/sys/authority/service/auth-service import { ProjectService } from "../../../modules/sys/enterprise/service/project-service.js"; import { ProjectMemberService } from "../../../modules/sys/enterprise/service/project-member-service.js"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -24,6 +25,10 @@ export class UserProjectController extends BaseController { return this.service; } + getAuditType(): string { + return AuditType.enterprise; + } + /** * @param body * @returns @@ -63,6 +68,7 @@ export class UserProjectController extends BaseController { async applyJoin(@Body(ALL) body: any) { const userId = this.getUserId(); const res = await this.service.applyJoin({ userId, projectId: body.projectId }); + this.auditLog({ content: "申请了加入项目" }); return this.ok(res); } @@ -84,6 +90,7 @@ export class UserProjectController extends BaseController { status, permission, }); + this.auditLog({ content: "更新了项目成员" }); return this.ok(res); } @@ -92,6 +99,7 @@ export class UserProjectController extends BaseController { const { projectId } = await this.getProjectUserIdAdmin(); const { status, permission, userId } = body; const res = await this.service.approveJoin({ userId, projectId: projectId, status, permission }); + this.auditLog({ content: "审批了加入项目申请" }); return this.ok(res); } @@ -100,8 +108,9 @@ export class UserProjectController extends BaseController { const { projectId } = await this.getProjectUserIdAdmin(); await this.projectMemberService.deleteWhere({ projectId, - userId: this.getUserId(), + userId: body.userId, }); + this.auditLog({ content: "删除了项目成员" }); return this.ok(); } @@ -113,6 +122,7 @@ export class UserProjectController extends BaseController { projectId, userId, }); + this.auditLog({ content: "离开了项目" }); return this.ok(); } } diff --git a/packages/ui/certd-server/src/controller/user/enterprise/project-member-controller.ts b/packages/ui/certd-server/src/controller/user/enterprise/project-member-controller.ts index 870ab64b6..6ed7f8202 100644 --- a/packages/ui/certd-server/src/controller/user/enterprise/project-member-controller.ts +++ b/packages/ui/certd-server/src/controller/user/enterprise/project-member-controller.ts @@ -5,6 +5,7 @@ import { ProjectMemberService } from "../../../modules/sys/enterprise/service/pr import { merge } from "lodash-es"; import { ProjectService } from "../../../modules/sys/enterprise/service/project-service.js"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @Provide() @@ -24,6 +25,10 @@ export class ProjectMemberController extends CrudController return this.service; } + getAuditType(): string { + return AuditType.enterprise; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询项目成员分页列表" }) async page(@Body(ALL) body: any) { const { projectId } = await this.getProjectUserIdRead(); @@ -53,7 +58,9 @@ export class ProjectMemberController extends CrudController projectId: bean.projectId, }); - return super.add(bean); + const res = await super.add(bean); + this.auditLog({ content: `新增了项目成员(ID:${res.data})` }); + return res; } @Post("/update", { description: Constants.per.authOnly, summary: "更新项目成员" }) @@ -71,7 +78,7 @@ export class ProjectMemberController extends CrudController permission: bean.permission, status: bean.status, }); - + this.auditLog({ content: `修改了项目成员(ID:${bean.id})` }); return this.ok(res); } @@ -98,7 +105,9 @@ export class ProjectMemberController extends CrudController userId: this.getUserId(), projectId: projectId, }); - return super.delete(id); + const res = await super.delete(id); + this.auditLog({ content: `删除了项目成员(ID:${id})` }); + return res; } @Post("/deleteByIds", { description: Constants.per.authOnly, summary: "批量删除项目成员" }) @@ -115,6 +124,7 @@ export class ProjectMemberController extends CrudController await this.service.delete(id as any); } + this.auditLog({ content: `批量删除了${ids.length}条项目成员` }); return this.ok({}); } } diff --git a/packages/ui/certd-server/src/controller/user/enterprise/transfer-controller.ts b/packages/ui/certd-server/src/controller/user/enterprise/transfer-controller.ts index 55bccd27f..92f2b1555 100644 --- a/packages/ui/certd-server/src/controller/user/enterprise/transfer-controller.ts +++ b/packages/ui/certd-server/src/controller/user/enterprise/transfer-controller.ts @@ -2,6 +2,7 @@ import { BaseController, Constants } from "@certd/lib-server"; import { Controller, Inject, Post, Provide } from "@midwayjs/core"; import { TransferService } from "../../../modules/sys/enterprise/service/transfer-service.js"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -16,6 +17,10 @@ export class TransferController extends BaseController { return this.service; } + getAuditType(): string { + return AuditType.enterprise; + } + /** * 我自己的资源 * @param body @@ -38,6 +43,7 @@ export class TransferController extends BaseController { const { projectId } = await this.getProjectUserIdRead(); const userId = this.getUserId(); await this.service.transferAll(userId, projectId); + this.auditLog({ content: "迁移了项目资源" }); return this.ok(); } } diff --git a/packages/ui/certd-server/src/controller/user/mine/email-controller.ts b/packages/ui/certd-server/src/controller/user/mine/email-controller.ts index 552186a57..db70b6c12 100644 --- a/packages/ui/certd-server/src/controller/user/mine/email-controller.ts +++ b/packages/ui/certd-server/src/controller/user/mine/email-controller.ts @@ -3,6 +3,7 @@ import { BaseController } from "@certd/lib-server"; import { Constants } from "@certd/lib-server"; import { EmailService } from "../../../modules/basic/service/email-service.js"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -13,10 +14,15 @@ export class EmailController extends BaseController { @Inject() emailService: EmailService; + getAuditType(): string { + return AuditType.mine; + } + @Post("/test", { description: Constants.per.authOnly, summary: "测试邮件发送" }) public async test(@Body("receiver") receiver) { const userId = super.getUserId(); await this.emailService.test(userId, receiver); + this.auditLog({ content: "测试了邮件发送" }); return this.ok({}); } @@ -31,6 +37,7 @@ export class EmailController extends BaseController { public async add(@Body("email") email) { const userId = super.getUserId(); await this.emailService.add(userId, email); + this.auditLog({ content: "添加了邮件" }); return this.ok({}); } @@ -38,6 +45,7 @@ export class EmailController extends BaseController { public async delete(@Body("email") email) { const userId = super.getUserId(); await this.emailService.delete(userId, email); + this.auditLog({ content: "删除了邮件" }); return this.ok({}); } } diff --git a/packages/ui/certd-server/src/controller/user/mine/mine-controller.ts b/packages/ui/certd-server/src/controller/user/mine/mine-controller.ts index 1faefb321..0935aafaf 100644 --- a/packages/ui/certd-server/src/controller/user/mine/mine-controller.ts +++ b/packages/ui/certd-server/src/controller/user/mine/mine-controller.ts @@ -9,6 +9,7 @@ import { http, logger, utils } from "@certd/basic"; import { ApiTags } from "@midwayjs/swagger"; import { CodeService } from "../../../modules/basic/service/code-service.js"; import { EmailService } from "../../../modules/basic/service/email-service.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -40,6 +41,10 @@ export class MineController extends BaseController { @Inject() emailService: EmailService; + getAuditType(): string { + return AuditType.mine; + } + @Post("/info", { description: Constants.per.authOnly, summary: "查询用户信息" }) public async info() { const userId = this.getUserId(); @@ -73,6 +78,7 @@ export class MineController extends BaseController { public async changePassword(@Body(ALL) body: any) { const userId = this.getUserId(); await this.userService.changePassword(userId, body); + this.auditLog({ content: "修改了密码" }); return this.ok({}); } @@ -80,6 +86,7 @@ export class MineController extends BaseController { public async initPassword(@Body(ALL) body: any) { const userId = this.getUserId(); await this.userService.initPassword(userId, body); + this.auditLog({ content: "初始化了密码" }); return this.ok({}); } @@ -91,6 +98,7 @@ export class MineController extends BaseController { avatar: body.avatar, nickName: body.nickName, }); + this.auditLog({ content: "更新了个人资料" }); return this.ok({}); } @@ -129,6 +137,7 @@ export class MineController extends BaseController { phoneCode: body.phoneCode, mobile: body.mobile, }); + this.auditLog({ content: "修改了手机号" }); return this.ok({}); } @@ -145,6 +154,7 @@ export class MineController extends BaseController { await this.userService.updateEmail(userId, { email: body.email, }); + this.auditLog({ content: "修改了邮箱" }); return this.ok({}); } @@ -198,6 +208,7 @@ export class MineController extends BaseController { }), }); + this.auditLog({ content: "初始化了Let's Encrypt ACME账号和邮件通知" }); return this.ok({ success: true }); } } diff --git a/packages/ui/certd-server/src/controller/user/mine/passkey-controller.ts b/packages/ui/certd-server/src/controller/user/mine/passkey-controller.ts index daed1c482..420d63380 100644 --- a/packages/ui/certd-server/src/controller/user/mine/passkey-controller.ts +++ b/packages/ui/certd-server/src/controller/user/mine/passkey-controller.ts @@ -3,6 +3,7 @@ import { PasskeyService } from "../../../modules/login/service/passkey-service.j import { BaseController, Constants } from "@certd/lib-server"; import { UserService } from "../../../modules/sys/authority/service/user-service.js"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; @Provide() @Controller("/api/mine/passkey") @@ -14,6 +15,10 @@ export class MinePasskeyController extends BaseController { @Inject() userService: UserService; + getAuditType(): string { + return AuditType.mine; + } + @Post("/generateRegistration", { description: Constants.per.authOnly, summary: "生成Passkey注册选项" }) public async generateRegistration( @Body(ALL) @@ -46,7 +51,7 @@ export class MinePasskeyController extends BaseController { const deviceName = body.deviceName; const result = await this.passkeyService.registerPasskey(userId, response, challenge, deviceName, this.ctx); - + this.auditLog({ content: "验证注册了Passkey" }); return this.ok(result); } @@ -62,6 +67,7 @@ export class MinePasskeyController extends BaseController { const result = await this.passkeyService.registerPasskey(userId, response, challenge, deviceName, this.ctx); + this.auditLog({ content: "注册了Passkey" }); return this.ok(result); } @@ -90,6 +96,7 @@ export class MinePasskeyController extends BaseController { } await this.passkeyService.delete([passkey.id]); + this.auditLog({ content: "解绑了Passkey" }); return this.ok({}); } } diff --git a/packages/ui/certd-server/src/controller/user/mine/setting-two-factor-controller.ts b/packages/ui/certd-server/src/controller/user/mine/setting-two-factor-controller.ts index cab7a7280..1b5df94f4 100644 --- a/packages/ui/certd-server/src/controller/user/mine/setting-two-factor-controller.ts +++ b/packages/ui/certd-server/src/controller/user/mine/setting-two-factor-controller.ts @@ -6,6 +6,7 @@ import { merge } from "lodash-es"; import { TwoFactorService } from "../../../modules/mine/service/two-factor-service.js"; import { isPlus } from "@certd/plus-core"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -19,6 +20,10 @@ export class UserTwoFactorSettingController extends BaseController { @Inject() twoFactorService: TwoFactorService; + getAuditType(): string { + return AuditType.mine; + } + @Post("/get", { description: Constants.per.authOnly, summary: "获取双因子认证设置" }) async get() { const userId = this.getUserId(); @@ -42,6 +47,7 @@ export class UserTwoFactorSettingController extends BaseController { } await this.service.saveSetting(userId, null, setting); + this.auditLog({ content: "保存了双因子认证设置" }); return this.ok({}); } @@ -62,6 +68,7 @@ export class UserTwoFactorSettingController extends BaseController { userId, verifyCode: bean.verifyCode, }); + this.auditLog({ content: "保存了验证器设置" }); return this.ok(); } @@ -69,6 +76,7 @@ export class UserTwoFactorSettingController extends BaseController { async authenticatorOff() { const userId = this.getUserId(); await this.twoFactorService.offAuthenticator(userId); + this.auditLog({ content: "关闭了验证器" }); return this.ok(); } } diff --git a/packages/ui/certd-server/src/controller/user/mine/user-settings-controller.ts b/packages/ui/certd-server/src/controller/user/mine/user-settings-controller.ts index 1eb45bccf..c99581c6d 100644 --- a/packages/ui/certd-server/src/controller/user/mine/user-settings-controller.ts +++ b/packages/ui/certd-server/src/controller/user/mine/user-settings-controller.ts @@ -6,6 +6,7 @@ import { UserGrantSetting } from "../../../modules/mine/service/models.js"; import { isPlus } from "@certd/plus-core"; import { merge } from "lodash-es"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -20,6 +21,10 @@ export class UserSettingsController extends CrudController return this.service; } + getAuditType(): string { + return AuditType.mine; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询用户设置分页列表" }) async page(@Body(ALL) body) { body.query = body.query ?? {}; @@ -62,6 +67,7 @@ export class UserSettingsController extends CrudController async save(@Body(ALL) bean: UserSettingsEntity) { bean.userId = this.getUserId(); await this.service.save(bean); + this.auditLog({ content: "保存了用户设置" }); return this.ok({}); } @@ -88,6 +94,7 @@ export class UserSettingsController extends CrudController merge(setting, bean); await this.service.saveSetting(userId, null, setting); + this.auditLog({ content: "保存了授权设置" }); return this.ok({}); } } diff --git a/packages/ui/certd-server/src/controller/user/monitor/cert-info-controller.ts b/packages/ui/certd-server/src/controller/user/monitor/cert-info-controller.ts index df86f0662..92e05cca9 100644 --- a/packages/ui/certd-server/src/controller/user/monitor/cert-info-controller.ts +++ b/packages/ui/certd-server/src/controller/user/monitor/cert-info-controller.ts @@ -8,6 +8,7 @@ import { logger } from "@certd/basic"; import dayjs from "dayjs"; import { ApiTags } from "@midwayjs/swagger"; import { CertReader } from "@certd/plugin-lib"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -29,6 +30,10 @@ export class CertInfoController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.monitor; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询证书分页列表" }) async page(@Body(ALL) body: any) { body.query = body.query ?? {}; @@ -117,7 +122,9 @@ export class CertInfoController extends CrudController { const { projectId, userId } = await this.getProjectUserIdWrite(); bean.projectId = projectId; bean.userId = userId; - return await super.add(bean); + const res = await super.add(bean); + this.auditLog({ content: `新增了证书(ID:${res.data})` }); + return res; } @Post("/update", { description: Constants.per.authOnly, summary: "更新证书" }) @@ -125,7 +132,9 @@ export class CertInfoController extends CrudController { await this.checkOwner(this.service, bean.id, "write"); delete bean.userId; delete bean.projectId; - return await super.update(bean); + const res = await super.update(bean); + this.auditLog({ content: `修改了证书(ID:${bean.id})` }); + return res; } @Post("/info", { description: Constants.per.authOnly, summary: "查询证书详情" }) async info(@Query("id") id: number) { @@ -136,7 +145,9 @@ export class CertInfoController extends CrudController { @Post("/delete", { description: Constants.per.authOnly, summary: "删除证书" }) async delete(@Query("id") id: number) { await this.checkOwner(this.service, id, "write"); - return await super.delete(id); + const res = await super.delete(id); + this.auditLog({ content: `删除了证书(ID:${id})` }); + return res; } @Post("/all", { description: Constants.per.authOnly, summary: "查询所有证书" }) diff --git a/packages/ui/certd-server/src/controller/user/monitor/job-history-controller.ts b/packages/ui/certd-server/src/controller/user/monitor/job-history-controller.ts index 698d2b75e..c57f70f2f 100644 --- a/packages/ui/certd-server/src/controller/user/monitor/job-history-controller.ts +++ b/packages/ui/certd-server/src/controller/user/monitor/job-history-controller.ts @@ -4,6 +4,7 @@ import { ApiTags } from "@midwayjs/swagger"; import { SiteInfoService } from "../../../modules/monitor/index.js"; import { JobHistoryService } from "../../../modules/monitor/service/job-history-service.js"; import { AuthService } from "../../../modules/sys/authority/service/auth-service.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -22,6 +23,10 @@ export class JobHistoryController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.jobHistory; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询监控运行历史分页列表" }) async page(@Body(ALL) body: any) { const { projectId, userId } = await this.getProjectUserIdRead(); @@ -54,12 +59,15 @@ export class JobHistoryController extends CrudController { @Post("/delete", { description: Constants.per.authOnly, summary: "删除监控运行历史" }) async delete(@Query("id") id: number) { await this.checkOwner(this.service, id, "write"); - return await super.delete(id); + const res = await super.delete(id); + this.auditLog({ content: `删除了监控运行历史(ID:${id})` }); + return res; } @Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除监控运行历史" }) async batchDelete(@Body("ids") ids: number[]) { const { projectId, userId } = await this.getProjectUserIdWrite(); await this.service.batchDelete(ids, userId, projectId); + this.auditLog({ content: `批量删除了${ids.length}条监控运行历史` }); return this.ok(); } } diff --git a/packages/ui/certd-server/src/controller/user/monitor/site-info-controller.ts b/packages/ui/certd-server/src/controller/user/monitor/site-info-controller.ts index f181fbe4c..54132d0d8 100644 --- a/packages/ui/certd-server/src/controller/user/monitor/site-info-controller.ts +++ b/packages/ui/certd-server/src/controller/user/monitor/site-info-controller.ts @@ -7,7 +7,7 @@ import { merge } from "lodash-es"; import { SiteIpService } from "../../../modules/monitor/service/site-ip-service.js"; import { utils } from "@certd/basic"; import { ApiTags } from "@midwayjs/swagger"; -import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -25,6 +25,10 @@ export class SiteInfoController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.monitor; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询站点监控分页列表" }) async page(@Body(ALL) body: any) { body.query = body.query ?? {}; @@ -76,8 +80,6 @@ export class SiteInfoController extends CrudController { this.service.check(entity.id, true, 0); } this.auditLog({ - type: AuditType.monitor, - action: AuditAction.add, content: `新增了站点监控「${bean.name}」(ID:${res.id}, 域名:${bean.domain})`, }); return this.ok(res); @@ -94,8 +96,6 @@ export class SiteInfoController extends CrudController { this.service.check(entity.id, true, 0); } this.auditLog({ - type: AuditType.monitor, - action: AuditAction.update, content: `修改了站点监控「${bean.name}」(ID:${bean.id})`, }); return this.ok(); @@ -111,8 +111,6 @@ export class SiteInfoController extends CrudController { await this.checkOwner(this.service, id, "write"); const res = await super.delete(id); this.auditLog({ - type: AuditType.monitor, - action: AuditAction.delete, content: `删除了站点监控(ID:${id})`, }); return res; @@ -121,11 +119,9 @@ export class SiteInfoController extends CrudController { @Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除站点监控" }) async batchDelete(@Body(ALL) body: any) { const { projectId, userId } = await this.getProjectUserIdWrite(); - await this.service.batchDelete(body.ids, userId, projectId); + const count = await this.service.batchDelete(body.ids, userId, projectId); this.auditLog({ - type: AuditType.monitor, - action: AuditAction.batchDelete, - content: `批量删除了${body.ids.length}条站点监控`, + content: `批量删除了${count}条站点监控`, }); return this.ok(); } @@ -154,6 +150,7 @@ export class SiteInfoController extends CrudController { userId, projectId, }); + this.auditLog({ content: "导入了站点监控" }); return this.ok(); } @@ -191,6 +188,7 @@ export class SiteInfoController extends CrudController { projectId: projectId, key, }); + this.auditLog({ content: "删除了站点监控导入任务" }); return this.ok(); } @@ -203,6 +201,7 @@ export class SiteInfoController extends CrudController { userId: userId, projectId: projectId, }); + this.auditLog({ content: "开始了站点监控导入任务" }); return this.ok(); } diff --git a/packages/ui/certd-server/src/controller/user/monitor/site-ip-controller.ts b/packages/ui/certd-server/src/controller/user/monitor/site-ip-controller.ts index 0a39bae98..4f04a85e7 100644 --- a/packages/ui/certd-server/src/controller/user/monitor/site-ip-controller.ts +++ b/packages/ui/certd-server/src/controller/user/monitor/site-ip-controller.ts @@ -4,6 +4,7 @@ import { AuthService } from "../../../modules/sys/authority/service/auth-service import { SiteIpService } from "../../../modules/monitor/service/site-ip-service.js"; import { SiteInfoService } from "../../../modules/monitor/index.js"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -22,6 +23,10 @@ export class SiteInfoController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.siteIp; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询站点IP分页列表" }) async page(@Body(ALL) body: any) { const { projectId, userId } = await this.getProjectUserIdRead(); @@ -57,6 +62,7 @@ export class SiteInfoController extends CrudController { const { domain, httpsPort } = siteEntity; this.service.check(res.id, domain, httpsPort); } + this.auditLog({ content: `新增了站点IP(ID:${res.id})` }); return this.ok(res); } @@ -71,6 +77,7 @@ export class SiteInfoController extends CrudController { const { domain, httpsPort } = siteEntity; this.service.check(siteEntity.id, domain, httpsPort); } + this.auditLog({ content: `修改了站点IP(ID:${bean.id})` }); return this.ok(); } @Post("/info", { description: Constants.per.authOnly, summary: "查询站点IP详情" }) @@ -85,6 +92,7 @@ export class SiteInfoController extends CrudController { const entity = await this.service.info(id); const res = await super.delete(id); await this.service.updateIpCount(entity.siteId); + this.auditLog({ content: `删除了站点IP(ID:${id})` }); return res; } @@ -124,6 +132,7 @@ export class SiteInfoController extends CrudController { siteId: body.siteId, projectId, }); + this.auditLog({ content: "导入了站点IP" }); return this.ok(); } } diff --git a/packages/ui/certd-server/src/controller/user/open/open-key-controller.ts b/packages/ui/certd-server/src/controller/user/open/open-key-controller.ts index 11f8af51c..34df90d41 100644 --- a/packages/ui/certd-server/src/controller/user/open/open-key-controller.ts +++ b/packages/ui/certd-server/src/controller/user/open/open-key-controller.ts @@ -3,7 +3,7 @@ import { Constants, CrudController } from "@certd/lib-server"; import { AuthService } from "../../../modules/sys/authority/service/auth-service.js"; import { OpenKeyService } from "../../../modules/open/service/open-key-service.js"; import { ApiTags } from "@midwayjs/swagger"; -import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** */ @@ -19,6 +19,10 @@ export class OpenKeyController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.openKey; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询开放API密钥分页列表" }) async page(@Body(ALL) body: any) { const { projectId, userId } = await this.getProjectUserIdRead(); @@ -58,8 +62,6 @@ export class OpenKeyController extends CrudController { body.userId = userId; const res = await this.service.add(body); this.auditLog({ - type: AuditType.openKey, - action: AuditAction.add, content: `新增了API密钥(ID:${res.id}, scope:${body.scope})`, }); return this.ok(res); @@ -72,8 +74,6 @@ export class OpenKeyController extends CrudController { delete bean.projectId; await this.service.update(bean); this.auditLog({ - type: AuditType.openKey, - action: AuditAction.update, content: `修改了API密钥(ID:${bean.id})`, }); return this.ok(); @@ -102,8 +102,6 @@ export class OpenKeyController extends CrudController { await this.checkOwner(this.getService(), id, "write"); const res = await super.delete(id); this.auditLog({ - type: AuditType.openKey, - action: AuditAction.delete, content: `删除了API密钥(ID:${id})`, }); return res; diff --git a/packages/ui/certd-server/src/controller/user/pipeline/access-controller.ts b/packages/ui/certd-server/src/controller/user/pipeline/access-controller.ts index 5872494e4..f11496f94 100644 --- a/packages/ui/certd-server/src/controller/user/pipeline/access-controller.ts +++ b/packages/ui/certd-server/src/controller/user/pipeline/access-controller.ts @@ -4,7 +4,7 @@ import { AccessService } from "@certd/lib-server"; import { AuthService } from "../../../modules/sys/authority/service/auth-service.js"; import { AccessDefine } from "@certd/pipeline"; import { ApiTags } from "@midwayjs/swagger"; -import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 授权 @@ -21,6 +21,10 @@ export class AccessController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.access; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询授权配置分页列表" }) async page(@Body(ALL) body) { const { projectId, userId } = await this.getProjectUserIdRead(); @@ -60,8 +64,6 @@ export class AccessController extends CrudController { bean.projectId = projectId; const res = await super.add(bean); this.auditLog({ - type: AuditType.access, - action: AuditAction.add, content: `新增了授权「${bean.name}」(ID:${res.data}, 类型:${bean.type})`, }); return res; @@ -74,8 +76,6 @@ export class AccessController extends CrudController { delete bean.projectId; const res = await super.update(bean); this.auditLog({ - type: AuditType.access, - action: AuditAction.update, content: `修改了授权「${bean.name}」(ID:${bean.id})`, }); return res; @@ -91,8 +91,6 @@ export class AccessController extends CrudController { await this.checkOwner(this.getService(), id, "write"); const res = await super.delete(id); this.auditLog({ - type: AuditType.access, - action: AuditAction.delete, content: `删除了授权(ID:${id})`, }); return res; diff --git a/packages/ui/certd-server/src/controller/user/pipeline/notification-controller.ts b/packages/ui/certd-server/src/controller/user/pipeline/notification-controller.ts index bbfecb631..58909e234 100644 --- a/packages/ui/certd-server/src/controller/user/pipeline/notification-controller.ts +++ b/packages/ui/certd-server/src/controller/user/pipeline/notification-controller.ts @@ -5,7 +5,7 @@ import { AuthService } from "../../../modules/sys/authority/service/auth-service import { NotificationDefine } from "@certd/pipeline"; import { checkPlus } from "@certd/plus-core"; import { ApiTags } from "@midwayjs/swagger"; -import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 通知 @@ -22,6 +22,10 @@ export class NotificationController extends CrudController return this.service; } + getAuditType(): string { + return AuditType.notification; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询通知配置分页列表" }) async page(@Body(ALL) body) { const { projectId, userId } = await this.getProjectUserIdRead(); @@ -64,8 +68,6 @@ export class NotificationController extends CrudController } const res = await super.add(bean); this.auditLog({ - type: AuditType.notification, - action: AuditAction.add, content: `新增了通知配置「${bean.name}」(ID:${res.data}, 类型:${bean.type})`, }); return res; @@ -92,8 +94,6 @@ export class NotificationController extends CrudController delete bean.projectId; const res = await super.update(bean); this.auditLog({ - type: AuditType.notification, - action: AuditAction.update, content: `修改了通知配置「${bean.name}」(ID:${bean.id})`, }); return res; @@ -109,8 +109,6 @@ export class NotificationController extends CrudController await this.checkOwner(this.getService(), id, "write"); const res = await super.delete(id); this.auditLog({ - type: AuditType.notification, - action: AuditAction.delete, content: `删除了通知配置(ID:${id})`, }); return res; @@ -172,6 +170,7 @@ export class NotificationController extends CrudController const { projectId, userId } = await this.getProjectUserIdRead(); await this.checkOwner(this.getService(), id, "write"); const res = await this.service.setDefault(id, userId, projectId); + this.auditLog({ content: `设置了默认通知配置(ID:${id})` }); return this.ok(res); } diff --git a/packages/ui/certd-server/src/controller/user/pipeline/pipeline-controller.ts b/packages/ui/certd-server/src/controller/user/pipeline/pipeline-controller.ts index 99e3ed9ae..fd060e65f 100644 --- a/packages/ui/certd-server/src/controller/user/pipeline/pipeline-controller.ts +++ b/packages/ui/certd-server/src/controller/user/pipeline/pipeline-controller.ts @@ -7,7 +7,7 @@ import { HistoryService } from "../../../modules/pipeline/service/history-servic import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js"; import { AuthService } from "../../../modules/sys/authority/service/auth-service.js"; import { PipelineEntity } from "../../../modules/pipeline/entity/pipeline.js"; -import { AuditType, AuditAction } from "../../../modules/sys/enterprise/service/audit-constants.js"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; const pipelineExample = ` // 流水线配置示例,实际传送时要去掉注释 @@ -124,11 +124,14 @@ export class PipelineController extends CrudController { @Inject() siteInfoService: SiteInfoService; - getService() { return this.service; } + getAuditType(): string { + return AuditType.pipeline; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询流水线分页列表" }) async page(@Body(ALL) body) { const isAdmin = await this.authService.isAdmin(this.ctx); @@ -216,8 +219,6 @@ export class PipelineController extends CrudController { const title = bean.title; this.auditLog({ - type: AuditType.pipeline, - action: isNew ? AuditAction.add : AuditAction.update, content: isNew ? `创建了流水线「${title}」(ID:${bean.id})` : `修改了流水线「${title}」(ID:${bean.id})`, projectId, }); @@ -240,8 +241,6 @@ export class PipelineController extends CrudController { await this.checkOwner(this.getService(), id, "write", true); await this.service.delete(id); this.auditLog({ - type: AuditType.pipeline, - action: AuditAction.delete, content: `删除了流水线(ID:${id})`, }); return this.ok({}); @@ -253,6 +252,7 @@ export class PipelineController extends CrudController { delete bean.userId; delete bean.projectId; await this.service.disabled(bean.id, bean.disabled); + this.auditLog({ content: `${bean.disabled ? "禁用" : "启用"}了流水线(ID:${bean.id})` }); return this.ok({}); } @@ -268,8 +268,6 @@ export class PipelineController extends CrudController { await this.checkOwner(this.getService(), id, "write", true); await this.service.trigger(id, stepId, true); this.auditLog({ - type: AuditType.pipeline, - action: AuditAction.execute, content: `手动执行了流水线(ID:${id})`, }); return this.ok({}); @@ -280,8 +278,6 @@ export class PipelineController extends CrudController { await this.checkOwner(this.historyService, historyId, "write", true); await this.service.cancel(historyId); this.auditLog({ - type: AuditType.pipeline, - action: AuditAction.cancel, content: `取消了流水线执行(historyId:${historyId})`, }); return this.ok({}); @@ -307,91 +303,77 @@ export class PipelineController extends CrudController { @Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除流水线" }) async batchDelete(@Body("ids") ids: number[]) { - await this.checkPermissionCall(async ({ userId, projectId }) => { - await this.service.batchDelete(ids, userId, projectId); + const count = await this.checkPermissionCall(async ({ userId, projectId }) => { + return await this.service.batchDelete(ids, userId, projectId); }); this.auditLog({ - type: AuditType.pipeline, - action: AuditAction.batchDelete, - content: `批量删除了${ids.length}条流水线`, + content: `批量删除了${count}条流水线`, }); return this.ok({}); } @Post("/batchUpdateGroup", { description: Constants.per.authOnly, summary: "批量更新流水线分组" }) async batchUpdateGroup(@Body("ids") ids: number[], @Body("groupId") groupId: number) { - await this.checkPermissionCall(async ({ userId, projectId }) => { - await this.service.batchUpdateGroup(ids, groupId, userId, projectId); + const count = await this.checkPermissionCall(async ({ userId, projectId }) => { + return await this.service.batchUpdateGroup(ids, groupId, userId, projectId); }); this.auditLog({ - type: AuditType.pipeline, - action: AuditAction.batchUpdate, - content: `批量修改了${ids.length}条流水线分组`, + content: `批量修改了${count}条流水线分组`, }); return this.ok({}); } @Post("/batchUpdateTrigger", { description: Constants.per.authOnly, summary: "批量更新流水线触发器" }) async batchUpdateTrigger(@Body("ids") ids: number[], @Body("trigger") trigger: any) { - await this.checkPermissionCall(async ({ userId, projectId }) => { - await this.service.batchUpdateTrigger(ids, trigger, userId, projectId); + const count = await this.checkPermissionCall(async ({ userId, projectId }) => { + return await this.service.batchUpdateTrigger(ids, trigger, userId, projectId); }); this.auditLog({ - type: AuditType.pipeline, - action: AuditAction.batchUpdate, - content: `批量修改了${ids.length}条流水线触发器`, + content: `批量修改了${count}条流水线触发器`, }); return this.ok({}); } @Post("/batchUpdateNotification", { description: Constants.per.authOnly, summary: "批量更新流水线通知" }) async batchUpdateNotification(@Body("ids") ids: number[], @Body("notification") notification: any) { - await this.checkPermissionCall(async ({ userId, projectId }) => { - await this.service.batchUpdateNotifications(ids, notification, userId, projectId); + const count = await this.checkPermissionCall(async ({ userId, projectId }) => { + return await this.service.batchUpdateNotifications(ids, notification, userId, projectId); }); this.auditLog({ - type: AuditType.pipeline, - action: AuditAction.batchUpdate, - content: `批量修改了${ids.length}条流水线通知`, + content: `批量修改了${count}条流水线通知`, }); return this.ok({}); } @Post("/batchUpdateCertApplyOptions", { description: Constants.per.authOnly, summary: "批量更新证书申请任务配置" }) async batchUpdateCertApplyOptions(@Body("ids") ids: number[], @Body("options") options: any) { - await this.checkPermissionCall(async ({ userId, projectId }) => { - await this.service.batchUpdateCertApplyOptions(ids, options, userId, projectId); + const count = await this.checkPermissionCall(async ({ userId, projectId }) => { + return await this.service.batchUpdateCertApplyOptions(ids, options, userId, projectId); }); this.auditLog({ - type: AuditType.pipeline, - action: AuditAction.batchUpdate, - content: `批量修改了${ids.length}条流水线证书申请配置`, + content: `批量修改了${count}条流水线证书申请配置`, }); return this.ok({}); } @Post("/batchRerun", { description: Constants.per.authOnly, summary: "批量重新运行流水线" }) async batchRerun(@Body("ids") ids: number[], @Body("force") force: boolean) { - await this.checkPermissionCall(async ({ userId, projectId }) => { - await this.service.batchRerun(ids, force, userId, projectId); + const count = await this.checkPermissionCall(async ({ userId, projectId }) => { + return await this.service.batchRerun(ids, force, userId, projectId); }); this.auditLog({ - type: AuditType.pipeline, - action: AuditAction.execute, - content: `批量重新执行了${ids.length}条流水线`, + content: `批量重新执行了${count}条流水线`, }); return this.ok({}); } @Post("/batchTransfer", { description: Constants.per.authOnly, summary: "批量迁移流水线" }) async batchTransfer(@Body("ids") ids: number[], @Body("toProjectId") toProjectId: number) { - await this.checkPermissionCall(async ({}) => { - await this.service.batchTransfer(ids, toProjectId); + const count = await this.checkPermissionCall(async ({}) => { + return await this.service.batchTransfer(ids, toProjectId); }); this.auditLog({ - type: AuditType.pipeline, - action: AuditAction.batchUpdate, - content: `批量迁移了${ids.length}条流水线`, + content: `批量迁移了${count}条流水线`, }); return this.ok({}); } @@ -401,8 +383,6 @@ export class PipelineController extends CrudController { await this.checkOwner(this.getService(), id, "write", true); const res = await this.service.refreshWebhookKey(id); this.auditLog({ - type: AuditType.pipeline, - action: AuditAction.update, content: `刷新了流水线(ID:${id})的Webhook密钥`, }); return this.ok({ diff --git a/packages/ui/certd-server/src/controller/user/pipeline/pipeline-group-controller.ts b/packages/ui/certd-server/src/controller/user/pipeline/pipeline-group-controller.ts index 624e672a3..d93e77c10 100644 --- a/packages/ui/certd-server/src/controller/user/pipeline/pipeline-group-controller.ts +++ b/packages/ui/certd-server/src/controller/user/pipeline/pipeline-group-controller.ts @@ -3,6 +3,7 @@ import { Constants, CrudController } from "@certd/lib-server"; import { AuthService } from "../../../modules/sys/authority/service/auth-service.js"; import { PipelineGroupService } from "../../../modules/pipeline/service/pipeline-group-service.js"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 通知 @@ -20,6 +21,10 @@ export class PipelineGroupController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.subDomain; + } + @Post("/parseDomain", { description: Constants.per.authOnly, summary: "解析域名" }) async parseDomain(@Body("fullDomain") fullDomain: string) { const { projectId, userId } = await this.getProjectUserIdRead(); @@ -64,7 +69,9 @@ export class SubDomainController extends CrudController { const { userId, projectId } = await this.getProjectUserIdRead(); bean.userId = userId; bean.projectId = projectId; - return super.add(bean); + const res = await super.add(bean); + this.auditLog({ content: `新增了子域名(ID:${res.data})` }); + return res; } @Post("/update", { description: Constants.per.authOnly, summary: "更新子域名" }) @@ -72,7 +79,9 @@ export class SubDomainController extends CrudController { await this.checkOwner(this.getService(), bean.id, "write"); delete bean.userId; delete bean.projectId; - return super.update(bean); + const res = await super.update(bean); + this.auditLog({ content: `修改了子域名(ID:${bean.id})` }); + return res; } @Post("/info", { description: Constants.per.authOnly, summary: "查询子域名详情" }) async info(@Query("id") id: number) { @@ -83,7 +92,9 @@ export class SubDomainController extends CrudController { @Post("/delete", { description: Constants.per.authOnly, summary: "删除子域名" }) async delete(@Query("id") id: number) { await this.checkOwner(this.getService(), id, "write"); - return super.delete(id); + const res = await super.delete(id); + this.auditLog({ content: `删除了子域名(ID:${id})` }); + return res; } @Post("/batchDelete", { description: Constants.per.authOnly, summary: "批量删除子域名" }) diff --git a/packages/ui/certd-server/src/controller/user/pipeline/template-controller.ts b/packages/ui/certd-server/src/controller/user/pipeline/template-controller.ts index f45a79f87..596ef3e2a 100644 --- a/packages/ui/certd-server/src/controller/user/pipeline/template-controller.ts +++ b/packages/ui/certd-server/src/controller/user/pipeline/template-controller.ts @@ -3,6 +3,7 @@ import { Constants, CrudController } from "@certd/lib-server"; import { TemplateService } from "../../../modules/pipeline/service/template-service.js"; import { checkPlus } from "@certd/plus-core"; import { ApiTags } from "@midwayjs/swagger"; +import { AuditType } from "../../../modules/sys/enterprise/service/audit-constants.js"; /** * 流水线模版 @@ -18,6 +19,10 @@ export class TemplateController extends CrudController { return this.service; } + getAuditType(): string { + return AuditType.template; + } + @Post("/page", { description: Constants.per.authOnly, summary: "查询流水线模版分页列表" }) async page(@Body(ALL) body) { body.query = body.query ?? {}; @@ -52,7 +57,9 @@ export class TemplateController extends CrudController { bean.userId = userId; bean.projectId = projectId; checkPlus(); - return super.add(bean); + const res = await super.add(bean); + this.auditLog({ content: `新增了流水线模版「${bean.name}」(ID:${res.data})` }); + return res; } @Post("/update", { description: Constants.per.authOnly, summary: "更新流水线模版" }) @@ -60,7 +67,9 @@ export class TemplateController extends CrudController { await this.checkOwner(this.service, bean.id, "write"); delete bean.userId; delete bean.projectId; - return super.update(bean); + const res = await super.update(bean); + this.auditLog({ content: `修改了流水线模版「${bean.name}」(ID:${bean.id})` }); + return res; } @Post("/info", { description: Constants.per.authOnly, summary: "查询流水线模版详情" }) async info(@Query("id") id: number) { @@ -72,6 +81,7 @@ export class TemplateController extends CrudController { async delete(@Query("id") id: number) { const { userId, projectId } = await this.getProjectUserIdWrite(); await this.service.batchDelete([id], userId, projectId); + this.auditLog({ content: `删除了流水线模版(ID:${id})` }); return this.ok({}); } @@ -79,6 +89,7 @@ export class TemplateController extends CrudController { async batchDelete(@Body("ids") ids: number[]) { const { userId, projectId } = await this.getProjectUserIdWrite(); await this.service.batchDelete(ids, userId, projectId); + this.auditLog({ content: `批量删除了${ids.length}条流水线模版` }); return this.ok({}); } @@ -95,6 +106,7 @@ export class TemplateController extends CrudController { body.projectId = projectId; checkPlus(); const res = await this.service.createPipelineByTemplate(body); + this.auditLog({ content: `根据模版创建了流水线(ID:${res.id})` }); return this.ok(res); } } diff --git a/packages/ui/certd-server/src/middleware/audit-log.test.ts b/packages/ui/certd-server/src/middleware/audit-log.test.ts new file mode 100644 index 000000000..d70a700e6 --- /dev/null +++ b/packages/ui/certd-server/src/middleware/audit-log.test.ts @@ -0,0 +1,116 @@ +/// + +import assert from "node:assert/strict"; +import { Constants } from "@certd/lib-server"; +import { AuditLogMiddleware } from "./audit-log.js"; + +class TestController { + import() {} + + noAudit() {} + + getAuditType(): string { + return "pipeline"; + } +} + +function createMiddleware() { + const middleware = new AuditLogMiddleware(); + const records: any[] = []; + middleware.auditService = { + async log(record: any) { + records.push(record); + }, + } as any; + (middleware as any).isPlusFn = async () => true; + return { middleware, records }; +} + +function createCtx(method = "import") { + return { + path: "/api/pi/cname/record/import", + status: 200, + body: Constants.res.success, + ip: "127.0.0.1", + user: { id: 1, username: "admin" }, + projectId: 3, + request: { + query: { id: "5" }, + body: { name: "test" }, + }, + requestContext: { + async getAsync() { + return new TestController(); + }, + }, + auditRouteInfo: { + controllerClz: TestController, + method, + summary: "导入CNAME记录", + }, + auditLog: { + enabled: true, + append: ["提交2条"], + }, + } as any; +} + +describe("AuditLogMiddleware", () => { + it("writes audit log after successful response", async () => { + const { middleware, records } = createMiddleware(); + + await middleware.resolve()(createCtx(), async () => {}); + + assert.equal(records.length, 1); + assert.equal(records[0].userId, 1); + assert.equal(records[0].type, "pipeline"); + assert.equal(records[0].action, "导入CNAME记录"); + assert.equal(records[0].content, "提交2条"); + assert.equal(records[0].username, "admin"); + assert.equal(records[0].projectId, 3); + assert.equal(records[0].ipAddress, "127.0.0.1"); + assert.equal(records[0].scope, "user"); + }); + + it("uses bean type and action overrides", async () => { + const { middleware, records } = createMiddleware(); + const ctx = createCtx(); + ctx.auditLog = { enabled: true, type: "settings", action: "修改设置", append: ["修改了安全设置"] }; + + await middleware.resolve()(ctx, async () => {}); + + assert.equal(records[0].type, "settings"); + assert.equal(records[0].action, "修改设置"); + assert.equal(records[0].content, "修改了安全设置"); + }); + + it("skips when auditLog not enabled", async () => { + const { middleware, records } = createMiddleware(); + const ctx = createCtx("noAudit"); + ctx.auditLog = {}; + + await middleware.resolve()(ctx, async () => {}); + + assert.equal(records.length, 0); + }); + + it("skips failed response", async () => { + const { middleware, records } = createMiddleware(); + const ctx = createCtx(); + ctx.body = Constants.res.error; + + await middleware.resolve()(ctx, async () => {}); + + assert.equal(records.length, 0); + }); + + it("skips anonymous request", async () => { + const { middleware, records } = createMiddleware(); + const ctx = createCtx(); + ctx.user = undefined; + + await middleware.resolve()(ctx, async () => {}); + + assert.equal(records.length, 0); + }); +}); diff --git a/packages/ui/certd-server/src/middleware/audit-log.ts b/packages/ui/certd-server/src/middleware/audit-log.ts new file mode 100644 index 000000000..5b436234f --- /dev/null +++ b/packages/ui/certd-server/src/middleware/audit-log.ts @@ -0,0 +1,100 @@ +import { Inject, Provide } from "@midwayjs/core"; +import { IMidwayKoaContext, IWebMiddleware, NextFunction } from "@midwayjs/koa"; +import { Constants } from "@certd/lib-server"; +import { AuditService } from "../modules/sys/enterprise/service/audit-service.js"; + +@Provide() +export class AuditLogMiddleware implements IWebMiddleware { + @Inject() + auditService: AuditService; + + private isPlusFn: (() => Promise) | null = null; + + private async getIsPlus(): Promise { + if (!this.isPlusFn) { + try { + const mod = await import("@certd/plus-core"); + this.isPlusFn = async () => mod.isPlus(); + } catch { + this.isPlusFn = async () => false; + } + } + return this.isPlusFn(); + } + + resolve() { + return async (ctx: IMidwayKoaContext, next: NextFunction) => { + await next(); + await this.writeAuditLog(ctx); + }; + } + + private async writeAuditLog(ctx: IMidwayKoaContext) { + const routeInfo = ctx.auditRouteInfo; + if (!routeInfo) { + return; + } + if (!ctx.auditLog?.enabled) { + return; + } + const isPlus = await this.getIsPlus(); + if (!isPlus) { + return; + } + if (!this.isSuccessResponse(ctx)) { + return; + } + + const auditLog = ctx.auditLog; + if (!auditLog.enabled) { + return; + } + const type = auditLog.type || (await this.resolveControllerType(routeInfo.controllerClz, ctx as any)); + const action = auditLog.action || routeInfo.summary || ""; + const append = auditLog.append; + const appendList = Array.isArray(append) ? append : append ? [append] : []; + const content = auditLog.content || appendList.filter(item => item && String(item).trim()).join(" "); + + if (!content) { + return; + } + + const projectId = auditLog.projectId ?? ctx.projectId ?? 0; + const scope = auditLog.scope || (ctx.path.startsWith("/api/sys/") ? "system" : "user"); + const ipAddress = ctx.ip || ""; + + await this.auditService.log({ + userId: auditLog.userId ?? ctx.user?.id ?? 0, + type: type || "unknown", + action, + content, + username: auditLog.username || ctx.user?.username, + projectId, + ipAddress, + scope, + }); + } + + private async resolveControllerType(controllerClz: any, ctx: any): Promise { + if (!controllerClz || !ctx.requestContext) { + return undefined; + } + try { + const controller = await ctx.requestContext.getAsync(controllerClz); + return controller?.getAuditType?.(); + } catch { + return undefined; + } + } + + private isSuccessResponse(ctx: IMidwayKoaContext) { + if (ctx.status >= 400) { + return false; + } + const body = ctx.body as any; + if (body?.code == null) { + return true; + } + return body.code === Constants.res.success.code; + } +} diff --git a/packages/ui/certd-server/src/middleware/authority.test.ts b/packages/ui/certd-server/src/middleware/authority.test.ts index 67a7a4f67..e3ff3eb1a 100644 --- a/packages/ui/certd-server/src/middleware/authority.test.ts +++ b/packages/ui/certd-server/src/middleware/authority.test.ts @@ -11,7 +11,7 @@ function createMiddleware(permission: string) { middleware.secret = "test-secret"; middleware.webRouterService = { async getMatchedRouterInfo() { - return { description: permission }; + return { description: permission, summary: "测试路由" }; }, } as any; return middleware; @@ -41,6 +41,7 @@ describe("AuthorityMiddleware guestOptionalAuth", () => { assert.equal(called, true); assert.equal(ctx.user, undefined); + assert.equal(ctx.auditRouteInfo.summary, "测试路由"); }); it("sets user when token is provided", async () => { diff --git a/packages/ui/certd-server/src/middleware/authority.ts b/packages/ui/certd-server/src/middleware/authority.ts index 5b14888f5..77eb42ff9 100644 --- a/packages/ui/certd-server/src/middleware/authority.ts +++ b/packages/ui/certd-server/src/middleware/authority.ts @@ -40,6 +40,8 @@ export class AuthorityMiddleware implements IWebMiddleware { await next(); return; } + ctx.auditRouteInfo = routeInfo; + this.extractProjectId(ctx); let permission = routeInfo.description || ""; permission = permission.trim().split(" ")[0]; if (permission == null || permission === "") { @@ -109,6 +111,16 @@ export class AuthorityMiddleware implements IWebMiddleware { return; } + private extractProjectId(ctx: IMidwayKoaContext) { + const headerVal = ctx.headers["project-id"] as string; + const queryVal = (ctx.request as any)?.query?.projectId; + const bodyVal = (ctx.request as any)?.body?.projectId; + const raw = headerVal || queryVal || bodyVal; + if (raw != null && raw !== "") { + ctx.projectId = parseInt(String(raw), 10) || 0; + } + } + private getTokenFromRequest(ctx: IMidwayKoaContext) { let token = ctx.get("Authorization") || ""; token = token.replace("Bearer ", "").trim(); diff --git a/packages/ui/certd-server/src/modules/auto/auto-cron.ts b/packages/ui/certd-server/src/modules/auto/auto-cron.ts index 1ff50b181..7dadd32b8 100644 --- a/packages/ui/certd-server/src/modules/auto/auto-cron.ts +++ b/packages/ui/certd-server/src/modules/auto/auto-cron.ts @@ -67,7 +67,7 @@ export class AutoCron { await this.registerDomainExpireCheckCron(); - await this.registerAuditCleanCron(); + // await this.registerAuditCleanCron(); } async registerSiteMonitorCron() { diff --git a/packages/ui/certd-server/src/modules/cname/service/cname-record-service.ts b/packages/ui/certd-server/src/modules/cname/service/cname-record-service.ts index 9e7eb1403..8dd471a37 100644 --- a/packages/ui/certd-server/src/modules/cname/service/cname-record-service.ts +++ b/packages/ui/certd-server/src/modules/cname/service/cname-record-service.ts @@ -503,6 +503,7 @@ export class CnameRecordService extends BaseService { }, }) ); + return { count: domains.length }; } async _import(req: { userId: number; projectId: number; domains: string[]; cnameProviderId: any }, task: BackTask) { diff --git a/packages/ui/certd-server/src/modules/login/service/login-service.ts b/packages/ui/certd-server/src/modules/login/service/login-service.ts index 542a29c50..8c5ac377a 100644 --- a/packages/ui/certd-server/src/modules/login/service/login-service.ts +++ b/packages/ui/certd-server/src/modules/login/service/login-service.ts @@ -64,7 +64,7 @@ export class LoginService { cache.delete(`login_block_duration:${username}`); } - addErrorTimes(username: string, errorMessage: string) { + addErrorTimes(username: string, errorMessage: string, userId?: number) { const errorTimesKey = `login_error_times:${username}`; const blockTimesKey = `login_block_times:${username}`; const blockDurationKey = `login_block_duration:${username}`; @@ -100,13 +100,13 @@ export class LoginService { }); // 清除error次数 cache.delete(errorTimesKey); - throw new LoginErrorException(`登录失败次数过多,请${leftMin}分钟后重试`, 0); + throw new LoginErrorException(`登录失败次数过多,请${leftMin}分钟后重试`, 0, userId); } const leftTimes = maxRetryTimes - errorTimes; if (leftTimes < 3) { - throw new LoginErrorException(`登录失败(${errorMessage}),剩余尝试次数:${leftTimes}`, leftTimes); + throw new LoginErrorException(`登录失败(${errorMessage}),剩余尝试次数:${leftTimes}`, leftTimes, userId); } - throw new LoginErrorException(errorMessage, leftTimes); + throw new LoginErrorException(errorMessage, leftTimes, userId); } async register(type: string, user: UserEntity, inviteCode?: string, withTx?: (tx: EntityManager) => Promise) { @@ -166,7 +166,7 @@ export class LoginService { } const right = await this.userService.checkPassword(password, info.password, info.passwordVersion); if (!right) { - this.addErrorTimes(username, "用户名或密码错误"); + this.addErrorTimes(username, "用户名或密码错误", info.id); } this.clearCacheOnSuccess(username); return this.onLoginSuccess(info); @@ -251,6 +251,7 @@ export class LoginService { return { token, expire, + userId: user.id, }; } diff --git a/packages/ui/certd-server/src/modules/monitor/service/site-info-service.ts b/packages/ui/certd-server/src/modules/monitor/service/site-info-service.ts index d94caec26..f2e714f09 100644 --- a/packages/ui/certd-server/src/modules/monitor/service/site-info-service.ts +++ b/packages/ui/certd-server/src/modules/monitor/service/site-info-service.ts @@ -805,11 +805,12 @@ export class SiteInfoService extends BaseService { }); } - async batchDelete(ids: number[], userId: number, projectId?: number): Promise { + async batchDelete(ids: number[], userId: number, projectId?: number): Promise { const userProjectQuery = this.buildUserProjectQuery(userId, projectId); - await this.repository.delete({ + const result = await this.repository.delete({ id: In(ids), ...userProjectQuery, }); + return result.affected || 0; } } diff --git a/packages/ui/certd-server/src/modules/pipeline/service/pipeline-service.ts b/packages/ui/certd-server/src/modules/pipeline/service/pipeline-service.ts index 9d69ba5bd..c3c6b1bf9 100644 --- a/packages/ui/certd-server/src/modules/pipeline/service/pipeline-service.ts +++ b/packages/ui/certd-server/src/modules/pipeline/service/pipeline-service.ts @@ -962,7 +962,7 @@ export class PipelineService extends BaseService { return result; } - async batchDelete(ids: number[], userId?: number, projectId?: number) { + async batchDelete(ids: number[], userId?: number, projectId?: number): Promise { if (!isPlus()) { throw new NeedVIPException("此功能需要升级Certd专业版"); } @@ -975,9 +975,10 @@ export class PipelineService extends BaseService { } await this.delete(id); } + return ids.length; } - async batchUpdateGroup(ids: number[], groupId: number, userId: any, projectId?: number) { + async batchUpdateGroup(ids: number[], groupId: number, userId: any, projectId?: number): Promise { if (!isPlus()) { throw new NeedVIPException("此功能需要升级Certd专业版"); } @@ -988,19 +989,20 @@ export class PipelineService extends BaseService { if (projectId) { query.projectId = projectId; } - await this.repository.update( + const result = await this.repository.update( { id: In(ids), ...query, }, { groupId } ); + return result.affected || 0; } /** * 批量转移到其他项目 */ - async batchTransfer(ids: number[], projectId: number) { + async batchTransfer(ids: number[], projectId: number): Promise { if (!isPlus()) { throw new NeedVIPException("此功能需要升级Certd专业版"); } @@ -1082,9 +1084,10 @@ export class PipelineService extends BaseService { await this.repository.save(entity); await this.save(entity); } + return ids.length; } - async batchUpdateTrigger(ids: number[], trigger: any, userId: any, projectId?: number) { + async batchUpdateTrigger(ids: number[], trigger: any, userId: any, projectId?: number): Promise { if (!isPlus()) { throw new NeedVIPException("此功能需要升级Certd专业版"); } @@ -1137,9 +1140,10 @@ export class PipelineService extends BaseService { } await this.doUpdatePipelineJson(item, pipeline); } + return list.length; } - async batchUpdateNotifications(ids: number[], notification: Notification, userId: any, projectId?: number) { + async batchUpdateNotifications(ids: number[], notification: Notification, userId: any, projectId?: number): Promise { if (!isPlus()) { throw new NeedVIPException("此功能需要升级Certd专业版"); } @@ -1178,9 +1182,10 @@ export class PipelineService extends BaseService { ]; await this.doUpdatePipelineJson(item, pipeline); } + return list.length; } - async batchUpdateCertApplyOptions(ids: number[], options: CertApplyStepInputPatch, userId: any, projectId?: number) { + async batchUpdateCertApplyOptions(ids: number[], options: CertApplyStepInputPatch, userId: any, projectId?: number): Promise { if (!isPlus()) { throw new NeedVIPException("此功能需要升级Certd专业版"); } @@ -1209,9 +1214,10 @@ export class PipelineService extends BaseService { } await this.doUpdatePipelineJson(item, pipeline); } + return list.length; } - async batchRerun(ids: number[], force: boolean, userId: any, projectId?: number) { + async batchRerun(ids: number[], force: boolean, userId: any, projectId?: number): Promise { if (!isPlus()) { throw new NeedVIPException("此功能需要升级Certd专业版"); } @@ -1237,6 +1243,7 @@ export class PipelineService extends BaseService { //异步执行 this.startBatchRerun(userId, ids, force); + return ids.length; } startBatchRerun(userId: number, ids: number[], force: boolean) { diff --git a/packages/ui/certd-server/src/modules/pipeline/service/template-service.ts b/packages/ui/certd-server/src/modules/pipeline/service/template-service.ts index b4db0ce0b..ade3e691a 100644 --- a/packages/ui/certd-server/src/modules/pipeline/service/template-service.ts +++ b/packages/ui/certd-server/src/modules/pipeline/service/template-service.ts @@ -87,7 +87,7 @@ export class TemplateService extends BaseService { }; } - async batchDelete(ids: number[], userId: number, projectId?: number) { + async batchDelete(ids: number[], userId: number, projectId?: number): Promise { const where: any = { id: In(ids), }; @@ -102,6 +102,7 @@ export class TemplateService extends BaseService { const pipelineIds = list.map(item => item.pipelineId); await this.delete(ids); await this.pipelineService.batchDelete(pipelineIds, userId, projectId); + return ids.length; } async createPipelineByTemplate(body: PipelineEntity) { diff --git a/packages/ui/certd-server/src/modules/sys/authority/service/user-service.ts b/packages/ui/certd-server/src/modules/sys/authority/service/user-service.ts index ac931a48f..1c2f3f6b9 100644 --- a/packages/ui/certd-server/src/modules/sys/authority/service/user-service.ts +++ b/packages/ui/certd-server/src/modules/sys/authority/service/user-service.ts @@ -272,7 +272,7 @@ export class UserService extends BaseService { // return; } await this.resetPassword(user.id, data.password); - return user.username; + return user; } async getByUsername(username: any) { diff --git a/packages/ui/certd-server/src/modules/sys/enterprise/entity/audit-log.ts b/packages/ui/certd-server/src/modules/sys/enterprise/entity/audit-log.ts index d4481b5be..77d702fac 100644 --- a/packages/ui/certd-server/src/modules/sys/enterprise/entity/audit-log.ts +++ b/packages/ui/certd-server/src/modules/sys/enterprise/entity/audit-log.ts @@ -10,8 +10,11 @@ export class AuditLogEntity { @Column({ name: "user_id", comment: "UserId" }) userId: number; + @Column({ name: "scope", comment: "system/user" }) + scope: string; + @Column({ name: "username", comment: "用户名" }) - userName: string; + username: string; @Column({ name: "project_id", comment: "ProjectId" }) projectId: number; diff --git a/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-constants.ts b/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-constants.ts index d156ad6bf..eff08d5dd 100644 --- a/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-constants.ts +++ b/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-constants.ts @@ -4,11 +4,27 @@ export const AuditType = { monitor: "monitor", notification: "notification", openKey: "openKey", + cname: "cname", user: "user", role: "role", permission: "permission", project: "project", settings: "settings", + domain: "domain", + dnsPersist: "dnsPersist", + certTemplate: "certTemplate", + pipelineGroup: "pipelineGroup", + subDomain: "subDomain", + template: "template", + mine: "mine", + login: "login", + addon: "addon", + enterprise: "enterprise", + plugin: "plugin", + siteIp: "siteIp", + jobHistory: "jobHistory", + account: "account", + plus: "plus", } as const; export const AuditTypeMap = { @@ -17,11 +33,27 @@ export const AuditTypeMap = { monitor: "站点监控", notification: "通知设置", openKey: "API密钥", + cname: "CNAME记录", user: "用户管理", role: "角色管理", permission: "权限管理", project: "项目管理", settings: "系统设置", + domain: "域名管理", + dnsPersist: "持久验证记录", + certTemplate: "证书参数模版", + pipelineGroup: "流水线分组", + subDomain: "子域名托管", + template: "流水线模版", + mine: "个人设置", + login: "登录日志", + addon: "扩展插件", + enterprise: "企业管理", + plugin: "插件管理", + siteIp: "站点IP", + jobHistory: "监控历史", + account: "账号管理", + plus: "Plus许可", } as const; export const AuditAction = { @@ -33,6 +65,16 @@ export const AuditAction = { batchDelete: "batchDelete", batchUpdate: "batchUpdate", disable: "disable", + import: "import", + bind: "bind", + unbind: "unbind", + register: "register", + login: "login", + resetStatus: "resetStatus", + setDefault: "setDefault", + save: "save", + trigger: "trigger", + active: "active", } as const; export const AuditActionMap = { @@ -44,6 +86,16 @@ export const AuditActionMap = { batchDelete: "批量删除", batchUpdate: "批量修改", disable: "禁用", + import: "导入", + bind: "绑定", + unbind: "解绑", + register: "注册", + login: "登录", + resetStatus: "重置状态", + setDefault: "设置默认", + save: "保存", + trigger: "触发", + active: "激活", } as const; export const AuditTypeColorMap: Record = { @@ -52,11 +104,27 @@ export const AuditTypeColorMap: Record = { monitor: "green", notification: "purple", openKey: "red", + cname: "cyan", user: "cyan", role: "geekblue", permission: "lime", project: "gold", settings: "magenta", + domain: "blue", + dnsPersist: "purple", + certTemplate: "orange", + pipelineGroup: "cyan", + subDomain: "geekblue", + template: "blue", + mine: "default", + login: "red", + addon: "orange", + enterprise: "gold", + plugin: "magenta", + siteIp: "green", + jobHistory: "default", + account: "geekblue", + plus: "volcano", }; export const AuditActionColorMap: Record = { @@ -68,6 +136,16 @@ export const AuditActionColorMap: Record = { batchDelete: "volcano", batchUpdate: "purple", disable: "default", + import: "cyan", + bind: "green", + unbind: "red", + register: "green", + login: "blue", + resetStatus: "orange", + setDefault: "cyan", + save: "purple", + trigger: "orange", + active: "green", }; export function buildAuditTypeDict() { diff --git a/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-service.ts b/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-service.ts index c1882582f..2f9cf9241 100644 --- a/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-service.ts +++ b/packages/ui/certd-server/src/modules/sys/enterprise/service/audit-service.ts @@ -1,108 +1,66 @@ +import { BaseService } from "@certd/lib-server"; import { Inject, Provide, Scope, ScopeEnum } from "@midwayjs/core"; -import { TypeORMDataSourceManager } from "@midwayjs/typeorm"; +import { InjectEntityModel } from "@midwayjs/typeorm"; import { LessThan, Repository } from "typeorm"; import { AuditLogEntity } from "../entity/audit-log.js"; import { logger } from "@certd/basic"; import { Cron } from "../../../cron/cron.js"; -export type AuditPageReq = { - page?: { offset: number; limit: number }; - query?: { - userId?: number; - type?: string; - action?: string; - createTime_start?: string; - createTime_end?: string; - }; - sort?: { prop: string; asc: boolean }; -}; - @Provide() @Scope(ScopeEnum.Request, { allowDowngrade: true }) -export class AuditService { - @Inject() - dataSourceManager: TypeORMDataSourceManager; +export class AuditService extends BaseService { + @InjectEntityModel(AuditLogEntity) + repository: Repository; @Inject() cron: Cron; - getRepository(): Repository { - return this.dataSourceManager.getDataSource("default").getRepository(AuditLogEntity); + getRepository() { + return this.repository; } - async log(params: { userId: number; type: string; action: string; content: string; username?: string; projectId?: number; projectName?: string; ipAddress?: string }): Promise { + async page(pageReq: any) { + if (pageReq.query?.createTime) { + const start = pageReq.query.createTime[0]; + const end = pageReq.query.createTime[1]; + delete pageReq.query.createTime; + pageReq.buildQuery = (qb: any) => { + qb.andWhere("main.createTime BETWEEN :start AND :end", { start, end }); + }; + } + return await super.page(pageReq); + } + + async log(params: { userId: number; type: string; action: string; content: string; username?: string; projectId?: number; ipAddress?: string; scope?: string }): Promise { try { let { username } = params; if (!username && params.userId != null) { - const userRepo = this.dataSourceManager.getDataSource("default").getRepository("sys_user" as any); + const userRepo = this.repository.manager.connection.getRepository("sys_user" as any); const user = await userRepo.findOne({ where: { id: params.userId } }); username = user?.username || ""; } - const repo = this.getRepository(); const entity = new AuditLogEntity(); entity.userId = params.userId; - entity.userName = username || ""; + entity.username = username || ""; entity.type = params.type; entity.action = params.action; entity.content = params.content; entity.projectId = params.projectId || 0; - entity.projectName = params.projectName || ""; + entity.projectName = ""; entity.ipAddress = params.ipAddress || ""; - await repo.save(entity); + entity.scope = params.scope || "user"; + await this.repository.save(entity); } catch (e) { logger.error("写入审计日志失败:", e); } } - async page(pageReq: AuditPageReq) { - const repo = this.getRepository(); - const { page, query, sort } = pageReq; - const offset = page?.offset ?? 0; - const limit = page?.limit ?? 20; - - const qb = repo.createQueryBuilder("main"); - - if (query?.userId != null) { - qb.andWhere("main.userId = :userId", { userId: query.userId }); - } - if (query?.type) { - qb.andWhere("main.type = :type", { type: query.type }); - } - if (query?.action) { - qb.andWhere("main.action = :action", { action: query.action }); - } - if (query?.createTime_start) { - qb.andWhere("main.createTime >= :start", { start: query.createTime_start }); - } - if (query?.createTime_end) { - qb.andWhere("main.createTime <= :end", { end: query.createTime_end }); - } - - if (sort?.prop) { - qb.orderBy("main." + sort.prop, sort.asc ? "ASC" : "DESC"); - } else { - qb.orderBy("main.id", "DESC"); - } - - qb.skip(offset).take(limit); - const list = await qb.getMany(); - const total = await qb.getCount(); - - return { - records: list, - total, - offset, - limit, - }; - } - async cleanExpired(retentionDays: number): Promise { - const repo = this.getRepository(); const cutoff = new Date(); cutoff.setDate(cutoff.getDate() - retentionDays); - const result = await repo.delete({ + const result = await this.repository.delete({ createTime: LessThan(cutoff), } as any); const deletedCount = result.affected || 0; @@ -112,11 +70,6 @@ export class AuditService { return deletedCount; } - async delete(id: number): Promise { - const repo = this.getRepository(); - await repo.delete({ id }); - } - registerCleanCron() { this.cron.register({ name: "audit.cleanExpired", diff --git a/packages/ui/certd-server/src/types/koa.d.ts b/packages/ui/certd-server/src/types/koa.d.ts new file mode 100644 index 000000000..10cad6c3f --- /dev/null +++ b/packages/ui/certd-server/src/types/koa.d.ts @@ -0,0 +1,9 @@ +import { AuditLogContext } from "@certd/lib-server"; + +declare module "koa" { + interface Context { + auditLog?: AuditLogContext; + auditRouteInfo?: { controllerClz?: any; method?: any; summary?: string; description?: string }; + projectId?: number; + } +}