金易证书/开放 API 文档

onessl 开放 API 文档

面向外部开发者 / 集成方。本文的每一个端点、每一个字段都可在后端源码里找到出处, 行末标注了来源(后端文件路径:行号 + 前端封装路径:行号)。源码里读不到明确结论的地方 一律标注「待确认」,不作推测。

权威来源:路由注册的唯一入口是 backend/apps/onessl-app-api/src/interface/router.rs (pub fn build(state: AppState) -> Router,全文 456 行)。本文端点清单是对该文件 87 条 .route() 注册、109 个「方法 × 路径」组合的逐条摘录 (动词分解:get 46 + post 45 + put 8 + delete 9 + patch 1 = 109,见文末附录)。


1. 概述

onessl 提供 TLS/SSL 证书全生命周期管理能力:证书申请与签发(ACME / 私有 CA)、 上传托管、自动续签、端点监控、CT-log 资产发现、自动化部署(Agent 拉取式)、 私有 CA 签发权威、通知与审计日志。

开始接入的最小路径:

  1. POST /api/v1/auth/login 拿 JWT(或让管理员在「设置 › API 密钥」生成一条 os_ 平台密钥);
  2. GET /api/v1/applications 取应用 id(几乎所有资源都以应用为作用域);
  3. 按业务调用资源端点。

2. 基础约定

2.1 Base URL

环境Base URL
本地开发http://127.0.0.1:8080/api/v1
生产https://<你的部署域名>/api/v1

监听地址由环境变量 SERVER_ADDR 决定,缺省 127.0.0.1:8080。 来源:apps/onessl-app-api/src/main.rs:394-395。

注意:/api/v1 前缀是路由字面量的一部分,没有 Router::nest(), 前端硬编码 const BASE = '/api/v1'(src/services/http.ts:14)。反向代理需原样透传路径。

Agent 端点族的 Base URL 是 http://<host>/api/agent/v1(见 §5.11),不带 /api/v1。

2.2 请求 / 响应编码

  • 请求体、响应体一律 application/json; charset=utf-8,字段命名 camelCase。
  • 唯一例外:PATCH /api/v1/deployment-tasks/{id}/paused 的请求体是 snake_case {"is_paused": bool}(interface/dto.rs:1152-1157,该结构体刻意不加 rename_all)。
  • Agent 端点族(/api/agent/v1/...)的请求/响应体是 snake_case,对齐 certkit 契约。

2.3 鉴权

/api/v1/* 的认证中间件 require_auth 同时接受两类凭据,按 os_ 前缀分派, 不做「先试 JWT 再试密钥」:

来源:apps/onessl-app-api/src/middleware/auth.rs:19-60, 101-133

凭据头判定角色来源失效方式
用户 JWTAuthorization: Bearer <jwt>非 os_ 前缀一律走此分支JWT claims 里的 role(签发时快照)登出即进黑名单,立即失效
平台 API 密钥Authorization: Bearer os_<32位base62>前缀 os_查库取 owner 的当前角色(管理员被降级后权限即时收敛)删除密钥

差异要点(写集成时必须知道):

  • API 密钥是系统级共享凭据:列表不按 user_id 过滤、删除按 id 不提 owner (interface/api_key_handler.rs:1-8)。user_id 只作创建者审计。
  • API 密钥明文只在 POST /api/v1/api-keys 的响应里返回一次 (ApiKeyDto interface/dto.rs:1423-1432 只有掩码,CreateApiKeyResponse :1457-1464 才带明文 key)。 库里只存 sha256 哈希 + 展示用前缀/后四位,明文不可恢复。
  • 明文格式:os_ + 32 位 base62([A-Za-z0-9]),总长 35 (libs/onessl-core/src/domain/api_key.rs:13-19)。
  • 列表里的 maskedKey = {prefix}••••••••{last4}(中间固定 8 个 U+2022) (domain/api_key.rs:106-110)。
  • 密钥鉴权失败一律 401,不泄露「密钥是否存在」(middleware/auth.rs:93-99)。 last_used_at 回写失败只告警、不阻断请求,且按 60 秒窗口节流(:121-124)。

三类鉴权要求在本文中缩写:

  • 公开:无任何鉴权头;
  • JWT:Bearer <jwt>;
  • JWT 或平台密钥:两者皆可(中间件不区分,但端点内的 SuperAdmin 守卫看角色);
  • SuperAdmin:JWT/平台密钥通过中间件后,端点内部再校验 role == SuperAdmin, 否则 403。绝大多数走统一守卫 AuthUser::require_super_admin(),返回 {"code":403,"message":"仅超级管理员可执行此操作"} (apps/onessl-app-api/src/state.rs:84-91);

    ⚠️ 但有例外:有 7 处 SuperAdmin 守卫没走统一守卫,而是直接 Err(AppError::Forbidden) → 文案是英文 operation forbidden (libs/core/src/error.rs:62;该文件 :25 的注释承认这是技术债)。 因此不要靠 message 判断是否权限不足,一律看 code == 403。 例外清单:ct_discovery_handler.rs:38/61/84/103、 private_ca_handler.rs:252/333/340(POST /api/v1/private-ca-authorities 创建全局 CA 即 :252,权限不足时返回的是 operation forbidden 而非中文串)。

  • AgentSig:ed25519 请求签名,见 §5.11。

2.4 应用作用域 appId

这是对接时最容易踩的坑。 几乎所有资源都归属某个应用(Application), 后端不再回退「默认应用」:

  • 列表类 GET /api/v1/certificates?appId=、GET /api/v1/monitoring?appId=、 GET /api/v1/dashboard/summary?appId=:appId 必填,缺失 400 {"message":"appId 必填"};
  • {id} 类端点:?appId= 必填,缺失由 axum Query 解构自动返 400(英文拒绝体, 不是中文 appId 必填);跨应用访问 → 404(不泄露资源存在性)。
  • 创建类端点:body.appId 必填(部署模板、部署任务、证书、上传证书、克隆模板、派生模板)。

来源:interface/certificate_handler.rs:54-60, 292-307; interface/monitoring_handler.rs:19-23, 149-164; interface/deployment_handler.rs:47-50, 230-245。

2.5 分页

列表端点统一用 page / pageSize(camelCase),响应包络:

{
  "data": [ /* ... */ ],
  "meta": { "page": 1, "pageSize": 20, "total": 137 }
}

来源:libs/core/src/response.rs:6-37。

各端点的默认值(不统一,逐个核对):

端点page 默认pageSize 默认
GET /certificates120
GET /finance/transactions110
GET /notifications120
GET /activity-logs120
GET /ct-discovery/certificates120
GET /ct-discovery/runs120

page / pageSize 都会 .max(1),传 0 会按 1 处理。 GET /api/v1/billing/events 不用分页,用 ?limit=(默认 100,clamp(1, 500))。 没有排序参数(无 sort / orderBy):排序是后端固定的(证书按 created_at 倒序、 检查历史倒序、presets 按 code 升序、CA 按 sort_order+code 升序)。

2.6 时间格式

两种并存,取决于 DTO,不能一概而论:

形态示例出现位置
北京时间展示串 YYYY-MM-DD HH:mm:ss(UTC+8)"2026-09-30 09:45:12"UserDto.createdAt、TransactionDto.time、NotificationDto.createdAt、ActivityLogDto.createdAt、AgentDto.*、DeploymentTaskDto.lastTime、MonitorDto.issuedAt/expiresAt、CtCertDto.*、AppDto.createdAt
RFC3339(带偏移)"2026-12-31T23:59:59+00:00"CertificateDto.expiresAt/issuedAt、PrivateCaAuthorityDto.rootNotAfter/issuingNotAfter/createdAt/updatedAt、MonitorCertInfoDto.notAfter

转换函数:interface/dto.rs:18-26(cn_time / cn_time_naive,固定 UTC+8)。 库里一律存 UTC。

入向时间(GET /activity-logs 的 from / to)接受 RFC3339 或 YYYY-MM-DD; 仅日期时按北京时间解释(下界当日 00:00:00、上界 23:59:59,闭区间)。 来源:interface/activity_log_handler.rs:103-131。

2.7 枚举:入向整数 / 出向可读串

后端库表用整数落库,对外输出可读串,但部分入向字段仍要整数。逐个核对:

枚举出向(响应)入向(请求)来源
角色 Role"SuperAdmin" / "User"整数 1 / 2libs/onessl-core/src/domain/user.rs:9-49;interface/dto.rs:82-85, 101-105
账号状态"Pending" / "Active"—(只读)domain/user.rs:53-90
证书状态"Pending" / "Active" / "Expiring" / "Expired"过滤参数取 "Pending"/"Active"/"Expired"domain/certificate.rs:27-63, 480-491
挑战子状态"pending" / "processing" / "valid" / "invalid"—(只读)domain/certificate.rs:69-107
证书类型"Single" / "Wildcard" / "Multi"创建时传串domain/certificate.rs:114-150
验证方式"dns" / "cname" / "http"创建时只允许 "" 或 "cname"interface/certificate_handler.rs:36-46
模板路径模式"unset"/"autofill"/"specific"/"none"传串domain/deployment.rs:55-90
模板作用域"platform" / "user"传串domain/deployment.rs:13-35
活动日志 action/targetType/resultsnake_case code 串过滤参数用同一批 code 串domain/activity_log.rs:223-279, 412-428, 483-487

Expiring 是派生状态(Active 且 30 天内到期,EXPIRING_THRESHOLD_DAYS = 30),不落库。

⚠️ 已知不一致(如实记录):GET /certificates?status= 的过滤走 CertStatus::from_str(...),而该函数只认 "Active" / "Expired", 其余值(含 "Expiring")一律兜底为 Pending (infrastructure/db/repositories.rs:435-439 + domain/certificate.rs:50-57)。 即 ?status=Expiring 等价于 ?status=Pending,不会报错。若要筛「临近到期」, 需客户端自行按 expiresInDays <= 30 && status == "Active" 过滤。


3. 错误约定

3.1 响应体结构

来源:libs/core/src/error.rs:46-76。任何非 2xx 都是这个形状:

{ "code": 400, "message": "appId 必填" }

code 就是 HTTP 状态码的数字形式(不是业务错误码)。message 中文/英文混用: 带内层文案的变体(BadRequest/Unprocessable/Conflict/ForbiddenMsg/DeploymentUnsupported) 输出中文或 CA 原文;无内层文案的变体输出固定英文:

HTTP形态message触发
400BadRequest(msg)msg(中文/CA 原文)参数缺失、校验失败
401中间件直返空 body(不是 JSON 包络)无/非法 Bearer 凭据
401Unauthorizedauthentication required业务层判未授权
401InvalidCredentials邮箱或密码错误登录失败
403Forbiddenoperation forbidden角色/归属不足。7 处 SuperAdmin 守卫也走这条(见 §2.3 例外清单)
403ForbiddenMsg仅超级管理员可执行此操作SuperAdmin 统一守卫(state.rs:84-91)
403ForbiddenMsg其它自定义串归属/成员校验(如非成员改应用)
404NotFoundnot found未命中 / 跨应用越权(统一按不存在处理)
409Conflict(msg)msg资源冲突(如邮箱已注册)
422Unprocessable(msg) / DeploymentUnsupported(msg)msg语义不可处理(如删默认应用)
500Internalinternal server error底层故障(详情只进服务端日志)

⚠️ 注意 401 有两种:中间件(缺 Authorization 头 / 前缀不符 / JWT 失效 / 密钥哈希未命中) 直接 StatusCode::UNAUTHORIZED.into_response(),响应体为空; 业务层 AppError::Unauthorized 才返回 JSON 包络。客户端解析错误体时必须容错。 来源:middleware/auth.rs:27, 43, 47, 51, 112, 118。

3.2 常见错误文案(源码里逐字可见)

appId 必填
domains 不能为空
domain 不能为空
当前仅支持 CNAME(免 DNS 授权 / acme-dns)验证方式
必须同意服务条款
姓名或邮箱格式不正确
角色取值非法
不能修改自己的角色
姓名不能为空
没有需要更新的字段
缺少邀请令牌
密码长度至少 8 位
baseTemplateId 与 templateId 只能填一个
必须指定模板
证书尚未签发
HOST 不能为空
未知的 CA 密钥算法: {x}(允许 EC_P256 / EC_P384 / RSA_2048 / RSA_4096)
该 CA 尚未完成证书回传,暂无证书可下载
该 CA 没有 CSR(仅 Bring your own root 未回传证书时有)
未知的活动动作: {code}
时间格式无效(需 RFC3339 或 YYYY-MM-DD): {s}

没有业务错误码表:ErrorBody 只有 code + message,code 等于 HTTP 状态。 (待确认:未来是否会引入独立业务码 —— 源码内无任何相关实现或 TODO。)


4. 统一成功包络

{ "data": <T>, "meta": { "page": 1, "pageSize": 20, "total": 137 } }
  • meta 只在分页端点出现(#[serde(skip_serializing_if = "Option::is_none")])。

  • 无返回体的动作端点(删除 / 通知全部标记已读 / 切换开关 等)返回 {"data":{"success":true}} (ApiResponse::ack(),libs/core/src/response.rs:54-62)。

  • 少数端点返回 {"data": null}:返回类型写作 ApiResponse<()> 的端点。全仓只有 3 处, 且全在监控模块:

    端点handler返回
    PUT /api/v1/monitoring/{id}monitoring_handler.rs:51{"data":null}
    POST /api/v1/monitoring(开启监控)monitoring_handler.rs:110{"data":null}
    DELETE /api/v1/monitoring/{id}(关闭监控)monitoring_handler.rs:135{"data":null}

    ⚠️ 集成方踩坑点:开启 / 关闭监控都不返回 {"success":true},只有 {"data":null}。 判定成败请看 HTTP 状态码(2xx = 成功),不要去读 data.success —— 该字段在这三个端点上不存在。


5. 端点全清单

总计 109 个「方法 × 路径」组合 / 87 条路径,分三组路由表: 公开 6 个、需鉴权 95 个、AgentSig 8 个(6 + 95 + 8 = 109)。

自校验口径:以 router.rs 正文(剥离 // 注释后)按括号配平统计 —— get 46 / post 45 / put 8 / delete 9 / patch 1,合计 109。 注释里提到的 POST /api/agent/v1/register-agent 等字样不计入(router.rs:30 附近为注释)。

标注格式:后端 文件:行号 指 handler 函数定义行;前端 src/services/xx.ts:行号 指封装函数行。

5.1 认证(Auth)

方法 路径鉴权后端前端
POST /api/v1/auth/register公开auth_handler.rs:15auth.ts:29
POST /api/v1/auth/login公开auth_handler.rs:37auth.ts:22
GET /api/v1/auth/meJWT 或平台密钥auth_handler.rs:69auth.ts:36
POST /api/v1/auth/logoutJWT 或平台密钥auth_handler.rs:311auth.ts:40
POST /api/v1/auth/change-passwordJWT 或平台密钥auth_handler.rs:85auth.ts:47

POST /api/v1/auth/login

Body(LoginRequest,dto.rs:40-43):

字段类型必填
emailstring✅
passwordstring✅

响应 200:

{
  "data": {
    "user": {
      "id": 1,
      "name": "张三",
      "email": "ops@example.com",
      "role": "SuperAdmin",
      "initials": "张",
      "createdAt": "2026-01-04 10:22:31",
      "status": "Active",
      "mustChangePassword": true
    },
    "accessToken": "eyJhbGciOi...",
    "expiresIn": 7200,
    "mustChangePassword": true
  }
}

expiresIn 取自 JWT_EXPIRY_SECS(本地 .env 为 7200)。 首登强制改密标记有两个出口、同源同值:顶层 mustChangePassword(前端 services/auth.ts:login() 自此读取) 与 user.mustChangePassword(UserDto 字段,dto.rs:69);GET /api/v1/auth/me 亦返回同一字段, 供已登录会话(如 /change-password 页刷新后)重新判定首登窗口。 登录成功/失败都会写活动日志;失败只记被尝试的邮箱,不记密码 (auth_handler.rs:33-60)。

curl -s http://127.0.0.1:8080/api/v1/auth/login \
  -H 'Content-Type: application/json' \
  -d '{"email":"ops@example.com","password":"********"}' | jq -r '.data.accessToken'

POST /api/v1/auth/change-password

修改自己的密码(Bearer 保护)。Body(ChangePasswordRequest,dto.rs:110-122):

字段类型必填说明
oldPasswordstring视情况首登窗口可省略(见下表);提供且非空 → 与当前密码比对
newPasswordstring✅至少 8 位,否则 400

安全边界(用户 2026-10-06 裁定):

条件结果
提供且非空 oldPassword一律照常校验;不匹配 → 403「当前密码不正确」
省略 / 空串 oldPassword 且 must_change_password == true放行(首登窗口:旧密码是一次性临时密码)
省略 / 空串 oldPassword 且 must_change_password == false400「请提供当前密码」

成功 200 → {"data":{"success":true}},后端清 must_change_password(下次登录不再强制)。 客户端判定走哪条分支:读 GET /api/v1/auth/me 的 mustChangePassword(UserDto.mustChangePassword, dto.rs:69);后端旧构建不返回该字段时应按 false(普通改密,仍须旧密码)兜底。

# 普通改密:必须带旧密码
curl -s http://127.0.0.1:8080/api/v1/auth/change-password \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"oldPassword":"<当前密码>","newPassword":"Str0ng-Passw0rd"}'

# 首登窗口:可省略旧密码
curl -s http://127.0.0.1:8080/api/v1/auth/change-password \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"newPassword":"Str0ng-Passw0rd"}'

POST /api/v1/auth/register

Body(RegisterRequest,dto.rs:31-36):name(string,✅) / email(string,✅) / password(string,✅) / agreedTerms(bool,✅,须为 true 否则 400「必须同意服务条款」)。

⚠️ 待确认(源码实读结论,非推测):register 没有密码长度下限校验; 而免登录的 accept-invite 有「至少 8 位」。源码里明确标注这是既有技术债、 两处口径不一致(auth_handler.rs:214-218)。集成方不要依赖注册端做强度校验。

POST /api/v1/auth/logout

无 body。把当前 JWT 加入黑名单(按 exp 记录),后续携带该 token 的请求一律 401 (middleware/auth.rs:45-48)。响应 {"data":{"success":true}}。

5.2 用户与邀请(Users)

方法 路径鉴权后端前端
GET /api/v1/usersSuperAdminauth_handler.rs:79users.ts:24
POST /api/v1/users/inviteSuperAdminauth_handler.rs:204users.ts:33
POST /api/v1/users/{id}/invite/resendSuperAdminauth_handler.rs:245users.ts:45
POST /api/v1/users/{id}/invite/revokeSuperAdminauth_handler.rs:165users.ts:50
PUT /api/v1/users/{id}JWT 或平台密钥(改 role / 改他人 name 需 SuperAdmin)auth_handler.rs:258users.ts:76
GET /api/v1/users/invite/{token}公开auth_handler.rs:194users.ts:58
POST /api/v1/users/accept-invite公开auth_handler.rs:206users.ts:66

POST /api/v1/users/invite

Body(InviteUserRequest,dto.rs:101-105):

字段类型必填说明
namestring✅非空(trim 后)
emailstring✅需含 @
roleint❌1=SuperAdmin / 2=User;缺省 2;其他值 400「角色取值非法」

响应(InviteUserResponse,dto.rs:119-135):

{
  "data": {
    "id": 12, "name": "李四", "email": "li@example.com",
    "role": "User", "status": "Active",
    "emailStatus": "queued", "emailReason": null,
    "temporaryPassword": "<一次性临时密码>", "inviteTtlHours": 72
  }
}

语义(务必理解,直接影响建号后的可用性):

  • 🔴 后台异步投递:请求立即返回,不等 SMTP;emailStatus 恒为 queued(邮件已交给后台任务), 投递的真实结果不回传,只写服务端 tracing 日志。queued 表示「已提交发送」,不是「已送达」。
  • 🔴 账号恒为 Active 且 must_change_password=true —— 改密前凭一次性临时密码即可登录, 首次登录后强制设置新密码(2026-10-06 起,异步投递不再影响账号状态)。
  • temporaryPassword 恒有值(非 null):异步下无法预知邮件是否送达,故始终回显一次性临时密码, 作为管理员的线下交付通道(邮件正文亦含密码与登录链接)。
  • emailStatus 四态:queued(默认,已交后台异步投递)/ sent(已送达)/ skipped(配置缺失)/ failed(真实故障)。后端当前恒出 queued;后三者仅保留于响应契约(将来若恢复同步投递可复用)。 emailReason 说明未送达原因,queued 时恒为 null。
  • 邀请链接有效期固定 72 小时(INVITE_TTL_HOURS,domain/user_invite.rs:23), 响应里 inviteTtlHours 带回,客户端不要硬编码。

站点公开地址(拼邀请链接用)优先级:system_config 表的键 site.public_url → 环境变量 PUBLIC_URL → 请求自带 Origin / Referer / X-Forwarded-Proto+Host 兜底(domain/setting.rs:99、 main.rs:243-250;请求头解析见 auth_handler.rs 的 request_origin)。 🔴 三者皆空也不再短路跳过投递(2026-10-06 用户裁定「不用管 PUBLIC_URL 配置」)——仍照旧投递, 只是邮件正文里的登录链接可能不完整。 SMTP 走环境变量(SMTP_HOST/SMTP_PORT/SMTP_USERNAME/SMTP_PASSWORD/SMTP_FROM/SMTP_TLS), 不是库表配置项(backend/.env 第 18-24 行)。

curl -s http://127.0.0.1:8080/api/v1/users/invite \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"name":"李四","email":"li@example.com","role":2}'

POST /api/v1/users/{id}/invite/resend

无 body。先作废该用户全部仍有效旧令牌再签发新的 —— 旧邮件链接立即失效 (auth_handler.rs:236-244,resend_invite 的 doc 注释)。响应形状同 invite (同样后台异步投递,emailStatus 恒为 queued)。

POST /api/v1/users/{id}/invite/revoke

无 body。仅作废令牌、不删账号。响应 RevokeInviteResponse(dto.rs:199-204):

{ "data": { "id": 12, "email": "li@example.com", "status": "Pending", "revoked": 1 } }

revoked = 实际作废的令牌条数,0 表示本就没有有效邀请(如实回报,不谎报成功)。

PUT /api/v1/users/{id}

Body(UpdateUserRequest,dto.rs:82-85):name(string,❌) / role(int,❌)。 两字段全缺省 → 400「没有需要更新的字段」。

权限三则(auth_handler.rs:247-257):改 role 必须 SuperAdmin; 禁止改自己的角色(400「不能修改自己的角色」,防自锁); 改他人 name 也须 SuperAdmin;改自己 name 无额外要求。

GET /api/v1/users/invite/{token}(公开)

只回非敏感字段(InviteDetailResponse,dto.rs:172-181):

{ "data": { "name": "李四", "email": "li@example.com", "role": "User",
            "expiresAt": "2026-10-03 09:45:12", "problem": null } }

令牌不可用(过期/已用/已撤销)时不抛错,problem 给出中文原因。

POST /api/v1/users/accept-invite(公开)

Body(AcceptInviteRequest,dto.rs:159-164):token(string,✅,邮件链接里的 40 位明文令牌) / password(string,✅,至少 8 位,按 char 计数)。响应为激活后的 UserDto。 令牌一次性 + 有期限。

curl -s http://127.0.0.1:8080/api/v1/users/accept-invite \
  -H 'Content-Type: application/json' \
  -d '{"token":"<40位令牌>","password":"Str0ng-Passw0rd"}'

5.3 应用(Applications)—— 作用域隔离单元

方法 路径鉴权后端前端
GET /api/v1/applicationsJWT 或平台密钥app_handler.rs:24application.ts:11
POST /api/v1/applicationsJWT 或平台密钥app_handler.rs:40application.ts:22
GET /api/v1/applications/{id}JWT 或平台密钥app_handler.rs:61application.ts:17
PUT /api/v1/applications/{id}主体管理员 + SuperAdminapp_handler.rs:72application.ts:27
DELETE /api/v1/applications/{id}主体管理员 + SuperAdminapp_handler.rs:96application.ts:32
GET /api/v1/applications/{id}/members主体管理员 + SuperAdmin(member 只读)app_handler.rs:111application.ts:43
PUT /api/v1/applications/{id}/members主体管理员 + SuperAdminapp_handler.rs:122application.ts:54
GET /api/v1/applications/{id}/member-candidates主体管理员 + SuperAdmin(member → 403)app_handler.rs:164application.ts:71
GET /api/v1/applications/{id}/agent-registration-key主体管理员 + SuperAdmin(member 只读)app_handler.rs:200agent.ts:114

GET /api/v1/applications 响应(AppDto,dto.rs:1669-1680,内联三色统计):

{ "data": [ {
  "id": 3, "name": "生产环境", "code": "a1b2c3d4", "description": null,
  "isDefault": true, "createdAt": "2026-01-04 10:22:31", "updatedAt": "2026-09-01 08:00:00",
  "stats": {
    "certificates": { "green": 12, "orange": 2, "red": 0 },
    "monitoring":    { "green": 4,  "orange": 0, "red": 1 },
    "agents":        { "green": 3,  "orange": 0, "red": 0 }
  }
} ] }

POST body:{"name": string, "description"?: string}。 PUT body 同(name 必填,全量覆盖)。

DELETE 返回 200 + AppResourceCounts(domain/app.rs:73-79), 供前端确认弹窗展示将级联删除的数量;默认应用返回 422:

{ "data": { "certificates": 14, "monitoring": 5, "agents": 3,
            "deploymentTasks": 6, "deploymentTemplates": 2 } }

成员:

  • GET .../members → [{"userId":7,"name":"李四","email":"li@example.com","initials":"李"}] (只含被授权的普通用户;主体管理员与 SuperAdmin 不入成员表)
  • PUT .../members body {"members":[{"userId":7},{"userId":9}]} —— 全量覆盖, 传 [] = 清空全部授权;SuperAdmin 会被后端过滤掉不入表。
  • GET .../member-candidates → [{"id":7,"name":"李四","email":"...","initials":"李"}] (信息最小化,不含角色/状态/时间;已过滤为 Active + 非 SuperAdmin + 非当前用户)

GET .../agent-registration-key 返回 {"code":"a1b2c3d4","lastUsedAt":"2026-09-02 11:00:00","registrationKey":"<明文或null>"}。

🔴 该端点可能触发一次幂等补齐:若该应用尚无密钥(存量老应用),首次读取时会生成并落库 (app_handler.rs:195-199)。已有密钥只读不改、永不轮换。 registrationKey 为 null 只剩一种情形:0098 迁移之前的存量密钥没有密文列,明文找不回。 POST(生成/重置)与 DELETE(吊销)已按 certkit 对齐移除(router.rs:370-379)。

5.4 证书(Certificates)

方法 路径鉴权后端前端
GET /api/v1/certificatesJWT 或平台密钥certificate_handler.rs:49certificate.ts:41
POST /api/v1/certificatesJWT 或平台密钥certificate_handler.rs:81certificate.ts:63
POST /api/v1/certificates/uploadJWT 或平台密钥certificate_handler.rs:150certificate.ts:205
POST /api/v1/certificates/cname-reserveJWT 或平台密钥certificate_handler.rs:188certificate.ts:117
POST /api/v1/certificates/cname-checkJWT 或平台密钥certificate_handler.rs:202certificate.ts:129
POST /api/v1/certificates/http-reserveJWT 或平台密钥certificate_handler.rs:222certificate.ts:140
POST /api/v1/certificates/http-checkJWT 或平台密钥certificate_handler.rs:246certificate.ts:149
GET /api/v1/certificates/{id}JWT 或平台密钥certificate_handler.rs:310certificate.ts:172
DELETE /api/v1/certificates/{id}JWT 或平台密钥certificate_handler.rs:323certificate.ts:178
GET /api/v1/certificates/{id}/challengeJWT 或平台密钥certificate_handler.rs:341certificate.ts:183
POST /api/v1/certificates/{id}/verifyJWT 或平台密钥certificate_handler.rs:353certificate.ts:188
GET /api/v1/certificates/{id}/bundleJWT 或平台密钥certificate_handler.rs:418certificate.ts:230
POST /api/v1/certificates/{id}/reissueJWT 或平台密钥certificate_handler.rs:378certificate.ts:194
GET /api/v1/certificates/{id}/applicationsJWT 或平台密钥certificate_handler.rs:404certificate.ts:220

GET /api/v1/certificates

Query:page(❌,默认1) / pageSize(❌,默认20) / keyword(❌,按 domain 列 LIKE %kw%) / status(❌,见 §2.7 的坑) / appId(✅,缺失 400「appId 必填」)。

响应 CertificateDto(dto.rs:333-359,注意 type 是保留字命名字段):

{ "data": [ {
  "id": 101, "domain": "*.example.com", "type": "Wildcard", "status": "Active",
  "provider": "letsencrypt", "expiresAt": "2026-12-28T07:59:59+00:00",
  "issuedAt": "2026-09-29T07:59:59+00:00", "issuer": "Let's Encrypt",
  "serialNumber": "03a1...", "keyType": "EC P-256", "expiresInDays": 89,
  "challengeStatus": "valid", "domains": ["*.example.com","example.com"],
  "verificationMethod": "cname", "source": "platform",
  "acmeAccountId": null, "thumbprintSha1": "A1B2C3..."
} ], "meta": { "page": 1, "pageSize": 20, "total": 137 } }

注:certificates 表的域名列是 domain(不是 common_name)。 thumbprintSha1 是叶子证书 DER 的 SHA1(大写 hex)= Windows 证书指纹; 证书未签发时为 null。

curl -s "http://127.0.0.1:8080/api/v1/certificates?appId=3&page=1&pageSize=20" \
  -H "Authorization: Bearer $TOKEN"

POST /api/v1/certificates

Body(CreateCertRequest,dto.rs:209-249):

字段类型必填说明
providerstring✅自由串;私有 CA 路径传 ""
certTypestring✅Single / Wildcard / Multi(未知兜底 Single)
domainsstring[]✅*与 domain 二选一提供(domains 优先;都空 → 400「domains 不能为空」)
domainstring✅*主域名,缺省取 domains[0]
verificationMethodstring✅只允许 "" 或 "cname",其他值 400
appIdint✅缺失 400「appId 必填」
caCodestring❌ca_providers.code
acmeAccountIdint|null❌指定第三方 CA 账号;null/缺省 = 平台默认 EAB
cnameFulldomain / cnameUsername / cnamePasswordstring❌复用已预留的 acme-dns 凭据
keyAlgostring❌EC_P256/EC_P384/RSA_2048/RSA_4096
profilestring❌记录用途,不改变 ACME 实际有效期(恒 90 天)
descriptionstring❌备注
privateCaIdint|null❌私有 CA 本地签发;与非空 caCode 互斥(同时出现 → 400)

成功返回 201。私有 CA 路径同步签发,落库即 Active;ACME 路径是异步的, 创建后状态为 Pending。

⚠️ google 是当前唯一 CA_REQUIRES_USER_ACCOUNT 命中的 CA:未指定 acmeAccountId 时创建/续签一律 400,必须先在「设置 › 证书颁发机构」登记账号(dto.rs:222-224)。

curl -s http://127.0.0.1:8080/api/v1/certificates \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"provider":"letsencrypt","certType":"Wildcard","domains":["*.example.com","example.com"],
       "verificationMethod":"cname","appId":3,"caCode":"letsencrypt","keyAlgo":"EC_P256"}'

POST /api/v1/certificates/upload

Body:certPem(string,✅) / certKeyPem(string,✅) / appId(int,✅) / description(string,❌)。 域名/类型/提供方由后端从证书内容解析(SAN/CN);source 落 uploaded (不支持自动续签)。返回 201。

CNAME / HTTP 预校验(创建前的向导用)

  • POST /certificates/cname-reserve:无 body。向 acme-dns 注册专属子域,返回 {"fulldomain":"<uuid>.ca.jinyiapp.com","username":"...","password":"..."}。 ⚠️ 该端点每次调用都注册一个新子域,重复调用会产生多个 acme-dns 账号; 创建证书时回传 cnameFulldomain/cnameUsername/cnamePassword 可复用以避免重复注册。
  • POST /certificates/cname-check body {"domains":["..."],"fulldomain":"..."} → {"ok":bool,"delegated":[...],"notDelegated":[...],"message":"..."}。只读,不写库、不签发。
  • POST /certificates/http-reserve body {"domains":["..."]} → [{"domain":"...","token":"...","keyAuth":"...","url":"http://.../.well-known/acme-challenge/<token>"}]。
  • POST /certificates/http-check body {"domains":["..."]} → {"ok":bool,"verified":[...],"failed":[...],"message":"..."}。

GET /api/v1/certificates/{id}/challenge

Query ?appId= 必填。响应 ChallengeDto(dto.rs:402-409):

{ "data": {
  "method": "cname", "recordName": "_acme-challenge.example.com",
  "recordValue": "a1b2c3d4.ca.jinyiapp.com", "challengeStatus": "pending",
  "records": [ { "domain": "example.com", "host": "_acme-challenge.example.com",
                 "value": "a1b2c3d4.ca.jinyiapp.com" } ]
} }

records 是按验证方式派生的逐域名记录:DNS=TXT、CNAME=CNAME 委派目标、HTTP=key authorization。

POST /api/v1/certificates/{id}/verify

Query ?appId= 必填,无 body。触发 finalize + 状态流转。返回更新后的 CertificateDto。

🔴 首次签发不需要(也不应)轮询调用它:后端有后台调度 pending_cname_verify_scheduler(main.rs:538-626),每 120 秒扫一次仍 Pending 的 CNAME 证书,委派一生效就自动完成签发(单证书 1800 秒退避,防烧 CA 失败配额)。 前端「验证」按钮已于 2026-09-27 移除。

GET /api/v1/certificates/{id}/bundle

Query ?appId= 必填。响应不是 JSON:application/zip, Content-Disposition: attachment; filename="<domain>.zip", 包内 {domain}/fullchain.pem + {domain}/privkey.pem(* 会被替换为 star)。 证书未签发 → 400「证书尚未签发」。

curl -s -o cert.zip "http://127.0.0.1:8080/api/v1/certificates/101/bundle?appId=3" \
  -H "Authorization: Bearer $TOKEN"

POST /api/v1/certificates/{id}/reissue

Query ?appId= 必填。Body(ReissueCertRequest,dto.rs:1808-1811): caCode(string,❌) / verificationMethod(string,❌)。原地更新,不新增行。

GET /api/v1/certificates/{id}/applications

Query ?appId= 必填。返回该证书的全部申请/续签记录(倒序)。ApplicationDto(dto.rs:1816-1837):

{ "data": [ {
  "id": 55, "certificateId": 101, "applicationType": "issue", "trigger": "manual",
  "status": "success", "caCode": "letsencrypt", "serialNumber": "03a1...",
  "issuedAt": "2026-09-29 15:59:59", "expiresAt": "2026-12-28 15:59:59",
  "issuer": "Let's Encrypt", "challengeStatus": "valid",
  "cnameFulldomain": "a1b2c3d4.ca.jinyiapp.com", "errorMessage": null,
  "createdAt": "2026-09-29 15:58:01", "finishedAt": "2026-09-29 15:59:59",
  "operator": "3"
} ] }

applicationType: issue / renew_manual / renew_auto; trigger: manual / auto;status: pending / success / failed。

5.5 CA 签发商与第三方 ACME 账号

方法 路径鉴权后端前端
GET /api/v1/ca-providersJWT 或平台密钥ca_provider_handler.rs:17certificate.ts:158
GET /api/v1/ca-providers/{code}JWT 或平台密钥ca_provider_handler.rs:33certificate.ts:167
PUT /api/v1/ca-providers/{code}SuperAdminca_provider_handler.rs:54—(无前端封装)
GET /api/v1/acme-accountsSuperAdminacme_account_handler.rs:16acmeAccounts.ts:17
POST /api/v1/acme-accountsSuperAdminacme_account_handler.rs:31acmeAccounts.ts:23
POST /api/v1/acme-accounts/{id}/verifySuperAdminacme_account_handler.rs:60acmeAccounts.ts:38
DELETE /api/v1/acme-accounts/{id}SuperAdminacme_account_handler.rs:92acmeAccounts.ts:43

GET /api/v1/ca-providers 响应 CaProviderDto[](dto.rs:1290-1307):

{ "data": [ {
  "id": "1", "code": "letsencrypt", "name": "Let's Encrypt", "description": "由 ISRG 运营…",
  "supportedCertTypes": ["single","wildcard","multi"],
  "supportedValidationMethods": ["dns","cname","http"],
  "acmeDirectoryUrl": "https://acme-v02.api.letsencrypt.org/directory",
  "useProxy": false, "proxyUrl": null, "eabRequired": false
} ] }

排序按 sort_order 升序 + code 升序(Let's Encrypt = 0 恒首位)。 已内置种子:letsencrypt / sectigo / digicert / godaddy / zerossl / actalis / globalsign (迁移 0103_add_six_ca_providers.sql:47-52、0111_letsencrypt_restore_and_eab_required.sql:41-44)。

eabRequired: true 且平台未配默认 EAB 的机构,前端须置灰并提示先登记账号。

PUT /api/v1/ca-providers/{code} body(UpdateCaProviderRequest,dto.rs:1797-1803): useProxy(bool,❌) / proxyConfig(object,❌,完全覆盖) / extensionParams(object,❌,完全覆盖)。

⚠️ 改代理配置后需重启后端才对 ACME 出网生效(CA 注册表启动时构建一次)— ca_provider_handler.rs:47-49。

ACME 账号 AcmeAccountDto(dto.rs:1336-1357)—— 永不返回 EAB HMAC(只给布尔):

{ "data": [ {
  "id": 4, "name": "我的 ZeroSSL", "providerCode": "zerossl", "providerName": "ZeroSSL",
  "accountEmail": "ops@example.com", "eabKeyId": "abc123", "hasEabHmac": true,
  "acmeDirectoryUrl": "https://acme.zerossl.com/v2/DV90",
  "eabVerifiedAt": "2026-09-20 14:00:00", "eabVerifyError": null,
  "accountUrl": "https://acme.zerossl.com/v2/DV90/account/xxx",
  "createdAt": "2026-09-20 13:59:00"
} ] }

POST /api/v1/acme-accounts body(CreateAcmeAccountRequest,dto.rs:1386-1399): name(✅) / providerCode(✅) / accountEmail(✅) / eabKeyId(❌) / eabHmac(❌,明文,仅此一次出域)。 创建时即真出网校验 EAB:CA 明确拒绝 → 400 且不入库;无法完成校验 → 入库并记 eabVerifyError (acmeAccounts.ts 头部注释)。

POST /api/v1/acme-accounts/{id}/verify:恒 200,失败信息在 eabVerifyError 字段。 只有 404(账号不存在/不属该用户)与 403(非超管)会走错误码。 ⚠️ 会真出网,可能耗时 10–30 秒。当前应用内无调用方(端点保留供运维脚本复用)。

curl -s http://127.0.0.1:8080/api/v1/acme-accounts \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"name":"我的 ZeroSSL","providerCode":"zerossl","accountEmail":"ops@example.com",
       "eabKeyId":"<kid>","eabHmac":"<hmac>"}'

5.6 平台 API 密钥(Api Keys)

方法 路径鉴权后端前端
GET /api/v1/api-keysSuperAdminapi_key_handler.rs:20apiKeys.ts:16
POST /api/v1/api-keysSuperAdminapi_key_handler.rs:32apiKeys.ts:22
DELETE /api/v1/api-keys/{id}SuperAdminapi_key_handler.rs:53apiKeys.ts:27

GET 响应(ApiKeyDto,dto.rs:1423-1432)—— 只有掩码:

{ "data": [ { "id": 1, "name": "CI 机器人", "maskedKey": "os_abc12345••••••••9a2f",
              "createdAt": "2026-09-01 10:00:00", "lastUsedAt": "2026-09-30 08:12:44" } ] }

POST body {"name": string},响应(CreateApiKeyResponse,dto.rs:1457-1464):

{ "data": { "id": 2, "name": "CI 机器人",
            "plaintext": "os_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
            "createdAt": "2026-09-30 09:45:12" } }

🔴 plaintext 只在本次响应出现一次,之后任何接口都拿不到(库里只有 sha256)。 请立刻写入你的密钥管理设施。

curl -s http://127.0.0.1:8080/api/v1/api-keys \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"name":"CI 机器人"}'
# 之后所有 /api/v1 请求都可以:
curl -s http://127.0.0.1:8080/api/v1/certificates?appId=3 \
  -H "Authorization: Bearer os_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

5.7 私有 CA(Private CA Authorities)

方法 路径鉴权后端前端
GET /api/v1/private-ca-authoritiesJWT 或平台密钥(读)private_ca_handler.rs:42privateCa.ts:25
POST /api/v1/private-ca-authoritiesSuperAdminprivate_ca_handler.rs:245privateCa.ts:50
GET /api/v1/private-ca-authorities/{id}JWT 或平台密钥(读)private_ca_handler.rs:64privateCa.ts:32
DELETE /api/v1/private-ca-authorities/{id}创建者 + SuperAdminprivate_ca_handler.rs:74privateCa.ts:62
GET /api/v1/private-ca-authorities/{id}/download读可见private_ca_handler.rs:101privateCa.ts:73
GET /api/v1/private-ca-authorities/{id}/csr创建者 + SuperAdminprivate_ca_handler.rs:162privateCa.ts:102
POST /api/v1/private-ca-authorities/{id}/certificate创建者 + SuperAdminprivate_ca_handler.rs:214privateCa.ts:132

全局化(迁移 0115):私有 CA 不再归属单个应用,一律 appId = 0(全局哨兵), 信任锚下发给所有应用的 Agent。请求体里的 appId 已废弃并被忽略 (private_ca_handler.rs:267,字段保留只为兼容旧前端)。 可见性:全局 CA 所有登录用户可读;管理(创建/删除/回传/下载 CSR)限创建者 + SuperAdmin; 创建一律 SuperAdmin(全局 CA 会进所有应用信任库,普通用户可创建 = 提权面)。

GET Query:?appId= 可选。传则先校验该应用访问权再列该 app;不传则按可见应用集合过滤。

响应 PrivateCaAuthorityDto(dto.rs:2025-2054,有单测锁死 16 个键,永不含私钥):

{ "data": [ {
  "id": 42, "appId": 0, "name": "Internal Root", "keyAlgo": "EC_P384",
  "hierarchy": "root_and_issuing", "status": "active",
  "rootCertPem": "-----BEGIN CERTIFICATE-----\n…",
  "rootSha256": "abab…", "rootNotAfter": "2036-01-01T00:00:00+00:00",
  "issuingCertPem": "-----BEGIN CERTIFICATE-----\n…",
  "issuingSha256": "cdcd…", "issuingNotAfter": "2035-01-01T00:00:00+00:00",
  "csrPem": null, "nameConstraints": null,
  "createdAt": "2026-01-01T00:00:00+00:00", "updatedAt": "2026-01-02T00:00:00+00:00"
} ] }

枚举:hierarchy = root_and_issuing / bring_your_own_root / root_only (未知值 400,不兜底);keyAlgo = EC_P256 / EC_P384 / RSA_2048 / RSA_4096 (严格匹配,未知值 400 —— 另有大小写/连字符别名 ec-p256、rsa4096 等, 见 private_ca_handler.rs:299-310);status = active / disabled / pending_cert。

POST body(CreatePrivateCaRequest,dto.rs:1987-2003):

字段类型必填说明
namestring✅≤128 字符
hierarchystring✅见上
keyAlgostring✅见上
nameConstraintsobject|null❌{"permitted":[…],"excluded":[…]};bring_your_own_root 传非空约束 → 400
appIdint❌已废弃,值被忽略

BYO(bring_your_own_root)两步流程:

  1. POST 创建 → 返回 status: "pending_cert"、csrPem 非空、证书字段全 null;
  2. GET /{id}/csr 下载 PKCS#10 CSR → 用你自己的根 CA 签发 Issuing CA;
  3. POST /{id}/certificate body {"issuingCertPem":"…","rootCertPem":"…"} → 激活, 返回 status: "active" 且信任锚同步下发。

GET /{id}/download 返回 application/x-pem-file 附件(不是 JSON): root_only → 根一段;root_and_issuing / 已激活 BYO → 根 + Issuing 两段(根在前)。 拼链判据是 issuingCertPem 是否存在(与层级名解耦)。 BYO pending(无 rootCertPem)→ 400「该 CA 尚未完成证书回传,暂无证书可下载」。 disabled 的 CA 允许下载(公钥证书,拒绝无安全收益)。

curl -s -O -J "http://127.0.0.1:8080/api/v1/private-ca-authorities/42/download" \
  -H "Authorization: Bearer $TOKEN"

5.8 端点监控(Monitoring)

方法 路径鉴权后端前端
GET /api/v1/monitoringJWT 或平台密钥monitoring_handler.rs:16monitoring.ts:5
POST /api/v1/monitoringJWT 或平台密钥monitoring_handler.rs:106monitoring.ts:43
GET /api/v1/monitoring/{id}JWT 或平台密钥monitoring_handler.rs:31monitoring.ts:11
PUT /api/v1/monitoring/{id}JWT 或平台密钥monitoring_handler.rs:45monitoring.ts:63
DELETE /api/v1/monitoring/{id}JWT 或平台密钥monitoring_handler.rs:130monitoring.ts:58
POST /api/v1/monitoring/{id}/query-certificateJWT 或平台密钥monitoring_handler.rs:75monitoring.ts:28
GET /api/v1/monitoring/{id}/checksJWT 或平台密钥monitoring_handler.rs:92monitoring.ts:39

GET /api/v1/monitoring?appId=(appId 必填,缺失 400「appId 必填」)。 MonitorDto(dto.rs:595-614):

{ "data": [ {
  "id": 7, "name": "example.com", "domain": "example.com", "status": "Live",
  "latency": null, "securityGrade": null, "lastCheck": null,
  "issuer": "Let's Encrypt", "serialNumber": "03a1…",
  "issuedAt": "2026-09-29 15:59:59", "expiresAt": "2026-12-28 15:59:59",
  "expiresInDays": 89, "san": ["example.com","www.example.com"]
} ] }

⚠️ latency / securityGrade / lastCheck 当前恒为 null(方案 B:真实探测未实现)。 status 三值 Live / Scanning / Degraded 由平台证书状态派生 (Active→Live、Pending→Scanning、其他→Degraded;外部域名无平台证书 → Scanning)。 来源:domain/monitor.rs:79-96。 后端每日调度做一次全量检查(main.rs:652-662)。

POST /api/v1/monitoring body(EnableMonitorRequest,dto.rs:716-724): domain(string,✅) / port(int,❌,缺省 443) / description(string,❌) / appId(int,✅)。 返回 {"data":null}(成功即 200)。

PUT /api/v1/monitoring/{id} body:domain(✅,trim 后非空否则 400「HOST 不能为空」) / port(❌) / description(❌) / appId(✅,在 body 里)。返回 {"data":null}。

POST /api/v1/monitoring/{id}/query-certificate?appId= 无 body: 对 domain:port 发起真实 TLS 握手,返回现网实际下发的叶子证书元信息。

🔴 这不是只读探针,它有写副作用。(早前版本误标为「只读,不落库」,已更正) 服务层 monitoring_service.rs:48-51 的注释即写明「解析元信息并落库」, query_certificate(:52)直接调用 check_one(:66),而 check_one 做三件事:

副作用位置说明
更新监控目标快照monitoring_service.rs:99-119写 last_checked_at / last_cert_not_after / last_cert_issuer / last_cert_serial / updated_at,即 MonitorDto 的「上次检查 / 过期剩余天数」数据源
追加一条检查历史monitoring_service.rs:120-129(targets.add_check)GET /monitoring/{id}/checks 会多一行;轮询多久就多多少行
写审计日志monitoring_handler.rs:83-...ActivityAction::QueryCertificate(activity_log.rs:107,code 73 / 字符串 query_certificate),可在 GET /api/v1/activity-logs 查到

同一函数被每日调度复用(run_scheduled_checks,monitoring_service.rs:133), 所以手动「检查」与自动巡检走的是同一条落库路径。 集成方请勿拿它当高频只读探针:需要只读探测请自行在客户端做 TLS 握手。

响应体(MonitorCertInfoDto,dto.rs:660-668;字段即 PeerCertInfo 的 camelCase 投影, cert_fetch.rs:45):

{ "data": { "commonName": "example.com", "sans": ["example.com"],
            "issuer": "Let's Encrypt", "serialNumber": "03a1…",
            "notAfter": "2026-12-28T07:59:59+00:00", "keyType": "EC P-256",
            "fingerprintSha256": "e3b0c442…" } }

失败分支(都是 400,不是 502):DNS 解析不出 A/AAAA → 400「域名 … 无法解析 … 通配符(*.x.com)不是有效主机名」;连不上 / 没证书 → 400「无法连接 domain:port 或未获取到证书(请确认域名可公网访问且该端口提供 HTTPS/TLS 服务)」。

GET /api/v1/monitoring/{id}/checks?appId= → [{"checkedAt":"2026-09-30 09:00:00","certInformation":"…","expires":"2026-12-28 15:59:59"}](倒序)。

5.9 部署(Deployment):模板 / 基础模板 / 任务 / 发现

部署模板(用户自定义蓝图)

方法 路径鉴权后端前端
GET /api/v1/deployment-templatesJWT 或平台密钥deployment_template_handler.rs:31deployment.ts:73
POST /api/v1/deployment-templatesJWT 或平台密钥(建 platform 需 SuperAdmin)deployment_template_handler.rs:58deployment.ts:91
GET /api/v1/deployment-templates/{id}JWT 或平台密钥deployment_template_handler.rs:109deployment.ts:86
PUT /api/v1/deployment-templates/{id}本人 或 SuperAdmin 改 platformdeployment_template_handler.rs:121deployment.ts:98
DELETE /api/v1/deployment-templates/{id}同上deployment_template_handler.rs:170deployment.ts:106
POST /api/v1/deployment-templates/{id}/cloneJWT 或平台密钥deployment_template_handler.rs:192deployment.ts:111

GET Query(可选,未知 query 由 serde 静默忽略): scope(platform/user) / tag / appId。

已下线的 ?targetType= 传入不会报错,只是过滤不生效(有单测锁死, deployment_template_handler.rs:309-319)。

DeploymentTemplateDto(dto.rs:1236-1261):

{ "data": [ {
  "id": 11, "userId": 3, "scope": "user", "name": "Nginx 生产",
  "baseTemplateId": 391, "content": "#!/bin/sh\n…", "format": "pem-key",
  "formats": ["pem-key", "pem-all"], "prefillPaths": true, "pathMode": "autofill",
  "variablesJson": "[{\"name\":\"certPath\",…}]",
  "schemaVersion": 1, "version": 3, "tagsJson": "[\"web\"]", "description": null,
  "createdAt": "2026-09-01 10:00:00", "updatedAt": "2026-09-10 12:00:00"
} ] }

formats 出参是已解析的字符串数组(后端在 DTO 边界 parse,不是 JSON 串); prefillPaths 为布尔;format(单值落盘格式,对齐 deployment_tasks.format)与 pathMode(unset/autofill/specific/none)保持不变。 paramsJson / metaJson 两个大字段已随 0160 拆列下线。 PUT 仅更新提供的字段,未提供项保留既有值(formats 缺省 = 保留、空数组 = 清空; prefillPaths 缺省 = 保留)。更新 version += 1; scope 是安全属性,不可经更新改变。 模板层(含基础模板)只存变量声明与脚本正文,机密值从不落模板表,故模板 DTO 无掩码字段。

POST body(CreateDeploymentTemplateRequest,dto.rs:1177-1198): name(✅) / scope(❌,缺省 user) / baseTemplateId(❌) / content(❌) / format(❌) / pathMode(❌,缺省 unset) / formats(❌,string[]) / prefillPaths(❌,boolean) / variablesJson(❌) / description(❌) / tagsJson(❌) / appId(✅,缺失 400「appId 必填」)。返回 201。

paramsJson / metaJson 两个大字段已随 0160 下线,不再接受。 formats 入参为字符串数组:缺省 = 保留既有值,空数组 = 清空;prefillPaths 缺省 = 保留既有值。 注:基础模板(deployment-base-templates,只读库)的 supportedFormats(0163 由 formats 改名)/ easyMode / requiredVariables(0164 新增)/ prefillPaths / content 由后端维护(播种器 / Agent 派生),不接受入参——上述请求字段仅适用于用户自定义部署模板。

PUT body(UpdateDeploymentTemplateRequest)与 POST 同形但全部可选、无 appId: name / scope / baseTemplateId / content / format / pathMode / formats(❌,string[]) / prefillPaths(❌,boolean) / variablesJson / description / tagsJson。

POST /{id}/clone body {"name"?: string, "appId": int}(appId 必填)。返回 201。

平台基础模板(只读库)

方法 路径鉴权后端前端
GET /api/v1/deployment-base-templatesJWT 或平台密钥deployment_template_handler.rs:243deployment.ts:150
GET /api/v1/deployment-base-templates/{id}JWT 或平台密钥deployment_template_handler.rs:260deployment.ts:161
POST /api/v1/deployment-base-templates/{id}/deriveJWT 或平台密钥deployment_template_handler.rs:279deployment.ts:166

GET Query:tag(❌)(另有 scope/appId 字段存在但 list 未消费,见 TemplateListQuery)。 POST /{id}/derive body {"name"?: string, "appId": int}(appId 必填)→ 生成一条用户自定义模板。

部署任务

方法 路径鉴权后端前端
GET /api/v1/deployment-tasksJWT 或平台密钥deployment_handler.rs:25deployment.ts:27
POST /api/v1/deployment-tasksJWT 或平台密钥deployment_handler.rs:42deployment.ts:37
GET /api/v1/deployment-tasks/{id}JWT 或平台密钥deployment_handler.rs:122deployment.ts:54
PUT /api/v1/deployment-tasks/{id}JWT 或平台密钥deployment_handler.rs:135deployment.ts:62
DELETE /api/v1/deployment-tasks/{id}JWT 或平台密钥deployment_handler.rs:179deployment.ts:49
POST /api/v1/deployment-tasks/{id}/runJWT 或平台密钥deployment_handler.rs:101deployment.ts:44
PATCH /api/v1/deployment-tasks/{id}/pausedJWT 或平台密钥deployment_handler.rs:201—(无前端封装)

GET Query:appId(❌) / certificateId(❌),同时传取交集;都不传返回全部。

POST body(CreateDeploymentTaskRequest,dto.rs:1026-1047):

字段类型必填说明
certificateIdint✅
agentIdint✅执行主体 Agent(归属校验跨用户 → 404)
baseTemplateIdint✅*平台基础模板 id
templateIdint✅*用户自定义模板 id
appIdint✅缺失 400「appId 必填」
formatstring❌证书落盘格式
updateCmdstring❌Post-Deploy Script;不传→回退模板默认;传 ""→明确不执行
variablesobject❌用户变量明文(服务端 AES 加密落库)

✅* 二选一:都传 → 400「baseTemplateId 与 templateId 只能填一个」; 都不传 → 400「必须指定模板」。返回 201。

DeploymentTaskDto(dto.rs:1062-1100):

{ "data": { "id": 33, "isPaused": false, "agentId": 5, "certificate": "*.example.com",
  "destination": "iis:443", "triggerMode": "auto", "lastStatus": "SYNCED",
  "lastTime": "2026-09-30 09:00:00", "detail": null, "providerCode": "agent",
  "product": null, "certificateId": 101, "paramsJson": "{…}", "updateCmd": "systemctl reload nginx",
  "executionMode": "agent", "hostName": "web-01",   "agentPreset": "nginx",
  "deployedNotAfter": "2026-12-28 15:59:59", "format": "pem-key",
  "baseTemplateId": 391, "userTemplateId": null, "templateKind": 1 } }

lastTime / deployedNotAfter 未部署过时为字符串 "-"(不是 null)。 templateKind:1=base / 2=user。

PATCH /{id}/paused?appId= body snake_case {"is_paused": bool}(全站唯一例外)。 返回更新后的 DeploymentTaskDto。审计按实际值记「暂停」或「恢复」,不写死。

PUT /{id}?appId= body 全可选(certificateId / format / baseTemplateId / templateId / updateCmd / variables)。variables 是合并语义:非空覆盖 / 空串删除 / 缺失保留。

POST /{id}/run?appId= 无 body,手动触发一次部署,返回更新后的 DeploymentTaskDto。 DELETE /{id}?appId= 返回 {"data":{"success":true}}。

curl -s "http://127.0.0.1:8080/api/v1/deployment-tasks/33/paused?appId=3" \
  -X PATCH -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"is_paused": true}'

部署发现目标

方法 路径鉴权后端前端
GET /api/v1/deployments/discoveredJWT 或平台密钥deployment_handler.rs:248deployment.ts:19
GET /api/v1/inventoryJWT 或平台密钥agent_mgmt_handler.rs:85agent.ts:86

两者返回同构的 AgentInventoryDto[](dto.rs:1756-1800), GET /inventory 的 ?appId= 参数存在但 handler 未消费(Query(_q),按 user 维度全量返回):

{ "data": [ { "id": 88, "agentId": 5, "kind": "iis", "server": "iis",
  "installMode": "host", "externalId": "iis:IIS:\\Sites|Default Web Site",
  "name": "Default Web Site", "domains": "example.com,www.example.com",
  "port": 443, "lastSeenAt": "2026-09-30 09:00:00", "source": "local",
  "certificateDetails": {
    "software": { "config_path": "IIS:\\Sites|SslFlags=0", "install_mode": "host",
                  "container": null, "runtime": null, "listen_port": 443 },
    "certificate": { "certificate_path": "Default Web Site:443", "key_path": "…",
                     "chain_path": null, "format": null, "identifier": null,
                     "serial_number": "03a1…", "not_after": "2026-12-28T15:59:59Z",
                     "fingerprint_sha1": null } } } ] }

source:local(主机软件)/ cloud(云资源);云行判据 source === "cloud"。

字段口径(迁移 0166 起):

  • server:软件名;本地行与 kind 同值并存,云行空串。
  • installMode:host / container / unknown(库内 TINYINT 1/2/0,出参转可读串)。
  • domains:半角逗号拼接的多域名(原单值 domain 列已删,同值冗余)。
  • certificateDetails:证书详情 JSON(原 deploy 列)。本地行 {software, certificate}、 云行 {product, certificate};certificate 子树的 8 个键两形齐全(缺者为 null), 消费方只有一条读取路径。键名一律 snake_case。

云行的 product 子树示例(阿里云 SLB):

{ "product": { "platform": "aliyun", "product": "slb", "resource_id": "lb-bp13…",
               "region": "cn-hangzhou", "listener_port": 443, "listener_protocol": "https",
               "load_balancer_id": "lb-bp13…", "load_balancer_status": "active" },
  "certificate": { "certificate_path": null, "key_path": null, "chain_path": null,
                   "format": null, "identifier": "1303832378848590_…",
                   "serial_number": null, "not_after": null, "fingerprint_sha1": null } }

5.10 Agent / 主机管理(JWT 侧)

方法 路径鉴权后端前端
GET /api/v1/agentsJWT 或平台密钥agent_mgmt_handler.rs:21agent.ts:34
GET /api/v1/agents/{id}JWT 或平台密钥agent_mgmt_handler.rs:62agent.ts:39
DELETE /api/v1/agents/{id}JWT 或平台密钥agent_mgmt_handler.rs:46agent.ts:44
POST /api/v1/agents/{id}/lock-requestJWT 或平台密钥agent_mgmt_handler.rs:114—(无前端封装)
POST /api/v1/agents/{id}/rediscover-requestJWT 或平台密钥agent_mgmt_handler.rs:165agent.ts:62
GET /api/v1/agent-server-presets—已下线(迁移 0166 删除 agent_server_presets 表,端点与 PresetDto 一并移除)—

GET /api/v1/agents 响应 AgentDto[](dto.rs:1486-1515,主机名列名是 hostname):

{ "data": [ { "id": 5, "name": "web-01", "hostname": "web-01", "machineId": "…",
  "timezone": "Asia/Shanghai+8", "hostType": "VM", "osType": "linux", "ip": "10.0.0.5",
  "agentVersion": "1.2.3", "binaryPath": "/usr/local/bin/certkit-agent",
  "configPath": "/etc/certkit/agent.json", "installPath": "/etc/certkit",
  "deployments": 4, "status": "active", "lockRequested": false,
  "lastSeenAt": "2026-09-30 09:44:00", "createdAt": "2026-09-01 10:00:00",
  "updatedAt": "2026-09-30 09:44:00" } ] }

⚠️ POST /api/v1/agents(原「平台侧手动注册」)已于迁移 0122 删除,不再存在。 🔴 注意状态码:该 path 仍注册着 GET(列表),故对 POST 实测返回 405 Method Not Allowed(不是 404)。 判断端点是否存活请看方法 + 路径两者,别只看路径(router.rs 的 .route("/api/v1/agents", get(...)))。 它曾返回 AgentTokenResponse,宣称下发"主机级 Bearer 明文 token,一次性"——但该 token 无任何中间件接受(middleware/auth.rs 只认 JWT 与 Bearer os_…;middleware/agent_auth.rs 明写「无 Bearer 回退」),其落库占位列 agents.token_hash 亦全后端零读点,属"发了没人认的凭据"。 现主机注册唯一入口 = §5.11 的 POST /api/agent/v1/register-agent (certkit E1 匿名自注册,凭应用级注册密钥;服务端仅回 { agent_id },此后每请求由 AgentSig 验签)。

POST /api/v1/agents/{id}/lock-request body camelCase {"lockRequested": bool} (agent_mgmt_handler.rs:99-103)。响应回读库内值: {"agentId":5,"lockRequested":true}。未命中 → 404。

POST /api/v1/agents/{id}/rediscover-request 无 body。响应 {"agentId":5,"rediscoveryRequested":true}。

⚠️ 不立即生效:只置一个「待处理」标记,Agent 在下一次 poll-config(~30 秒轮询) 才会收到 force_autodiscover 并触发 inventory 上报。

GET /api/v1/agent-server-presets(已下线,迁移 0166):原返回 PresetDto[] (code / name / description / target / format / activateCommand / activateParams)。 语义去向:code → agent_inventory.server,target → agent_inventory.installMode(host/container), format → deployment_base_templates.supportedFormats;activateCommand/activateParams 为死数据(真正的 reload 走 deployment_tasks.update_cmd)。open-api 侧同一端点的 seq 52 亦已移除。

5.11 Agent 主机级端点族(AgentSig 验签)

Base:http://<host>/api/agent/v1/{agentId}/<action>。全部 POST。

方法 路径后端
POST /api/agent/v1/register-agentagent_handler.rs:55(公开,无鉴权不签名)
POST /api/agent/v1/{agent_id}/update-inventoryagent_handler.rs:484
POST /api/agent/v1/{agent_id}/poll-configagent_handler.rs:1145
POST /api/agent/v1/{agent_id}/report-erroragent_handler.rs:712
POST /api/agent/v1/{agent_id}/update-statusagent_handler.rs:1726
POST /api/agent/v1/{agent_id}/unregisteragent_handler.rs:1752
POST /api/agent/v1/{agent_id}/fetch-certificateagent_handler.rs:204
POST /api/agent/v1/{agent_id}/fetch-pfxagent_handler.rs:248
POST /api/agent/v1/{agent_id}/update-private-ca-statusagent_handler.rs:1793

鉴权:AgentSig ed25519

来源:middleware/agent_auth.rs:169-254 + infrastructure/deployment/agent_sig.rs:1-56。 无 Bearer 回退。必需请求头:

头说明
X-Agent-IdAgent 主机级身份(注册返回的 UUID)
X-Agent-TimestampUnix 秒;超出 ±300 秒窗口 → 401
X-Agent-Content-SHA256base64url(sha256(body)),空 body = sha256(nil)
AuthorizationAgentSig agentId="…", alg="ed25519", sig="…", signed="method path host ts body_sha256"
Host含端口(与客户端 canonicalHost 对齐)

签名串(5 行,\n 连接,行内 ": ",method 大写、host 小写):

method: POST
path: /api/agent/v1/<agentId>/poll-config
host: 127.0.0.1:8080
ts: 1760000000
body_sha256: <base64url 无填充>

状态码语义(403 只有两个来源,其余验签失败一律 401):

  • 403:① 库中无该 agent 行(已注销/已吊销);② 路径 {agentId} 与 X-Agent-Id 不一致;
  • 401:头缺失 / 时间戳非整数或超窗 / body 摘要不符 / alg 非 ed25519 / Authorization.agentId 与 X-Agent-Id 不符 / signed 非约定字面值 / ed25519 验签失败 / public_key 为空。

POST /api/agent/v1/register-agent(公开)

Body(RegisterAgentRequest,dto.rs:1553-1578,snake_case):

字段类型必填
public_keystring✅(base64url 无填充的 32 字节 ed25519 公钥)
registration_keystring✅(应用级注册密钥明文)
hostname / version / machine_id / operating_system / timezonestring❌
path_to_bin / path_to_config / service_name / host_typestring❌

成功 200 → {"agent_id":"<UUID>"}。 未命中 / 该应用未配置密钥 → 403(不是 401):

{ "error": "application_registration_key_required",
  "message": "该应用未配置 Agent 注册密钥,请在应用设置中生成后再注册" }

⚠️ 不幂等:与 certkit 一致,不按 machine_id 去重,每次成功调用都生成新 agent_id 与新行(agent_handler.rs:52-54)。Agent 侧应在本地已有 agent_id 时跳过注册。 归属应用由 sha256(registration_key) 反查,请求体里没有 application/app_id。

POST /api/agent/v1/{agent_id}/poll-config

Body(PollConfigRequest,agent_handler.rs:815-828,snake_case):

{
  "certificate_configurations": [
    { "config_id": "33", "last_configuration_update_date": "2026-09-11T10:00:00+00:00",
      "last_certificate_update_date": "2026-09-11T10:00:00+00:00",
      "latest_certificate_sha1": "A1B2…" }
  ],
  "private_cas": [ { "ca_id": "42", "root_sha256": "abab…", "auto_install": true, "status": "installed" } ],
  "is_locked": false,
  "force_full_sync": false
}

响应(PollConfigResponse,agent_handler.rs:900-934):

  • 快照无变化 → 204 No Content(空 body);
  • 有变化 → 200:
{
  "updated_certificate_configurations": [ {
    "config_id": "33", "certificate_id": "101",
    "last_configuration_update_date": "2026-09-11T10:00:00+00:00",
    "last_certificate_update_date": "2026-09-11T10:00:00+00:00",
    "latest_certificate_sha1": "A1B2…", "last_status": "SYNCED",
    "pem_destination": "certificates/101/cert.pem",
    "key_destination": "certificates/101/key.pem",
    "chain_destination": "", "owner_user": "", "owner_group": "", "file_permissions": "",
    "update_window": "", "update_cmd": "systemctl reload nginx", "name": "Nginx 生产",
    "all_in_one": false, "is_pfx": false, "config_type": "nginx",
    "update_variables": [ { "name": "certPath", "value": "certificates/101/cert.pem" } ]
  } ],
  "private_cas": [ { "ca_id": "42", "name": "Internal Root", "root_ca_pem": "-----BEGIN…",
                     "root_sha256": "abab…", "auto_install": true } ],
  "lock_requested": false,
  "keystore": { "host": "…", "ca_cert_pem": "-----BEGIN…" },
  "update_available": { "version": "1.3.0", "download_url": "https://…", "sha256": "…" },
  "force_autodiscover": false
}

private_cas / keystore / update_available 为空/未配置时键不出现(certkit omitempty 语义); force_autodiscover 为 false 时键不出现。 config_type == "iis" 时 pem_destination 会被合成为 {site}:{port}[:{hostHeader}]。

POST /api/agent/v1/{agent_id}/fetch-certificate / fetch-pfx

请求体(两者相同,FetchCertificateRequest,agent_handler.rs:179-185):

{ "config_id": "33", "certificate_id": "101" }
  • fetch-certificate → 200 JSON: {"certificate_pem":"-----BEGIN…","key_pem":"-----BEGIN…","certificate_sha1":"A1B2…"};
  • fetch-pfx → 200,body 是原始 PKCS#12 字节(application/octet-stream), 口令经响应头 X-Onessl-Pfx-Password 下发(双端契约名:服务端与 agent 必须同名, 任一侧改动都会导致口令取不到)。 口令每次请求随机生成、不落库、不写日志。

失败:certificate_id 非数字 → 400「certificate_id 非法」; config_id 空 → 400「config_id 不能为空」; 证书不存在/跨属主 → 404;未签发 → 400「证书尚未签发(缺少 cert_pem)」; PFX 合成失败 → 500 + {"code":500,"message":"fetch-pfx 合成失败…"}。

POST /api/agent/v1/{agent_id}/update-inventory

Body(InventoryUpdate,agent_handler.rs:328-444):

{ "items": [
  { "server": "nginx", "config_path": "/etc/nginx/conf.d/site.conf",
    "certificate_path": "/etc/ssl/site.pem", "key_path": "/etc/ssl/site.key",
    "chain_path": null, "domains": "example.com,www.example.com" },
  { "platform": "aliyun", "product": "cdn", "resource_id": "example.com",
    "account": "acct-1", "region": "cn-hangzhou", "domain": "example.com",
    "domains": "example.com", "listener_port": 443, "listener_protocol": "HTTPS",
    "cert_identifier": "cloud-cert-id", "cert_not_after": "2026-12-28T07:59:59Z",
    "cert_serial": "03a1…", "cdn": { "domain": "example.com" } }
] }

判别:含 platform 即云 item(必填 platform/product/resource_id),否则本地 item (必填 server/config_path/certificate_path)。云 item 的产品专属参数用 #[serde(flatten)] 平级展开,键名 = 产品 code(如 cdn)。响应 {"data":{"success":true}}。

POST /api/agent/v1/{agent_id}/update-status

Body(StatusBatchDto,agent_handler.rs:1720-1723):

{ "updates": [ { "config_id": "33", "status": "SYNCED",
                 "message": null, "last_status_date": "2026-09-30T09:00:00Z" } ] }

status 取值(agent 侧 synchronize.rs 定义):SYNCED / WAITING_FOR_WINDOW / ERROR_UPDATE_CMD / ERROR_GET_CERT / ERROR_WRITE_CERT / ERROR_GENERAL (另兼容历史小写 success / failed)。非法 config_id 会被跳过(不污染整批)。 响应 {"data":{"success":true}}。

POST /api/agent/v1/{agent_id}/report-error

Body(AgentErrorReport,agent_handler.rs:668-675): {"message":"…","config_id":"…","certificate_id":"…"}, 键名 snake_case(没有 domain 字段)。

唯一有限流的端点:每个 agent 在 60 秒窗口内最多放行 20 条,超限静默丢弃 (仍返回 200 {"data":{"success":true}},仅服务端记一条 warn)。 进程内内存计数,重启即清零(agent_handler.rs:677-706)。

POST /api/agent/v1/{agent_id}/unregister

Body 任意 JSON。硬删本 Agent 的主机级元数据。响应 {"data":{"success":true}}。

POST /api/agent/v1/{agent_id}/update-private-ca-status

Body(PrivateCaStatusBatchDto,agent_handler.rs:1783-1786):

{ "updates": [ { "ca_id": "42", "status": "installed", "message": null,
                 "last_status_date": "2026-09-30T09:00:00Z", "installed_by_agent": true } ] }

响应 {"data":{"success":true}}。

5.12 CT-log 资产发现

方法 路径鉴权后端前端
POST /api/v1/ct-discovery/runSuperAdminct_discovery_handler.rs:33—(无前端封装)
GET /api/v1/ct-discovery/certificatesSuperAdminct_discovery_handler.rs:55discovery.ts:20
POST /api/v1/ct-discovery/search-remoteSuperAdminct_discovery_handler.rs:78discovery.ts:42
GET /api/v1/ct-discovery/runsSuperAdminct_discovery_handler.rs:97—(无前端封装)

这四个端点用 matches!(auth.role, Role::SuperAdmin) 直接判,非超管 → 403 {"code":403,"message":"operation forbidden"}(不是中文「仅超级管理员…」)。

POST /ct-discovery/run 无 body,立即跑一轮增量发现:

{ "data": { "logsScanned": 3, "entriesProcessed": 12480, "matched": 7, "upserted": 5, "errors": [] } }

GET /ct-discovery/certificates Query:customerId(❌) / q(❌,域名关键字) / page(❌,1) / pageSize(❌,20)。返回 CtCertDto[](dto.rs:1903-1921)。

POST /ct-discovery/search-remote body {"domain":"example.com"} → {"domain":"example.com","fetched":12,"source":"ct-log-aggregator"}。 ⚠️ 同步阻塞约 5–60 秒(按序尝试 crt.sh → Cert Spotter)。

GET /ct-discovery/runs Query 同 CtCertListQuery(只有 page/pageSize 生效), 返回 CtRunDto[]:id / runId / trigger / status / scannedCount / accepted / upserted / error / startedAt / finishedAt。

后台调度默认每 10 分钟一轮(main.rs:682-697)。

5.13 通知(Notifications)

方法 路径鉴权后端前端
GET /api/v1/notificationsJWT 或平台密钥notification_handler.rs:9notification.ts:7
POST /api/v1/notifications/read-allJWT 或平台密钥notification_handler.rs:40notification.ts:30
POST /api/v1/notifications/{id}/readJWT 或平台密钥notification_handler.rs:30notification.ts:26

GET Query:page(❌,1) / pageSize(❌,20) / unreadOnly(bool,❌,默认 false)。 响应 data 是对象(不是数组):

{ "data": { "items": [ { "id": "77", "title": "证书续签成功 · example.com",
    "body": "证书已自动续签,新证书可下载。", "level": "info", "channel": "email",
    "isRead": false, "createdAt": "2026-09-30 09:00:00" } ],
  "unreadCount": 3 },
  "meta": { "page": 1, "pageSize": 20, "total": 42 } }

其余两条返回 {"data":{"success":true}},跨用户访问 → 404。

⚠️ 已下线:POST /api/v1/notifications/test-connection 已于 2026-09-27 随 「通知渠道连通性测试」功能一并删除(路由 / handler / 内核 test_channel / 掩码函数 / DTO 全量移除,见 router.rs:230-233)。通知配置的唯一真相是 GET/PUT /api/v1/settings。

5.14 财务与计费(Finance / Billing)

方法 路径鉴权后端前端
GET /api/v1/finance/transactionsJWT 或平台密钥finance_handler.rs:9finance.ts:4
GET /api/v1/finance/summaryJWT 或平台密钥finance_handler.rs:27finance.ts:18
POST /api/v1/billing/quoteJWT 或平台密钥billing_handler.rs:28—(无前端封装)
GET /api/v1/billing/pricesSuperAdminbilling_handler.rs:41—
POST /api/v1/billing/grantSuperAdminbilling_handler.rs:54—
GET /api/v1/billing/eventsSuperAdminbilling_handler.rs:80—

所有金额以金币为单位。GET /finance/transactions Query: page(❌,1) / pageSize(❌,10) / keyword(❌,按单号)。

{ "data": [ { "id": "9001", "time": "2026-09-29 15:58:01", "orderId": "cert-101-1",
  "type": "consume", "amountCoins": -100, "status": "Success",
  "bizKind": "cert.create" } ],
  "meta": { "page": 1, "pageSize": 10, "total": 21 } }

bizKind:cert.create / cert.reissue / billing.refund / billing.grant / signup.grant。

GET /finance/summary:

{ "data": { "balanceCoins": 8800, "monthSpendCoins": 300, "lastMonthSpendCoins": 500,
            "monthOverMonthPct": -40, "invoiceableCount": 12, "exchangeRate": 100 } }

exchangeRate(1 元 = N 金币)随概览下发,客户端不要写死 100。 monthOverMonthPct 上月无支出时为 null。

POST /billing/quote body {"itemCode": string, "context": {…}}(context 取价上下文维度, 如 {"cert_type":"Wildcard"})。只读,不产生账本写入:

{ "data": { "itemCode": "cert.create", "resolved": "Priced", "priceCoins": 100,
            "unitLabel": "张", "balanceCoins": 8800, "sufficient": true,
            "shortfallCoins": 0, "exchangeRate": 100 } }

resolved:Priced / Free / Unpriced。

POST /billing/grant body {"userId": int, "amountCoins": int, "note"?: string} → {"txId":"9002","balanceCoins":8900}。 GET /billing/events?limit=(默认 100,上限 500)→ 计费异常事件(未定价拒绝 / 同优先级冲突)。

5.15 设置(Settings)—— 🔴 端点已移除

GET /api/v1/settings 与 PUT /api/v1/settings 已整体删除(2026-10-06 用户裁定 / 迁移 0135_drop_settings_add_payload.sql:DROP TABLE settings)。

原因:该表最终只剩 4 个键,全部零消费—— app.public_url(2026-09-25 已改用环境变量 PUBLIC_URL,后端无读取点)、 prefs.language / prefs.timezone / security.twoFactor(只存在于 DEFAULT_SETTINGS 的 默认值与测试断言中,无任何真实读写路径)。前端 services/settings.ts 的 getSettings / updateSettings 亦无任何页面调用 ⇒ 一并删除(死代码)。

去向:

原位置现位置
通知渠道/凭据/收件人§5.15b /api/v1/notification-config/endpoints
事件订阅§5.15b /api/v1/notification-config/subscriptions
投递去重标记(内部键)event_delivery_log 表(无接口,直接查库)
证书到期提前天数🔴 system_config 表键 event.cert_expiry.advance_days(无 HTTP 端点,见 §5.15b)
站点主域名🔴 system_config 表键 site.public_url(无 HTTP 端点)

🔴 SMTP 不在任何接口配:走服务端环境变量 SMTP_HOST / SMTP_PORT / SMTP_USERNAME / SMTP_PASSWORD / SMTP_FROM / SMTP_TLS,改完须重启后端。 主体级 SMTP 参数不再被任何代码读取(email.rs::global 刻意不接收 ChannelConfig)。 邮件渠道从端点读的只剩收件人名单(parameters.receiver 数组)。

5.15b 通知配置(Notification Config)

🔴 2026-10-06 新增(迁移 0134_notify_domain_rebuild.sql):通知的渠道端点 / 事件订阅 / 提前天数 / 投递记录改由 4 张表承载,全部主体级(不再是 settings 的 per-user KV 键, 也不再需要 customer_settings 表 —— 该表已被 DROP TABLE)。

方法 路径权限后端 handler前端 service
GET /api/v1/notification-config/event-types主体管理员list_event_typeslistNotifyEventTypes
GET /api/v1/notification-config/channels主体管理员list_channelslistNotifyChannels
GET /api/v1/notification-config/endpoints主体管理员list_endpointslistNotifyEndpoints
GET /api/v1/notification-config/endpoints/{channelCode}主体管理员get_endpointgetNotifyEndpoint
PUT /api/v1/notification-config/endpoints/{channelCode}主体管理员update_endpointupdateNotifyEndpoint
GET /api/v1/notification-config/subscriptions主体管理员list_subscriptionslistNotifySubscriptions
PUT /api/v1/notification-config/subscriptions主体管理员update_subscriptionsupdateNotifySubscriptions
GET /api/v1/notification-config/deliveries?page=&pageSize=主体管理员list_deliverieslistNotifyDeliveries

🔴 2026-10-06 起本组 8 条端点全部要求主体管理员(users.role = 1;迁移 0137 后 users.role 本身即「主体内角色」,故 SuperAdmin 在此语义 = 本主体管理员)。 非管理员一律 403 {"code":403,"message":"仅超级管理员可执行此操作"} (走统一守卫 AuthUser::require_super_admin(),见 §2.3)。

改动前这 8 条无任何角色校验(仅过全局 require_auth)⇒ 普通成员可 GET /endpoints 读回已解密的明文凭据,并可 PUT 改写主体级通知配置与订阅矩阵。 同批收归管理员的还有 GET /finance/transactions、GET /finance/summary、 GET /activity-logs,以及私有 CA 的 写类 5 条(POST /private-ca-authorities、 DELETE /private-ca-authorities/{id}、/{id}/download、/{id}/csr、/{id}/certificate)。 ⚠️ 有意不收(证书签发流程依赖,成员保持可用):GET /ca-providers、 GET /ca-providers/{code}、GET /private-ca-authorities、GET /private-ca-authorities/{id}。

事件字典(表 event_type,5 行种子):

🔴 advanceDays 不在 event_type 表里(迁移 0135 已把该列移入 system_config)。 下方 advanceDays 由后端从 system_config['event.cert_expiry.advance_days'] 读取后 附加到 cert_expiry 行上(仅该事件有值;其余恒 null),只读。

{ "data": [
  { "id": "1", "code": "cert_expiry", "name": "证书即将到期", "advanceDays": 15 },
  { "id": "2", "code": "renew_success", "name": "续期成功", "advanceDays": null },
  { "id": "3", "code": "renew_failure", "name": "续期失败", "advanceDays": null },
  { "id": "4", "code": "deploy_success", "name": "部署成功", "advanceDays": null },
  { "id": "5", "code": "deploy_failure", "name": "部署失败", "advanceDays": null }
] }

🔴 提前天数是系统级参数,无 HTTP 写入口:直接改 system_config 表的 event.cert_expiry.advance_days(字符串,如 '30')。读取链路 = expiry_scan_service::parse_advance_days(SystemConfigRepository::get(...)): 键缺失 / 值非数字 / 值 ≤ 0 ⇒ 回落 15;值 > 90 ⇒ clamp 到 90。 理由:漏发到期告警违背「失败必须可见」,宁可用保守默认值也不能让配置问题静默关掉扫描。

渠道字典(表 notification_channel,4 行种子)—— 🔴 不含 sms(旧配置里的无实现空壳键):

{ "data": [
  { "id": "11", "code": "email", "name": "邮件" },
  { "id": "12", "code": "feishu", "name": "飞书" },
  { "id": "13", "code": "dingtalk", "name": "钉钉" },
  { "id": "14", "code": "webhook", "name": "Webhook" }
] }

主体端点(表 customer_notification_endpoint,UNIQUE(customer_id, channel_id))—— parameters 形状按渠道不同:

渠道parameters JSON凭据字段
email{"receiver": ["a@b.c", …]}无(收件人不是凭据)
feishu{"webhook": {"url": "", "token": ""}}webhook.token
dingtalk{"webhook": {"url": "", "token": ""}}webhook.token
webhook{"url": "", "token": ""}token

🔴 凭据加密由后端按渠道码决定(domain::notify::credential_field_path):前端 PUT 传明文 token 即可,后端加密成 enc: + hex 落库;GET 返回时已解密为明文(与旧 GET /settings 行为 一致,设置页需要回显编辑)。已带 enc: 前缀的值原样透传(幂等,重复提交不会二次加密)。

主体订阅(表 customer_event_subscription,UNIQUE(customer_id, event_type_id, channel_id)): 5 事件 × 4 渠道 = 20 条,开户播种时全部 enabled: true(旧默认亦全开)。

{ "data": [
  { "id": "1", "eventTypeId": "1", "eventCode": "cert_expiry",
    "channelId": "14", "channelCode": "webhook", "enabled": true }
] }

PUT /subscriptions body:{"items":[{"eventCode":"…","channelCode":"…","enabled":true}]}。 先校验全部事件码/渠道码再逐条 upsert(避免半截状态)。

投递记录(表 event_delivery_log):成功 / 失败 / 跳过全部落库 (旧实现只有失败与跳过落 notifications,成功只进日志 ⇒ 前端「最近投递」看不到成功)。

🔴 payload 是事件 BODY 数据结构(迁移 0135 新增),形状按事件不同:

事件payload
cert_expiry{"certId":18,"days":15,"expiresAt":"2026-12-21T05:18:47+00:00"}
renew_success / renew_failure{"certId":18}
deploy_success / deploy_failure{"taskId":9,"agentId":4,"status":"SYNCED"}
其它 / 上下文缺失{}(缺字段直接省略,不写 null 占位)

⚠️ deploy-* 没有 appId —— deployment_tasks 表无 app_id 列(任务直挂 Agent、 归属 customer_id),故不编造该字段。 payload 不参与去重(去重判据恒为 customer+event+channel+sent_at)。

{ "data": [
  { "id": "9", "eventCode": "deploy_success", "channelCode": "webhook",
    "status": "success", "errorMessage": null,
    "payload": { "taskId": 9, "agentId": 4, "status": "SYNCED" },
    "sentAt": "2026-10-06 11:30:00" }
], "meta": { "total": 42 } }

status ∈ success / failed / skipped;后两者必带 errorMessage。 sentAt 是北京时间展示串,直接展示、勿再转换。

curl -s -X PUT http://127.0.0.1:8080/api/v1/notification-config/endpoints/webhook \
  -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
  -d '{"enabled":true,"parameters":{"url":"https://example.com/hook","token":"s3cr3t"}}'

5.16 仪表盘统计

方法 路径鉴权后端前端
GET /api/v1/dashboard/summaryJWT 或平台密钥dashboard_handler.rs:13certificate.ts:36

Query appId 必填(DashboardSummaryQuery.app_id 是非 Option,缺参由 axum Query 解构自动返 400)。SQL COUNT 条件聚合计四卡:

{ "data": { "totalCertificates": 137, "active": 120, "expiring": 12, "expired": 5 } }

临近窗口边界复用 EXPIRING_THRESHOLD_DAYS = 30(domain/certificate.rs:7)。

5.17 活动日志(审计)

方法 路径鉴权后端前端
GET /api/v1/activity-logsJWT 或平台密钥activity_log_handler.rs:25activityLogs.ts:22

Query:page(❌,1) / pageSize(❌,20) / keyword(❌) / action(❌,支持逗号分隔多值) / result(❌) / from(❌) / to(❌)。

  • action 未知 code 或含空项一律 400(严格,不静默忽略);重复项去重并保持首次顺序。
  • result:success / failed / unknown。
  • 归属过滤:SuperAdmin 看全部,普通用户只看自己(按 customer_id)。

响应 ActivityLogDto(dto.rs:2242-2266,存数字、出可读 code 串):

{ "data": [ { "id": 901, "customerId": 3, "actorUserId": 3, "actorName": "张三",
  "actorRole": "SuperAdmin", "action": "delete_cert", "targetType": "certificate",
  "targetId": 101, "targetName": "*.example.com", "result": "success",
  "errorMessage": "", "ip": "203.0.113.7", "userAgent": "curl/8.5.0",
  "createdAt": "2026-09-30 09:45:12" } ],
  "meta": { "page": 1, "pageSize": 20, "total": 312 } }

actorRole 在操作者未知时为 "unknown"(不谎称 User)。 ip 取自 x-forwarded-for 首段(无则空串)。

action 全量 code(domain/activity_log.rs:223-279,逐字摘录):

unknown, login, login_failed, logout, accept_invite, invite_user, resend_invite,
revoke_invite, update_user, create_cert, upload_cert, verify_cert, reissue_cert,
delete_cert, create_deployment, update_deployment, run_deployment, pause_deployment,
resume_deployment, delete_deployment, revoke_agent_token, create_template,
update_template, clone_template, delete_template, derive_template, run_ct_discovery,
register_agent, delete_agent, set_agent_lock, enable_monitor, update_monitor,
disable_monitor, query_certificate, update_ca_provider, create_ca_account,
verify_ca_account, delete_ca_account, create_api_key, delete_api_key,
create_private_ca, upload_private_ca_cert, delete_private_ca, download_private_ca,
download_private_ca_csr, create_app, update_app, update_app_members, delete_app,
generate_app_reg_key, revoke_app_reg_key, grant_coins, update_settings

targetType 全量 code(domain/activity_log.rs:412-428):

none, user, certificate, deployment_task, deployment_template, agent, monitor,
ca_provider, ca_account, api_key, private_ca, application, billing, setting, ct_discovery

注:generate_app_reg_key / revoke_app_reg_key / revoke_agent_token 三个动作 已无对应端点(注册密钥重置与 Agent token 吊销均已移除),保留只为存量日志行双向可读 (app_handler.rs:192-193、router.rs:387-389)。

curl -s "http://127.0.0.1:8080/api/v1/activity-logs?action=delete_cert,create_cert&result=success&from=2026-09-01&to=2026-09-30" \
  -H "Authorization: Bearer $TOKEN"

5.18 公开 ACME 挑战响应端点

方法 路径鉴权后端
GET /.well-known/acme-challenge/{token}公开(CA 无 token)certificate_handler.rs:266

响应 200 text/plain,body 就是该 token 对应的 key authorization。 未命中 / 探针已过期 → 404。不属于 /api/v1,反向代理必须原样透传该路径给后端。


6. 典型调用流程

6.1 申请一张 CNAME(acme-dns 免 DNS 授权)证书并部署

1) POST /api/v1/auth/login                         -> accessToken
2) GET  /api/v1/applications                       -> 取 appId(如 3)
3) POST /api/v1/certificates/cname-reserve         -> { fulldomain, username, password }
      ↓ 用户去 DNS 控制台加 CNAME:
        _acme-challenge.<基域名>  CNAME  <fulldomain>
4) POST /api/v1/certificates/cname-check
      body { domains:[...], fulldomain }           -> { ok:true, ... }  (可选预检)
5) POST /api/v1/certificates
      body { provider, certType, domains, verificationMethod:"cname",
             appId, caCode, cnameFulldomain, cnameUsername, cnamePassword }
                                                   -> 201,status="Pending"
6) (无需手动 verify)后端 pending_cname_verify_scheduler 每 120s 扫描,
   委派生效即自动完成签发。轮询:
   GET /api/v1/certificates/{id}?appId=3           直到 status=="Active"
7) GET /api/v1/certificates/{id}/bundle?appId=3    -> ZIP(fullchain.pem + privkey.pem)
8) 部署:POST /api/v1/deployment-tasks             -> 201
   Agent 下一次 poll-config(~30s)拉走配置并自行 fetch-certificate / fetch-pfx
9) GET /api/v1/deployment-tasks?appId=3&certificateId={id}  -> 看 lastStatus

6.2 用平台 API 密钥做无人值守集成

1) 管理员登录 Web,设置 › API 密钥 › 新建  -> 复制唯一一次明文 os_xxx
2) 所有请求带 Authorization: Bearer os_xxx
3) 注意:密钥继承 owner 的【当前】角色 —— 管理员被降级后该密钥权限立即收敛
4) 吊销:DELETE /api/v1/api-keys/{id}

6.3 私有 CA(BYO 模式)接入

1) POST /api/v1/private-ca-authorities   { name, hierarchy:"bring_your_own_root", keyAlgo:"EC_P384" }
      -> 201, status="pending_cert", csrPem 非空(SuperAdmin 专属)
2) GET  /api/v1/private-ca-authorities/{id}/csr     -> PKCS#10 PEM
3) 用你自己的根 CA 签发该 CSR,得到 Issuing CA 证书
4) POST /api/v1/private-ca-authorities/{id}/certificate
      { issuingCertPem, rootCertPem }              -> status="active",信任锚同步下发
5) Agent 下次 poll-config 的 private_cas 段会带上该根证书
6) 用该 CA 签叶子:POST /api/v1/certificates 带 privateCaId(与 caCode 互斥),同步签发

7. 幂等性与副作用

天然幂等(重复调用不产生新副作用)

端点说明
所有 GET只读(例外见下)
PUT /api/v1/settings同键同值重复写,结果不变
PUT /api/v1/users/{id}同值重复写
PUT /api/v1/monitoring/{id}同值重复写
PUT /api/v1/applications/{id}/members全量覆盖,同集合重复写结果不变
PATCH /api/v1/deployment-tasks/{id}/paused同值重复写
DELETE /api/v1/api-keys/{id} / acme-accounts/{id} 等第二次 → 404(无害)
POST /api/v1/notifications/read-all重复调用无副作用
POST /api/v1/certificates/cname-check / http-check只读校验,不写库不签发
POST /api/v1/billing/quote只读,不产生账本写入

有副作用(重复调用会累积)

端点副作用说明
POST /api/v1/certificates/cname-reserve每次都注册一个新 acme-dns 子域创建证书时回传 cnameFulldomain/cnameUsername/cnamePassword 复用
POST /api/v1/certificates新建证书行 + ACME 下单 + 计费预扣重复调用产生多张证书
POST /api/v1/certificates/{id}/verify回填 TXT + finalize + 转正/退费会真实消耗 CA 的失败配额
POST /api/v1/certificates/{id}/reissue重新下单 + 计费预扣
POST /api/v1/api-keys新建密钥,明文只出一次
POST /api/agent/v1/register-agent每次都生成新 agent_id / 新行register-agent 不按 machine_id 去重(旧的 JWT 侧 POST /api/v1/agents 已随 0122 删除)
POST /api/v1/acme-accounts新建账号 + 真出网校验 EAB
POST /api/v1/billing/grant写一条新流水 + 增加余额无幂等键,重试会重复发放
POST /api/v1/deployment-tasks/{id}/run触发一次部署
POST /api/v1/deployment-templates/{id}/clone新建副本,version=1
POST /api/v1/ct-discovery/run跑一轮发现(有后台调度也在跑)
POST /api/v1/ct-discovery/search-remote同步抓取并 upsert 台账(5–60 秒)
POST /api/v1/users/invite / invite/resendresend 先作废旧令牌再签发新的旧邮件链接立即失效
POST /api/v1/monitoring新建监控目标
POST /api/v1/monitoring/{id}/query-certificate有写副作用:更新目标快照(last_checked_at / last_cert_not_after / last_cert_issuer / last_cert_serial / updated_at)+ 追加一条检查历史 + 写审计日志 query_certificate不要当只读探针轮询;与每日调度共用同一 check_one(monitoring_service.rs:66-131)
GET /api/v1/applications/{id}/agent-registration-key可能触发一次幂等补齐(存量应用首次读取时生成密钥)已有密钥只读不改

没有通用幂等键机制:源码里没有 Idempotency-Key 头、没有 client_token 之类的 去重字段。需要幂等请在自己的调用侧用业务唯一键(如域名)先查再写。


8. 限流与配额

当前版本没有实现通用的 API 限流。 全仓检索(apps/onessl-app-api/src)只找到一处限流:

  • POST /api/agent/v1/{agent_id}/report-error:每 agent 60 秒窗口最多 20 条, 超限静默丢弃(仍返回 200),进程内内存计数,重启清零,不做跨实例聚合 (agent_handler.rs:677-706)。

没有 QPS 限流、没有并发限制、没有配额头(X-RateLimit-* 一律不存在)、 没有 429 响应(AppError 枚举里没有 TooManyRequests)。 请自行在客户端或网关侧做节流。

间接的出网节流(不是 API 限流,但会影响你的重试策略):

  • pending_cname_verify_scheduler:单张证书两次签发尝试间隔 1800 秒 (main.rs:549),防烧 CA 失败配额(Let's Encrypt 限 5 次失败/主机名/小时);
  • API 密钥 last_used_at 回写按 60 秒窗口节流(middleware/auth.rs:121)。

9. 变更与版本策略

当前没有 API 版本化机制。 如实说明:

  • 路径前缀 /api/v1 是硬编码字面量,不是版本协商结果;不存在 /api/v2, 也不存在 Accept-Version / API-Version 头解析。
  • 没有 deprecation 头(Sunset / Deprecation),没有变更日志接口。
  • 破坏性变更历史上是直接删除端点,源码注释里留下了若干已下线记录:
已下线时间记录位置
POST /api/v1/notifications/test-connection2026-09-27router.rs:230-233
GET/PUT /api/v1/system-settings2026-09-29router.rs:239-241
/api/v1/deployment-destinations CRUD2026-09-03router.rs:248-249
/api/v1/deployment-templates/{id}/destinations2026-09-03router.rs:307-308
GET /api/v1/agent/{manifest,certificate}、POST /agent/reportC1/T06router.rs:387-389
GET /api/v1/agent/selfupdateC1/T18router.rs:440-442
GET /api/v1/agent/runtimeC1/T09router.rs:443-446
POST /api/v1/deployment-tasks/{id}/agent-tokens、POST /api/v1/deployment-tasks/{id}/agent-tokens/{tok_id}/revoke迁移 0121agent_handler.rs:10-12 注释
POST /api/v1/agents(手动注册,返回"一次性主机 token")迁移 0122agent_mgmt_handler.rs:1-4 注释
POST/DELETE /api/v1/applications/{id}/agent-registration-key2026-09-29router.rs:370-379

对接建议:不要假设端点长期稳定;升级后端前请对照 backend/apps/onessl-app-api/src/interface/router.rs 复核一次端点清单, 或直接跑一次本仓库的冒烟脚本(backend/smoke_modules.sh、backend/selftest.sh)。

待确认:是否存在对外发布的 changelog 通道 —— 本仓库内未发现任何机器可读的 API 变更记录文件。


10. SDK / 集成建议

10.1 TypeScript(浏览器 / Node 18+)fetch 封装

// onessl-client.ts —— 与前端 src/services/http.ts 同构,去掉了 401 跳登录逻辑
export class ApiError extends Error {
  readonly status: number;
  constructor(status: number, message: string) {
    super(message);
    this.name = 'ApiError';
    this.status = status;
  }
}

export interface Envelope<T> {
  data: T;
  meta?: { page: number; pageSize: number; total: number };
}

export class OneSslClient {
  constructor(
    private readonly baseUrl: string,   // 例 'http://127.0.0.1:8080/api/v1'
    private readonly token: string,     // JWT 或 'os_...' 平台密钥,中间件按前缀分派
  ) {}

  private async send<T>(
    method: string,
    path: string,
    body?: unknown,
  ): Promise<Envelope<T>> {
    const headers: Record<string, string> = {
      Authorization: `Bearer ${this.token}`,
    };
    let payload: BodyInit | undefined;
    if (body !== undefined) {
      headers['Content-Type'] = 'application/json';
      payload = JSON.stringify(body);
    }
    const res = await fetch(`${this.baseUrl}${path}`, { method, headers, body: payload });
    if (!res.ok) {
      // 401 有两态:中间件直返(空 body)与业务 JSON 包络,必须容错
      let message = `请求失败 (${res.status})`;
      try {
        const err = (await res.json()) as { message?: string };
        if (typeof err?.message === 'string') message = err.message;
      } catch {
        /* 空 body 或非法 JSON:沿用默认文案 */
      }
      throw new ApiError(res.status, message);
    }
    return (await res.json()) as Envelope<T>;
  }

  /** 应用列表(几乎所有资源都要先拿 appId)。 */
  listApplications() {
    return this.send<Array<{ id: number; name: string; code: string }>>(
      'GET', '/applications',
    );
  }

  /** 证书列表:appId 必填,缺失 400「appId 必填」。 */
  listCertificates(appId: number, page = 1, pageSize = 20, keyword?: string) {
    const qs = new URLSearchParams({
      appId: String(appId),
      page: String(page),
      pageSize: String(pageSize),
    });
    if (keyword) qs.set('keyword', keyword);
    return this.send<Array<Record<string, unknown>>>('GET', `/certificates?${qs}`);
  }

  /** 创建证书(verificationMethod 当前只允许 'cname')。 */
  createCertificate(input: {
    provider: string;
    certType: 'Single' | 'Wildcard' | 'Multi';
    domains: string[];
    appId: number;
    verificationMethod?: 'cname';
    caCode?: string;
    acmeAccountId?: number | null;
    privateCaId?: number;
    keyAlgo?: string;
    description?: string;
  }) {
    return this.send<Record<string, unknown>>('POST', '/certificates', {
      verificationMethod: 'cname',
      ...input,
    });
  }

  /** 轮询直到证书离开 Pending(后端有 120s 自动补验调度,别自己猛点 verify)。 */
  async waitForActive(
    certId: number,
    appId: number,
    opts: { timeoutMs?: number; intervalMs?: number } = {},
  ): Promise<string> {
    const timeoutMs = opts.timeoutMs ?? 30 * 60 * 1000;
    const intervalMs = opts.intervalMs ?? 30 * 1000;
    const deadline = Date.now() + timeoutMs;
    while (Date.now() < deadline) {
      const { data } = await this.send<{ id: number; status: string }>(
        'GET', `/certificates/${certId}?appId=${appId}`,
      );
      if (data.status !== 'Pending') return data.status;
      await new Promise((r) => setTimeout(r, intervalMs));
    }
    throw new Error(`证书 ${certId} 在 ${timeoutMs}ms 内仍未离开 Pending`);
  }

  /** 下载证书 ZIP(非 JSON 响应,走原始 fetch)。 */
  async downloadBundle(certId: number, appId: number): Promise<Blob> {
    const res = await fetch(
      `${this.baseUrl}/certificates/${certId}/bundle?appId=${appId}`,
      { headers: { Authorization: `Bearer ${this.token}` } },
    );
    if (!res.ok) throw new ApiError(res.status, `下载失败 (${res.status})`);
    return res.blob();
  }
}

用法:

const cli = new OneSslClient('http://127.0.0.1:8080/api/v1', process.env.ONESSL_TOKEN!);
const apps = await cli.listApplications();
const appId = apps.data[0].id;
const certs = await cli.listCertificates(appId, 1, 20);
console.log(certs.meta?.total);

10.2 Node 侧:用 zip 包配置 Nginx

#!/usr/bin/env bash
set -euo pipefail

BASE="http://127.0.0.1:8080/api/v1"
TOKEN="${ONESSL_TOKEN:?需要 Bearer 凭据(JWT 或 os_ 平台密钥)}"
APP_ID=3
CERT_ID=101
OUT=/etc/ssl/onessl

mkdir -p "$OUT"
curl -fsS -o "$OUT/bundle.zip" \
  "$BASE/certificates/$CERT_ID/bundle?appId=$APP_ID" \
  -H "Authorization: Bearer $TOKEN"

unzip -o "$OUT/bundle.zip" -d "$OUT"
# 包内结构:{domain}/fullchain.pem + {domain}/privkey.pem('*' 已被替换为 'star')
chmod 600 "$OUT"/*/privkey.pem
nginx -t && systemctl reload nginx

10.3 OpenSSL 侧:校验证书与私钥匹配

# 1) 从平台下载的包里取出两段 PEM
CERT=$(find /etc/ssl/onessl -name fullchain.pem | head -1)
KEY=$(find /etc/ssl/onessl -name privkey.pem | head -1)

# 2) 证书公钥 mod hash
openssl x509 -noout -modulus -in "$CERT" | openssl sha256
# 3) 私钥 mod hash(两者必须一致)
openssl rsa  -noout -modulus -in "$KEY"  | openssl sha256   # RSA
# EC 私钥用:
#   openssl pkey -in "$KEY" -pubout | openssl sha256
#   openssl x509 -in "$CERT" -noout -pubkey | openssl sha256

# 4) 与平台 thumbprintSha1 对账(Windows 指纹口径 = 叶子证书 DER 的 SHA1,大写)
openssl x509 -in "$CERT" -outform DER 2>/dev/null | openssl sha1 | tr 'a-f' 'A-F'
# 前端 dto.rs:355-358 的 thumbprintSha1 与 Agent 端 latest_certificate_sha1 同算法同值

# 5) 看剩余有效期
openssl x509 -in "$CERT" -noout -dates -subject -issuer

10.4 Agent 侧签名(示意,Node)

import { createHash, sign as edSign } from 'node:crypto';

// 签名串必须逐字对齐 agent_sig.rs:41-56(\n 连接 5 行,行内 ": ")
function buildSigningString(
  method: string, pathQuery: string, host: string, ts: number, bodyHash: string,
): string {
  return [
    `method: ${method.toUpperCase()}`,
    `path: ${pathQuery}`,
    `host: ${host.toLowerCase()}`,
    `ts: ${ts}`,
    `body_sha256: ${bodyHash}`,
  ].join('\n');
}

// bodyHash = base64url 无填充(sha256(body));空 body 等价于 sha256("") 
const body = JSON.stringify({ certificate_configurations: [] });
const bodyHash = createHash('sha256').update(body, 'utf8').digest('base64url');
const ts = Math.floor(Date.now() / 1000);
const host = '127.0.0.1:8080';                 // 含端口
const pathQuery = `/api/agent/v1/${agentId}/poll-config`;
const signing = buildSigningString('POST', pathQuery, host, ts, bodyHash);
const sig = edSign(null, Buffer.from(signing, 'utf8'), privateKeyPem).toString('base64url');

const res = await fetch(`http://127.0.0.1:8080${pathQuery}`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-Agent-Id': agentId,
    'X-Agent-Timestamp': String(ts),           // 超出 ±300s → 401
    'X-Agent-Content-SHA256': bodyHash,
    'X-Agent-Version': '1.2.3',                // 可选;空串会被当作「无此头」
    // signed 字段是固定字面量(只放键名,不放值)
    Authorization: `AgentSig agentId="${agentId}", alg="ed25519", sig="${sig}", signed="method path host ts body_sha256"`,
  },
  body,
});
if (res.status === 204) return null;           // 快照无变化
if (res.status === 403) throw new Error('agent 未授权/已注销,或路径 agentId 与头不一致');
if (res.status === 401) throw new Error('验签失败(头缺失/超窗/摘要不符/签名不过)');
return res.json();

11. 「文档 ↔ 实现」不一致与坑位清单(如实记录)

读源码过程中发现的、集成时容易踩的问题,全部有源码出处:

  1. ?status=Expiring 等价于 ?status=Pending。过滤走 CertStatus::from_str, 该函数只认 Active/Expired,其余兜底 Pending (infrastructure/db/repositories.rs:437 + domain/certificate.rs:50-57)。 列表实际会输出 Expiring,但按它过滤不到。
  2. 401 有两种响应体。中间件直返时 body 为空;业务层才有 JSON 包络 (middleware/auth.rs:27/43/47/51/112/118 vs libs/core/src/error.rs:60)。
  3. {id} 端点缺 appId 返回的是 axum 默认英文 400,不是中文「appId 必填」 (只有列表端点做了手写校验才给中文)。
  4. 时间格式两套并存(北京时间展示串 vs RFC3339),逐 DTO 不同,见 §2.6。
  5. register 无密码强度校验,accept-invite 有(≥8 位),源码自认是技术债 (auth_handler.rs:214-218)。
  6. POST /certificates/cname-reserve 每次都注册新 acme-dns 子域,重复调用会累积。
  7. register-agent 不幂等(不按 machine_id 去重),每次成功都建新 agent (agent_handler.rs:52-54)。
  8. GET /inventory 的 ?appId= 参数存在但 handler 未消费(Query(_q)), 实际按 user 维度全量返回(agent_mgmt_handler.rs:85-88)。
  9. PUT /monitoring/{id} 的 appId 在 body 里,不在 query(与同族其他端点不同) (monitoring_handler.rs:48-55)。
  10. monitoring 的 latency(:603) / securityGrade(:605) / lastCheck(:607) 恒 null (真实探测未实现,dto.rs:595-614 内注释写明「方案 B」+ domain/monitor.rs:94-96)。
  11. 有 7 处 SuperAdmin 守卫用的是 AppError::Forbidden(英文 operation forbidden), 不是统一守卫的中文文案:ct_discovery_handler.rs:38/61/84/103 + private_ca_handler.rs:252/333/340。同样是权限不足,message 却分中英两种, 客户端请只判 code == 403。
  12. private_ca_authorities 创建一律 SuperAdmin,但删除/回传/下载 CSR 是 「创建者 + SuperAdmin」,读是「所有登录用户」——三档权限不同(§5.7)。
  13. deployment-templates 已随 0160 拆列:paramsJson / metaJson 两个大字段从模板 DTO 下线, 改为 formats(已解析数组,非 JSON 串)/ prefillPaths(布尔);故旧文档所称 「paramsJson 出参是掩码值」不再成立,模板 DTO 已不再回传参数内容 (任务形态的 paramsJson 仍存在,属 DeploymentTaskDto,与本节无关)。
  14. ca-providers 改代理配置后需重启后端才生效(ca_provider_handler.rs:47-49)。
  15. 部分组件裸 syslog 无更多信息:agent_error_report 只写日志、不落表, 超限静默丢弃(agent_handler.rs:708-738)——排障时不要指望能查到全部错误。
  16. .trigger 在 SQL 里需要反引号(MySQL 保留字)——写自定义 SQL 时注意。
  17. certificates 域名列是 domain(不是 common_name); agents 主机名列是 hostname。
  18. 源码注释与实现对不上:dto.rs:657 写着「只读不落库」,实际是落库的。 MonitorCertInfoDto 的文档注释声称该查询「只读不落库」,但 monitoring_service.rs:48-51 的注释与 :99-129 的实现都明确落库(快照 + 检查历史 + 审计)。 以实现为准,见 §5.8 与 §7。(这条注释是本次文档被误标的根因,建议顺手修注释。)

12. 待确认条目

源码里读不到明确结论、本文不做推测的项:

#条目为什么待确认
1是否存在独立业务错误码(区别于 HTTP 状态)ErrorBody 只有 code + message,code == HTTP 状态;未见业务码表或 TODO
2CtDiscoveredCert.status 的取值集合类型是自由 String(dto.rs:1918),后端无枚举约束、无取值注释
3DeploymentTaskDto.lastStatus / triggerMode 的完整取值集合落库为自由串;status 取值集合只在 agent 侧注释里有(§5.11),服务端未枚举校验
4TransactionDto.type 的取值集合自由串,服务端只读出不出枚举
5MonitorDto 的 latency / securityGrade 未来是否会实现源码注释写「方案 B:恒 null」,但未说明是否为永久设计
6AgentDto.ip 是否会由服务端刷新注释明确「ip 列本就恒 NULL,已被裁定删除」(agent_handler.rs:1719),但列仍在 DTO 里
7是否计划引入限流全仓只有 agent 错误上报一处限流,见 §8
8API 版本化 / 变更日志通道见 §9,源码内无
9POST /api/v1/billing/quote 的合法 itemCode 集合由 billing_prices 表数据驱动,源码无硬编码枚举
10application 端点族中 TemplateListQuery.appId 对 list_base_templates 是否生效结构体有该字段,但 handler 只消费 tag(deployment_template_handler.rs:243-257)
11register 的密码强度是否后续会补齐源码标注为技术债,未见修复计划
12keystore / update_available 段的下发条件由环境变量 AGENT_RELEASE_* 与配置决定,源码未列出 keystore 的配置键名

附:端点总数与路由文件清单

端点总数:109 个「方法 × 路径」组合,分布在 87 条唯一路径上。

路由组路径数方法 × 路径鉴权
public66无
protected7395require_auth(JWT 或平台 API 密钥),端点内再判 SuperAdmin
agent_host88require_agent_sig(ed25519 验签)
合计87109—

动词分解(自校验用,剥离 // 注释后统计)

动词数量分布
get46public 2 / protected 44
post45public 4 / protected 33 / agent_host 8
put8protected 8
delete9protected 9
patch1protected 1
合计109public 6 / protected 95 / agent_host 8

⚠️ 同一条路径可挂多个动词(如 /api/v1/agents 只有 GET,POST 已下线 → 实测 405), 所以「路径数 87」<「方法 × 路径 109」。判断端点是否存活必须看方法 + 路径两者。

双向校验:本文 §5 的端点表格本身也是 109 行 / 87 条唯一路径 (get 46 / post 45 / put 8 / delete 9 / patch 1),与 router.rs 实测完全对齐; 任一侧变动都会立刻对不上,改路由时请两边一起改。

实际定位到的路由 / handler 文件清单(均在 backend/apps/onessl-app-api/src/ 下):

  • interface/router.rs —— 路由注册唯一入口(456 行)
  • interface/auth_handler.rs
  • interface/certificate_handler.rs
  • interface/ca_provider_handler.rs
  • interface/acme_account_handler.rs
  • interface/api_key_handler.rs
  • interface/private_ca_handler.rs
  • interface/monitoring_handler.rs
  • interface/dashboard_handler.rs
  • interface/deployment_handler.rs
  • interface/deployment_template_handler.rs
  • interface/agent_handler.rs(3213 行)
  • interface/agent_mgmt_handler.rs
  • interface/app_handler.rs
  • interface/ct_discovery_handler.rs
  • interface/notification_handler.rs
  • interface/settings_handler.rs
  • interface/finance_handler.rs
  • interface/billing_handler.rs
  • interface/activity_log_handler.rs
  • interface/dto.rs(2334 行,全部请求/响应 DTO)
  • middleware/auth.rs(JWT + 平台密钥分派)
  • middleware/agent_auth.rs(AgentSig 验签)
  • state.rs(AuthUser::require_super_admin)

前端调用点(交叉核对,均在 frontend/web-app/src/services/ 下): http.ts(BASE = '/api/v1')、auth.ts、users.ts、apiKeys.ts、acmeAccounts.ts、 certificate.ts、monitoring.ts、deployment.ts、application.ts、agent.ts、 discovery.ts、finance.ts、notification.ts、settings.ts、privateCa.ts、activityLogs.ts。


本文由回源核对生成。所有端点、字段、行号均可在上述源码文件中复核; 如与源码冲突,以源码为准。

文档随源码同源维护,与实现冲突时以源码为准。本页面免登录可访问。
浙ICP备2023042480号-4