Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
353daa2eec | ||
|
|
f5064254dc | ||
|
|
d92fb0f4cc | ||
|
|
1426e3ed31 | ||
|
|
17dcd50148 | ||
|
|
29d550473e | ||
|
|
d0de5d77e2 | ||
|
|
b791ba43d7 | ||
|
|
3710317011 |
No files matched your search
@@ -1,7 +1,5 @@
|
||||
# Ydisks闲鱼助手
|
||||
|
||||

|
||||
|
||||
基于 Go 与 React 构建的闲鱼多账号管理、消息回复与自动发货系统
|
||||
|
||||
[](go.mod)
|
||||
@@ -16,9 +14,15 @@
|
||||
在线聊天、账号自动任务、批量铺货、自动化发货、AI、通知和运维流程。
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 本项目是社区维护的非官方工具,与闲鱼、阿里巴巴集团及其关联公司无隶属、合作或
|
||||
> 授权关系。请仅在遵守当地法律法规、闲鱼平台规则及账号授权范围的前提下使用。
|
||||
> 使用自动化能力可能触发平台风控,请自行评估风险并妥善保护账号凭证。
|
||||
> 本项目仅用于个人技术学习研究,**未获得闲鱼/阿里巴巴任何官方授权**。
|
||||
>
|
||||
> 本项目调用闲鱼网页端非公开接口,使用本软件将违反闲鱼用户协议,可能造成闲鱼账号封禁。
|
||||
>
|
||||
> 本项目是社区维护的非官方工具,与闲鱼、阿里巴巴集团及其关联公司无隶属、合作或授权关系。
|
||||
>
|
||||
> 请仅在遵守当地法律法规的前提下使用,所有使用该代码造成的一切后果,全部由使用者自行承担,项目作者不承担任何责任。
|
||||
>
|
||||
> 收到平台下架通知时,本项目会随时删除归档。
|
||||
>
|
||||
> **有账号登录时,不要频繁重启本程序!**
|
||||
>
|
||||
@@ -32,7 +36,7 @@ Ydisks闲鱼助手是一个面向闲鱼卖家的自托管管理系统。它将
|
||||
|
||||
项目采用 Go 语言实现闲鱼登录、Cookie 续期、MTOP 请求和 WebSocket 消息链路。
|
||||
扫码登录、人脸验证流程、消息连接、凭证更新和绝大部分业务逻辑均由 Go 客户端完成。
|
||||
使用 Chromium 处理必须依赖浏览器环境的滑块风控。
|
||||
使用 Chromium 处理必须依赖浏览器环境的相关功能。
|
||||
|
||||
### 与 Ydisks 网盘拉新助手协同使用
|
||||
|
||||
@@ -53,7 +57,6 @@ Ydisks 支持管理渠道、推广账号、原始链接、推广短链与域名
|
||||
- 付款后发货、评价赠品、超时求评价等自动化流程
|
||||
- 商品与订单同步、单商品发布及支持逐行/默认类目、自动识别和最终兜底的表格批量铺货
|
||||
- 接入 OpenAI 兼容接口实现可控的 AI 客服回复
|
||||
- 账号掉线、风控、续期和发货结果的多渠道通知
|
||||
|
||||
## 功能特性
|
||||
|
||||
@@ -74,8 +77,6 @@ Ydisks 支持管理渠道、推广账号、原始链接、推广短链与域名
|
||||
| 安全能力 | 管理端会话、敏感字段 AES-256-GCM 加密、日志脱敏和出站地址校验 |
|
||||
| 容器部署 | PostgreSQL 17、健康检查、持久化卷、GHCR amd64/arm64 多架构镜像 |
|
||||
|
||||
批量铺货的类目优先级为:表格当前行指定类目 > 上传页通过关键词获取的默认类目 > 闲鱼按标题、描述和图片自动识别 > “电子资料”最终兜底。模板类目字段可全部留空;如填写,类目 ID、名称和频道类目 ID 必须同时填写,淘宝类目 ID 按闲鱼响应提供的值填写。
|
||||
|
||||
## 系统架构
|
||||
|
||||
```mermaid
|
||||
@@ -88,7 +89,7 @@ flowchart LR
|
||||
Engine --> MTOP["闲鱼 MTOP"]
|
||||
Engine --> Automation["自动化中心"]
|
||||
Automation --> Notify["通知渠道"]
|
||||
Engine -. "仅指纹与滑块风控" .-> Chromium["Playwright / Chromium"]
|
||||
Engine -. "浏览器能力" .-> Chromium["Playwright / Chromium"]
|
||||
```
|
||||
|
||||
核心职责划分:
|
||||
@@ -98,7 +99,7 @@ flowchart LR
|
||||
- `internal/xianyu`:登录协议、Cookie、MTOP、WebSocket 和消息协议
|
||||
- `internal/engine`:单账号生命周期、消息处理、回复与交付行为
|
||||
- `internal/automation`:发货、评价赠品、求评价和任务调度
|
||||
- `internal/browser`:Chromium 指纹读取与滑块验证
|
||||
- `internal/browser`:Chromium 指纹读取
|
||||
- `internal/db`:多数据库访问、敏感字段加密和嵌入式迁移
|
||||
- `internal/server`:HTTP/SPA transport、管理端鉴权和前端静态资源
|
||||
|
||||
@@ -301,8 +302,7 @@ go run ./cmd/server -db data/xianyu_data.db -addr :59188
|
||||
go run ./cmd/server -db data/xianyu_data.db -addr :59188 -no-browser
|
||||
```
|
||||
|
||||
此模式仍可运行管理后台,但浏览器指纹读取和滑块风控处理不可用,不建议用于需要登录
|
||||
和长期运行账号的生产环境。
|
||||
此模式仍可运行管理后台,但由于缺少UA,无法登陆账号。
|
||||
|
||||
## 初次使用
|
||||
|
||||
@@ -387,7 +387,7 @@ Docker Compose 还支持:
|
||||
| `-playwright-browser-dir` | 空 | Playwright 浏览器缓存目录,会设置为当前进程的 browser 路径 |
|
||||
| `-data-key-file` | 空 | `XIANYU_DATA_KEY` 持久化文件;文件不存在时自动生成 |
|
||||
| `-secure` | `false` | 为管理端 Cookie 添加 `Secure` 属性,HTTPS 部署应启用 |
|
||||
| `-no-browser` | `false` | 禁用 Chromium 指纹读取和滑块处理 |
|
||||
| `-no-browser` | `false` | 禁用 Chromium 指纹读取 |
|
||||
| `-log-level` | 环境变量或系统设置 | 覆盖日志等级 |
|
||||
| `-log-format` | 环境变量或系统设置 | 覆盖日志格式 |
|
||||
| `-v` | `false` | 启用调试日志,等价于未显式配置时使用 debug |
|
||||
@@ -426,7 +426,6 @@ DATABASE_URL="postgres://user:pass@127.0.0.1:5432/xianyu?sslmode=disable" ./xian
|
||||
- **议价策略**:最大折扣比例、最大折扣金额和最多议价轮次
|
||||
- **通知设置**:Bark、钉钉、飞书、企业微信、Telegram、邮件和 Webhook
|
||||
- **日志设置**:日志等级、输出格式和续期日志保留天数
|
||||
- **远程滑块服务**:服务地址、密钥及是否允许传递 Cookie;默认不传递 Cookie
|
||||
- **管理凭据**:管理员用户名、密码和邮箱
|
||||
|
||||
AI Base URL 支持 OpenAI 兼容接口,可连接 OpenAI、通义千问、Ollama、vLLM、
|
||||
@@ -600,7 +599,7 @@ services:
|
||||
│ ├── application/ # 用例编排、事务与补偿
|
||||
│ ├── adapter/ # 业务模块接线层
|
||||
│ ├── automation/ # 自动化中心与调度器
|
||||
│ ├── browser/ # Chromium 指纹和滑块验证
|
||||
│ ├── browser/ # Chromium 指纹验证
|
||||
│ ├── composition/ # 唯一生产组合根
|
||||
│ ├── db/ # 数据访问、加密与迁移
|
||||
│ ├── engine/ # 单账号消息和交付运行时
|
||||
@@ -732,7 +731,7 @@ go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密
|
||||
- 不要提交 `.env`、数据库文件、Cookie、二维码、日志或浏览器数据目录。
|
||||
- 定期备份 PostgreSQL,并实际验证恢复流程。
|
||||
- 使用版本或 SHA 镜像标签部署生产环境。
|
||||
- 仅向可信的 AI、SMTP、Webhook 和远程滑块服务发送数据。
|
||||
- 仅向可信的 AI、SMTP、Webhook 发送数据。
|
||||
- 发现账号异常时先停用账号,再检查登录审计和续期日志。
|
||||
|
||||
## 贡献
|
||||
@@ -743,7 +742,6 @@ go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密
|
||||
2. 为协议、数据库和关键业务行为补充测试。
|
||||
3. 运行 `make check` 和前端测试。
|
||||
4. 不要提交真实账号、Cookie、订单、卡密、密钥或其他敏感数据。
|
||||
5. 不要在未说明原因和验证证据的情况下修改风控与滑块行为。
|
||||
|
||||
提交安全问题时,请避免在公开 Issue 中附带真实凭证或用户数据。
|
||||
|
||||
|
||||
+114
-4
@@ -2012,6 +2012,42 @@ paths:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
"/api/v1/cards/test-api":
|
||||
post:
|
||||
operationId: postApiV1CardsTestApi
|
||||
summary: postApiV1CardsTestApi
|
||||
security: [{cookieAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/CardAPITestRequest'
|
||||
responses:
|
||||
'200':
|
||||
description: 测试完成
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/CardAPITestResponse'
|
||||
'400':
|
||||
description: 统一错误响应
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'401':
|
||||
description: 统一错误响应
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'503':
|
||||
description: 统一错误响应
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
"/api/v1/cards/{card_id}":
|
||||
delete:
|
||||
operationId: deleteApiV1CardsBycard_id
|
||||
@@ -6540,13 +6576,19 @@ paths:
|
||||
schema:
|
||||
type: string
|
||||
security: [{cookieAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/SystemSettingSingleUpdateRequest'
|
||||
responses:
|
||||
'200':
|
||||
description: 成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ApiResponse'
|
||||
$ref: '#/components/schemas/OperationResponse'
|
||||
'400':
|
||||
description: 统一错误响应
|
||||
content:
|
||||
@@ -7278,7 +7320,10 @@ components:
|
||||
properties:
|
||||
name: {type: string}
|
||||
type: {type: string, enum: [api, text, data, image]}
|
||||
api_config: {type: string}
|
||||
api_config:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/APICardConfigMutation'
|
||||
- type: string
|
||||
text_content: {type: string}
|
||||
data_content: {type: string}
|
||||
image_url: {type: string}
|
||||
@@ -7328,12 +7373,15 @@ components:
|
||||
id: {type: integer}
|
||||
CardResponse:
|
||||
type: object
|
||||
required: [id, name, type, api_config, text_content, data_content, image_url, description, enabled, delay_seconds, is_multi_spec, spec_name, spec_value]
|
||||
required: [id, name, type, text_content, data_content, image_url, description, enabled, delay_seconds, is_multi_spec, spec_name, spec_value]
|
||||
properties:
|
||||
id: {type: integer}
|
||||
name: {type: string}
|
||||
type: {type: string, enum: [api, text, data, image]}
|
||||
api_config: {type: string}
|
||||
api_config:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/APICardConfigResponse'
|
||||
nullable: true
|
||||
text_content: {type: string}
|
||||
data_content: {type: string}
|
||||
image_url: {type: string}
|
||||
@@ -7344,6 +7392,59 @@ components:
|
||||
spec_name: {type: string}
|
||||
spec_value: {type: string}
|
||||
user_id: {type: integer}
|
||||
APICardConfigMutation:
|
||||
type: object
|
||||
required: [url]
|
||||
properties:
|
||||
url: {type: string, format: uri}
|
||||
method: {type: string, enum: [GET, POST], default: GET}
|
||||
timeout_seconds: {type: integer, minimum: 1, maximum: 60, default: 10}
|
||||
headers:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
params:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
body:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
content_type: {type: string, default: application/json}
|
||||
headers_action: {type: string, enum: [retain, replace, clear]}
|
||||
params_action: {type: string, enum: [retain, replace, clear]}
|
||||
response_path: {type: string}
|
||||
retry_enabled: {type: boolean}
|
||||
APICardConfigResponse:
|
||||
type: object
|
||||
required: [url, method, timeout_seconds, content_type, retry_enabled, headers_configured, params_configured, ready]
|
||||
properties:
|
||||
url: {type: string}
|
||||
method: {type: string, enum: [GET, POST]}
|
||||
timeout_seconds: {type: integer}
|
||||
content_type: {type: string}
|
||||
response_path: {type: string}
|
||||
retry_enabled: {type: boolean}
|
||||
headers_configured: {type: boolean}
|
||||
params_configured: {type: boolean}
|
||||
ready: {type: boolean}
|
||||
validation_error: {type: string}
|
||||
CardAPITestRequest:
|
||||
type: object
|
||||
required: [api_config]
|
||||
properties:
|
||||
api_config:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/APICardConfigMutation'
|
||||
- type: string
|
||||
CardAPITestResponse:
|
||||
type: object
|
||||
required: [status, status_code, response_content_type, response_fields]
|
||||
properties:
|
||||
status: {type: string, enum: [success, failed]}
|
||||
status_code: {type: integer}
|
||||
response_content_type: {type: string}
|
||||
response_fields: {type: array, items: {type: string}}
|
||||
extracted_value: {type: string}
|
||||
response_preview: {type: string}
|
||||
ItemListResponse:
|
||||
type: object
|
||||
required: [id, cookie_id, item_id, item_title, item_description, item_category, item_price, item_detail, item_image, is_multi_spec, multi_quantity_delivery, is_multi_qty_ship]
|
||||
@@ -7759,6 +7860,15 @@ components:
|
||||
type: object
|
||||
additionalProperties:
|
||||
$ref: '#/components/schemas/SecretSettingChange'
|
||||
SystemSettingSingleUpdateRequest:
|
||||
type: object
|
||||
required: [value]
|
||||
properties:
|
||||
value:
|
||||
type: string
|
||||
action:
|
||||
type: string
|
||||
enum: [retain, replace, clear]
|
||||
SystemSettingsResponse:
|
||||
type: object
|
||||
additionalProperties:
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/logging"
|
||||
"xianyu-go/internal/logsafe"
|
||||
"xianyu-go/internal/netguard"
|
||||
appversion "xianyu-go/internal/version"
|
||||
)
|
||||
|
||||
@@ -352,6 +353,13 @@ func openServerInfrastructure(ctx context.Context, startup serverStartupConfig,
|
||||
closeLog()
|
||||
return serverInfrastructure{}, fmt.Errorf("校验或升级数据库敏感字段失败: %w", err)
|
||||
}
|
||||
// outboundPublicOnly 保存用户可配置 HTTP 请求的启动期公网限制快照。
|
||||
if raw, settingErr := store.Settings.Get(ctx, "outbound_http_public_only"); settingErr == nil {
|
||||
netguard.SetDefaultPublicOnly(strings.EqualFold(strings.TrimSpace(raw), "true"))
|
||||
} else {
|
||||
logger.Warn("读取统一 HTTP 出站策略失败,按默认关闭处理", "err", settingErr)
|
||||
netguard.SetDefaultPublicOnly(false)
|
||||
}
|
||||
if !startup.explicitLogLevel {
|
||||
// level、levelErr 分别是数据库保存的日志等级及其读取错误;读取失败时保留进程默认值。
|
||||
if level, levelErr := store.Settings.Get(ctx, "log_level"); levelErr == nil && strings.TrimSpace(level) != "" {
|
||||
|
||||
@@ -6,6 +6,14 @@
|
||||
|
||||
本文记录 `internal/browser` 中当前滑块认证的完整行为契约。它是维护边界,不是待办方案。后续任务即使涉及登录、Cookie、浏览器自动化、风控恢复或代码清理,也必须保持本文行为逐项不变。
|
||||
|
||||
## 本次 API 发货 Feature 的远程服务网络补充
|
||||
|
||||
本次用户明确授权仅调整远程滑块服务的网络准入:远程滑块服务请求现在使用统一的用户配置 HTTP 出站策略。系统设置
|
||||
`outbound_http_public_only` 默认关闭;关闭时允许内网 HTTP(S) 地址,但仍限制协议、重定向次数和响应大小;开启时会在 DNS
|
||||
解析和每次重定向连接前拒绝回环、私网、链路本地、保留地址及元数据地址。该开关保存后立即生效。
|
||||
|
||||
这项补充不改变滑块选择器、轨迹、拖动距离、重试顺序、Cookie 合并、成功判定、本地浏览器回退或日志语义。除网络目标校验外,本文其余冻结条款继续优先适用。
|
||||
|
||||
## 1. 保护范围
|
||||
|
||||
以下文件为直接保护对象:
|
||||
|
||||
@@ -19,10 +19,16 @@
|
||||
| 文本 | 固定说明、链接 | 填写文本内容。 |
|
||||
| 批量卡密(`data`) | 一次性兑换码、序列号 | 每行一个卡密;发货会按库存消费。 |
|
||||
| 图片 | 固定图片资源 | 填写公开可访问的图片 URL。 |
|
||||
| API | 外部发码接口 | 填写 URL、GET/POST、超时、请求头和参数;先用无敏感测试数据验证。 |
|
||||
| API | 外部发码接口 | 填写 URL、GET/POST、超时、请求头、参数和响应路径;先用无敏感测试数据验证。 |
|
||||
|
||||
通用字段包括名称、描述、启用状态和默认延时秒数。保存后复制“卡密组 ID”;它是自动化规则和批量铺货表格引用库存的唯一标识。
|
||||
|
||||
API 卡支持 `{order_id}`、`{item_id}`、`{buyer_id}`、`{chat_id}`、`{account_id}`、`{cookie_id}`、`{spec_name}`、`{spec_value}`、`{quantity}`、`{order_quantity}`、`{amount}`、`{order_amount}`、`{item_detail}`、`{trigger_type}`、`{timestamp}`、`{delivery_unit_index}`、`{delivery_total_count}` 和 `{idempotency_key}`。变量只替换请求头和参数值,不替换 URL 或请求头名称;GET 将参数放入 query,POST 使用 JSON body。响应路径可写成 `data.card.code` 或 `data.cards[0].code`,为空时系统会按 `data`、`content`、`card` 顺序提取。
|
||||
|
||||
请求头和参数会整体加密保存,列表和规则接口只返回是否已配置,不回显密钥明文。编辑时“保留”不会覆盖旧模板,“替换”写入新模板,“清除”删除对应模板。启用幂等重试前必须在请求头或参数中显式写入 `{idempotency_key}`;最多请求 3 次,只重试网络错误、超时、408、429 和 5xx。
|
||||
|
||||
管理员可在系统设置开启“用户配置 HTTP 只能访问公网”。开启后 API 发货、AI、HTTP 通知、远程图片和远程滑块服务不能访问本机、内网、链路本地、保留或云元数据地址,并会在 DNS 解析和重定向时重复校验。该开关默认关闭且保存后立即生效;不要把它当作 API 密钥或请求模板的替代安全措施。
|
||||
|
||||
批量卡密可用“批量导入”创建,也可选择已有 `data` 类型卡密组追加新卡密。上架前检查库存余量;库存不足时应先补货,不要依赖人工补救。
|
||||
|
||||
## 3. 同步或发布商品
|
||||
|
||||
@@ -29,12 +29,13 @@ import { appendCardData,batchCreateCards,createCard,deleteCard,getCardDetails,ge
|
||||
import { getChatMessagePage,getChatMessages,getChatSessionPage,getChatSessions,markChatRead,sendChatImage,sendChatMessage } from './chat/api';
|
||||
import { getDashboardStats,getOrderAnalytics,getValidOrders } from './dashboard/api';
|
||||
import { cancelItemPublishBatch,createItem,deleteItem,deleteItemPublishBatch,getItemDetail,getItemPublishBatch,getItemPublishBatches,getItems,previewItemPublishBatch,publishItem,recommendPublishCategory,retryFailedItemPublishBatch,startItemPublishBatch,syncItemsFromAccount,updateItem } from './items/api';
|
||||
import { createNotificationChannel,deleteAccountNotifications,deleteMessageNotification,deleteNotificationChannel,getAccountBindings,getMessageNotifications,getNotificationChannels,setAccountBindings,setMessageNotification,testNotificationChannel,updateNotificationChannel } from './notifications/api';
|
||||
import { createNotificationChannel,deleteAccountNotifications,deleteMessageNotification,deleteNotificationChannel,getAccountBindings,getMessageNotifications,getNotificationChannels,setAccountBindings,setMessageNotification,testNotificationChannel,updateNotificationChannel,updateSystemSettings as updateNotificationSystemSettings } from './notifications/api';
|
||||
import { cancelOrderRefreshJob,deleteOrder,getAdminStats,getOrderDetail,getOrders,importOrders,manualShipOrder,syncOrders,syncSingleOrder,updateOrder } from './orders/api';
|
||||
import { clearDefaultReplyRecords,deleteDefaultReply,deleteReplyRule,deleteShippingRule,getAutomationIssues,getDefaultReplies,getDefaultReply,getReplyRules,getShippingRules,getShippingRulesPage,resolveAutomationRun,resolveDeferredAutomationTask,updateDefaultReply,updateReplyRule,updateShippingRule } from './rules/api';
|
||||
import { initializeAdmin,login,logout,verifySession } from './session/api';
|
||||
import { changePassword,fetchAIModels,getSystemSettings,updateLoginCredentials,updateSystemSettings } from './settings/api';
|
||||
import { getHealth } from './system/api';
|
||||
import { normalizeSystemSettingsUpdate } from '../../shared/api-contract/settings';
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
@@ -89,6 +90,44 @@ test('updateSystemSettings separates sensitive values into explicit commands', /
|
||||
});
|
||||
});
|
||||
|
||||
test('normalizeSystemSettingsUpdate separates every sensitive system setting', /* 当前回调验证共享归一器不会遗漏任一敏感系统设置。 */ () => {
|
||||
// payload 是混合普通值和四类敏感值后的系统设置命令。
|
||||
const payload = normalizeSystemSettingsUpdate({
|
||||
theme_color: 'blue',
|
||||
ai_api_key: 'test-ai-key',
|
||||
smtp_password: 'test-smtp-password',
|
||||
qq_reply_secret_key: 'test-qq-secret',
|
||||
'captcha.remote_secret_key': 'test-captcha-secret',
|
||||
});
|
||||
expect(payload.values).toEqual({ theme_color: 'blue' });
|
||||
expect(payload.secrets).toEqual({
|
||||
ai_api_key: { action: 'replace', value: 'test-ai-key' },
|
||||
smtp_password: { action: 'replace', value: 'test-smtp-password' },
|
||||
qq_reply_secret_key: { action: 'replace', value: 'test-qq-secret' },
|
||||
'captcha.remote_secret_key': { action: 'replace', value: 'test-captcha-secret' },
|
||||
});
|
||||
});
|
||||
|
||||
test('notification SMTP settings separate the authorization code into a secret command', /* 当前回调验证通知页不会把 SMTP 授权码写入普通设置。 */ async () => {
|
||||
// fetchMock 是通知页系统设置更新请求的 HTTP 替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true }));
|
||||
stubContractFetch(fetchMock);
|
||||
await updateNotificationSystemSettings({
|
||||
smtp_server: 'smtp.example.com', smtp_port: 465, smtp_user: 'sender@example.com',
|
||||
smtp_password: 'test-smtp-secret', qq_reply_secret_key: 'test-qq-secret',
|
||||
'captcha.remote_secret_key': 'test-captcha-secret',
|
||||
});
|
||||
// payload 是通知页适配器分流后的普通设置和敏感命令。
|
||||
const payload = JSON.parse(fetchMock.mock.calls[0][1].body);
|
||||
expect(payload.values).toEqual({ smtp_server: 'smtp.example.com', smtp_port: 465, smtp_user: 'sender@example.com' });
|
||||
expect(payload.secrets).toEqual({
|
||||
smtp_password: { action: 'replace', value: 'test-smtp-secret' },
|
||||
qq_reply_secret_key: { action: 'replace', value: 'test-qq-secret' },
|
||||
'captcha.remote_secret_key': { action: 'replace', value: 'test-captcha-secret' },
|
||||
});
|
||||
expect(payload.values).not.toHaveProperty('smtp_password');
|
||||
});
|
||||
|
||||
test('health API exposes build metadata through the request boundary', async () => {
|
||||
// fetchMock 是健康检查 API 的请求替身。
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ version: '1.2.3', commit: 'abc123' }));
|
||||
@@ -836,7 +875,7 @@ test('getCards 解析 JSON 和损坏 JSON 的卡密接口配置', /* 当前回
|
||||
stubContractFetch(fetchMock);
|
||||
// cards 是卡密配置归一化后的库存列表。
|
||||
const cards = await getCards();
|
||||
expect(cards[0].api_config).toEqual({ endpoint: 'https://example.com' });
|
||||
expect(cards[0].api_config).toEqual({ endpoint: 'https://example.com', content_type: 'application/json' });
|
||||
expect(cards[1].api_config).toBeUndefined();
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,9 @@ import {
|
||||
Card,
|
||||
CardAppendResponse,
|
||||
CardBatchResponse,
|
||||
CardMutation,
|
||||
CardAPITestResult,
|
||||
CardAPIConfigInput,
|
||||
MutationIDResponse,OperationResponse
|
||||
} from './models';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
@@ -20,14 +23,37 @@ const normalizeCard = (item: any): Card => {
|
||||
apiConfig = undefined;
|
||||
}
|
||||
}
|
||||
if (apiConfig && typeof apiConfig === 'object' && apiConfig.timeout_seconds === undefined && apiConfig.timeout !== undefined) {
|
||||
// normalizedTimeout 将历史 timeout 字段迁移到新版摘要字段。
|
||||
apiConfig.timeout_seconds = Number(apiConfig.timeout) || 10;
|
||||
}
|
||||
if (apiConfig && typeof apiConfig === 'object' && !apiConfig.content_type) {
|
||||
apiConfig.content_type = 'application/json';
|
||||
}
|
||||
return {...item, api_config: apiConfig || undefined} as Card;
|
||||
};
|
||||
|
||||
// cardPayload 卡密请求载荷,用于当前 API 处理流程。
|
||||
const cardPayload = (data: Partial<Card>) => ({
|
||||
// parseTemplateJSON 将表单中的 JSON 模板转换为请求对象,空模板交给服务端执行保留语义。
|
||||
const parseTemplateJSON = (value: unknown): Record<string, unknown> | undefined => {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) return value as Record<string, unknown>;
|
||||
if (typeof value !== 'string' || !value.trim()) return undefined;
|
||||
// parsed 保存表单 JSON 文本解析后的未知值,随后只接受对象。
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('请求头和请求参数必须是 JSON 对象');
|
||||
return parsed as Record<string, unknown>;
|
||||
};
|
||||
|
||||
// cardPayload 将 feature 表单映射为新版具名 API 请求载荷,并兼容旧字符串配置。
|
||||
const cardPayload = (data: CardMutation) => ({
|
||||
name: data.name,
|
||||
type: data.type,
|
||||
api_config: data.api_config ? JSON.stringify(data.api_config) : '',
|
||||
api_config: typeof data.api_config === 'string' ? data.api_config : data.api_config ? {
|
||||
...data.api_config,
|
||||
headers: parseTemplateJSON(data.api_config.headers),
|
||||
params: parseTemplateJSON(data.api_config.params),
|
||||
body: parseTemplateJSON(data.api_config.body),
|
||||
content_type: data.api_config.content_type || 'application/json',
|
||||
} : undefined,
|
||||
text_content: data.text_content,
|
||||
data_content: data.data_content,
|
||||
image_url: data.image_url,
|
||||
@@ -49,12 +75,12 @@ export const getCards = async (options?: RequestControlOptions): Promise<Card[]>
|
||||
};
|
||||
|
||||
// createCard 创建卡密组。
|
||||
export const createCard = async (data: Partial<Card>): Promise<MutationIDResponse> => {
|
||||
export const createCard = async (data: CardMutation): Promise<MutationIDResponse> => {
|
||||
return runContractRequest(/* signal 控制卡券创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards', { body: cardPayload(data), signal }));
|
||||
};
|
||||
|
||||
// updateCard 更新卡密组。
|
||||
export const updateCard = async (cardId: string | number, data: Partial<Card>): Promise<OperationResponse> => {
|
||||
export const updateCard = async (cardId: string | number, data: CardMutation): Promise<OperationResponse> => {
|
||||
return runContractRequest(/* signal 控制卡券更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/cards/{card_id}', { params: { path: { card_id: String(cardId) } }, body: cardPayload(data), signal }));
|
||||
};
|
||||
|
||||
@@ -87,3 +113,11 @@ export const batchCreateCards = async (file: File, options?: RequestControlOptio
|
||||
export const appendCardData = async (cardId: string | number, content: string, options?: RequestControlOptions): Promise<CardAppendResponse> => {
|
||||
return runContractRequest(/* signal 控制卡券追加数据请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/{card_id}/append-data', { params: { path: { card_id: String(cardId) } }, body: { content }, signal }), options);
|
||||
};
|
||||
|
||||
// testCardAPI 发送一次临时 API 配置测试请求,不保存卡密配置。
|
||||
export const testCardAPI = async (data: CardAPIConfigInput): Promise<CardAPITestResult> => {
|
||||
return runContractRequest(/* signal 控制 API 测试请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/test-api', {
|
||||
body: { api_config: cardPayload({ name: '', type: 'api', api_config: data }).api_config } as never,
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
@@ -91,6 +91,42 @@ describe('useCardActions 卡密动作协调器', /* 当前回调验证卡密筛
|
||||
expect(hook.result.current.showAddModal).toBe(false);
|
||||
});
|
||||
|
||||
test('编辑 API 卡替换空模板时明确清空而不是保留旧模板', /* 当前回调验证敏感模板替换空值的显式清除语义。 */ async () => {
|
||||
// apiCard 保存只含脱敏摘要的 API 卡密组。
|
||||
const apiCard: Card = {
|
||||
...cardFixture,
|
||||
id: 4,
|
||||
name: '接口卡',
|
||||
type: 'api',
|
||||
api_config: {
|
||||
url: 'https://example.test/card',
|
||||
method: 'POST',
|
||||
timeout_seconds: 10,
|
||||
content_type: 'application/json',
|
||||
headers_configured: true,
|
||||
params_configured: true,
|
||||
retry_enabled: false,
|
||||
ready: true,
|
||||
},
|
||||
};
|
||||
// loadCards 是 API 卡编辑完成后的刷新替身。
|
||||
const loadCards = vi.fn().mockResolvedValue(undefined);
|
||||
// hook 是注入 API 卡测试数据的动作 Hook。
|
||||
const hook = renderHook(/* hookFactory 渲染注入 API 卡的动作 Hook。 */ () => useCardActions({ cards: [apiCard], loadCards }));
|
||||
act(/* editAction 打开 API 卡编辑表单。 */ () => hook.result.current.handleEdit(apiCard));
|
||||
act(/* templateAction 将两个敏感模板设置为显式替换。 */ () => hook.result.current.setEditForm(/* formUpdater 清空替换模板的表单值。 */ current => ({
|
||||
...current,
|
||||
api_headers_action: 'replace',
|
||||
api_params_action: 'replace',
|
||||
api_headers: '',
|
||||
api_params: '',
|
||||
})));
|
||||
await act(/* saveAction 提交 API 卡编辑并等待刷新完成。 */ async () => hook.result.current.handleSaveEdit());
|
||||
expect(cardActionMocks.updateCard).toHaveBeenCalledWith(4, expect.objectContaining({
|
||||
api_config: expect.objectContaining({ headers: {}, params: {} }),
|
||||
}));
|
||||
});
|
||||
|
||||
test('删除取消、删除失败和状态切换失败均不制造虚假成功', /* 当前回调验证卡密删除和启停异常分支。 */ async () => {
|
||||
// actionContext 保存卡密删除 Hook 和库存刷新替身。
|
||||
const { hook, loadCards } = createCardHook();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback,useMemo,useState,type Dispatch,type SetStateAction } from 'react';
|
||||
import type { Card } from './api';
|
||||
import type { Card,CardMutation } from './api';
|
||||
import { createCard,deleteCard,updateCard } from './api';
|
||||
import { filterCards } from './batchState';
|
||||
import type { AddCardForm,EditCardForm } from './types';
|
||||
@@ -16,6 +16,10 @@ export const emptyAddForm = (): AddCardForm => ({
|
||||
api_timeout: 10,
|
||||
api_headers: '',
|
||||
api_params: '',
|
||||
api_content_type: 'application/json',
|
||||
api_body: '',
|
||||
api_response_path: '',
|
||||
api_retry_enabled: false,
|
||||
});
|
||||
|
||||
// CardActionsOptions 描述卡密动作协调器依赖的库存状态和刷新操作。
|
||||
@@ -110,9 +114,15 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
type: card.type || 'text',
|
||||
api_url: card.api_config?.url || '',
|
||||
api_method: card.api_config?.method || 'GET',
|
||||
api_timeout: card.api_config?.timeout || 10,
|
||||
api_headers: card.api_config?.headers || '',
|
||||
api_params: card.api_config?.params || '',
|
||||
api_timeout: card.api_config?.timeout_seconds || 10,
|
||||
api_headers: '',
|
||||
api_params: '',
|
||||
api_content_type: card.api_config?.content_type || 'application/json',
|
||||
api_body: '',
|
||||
api_response_path: card.api_config?.response_path || '',
|
||||
api_retry_enabled: card.api_config?.retry_enabled || false,
|
||||
api_headers_action: 'retain',
|
||||
api_params_action: 'retain',
|
||||
text_content: card.text_content || '',
|
||||
data_content: card.data_content || '',
|
||||
image_url: card.image_url || '',
|
||||
@@ -136,7 +146,7 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
}
|
||||
try {
|
||||
// updateData 保存映射到卡密更新接口的字段。
|
||||
const updateData: Partial<Card> = {
|
||||
const updateData: CardMutation = {
|
||||
name: editForm.name.trim(),
|
||||
type: editForm.type,
|
||||
description: editForm.description?.trim(),
|
||||
@@ -147,9 +157,15 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
updateData.api_config = {
|
||||
url: editForm.api_url?.trim() || '',
|
||||
method: editForm.api_method || 'GET',
|
||||
timeout: editForm.api_timeout || 10,
|
||||
headers: editForm.api_headers?.trim() || undefined,
|
||||
params: editForm.api_params?.trim() || undefined,
|
||||
timeout_seconds: editForm.api_timeout || 10,
|
||||
headers: editForm.api_headers_action === 'clear' ? undefined : editForm.api_headers_action === 'replace' && !editForm.api_headers?.trim() ? {} : editForm.api_headers?.trim() || undefined,
|
||||
params: editForm.api_params_action === 'clear' ? undefined : editForm.api_params_action === 'replace' && !editForm.api_params?.trim() ? {} : editForm.api_params?.trim() || undefined,
|
||||
content_type: editForm.api_content_type || 'application/json',
|
||||
body: editForm.api_body?.trim() || undefined,
|
||||
headers_action: editForm.api_headers_action || 'retain',
|
||||
params_action: editForm.api_params_action || 'retain',
|
||||
response_path: editForm.api_response_path?.trim() || undefined,
|
||||
retry_enabled: editForm.api_retry_enabled || false,
|
||||
};
|
||||
} else if (editForm.type === 'text') {
|
||||
updateData.text_content = editForm.text_content?.trim() || '';
|
||||
@@ -191,7 +207,7 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
}
|
||||
try {
|
||||
// payload 保存新增卡密组的接口载荷。
|
||||
const payload: Partial<Card> = {
|
||||
const payload: CardMutation = {
|
||||
name: addForm.name.trim(),
|
||||
type: addForm.type,
|
||||
description: addForm.description.trim(),
|
||||
@@ -205,9 +221,13 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
payload.api_config = {
|
||||
url: addForm.content.trim(),
|
||||
method: addForm.api_method,
|
||||
timeout: addForm.api_timeout,
|
||||
timeout_seconds: addForm.api_timeout,
|
||||
headers: addForm.api_headers.trim() || undefined,
|
||||
params: addForm.api_params.trim() || undefined,
|
||||
content_type: addForm.api_content_type,
|
||||
body: addForm.api_body.trim() || undefined,
|
||||
response_path: addForm.api_response_path.trim() || undefined,
|
||||
retry_enabled: addForm.api_retry_enabled,
|
||||
};
|
||||
}
|
||||
await createCard(payload);
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
import { Loader2, Play, Plus, Trash2 } from 'lucide-react';
|
||||
import { useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||
import type { CardAPITestResult } from '../models';
|
||||
|
||||
// APIRequestMethod 是 API 发货请求支持的 HTTP 方法。
|
||||
export type APIRequestMethod = 'GET' | 'POST';
|
||||
|
||||
// APISecretAction 描述编辑敏感模板时对服务端已保存值的处理方式。
|
||||
export type APISecretAction = 'retain' | 'replace' | 'clear';
|
||||
|
||||
// APIKeyValueRow 是 Postman 风格键值编辑器中的一行表单数据。
|
||||
export interface APIKeyValueRow {
|
||||
// key 是请求头、查询参数或表单字段名称。
|
||||
key: string;
|
||||
// value 是字段值;动态变量会以文本形式保留到服务端替换。
|
||||
value: string;
|
||||
}
|
||||
|
||||
// APIRequestBuilderProps 描述 API 请求编辑器的受控字段和保存动作。
|
||||
export interface APIRequestBuilderProps {
|
||||
// url 是远端 API 地址。
|
||||
url: string;
|
||||
// method 是远端 API 请求方法。
|
||||
method: APIRequestMethod;
|
||||
// timeout 是单次远端请求的超时秒数。
|
||||
timeout: number;
|
||||
// headers 是请求头 JSON 文本,组件以键值行展示。
|
||||
headers: string;
|
||||
// params 是 URL 查询参数 JSON 文本,组件以键值行展示。
|
||||
params: string;
|
||||
// contentType 是 POST 请求正文的 Content-Type。
|
||||
contentType: string;
|
||||
// body 是 JSON 正文或非 JSON 正文的键值 JSON 文本。
|
||||
body: string;
|
||||
// responsePath 是成功响应中的卡密提取路径。
|
||||
responsePath: string;
|
||||
// retryEnabled 表示是否启用带幂等键的重试。
|
||||
retryEnabled: boolean;
|
||||
// headersAction 是编辑时请求头敏感模板的三态处理方式。
|
||||
headersAction?: APISecretAction;
|
||||
// paramsAction 是编辑时查询参数敏感模板的三态处理方式。
|
||||
paramsAction?: APISecretAction;
|
||||
// onChange 更新指定 API 配置字段。
|
||||
onChange: (field: APIRequestField, value: string | number | boolean) => void;
|
||||
// onTest 使用当前配置执行临时测试请求。
|
||||
onTest?: () => Promise<CardAPITestResult>;
|
||||
}
|
||||
|
||||
// APIRequestField 是 APIRequestBuilder 可更新字段的联合类型。
|
||||
export type APIRequestField =
|
||||
| 'url'
|
||||
| 'method'
|
||||
| 'timeout'
|
||||
| 'headers'
|
||||
| 'params'
|
||||
| 'contentType'
|
||||
| 'body'
|
||||
| 'responsePath'
|
||||
| 'retryEnabled'
|
||||
| 'headersAction'
|
||||
| 'paramsAction';
|
||||
|
||||
// APITestState 保存 API 测试请求的加载状态、非敏感诊断结果与请求错误。
|
||||
interface APITestState {
|
||||
// loading 表示当前是否正在等待远端测试响应。
|
||||
loading: boolean;
|
||||
// result 是远端完成请求后返回的状态和响应结构诊断。
|
||||
result?: CardAPITestResult;
|
||||
// error 是本地请求、超时或配置错误的用户可见提示。
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// contentTypes 保存常用且不依赖文件上传的请求正文类型。
|
||||
const contentTypes = [
|
||||
{ value: 'application/json', label: 'JSON(application/json)' },
|
||||
{ value: 'application/x-www-form-urlencoded', label: '表单键值(x-www-form-urlencoded)' },
|
||||
{ value: 'text/plain', label: '纯文本(text/plain)' },
|
||||
{ value: 'application/xml', label: 'XML(application/xml)' },
|
||||
];
|
||||
|
||||
// isJSONContentType 判断正文类型是否应该使用 JSON 编辑器。
|
||||
const isJSONContentType = (contentType: string): boolean => contentType.toLowerCase().includes('json');
|
||||
|
||||
// rowsFromJSON 将已保存的 JSON 对象转成适合键值编辑器展示的行。
|
||||
const rowsFromJSON = (value: string): APIKeyValueRow[] => {
|
||||
if (!value.trim()) return [{ key: '', value: '' }];
|
||||
try {
|
||||
// parsed 是配置模板解析后的未知 JSON 值。
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return [{ key: '', value: '' }];
|
||||
// entries 是对象中每个字段的键和值。
|
||||
const entries = Object.entries(parsed as Record<string, unknown>);
|
||||
if (entries.length === 0) return [{ key: '', value: '' }];
|
||||
return entries.map(/* entry 保存当前对象字段的键和值。 */ entry => {
|
||||
// key、entryValue 分别是当前模板字段名称和字段值。
|
||||
const [key, entryValue] = entry;
|
||||
return { key, value: typeof entryValue === 'string' ? entryValue : JSON.stringify(entryValue) };
|
||||
});
|
||||
} catch {
|
||||
return [{ key: '', value: value.trim() }];
|
||||
}
|
||||
};
|
||||
|
||||
// rowsToJSON 将键值行序列化为服务端使用的 JSON 对象文本。
|
||||
const rowsToJSON = (rows: APIKeyValueRow[]): string => {
|
||||
// object 是过滤空键后待提交的键值对象。
|
||||
const object = rows.reduce<Record<string, string>>(/* reduceCallback 汇总非空键名的模板字段。 */ (result, row) => {
|
||||
// key 是当前行清理空白后的字段名称。
|
||||
const key = row.key.trim();
|
||||
if (key) result[key] = row.value;
|
||||
return result;
|
||||
}, {});
|
||||
return JSON.stringify(object);
|
||||
};
|
||||
|
||||
// KeyValueEditorProps 描述一组 Postman 风格键值行编辑器。
|
||||
interface KeyValueEditorProps {
|
||||
// label 是当前键值区块的可见标题。
|
||||
label: string;
|
||||
// value 是当前键值对象的 JSON 文本。
|
||||
value: string;
|
||||
// placeholder 是第一行输入的示例文本。
|
||||
placeholder: string;
|
||||
// onChange 接收序列化后的键值对象。
|
||||
onChange: (value: string) => void;
|
||||
}
|
||||
|
||||
// KeyValueEditor 渲染可增删的键值对输入行。
|
||||
const KeyValueEditor = ({ label, value, placeholder, onChange }: KeyValueEditorProps) => {
|
||||
// rows 保存当前键值编辑行;空行也必须保留在本地状态中,才能支持连续添加。
|
||||
const [rows, setRows] = useState<APIKeyValueRow[]>(() => rowsFromJSON(value));
|
||||
// lastEmittedValue 记录本组件最近一次提交的 JSON,避免空行序列化为 {} 后被外部同步立即抹掉。
|
||||
const lastEmittedValue = useRef(value);
|
||||
|
||||
// syncRows 在父表单从外部载入新模板时重置编辑行;本组件自己的更新不重复覆盖空行。
|
||||
useEffect(/* syncRowsEffect 同步外部模板变更并保留本地新增空行。 */ () => {
|
||||
if (value !== lastEmittedValue.current) {
|
||||
setRows(rowsFromJSON(value));
|
||||
lastEmittedValue.current = value;
|
||||
}
|
||||
}, [value]);
|
||||
|
||||
// emitRows 保存本地键值行并通知父表单更新敏感模板 JSON。
|
||||
const emitRows = (nextRows: APIKeyValueRow[]) => {
|
||||
// serialized 是当前键值行转成的服务端 JSON 对象文本。
|
||||
const serialized = rowsToJSON(nextRows);
|
||||
setRows(nextRows);
|
||||
lastEmittedValue.current = serialized;
|
||||
onChange(serialized);
|
||||
};
|
||||
|
||||
// updateRow 修改某一行并把完整对象交回父表单。
|
||||
const updateRow = (index: number, field: keyof APIKeyValueRow, nextValue: string) => {
|
||||
// nextRows 是修改当前字段后的完整键值行列表。
|
||||
const nextRows = rows.map(/* rowUpdater 更新当前键值编辑行。 */ (row, rowIndex) => rowIndex === index ? { ...row, [field]: nextValue } : row);
|
||||
emitRows(nextRows);
|
||||
};
|
||||
|
||||
// addRow 在末尾追加一行空键值输入。
|
||||
const addRow = () => emitRows([...rows, { key: '', value: '' }]);
|
||||
|
||||
// removeRow 删除指定键值行,并确保编辑器始终保留一行可输入内容。
|
||||
const removeRow = (index: number) => emitRows(rows.filter(/* rowFilter 保留未被删除的键值行。 */ (_, rowIndex) => rowIndex !== index));
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className="text-sm font-bold text-gray-800">{label}</label>
|
||||
<button
|
||||
type="button"
|
||||
onClick={addRow}
|
||||
className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-xs font-bold text-blue-600 transition-colors hover:bg-blue-50"
|
||||
title={`添加${label}字段`}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
添加字段
|
||||
</button>
|
||||
</div>
|
||||
<div className="overflow-hidden rounded-xl border border-gray-200 bg-white">
|
||||
<div className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)_40px] gap-2 border-b border-gray-100 bg-gray-50 px-3 py-2 text-[11px] font-bold uppercase tracking-wide text-gray-400">
|
||||
<span>KEY</span>
|
||||
<span>VALUE</span>
|
||||
<span aria-hidden="true" />
|
||||
</div>
|
||||
<div className="divide-y divide-gray-100">
|
||||
{rows.map(/* rowRenderer 渲染当前键值编辑行。 */ (row, index) => (
|
||||
<div className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)_40px] items-center gap-2 px-3 py-2" key={`${label}-${index}`}>
|
||||
<input
|
||||
aria-label={`${label}第${index + 1}行键名`}
|
||||
value={row.key}
|
||||
onChange={/* 当前回调更新键值行的字段名称。 */ (event: ChangeEvent<HTMLInputElement>) => updateRow(index, 'key', event.target.value)}
|
||||
placeholder={index === 0 ? placeholder : '键名'}
|
||||
className="min-w-0 border-0 bg-transparent px-1 py-2 font-mono text-sm text-gray-800 outline-none ring-0 placeholder:text-gray-300"
|
||||
/>
|
||||
<input
|
||||
aria-label={`${label}第${index + 1}行值`}
|
||||
value={row.value}
|
||||
onChange={/* 当前回调更新键值行的字段值。 */ (event: ChangeEvent<HTMLInputElement>) => updateRow(index, 'value', event.target.value)}
|
||||
placeholder={index === 0 ? '输入值或动态变量,例如 {order_id}' : '值'}
|
||||
className="min-w-0 border-0 bg-transparent px-1 py-2 font-mono text-sm text-gray-800 outline-none ring-0 placeholder:text-gray-300"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={/* 当前回调删除指定键值编辑行。 */ () => removeRow(index)}
|
||||
className="inline-flex h-8 w-8 items-center justify-center rounded-lg text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
|
||||
title={`删除${label}第${index + 1}行`}
|
||||
aria-label={`删除${label}第${index + 1}行`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// APIRequestBuilder 渲染 API 地址、元数据以及 Headers / Params / Body 三个请求区块。
|
||||
export const APIRequestBuilder = ({
|
||||
url,
|
||||
method,
|
||||
timeout,
|
||||
headers,
|
||||
params,
|
||||
contentType,
|
||||
body,
|
||||
responsePath,
|
||||
retryEnabled,
|
||||
headersAction,
|
||||
paramsAction,
|
||||
onChange,
|
||||
onTest,
|
||||
}: APIRequestBuilderProps) => {
|
||||
// jsonBody 表示当前正文类型是否使用 JSON 文本编辑器。
|
||||
const jsonBody = isJSONContentType(contentType);
|
||||
// testState 保存最近一次 API 测试的加载、结果和错误状态。
|
||||
const [testState, setTestState] = useState<APITestState>({ loading: false });
|
||||
// runTest 触发临时请求并保留结果在当前弹窗中。
|
||||
const runTest = async () => {
|
||||
if (!onTest) return;
|
||||
setTestState({ loading: true });
|
||||
try {
|
||||
setTestState({ loading: false, result: await onTest() });
|
||||
} catch (/* error 表示测试请求的本地错误或共享 HTTP 客户端返回的异常。 */ error) {
|
||||
setTestState({ loading: false, error: error instanceof Error ? error.message : 'API 测试请求失败' });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-5 rounded-2xl border border-blue-100 bg-blue-50/40 p-4 sm:p-5">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="font-bold text-gray-900">API 请求配置</h3>
|
||||
<p className="mt-1 text-xs text-gray-500">按 Postman 的请求结构填写,敏感模板只会加密保存在服务端。</p>
|
||||
</div>
|
||||
<span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-bold text-blue-600 shadow-sm">API</span>
|
||||
</div>
|
||||
{onTest && (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button type="button" onClick={runTest} disabled={testState.loading} className="inline-flex items-center gap-2 rounded-xl bg-gray-900 px-4 py-2.5 text-sm font-bold text-white transition-colors hover:bg-gray-700 disabled:cursor-wait disabled:opacity-60">
|
||||
{testState.loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
|
||||
测试请求
|
||||
</button>
|
||||
{testState.error && <span className="text-sm font-semibold text-red-600">{testState.error}</span>}
|
||||
{testState.result && (
|
||||
<div className={`w-full rounded-xl border p-3 text-sm ${testState.result.status === 'success' ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50'}`}>
|
||||
<div className="flex flex-wrap gap-x-5 gap-y-1 font-semibold">
|
||||
<span>{testState.result.status === 'success' ? '测试成功' : '测试失败'}</span>
|
||||
<span>HTTP 状态:{testState.result.status_code || '网络错误'}</span>
|
||||
<span>响应类型:{testState.result.response_content_type || '未知'}</span>
|
||||
</div>
|
||||
<div className="mt-2 grid gap-1 text-gray-700"><span>响应字段:{testState.result.response_fields.length ? testState.result.response_fields.join('、') : '未识别 JSON 字段'}</span><span>提取结果:{testState.result.extracted_value || '未提取到内容'}</span></div>
|
||||
{testState.result.response_preview && <pre className="mt-2 max-h-32 overflow-auto whitespace-pre-wrap rounded-lg bg-white/70 p-2 text-xs text-gray-600">{testState.result.response_preview}</pre>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-[minmax(0,1fr)_130px_130px]">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">API 地址</label>
|
||||
<input
|
||||
type="url"
|
||||
value={url}
|
||||
onChange={/* 当前回调更新远端 API 地址。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('url', event.target.value)}
|
||||
className="w-full ios-input rounded-xl px-4 py-3 font-mono text-sm"
|
||||
placeholder="https://api.example.com/get-code"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">请求方法</label>
|
||||
<select value={method} onChange={/* 当前回调切换 API 请求方法。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('method', event.target.value)} className="w-full ios-input rounded-xl px-3 py-3">
|
||||
<option value="GET">GET</option>
|
||||
<option value="POST">POST</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">超时(秒)</label>
|
||||
<input type="number" min="1" max="60" value={timeout} onChange={/* 当前回调更新 API 请求超时秒数。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('timeout', Number(event.target.value) || 10)} className="w-full ios-input rounded-xl px-3 py-3" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-5 border-t border-blue-100 pt-5">
|
||||
<KeyValueEditor label="Headers / 请求头" value={headers} onChange={/* 当前回调保存请求头键值对象。 */ nextValue => onChange('headers', nextValue)} placeholder="Authorization" />
|
||||
{headersAction && (
|
||||
<select aria-label="请求头处理方式" value={headersAction} onChange={/* 当前回调选择请求头敏感模板处理方式。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('headersAction', event.target.value)} className="w-full ios-input rounded-xl px-3 py-2 text-sm sm:w-auto">
|
||||
<option value="retain">保留已保存请求头</option>
|
||||
<option value="replace">替换为上方字段</option>
|
||||
<option value="clear">清除已保存请求头</option>
|
||||
</select>
|
||||
)}
|
||||
|
||||
<KeyValueEditor label="Params / 查询参数" value={params} onChange={/* 当前回调保存查询参数键值对象。 */ nextValue => onChange('params', nextValue)} placeholder="order_id" />
|
||||
{paramsAction && (
|
||||
<select aria-label="查询参数处理方式" value={paramsAction} onChange={/* 当前回调选择查询参数敏感模板处理方式。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('paramsAction', event.target.value)} className="w-full ios-input rounded-xl px-3 py-2 text-sm sm:w-auto">
|
||||
<option value="retain">保留已保存查询参数</option>
|
||||
<option value="replace">替换为上方字段</option>
|
||||
<option value="clear">清除已保存查询参数</option>
|
||||
</select>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<label className="text-sm font-bold text-gray-800">Body / 请求正文</label>
|
||||
<select aria-label="请求正文 Content-Type" value={contentType} onChange={/* 当前回调切换请求正文类型。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('contentType', event.target.value)} className="ios-input rounded-xl px-3 py-2 text-sm sm:w-[290px]">
|
||||
{contentTypes.map(/* 当前回调渲染一个常用 Content-Type 选项。 */ contentTypeOption => <option key={contentTypeOption.value} value={contentTypeOption.value}>{contentTypeOption.label}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
{jsonBody ? (
|
||||
<textarea
|
||||
aria-label="JSON 请求正文"
|
||||
value={body}
|
||||
onChange={/* 当前回调更新 JSON 请求正文。 */ (event: ChangeEvent<HTMLTextAreaElement>) => onChange('body', event.target.value)}
|
||||
className="h-36 w-full resize-y ios-input rounded-xl px-4 py-3 font-mono text-sm"
|
||||
placeholder={'{\n "order_id": "{order_id}"\n}'}
|
||||
/>
|
||||
) : (
|
||||
<KeyValueEditor label="Body 字段" value={body} onChange={/* 当前回调保存非 JSON 正文键值对象。 */ nextValue => onChange('body', nextValue)} placeholder="field" />
|
||||
)}
|
||||
<p className="text-xs text-gray-500">GET 请求通常只使用 Params;POST 请求会按所选 Content-Type 发送 Body。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 border-t border-blue-100 pt-5 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">响应提取路径(可选)</label>
|
||||
<input value={responsePath} onChange={/* 当前回调更新响应提取路径。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('responsePath', event.target.value)} className="w-full ios-input rounded-xl px-4 py-3 font-mono text-sm" placeholder="data.cards[0].code" />
|
||||
</div>
|
||||
<label className="flex items-center gap-2 self-end pb-3 text-sm font-bold text-gray-700">
|
||||
<input type="checkbox" checked={retryEnabled} onChange={/* 当前回调切换 API 幂等重试。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('retryEnabled', event.target.checked)} />
|
||||
启用幂等重试(需配置 {'{idempotency_key}'})
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -15,19 +15,8 @@ export interface Card {
|
||||
text_content?: string;
|
||||
// 批量数据类型
|
||||
data_content?: string;
|
||||
// API 类型配置
|
||||
api_config?: {
|
||||
/** API 卡券请求地址。 */
|
||||
url: string;
|
||||
/** API 卡券请求方法。 */
|
||||
method: 'GET' | 'POST';
|
||||
/** API 请求超时时间。 */
|
||||
timeout?: number;
|
||||
/** API 请求头 JSON。 */
|
||||
headers?: string;
|
||||
/** API 请求参数 JSON。 */
|
||||
params?: string;
|
||||
};
|
||||
// API 类型配置只保存服务端返回的脱敏摘要。
|
||||
api_config?: CardAPIConfigSummary;
|
||||
// 图片类型
|
||||
/** 图片卡券地址。 */
|
||||
image_url?: string;
|
||||
@@ -43,6 +32,78 @@ export interface Card {
|
||||
spec_value?: string;
|
||||
}
|
||||
|
||||
/** API 卡券查询返回的脱敏摘要;请求头和参数永远不在此模型中。 */
|
||||
export interface CardAPIConfigSummary {
|
||||
/** API 卡券请求地址。 */
|
||||
url: string;
|
||||
/** API 卡券请求方法。 */
|
||||
method: 'GET' | 'POST';
|
||||
/** API 请求正文的 Content-Type。 */
|
||||
content_type: string;
|
||||
/** API 请求超时时间。 */
|
||||
timeout_seconds: number;
|
||||
/** API 响应提取路径。 */
|
||||
response_path?: string;
|
||||
/** 是否启用幂等重试。 */
|
||||
retry_enabled: boolean;
|
||||
/** 是否已配置请求头模板。 */
|
||||
headers_configured: boolean;
|
||||
/** 是否已配置请求参数模板。 */
|
||||
params_configured: boolean;
|
||||
/** 当前配置是否可以被规则使用。 */
|
||||
ready: boolean;
|
||||
/** 当前配置的非敏感校验错误。 */
|
||||
validation_error?: string;
|
||||
}
|
||||
|
||||
/** API 卡券提交用的具名配置;敏感模板为空时由服务端保留旧值。 */
|
||||
export interface CardAPIConfigInput {
|
||||
/** API 卡券请求地址。 */
|
||||
url: string;
|
||||
/** API 卡券请求方法。 */
|
||||
method: 'GET' | 'POST';
|
||||
/** API 请求超时时间。 */
|
||||
timeout_seconds: number;
|
||||
/** API 请求头 JSON 文本或对象。 */
|
||||
headers?: string | Record<string, unknown>;
|
||||
/** API 请求参数 JSON 文本或对象。 */
|
||||
params?: string | Record<string, unknown>;
|
||||
/** API 请求正文 JSON 文本或对象。 */
|
||||
body?: string | Record<string, unknown>;
|
||||
/** API 请求正文的 Content-Type。 */
|
||||
content_type?: string;
|
||||
/** 请求头的三态变更意图。 */
|
||||
headers_action?: 'retain' | 'replace' | 'clear';
|
||||
/** 请求参数的三态变更意图。 */
|
||||
params_action?: 'retain' | 'replace' | 'clear';
|
||||
/** API 响应提取路径。 */
|
||||
response_path?: string;
|
||||
/** 是否启用幂等重试。 */
|
||||
retry_enabled?: boolean;
|
||||
}
|
||||
|
||||
/** API 测试请求返回的非敏感诊断结果。 */
|
||||
export interface CardAPITestResult {
|
||||
/** 远端请求是否返回 2xx。 */
|
||||
status: 'success' | 'failed';
|
||||
/** 远端 HTTP 状态码。 */
|
||||
status_code: number;
|
||||
/** 远端响应媒体类型。 */
|
||||
response_content_type: string;
|
||||
/** JSON 响应顶层字段名称。 */
|
||||
response_fields: string[];
|
||||
/** 响应提取路径命中的值。 */
|
||||
extracted_value?: string;
|
||||
/** 限长响应预览。 */
|
||||
response_preview?: string;
|
||||
}
|
||||
|
||||
/** 卡券创建和更新所需的前端提交模型。 */
|
||||
export type CardMutation = Omit<Partial<Card>, 'api_config'> & {
|
||||
/** API 卡券具名请求配置或历史 JSON 字符串。 */
|
||||
api_config?: CardAPIConfigInput | string;
|
||||
};
|
||||
|
||||
/** 卡券批量创建接口的逐行结果。 */
|
||||
/** 由当前 feature adapter 归一后的 CardBatchResult UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface CardBatchResult {
|
||||
|
||||
@@ -11,6 +11,7 @@ const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享
|
||||
createCard: vi.fn(),
|
||||
deleteCard: vi.fn(),
|
||||
updateCard: vi.fn(),
|
||||
testCardAPI: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../hooks', /* cardsHooksMockFactory 提供卡密库存和批量 Hook 替身。 */ () => ({
|
||||
@@ -49,6 +50,7 @@ vi.mock('../api', /* cardsApiMockFactory 提供卡密页面动作 API 替身。
|
||||
createCard: cardListMocks.createCard,
|
||||
deleteCard: cardListMocks.deleteCard,
|
||||
updateCard: cardListMocks.updateCard,
|
||||
testCardAPI: cardListMocks.testCardAPI,
|
||||
}));
|
||||
|
||||
vi.mock('../components/BatchCardImportModal', /* batchModalMockFactory 提供批量弹窗替身。 */ () => ({
|
||||
@@ -86,6 +88,7 @@ describe('CardList 页面组合行为', /* 当前回调验证卡密筛选、批
|
||||
cardListMocks.createCard.mockResolvedValue({ success: true, id: 3 });
|
||||
cardListMocks.deleteCard.mockResolvedValue({ success: true });
|
||||
cardListMocks.updateCard.mockResolvedValue({ success: true });
|
||||
cardListMocks.testCardAPI.mockResolvedValue({ status: 'success', status_code: 200, response_content_type: 'application/json', response_fields: ['data', 'message'], extracted_value: 'TEST-CODE' });
|
||||
vi.spyOn(window, 'alert').mockImplementation(/* alertImplementation 屏蔽卡密页面提示。 */ () => undefined);
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
});
|
||||
@@ -123,6 +126,33 @@ describe('CardList 页面组合行为', /* 当前回调验证卡密筛选、批
|
||||
expect(cardListMocks.loadCards).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test('API 卡密使用三段请求编辑器并支持切换正文类型', /* 当前回调验证 API 地址、Headers、Params、Body 和 Content-Type 控件。 */ () => {
|
||||
render(<CardList />);
|
||||
fireEvent.click(screen.getByText('添加新卡密'));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'API 接口' }));
|
||||
expect(screen.getByRole('heading', { name: 'API 请求配置' })).toBeTruthy();
|
||||
expect(screen.getByLabelText('Headers / 请求头第1行键名')).toBeTruthy();
|
||||
expect(screen.getByLabelText('Params / 查询参数第1行键名')).toBeTruthy();
|
||||
expect(screen.getByLabelText('JSON 请求正文')).toBeTruthy();
|
||||
fireEvent.change(screen.getByRole('combobox', { name: '请求正文 Content-Type' }), { target: { value: 'application/x-www-form-urlencoded' } });
|
||||
expect(screen.getByLabelText('Body 字段第1行键名')).toBeTruthy();
|
||||
fireEvent.click(screen.getByTitle('添加Headers / 请求头字段'));
|
||||
expect(screen.getByLabelText('Headers / 请求头第2行键名')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('新增卡密类型单行排列且 API 测试展示远端诊断', /* 当前回调验证类型顺序和 API 测试结果可见。 */ async () => {
|
||||
render(<CardList />);
|
||||
fireEvent.click(screen.getByText('添加新卡密'));
|
||||
// typeButtons 保存新增弹窗中按显示顺序排列的四种卡密类型按钮。
|
||||
const typeButtons = ['批量库存', '文本', '图片', 'API 接口'].map(/* typeButtonMapper 查找当前类型按钮。 */ typeName => screen.getByRole('button', { name: typeName }));
|
||||
expect(typeButtons.map(/* typeNameMapper 读取当前类型按钮名称。 */ button => button.textContent?.trim())).toEqual(['批量库存', '文本', '图片', 'API 接口']);
|
||||
fireEvent.click(typeButtons[3]);
|
||||
fireEvent.click(screen.getByRole('button', { name: '测试请求' }));
|
||||
await waitFor(/* testResultAssertion 等待 API 测试结果展示。 */ () => expect(screen.getByText('HTTP 状态:200')).toBeTruthy());
|
||||
expect(screen.getByText('响应字段:data、message')).toBeTruthy();
|
||||
expect(screen.getByText('提取结果:TEST-CODE')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('启停、复制和删除按钮调用对应页面动作', /* 当前回调验证卡密行级动作边界。 */ async () => {
|
||||
render(<CardList />);
|
||||
fireEvent.click(screen.getByRole('button', { name: '切换卡密 库存一 状态' }));
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Copy,CreditCard,Edit,FileText,Image as ImageIcon,Package,Plus,Save,Search,SlidersHorizontal,Trash2,Upload,X } from 'lucide-react';
|
||||
import { Copy,CreditCard,Edit,FileText,Globe,Image as ImageIcon,Package,Plus,Save,Search,SlidersHorizontal,Trash2,Upload,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Card } from '../api';
|
||||
import { Card, testCardAPI } from '../api';
|
||||
import { useCardActions } from '../cardActions';
|
||||
import { APIRequestBuilder } from '../components/APIRequestBuilder';
|
||||
import { BatchCardImportModal } from '../components/BatchCardImportModal';
|
||||
import { CardIcon } from '../components/CardIcon';
|
||||
import { useCardBatchActions,useCardsData } from '../hooks';
|
||||
@@ -256,71 +257,46 @@ const CardList: React.FC = () => {
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
>
|
||||
<option value="">请选择类型</option>
|
||||
<option value="data">批量库存</option>
|
||||
<option value="text">固定文字</option>
|
||||
<option value="data">批量数据</option>
|
||||
{selectedCard?.type === 'api' && <option value="api">API接口(仅保留现有配置)</option>}
|
||||
<option value="image">图片</option>
|
||||
<option value="api">API 接口</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* API 配置 */}
|
||||
{editForm.type === 'api' && (
|
||||
<div className="border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50">
|
||||
<h3 className="font-bold text-gray-900">API 配置</h3>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">API 地址</label>
|
||||
<input
|
||||
type="url"
|
||||
value={editForm.api_url || ''}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_url: e.target.value })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl font-mono text-sm"
|
||||
placeholder="https://api.example.com/get-card"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">请求方法</label>
|
||||
<select
|
||||
value={editForm.api_method || 'GET'}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_method: e.target.value as 'GET' | 'POST' })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
>
|
||||
<option value="GET">GET</option>
|
||||
<option value="POST">POST</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">超时时间(秒)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={editForm.api_timeout || 10}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_timeout: parseInt(e.target.value) || 10 })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
min="1"
|
||||
max="60"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">请求头(JSON 格式)</label>
|
||||
<textarea
|
||||
value={editForm.api_headers || ''}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_headers: e.target.value })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm"
|
||||
placeholder='{"Authorization": "Bearer token"}'
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">请求参数(JSON 格式)</label>
|
||||
<textarea
|
||||
value={editForm.api_params || ''}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_params: e.target.value })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm"
|
||||
placeholder='{"type": "card", "count": 1}'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<>
|
||||
<APIRequestBuilder
|
||||
url={editForm.api_url || ''}
|
||||
method={editForm.api_method || 'GET'}
|
||||
timeout={editForm.api_timeout || 10}
|
||||
headers={editForm.api_headers || ''}
|
||||
params={editForm.api_params || ''}
|
||||
contentType={editForm.api_content_type || 'application/json'}
|
||||
body={editForm.api_body || ''}
|
||||
responsePath={editForm.api_response_path || ''}
|
||||
retryEnabled={editForm.api_retry_enabled || false}
|
||||
headersAction={editForm.api_headers_action || 'retain'}
|
||||
paramsAction={editForm.api_params_action || 'retain'}
|
||||
onTest={/* editAPITest 使用当前编辑草稿发起临时 API 测试,不保存草稿。 */ () => testCardAPI({ url: editForm.api_url || '', method: editForm.api_method || 'GET', timeout_seconds: editForm.api_timeout || 10, headers: editForm.api_headers || undefined, params: editForm.api_params || undefined, content_type: editForm.api_content_type || 'application/json', body: editForm.api_body || undefined, response_path: editForm.api_response_path || undefined, retry_enabled: editForm.api_retry_enabled || false })}
|
||||
onChange={/* 当前回调把 API 请求编辑器字段写回编辑草稿。 */ (field, value) => setEditForm(/* currentUpdater 基于最新编辑草稿合并 API 字段。 */ current => ({
|
||||
...current,
|
||||
...(field === 'url' ? { api_url: String(value) } : {}),
|
||||
...(field === 'method' ? { api_method: value as 'GET' | 'POST' } : {}),
|
||||
...(field === 'timeout' ? { api_timeout: Number(value) } : {}),
|
||||
...(field === 'headers' ? { api_headers: String(value) } : {}),
|
||||
...(field === 'params' ? { api_params: String(value) } : {}),
|
||||
...(field === 'contentType' ? { api_content_type: String(value) } : {}),
|
||||
...(field === 'body' ? { api_body: String(value) } : {}),
|
||||
...(field === 'responsePath' ? { api_response_path: String(value) } : {}),
|
||||
...(field === 'retryEnabled' ? { api_retry_enabled: Boolean(value) } : {}),
|
||||
...(field === 'headersAction' ? { api_headers_action: value as 'retain' | 'replace' | 'clear' } : {}),
|
||||
...(field === 'paramsAction' ? { api_params_action: value as 'retain' | 'replace' | 'clear' } : {}),
|
||||
}))}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 固定文字配置 */}
|
||||
@@ -492,7 +468,7 @@ const CardList: React.FC = () => {
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">类型</label>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'data', content: '' })}
|
||||
@@ -517,22 +493,22 @@ const CardList: React.FC = () => {
|
||||
<ImageIcon className="w-5 h-5 mx-auto mb-1" />
|
||||
图片
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'api', content: '' })}
|
||||
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'api' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
|
||||
>
|
||||
<Globe className="w-5 h-5 mx-auto mb-1" />
|
||||
API 接口
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{addForm.type !== 'api' && <div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">
|
||||
{addForm.type === 'data' ? '库存内容(一行一个)' : addForm.type === 'text' ? '固定回复内容' : addForm.type === 'image' ? '图片 URL' : 'API 地址'}
|
||||
{addForm.type === 'data' ? '库存内容(一行一个)' : addForm.type === 'text' ? '固定回复内容' : '图片 URL'}
|
||||
</label>
|
||||
{addForm.type === 'api' ? (
|
||||
<input
|
||||
type="url"
|
||||
value={addForm.content}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAddForm({ ...addForm, content: e.target.value })}
|
||||
placeholder="https://api.example.com/get-code"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
/>
|
||||
) : addForm.type === 'image' ? (
|
||||
{addForm.type === 'image' ? (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
type="url"
|
||||
@@ -554,34 +530,35 @@ const CardList: React.FC = () => {
|
||||
{addForm.type === 'data' && (
|
||||
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-brand">{addForm.content.split('\n').filter(/* 当前回调处理集合中的单个元素。 */ line => line.trim()).length}</span> 条</p>
|
||||
)}
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
{addForm.type === 'api' && (
|
||||
<div className="border-t border-gray-100 pt-5 space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">请求方法</label>
|
||||
<select value={addForm.api_method} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_method: e.target.value as 'GET' | 'POST'})} className="w-full ios-input px-4 py-3 rounded-xl">
|
||||
<option value="GET">GET</option>
|
||||
<option value="POST">POST</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">超时时间(秒)</label>
|
||||
<input type="number" min="1" max="60" value={addForm.api_timeout} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_timeout: parseInt(e.target.value) || 10})} className="w-full ios-input px-4 py-3 rounded-xl" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">请求头(JSON)</label>
|
||||
<textarea value={addForm.api_headers} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_headers: e.target.value})} className="w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs" placeholder='{"Authorization":"Bearer token"}' />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">请求参数(JSON)</label>
|
||||
<textarea value={addForm.api_params} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_params: e.target.value})} className="w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs" placeholder='{"order_id":"{order_id}"}' />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<>
|
||||
<APIRequestBuilder
|
||||
url={addForm.content}
|
||||
method={addForm.api_method}
|
||||
timeout={addForm.api_timeout}
|
||||
headers={addForm.api_headers}
|
||||
params={addForm.api_params}
|
||||
contentType={addForm.api_content_type}
|
||||
body={addForm.api_body}
|
||||
responsePath={addForm.api_response_path}
|
||||
retryEnabled={addForm.api_retry_enabled}
|
||||
onTest={/* addAPITest 使用当前新增草稿发起临时 API 测试,不创建卡密。 */ () => testCardAPI({ url: addForm.content, method: addForm.api_method, timeout_seconds: addForm.api_timeout, headers: addForm.api_headers || undefined, params: addForm.api_params || undefined, content_type: addForm.api_content_type, body: addForm.api_body || undefined, response_path: addForm.api_response_path || undefined, retry_enabled: addForm.api_retry_enabled })}
|
||||
onChange={/* 当前回调把 API 请求编辑器字段写回新增草稿。 */ (field, value) => setAddForm(/* currentUpdater 基于最新新增草稿合并 API 字段。 */ current => ({
|
||||
...current,
|
||||
...(field === 'url' ? { content: String(value) } : {}),
|
||||
...(field === 'method' ? { api_method: value as 'GET' | 'POST' } : {}),
|
||||
...(field === 'timeout' ? { api_timeout: Number(value) } : {}),
|
||||
...(field === 'headers' ? { api_headers: String(value) } : {}),
|
||||
...(field === 'params' ? { api_params: String(value) } : {}),
|
||||
...(field === 'contentType' ? { api_content_type: String(value) } : {}),
|
||||
...(field === 'body' ? { api_body: String(value) } : {}),
|
||||
...(field === 'responsePath' ? { api_response_path: String(value) } : {}),
|
||||
...(field === 'retryEnabled' ? { api_retry_enabled: Boolean(value) } : {}),
|
||||
}))}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4">
|
||||
|
||||
@@ -23,6 +23,14 @@ export interface AddCardForm {
|
||||
api_headers: string;
|
||||
// api_params 是 API 请求参数 JSON 文本。
|
||||
api_params: string;
|
||||
// api_content_type 是 API 请求正文的 Content-Type。
|
||||
api_content_type: string;
|
||||
// api_body 是 API 请求正文 JSON 文本或键值对象 JSON 文本。
|
||||
api_body: string;
|
||||
// api_response_path 是 API 响应提取路径。
|
||||
api_response_path: string;
|
||||
// api_retry_enabled 表示是否启用带幂等键的重试。
|
||||
api_retry_enabled: boolean;
|
||||
}
|
||||
|
||||
// EditCardForm 描述编辑卡密组时的表单字段和 API 扩展字段。
|
||||
@@ -37,6 +45,18 @@ export type EditCardForm = Partial<Card> & {
|
||||
api_headers?: string;
|
||||
// api_params 是编辑中的 API 请求参数 JSON 文本。
|
||||
api_params?: string;
|
||||
// api_content_type 是编辑中的 API 请求正文 Content-Type。
|
||||
api_content_type?: string;
|
||||
// api_body 是编辑中的 API 请求正文 JSON 文本或键值对象 JSON 文本。
|
||||
api_body?: string;
|
||||
// api_response_path 是编辑中的 API 响应提取路径。
|
||||
api_response_path?: string;
|
||||
// api_retry_enabled 表示编辑中是否启用带幂等键的重试。
|
||||
api_retry_enabled?: boolean;
|
||||
// api_headers_action 保存请求头模板的三态变更意图。
|
||||
api_headers_action?: 'retain' | 'replace' | 'clear';
|
||||
// api_params_action 保存请求参数模板的三态变更意图。
|
||||
api_params_action?: 'retain' | 'replace' | 'clear';
|
||||
};
|
||||
|
||||
// CardBatchTab 表示批量导入弹窗当前展示的操作页签。
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { MutationIDResponse,NotificationBinding,NotificationChannel,NotificationChannelResponse,NotificationEventType,OperationResponse,SystemSettings } from './models';
|
||||
import { normalizeSystemSettingsUpdate } from '../../../shared/api-contract/settings';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
|
||||
export type * from './models';
|
||||
@@ -128,4 +129,4 @@ export const getSystemSettings = async (options?: RequestControlOptions): Promis
|
||||
};
|
||||
|
||||
/** 保存通知 SMTP 编辑器提交的系统设置。 */
|
||||
export const updateSystemSettings = async (settings: Partial<SystemSettings>, options?: RequestControlOptions): Promise<OperationResponse> => runContractRequest(/* signal 控制系统设置更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/settings/system', { body: settings as never, signal }), options);
|
||||
export const updateSystemSettings = async (settings: Partial<SystemSettings>, options?: RequestControlOptions): Promise<OperationResponse> => runContractRequest(/* signal 控制系统设置更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/settings/system', { body: normalizeSystemSettingsUpdate(settings), signal }), options);
|
||||
@@ -108,11 +108,19 @@ export interface Card {
|
||||
/** API 卡券请求方法。 */
|
||||
method: 'GET' | 'POST';
|
||||
/** API 请求超时时间。 */
|
||||
timeout?: number;
|
||||
/** API 请求头 JSON。 */
|
||||
headers?: string;
|
||||
/** API 请求参数 JSON。 */
|
||||
params?: string;
|
||||
timeout_seconds: number;
|
||||
/** API 响应提取路径。 */
|
||||
response_path?: string;
|
||||
/** 是否启用幂等重试。 */
|
||||
retry_enabled: boolean;
|
||||
/** 是否配置了请求头模板;具体值不会进入前端。 */
|
||||
headers_configured: boolean;
|
||||
/** 是否配置了请求参数模板;具体值不会进入前端。 */
|
||||
params_configured: boolean;
|
||||
/** 配置是否可用于规则发货。 */
|
||||
ready: boolean;
|
||||
/** 配置无效时的脱敏错误说明。 */
|
||||
validation_error?: string;
|
||||
};
|
||||
// 图片类型
|
||||
/** 图片卡券地址。 */
|
||||
|
||||
@@ -835,7 +835,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
className="w-full ios-input px-3 py-2.5 rounded-lg"
|
||||
>
|
||||
<option value="">请选择卡密库存</option>
|
||||
{cards.filter(/* 当前回调处理集合中的单个元素。 */ card => card.enabled && card.type !== 'api').map(/* 当前回调处理集合中的单个元素。 */ card => (
|
||||
{cards.filter(/* 当前回调处理集合中的单个元素。 */ card => card.enabled && (card.type !== 'api' || card.api_config?.ready === true)).map(/* 当前回调处理集合中的单个元素。 */ card => (
|
||||
<option key={card.id} value={card.id}>{card.name}</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { OperationResponse,SystemSettings } from './models';
|
||||
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
|
||||
import { normalizeSystemSettingsUpdate,SENSITIVE_SYSTEM_SETTING_KEYS } from '../../../shared/api-contract/settings';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
import type { SystemSettingsUpdate } from '../../../shared/api-contract/settings';
|
||||
export type * from './models';
|
||||
export { normalizeSystemSettingsUpdate } from '../../../shared/api-contract/settings';
|
||||
export type { SensitiveSettingChange,SystemSettingsUpdate } from '../../../shared/api-contract/settings';
|
||||
|
||||
/** 设置页面使用的会话状态传输契约,避免跨 feature 依赖。 */
|
||||
export interface SettingsSessionStatusResponse {
|
||||
@@ -17,43 +21,6 @@ export interface SettingsSessionStatusResponse {
|
||||
is_admin?: boolean;
|
||||
}
|
||||
|
||||
/** 敏感系统设置的显式三态变更命令。 */
|
||||
export type SensitiveSettingChange = {
|
||||
/** 敏感值的保存策略。 */
|
||||
action: 'retain' | 'replace' | 'clear';
|
||||
/** replace 策略需要保存的新值,只存在于提交请求中。 */
|
||||
value?: string;
|
||||
};
|
||||
|
||||
/** 系统设置更新请求,将普通配置与敏感命令分开传输。 */
|
||||
export type SystemSettingsUpdate = {
|
||||
/** 非敏感配置字段。 */
|
||||
values?: Record<string, string | number | boolean>;
|
||||
/** 由服务端解释的敏感值变更命令。 */
|
||||
secrets?: Record<string, SensitiveSettingChange>;
|
||||
};
|
||||
|
||||
/** SENSITIVE_SYSTEM_SETTING_KEYS 标识不得写入普通 values 的秘密键。 */
|
||||
const SENSITIVE_SYSTEM_SETTING_KEYS = new Set(['ai_api_key', 'smtp_password', 'qq_reply_secret_key', 'captcha.remote_secret_key']);
|
||||
|
||||
/** 将历史设置草稿转换为服务端要求的普通值与敏感命令结构。 */
|
||||
const normalizeSystemSettingsUpdate = (settings: Partial<SystemSettings> | SystemSettingsUpdate): SystemSettingsUpdate => {
|
||||
if ('values' in settings || 'secrets' in settings) return settings as SystemSettingsUpdate;
|
||||
// values 保存普通设置,永不容纳秘密文本。
|
||||
const values: Record<string, string | number | boolean> = {};
|
||||
// secrets 保存服务端需要独立处理的敏感设置命令。
|
||||
const secrets: Record<string, SensitiveSettingChange> = {};
|
||||
for (const /* key、value 是当前待分流的设置键和值。 */ [key, value] of Object.entries(settings)) {
|
||||
if (value === undefined || value === null) continue;
|
||||
if (SENSITIVE_SYSTEM_SETTING_KEYS.has(key)) {
|
||||
secrets[key] = value === '' ? { action: 'clear' } : { action: 'replace', value: String(value) };
|
||||
continue;
|
||||
}
|
||||
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') values[key] = value;
|
||||
}
|
||||
return Object.keys(secrets).length > 0 ? { values, secrets } : values;
|
||||
};
|
||||
|
||||
/** 将服务端可兼容的字符串和数值设置归一为 UI 可消费的只读契约。 */
|
||||
const normalizeSettings = (settings: Record<string, unknown>): SystemSettings => {
|
||||
// result 是不修改原始响应的设置副本。
|
||||
@@ -69,6 +36,10 @@ const normalizeSettings = (settings: Record<string, unknown>): SystemSettings =>
|
||||
const days = Number(result.renewal_log_retention_days);
|
||||
result.renewal_log_retention_days = Number.isFinite(days) ? days : 10;
|
||||
}
|
||||
if ('outbound_http_public_only' in result) {
|
||||
// publicOnly 保存统一出站策略的布尔状态,兼容旧服务端返回的字符串。
|
||||
result.outbound_http_public_only = result.outbound_http_public_only === true || result.outbound_http_public_only === 'true';
|
||||
}
|
||||
return result as SystemSettings;
|
||||
};
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface SystemSettings {
|
||||
log_level?: 'debug' | 'info' | 'warn' | 'error' | string;
|
||||
/** 服务端日志格式。 */
|
||||
log_format?: 'text' | 'json' | string;
|
||||
/** 是否阻止用户配置的服务端 HTTP 请求访问内网地址。 */
|
||||
outbound_http_public_only?: boolean;
|
||||
/** 续期日志保留天数。 */
|
||||
renewal_log_retention_days?: number;
|
||||
/** 远程验证码服务地址。 */
|
||||
|
||||
@@ -126,6 +126,14 @@ const Settings: React.FC = () => {
|
||||
/>
|
||||
<p className="text-xs text-gray-500">0 表示不自动清理续期日志</p>
|
||||
</div>
|
||||
|
||||
<label className="flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4 cursor-pointer">
|
||||
<input type="checkbox" className="mt-1" checked={settings.outbound_http_public_only || false} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setSettings({ ...settings, outbound_http_public_only: event.target.checked })} />
|
||||
<span>
|
||||
<span className="block text-sm font-bold text-amber-900">限制用户配置的 HTTP 出站请求只能访问公网</span>
|
||||
<span className="mt-1 block text-xs leading-5 text-amber-800">开启后会同时约束 API 发货、AI、HTTP 通知、远程图片和远程滑块服务;保存后立即生效,可能使内网服务不可用。</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -3,13 +3,105 @@ import { execFileSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import ts from 'typescript';
|
||||
|
||||
// frontendRoot 是前端源码根目录,所有前端契约和静态门禁均以它解析相对路径。
|
||||
const frontendRoot = path.resolve(import.meta.dirname, '..');
|
||||
// repositoryRoot 是包含 OpenAPI 单一契约源的仓库根目录。
|
||||
const repositoryRoot = path.resolve(frontendRoot, '..');
|
||||
// temporaryDirectory 保存本次生成的临时 TypeScript 契约,校验完成后必须删除。
|
||||
const temporaryDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'ydisks-openapi-'));
|
||||
// temporarySchema 是临时 OpenAPI 生成文件的绝对路径。
|
||||
const temporarySchema = path.join(temporaryDirectory, 'schema.ts');
|
||||
// checkedInSchema 是仓库中受版本控制的 OpenAPI 生成文件。
|
||||
const checkedInSchema = path.join(frontendRoot, 'shared', 'api-contract', 'generated', 'schema.ts');
|
||||
// generator 是固定依赖安装后实际执行的 OpenAPI TypeScript 生成器。
|
||||
const generator = path.join(frontendRoot, 'node_modules', 'openapi-typescript', 'bin', 'cli.js');
|
||||
// featureRoot 是允许通过 feature adapter 写入系统设置的源码树。
|
||||
const featureRoot = path.join(frontendRoot, 'app', 'features');
|
||||
// systemSettingsPath 是必须经由秘密归一器构造请求体的版本化系统设置写入端点。
|
||||
const systemSettingsPath = '/api/v1/settings/system';
|
||||
|
||||
// listFeatureSourceFiles 递归收集 feature 内需要接受系统设置写入门禁的生产 TypeScript 文件。
|
||||
const listFeatureSourceFiles = directory => {
|
||||
// entries 保存当前目录的子项,用于继续递归或收集源码文件。
|
||||
const entries = fs.readdirSync(directory, { withFileTypes: true });
|
||||
// files 保存当前目录及其后代目录中待检查的生产源码绝对路径。
|
||||
const files = [];
|
||||
for (const entry of entries) {
|
||||
// entryPath 是当前目录项的绝对路径。
|
||||
const entryPath = path.join(directory, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
files.push(...listFeatureSourceFiles(entryPath));
|
||||
continue;
|
||||
}
|
||||
if (entry.isFile() && /(?<!\.test)\.(ts|tsx)$/.test(entry.name)) files.push(entryPath);
|
||||
}
|
||||
return files;
|
||||
};
|
||||
|
||||
// importsSharedSettingsNormalizer 判断源码是否从共享契约层导入真正的系统设置秘密归一器。
|
||||
const importsSharedSettingsNormalizer = sourceFile => sourceFile.statements.some(statement => {
|
||||
if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) return false;
|
||||
if (!statement.moduleSpecifier.text.endsWith('/shared/api-contract/settings')) return false;
|
||||
// importClause 保存当前 import 的默认、命名或 namespace 导入定义。
|
||||
const importClause = statement.importClause;
|
||||
if (!importClause || !importClause.namedBindings || !ts.isNamedImports(importClause.namedBindings)) return false;
|
||||
return importClause.namedBindings.elements.some(element => element.name.text === 'normalizeSystemSettingsUpdate');
|
||||
});
|
||||
|
||||
// isSystemSettingsWrite 判断调用是否直接写入系统设置端点;读取和其他端点不受此规则影响。
|
||||
const isSystemSettingsWrite = node => {
|
||||
if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)) return false;
|
||||
if (node.expression.name.text !== 'PUT' || !ts.isIdentifier(node.expression.expression) || node.expression.expression.text !== 'contractClient') return false;
|
||||
// endpointArgument 是 contractClient.PUT 的首个路径参数。
|
||||
const endpointArgument = node.arguments[0];
|
||||
return ts.isStringLiteral(endpointArgument) && endpointArgument.text === systemSettingsPath;
|
||||
};
|
||||
|
||||
// usesSharedSettingsNormalizer 判断写入选项中的 body 是否直接由共享秘密归一器生成,禁止表单对象和 as never 绕过类型。
|
||||
const usesSharedSettingsNormalizer = node => {
|
||||
// requestOptions 是 PUT 调用的第二个参数,必须是包含 body 的对象字面量。
|
||||
const requestOptions = node.arguments[1];
|
||||
if (!requestOptions || !ts.isObjectLiteralExpression(requestOptions)) return false;
|
||||
// bodyProperty 是写入请求体字段;不存在即无法满足系统设置的显式秘密命令契约。
|
||||
const bodyProperty = requestOptions.properties.find(property => ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === 'body');
|
||||
if (!bodyProperty || !ts.isPropertyAssignment(bodyProperty) || !ts.isCallExpression(bodyProperty.initializer)) return false;
|
||||
// normalizerCall 是生成请求体的调用,只接受共享函数的直接调用,避免本地同名包装绕过门禁。
|
||||
const normalizerCall = bodyProperty.initializer;
|
||||
return ts.isIdentifier(normalizerCall.expression) && normalizerCall.expression.text === 'normalizeSystemSettingsUpdate';
|
||||
};
|
||||
|
||||
// verifySystemSettingsWriteBoundary 强制所有 feature 的系统设置 PUT 经过共享秘密归一器,避免敏感字段落入普通 values 或顶层表单对象。
|
||||
const verifySystemSettingsWriteBoundary = () => {
|
||||
// violations 保存每个不符合系统设置敏感命令边界的源码位置。
|
||||
const violations = [];
|
||||
for (const filePath of listFeatureSourceFiles(featureRoot)) {
|
||||
// sourceText 是待扫描的 TypeScript 源码文本。
|
||||
const sourceText = fs.readFileSync(filePath, 'utf8');
|
||||
// sourceFile 是用于可靠识别调用、对象字段和类型断言的 TypeScript AST。
|
||||
const sourceFile = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true);
|
||||
// hasSystemSettingsWrite 标记当前文件是否直接写入系统设置端点,用于校验共享函数的实际导入。
|
||||
let hasSystemSettingsWrite = false;
|
||||
// visit 递归检查当前节点及其子节点中的系统设置写入调用。
|
||||
const visit = node => {
|
||||
if (isSystemSettingsWrite(node)) {
|
||||
hasSystemSettingsWrite = true;
|
||||
if (!usesSharedSettingsNormalizer(node)) {
|
||||
// lineNumber 是违规 PUT 调用在源码中的一基行号,供修复时精确定位。
|
||||
const lineNumber = sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
||||
violations.push(`${path.relative(frontendRoot, filePath)}:${lineNumber} 必须使用 normalizeSystemSettingsUpdate 构造 /api/v1/settings/system 请求体`);
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
};
|
||||
visit(sourceFile);
|
||||
if (hasSystemSettingsWrite && !importsSharedSettingsNormalizer(sourceFile)) {
|
||||
violations.push(`${path.relative(frontendRoot, filePath)} 必须从 shared/api-contract/settings 导入 normalizeSystemSettingsUpdate`);
|
||||
}
|
||||
}
|
||||
if (violations.length > 0) throw new Error(`系统设置敏感命令门禁失败:\n${violations.join('\n')}`);
|
||||
};
|
||||
|
||||
try {
|
||||
execFileSync(process.execPath, [generator, path.join(repositoryRoot, 'api', 'openapi.yaml'), '-o', temporarySchema], {
|
||||
@@ -21,6 +113,7 @@ try {
|
||||
if (!generatedContent.equals(checkedInContent)) {
|
||||
throw new Error('生成的 OpenAPI TypeScript 类型与提交产物不一致;请运行 npm run api:generate --prefix frontend。');
|
||||
}
|
||||
verifySystemSettingsWriteBoundary();
|
||||
} finally {
|
||||
fs.rmSync(temporaryDirectory, { recursive: true, force: true });
|
||||
}
|
||||
@@ -541,6 +541,23 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/cards/test-api": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/** postApiV1CardsTestApi */
|
||||
post: operations["postApiV1CardsTestApi"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/cards/{card_id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -2220,7 +2237,7 @@ export interface components {
|
||||
name?: string;
|
||||
/** @enum {string} */
|
||||
type?: "api" | "text" | "data" | "image";
|
||||
api_config?: string;
|
||||
api_config?: components["schemas"]["APICardConfigMutation"] | string;
|
||||
text_content?: string;
|
||||
data_content?: string;
|
||||
image_url?: string;
|
||||
@@ -2262,7 +2279,7 @@ export interface components {
|
||||
name: string;
|
||||
/** @enum {string} */
|
||||
type: "api" | "text" | "data" | "image";
|
||||
api_config: string;
|
||||
api_config?: components["schemas"]["APICardConfigResponse"] | null;
|
||||
text_content: string;
|
||||
data_content: string;
|
||||
image_url: string;
|
||||
@@ -2274,6 +2291,59 @@ export interface components {
|
||||
spec_value: string;
|
||||
user_id?: number;
|
||||
};
|
||||
APICardConfigMutation: {
|
||||
/** Format: uri */
|
||||
url: string;
|
||||
/**
|
||||
* @default GET
|
||||
* @enum {string}
|
||||
*/
|
||||
method: "GET" | "POST";
|
||||
/** @default 10 */
|
||||
timeout_seconds: number;
|
||||
headers?: {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
params?: {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
body?: {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
/** @default application/json */
|
||||
content_type: string;
|
||||
/** @enum {string} */
|
||||
headers_action?: "retain" | "replace" | "clear";
|
||||
/** @enum {string} */
|
||||
params_action?: "retain" | "replace" | "clear";
|
||||
response_path?: string;
|
||||
retry_enabled?: boolean;
|
||||
};
|
||||
APICardConfigResponse: {
|
||||
url: string;
|
||||
/** @enum {string} */
|
||||
method: "GET" | "POST";
|
||||
timeout_seconds: number;
|
||||
content_type: string;
|
||||
response_path?: string;
|
||||
retry_enabled: boolean;
|
||||
headers_configured: boolean;
|
||||
params_configured: boolean;
|
||||
ready: boolean;
|
||||
validation_error?: string;
|
||||
};
|
||||
CardAPITestRequest: {
|
||||
api_config: components["schemas"]["APICardConfigMutation"] | string;
|
||||
};
|
||||
CardAPITestResponse: {
|
||||
/** @enum {string} */
|
||||
status: "success" | "failed";
|
||||
status_code: number;
|
||||
response_content_type: string;
|
||||
response_fields: string[];
|
||||
extracted_value?: string;
|
||||
response_preview?: string;
|
||||
};
|
||||
ItemListResponse: {
|
||||
id: number;
|
||||
cookie_id: string;
|
||||
@@ -2502,6 +2572,11 @@ export interface components {
|
||||
[key: string]: components["schemas"]["SecretSettingChange"];
|
||||
};
|
||||
};
|
||||
SystemSettingSingleUpdateRequest: {
|
||||
value: string;
|
||||
/** @enum {string} */
|
||||
action?: "retain" | "replace" | "clear";
|
||||
};
|
||||
SystemSettingsResponse: {
|
||||
[key: string]: string | number | boolean;
|
||||
};
|
||||
@@ -5673,6 +5748,57 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
postApiV1CardsTestApi: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["CardAPITestRequest"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description 测试完成 */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["CardAPITestResponse"];
|
||||
};
|
||||
};
|
||||
/** @description 统一错误响应 */
|
||||
400: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ErrorResponse"];
|
||||
};
|
||||
};
|
||||
/** @description 统一错误响应 */
|
||||
401: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ErrorResponse"];
|
||||
};
|
||||
};
|
||||
/** @description 统一错误响应 */
|
||||
503: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ErrorResponse"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
getApiV1CardsBycard_id: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -12119,7 +12245,11 @@ export interface operations {
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["SystemSettingSingleUpdateRequest"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description 成功 */
|
||||
200: {
|
||||
@@ -12127,7 +12257,7 @@ export interface operations {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ApiResponse"];
|
||||
"application/json": components["schemas"]["OperationResponse"];
|
||||
};
|
||||
};
|
||||
/** @description 统一错误响应 */
|
||||
|
||||
@@ -1,7 +1,49 @@
|
||||
// settings 只公开 OpenAPI 生成的设置传输类型;表单状态属于 settings feature。
|
||||
// settings 只公开 OpenAPI 生成的设置传输类型和跨 feature 共用的更新契约;表单状态属于各自 feature。
|
||||
import type { components } from './generated/schema';
|
||||
|
||||
/** SystemSettingsTransport 表示受约束动态键的设置响应。 */
|
||||
export type SystemSettingsTransport = components['schemas']['SystemSettingsResponse'];
|
||||
/** AIModelsTransport 表示生成的模型发现响应。 */
|
||||
export type AIModelsTransport = components['schemas']['AIModelsResponse'];
|
||||
|
||||
/** 敏感系统设置的显式三态变更命令。 */
|
||||
export type SensitiveSettingChange = {
|
||||
/** 敏感值的保存策略。 */
|
||||
action: 'retain' | 'replace' | 'clear';
|
||||
/** replace 策略需要保存的新值,只存在于提交请求中。 */
|
||||
value?: string;
|
||||
};
|
||||
|
||||
/** 系统设置更新请求,将普通配置与敏感命令分开传输。 */
|
||||
export type SystemSettingsUpdate = {
|
||||
/** 非敏感配置字段。 */
|
||||
values?: Record<string, string | number | boolean>;
|
||||
/** 由服务端解释的敏感值变更命令。 */
|
||||
secrets?: Record<string, SensitiveSettingChange>;
|
||||
};
|
||||
|
||||
/** SENSITIVE_SYSTEM_SETTING_KEYS 标识不得写入普通 values 的秘密键。 */
|
||||
export const SENSITIVE_SYSTEM_SETTING_KEYS = new Set([
|
||||
'ai_api_key',
|
||||
'smtp_password',
|
||||
'qq_reply_secret_key',
|
||||
'captcha.remote_secret_key',
|
||||
]);
|
||||
|
||||
/** 将各 feature 的设置草稿转换为服务端要求的普通值与敏感命令结构。 */
|
||||
export const normalizeSystemSettingsUpdate = (settings: Record<string, string | number | boolean | undefined> | SystemSettingsUpdate): SystemSettingsUpdate => {
|
||||
if ('values' in settings || 'secrets' in settings) return settings as SystemSettingsUpdate;
|
||||
// values 保存普通设置,永不容纳秘密文本。
|
||||
const values: Record<string, string | number | boolean> = {};
|
||||
// secrets 保存服务端需要独立处理的敏感设置命令。
|
||||
const secrets: Record<string, SensitiveSettingChange> = {};
|
||||
for (const /* key、value 是当前待分流的设置键和值。 */ [key, value] of Object.entries(settings)) {
|
||||
if (value === undefined || value === null) continue;
|
||||
if (SENSITIVE_SYSTEM_SETTING_KEYS.has(key)) {
|
||||
secrets[key] = value === '' ? { action: 'clear' } : { action: 'replace', value: String(value) };
|
||||
continue;
|
||||
}
|
||||
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') values[key] = value;
|
||||
}
|
||||
return Object.keys(secrets).length > 0 ? { values, secrets } : values;
|
||||
};
|
||||
@@ -163,6 +163,7 @@ func NewRuntimeBundle(store *db.Store, bm *browser.Manager, logger *slog.Logger)
|
||||
autoCenter := automation.NewWithDependencies(store, automationSenders, logger, automation.CenterDependencies{
|
||||
OrderDetailFetcher: runtimeAdapter,
|
||||
Notifier: notifier,
|
||||
APICardFetcher: newAPIDeliveryClient(store, logger),
|
||||
})
|
||||
runtimeAdapter.chat = chatService
|
||||
runtimeAdapter.automation = autoCenter
|
||||
|
||||
@@ -313,7 +313,8 @@ func (a *Adapter) HandleSystemEvent(ctx context.Context, task automation.Task) e
|
||||
if a.automation == nil {
|
||||
return nil
|
||||
}
|
||||
a.logger.Info("系统自动化事件", "account", task.AccountID, "trigger", task.TriggerType, "order_id", task.OrderID)
|
||||
// 入口日志只表示收到平台卡片,不代表已经匹配规则或执行动作;统一使用 DEBUG 避免半成品和重复推送污染业务 INFO 日志。
|
||||
a.logger.Debug("收到系统自动化事件", "account", task.AccountID, "trigger", task.TriggerType, "order_id", task.OrderID)
|
||||
return a.automation.HandleTask(ctx, task)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
@@ -382,6 +384,36 @@ func TestHandleSystemEvent_UninjectedSafe(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleSystemEventIngressUsesDebugLog 验证系统卡片入口日志不会把尚未匹配规则的事件伪装成业务 INFO。
|
||||
func TestHandleSystemEventIngressUsesDebugLog(t *testing.T) {
|
||||
// store、cleanup 保存自动化中心测试数据库及清理函数。
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// logBuffer 收集适配器入口日志,用于检查日志级别而不依赖全局日志输出。
|
||||
var logBuffer bytes.Buffer
|
||||
// logger 将 DEBUG 及以上日志写入内存,便于断言空订单和完整订单事件的入口记录。
|
||||
logger := slog.New(slog.NewTextHandler(&logBuffer, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
||||
// adapter 是装配自动化中心后的事件转发适配器。
|
||||
adapter := New(store, nil, logger)
|
||||
adapter.automation = automation.New(store, nil, logger)
|
||||
// firstErr 是空订单创建卡片进入自动化中心后不应产生的处理错误。
|
||||
if firstErr := adapter.HandleSystemEvent(context.Background(), automation.Task{AccountID: "cid", TriggerType: automation.TriggerOrderCreated}); firstErr != nil {
|
||||
t.Fatal(firstErr)
|
||||
}
|
||||
// secondErr 是带订单 ID 的无规则付款卡片进入自动化中心后不应产生的处理错误。
|
||||
if secondErr := adapter.HandleSystemEvent(context.Background(), automation.Task{AccountID: "cid", TriggerType: automation.TriggerOrderPaid, OrderID: "order-log"}); secondErr != nil {
|
||||
t.Fatal(secondErr)
|
||||
}
|
||||
// output 是入口和中心日志的文本结果;入口事件必须以 DEBUG 记录,不得出现旧的 INFO 文案。
|
||||
output := logBuffer.String()
|
||||
if !strings.Contains(output, "msg=收到系统自动化事件") || !strings.Contains(output, "level=DEBUG") {
|
||||
t.Fatalf("入口事件应记录为 DEBUG: %s", output)
|
||||
}
|
||||
if strings.Contains(output, "level=INFO msg=系统自动化事件") {
|
||||
t.Fatalf("入口事件不应继续记录旧 INFO 日志: %s", output)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchOrderDetail_LocalHitShortCircuits 本地订单字段齐全时不启动浏览器。
|
||||
func TestFetchOrderDetail_LocalHitShortCircuits(t *testing.T) {
|
||||
// store、cleanup 用于本次流程后续判断的store、cleanup
|
||||
|
||||
@@ -25,7 +25,7 @@ type AIModelClient struct {
|
||||
func NewAIModelClient() *AIModelClient {
|
||||
// client 保存生产环境使用的模型目录客户端。
|
||||
client := &AIModelClient{newHTTPClient: func(baseURL string) (*http.Client, error) {
|
||||
return netguard.TrustedEndpointHTTPClient(baseURL, 20*time.Second)
|
||||
return netguard.ConfiguredEndpointHTTPClient(baseURL, 20*time.Second)
|
||||
}}
|
||||
return client
|
||||
}
|
||||
|
||||
@@ -0,0 +1,636 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/netguard"
|
||||
)
|
||||
|
||||
// apiDeliveryResponseLimit 是 API 发货允许读取的最大响应体大小,避免远端响应耗尽服务端内存。
|
||||
const apiDeliveryResponseLimit int64 = 1 << 20
|
||||
|
||||
// apiTestPreviewLimit 限制测试响应返回给浏览器的预览长度,避免把大响应或敏感内容扩散到前端。
|
||||
const apiTestPreviewLimit = 4096
|
||||
|
||||
// apiDeliveryRetryLimit 是开启幂等重试后允许的总请求次数。
|
||||
const apiDeliveryRetryLimit = 3
|
||||
|
||||
// apiDeliveryRetryGaps 是第 2、3 次 API 发货请求前的退避间隔;测试可临时替换它。
|
||||
var apiDeliveryRetryGaps = []time.Duration{time.Second, 2 * time.Second}
|
||||
|
||||
// apiDeliveryClient 实现自动化中心要求的普通 API 卡发货能力。
|
||||
type apiDeliveryClient struct {
|
||||
// store 读取模板变量所需的商品详情,不读取账号凭证明文。
|
||||
store *db.Store
|
||||
// logger 只记录请求元数据,不记录 URL 查询串、请求模板或响应内容。
|
||||
logger *slog.Logger
|
||||
// client 是共享的策略 HTTP 客户端;单次超时由请求 Context 控制,避免每个单位创建 Transport。
|
||||
client *http.Client
|
||||
// clientOnce 保证测试构造的零值客户端只初始化一次共享 Transport。
|
||||
clientOnce sync.Once
|
||||
}
|
||||
|
||||
// newAPIDeliveryClient 创建 API 发货适配器。
|
||||
func newAPIDeliveryClient(store *db.Store, logger *slog.Logger) automation.APICardFetcher {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &apiDeliveryClient{store: store, logger: logger, client: netguard.ConfiguredHTTPClient(0)}
|
||||
}
|
||||
|
||||
// NewAPICardTester 创建卡密 API 测试适配器;它与自动发货共享出站策略但不会执行重试或写入库存。
|
||||
func NewAPICardTester(store *db.Store, logger *slog.Logger) cardsapp.APIRequestTester {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &apiDeliveryClient{store: store, logger: logger, client: netguard.ConfiguredHTTPClient(0)}
|
||||
}
|
||||
|
||||
// Test 发送一次不带真实订单数据的 API 测试请求,并返回状态和响应结构诊断。
|
||||
func (c *apiDeliveryClient) Test(ctx context.Context, input cardsapp.APIRequestTestInput) (cardsapp.APIRequestTestResult, error) {
|
||||
// config、err 分别是规范化后的临时测试配置及其输入校验错误。
|
||||
config, err := cardsapp.ParseAPIConfig(input.Config)
|
||||
if err != nil {
|
||||
return cardsapp.APIRequestTestResult{}, err
|
||||
}
|
||||
// variables 是测试环境稳定占位符,绝不使用真实订单、买家或账号数据。
|
||||
variables := map[string]string{
|
||||
"{order_id}": "test-order", "{item_id}": "test-item", "{buyer_id}": "test-buyer",
|
||||
"{chat_id}": "test-chat", "{account_id}": "test-account", "{cookie_id}": "test-account",
|
||||
"{spec_name}": "", "{spec_value}": "", "{quantity}": "1", "{order_quantity}": "1",
|
||||
"{amount}": "0", "{order_amount}": "0", "{item_detail}": "", "{trigger_type}": "test",
|
||||
"{timestamp}": time.Now().UTC().Format(time.RFC3339Nano), "{delivery_unit_index}": "1",
|
||||
"{delivery_total_count}": "1", "{idempotency_key}": "test-idempotency-key",
|
||||
}
|
||||
// headers、params 分别是已用测试变量替换的请求头和查询参数。
|
||||
headers := replaceAPIJSONMap(config.Headers, variables)
|
||||
// params 是已用测试变量替换的查询参数。
|
||||
params := replaceAPIJSONMap(config.Params, variables)
|
||||
// requestURL、err 分别是待请求 URL 和解析错误;错误文本不回显原始地址。
|
||||
requestURL, err := url.Parse(config.URL)
|
||||
if err != nil {
|
||||
return cardsapp.APIRequestTestResult{}, errors.New("API 地址无效")
|
||||
}
|
||||
if config.Method == http.MethodGet {
|
||||
// query 保存基础地址与模板参数合并后的查询字符串。
|
||||
query := requestURL.Query()
|
||||
// key、value 分别是查询字段名称和已替换的字段值。
|
||||
for key, value := range params {
|
||||
query.Set(key, apiJSONScalar(value))
|
||||
}
|
||||
requestURL.RawQuery = query.Encode()
|
||||
}
|
||||
// bodyValues 是已替换的正文模板;为空时沿用历史 Params 正文兼容规则。
|
||||
bodyValues := replaceAPIJSONMap(config.Body, variables)
|
||||
if len(bodyValues) == 0 {
|
||||
bodyValues = params
|
||||
}
|
||||
// body、err 分别是按 Content-Type 编码后的正文和编码错误。
|
||||
body, err := encodeAPIDeliveryBody(bodyValues, config.ContentType)
|
||||
if err != nil {
|
||||
return cardsapp.APIRequestTestResult{}, fmt.Errorf("编码 API 请求参数: %w", err)
|
||||
}
|
||||
// requestCtx、cancel 限制本次测试请求的最长耗时,并在函数返回时释放计时器。
|
||||
requestCtx, cancel := context.WithTimeout(ctx, time.Duration(config.Timeout)*time.Second)
|
||||
defer cancel()
|
||||
// requestBody 仅用于 POST 的可重复读取正文,GET 请求保持为空。
|
||||
var requestBody io.Reader
|
||||
if config.Method == http.MethodPost {
|
||||
requestBody = bytes.NewReader(body)
|
||||
}
|
||||
// request、err 分别是受上下文控制的远端请求和构造错误。
|
||||
request, err := http.NewRequestWithContext(requestCtx, config.Method, requestURL.String(), requestBody)
|
||||
if err != nil {
|
||||
return cardsapp.APIRequestTestResult{}, errors.New("API 请求地址无效")
|
||||
}
|
||||
// key、value 分别是请求头名称和经过模板替换的字段值。
|
||||
for key, value := range headers {
|
||||
request.Header.Set(key, apiJSONScalar(value))
|
||||
}
|
||||
if config.Method == http.MethodPost && request.Header.Get("Content-Type") == "" {
|
||||
request.Header.Set("Content-Type", config.ContentType)
|
||||
}
|
||||
// response、err 分别是远端响应和不含请求秘密的网络错误。
|
||||
response, err := c.httpClient().Do(request)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return cardsapp.APIRequestTestResult{}, ctx.Err()
|
||||
}
|
||||
return cardsapp.APIRequestTestResult{}, errors.New("API 测试请求失败")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
// rawBody、err 分别是受 1 MiB 限制的响应内容和读取错误。
|
||||
rawBody, err := readAPIDeliveryBody(response.Body)
|
||||
if err != nil {
|
||||
return cardsapp.APIRequestTestResult{Status: "failed", StatusCode: response.StatusCode, ResponseContentType: response.Header.Get("Content-Type")}, err
|
||||
}
|
||||
// result 是返回给前端的非敏感状态、类型和限长响应预览。
|
||||
result := cardsapp.APIRequestTestResult{Status: "success", StatusCode: response.StatusCode, ResponseContentType: response.Header.Get("Content-Type"), ResponsePreview: truncateAPITestPreview(string(rawBody))}
|
||||
if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
|
||||
result.Status = "failed"
|
||||
return result, nil
|
||||
}
|
||||
// document 只在当前函数内持有 JSON 响应,用于字段名和路径提取。
|
||||
var document any
|
||||
// decoder 使用 JSON Number 以保持卡密等大整数的原始精度。
|
||||
decoder := json.NewDecoder(bytes.NewReader(rawBody))
|
||||
decoder.UseNumber()
|
||||
if decoder.Decode(&document) == nil {
|
||||
// object、ok 分别是 JSON 顶层对象视图和类型判断结果。
|
||||
if object, ok := document.(map[string]any); ok {
|
||||
result.ResponseFields = make([]string, 0, len(object))
|
||||
// key 是当前 JSON 顶层字段名称,只返回名称不返回全部字段值。
|
||||
for key := range object {
|
||||
result.ResponseFields = append(result.ResponseFields, key)
|
||||
}
|
||||
sort.Strings(result.ResponseFields)
|
||||
}
|
||||
if config.ResponsePath != "" {
|
||||
// value、found 分别是响应路径命中的值和是否存在标记。
|
||||
if value, found := lookupAPIResponsePath(document, config.ResponsePath); found {
|
||||
result.ExtractedValue = truncateAPITestPreview(apiJSONScalar(value))
|
||||
}
|
||||
} else {
|
||||
result.ExtractedValue = truncateAPITestPreview(apiJSONScalar(document))
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// truncateAPITestPreview 限制测试结果文本长度并标记被截断的响应。
|
||||
func truncateAPITestPreview(value string) string {
|
||||
if len(value) <= apiTestPreviewLimit {
|
||||
return value
|
||||
}
|
||||
return value[:apiTestPreviewLimit] + "..."
|
||||
}
|
||||
|
||||
// Fetch 根据单个订单单位构造并发送一次 API 请求;重试仍复用同一幂等键。
|
||||
func (c *apiDeliveryClient) Fetch(ctx context.Context, request automation.APICardRequest) (automation.APICardResult, error) {
|
||||
// config 是从专用卡券读取路径得到的完整 API 配置。
|
||||
config, err := cardsapp.ParseAPIConfig(request.Config)
|
||||
if err != nil {
|
||||
return automation.APICardResult{}, err
|
||||
}
|
||||
// itemDetail 是本地已保存的商品详情;查询不到时保持空字符串,不凭空补造内容。
|
||||
itemDetail := ""
|
||||
if c.store != nil && c.store.Items != nil && request.ItemID != "" {
|
||||
// item、itemErr 保存商品详情查询结果及不存在/数据库错误的区分。
|
||||
if item, itemErr := c.store.Items.GetByCookieItem(ctx, request.AccountID, request.ItemID); itemErr == nil {
|
||||
itemDetail = item.ItemDetail
|
||||
} else if !errors.Is(itemErr, db.ErrNotFound) {
|
||||
return automation.APICardResult{}, fmt.Errorf("读取商品详情: %w", itemErr)
|
||||
}
|
||||
}
|
||||
// idempotencyKey 是由触发键、动作、卡券和单位序号稳定生成的请求幂等键。
|
||||
idempotencyKey := apiDeliveryIdempotencyKey(request.TriggerKey, request.ActionID, request.CardID, request.UnitIndex)
|
||||
// variables 保存可用于请求头和参数值替换的订单上下文。
|
||||
variables := map[string]string{
|
||||
"{order_id}": request.OrderID,
|
||||
"{item_id}": request.ItemID,
|
||||
"{buyer_id}": request.BuyerID,
|
||||
"{chat_id}": request.ChatID,
|
||||
"{account_id}": request.AccountID,
|
||||
"{cookie_id}": request.AccountID,
|
||||
"{spec_name}": request.SpecName,
|
||||
"{spec_value}": request.SpecValue,
|
||||
"{quantity}": request.Quantity,
|
||||
"{order_quantity}": request.Quantity,
|
||||
"{amount}": request.Amount,
|
||||
"{order_amount}": request.Amount,
|
||||
"{item_detail}": itemDetail,
|
||||
"{trigger_type}": request.TriggerType,
|
||||
"{timestamp}": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
"{delivery_unit_index}": strconv.Itoa(request.UnitIndex),
|
||||
"{delivery_total_count}": strconv.Itoa(request.TotalUnits),
|
||||
"{idempotency_key}": idempotencyKey,
|
||||
}
|
||||
// headers、params 是递归替换后的请求模板,模板键名保持不变。
|
||||
headers := replaceAPIJSONMap(config.Headers, variables)
|
||||
// params 保存递归替换后的请求参数模板。
|
||||
params := replaceAPIJSONMap(config.Params, variables)
|
||||
// requestURL 是不包含动态替换的固定 API 地址;GET 参数随后编码到查询部分。
|
||||
requestURL, err := url.Parse(config.URL)
|
||||
if err != nil {
|
||||
return automation.APICardResult{}, err
|
||||
}
|
||||
if config.Method == http.MethodGet {
|
||||
// query 保存固定 URL 查询参数与 API 模板参数合并后的结果。
|
||||
query := requestURL.Query()
|
||||
// key、value 分别是不会动态替换的参数名及已经替换的参数值。
|
||||
for key, value := range params {
|
||||
query.Set(key, apiJSONScalar(value))
|
||||
}
|
||||
requestURL.RawQuery = query.Encode()
|
||||
}
|
||||
// bodyValues 保存 POST 正文模板;旧配置没有 body 时继续把 params 作为正文,保持兼容。
|
||||
bodyValues := replaceAPIJSONMap(config.Body, variables)
|
||||
if len(bodyValues) == 0 {
|
||||
bodyValues = params
|
||||
}
|
||||
// body 保存 POST 请求编码后的正文;GET 请求不把参数复制到请求体。
|
||||
body, err := encodeAPIDeliveryBody(bodyValues, config.ContentType)
|
||||
if err != nil {
|
||||
return automation.APICardResult{}, fmt.Errorf("编码 API 请求参数: %w", err)
|
||||
}
|
||||
// attempts 是本次请求允许执行的总次数;未开启重试时固定为一次。
|
||||
attempts := 1
|
||||
if config.RetryEnabled {
|
||||
attempts = apiDeliveryRetryLimit
|
||||
}
|
||||
// attempt 表示当前已执行的请求次数,最多不超过配置允许的总次数。
|
||||
for attempt := 1; attempt <= attempts; attempt++ {
|
||||
// result、attemptErr 保存本次 HTTP 调用的结果及响应提取错误。
|
||||
result, attemptErr := c.doAPIRequest(ctx, config, requestURL.String(), headers, body, attempt)
|
||||
if attemptErr == nil {
|
||||
return result, nil
|
||||
}
|
||||
if !shouldRetryAPIDelivery(attemptErr, attempt, attempts) {
|
||||
return result, attemptErr
|
||||
}
|
||||
// retryTimer 在上下文取消时立即终止退避,避免自动化工作线程被无意义占用。
|
||||
retryGap := apiDeliveryRetryGaps[attempt-1]
|
||||
// retryTimer 控制下一次请求前的有限退避时间。
|
||||
retryTimer := time.NewTimer(retryGap)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if !retryTimer.Stop() {
|
||||
select {
|
||||
case <-retryTimer.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
return automation.APICardResult{Dispatched: result.Dispatched}, ctx.Err()
|
||||
case <-retryTimer.C:
|
||||
}
|
||||
}
|
||||
return automation.APICardResult{Dispatched: true}, errors.New("API 发货请求重试次数耗尽")
|
||||
}
|
||||
|
||||
// doAPIRequest 执行一次不含重试的 HTTP 请求,并把状态码映射为可安全分类的结果。
|
||||
func (c *apiDeliveryClient) doAPIRequest(ctx context.Context, config cardsapp.APIConfig, rawURL string, headers map[string]any, body []byte, attempt int) (automation.APICardResult, error) {
|
||||
// requestBody 保存 POST 的可重复读取请求体;GET 请求传入空体。
|
||||
var requestBody io.Reader
|
||||
if config.Method == http.MethodPost {
|
||||
requestBody = bytes.NewReader(body)
|
||||
}
|
||||
// request、err 保存当前尝试的 HTTP 请求及构造错误。
|
||||
requestCtx, cancel := context.WithTimeout(ctx, time.Duration(config.Timeout)*time.Second)
|
||||
defer cancel()
|
||||
// request、err 保存当前尝试的 HTTP 请求及构造错误。
|
||||
request, err := http.NewRequestWithContext(requestCtx, config.Method, rawURL, requestBody)
|
||||
if err != nil {
|
||||
return automation.APICardResult{}, err
|
||||
}
|
||||
// key、value 分别是请求头名称及递归替换后的请求头值。
|
||||
for key, value := range headers {
|
||||
request.Header.Set(key, apiJSONScalar(value))
|
||||
}
|
||||
if config.Method == http.MethodPost && request.Header.Get("Content-Type") == "" {
|
||||
// contentType 是用户选择的正文媒体类型;缺省时使用 JSON 兼容旧配置。
|
||||
contentType := config.ContentType
|
||||
if contentType == "" {
|
||||
contentType = "application/json"
|
||||
}
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
// response、err 保存远端响应及网络调用错误。
|
||||
client := c.httpClient()
|
||||
// response、err 保存远端响应及网络调用错误。
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return automation.APICardResult{}, ctx.Err()
|
||||
}
|
||||
return automation.APICardResult{Dispatched: true}, &apiDeliveryRetryableError{kind: "network", err: err}
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if c.logger != nil {
|
||||
c.logger.Info("API 卡发货请求完成", "method", config.Method, "attempt", attempt, "status", response.StatusCode)
|
||||
}
|
||||
if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
|
||||
// readErr 保存受限读取暂时性错误,不读取响应正文到日志。
|
||||
if _, readErr := readAPIDeliveryBody(response.Body); readErr != nil {
|
||||
return automation.APICardResult{Dispatched: response.StatusCode == http.StatusRequestTimeout || response.StatusCode == http.StatusTooManyRequests || response.StatusCode >= 500}, readErr
|
||||
}
|
||||
// dispatched 表示暂时性状态可能伴随服务端处理;明确的其他 4xx 视为确定拒绝。
|
||||
dispatched := response.StatusCode == http.StatusRequestTimeout || response.StatusCode == http.StatusTooManyRequests || response.StatusCode >= 500
|
||||
return automation.APICardResult{Dispatched: dispatched}, &apiDeliveryHTTPError{statusCode: response.StatusCode}
|
||||
}
|
||||
// content、readErr 保存成功响应的提取结果及解析错误。
|
||||
content, readErr := readAPIDeliveryResponse(response.Body, response.Header.Get("Content-Type"), config.ResponsePath)
|
||||
if readErr != nil {
|
||||
return automation.APICardResult{Dispatched: true}, readErr
|
||||
}
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return automation.APICardResult{Dispatched: true}, errors.New("API 响应提取结果为空")
|
||||
}
|
||||
return automation.APICardResult{Content: content}, nil
|
||||
}
|
||||
|
||||
// encodeAPIDeliveryBody 按用户选择的 Content-Type 编码 API 请求正文。
|
||||
func encodeAPIDeliveryBody(values map[string]any, contentType string) ([]byte, error) {
|
||||
// lowerContentType 保存忽略大小写后的媒体类型,供正文编码分支判断。
|
||||
lowerContentType := strings.ToLower(contentType)
|
||||
if strings.Contains(lowerContentType, "x-www-form-urlencoded") {
|
||||
// formValues 保存表单编码所需的字符串字段。
|
||||
formValues := url.Values{}
|
||||
// key、value 分别是表单字段名称和待编码的模板值。
|
||||
// key、value 分别是纯文本字段名称和字段值。
|
||||
for key, value := range values {
|
||||
formValues.Set(key, apiJSONScalar(value))
|
||||
}
|
||||
return []byte(formValues.Encode()), nil
|
||||
}
|
||||
if strings.Contains(lowerContentType, "text/plain") {
|
||||
// lines 保存纯文本键值正文,每行一个字段,便于普通 Web 服务直接读取。
|
||||
lines := make([]string, 0, len(values))
|
||||
// key、value 分别是 XML 字段名称和字段值。
|
||||
for key, value := range values {
|
||||
lines = append(lines, key+"="+apiJSONScalar(value))
|
||||
}
|
||||
sort.Strings(lines)
|
||||
return []byte(strings.Join(lines, "\n")), nil
|
||||
}
|
||||
if strings.Contains(lowerContentType, "application/xml") {
|
||||
// xmlParts 保存经过 XML 转义的简单字段元素。
|
||||
xmlParts := make([]string, 0, len(values))
|
||||
// key、value 分别是 XML 字段名称和待转义字段值。
|
||||
for key, value := range values {
|
||||
if !isXMLTagName(key) {
|
||||
key = "field"
|
||||
}
|
||||
xmlParts = append(xmlParts, fmt.Sprintf("<%s>%s</%s>", key, xmlEscape(apiJSONScalar(value)), key))
|
||||
}
|
||||
sort.Strings(xmlParts)
|
||||
return []byte("<body>" + strings.Join(xmlParts, "") + "</body>"), nil
|
||||
}
|
||||
return json.Marshal(values)
|
||||
}
|
||||
|
||||
// isXMLTagName 判断用户填写的键名是否可以作为 XML 标签名使用。
|
||||
func isXMLTagName(value string) bool {
|
||||
if value == "" || (value[0] >= '0' && value[0] <= '9') {
|
||||
return false
|
||||
}
|
||||
// character 表示当前键名中的一个 Unicode 字符。
|
||||
for _, character := range value {
|
||||
if character != '_' && character != '-' && character != ':' && character != '.' &&
|
||||
(character < 'a' || character > 'z') && (character < 'A' || character > 'Z') && (character < '0' || character > '9') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// xmlEscape 转义 XML 正文中的五类保留字符,避免用户输入破坏请求结构。
|
||||
func xmlEscape(value string) string {
|
||||
return strings.NewReplacer("&", "&", "<", "<", ">", ">", "\"", """, "'", "'").Replace(value)
|
||||
}
|
||||
|
||||
// httpClient 返回 API 发货共享的出站客户端;客户端策略会在每次请求时读取运行时开关。
|
||||
func (c *apiDeliveryClient) httpClient() *http.Client {
|
||||
if c == nil {
|
||||
return netguard.ConfiguredHTTPClient(0)
|
||||
}
|
||||
c.clientOnce.Do(func() {
|
||||
if c.client == nil {
|
||||
c.client = netguard.ConfiguredHTTPClient(0)
|
||||
}
|
||||
})
|
||||
return c.client
|
||||
}
|
||||
|
||||
// apiDeliveryRetryableError 标记可按网络错误策略重试的单次调用失败。
|
||||
type apiDeliveryRetryableError struct {
|
||||
// kind 记录失败类别,不包含请求地址或响应秘密。
|
||||
kind string
|
||||
// err 保存底层网络错误供日志外的调用链诊断。
|
||||
err error
|
||||
}
|
||||
|
||||
// Error 返回不含请求秘密的网络错误文本。
|
||||
func (e *apiDeliveryRetryableError) Error() string { return "API 发货网络请求失败" }
|
||||
|
||||
// Unwrap 返回底层错误供上下文取消和超时判断使用。
|
||||
func (e *apiDeliveryRetryableError) Unwrap() error { return e.err }
|
||||
|
||||
// apiDeliveryHTTPError 保存可用于重试判断的 HTTP 状态码。
|
||||
type apiDeliveryHTTPError struct {
|
||||
// statusCode 是远端返回的 HTTP 状态码。
|
||||
statusCode int
|
||||
}
|
||||
|
||||
// Error 返回不包含响应正文的 HTTP 错误。
|
||||
func (e *apiDeliveryHTTPError) Error() string {
|
||||
return fmt.Sprintf("API 发货 HTTP 状态异常: %d", e.statusCode)
|
||||
}
|
||||
|
||||
// shouldRetryAPIDelivery 判断错误是否属于幂等重试允许的网络、超时或暂时性 HTTP 错误。
|
||||
func shouldRetryAPIDelivery(err error, attempt, limit int) bool {
|
||||
if err == nil || attempt >= limit {
|
||||
return false
|
||||
}
|
||||
// httpErr 保存可按状态码判断的 HTTP 失败。
|
||||
var httpErr *apiDeliveryHTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
return httpErr.statusCode == http.StatusRequestTimeout || httpErr.statusCode == http.StatusTooManyRequests || httpErr.statusCode >= 500
|
||||
}
|
||||
// networkErr 保存可按幂等策略重试的网络失败。
|
||||
var networkErr *apiDeliveryRetryableError
|
||||
return errors.As(err, &networkErr) && (networkErr.kind == "network" || errors.Is(networkErr, context.DeadlineExceeded))
|
||||
}
|
||||
|
||||
// readAPIDeliveryResponse 读取受限响应并按路径提取卡密文本。
|
||||
func readAPIDeliveryResponse(reader io.Reader, contentType, responsePath string) (string, error) {
|
||||
// body 保存受大小限制读取的完整响应体。
|
||||
body, err := readAPIDeliveryBody(reader)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// trimmed 保存去除空白后的响应内容,用于空值和 JSON 判断。
|
||||
trimmed := strings.TrimSpace(string(body))
|
||||
if trimmed == "" {
|
||||
return "", errors.New("API 响应为空")
|
||||
}
|
||||
// document 保存 JSON 响应的动态结构,仅在当前函数内用于提取文本。
|
||||
var document any
|
||||
// decoder 保留 JSON 数字的原始文本,避免大数型卡密经过 float64 发生舍入。
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.UseNumber()
|
||||
if decoder.Decode(&document) != nil {
|
||||
return trimmed, nil
|
||||
}
|
||||
if responsePath != "" {
|
||||
// value、found 保存响应路径命中的节点及命中状态。
|
||||
value, found := lookupAPIResponsePath(document, responsePath)
|
||||
if !found || value == nil {
|
||||
return "", errors.New("API 响应路径不存在或为空")
|
||||
}
|
||||
return apiJSONScalar(value), nil
|
||||
}
|
||||
// object、ok 保存可按默认字段提取的 JSON 对象及类型判断。
|
||||
if object, ok := document.(map[string]any); ok {
|
||||
// key 表示默认响应提取候选字段名。
|
||||
for _, key := range []string{"data", "content", "card"} {
|
||||
// value、found 保存候选字段的值及是否存在。
|
||||
if value, found := object[key]; found && value != nil {
|
||||
return apiJSONScalar(value), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return apiJSONScalar(document), nil
|
||||
}
|
||||
|
||||
// readAPIDeliveryBody 读取 API 响应体并拒绝超过 1 MiB 的内容,不返回正文到日志或 HTTP 响应。
|
||||
func readAPIDeliveryBody(reader io.Reader) ([]byte, error) {
|
||||
// limited 保存多读取一个字节以检测超大响应的受限读取器。
|
||||
limited := io.LimitReader(reader, apiDeliveryResponseLimit+1)
|
||||
// body、err 保存受限读取的响应体和读取错误。
|
||||
body, err := io.ReadAll(limited)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取 API 响应失败: %w", err)
|
||||
}
|
||||
if int64(len(body)) > apiDeliveryResponseLimit {
|
||||
return nil, errors.New("API 响应超过 1 MiB 限制")
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// lookupAPIResponsePath 按点号字段和数组下标解析响应路径。
|
||||
func lookupAPIResponsePath(document any, path string) (any, bool) {
|
||||
// current 保存逐段路径解析的当前 JSON 节点。
|
||||
current := document
|
||||
// segment 表示当前响应路径的字段或数组段。
|
||||
for _, segment := range strings.Split(strings.TrimPrefix(path, "$."), ".") {
|
||||
if segment == "" {
|
||||
return nil, false
|
||||
}
|
||||
// name、index、hasIndex、ok 保存当前路径段的字段名、数组下标和解析状态。
|
||||
name, index, hasIndex, ok := parseAPIPathSegment(segment)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
if name != "" {
|
||||
// object、objectOK 保存当前节点的对象视图及类型判断。
|
||||
object, objectOK := current.(map[string]any)
|
||||
if !objectOK {
|
||||
return nil, false
|
||||
}
|
||||
current, ok = object[name]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
if hasIndex {
|
||||
// array、arrayOK 保存当前节点的数组视图及类型判断。
|
||||
array, arrayOK := current.([]any)
|
||||
if !arrayOK || index < 0 || index >= len(array) {
|
||||
return nil, false
|
||||
}
|
||||
current = array[index]
|
||||
}
|
||||
}
|
||||
return current, true
|
||||
}
|
||||
|
||||
// parseAPIPathSegment 把字段名和可选数组下标拆分为结构化路径段。
|
||||
func parseAPIPathSegment(segment string) (string, int, bool, bool) {
|
||||
// bracket 保存数组下标左括号位置。
|
||||
bracket := strings.IndexByte(segment, '[')
|
||||
if bracket < 0 {
|
||||
return segment, 0, false, true
|
||||
}
|
||||
if !strings.HasSuffix(segment, "]") || bracket == len(segment)-2 {
|
||||
return "", 0, false, false
|
||||
}
|
||||
// index、err 保存括号内数组下标及其解析错误。
|
||||
index, err := strconv.Atoi(segment[bracket+1 : len(segment)-1])
|
||||
if err != nil || index < 0 {
|
||||
return "", 0, false, false
|
||||
}
|
||||
return segment[:bracket], index, true, true
|
||||
}
|
||||
|
||||
// replaceAPIJSONMap 递归替换模板值,保持 JSON 对象键名原样不变。
|
||||
func replaceAPIJSONMap(input map[string]any, variables map[string]string) map[string]any {
|
||||
// output 保存替换后的新对象,避免修改卡券配置缓存。
|
||||
output := make(map[string]any, len(input))
|
||||
// key、value 分别是模板字段名和待替换模板值。
|
||||
for key, value := range input {
|
||||
output[key] = replaceAPIJSONValue(value, variables)
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
// replaceAPIJSONValue 递归处理对象、数组和字符串模板值。
|
||||
func replaceAPIJSONValue(value any, variables map[string]string) any {
|
||||
// current 保存当前递归节点的动态 JSON 值。
|
||||
switch current := value.(type) {
|
||||
case string:
|
||||
// key、replacement 分别是动态变量和订单上下文替换值。
|
||||
for key, replacement := range variables {
|
||||
current = strings.ReplaceAll(current, key, replacement)
|
||||
}
|
||||
return current
|
||||
case map[string]any:
|
||||
return replaceAPIJSONMap(current, variables)
|
||||
case []any:
|
||||
// output 保存数组中每个值的递归替换结果。
|
||||
output := make([]any, len(current))
|
||||
// index、child 分别是数组位置和当前递归节点。
|
||||
for index, child := range current {
|
||||
output[index] = replaceAPIJSONValue(child, variables)
|
||||
}
|
||||
return output
|
||||
default:
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
// apiJSONScalar 将响应或查询参数的 JSON 值转换为 API 发货使用的紧凑文本。
|
||||
func apiJSONScalar(value any) string {
|
||||
// current 保存当前需要转换为紧凑文本的动态值。
|
||||
switch current := value.(type) {
|
||||
case string:
|
||||
return current
|
||||
case json.Number:
|
||||
return current.String()
|
||||
case nil:
|
||||
return ""
|
||||
default:
|
||||
// encoded、err 保存复杂响应值的紧凑 JSON 表示及编码错误。
|
||||
encoded, err := json.Marshal(current)
|
||||
if err != nil {
|
||||
return fmt.Sprint(current)
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
}
|
||||
|
||||
// apiDeliveryIdempotencyKey 生成跨进程稳定且不暴露订单内容的幂等键。
|
||||
func apiDeliveryIdempotencyKey(triggerKey string, actionID, cardID int64, unitIndex int) string {
|
||||
// sum 保存幂等键输入的 SHA-256 摘要,不包含可逆订单秘密。
|
||||
sum := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%d\x00%d\x00%d", triggerKey, actionID, cardID, unitIndex)))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
var _ automation.APICardFetcher = (*apiDeliveryClient)(nil)
|
||||
@@ -0,0 +1,238 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
"xianyu-go/internal/automation"
|
||||
)
|
||||
|
||||
// TestAPICardTesterReturnsResponseDiagnostics 验证测试请求返回状态码、JSON 顶层字段和响应路径提取结果。
|
||||
func TestAPICardTesterReturnsResponseDiagnostics(t *testing.T) {
|
||||
// server 是返回固定 JSON 结构的本地 API 测试端点。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
_, _ = writer.Write([]byte(`{"data":{"code":"TEST-CODE"},"message":"ok"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是不访问数据库的临时 API 测试适配器。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存测试请求返回的诊断和错误。
|
||||
result, err := client.Test(context.Background(), cardsapp.APIRequestTestInput{Config: fmt.Sprintf(`{"url":%q,"method":"GET","timeout_seconds":10,"response_path":"data.code"}`, server.URL)})
|
||||
if err != nil {
|
||||
t.Fatalf("API 测试请求失败: %v", err)
|
||||
}
|
||||
if result.Status != "success" || result.StatusCode != http.StatusOK || result.ExtractedValue != "TEST-CODE" {
|
||||
t.Fatalf("API 测试诊断错误: %+v", result)
|
||||
}
|
||||
if strings.Join(result.ResponseFields, ",") != "data,message" {
|
||||
t.Fatalf("API 测试响应字段错误: %v", result.ResponseFields)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPICardTesterPreservesRemoteFailureDiagnostics 验证远端非 2xx 仍作为完成结果返回状态码和限长预览。
|
||||
func TestAPICardTesterPreservesRemoteFailureDiagnostics(t *testing.T) {
|
||||
// server 是返回明确失败状态的本地 API 端点。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.WriteHeader(http.StatusBadGateway)
|
||||
_, _ = writer.Write([]byte("remote failure"))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是不访问数据库的临时 API 测试适配器。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存远端失败诊断和错误。
|
||||
result, err := client.Test(context.Background(), cardsapp.APIRequestTestInput{Config: fmt.Sprintf(`{"url":%q,"method":"GET","timeout_seconds":10}`, server.URL)})
|
||||
if err != nil {
|
||||
t.Fatalf("远端失败不应变为本地错误: %v", err)
|
||||
}
|
||||
if result.Status != "failed" || result.StatusCode != http.StatusBadGateway || result.ResponsePreview != "remote failure" {
|
||||
t.Fatalf("远端失败诊断错误: %+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDeliveryClientGETAndTemplateReplacement 验证 GET 查询参数、递归变量替换和响应路径提取。
|
||||
func TestAPIDeliveryClientGETAndTemplateReplacement(t *testing.T) {
|
||||
// receivedQuery、receivedHeader 保存服务端观察到的动态请求字段。
|
||||
var receivedQuery, receivedHeader string
|
||||
// server 是接收 GET 模板请求的本地测试服务。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
receivedQuery = request.URL.Query().Get("order")
|
||||
receivedHeader = request.Header.Get("X-Unit")
|
||||
_, _ = writer.Write([]byte(`{"data":{"cards":[{"code":"CODE-1"}]}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是使用测试 HTTP 服务的普通 API 发货客户端。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存单件 API 请求的提取结果及错误。
|
||||
result, err := client.Fetch(context.Background(), automation.APICardRequest{
|
||||
Config: fmt.Sprintf(`{"url":%q,"method":"GET","timeout_seconds":10,"headers":{"X-Unit":"{delivery_unit_index}"},"params":{"order":"{order_id}","nested":{"buyer":"{buyer_id}"}},"response_path":"data.cards[0].code"}`, server.URL),
|
||||
TriggerKey: "trigger-1", ActionID: 2, CardID: 3, UnitIndex: 1, TotalUnits: 2,
|
||||
AccountID: "account", OrderID: "order-7", BuyerID: "buyer-8",
|
||||
})
|
||||
if err != nil || result.Content != "CODE-1" {
|
||||
t.Fatalf("GET API 发货结果错误 result=%+v err=%v", result, err)
|
||||
}
|
||||
if receivedQuery != "order-7" || receivedHeader != "1" {
|
||||
t.Fatalf("动态字段未替换 query=%q header=%q", receivedQuery, receivedHeader)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDeliveryClientPOSTRetryAndStableIdempotencyKey 验证 POST JSON、三次重试和幂等键稳定复用。
|
||||
func TestAPIDeliveryClientPOSTRetryAndStableIdempotencyKey(t *testing.T) {
|
||||
// oldGaps 保存全局退避配置,避免测试等待真实秒数。
|
||||
oldGaps := apiDeliveryRetryGaps
|
||||
apiDeliveryRetryGaps = []time.Duration{time.Millisecond, time.Millisecond}
|
||||
defer func() { apiDeliveryRetryGaps = oldGaps }()
|
||||
// calls 记录服务端实际收到的请求次数。
|
||||
var calls int32
|
||||
// keys 保存每次请求观察到的幂等键。
|
||||
var keys []string
|
||||
// server 是返回暂时性失败并记录幂等键的本地测试服务。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
atomic.AddInt32(&calls, 1)
|
||||
// body 保存 POST 参数对象。
|
||||
var body map[string]any
|
||||
// err 表示测试服务解析 POST body 的错误。
|
||||
if err := json.NewDecoder(request.Body).Decode(&body); err != nil {
|
||||
t.Errorf("POST JSON 解码失败: %v", err)
|
||||
}
|
||||
keys = append(keys, fmt.Sprint(body["key"]))
|
||||
if calls < 3 {
|
||||
writer.WriteHeader(http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"content":"POST-CODE"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是使用测试 HTTP 服务的普通 API 发货客户端。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存带重试的 API 请求结果。
|
||||
result, err := client.Fetch(context.Background(), automation.APICardRequest{
|
||||
Config: fmt.Sprintf(`{"url":%q,"method":"POST","timeout_seconds":10,"params":{"key":"{idempotency_key}","unit":"{delivery_unit_index}"},"retry_enabled":true}`, server.URL),
|
||||
TriggerKey: "trigger-2", ActionID: 4, CardID: 5, UnitIndex: 2, TotalUnits: 2,
|
||||
})
|
||||
if err != nil || result.Content != "POST-CODE" {
|
||||
t.Fatalf("POST API 发货结果错误 result=%+v err=%v", result, err)
|
||||
}
|
||||
if atomic.LoadInt32(&calls) != 3 || len(keys) != 3 || keys[0] == "" || keys[0] != keys[1] || keys[1] != keys[2] {
|
||||
t.Fatalf("重试次数或幂等键错误 calls=%d keys=%v", atomic.LoadInt32(&calls), keys)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDeliveryClientFormBodyAndContentType 验证非 JSON Content-Type 使用键值表单正文,而不是上传文件格式。
|
||||
func TestAPIDeliveryClientFormBodyAndContentType(t *testing.T) {
|
||||
// receivedContentType、receivedBody 保存测试服务观察到的正文元数据和内容。
|
||||
var receivedContentType, receivedBody string
|
||||
// server 是接收表单正文并返回固定卡密的本地服务。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
receivedContentType = request.Header.Get("Content-Type")
|
||||
// body、readErr 保存服务端读取到的正文和读取错误。
|
||||
body, readErr := io.ReadAll(request.Body)
|
||||
if readErr != nil {
|
||||
t.Errorf("读取表单正文失败: %v", readErr)
|
||||
}
|
||||
receivedBody = string(body)
|
||||
_, _ = writer.Write([]byte(`{"content":"FORM-CODE"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是使用本地测试服务的 API 发货客户端。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存表单请求的发货结果及错误。
|
||||
result, err := client.Fetch(context.Background(), automation.APICardRequest{
|
||||
Config: fmt.Sprintf(`{"url":%q,"method":"POST","timeout_seconds":10,"content_type":"application/x-www-form-urlencoded","body":{"order_id":"{order_id}","quantity":"{quantity}"}}`, server.URL),
|
||||
OrderID: "order-form", Quantity: "2",
|
||||
})
|
||||
if err != nil || result.Content != "FORM-CODE" {
|
||||
t.Fatalf("表单 API 发货结果错误 result=%+v err=%v", result, err)
|
||||
}
|
||||
if receivedContentType != "application/x-www-form-urlencoded" || receivedBody != "order_id=order-form&quantity=2" {
|
||||
t.Fatalf("表单正文编码错误 content_type=%q body=%q", receivedContentType, receivedBody)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEncodeAPIDeliveryBodyTextAndXML 验证非表单 Content-Type 的键值正文编码和转义边界。
|
||||
func TestEncodeAPIDeliveryBodyTextAndXML(t *testing.T) {
|
||||
// values 保存测试使用的普通字段和包含 XML 特殊字符的字段。
|
||||
values := map[string]any{"z": "last", "a": "<&"}
|
||||
// textBody、textErr 保存纯文本正文和编码错误。
|
||||
textBody, textErr := encodeAPIDeliveryBody(values, "text/plain")
|
||||
if textErr != nil || string(textBody) != "a=<&\nz=last" {
|
||||
t.Fatalf("纯文本正文错误 body=%q err=%v", textBody, textErr)
|
||||
}
|
||||
// xmlBody、xmlErr 保存 XML 正文和编码错误。
|
||||
xmlBody, xmlErr := encodeAPIDeliveryBody(values, "application/xml")
|
||||
if xmlErr != nil || string(xmlBody) != "<body><a><&</a><z>last</z></body>" {
|
||||
t.Fatalf("XML 正文错误 body=%q err=%v", xmlBody, xmlErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDeliveryClientResponseAndSizeErrors 验证文本响应、非 2xx 和超大响应不会泄漏正文且不误提取。
|
||||
func TestAPIDeliveryClientResponseAndSizeErrors(t *testing.T) {
|
||||
// cases 保存不同响应场景及预期错误判定。
|
||||
cases := []struct {
|
||||
// name 是场景名称。
|
||||
name string
|
||||
// status 是服务端返回状态码。
|
||||
status int
|
||||
// body 是服务端返回的响应体。
|
||||
body string
|
||||
// wantContent 是预期的成功文本。
|
||||
wantContent string
|
||||
// wantError 表示是否应返回错误。
|
||||
wantError bool
|
||||
}{
|
||||
{name: "plain", status: http.StatusOK, body: "PLAIN-CODE", wantContent: "PLAIN-CODE"},
|
||||
{name: "bad-request", status: http.StatusBadRequest, body: "secret-error", wantError: true},
|
||||
{name: "too-large", status: http.StatusOK, body: strings.Repeat("x", int(apiDeliveryResponseLimit)+1), wantError: true},
|
||||
}
|
||||
// testCase 保存当前响应场景及其预期行为。
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
// server 是当前场景使用的本地响应服务器。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.WriteHeader(testCase.status)
|
||||
_, _ = writer.Write([]byte(testCase.body))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是当前场景使用的 API 发货客户端。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存当前场景的执行结果。
|
||||
result, err := client.Fetch(context.Background(), automation.APICardRequest{
|
||||
Config: fmt.Sprintf(`{"url":%q,"method":"GET","timeout_seconds":10}`, server.URL),
|
||||
})
|
||||
if (err != nil) != testCase.wantError || result.Content != testCase.wantContent {
|
||||
t.Fatalf("响应判定错误 result=%+v err=%v", result, err)
|
||||
}
|
||||
if testCase.name == "bad-request" && result.Dispatched {
|
||||
t.Fatal("明确 4xx 拒绝不应被标记为结果未知")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDeliveryClientPreservesJSONNumbers 验证大整数卡密不会因 JSON 浮点转换发生舍入。
|
||||
func TestAPIDeliveryClientPreservesJSONNumbers(t *testing.T) {
|
||||
// server 是返回超出 float64 精确整数范围的 JSON 数字端点。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write([]byte(`{"data":{"card":{"code":9007199254740993}}}`))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
// client 是本测试使用的零值 API 发货客户端。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存 JSON 数字提取结果及错误。
|
||||
result, err := client.Fetch(context.Background(), automation.APICardRequest{
|
||||
Config: fmt.Sprintf(`{"url":%q,"method":"GET","response_path":"data.card.code"}`, server.URL),
|
||||
})
|
||||
if err != nil || result.Content != "9007199254740993" {
|
||||
t.Fatalf("JSON 大整数被错误转换 result=%+v err=%v", result, err)
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,19 @@ func (s automationImageSender) SendText(ctx context.Context, chatID, toUserID, t
|
||||
return s.sender.SendText(ctx, chatID, toUserID, text)
|
||||
}
|
||||
|
||||
// AutomationReady 透传账号运行时的 WebSocket 就绪状态,使自动化能在请求 API 卡密前阻止尚未完成注册的账号。
|
||||
func (s automationImageSender) AutomationReady() bool {
|
||||
if s.sender == nil {
|
||||
return false
|
||||
}
|
||||
// readySender 是实现连接就绪报告能力的账号运行时发送器。
|
||||
readySender, ok := s.sender.(interface{ AutomationReady() bool })
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
return readySender.AutomationReady()
|
||||
}
|
||||
|
||||
// SendImage 将图片卡密 URL 在内存中下载、上传到闲鱼图片服务后,再交给账号运行时发送。
|
||||
// 下载或上传失败发生在 WebSocket 写入之前,必须标记为确定未发送以允许自动化安全重试。
|
||||
func (s automationImageSender) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64, _, _ int) error {
|
||||
@@ -127,7 +140,7 @@ func downloadAutomationImage(ctx context.Context, rawURL string) ([]byte, string
|
||||
return nil, "", "", fmt.Errorf("创建图片下载请求失败")
|
||||
}
|
||||
// client 只允许访问公网地址,并在重定向时重复校验目标,避免卡密 URL 触发 SSRF。
|
||||
client := netguard.PublicHTTPClient(30 * time.Second)
|
||||
client := netguard.ConfiguredHTTPClient(30 * time.Second)
|
||||
// response、err 保存远程图片响应及网络访问失败原因。
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
|
||||
@@ -19,6 +19,8 @@ type automationImageSenderStub struct {
|
||||
width, height int
|
||||
// imageCalls 记录最终 WebSocket 图片发送次数。
|
||||
imageCalls int
|
||||
// ready 表示模拟账号的 WebSocket 是否完成自动化消息注册。
|
||||
ready bool
|
||||
}
|
||||
|
||||
// SendText 满足自动化发送契约;本测试只验证图片链路。
|
||||
@@ -36,6 +38,27 @@ func (s *automationImageSenderStub) SendImage(_ context.Context, _, _, imageURL
|
||||
// UpdateCookie 满足自动化发送契约;凭证写回由图片上传适配器自身负责。
|
||||
func (s *automationImageSenderStub) UpdateCookie(string) {}
|
||||
|
||||
// AutomationReady 返回测试替身配置的 WebSocket 自动化就绪状态。
|
||||
func (s *automationImageSenderStub) AutomationReady() bool { return s.ready }
|
||||
|
||||
// TestAutomationImageSenderReportsWrappedWebSocketReadiness 验证图片/API 卡密包装器不会掩盖账号运行时的连接未就绪状态。
|
||||
func TestAutomationImageSenderReportsWrappedWebSocketReadiness(t *testing.T) {
|
||||
// unavailableSender 是尚未完成 WebSocket 注册的账号发送器。
|
||||
unavailableSender := &automationImageSenderStub{ready: false}
|
||||
// unavailableWrapper 包装未就绪发送器后仍必须报告不可发送。
|
||||
unavailableWrapper := automationImageSender{sender: unavailableSender}
|
||||
if unavailableWrapper.AutomationReady() {
|
||||
t.Fatal("包装器不应把未就绪 WebSocket 误报为可发送")
|
||||
}
|
||||
// readySender 是已经完成 WebSocket 注册的账号发送器。
|
||||
readySender := &automationImageSenderStub{ready: true}
|
||||
// readyWrapper 包装已就绪发送器后必须保留可发送状态。
|
||||
readyWrapper := automationImageSender{sender: readySender}
|
||||
if !readyWrapper.AutomationReady() {
|
||||
t.Fatal("包装器应保留已就绪 WebSocket 状态")
|
||||
}
|
||||
}
|
||||
|
||||
// automationImageUploaderStub 记录上传输入并返回可控的平台图片结果。
|
||||
type automationImageUploaderStub struct {
|
||||
// accountID 保存上传时实际使用的发货账号。
|
||||
|
||||
@@ -198,14 +198,14 @@ func (r *AutomationRepository) OwnsItem(ctx context.Context, userID int64, accou
|
||||
// GetCard 返回用户拥有的卡密组类型,不将卡密内容传入应用层。
|
||||
func (r *AutomationRepository) GetCard(ctx context.Context, userID, cardID int64) (automationapp.CardInfo, error) {
|
||||
// card、err 保存卡密组摘要及读取失败原因;卡密正文不会进入应用层。
|
||||
card, err := r.store.Cards.Get(ctx, cardID)
|
||||
card, err := r.store.Cards.GetSummary(ctx, cardID)
|
||||
if errors.Is(err, db.ErrNotFound) || (err == nil && (card == nil || card.UserID != userID)) {
|
||||
return automationapp.CardInfo{}, automationapp.ErrRuleNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return automationapp.CardInfo{}, err
|
||||
}
|
||||
return automationapp.CardInfo{Type: card.Type}, nil
|
||||
return automationapp.CardInfo{Type: card.Type, APIReady: card.Type != "api" || card.APIConfigSummary != nil && card.APIConfigSummary.Ready}, nil
|
||||
}
|
||||
|
||||
// AIReplyEnabled 判断账号是否启用了 AI 议价,不读取任何 API 密钥或平台凭证。
|
||||
|
||||
@@ -26,7 +26,7 @@ func (r *CardsRepository) ListForUser(ctx context.Context, userID int64) ([]card
|
||||
return nil, err
|
||||
}
|
||||
// records 是数据库仓储按倒序返回的卡券完整记录。
|
||||
records, err := r.store.Cards.AllForUser(ctx, userID)
|
||||
records, err := r.store.Cards.AllForUserSummary(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -46,7 +46,24 @@ func (r *CardsRepository) Get(ctx context.Context, cardID int64) (cardsapp.Card,
|
||||
return cardsapp.Card{}, err
|
||||
}
|
||||
// record 是数据库返回的完整卡券记录。
|
||||
record, err := r.store.Cards.Get(ctx, cardID)
|
||||
record, err := r.store.Cards.GetSummary(ctx, cardID)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return cardsapp.Card{}, cardsapp.ErrNotFound
|
||||
}
|
||||
return cardsapp.Card{}, err
|
||||
}
|
||||
return cardApplicationModel(*record), nil
|
||||
}
|
||||
|
||||
// GetFull 读取更新时需要保留的完整 API 模板,禁止用于普通查询响应。
|
||||
func (r *CardsRepository) GetFull(ctx context.Context, cardID int64) (cardsapp.Card, error) {
|
||||
// err 表示卡券适配器依赖缺失时的装配错误。
|
||||
if err := r.validate(); err != nil {
|
||||
return cardsapp.Card{}, err
|
||||
}
|
||||
// record、err 保存自动发货专用完整卡券及读取错误。
|
||||
record, err := r.store.Cards.GetForDelivery(ctx, cardID)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return cardsapp.Card{}, cardsapp.ErrNotFound
|
||||
@@ -106,8 +123,21 @@ func (r *CardsRepository) validate() error {
|
||||
|
||||
// cardApplicationModel 将数据库卡券记录转换为基础设施无关的应用模型。
|
||||
func cardApplicationModel(record db.CardFull) cardsapp.Card {
|
||||
// summary 保存数据库摘要对应的应用层脱敏摘要。
|
||||
var summary *cardsapp.APIConfigSummary
|
||||
if record.APIConfigSummary != nil {
|
||||
// summaryValue 保存当前记录的独立摘要副本,避免共享数据库对象。
|
||||
summaryValue := cardsapp.APIConfigSummary{
|
||||
URL: record.APIConfigSummary.URL, Method: record.APIConfigSummary.Method,
|
||||
TimeoutSeconds: record.APIConfigSummary.TimeoutSeconds, ResponsePath: record.APIConfigSummary.ResponsePath,
|
||||
RetryEnabled: record.APIConfigSummary.RetryEnabled, HeadersConfigured: record.APIConfigSummary.HeadersConfigured,
|
||||
ParamsConfigured: record.APIConfigSummary.ParamsConfigured, Ready: record.APIConfigSummary.Ready,
|
||||
ValidationError: record.APIConfigSummary.ValidationError,
|
||||
}
|
||||
summary = &summaryValue
|
||||
}
|
||||
return cardsapp.Card{
|
||||
ID: record.ID, Name: record.Name, Type: record.Type, APIConfig: record.APIConfig,
|
||||
ID: record.ID, Name: record.Name, Type: record.Type, APIConfig: record.APIConfig, APIConfigSummary: summary,
|
||||
TextContent: record.TextContent, DataContent: record.DataContent, ImageURL: record.ImageURL,
|
||||
Description: record.Description, Enabled: record.Enabled, DelaySeconds: record.DelaySeconds,
|
||||
IsMultiSpec: record.IsMultiSpec, SpecName: record.SpecName, SpecValue: record.SpecValue, UserID: record.UserID,
|
||||
|
||||
@@ -2,7 +2,9 @@ package adapter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
notificationsapp "xianyu-go/internal/application/notifications"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
@@ -53,3 +55,11 @@ func (d *MiscDependencies) NewCardsRepository() *CardsRepository {
|
||||
}
|
||||
return NewCardsRepository(d.store)
|
||||
}
|
||||
|
||||
// NewAPICardTester 创建卡券 API 测试适配器,供组合根投影给 HTTP transport。
|
||||
func (d *MiscDependencies) NewAPICardTester(logger *slog.Logger) cardsapp.APIRequestTester {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAPICardTester(d.store, logger)
|
||||
}
|
||||
@@ -86,7 +86,11 @@ func (r *SettingsRepository) ApplySystemChanges(ctx context.Context, values map[
|
||||
for key, change := range secrets {
|
||||
dbSecrets[key] = db.SensitiveSettingChange{Action: change.Action, Value: change.Value}
|
||||
}
|
||||
return r.store.Settings.ApplyChanges(ctx, values, dbSecrets)
|
||||
// err 表示普通设置与敏感设置原子保存错误。
|
||||
if err := r.store.Settings.ApplyChanges(ctx, values, dbSecrets); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetSystem 保存一项普通系统设置。
|
||||
|
||||
@@ -6,11 +6,11 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/netguard"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
@@ -80,21 +80,7 @@ func (a *Adapter) loadRemoteCaptchaConfig(ctx context.Context, cookieID string)
|
||||
|
||||
// newRemoteCaptchaHTTPClient 封装newRemoteCaptchaHTTPClient业务协调。
|
||||
func newRemoteCaptchaHTTPClient() *http.Client {
|
||||
// dialer 用于本次流程后续判断的dialer
|
||||
dialer := &net.Dialer{Timeout: 8 * time.Second, KeepAlive: 30 * time.Second}
|
||||
return &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: dialer.DialContext,
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 20,
|
||||
MaxIdleConnsPerHost: 4,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
TLSHandshakeTimeout: 8 * time.Second,
|
||||
ResponseHeaderTimeout: 90 * time.Second,
|
||||
},
|
||||
Timeout: 90 * time.Second,
|
||||
}
|
||||
return netguard.PolicyHTTPClientWithTimeouts(nil, 90*time.Second, 90*time.Second, 8*time.Second)
|
||||
}
|
||||
|
||||
// callRemoteCaptcha 封装callRemoteCaptcha业务协调。
|
||||
|
||||
@@ -2,6 +2,7 @@ package adapter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
adminapp "xianyu-go/internal/application/admin"
|
||||
analyticsapp "xianyu-go/internal/application/analytics"
|
||||
@@ -29,6 +30,8 @@ type TransportApplicationServiceOptions struct {
|
||||
ChannelSender notificationsapp.ChannelSender
|
||||
// ModelClient 读取远端 AI 模型目录,不得记录 API 密钥。
|
||||
ModelClient settingsapp.ModelClient
|
||||
// OutboundPolicy 提供系统设置切换用户可配置 HTTP 出站策略的运行时 Port。
|
||||
OutboundPolicy settingsapp.OutboundPolicy
|
||||
}
|
||||
|
||||
// TransportApplicationServices 是由进程组合根一次性构造并注入 Server 的应用服务集合。
|
||||
@@ -52,6 +55,8 @@ type TransportApplicationServices struct {
|
||||
AutomationRules *automationapp.RuleService
|
||||
// Cards 提供卡券库存 CRUD 用例。
|
||||
Cards *cardsapp.Service
|
||||
// APICardTester 提供卡券 API 临时测试请求能力。
|
||||
APICardTester cardsapp.APIRequestTester
|
||||
// PublishAutomationRules 提供发布后自动化规则准备流程。
|
||||
PublishAutomationRules *automationapp.PublishRuleService
|
||||
// DefaultReplies 提供默认回复配置与投递记录用例。
|
||||
@@ -84,7 +89,7 @@ func NewTransportApplicationServices(options TransportApplicationServiceOptions)
|
||||
}
|
||||
// services 是进程启动期完成构造、随后作为只读依赖交给 Server 的服务集合。
|
||||
services := &TransportApplicationServices{
|
||||
Settings: settingsapp.NewService(options.AdminSettingsDependencies.NewSettingsRepository(), options.ModelClient),
|
||||
Settings: settingsapp.NewService(options.AdminSettingsDependencies.NewSettingsRepository(), options.ModelClient, options.OutboundPolicy),
|
||||
Admin: adminapp.NewServiceWithRuntime(options.AdminSettingsDependencies.NewAdminRepository(), options.AdminRuntime),
|
||||
AccountTasks: automationapp.NewService(options.AutomationDependencies.NewAccountTaskRepository(), options.AccountTaskRunner),
|
||||
UncertainNotifications: notificationsapp.New(options.MiscDependencies.NewNotificationUncertainRepository()),
|
||||
@@ -93,6 +98,7 @@ func NewTransportApplicationServices(options TransportApplicationServiceOptions)
|
||||
AutomationIssues: automationapp.NewIssueService(automationRepository),
|
||||
AutomationRules: automationapp.NewRuleService(automationRepository, automationRepository),
|
||||
Cards: cardsapp.NewService(options.MiscDependencies.NewCardsRepository()),
|
||||
APICardTester: options.MiscDependencies.NewAPICardTester(slog.Default()),
|
||||
PublishAutomationRules: automationapp.NewPublishRuleService(automationRepository),
|
||||
DefaultReplies: defaultreplyapp.NewService(options.AutomationDependencies.NewDefaultReplyRepository()),
|
||||
Keywords: keywordsapp.NewService(options.AutomationDependencies.NewKeywordRepository()),
|
||||
@@ -109,7 +115,7 @@ func (services *TransportApplicationServices) Validate() error {
|
||||
if services == nil {
|
||||
return fmt.Errorf("transport 应用服务集合不能为空")
|
||||
}
|
||||
if services.Settings == nil || services.Admin == nil || services.AccountTasks == nil || services.UncertainNotifications == nil || services.NotificationChannels == nil || services.Analytics == nil || services.AutomationIssues == nil || services.AutomationRules == nil || services.Cards == nil || services.PublishAutomationRules == nil || services.DefaultReplies == nil || services.Keywords == nil {
|
||||
if services.Settings == nil || services.Admin == nil || services.AccountTasks == nil || services.UncertainNotifications == nil || services.NotificationChannels == nil || services.Analytics == nil || services.AutomationIssues == nil || services.AutomationRules == nil || services.Cards == nil || services.APICardTester == nil || services.PublishAutomationRules == nil || services.DefaultReplies == nil || services.Keywords == nil {
|
||||
return fmt.Errorf("transport 应用服务集合存在未装配服务")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -198,6 +198,8 @@ type RuleFilter struct {
|
||||
type CardInfo struct {
|
||||
// Type 是卡密组类型。
|
||||
Type string
|
||||
// APIReady 表示 API 卡券配置已通过完整校验且允许被规则选择。
|
||||
APIReady bool
|
||||
}
|
||||
|
||||
// RuleRepository 定义规则持久化所需的窄接口。
|
||||
@@ -408,7 +410,7 @@ func (s *RuleService) normalizeDraftActions(ctx context.Context, userID int64, d
|
||||
return actions, flags, nil
|
||||
}
|
||||
|
||||
// validateSendCardAction 校验发卡动作的卡密选择、归属和类型限制。
|
||||
// validateSendCardAction 校验发卡动作的卡密选择和归属;具体卡券类型由执行器处理。
|
||||
func (s *RuleService) validateSendCardAction(ctx context.Context, userID int64, draftAction ActionDraft) error {
|
||||
if draftAction.CardID <= 0 {
|
||||
return errors.New("发送卡密动作必须选择卡密组")
|
||||
@@ -421,8 +423,8 @@ func (s *RuleService) validateSendCardAction(ctx context.Context, userID int64,
|
||||
}
|
||||
return errors.New("卡密组不存在或不属于当前用户")
|
||||
}
|
||||
if card.Type == "api" {
|
||||
return errors.New("API 卡密暂不支持自动发货,请选择文本、批量数据或图片卡密")
|
||||
if card.Type == "api" && !card.APIReady {
|
||||
return errors.New("API 卡券配置无效,请重新保存后再选择")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ func TestRuleServiceNormalizeAppliesDefaults(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuleServiceRejectsInvalidAction 验证不支持的动作和 API 卡密被拒绝。
|
||||
// TestRuleServiceRejectsInvalidAction 验证不支持的动作会被拒绝。
|
||||
func TestRuleServiceRejectsInvalidAction(t *testing.T) {
|
||||
// cases 保存非法规则输入和预期错误。
|
||||
cases := []struct {
|
||||
@@ -171,7 +171,6 @@ func TestRuleServiceRejectsInvalidAction(t *testing.T) {
|
||||
want string
|
||||
}{
|
||||
{name: "unknown action", ownership: &ruleOwnershipFake{}, draft: RuleDraft{CookieID: "a", TriggerType: TriggerBuyerReviewed, Actions: []ActionDraft{{ActionType: "unknown"}}}, want: "不支持的动作"},
|
||||
{name: "api card", ownership: &ruleOwnershipFake{cardType: "api"}, draft: RuleDraft{CookieID: "a", TriggerType: TriggerOrderPaid, Actions: []ActionDraft{{ActionType: ActionSendCard, CardID: 1}}}, want: "API 卡密"},
|
||||
}
|
||||
// testCase 是当前非法规则分支及其预期错误的测试样例。
|
||||
for _, testCase /* testCase 是当前非法规则分支及其预期错误的测试样例。 */ := range cases {
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
package cards
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// APIRequestTestInput 保存前端临时测试的完整配置文本;测试不会写入卡券库存。
|
||||
type APIRequestTestInput struct {
|
||||
// Config 是与卡券保存接口相同的 API 配置 JSON 文本。
|
||||
Config string
|
||||
}
|
||||
|
||||
// APIRequestTestResult 保存一次测试请求的非敏感诊断结果。
|
||||
type APIRequestTestResult struct {
|
||||
// Status 表示远端请求是否返回 2xx。
|
||||
Status string `json:"status"`
|
||||
// StatusCode 是远端 HTTP 状态码;网络错误时为 0。
|
||||
StatusCode int `json:"status_code"`
|
||||
// ResponseContentType 是远端响应声明的媒体类型。
|
||||
ResponseContentType string `json:"response_content_type"`
|
||||
// ResponseFields 是 JSON 顶层字段名称,不包含字段值。
|
||||
ResponseFields []string `json:"response_fields"`
|
||||
// ExtractedValue 是按响应路径提取的限长文本。
|
||||
ExtractedValue string `json:"extracted_value,omitempty"`
|
||||
// ResponsePreview 是限长响应预览,便于用户诊断返回格式。
|
||||
ResponsePreview string `json:"response_preview,omitempty"`
|
||||
}
|
||||
|
||||
// APIRequestTester 定义卡密 API 测试请求的最小应用能力。
|
||||
type APIRequestTester interface {
|
||||
Test(context.Context, APIRequestTestInput) (APIRequestTestResult, error)
|
||||
}
|
||||
|
||||
// apiConfigDocument 是 API 卡券持久化使用的规范化 JSON 文档。
|
||||
type apiConfigDocument struct {
|
||||
URL string `json:"url"`
|
||||
Method string `json:"method"`
|
||||
Timeout int `json:"timeout_seconds"`
|
||||
Headers map[string]any `json:"headers"`
|
||||
Params map[string]any `json:"params"`
|
||||
Body map[string]any `json:"body"`
|
||||
ContentType string `json:"content_type"`
|
||||
ResponsePath string `json:"response_path,omitempty"`
|
||||
RetryEnabled bool `json:"retry_enabled,omitempty"`
|
||||
}
|
||||
|
||||
// APIConfig 是自动发货适配器读取的规范化 API 请求配置;Headers 与 Params 只在服务端内部流转。
|
||||
type APIConfig = apiConfigDocument
|
||||
|
||||
// ParseAPIConfig 解析并校验完整 API 卡券配置,供自动化适配器读取已解密的专用配置。
|
||||
func ParseAPIConfig(raw string) (APIConfig, error) {
|
||||
// normalized 保存兼容旧字段、补齐默认值后的规范化 JSON。
|
||||
normalized, err := normalizeAPIConfig(raw, "")
|
||||
if err != nil {
|
||||
return APIConfig{}, err
|
||||
}
|
||||
// fields 保存规范化 API 配置的 JSON 字段。
|
||||
var fields map[string]json.RawMessage
|
||||
// err 表示规范化配置 JSON 的解析错误。
|
||||
if err := json.Unmarshal([]byte(normalized), &fields); err != nil {
|
||||
return APIConfig{}, fmt.Errorf("API 配置 JSON 无效: %w", err)
|
||||
}
|
||||
// document 保存解码后的 API 执行配置。
|
||||
var document APIConfig
|
||||
// err 表示兼容字段解码错误。
|
||||
if err := decodeAPIConfig(fields, &document); err != nil {
|
||||
return APIConfig{}, err
|
||||
}
|
||||
// err 表示 URL、方法、超时或重试条件校验错误。
|
||||
if err := validateAPIConfig(document); err != nil {
|
||||
return APIConfig{}, err
|
||||
}
|
||||
return document, nil
|
||||
}
|
||||
|
||||
// APIConfigSummary 是卡券查询接口允许返回的 API 配置脱敏摘要。
|
||||
type APIConfigSummary struct {
|
||||
URL string `json:"url"`
|
||||
Method string `json:"method"`
|
||||
TimeoutSeconds int `json:"timeout_seconds"`
|
||||
ContentType string `json:"content_type"`
|
||||
ResponsePath string `json:"response_path,omitempty"`
|
||||
RetryEnabled bool `json:"retry_enabled"`
|
||||
HeadersConfigured bool `json:"headers_configured"`
|
||||
ParamsConfigured bool `json:"params_configured"`
|
||||
Ready bool `json:"ready"`
|
||||
ValidationError string `json:"validation_error,omitempty"`
|
||||
}
|
||||
|
||||
// SummarizeAPIConfig 将完整配置转换为不含请求模板、密钥或响应正文的查询摘要。
|
||||
func SummarizeAPIConfig(raw string) APIConfigSummary {
|
||||
// summary 保存不包含请求模板值的脱敏状态。
|
||||
var summary APIConfigSummary
|
||||
// normalized 保存兼容旧字段、补齐默认值后的规范化 JSON。
|
||||
normalized, err := normalizeAPIConfig(raw, "")
|
||||
if err != nil {
|
||||
summary.ValidationError = err.Error()
|
||||
return summary
|
||||
}
|
||||
// fields 保存规范化配置的 JSON 字段。
|
||||
var fields map[string]json.RawMessage
|
||||
// err 表示规范化配置 JSON 的解析错误。
|
||||
if err := json.Unmarshal([]byte(normalized), &fields); err != nil {
|
||||
summary.ValidationError = "API 配置解析失败"
|
||||
return summary
|
||||
}
|
||||
// document、err 保存摘要解析出的执行配置和解析错误。
|
||||
document, err := decodeAPIConfigForSummary(fields)
|
||||
if err != nil {
|
||||
summary.ValidationError = "API 配置解析失败"
|
||||
return summary
|
||||
}
|
||||
summary.URL, summary.Method, summary.TimeoutSeconds = document.URL, document.Method, document.Timeout
|
||||
summary.ResponsePath, summary.RetryEnabled = document.ResponsePath, document.RetryEnabled
|
||||
summary.ContentType = document.ContentType
|
||||
summary.HeadersConfigured, summary.ParamsConfigured = len(document.Headers) > 0, len(document.Params) > 0
|
||||
// validationErr 保存摘要配置的非敏感校验错误。
|
||||
if validationErr := validateAPIConfig(document); validationErr != nil {
|
||||
summary.ValidationError = validationErr.Error()
|
||||
return summary
|
||||
}
|
||||
summary.Ready = true
|
||||
return summary
|
||||
}
|
||||
|
||||
// decodeAPIConfigForSummary 在不泄漏字段值的前提下解析摘要所需的配置结构。
|
||||
func decodeAPIConfigForSummary(fields map[string]json.RawMessage) (apiConfigDocument, error) {
|
||||
// document 保存摘要使用的执行配置模型。
|
||||
var document apiConfigDocument
|
||||
// err 表示配置字段解码错误。
|
||||
if err := decodeAPIConfig(fields, &document); err != nil {
|
||||
return apiConfigDocument{}, err
|
||||
}
|
||||
return document, nil
|
||||
}
|
||||
|
||||
// normalizeAPIConfig 将新旧 API 配置归一化,并在更新时保留未提交的敏感模板。
|
||||
func normalizeAPIConfig(raw, existing string) (string, error) {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
raw = existing
|
||||
}
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return "", errors.New("API 卡密缺少配置")
|
||||
}
|
||||
// fields 保存新旧 API 配置字段,后续会清理兼容控制字段。
|
||||
var fields map[string]json.RawMessage
|
||||
// err 表示配置 JSON 解析错误。
|
||||
if err := json.Unmarshal([]byte(raw), &fields); err != nil {
|
||||
return "", fmt.Errorf("API 配置 JSON 无效: %w", err)
|
||||
}
|
||||
if fields == nil {
|
||||
return "", errors.New("API 配置必须是 JSON 对象")
|
||||
}
|
||||
// previous 保存更新前的敏感模板,用于 retain 三态操作。
|
||||
var previous map[string]json.RawMessage
|
||||
if strings.TrimSpace(existing) != "" {
|
||||
_ = json.Unmarshal([]byte(existing), &previous)
|
||||
}
|
||||
// action 表示请求头模板的三态更新意图。
|
||||
if err := mergeAPISecretField(fields, previous, "headers"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// action 表示请求参数模板的三态更新意图。
|
||||
if err := mergeAPISecretField(fields, previous, "params"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
delete(fields, "headers_action")
|
||||
delete(fields, "params_action")
|
||||
// timeout 表示历史配置使用的兼容超时字段。
|
||||
if timeout := rawString(fields["timeout"]); timeout != "" && fields["timeout_seconds"] == nil {
|
||||
fields["timeout_seconds"] = json.RawMessage(strconv.Itoa(parseIntDefault(timeout, 10)))
|
||||
}
|
||||
if fields["method"] == nil {
|
||||
fields["method"] = json.RawMessage(`"GET"`)
|
||||
}
|
||||
if fields["timeout_seconds"] == nil {
|
||||
fields["timeout_seconds"] = json.RawMessage("10")
|
||||
}
|
||||
if fields["headers"] == nil {
|
||||
fields["headers"] = json.RawMessage(`{}`)
|
||||
}
|
||||
if fields["params"] == nil {
|
||||
fields["params"] = json.RawMessage(`{}`)
|
||||
}
|
||||
if fields["body"] == nil {
|
||||
fields["body"] = json.RawMessage(`{}`)
|
||||
}
|
||||
if fields["content_type"] == nil {
|
||||
fields["content_type"] = json.RawMessage(`"application/json"`)
|
||||
}
|
||||
// document 保存规范化后的 API 执行配置。
|
||||
var document apiConfigDocument
|
||||
// err 表示兼容字段解码错误。
|
||||
if err := decodeAPIConfig(fields, &document); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// err 表示规范化配置校验错误。
|
||||
if err := validateAPIConfig(document); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// encoded、err 保存规范化 JSON 文本及编码错误。
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("编码 API 配置失败: %w", err)
|
||||
}
|
||||
return string(encoded), nil
|
||||
}
|
||||
|
||||
// mergeAPISecretField 在请求没有提交敏感模板时保留数据库中的旧值。
|
||||
func mergeAPISecretField(fields, previous map[string]json.RawMessage, name string) error {
|
||||
// action 表示当前模板字段的三态更新意图。
|
||||
action := strings.ToLower(strings.TrimSpace(rawString(fields[name+"_action"])))
|
||||
switch action {
|
||||
case "":
|
||||
if fields[name] == nil && previous != nil && previous[name] != nil {
|
||||
fields[name] = previous[name]
|
||||
}
|
||||
case "retain":
|
||||
if previous != nil && previous[name] != nil {
|
||||
fields[name] = previous[name]
|
||||
} else if fields[name] == nil {
|
||||
fields[name] = json.RawMessage(`{}`)
|
||||
}
|
||||
case "replace":
|
||||
if fields[name] == nil {
|
||||
return fmt.Errorf("%s_action=replace 时必须提供 JSON 对象", name)
|
||||
}
|
||||
case "clear":
|
||||
fields[name] = json.RawMessage(`{}`)
|
||||
default:
|
||||
return fmt.Errorf("%s_action 必须是 retain、replace 或 clear", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeAPIConfig 把兼容字段映射为执行器使用的规范化模型。
|
||||
func decodeAPIConfig(fields map[string]json.RawMessage, document *apiConfigDocument) error {
|
||||
// name 表示需要兼容旧版 JSON 字符串表示的敏感模板字段。
|
||||
for _, name := range []string{"headers", "params"} {
|
||||
// raw 保存当前模板字段的原始 JSON。
|
||||
raw := fields[name]
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
continue
|
||||
}
|
||||
// encodedString、encodedObject 分别保存旧字符串模板和规范对象模板。
|
||||
var encodedString string
|
||||
// encodedObject 保存旧版字符串字段解析后的 JSON 对象。
|
||||
var encodedObject map[string]any
|
||||
if json.Unmarshal(raw, &encodedString) == nil {
|
||||
if strings.TrimSpace(encodedString) == "" {
|
||||
fields[name] = json.RawMessage(`{}`)
|
||||
continue
|
||||
}
|
||||
// err 表示旧版模板字符串不是 JSON 对象的错误。
|
||||
if err := json.Unmarshal([]byte(encodedString), &encodedObject); err != nil {
|
||||
return fmt.Errorf("解析 API %s 模板失败: %w", name, err)
|
||||
}
|
||||
// converted、err 保存旧版对象转换后的 JSON 和编码错误。
|
||||
converted, err := json.Marshal(encodedObject)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fields[name] = converted
|
||||
}
|
||||
}
|
||||
// encoded、err 保存字段集合重新编码后的 JSON 和编码错误。
|
||||
encoded, err := json.Marshal(fields)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// err 表示规范字段解码到执行模型时的错误。
|
||||
if err := json.Unmarshal(encoded, document); err != nil {
|
||||
return fmt.Errorf("解析 API 配置失败: %w", err)
|
||||
}
|
||||
if document.Headers == nil {
|
||||
document.Headers = map[string]any{}
|
||||
}
|
||||
if document.Params == nil {
|
||||
document.Params = map[string]any{}
|
||||
}
|
||||
document.Method = strings.ToUpper(strings.TrimSpace(document.Method))
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateAPIConfig 校验 API 地址、方法、超时和幂等重试约束。
|
||||
func validateAPIConfig(document apiConfigDocument) error {
|
||||
// parsed、err 保存 API 地址解析结果及地址格式错误。
|
||||
parsed, err := url.Parse(strings.TrimSpace(document.URL))
|
||||
if err != nil || parsed.Hostname() == "" || parsed.User != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
|
||||
return errors.New("API 地址必须是 HTTP(S) 地址且不能包含用户凭据")
|
||||
}
|
||||
if document.Method != "GET" && document.Method != "POST" {
|
||||
return errors.New("API 请求方法只能是 GET 或 POST")
|
||||
}
|
||||
if document.Timeout < 1 || document.Timeout > 60 {
|
||||
return errors.New("API 超时时间必须在 1 到 60 秒之间")
|
||||
}
|
||||
if document.RetryEnabled && !containsAPIPlaceholder(document.Headers, "{idempotency_key}") && !containsAPIPlaceholder(document.Params, "{idempotency_key}") {
|
||||
return errors.New("启用 API 重试时,请求头或请求参数必须包含 {idempotency_key}")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// containsAPIPlaceholder 递归判断 JSON 模板中是否包含指定占位符。
|
||||
func containsAPIPlaceholder(value any, placeholder string) bool {
|
||||
// current 保存当前递归节点,用于查找幂等键变量。
|
||||
switch current := value.(type) {
|
||||
case string:
|
||||
return strings.Contains(current, placeholder)
|
||||
case map[string]any:
|
||||
// child 表示对象中的递归模板值。
|
||||
for _, child := range current {
|
||||
if containsAPIPlaceholder(child, placeholder) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
// child 表示数组中的递归模板值。
|
||||
for _, child := range current {
|
||||
if containsAPIPlaceholder(child, placeholder) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// rawString 读取 JSON 字段的字符串表示,兼容数字和旧版字符串字段。
|
||||
func rawString(raw json.RawMessage) string {
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return ""
|
||||
}
|
||||
// value 保存字符串类型的 JSON 字段值。
|
||||
var value string
|
||||
if json.Unmarshal(raw, &value) == nil {
|
||||
return value
|
||||
}
|
||||
// generic 保存非字符串 JSON 字段的通用值。
|
||||
var generic any
|
||||
if json.Unmarshal(raw, &generic) == nil {
|
||||
return fmt.Sprint(generic)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// parseIntDefault 将兼容字符串数字转为整数并提供稳定默认值。
|
||||
func parseIntDefault(raw string, fallback int) int {
|
||||
// value、err 保存兼容超时字段的整数值及解析错误。
|
||||
value, err := strconv.Atoi(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package cards
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestParseAPIConfigCompatibilityAndRetryGuard 验证历史字段归一、合法路径和幂等重试前置条件。
|
||||
func TestParseAPIConfigCompatibilityAndRetryGuard(t *testing.T) {
|
||||
// legacy 保存历史项目使用的 timeout、headers 和 params 字符串字段。
|
||||
legacy := `{"url":"https://example.com/card","method":"get","timeout":"12","headers":"{\"Authorization\":\"Bearer secret\"}","params":"{\"order\":\"{order_id}\"}"}`
|
||||
// config、err 保存历史配置归一结果及错误。
|
||||
config, err := normalizeAPIConfig(legacy, "")
|
||||
if err != nil || config == "" {
|
||||
t.Fatalf("历史 API 配置应可归一 config=%q err=%v", config, err)
|
||||
}
|
||||
// document、parseErr 保存归一配置的执行模型。
|
||||
document, parseErr := ParseAPIConfig(config)
|
||||
if parseErr != nil || document.Method != "GET" || document.Timeout != 12 || document.Params["order"] != "{order_id}" {
|
||||
t.Fatalf("历史 API 配置归一错误 document=%+v err=%v", document, parseErr)
|
||||
}
|
||||
// _, retryErr 验证缺少稳定幂等键时拒绝开启重试。
|
||||
if _, retryErr := normalizeAPIConfig(`{"url":"https://example.com","retry_enabled":true,"params":{"order_id":"{order_id}"}}`, ""); retryErr == nil {
|
||||
t.Fatal("启用重试但没有幂等键时必须拒绝保存")
|
||||
}
|
||||
// summary 保存脱敏摘要,确认模板秘密不会进入查询模型。
|
||||
summary := SummarizeAPIConfig(config)
|
||||
if !summary.Ready || !summary.HeadersConfigured || !summary.ParamsConfigured || summary.ValidationError != "" {
|
||||
t.Fatalf("API 摘要错误: %+v", summary)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeAPIConfigThreeStateAndNullGuard 验证敏感模板三态更新及 null 配置不会触发 panic。
|
||||
func TestNormalizeAPIConfigThreeStateAndNullGuard(t *testing.T) {
|
||||
// existing 是包含秘密模板的旧配置,仅用于验证保留和清除语义。
|
||||
existing := `{"url":"https://example.com","headers":{"Authorization":"secret"},"params":{"token":"value"}}`
|
||||
// retained、retainErr 保存 retain 操作的归一结果及错误。
|
||||
retained, retainErr := normalizeAPIConfig(`{"url":"https://example.com","headers_action":"retain","params_action":"retain"}`, existing)
|
||||
if retainErr != nil || retained == "" {
|
||||
t.Fatalf("retain 应保留旧模板 config=%q err=%v", retained, retainErr)
|
||||
}
|
||||
// cleared、clearErr 保存 clear 操作的归一结果及错误。
|
||||
cleared, clearErr := normalizeAPIConfig(`{"url":"https://example.com","headers_action":"clear","params_action":"clear"}`, existing)
|
||||
if clearErr != nil || !containsJSONEmptyObject(cleared, "headers") || !containsJSONEmptyObject(cleared, "params") {
|
||||
t.Fatalf("clear 应清空旧模板 config=%q err=%v", cleared, clearErr)
|
||||
}
|
||||
// replaceErr 保存缺少替换模板时的校验错误。
|
||||
if _, replaceErr := normalizeAPIConfig(`{"url":"https://example.com","headers_action":"replace"}`, existing); replaceErr == nil {
|
||||
t.Fatal("replace 未提供模板时必须拒绝而不是默默保留")
|
||||
}
|
||||
// nullErr 保存 null 配置的校验错误。
|
||||
if _, nullErr := normalizeAPIConfig("null", existing); nullErr == nil {
|
||||
t.Fatal("null API 配置必须返回校验错误")
|
||||
}
|
||||
}
|
||||
|
||||
// containsJSONEmptyObject 判断规范 JSON 中指定模板是否为显式空对象。
|
||||
func containsJSONEmptyObject(raw, key string) bool {
|
||||
// fields 保存规范 JSON 对象,测试只检查模板是否为空而不输出秘密值。
|
||||
var fields map[string]any
|
||||
// err 表示测试 JSON 解析错误。
|
||||
if err := json.Unmarshal([]byte(raw), &fields); err != nil {
|
||||
return false
|
||||
}
|
||||
// value、ok 保存指定字段的对象值及类型判断。
|
||||
value, ok := fields[key].(map[string]any)
|
||||
return ok && len(value) == 0
|
||||
}
|
||||
@@ -21,9 +21,6 @@ var ErrNotFound = errors.New("卡券不存在")
|
||||
// ErrForbidden 表示卡券组存在但不属于当前用户。
|
||||
var ErrForbidden = errors.New("无权操作该卡密组")
|
||||
|
||||
// ErrUnsupportedAPIType 表示当前自动发货链路不允许新建或转换为 API 卡券。
|
||||
var ErrUnsupportedAPIType = errors.New("API 卡密暂不支持自动发货")
|
||||
|
||||
// ErrNotDataType 表示只有 data 类型卡券组允许追加逐行卡密。
|
||||
var ErrNotDataType = errors.New("只有 data(批量卡密)类型支持追加卡密")
|
||||
|
||||
@@ -49,8 +46,10 @@ type Card struct {
|
||||
Name string
|
||||
// Type 是 text、data、image 或历史兼容的 api 类型。
|
||||
Type string
|
||||
// APIConfig 是历史 API 卡券配置;当前仅允许读取或更新既有 API 卡券。
|
||||
// APIConfig 是 API 卡券的规范化 JSON 配置;敏感请求模板由仓储加密保存。
|
||||
APIConfig string
|
||||
// APIConfigSummary 是普通卡券查询可见的 API 配置摘要,不含请求头、参数或密钥。
|
||||
APIConfigSummary *APIConfigSummary
|
||||
// TextContent 是 text 类型自动发货时发送的文本内容。
|
||||
TextContent string
|
||||
// DataContent 是 data 类型尚未消费的逐行卡密库存。
|
||||
@@ -79,7 +78,7 @@ type Draft struct {
|
||||
Name string
|
||||
// Type 是 text、data、image 或历史兼容的 api 类型。
|
||||
Type string
|
||||
// APIConfig 是历史 API 卡券配置;新建 API 卡券仍被业务规则禁止。
|
||||
// APIConfig 是 API 卡券的规范化 JSON 配置。
|
||||
APIConfig string
|
||||
// TextContent 是 text 类型必须提供的非空发货内容。
|
||||
TextContent string
|
||||
@@ -107,6 +106,8 @@ type Repository interface {
|
||||
ListForUser(ctx context.Context, userID int64) ([]Card, error)
|
||||
// Get 按标识读取卡券组;资源缺失时返回 ErrNotFound。
|
||||
Get(ctx context.Context, cardID int64) (Card, error)
|
||||
// GetFull 仅供更新时读取需要保留的敏感 API 模板,调用方不得将结果作为普通响应返回。
|
||||
GetFull(ctx context.Context, cardID int64) (Card, error)
|
||||
// Create 持久化已校验且带所有者的卡券组,并返回新标识。
|
||||
Create(ctx context.Context, card Card) (int64, error)
|
||||
// Update 覆盖指定卡券组的可编辑字段,但不得改变所有者。
|
||||
@@ -168,33 +169,43 @@ func (s *Service) Create(ctx context.Context, userID int64, draft Draft) (int64,
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if draft.Type == "api" {
|
||||
// normalized、normalizeErr 是新建 API 卡配置的规范化结果和校验错误。
|
||||
normalized, normalizeErr := normalizeAPIConfig(draft.APIConfig, "")
|
||||
if normalizeErr != nil {
|
||||
return 0, &ValidationError{Message: normalizeErr.Error()}
|
||||
}
|
||||
draft.APIConfig = normalized
|
||||
}
|
||||
// err 表示卡券草稿未满足类型、内容或延迟范围约束的校验错误。
|
||||
if err := validateDraft(draft); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if draft.Type == "api" {
|
||||
return 0, ErrUnsupportedAPIType
|
||||
}
|
||||
return s.repository.Create(ctx, cardFromDraft(0, userID, draft))
|
||||
}
|
||||
|
||||
// Update 校验 draft 和所有权后更新 cardID;既有 API 卡券可继续编辑,但其他类型不能转换为 API。
|
||||
// Update 校验 draft 和所有权后更新 cardID;API 配置未提交的敏感模板会保留原值。
|
||||
func (s *Service) Update(ctx context.Context, userID, cardID int64, draft Draft) error {
|
||||
// err 表示用户身份或应用仓储未满足执行条件的错误。
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 表示卡券草稿未满足类型、内容或延迟范围约束的校验错误。
|
||||
if err := validateDraft(draft); err != nil {
|
||||
return err
|
||||
}
|
||||
// existing 是已经通过当前用户归属校验的卡券组。
|
||||
existing, err := s.ownedCard(ctx, userID, cardID)
|
||||
existing, err := s.ownedCardFull(ctx, userID, cardID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if draft.Type == "api" && existing.Type != "api" {
|
||||
return ErrUnsupportedAPIType
|
||||
if draft.Type == "api" {
|
||||
// normalized、normalizeErr 合并脱敏编辑请求与数据库中未展示的旧模板。
|
||||
normalized, normalizeErr := normalizeAPIConfig(draft.APIConfig, existing.APIConfig)
|
||||
if normalizeErr != nil {
|
||||
return &ValidationError{Message: normalizeErr.Error()}
|
||||
}
|
||||
draft.APIConfig = normalized
|
||||
}
|
||||
// err 表示卡券草稿未满足类型、内容或延迟范围约束的校验错误。
|
||||
if err := validateDraft(draft); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repository.Update(ctx, cardFromDraft(existing.ID, existing.UserID, draft))
|
||||
}
|
||||
@@ -260,6 +271,22 @@ func (s *Service) ownedCard(ctx context.Context, userID, cardID int64) (Card, er
|
||||
return card, nil
|
||||
}
|
||||
|
||||
// ownedCardFull 读取更新所需的完整卡券配置并验证所有权,敏感内容只在应用内部短暂流转。
|
||||
func (s *Service) ownedCardFull(ctx context.Context, userID, cardID int64) (Card, error) {
|
||||
if cardID <= 0 {
|
||||
return Card{}, ErrInvalidCardID
|
||||
}
|
||||
// card 是更新保留敏感模板所需的完整卡券记录。
|
||||
card, err := s.repository.GetFull(ctx, cardID)
|
||||
if err != nil {
|
||||
return Card{}, err
|
||||
}
|
||||
if card.UserID != userID {
|
||||
return Card{}, ErrForbidden
|
||||
}
|
||||
return card, nil
|
||||
}
|
||||
|
||||
// validateDraft 校验类型、必填内容和延迟范围,保持创建与更新使用同一套规则。
|
||||
func validateDraft(draft Draft) error {
|
||||
if draft.Name == "" || draft.Type == "" {
|
||||
@@ -291,6 +318,10 @@ func validateDraft(draft Draft) error {
|
||||
if err != nil || imageURL.Hostname() == "" || imageURL.User != nil || (imageURL.Scheme != "http" && imageURL.Scheme != "https") {
|
||||
return &ValidationError{Message: "图片卡密 URL 必须是 HTTP(S) 地址"}
|
||||
}
|
||||
case "api":
|
||||
if strings.TrimSpace(draft.APIConfig) == "" {
|
||||
return &ValidationError{Message: "API 卡密配置不能为空"}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -44,6 +44,12 @@ func (r *cardRepositoryStub) Get(_ context.Context, cardID int64) (Card, error)
|
||||
return r.card, r.getErr
|
||||
}
|
||||
|
||||
// GetFull 返回更新用的完整卡券并复用测试替身的错误控制。
|
||||
func (r *cardRepositoryStub) GetFull(_ context.Context, cardID int64) (Card, error) {
|
||||
r.gotCardID = cardID
|
||||
return r.card, r.getErr
|
||||
}
|
||||
|
||||
// Create 记录待创建卡券并返回预设标识或错误。
|
||||
func (r *cardRepositoryStub) Create(_ context.Context, card Card) (int64, error) {
|
||||
r.createdCard = card
|
||||
@@ -146,13 +152,13 @@ func TestServiceCreateValidation(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
// err 表示创建 API 卡券时的业务限制错误。
|
||||
if _, err := service.Create(context.Background(), 7, Draft{Name: "API", Type: "api"}); !errors.Is(err, ErrUnsupportedAPIType) {
|
||||
t.Fatalf("新建 API 卡券应拒绝,err=%v", err)
|
||||
// err 表示创建合法 API 卡券时的业务校验结果。
|
||||
if _, err := service.Create(context.Background(), 7, Draft{Name: "API", Type: "api", APIConfig: `{"url":"https://example.com/card"}`}); err != nil {
|
||||
t.Fatalf("新建 API 卡券应允许,err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceUpdateAndDeleteOwnership 验证更新、删除不会接受请求覆盖所有者,并覆盖 API 转换限制与错误阶段。
|
||||
// TestServiceUpdateAndDeleteOwnership 验证更新、删除不会接受请求覆盖所有者,并覆盖 API 转换与错误阶段。
|
||||
func TestServiceUpdateAndDeleteOwnership(t *testing.T) {
|
||||
// updateErr 是更新持久化失败的预设错误。
|
||||
updateErr := errors.New("update failed")
|
||||
@@ -169,12 +175,13 @@ func TestServiceUpdateAndDeleteOwnership(t *testing.T) {
|
||||
if repository.updatedCard.ID != 5 || repository.updatedCard.UserID != 7 || repository.updatedCard.Name != "new" {
|
||||
t.Fatalf("更新模型未保留标识和所有者:%+v", repository.updatedCard)
|
||||
}
|
||||
// err 表示非 API 卡券转换为 API 类型时的业务错误。
|
||||
if err := service.Update(context.Background(), 7, 5, Draft{Name: "api", Type: "api"}); !errors.Is(err, ErrUnsupportedAPIType) {
|
||||
t.Fatalf("非 API 卡券转换为 API 应拒绝,err=%v", err)
|
||||
}
|
||||
repository.updateErr = nil
|
||||
// err 表示非 API 卡券转换为 API 类型时的业务校验结果。
|
||||
if err := service.Update(context.Background(), 7, 5, Draft{Name: "api", Type: "api", APIConfig: `{"url":"https://example.com/card"}`}); err != nil {
|
||||
t.Fatalf("非 API 卡券转换为 API 应允许,err=%v", err)
|
||||
}
|
||||
repository.card.Type = "api"
|
||||
repository.card.APIConfig = `{"url":"https://example.com/card"}`
|
||||
// err 表示既有 API 卡券继续编辑时的更新结果。
|
||||
if err := service.Update(context.Background(), 7, 5, Draft{Name: "legacy", Type: "api"}); err != nil {
|
||||
t.Fatalf("既有 API 卡券应允许继续编辑,err=%v", err)
|
||||
|
||||
@@ -108,12 +108,20 @@ type ModelClient interface {
|
||||
Fetch(ctx context.Context, baseURL, apiKey string) ([]string, error)
|
||||
}
|
||||
|
||||
// OutboundPolicy 定义系统设置切换用户可配置 HTTP 出站策略所需的最小运行时 Port。
|
||||
type OutboundPolicy interface {
|
||||
// SetPublicOnly 立即切换公网地址限制,不负责持久化设置值。
|
||||
SetPublicOnly(publicOnly bool)
|
||||
}
|
||||
|
||||
// Service 编排设置读取、校验、审计和持久化,不依赖 HTTP 或数据库类型。
|
||||
type Service struct {
|
||||
// repository 提供设置持久化与敏感访问审计能力。
|
||||
repository Repository
|
||||
// modelClient 提供远端模型目录读取能力。
|
||||
modelClient ModelClient
|
||||
// outboundPolicy 保存运行时 HTTP 策略端口,数据库仓储不直接依赖基础设施实现。
|
||||
outboundPolicy OutboundPolicy
|
||||
}
|
||||
|
||||
// IsSensitiveSettingKey 判断 HTTP 兼容层中的设置键是否属于敏感白名单。
|
||||
@@ -122,9 +130,14 @@ func (s *Service) IsSensitiveSettingKey(key string) bool {
|
||||
}
|
||||
|
||||
// NewService 构造设置应用服务。
|
||||
func NewService(repository Repository, modelClient ModelClient) *Service {
|
||||
func NewService(repository Repository, modelClient ModelClient, policies ...OutboundPolicy) *Service {
|
||||
// service 保存调用方提供的设置 Port 与模型客户端。
|
||||
service := &Service{repository: repository, modelClient: modelClient}
|
||||
var policy OutboundPolicy
|
||||
if len(policies) > 0 {
|
||||
policy = policies[0]
|
||||
}
|
||||
// service 保存调用方提供的设置 Port、模型客户端和运行时策略端口。
|
||||
service := &Service{repository: repository, modelClient: modelClient, outboundPolicy: policy}
|
||||
return service
|
||||
}
|
||||
|
||||
@@ -183,7 +196,12 @@ func (s *Service) ApplySystemChanges(ctx context.Context, userID int64, values m
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.repository.ApplySystemChanges(ctx, values, secrets)
|
||||
// err 表示普通设置和敏感设置原子保存失败。
|
||||
if err := s.repository.ApplySystemChanges(ctx, values, secrets); err != nil {
|
||||
return err
|
||||
}
|
||||
s.applyOutboundPolicy(values)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetSystem 保存单项系统设置,并把敏感设置的三态命令统一交给应用层校验。
|
||||
@@ -208,7 +226,16 @@ func (s *Service) SetSystem(ctx context.Context, userID int64, key, value, actio
|
||||
}
|
||||
return s.repository.ApplySystemChanges(ctx, nil, map[string]SecretChange{key: change})
|
||||
}
|
||||
return s.repository.SetSystem(ctx, key, value)
|
||||
// err 表示单项普通设置的业务值校验错误。
|
||||
if err := validateSystemValue(key, value); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 表示单项普通设置持久化失败。
|
||||
if err := s.repository.SetSystem(ctx, key, value); err != nil {
|
||||
return err
|
||||
}
|
||||
s.applyOutboundPolicy(map[string]string{key: value})
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListUser 读取当前用户的全部偏好设置。
|
||||
@@ -380,10 +407,33 @@ func (s *Service) validateValues(values map[string]string) error {
|
||||
if s.repository.IsSensitiveSettingKey(key) {
|
||||
return errors.New("敏感设置必须放入 secrets 命令")
|
||||
}
|
||||
// err 表示批量普通设置的业务值校验错误。
|
||||
if err := validateSystemValue(key, values[key]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateSystemValue 校验具有运行时语义的普通系统设置,避免非法值落库或切换策略。
|
||||
func validateSystemValue(key, value string) error {
|
||||
if key == "outbound_http_public_only" && !strings.EqualFold(strings.TrimSpace(value), "true") && !strings.EqualFold(strings.TrimSpace(value), "false") {
|
||||
return errors.New("outbound_http_public_only 必须是布尔值")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyOutboundPolicy 在系统设置成功持久化后立即同步运行时策略。
|
||||
func (s *Service) applyOutboundPolicy(values map[string]string) {
|
||||
if s == nil || s.outboundPolicy == nil {
|
||||
return
|
||||
}
|
||||
// raw、ok 保存公网限制值及本次变更是否包含该设置。
|
||||
if raw, ok := values["outbound_http_public_only"]; ok {
|
||||
s.outboundPolicy.SetPublicOnly(strings.EqualFold(strings.TrimSpace(raw), "true"))
|
||||
}
|
||||
}
|
||||
|
||||
// validSecretAction 判断敏感设置命令是否具有受支持的三态语义。
|
||||
func validSecretAction(change SecretChange) bool {
|
||||
switch change.Action {
|
||||
|
||||
@@ -29,6 +29,20 @@ type settingsRepositoryFake struct {
|
||||
adjustRuleEnabled bool
|
||||
}
|
||||
|
||||
// outboundPolicyFake 记录应用服务要求立即生效的公网限制状态。
|
||||
type outboundPolicyFake struct {
|
||||
// publicOnly 保存最近一次运行时公网限制状态。
|
||||
publicOnly bool
|
||||
// calls 保存策略切换次数,用于确认数据库保存成功后才切换。
|
||||
calls int
|
||||
}
|
||||
|
||||
// SetPublicOnly 记录测试中的运行时策略切换。
|
||||
func (p *outboundPolicyFake) SetPublicOnly(publicOnly bool) {
|
||||
p.publicOnly = publicOnly
|
||||
p.calls++
|
||||
}
|
||||
|
||||
// IsSensitiveSettingKey 判断测试设置键是否属于敏感集合。
|
||||
func (r *settingsRepositoryFake) IsSensitiveSettingKey(key string) bool {
|
||||
// candidate 是测试敏感键集合中的当前候选值。
|
||||
@@ -192,6 +206,30 @@ func TestServiceRejectsSensitivePlainValue(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceAppliesOutboundPolicyAfterValidation 验证公网限制设置校验和运行时即时生效边界。
|
||||
func TestServiceAppliesOutboundPolicyAfterValidation(t *testing.T) {
|
||||
// repository 是保存系统设置的内存 Port。
|
||||
repository := &settingsRepositoryFake{}
|
||||
// policy 是记录运行时开关状态的测试 Port。
|
||||
policy := &outboundPolicyFake{}
|
||||
// service 是注入策略 Port 的设置应用服务。
|
||||
service := NewService(repository, nil, policy)
|
||||
// err 表示合法公网限制设置的保存错误。
|
||||
if err := service.ApplySystemChanges(context.Background(), 7, map[string]string{"outbound_http_public_only": "true"}, nil); err != nil {
|
||||
t.Fatalf("保存公网限制失败: %v", err)
|
||||
}
|
||||
if !policy.publicOnly || policy.calls != 1 {
|
||||
t.Fatalf("公网限制未即时生效 policy=%+v", policy)
|
||||
}
|
||||
// err 表示非法公网限制设置的保存结果。
|
||||
if err := service.ApplySystemChanges(context.Background(), 7, map[string]string{"outbound_http_public_only": "maybe"}, nil); err == nil {
|
||||
t.Fatal("非法公网限制值必须拒绝")
|
||||
}
|
||||
if policy.calls != 1 {
|
||||
t.Fatalf("非法值不应切换运行时策略 policy=%+v", policy)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceAIReplyOwnershipAndValidation 验证账号 AI 设置的归属和数值约束。
|
||||
func TestServiceAIReplyOwnershipAndValidation(t *testing.T) {
|
||||
// repository 保存测试账号所有者及配置。
|
||||
|
||||
@@ -33,6 +33,8 @@ type automationActionExecutor struct {
|
||||
cookieSource func(context.Context, string) (string, error)
|
||||
// wakeCredentialBlocked 在 Cookie 更新后唤醒凭证阻塞的自动化任务。
|
||||
wakeCredentialBlocked func(context.Context, string)
|
||||
// apiFetcher 为 API 卡发货提供外部请求能力;业务执行器不直接依赖 net/http。
|
||||
apiFetcher func() APICardFetcher
|
||||
// cardLocks 串行化同一卡密组的数据库存取和消费。
|
||||
cardLocks sync.Map
|
||||
}
|
||||
@@ -502,7 +504,7 @@ func (e *automationActionExecutor) sendCard(ctx context.Context, task Task, acti
|
||||
// count 是当前订单需要发送的卡密数量。
|
||||
count := deliverySendCount(task, action)
|
||||
// card 是待发送的卡密组完整配置。
|
||||
card, err := e.store.Cards.Get(ctx, action.CardID)
|
||||
card, err := e.store.Cards.GetForDelivery(ctx, action.CardID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -512,6 +514,9 @@ func (e *automationActionExecutor) sendCard(ctx context.Context, task Task, acti
|
||||
if card.Type == "data" {
|
||||
return e.sendDataCard(ctx, task, card, count)
|
||||
}
|
||||
if card.Type == "api" {
|
||||
return e.sendAPICard(ctx, task, action, card, count)
|
||||
}
|
||||
// sent 是已经成功发送的卡密数量。
|
||||
sent := 0
|
||||
// i 表示当前卡密发送序号。
|
||||
@@ -541,6 +546,45 @@ func (e *automationActionExecutor) sendCard(ctx context.Context, task Task, acti
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
// sendAPICard 按发货单位逐次调用普通 API,并在消息发送失败时保留结果未知状态。
|
||||
func (e *automationActionExecutor) sendAPICard(ctx context.Context, task Task, action db.AutomationAction, card *db.CardFull, count int) (int, error) {
|
||||
// fetcher 是构造期固定的 API 卡发货客户端。
|
||||
var fetcher APICardFetcher
|
||||
if e.apiFetcher != nil {
|
||||
fetcher = e.apiFetcher()
|
||||
}
|
||||
if fetcher == nil {
|
||||
return 0, errors.New("API 卡发货客户端未初始化")
|
||||
}
|
||||
// sent 是已经完成 API 获取和买家消息发送的单位数量。
|
||||
sent := 0
|
||||
// unitIndex 表示从 1 开始的当前 API 发货单位序号。
|
||||
for unitIndex := 1; unitIndex <= count; unitIndex++ {
|
||||
// result、fetchErr 保存当前单位的 API 响应与请求错误。
|
||||
result, fetchErr := fetcher.Fetch(ctx, APICardRequest{
|
||||
Config: card.APIConfig, TriggerKey: buildTriggerKey(task), ActionID: action.ID, CardID: card.ID,
|
||||
UnitIndex: unitIndex, TotalUnits: count, AccountID: task.AccountID, OrderID: task.OrderID,
|
||||
ItemID: task.ItemID, BuyerID: task.BuyerID, ChatID: task.ChatID, SpecName: task.SpecName,
|
||||
SpecValue: task.SpecValue, Quantity: task.Quantity, Amount: task.Amount, TriggerType: task.TriggerType,
|
||||
})
|
||||
if fetchErr != nil {
|
||||
if result.Dispatched {
|
||||
return sent, uncertainAction(fetchErr)
|
||||
}
|
||||
return sent, noRetryAction(fetchErr)
|
||||
}
|
||||
if strings.TrimSpace(result.Content) == "" {
|
||||
return sent, uncertainAction(errors.New("API 卡发货响应没有可发送内容"))
|
||||
}
|
||||
// sendErr 保存已取得卡密后向买家发送消息的结果;此时失败不能安全重放 API 请求。
|
||||
if sendErr := e.sendText(ctx, task, result.Content); sendErr != nil {
|
||||
return sent, uncertainAction(sendErr)
|
||||
}
|
||||
sent++
|
||||
}
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
// sendDataCard 只在卡券锁内完成库存预留与恢复,把外部消息发送放到锁外。
|
||||
func (e *automationActionExecutor) sendDataCard(ctx context.Context, task Task, card *db.CardFull, count int) (int, error) {
|
||||
// sent 是已经成功发送的数据卡密数量。
|
||||
@@ -626,7 +670,7 @@ func (e *automationActionExecutor) cardContent(_ context.Context, card *db.CardF
|
||||
}
|
||||
return "", card.ImageURL, nil
|
||||
case "api":
|
||||
return "", "", fmt.Errorf("自动化中心暂不支持 API 卡密动作")
|
||||
return "", "", fmt.Errorf("API 卡密必须通过 sendAPICard 发送")
|
||||
default:
|
||||
return "", "", fmt.Errorf("未知卡密类型: %s", card.Type)
|
||||
}
|
||||
|
||||
@@ -73,6 +73,54 @@ func TestAutomationActionExecutorPreservesMessageNotSent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// apiCardFetcherStub 记录 API 卡发货请求,供逐单位执行测试使用。
|
||||
type apiCardFetcherStub struct {
|
||||
// requests 保存自动化执行器提交的每个发货单位上下文。
|
||||
requests []APICardRequest
|
||||
}
|
||||
|
||||
// Fetch 返回按单位序号生成的测试卡密,不执行真实网络请求。
|
||||
func (s *apiCardFetcherStub) Fetch(_ context.Context, request APICardRequest) (APICardResult, error) {
|
||||
s.requests = append(s.requests, request)
|
||||
return APICardResult{Content: fmt.Sprintf("API-CODE-%d", request.UnitIndex)}, nil
|
||||
}
|
||||
|
||||
// TestSendAPICardDeliversEachUnit 验证规则数量乘订单数量后逐单位获取并立即发送 API 卡密。
|
||||
func TestSendAPICardDeliversEachUnit(t *testing.T) {
|
||||
// store、cleanup 保存测试数据库和清理函数。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存数据库与执行器共用的测试上下文。
|
||||
ctx := context.Background()
|
||||
// admin 是测试卡券的所有者。
|
||||
admin, err := store.Users.GetByUsername(ctx, "admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// cardID 保存测试 API 卡券组标识。
|
||||
cardID, err := store.Cards.Create(ctx, &db.CardFull{Name: "API", Type: "api", APIConfig: `{"url":"https://example.com"}`, Enabled: true, UserID: admin.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// fetcher 记录每个单位的 API 请求上下文。
|
||||
fetcher := &apiCardFetcherStub{}
|
||||
// sender 保存已经发送给买家的 API 卡密文本。
|
||||
sender := &testSender{}
|
||||
// executor 是注入 API 客户端和在线发送器的动作执行器。
|
||||
executor := automationActionExecutor{store: store, senders: testSenderProvider{sender: sender}, apiFetcher: func() APICardFetcher { return fetcher }}
|
||||
// sent、sendErr 保存四个单位的执行统计和最终错误。
|
||||
sent, sendErr := executor.sendCard(ctx, Task{AccountID: "cid", OrderID: "order", ChatID: "chat", BuyerID: "buyer", Quantity: "2", TriggerType: TriggerOrderPaid}, db.AutomationAction{ID: 8, ActionType: ActionSendCard, CardID: cardID, DeliveryCount: 2, ConfigJSON: "{}"})
|
||||
if sendErr != nil || sent != 4 || len(fetcher.requests) != 4 || len(sender.texts) != 4 {
|
||||
t.Fatalf("API 卡未逐单位发送 sent=%d requests=%d texts=%v err=%v", sent, len(fetcher.requests), sender.texts, sendErr)
|
||||
}
|
||||
// index、request 分别表示发货单位序号和对应的 API 请求上下文。
|
||||
for index, request := range fetcher.requests {
|
||||
if request.UnitIndex != index+1 || request.TotalUnits != 4 {
|
||||
t.Fatalf("单位上下文错误 index=%d request=%+v", index, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendDataCardReleasesInventoryLockBeforeExternalSend 验证第二个库存操作不会等待第一个外部发送完成。
|
||||
func TestSendDataCardReleasesInventoryLockBeforeExternalSend(t *testing.T) {
|
||||
// store、cleanup 保存测试数据库及其清理函数。
|
||||
|
||||
@@ -23,11 +23,11 @@ func (c *Center) handleAIPricingMode(ctx context.Context, task Task) (bool, erro
|
||||
return false, nil
|
||||
}
|
||||
if !autoAdjustEnabled {
|
||||
c.logger.Info("AI 议价已接管订单价格,但商家未开启真实自动改价", "account", task.AccountID, "order_id", task.OrderID)
|
||||
c.logger.Debug("AI 议价已接管订单价格,但商家未开启真实自动改价", "account", task.AccountID, "order_id", task.OrderID)
|
||||
return true, nil
|
||||
}
|
||||
if task.OrderID == "" || task.ChatID == "" || task.BuyerID == "" || task.ItemID == "" {
|
||||
c.logger.Warn("订单事实不足,无法匹配 AI 报价", "account", task.AccountID, "order_id", task.OrderID)
|
||||
c.logger.Debug("订单事实不足,无法匹配 AI 报价", "account", task.AccountID, "order_id", task.OrderID)
|
||||
return true, nil
|
||||
}
|
||||
// quote 是与账号、买家、商品、会话和有效期匹配后原子领取的最新报价;claimErr 是领取错误。
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package automation
|
||||
|
||||
import "context"
|
||||
|
||||
// APICardFetcher 是自动化消费者定义的普通 API 卡发货最小接口。
|
||||
type APICardFetcher interface {
|
||||
// Fetch 为一个发货单位获取卡密内容;Dispatched 表示远端可能已经产生副作用。
|
||||
Fetch(context.Context, APICardRequest) (APICardResult, error)
|
||||
}
|
||||
|
||||
// APICardRequest 描述一次 API 卡发货单位的完整业务上下文,不包含账号 Cookie。
|
||||
type APICardRequest struct {
|
||||
// Config 是已由专用仓储读取的完整 API 配置 JSON。
|
||||
Config string
|
||||
// TriggerKey 是本次自动化运行的稳定防重键。
|
||||
TriggerKey string
|
||||
// ActionID 是规则动作稳定标识。
|
||||
ActionID int64
|
||||
// CardID 是 API 卡券组稳定标识。
|
||||
CardID int64
|
||||
// UnitIndex 是从 1 开始的当前发货单位序号。
|
||||
UnitIndex int
|
||||
// TotalUnits 是本动作本次应发出的总单位数。
|
||||
TotalUnits int
|
||||
// AccountID 是账号或 Cookie 稳定标识。
|
||||
AccountID string
|
||||
// OrderID 是订单稳定标识。
|
||||
OrderID string
|
||||
// ItemID 是商品稳定标识。
|
||||
ItemID string
|
||||
// BuyerID 是买家稳定标识。
|
||||
BuyerID string
|
||||
// ChatID 是聊天会话稳定标识。
|
||||
ChatID string
|
||||
// SpecName 是订单规格名称。
|
||||
SpecName string
|
||||
// SpecValue 是订单规格值。
|
||||
SpecValue string
|
||||
// Quantity 是订单购买数量文本。
|
||||
Quantity string
|
||||
// Amount 是订单金额文本。
|
||||
Amount string
|
||||
// TriggerType 是触发事件类型。
|
||||
TriggerType string
|
||||
}
|
||||
|
||||
// APICardResult 保存 API 卡请求取得的内容及远端副作用状态。
|
||||
type APICardResult struct {
|
||||
// Content 是成功提取并准备发送给买家的卡密文本。
|
||||
Content string
|
||||
// Dispatched 表示请求已发出但最终结果可能不明。
|
||||
Dispatched bool
|
||||
}
|
||||
@@ -135,20 +135,8 @@ type centerDependencies struct {
|
||||
notifier Notifier
|
||||
// cookieSrc 是构造期注入的 Cookie 读取函数。
|
||||
cookieSrc func(context.Context, string) (string, error)
|
||||
}
|
||||
|
||||
// CenterDependencies 保存自动化中心启动时必须固定的外部协作依赖。
|
||||
type CenterDependencies struct {
|
||||
// MTop 提供确认发货使用的 MTOP 协议客户端;为空时使用默认实现。
|
||||
MTop mtop.Client
|
||||
// AccountTaskClient 提供自动评价与商品擦亮的协议调用;使用默认 MTOP 时可自动复用其任务能力。
|
||||
AccountTaskClient AccountTaskClient
|
||||
// OrderDetailFetcher 提供自动发货前的订单详情查询能力。
|
||||
OrderDetailFetcher OrderDetailFetcher
|
||||
// Notifier 接收发货结果通知;为空时不发送通知。
|
||||
Notifier Notifier
|
||||
// CookieSource 提供自动发货读取 Cookie 的可替换边界;为空时读取仓储。
|
||||
CookieSource func(context.Context, string) (string, error)
|
||||
// apiFetcher 提供普通 API 卡发货请求能力。
|
||||
apiFetcher APICardFetcher
|
||||
}
|
||||
|
||||
// New 构造使用默认协议实现的自动化中心。
|
||||
@@ -189,6 +177,7 @@ func NewWithDependencies(store *db.Store, senders SenderProvider, logger *slog.L
|
||||
fetcher: dependencies.OrderDetailFetcher,
|
||||
notifier: dependencies.Notifier,
|
||||
cookieSrc: dependencies.CookieSource,
|
||||
apiFetcher: dependencies.APICardFetcher,
|
||||
},
|
||||
logger: logger.With("subsys", "automation"),
|
||||
}
|
||||
@@ -213,6 +202,7 @@ func NewWithDependencies(store *db.Store, senders SenderProvider, logger *slog.L
|
||||
}
|
||||
return center.store.Cookies.GetValue(ctx, cookieID)
|
||||
},
|
||||
apiFetcher: func() APICardFetcher { return center.dependencies.apiFetcher },
|
||||
wakeCredentialBlocked: center.wakeCredentialBlockedAutomation,
|
||||
}
|
||||
center.notifications = deliveryNotifier{
|
||||
@@ -236,6 +226,7 @@ func NewWithDependencies(store *db.Store, senders SenderProvider, logger *slog.L
|
||||
prepareTask: center.prepareTask,
|
||||
actionDelaySeconds: center.actionDelaySeconds,
|
||||
accountAutomationAllowed: center.accountAutomationAllowed,
|
||||
accountSenderReady: center.accountSenderReady,
|
||||
deferTask: center.deferTask,
|
||||
executeAction: center.executeAction,
|
||||
hasNotifier: func() bool { return center.dependencies.notifier != nil },
|
||||
@@ -272,6 +263,11 @@ func (c *Center) handleTask(ctx context.Context, task Task) (bool, error) {
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := c.facts.record(ctx, task); err != nil {
|
||||
if errors.Is(err, db.ErrForbidden) {
|
||||
// 同一平台交易卡片可能同时送到卖家和买家登录账号;订单已归属其他账号时,绝不能覆盖或执行该副本。
|
||||
c.logger.Debug("跨账号重复订单事件,忽略", "account", task.AccountID, "trigger", task.TriggerType, "order_id", task.OrderID)
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
if task.OrderID != "" {
|
||||
@@ -314,7 +310,7 @@ func (c *Center) handleTask(ctx context.Context, task Task) (bool, error) {
|
||||
return false, err
|
||||
}
|
||||
if len(rules) == 0 {
|
||||
c.logger.Info("无匹配自动化规则,忽略事件", "trigger", task.TriggerType, "order_id", task.OrderID, "item_id", task.ItemID)
|
||||
c.logger.Debug("无匹配自动化规则,忽略事件", "trigger", task.TriggerType, "order_id", task.OrderID, "item_id", task.ItemID)
|
||||
return false, nil
|
||||
}
|
||||
// firstErr 用于本次流程后续判断的firstErr
|
||||
@@ -593,7 +589,7 @@ func (c *Center) actionDelaySeconds(ctx context.Context, action db.AutomationAct
|
||||
}
|
||||
_ = json.Unmarshal([]byte(action.ConfigJSON), &cfg)
|
||||
// card、err 用于本次流程后续判断的card、err
|
||||
card, err := c.store.Cards.Get(ctx, action.CardID)
|
||||
card, err := c.store.Cards.GetSummary(ctx, action.CardID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// CenterDependencies 保存自动化中心启动时必须固定的外部协作依赖。
|
||||
type CenterDependencies struct {
|
||||
// MTop 提供确认发货使用的 MTOP 协议客户端;为空时使用默认实现。
|
||||
MTop mtop.Client
|
||||
// AccountTaskClient 提供自动评价与商品擦亮的协议调用;使用默认 MTOP 时可自动复用其任务能力。
|
||||
AccountTaskClient AccountTaskClient
|
||||
// OrderDetailFetcher 提供自动发货前的订单详情查询能力。
|
||||
OrderDetailFetcher OrderDetailFetcher
|
||||
// Notifier 接收发货结果通知;为空时不发送通知。
|
||||
Notifier Notifier
|
||||
// CookieSource 提供自动发货读取 Cookie 的可替换边界;为空时读取仓储。
|
||||
CookieSource func(context.Context, string) (string, error)
|
||||
// APICardFetcher 提供普通 API 卡发货请求能力;为空时 API 卡执行会明确失败。
|
||||
APICardFetcher APICardFetcher
|
||||
}
|
||||
@@ -237,6 +237,58 @@ func TestMessageDefinitelyNotSentIsRetried(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCenterDoesNotRequestAPICardBeforeWebSocketReady 验证 API 卡密在账号 WebSocket 未就绪时不会先请求外部供应商,避免领到卡密后无法投递。
|
||||
func TestCenterDoesNotRequestAPICardBeforeWebSocketReady(t *testing.T) {
|
||||
// store、cleanup 是本测试使用的 SQLite 自动化存储及资源清理函数。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是创建规则、执行事件和查询运行记录共用的上下文。
|
||||
ctx := context.Background()
|
||||
// admin 是 API 卡密组和自动化规则的所属用户。
|
||||
admin, adminErr := store.Users.GetByUsername(ctx, "admin")
|
||||
if adminErr != nil {
|
||||
t.Fatal(adminErr)
|
||||
}
|
||||
// cardID 是供付款后发货规则引用的 API 卡密组标识。
|
||||
cardID, cardErr := store.Cards.Create(ctx, &db.CardFull{Name: "API", Type: "api", APIConfig: `{"url":"https://example.com"}`, Enabled: true, UserID: admin.ID})
|
||||
if cardErr != nil {
|
||||
t.Fatal(cardErr)
|
||||
}
|
||||
// ruleErr 是创建 API 卡密自动发货规则的数据库错误。
|
||||
if _, ruleErr := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "api-before-websocket", TriggerType: TriggerOrderPaid, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendCard, CardID: cardID, DeliveryCount: 1, Enabled: true}},
|
||||
}); ruleErr != nil {
|
||||
t.Fatal(ruleErr)
|
||||
}
|
||||
// fetcher 记录外部 API 是否被执行;未就绪时其请求列表必须保持为空。
|
||||
fetcher := &apiCardFetcherStub{}
|
||||
// sender 模拟存在账号实例但尚未完成闲鱼 WebSocket 注册的短暂状态。
|
||||
sender := &readinessTestSender{testSender: &testSender{}, ready: false}
|
||||
// center 注入可报告连接就绪状态的发送器和记录 API 请求的测试客户端。
|
||||
center := NewWithDependencies(store, readinessTestProvider{sender: sender}, nil, CenterDependencies{APICardFetcher: fetcher})
|
||||
// task 是需要调用 API 卡密发货的付款事件。
|
||||
task := Task{AccountID: "cid", TriggerType: TriggerOrderPaid, OrderID: "api-wait-websocket", ChatID: "chat", BuyerID: "buyer", Quantity: "1"}
|
||||
// runErr 是连接未就绪时的预期安全重试错误。
|
||||
runErr := center.HandleTask(ctx, task)
|
||||
if !errors.Is(runErr, ErrMessageNotSent) {
|
||||
t.Fatalf("连接未就绪应返回确定未发送错误: %v", runErr)
|
||||
}
|
||||
if len(fetcher.requests) != 0 {
|
||||
t.Fatalf("WebSocket 未就绪时不应请求 API 卡密: %+v", fetcher.requests)
|
||||
}
|
||||
// status、errorMessage 分别是持久化运行状态和用于恢复的错误分类标记。
|
||||
var status, errorMessage string
|
||||
// queryErr 是读取本次付款事件运行状态失败的数据库错误。
|
||||
queryErr := store.DB.QueryRowContext(ctx, `SELECT status,error_message FROM automation_runs WHERE order_id=?`, task.OrderID).Scan(&status, &errorMessage)
|
||||
if queryErr != nil {
|
||||
t.Fatal(queryErr)
|
||||
}
|
||||
if status != "failed" || !strings.HasPrefix(errorMessage, db.SafeRetryErrorPrefix) {
|
||||
t.Fatalf("未就绪 API 发货应进入安全重试: status=%q error=%q", status, errorMessage)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAbortRunActionFailureQuarantinesRun 封装TestAbort运行动作FailureQuarantines运行业务协调。
|
||||
func TestAbortRunActionFailureQuarantinesRun(t *testing.T) {
|
||||
// store、cleanup 用于本次流程后续判断的store、cleanup
|
||||
@@ -1014,10 +1066,12 @@ func TestCenterOrderPaidFetchesOrderDetailMatchesSpecAndQuantity(t *testing.T) {
|
||||
}},
|
||||
})
|
||||
|
||||
err = center.HandleTask(ctx, Task{
|
||||
// task 是模拟 WebSocket 重复投递时保持不变的订单支付事件。
|
||||
task := Task{
|
||||
Source: "ws", AccountID: "cid", CookieStr: "unb=123; _m_h5_tk=tk_1;", TriggerType: TriggerOrderPaid,
|
||||
ChatID: "chat-1", OrderID: "order-1", ItemID: "item-1", BuyerID: "buyer-1", Raw: map[string]any{"message_id": "m1"},
|
||||
})
|
||||
}
|
||||
err = center.HandleTask(ctx, task)
|
||||
if err != nil {
|
||||
t.Fatalf("HandleTask: %v", err)
|
||||
}
|
||||
@@ -1032,6 +1086,15 @@ func TestCenterOrderPaidFetchesOrderDetailMatchesSpecAndQuantity(t *testing.T) {
|
||||
t.Fatalf("texts[%d]=%q want %q", i, sender.texts[i], want)
|
||||
}
|
||||
}
|
||||
// duplicateErr 是同一支付事件被重复投递时不应出现的执行错误;测试同时确保不会重复发卡。
|
||||
duplicateErr := center.HandleTask(ctx, task)
|
||||
if duplicateErr != nil {
|
||||
t.Fatalf("重复支付事件不应执行或报错: %v", duplicateErr)
|
||||
}
|
||||
// got 与 want 分别是重复事件处理后的实际和预期发卡消息数量。
|
||||
if got, want := len(sender.texts), 4; got != want {
|
||||
t.Fatalf("重复支付事件不应重复发送卡密: got=%d want=%d texts=%v", got, want, sender.texts)
|
||||
}
|
||||
// order、err 用于本次流程后续判断的order、err
|
||||
order, err := store.Orders.Get(ctx, "order-1")
|
||||
if err != nil {
|
||||
@@ -1832,6 +1895,87 @@ func TestCenterNoNotifyWhenNoMatchingRule(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCenterSkipsWebSocketOrderEventWithoutIdempotencyKey 验证没有订单 ID 和 updateKey 的卡片不会执行动作,但中心不能因此丢弃含 updateKey 的合法付款事件。
|
||||
func TestCenterSkipsWebSocketOrderEventWithoutIdempotencyKey(t *testing.T) {
|
||||
// store、cleanup 保存测试自动化仓储及其关闭函数。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是创建规则和处理空订单事件共用的上下文。
|
||||
ctx := context.Background()
|
||||
// admin 是创建测试规则的账号所属用户。
|
||||
admin, adminErr := store.Users.GetByUsername(ctx, "admin")
|
||||
if adminErr != nil {
|
||||
t.Fatal(adminErr)
|
||||
}
|
||||
// ruleErr 是创建本应由空防重键跳过的付款后文本动作失败原因。
|
||||
_, ruleErr := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "empty-ws-order", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "must-not-send", Enabled: true}},
|
||||
})
|
||||
if ruleErr != nil {
|
||||
t.Fatal(ruleErr)
|
||||
}
|
||||
// sender 记录所有实际投递;空订单事件必须使其保持为空。
|
||||
sender := &testSender{}
|
||||
// center 是注入可观察发送器的自动化中心。
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
// handleErr 是空防重键事件被安全跳过时不应出现的处理错误。
|
||||
handleErr := center.HandleTask(ctx, Task{Source: "ws", AccountID: "cid", TriggerType: TriggerOrderPaid})
|
||||
if handleErr != nil {
|
||||
t.Fatalf("空防重键 WebSocket 事件应被安全跳过,err=%v", handleErr)
|
||||
}
|
||||
if len(sender.texts) != 0 {
|
||||
t.Fatalf("空防重键 WebSocket 事件不得触发发送动作: %v", sender.texts)
|
||||
}
|
||||
// updateKeyErr 是只有平台业务键、尚未解析出订单 ID 的合法付款事件处理错误。
|
||||
updateKeyErr := center.HandleTask(ctx, Task{Source: "ws", AccountID: "cid", TriggerType: TriggerBuyerReviewed, ChatID: "chat", BuyerID: "buyer", UpdateKey: "chat:platform-order:10:BUYER_RATE_SELLER:26"})
|
||||
if updateKeyErr != nil {
|
||||
t.Fatalf("带 updateKey 的付款事件不应被空订单门禁拦截,err=%v", updateKeyErr)
|
||||
}
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "must-not-send" {
|
||||
t.Fatalf("带 updateKey 的付款事件应继续执行规则动作: %v", sender.texts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCenterIgnoresOrderEventOwnedByAnotherAccount 验证同一平台订单被另一登录账号重复推送时,中心不会把归属保护当作系统错误。
|
||||
func TestCenterIgnoresOrderEventOwnedByAnotherAccount(t *testing.T) {
|
||||
// store、cleanup 保存自动化中心使用的 SQLite 仓储及关闭函数。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是写入账号、订单和处理重复事件共用的上下文。
|
||||
ctx := context.Background()
|
||||
// admin 是测试中两个账号的共同所有者。
|
||||
admin, adminErr := store.Users.GetByUsername(ctx, "admin")
|
||||
if adminErr != nil {
|
||||
t.Fatal(adminErr)
|
||||
}
|
||||
// saveErr 是创建第二个已连接账号的持久化错误。
|
||||
saveErr := store.Cookies.Save(ctx, "other-account", "unb=456; _m_h5_tk=tk_2;", admin.ID)
|
||||
if saveErr != nil {
|
||||
t.Fatal(saveErr)
|
||||
}
|
||||
// orderErr 是预先归属给实际卖家账号的订单事实写入错误。
|
||||
orderErr := store.Orders.Upsert(ctx, "cross-account-order", db.OrderUpsertOpts{CookieID: "cid", ItemID: "item-owner"})
|
||||
if orderErr != nil {
|
||||
t.Fatal(orderErr)
|
||||
}
|
||||
// center 是处理另一账号收到的重复付款卡片的自动化中心。
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
// handleErr 是跨账号重复副本被安全忽略时不应出现的处理错误。
|
||||
handleErr := center.HandleTask(ctx, Task{Source: "ws", AccountID: "other-account", TriggerType: TriggerOrderPaid, OrderID: "cross-account-order"})
|
||||
if handleErr != nil {
|
||||
t.Fatalf("跨账号重复订单事件应被忽略,err=%v", handleErr)
|
||||
}
|
||||
// order、getErr 分别是处理后的归属记录和读取它的错误;归属必须仍保留在原卖家账号。
|
||||
order, getErr := store.Orders.Get(ctx, "cross-account-order")
|
||||
if getErr != nil {
|
||||
t.Fatal(getErr)
|
||||
}
|
||||
if order.CookieID != "cid" {
|
||||
t.Fatalf("跨账号重复事件不应改写订单归属: cookie_id=%q", order.CookieID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDueReviewRequestOrdersHandlesNullSpecColumns 验证订单 spec_name/spec_value 为 NULL
|
||||
// 时(旧库升级数据常见)DueReviewRequestOrders 不报扫描错误。
|
||||
// TestDueReviewRequestOrdersHandlesNullSpecColumns 封装TestDueReview请求订单列表HandlesNullSpecColumns业务协调。
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package automation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// noRetryAction 标记外部动作确定未执行且不应被通用恢复队列再次调用的错误。
|
||||
func noRetryAction(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(err.Error(), db.NoRetryErrorPrefix) {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%s: %w", db.NoRetryErrorPrefix, err)
|
||||
}
|
||||
@@ -66,7 +66,7 @@ type OrderDetail struct {
|
||||
}
|
||||
|
||||
// ExtractTaskFromWS 从一条解密后的 WS 消息中提取系统事件。
|
||||
// 这里只做事实解析:识别平台告诉了我们什么;是否执行自动化由 Center 根据规则决定。
|
||||
// 这里只做事实解析:识别平台告诉了我们什么;是否执行自动化由 Center 根据规则和可用的订单或 updateKey 防重键决定。
|
||||
// ExtractTaskFromWS 封装Extract任务FromWS业务协调。
|
||||
func ExtractTaskFromWS(accountID, cookieStr string, raw map[string]any) *Task {
|
||||
if raw == nil {
|
||||
@@ -203,11 +203,9 @@ func fieldsFromRaw(raw map[string]any) rawFields {
|
||||
f.orderID = matchOrderID(f.reminderURL)
|
||||
}
|
||||
}
|
||||
// 平台交易卡片会随客户端版本把订单事实移动到不同嵌套层级或 JSON 字符串中;
|
||||
// 固定路径未命中时,只补齐仍为空的明确业务字段,不能覆盖已按优先路径解析出的事实。
|
||||
if f.chatID == "" || f.orderID == "" || f.itemID == "" || f.buyerID == "" {
|
||||
supplementEventFacts(&f, raw, 0)
|
||||
}
|
||||
// 平台交易卡片会随客户端版本把订单事实或买卖角色移动到不同嵌套层级或 JSON 字符串中;
|
||||
// 固定路径已取到全部事实时仍需识别角色,避免买家侧卡片被误投递为卖家自动化。
|
||||
supplementEventFacts(&f, raw, 0)
|
||||
return f
|
||||
}
|
||||
|
||||
@@ -288,6 +286,18 @@ func supplementEventFactByKey(fields *rawFields, key string, value any) {
|
||||
if fields.buyerID == "" {
|
||||
fields.buyerID = text
|
||||
}
|
||||
case "role", "orderrole":
|
||||
if fields.orderRole == "" {
|
||||
fields.orderRole = normalizedOrderRole(text)
|
||||
}
|
||||
case "taskname":
|
||||
if fields.orderRole == "" {
|
||||
fields.orderRole = orderRoleFromTaskName(text)
|
||||
}
|
||||
case "biztag":
|
||||
if fields.orderRole == "" {
|
||||
fields.orderRole = orderRoleFromTaskName(bizTaskName(text))
|
||||
}
|
||||
case "reminderurl", "targeturl", "url", "deeplink", "link":
|
||||
supplementEventFactsFromURL(fields, text)
|
||||
}
|
||||
@@ -314,7 +324,7 @@ func directOrderID(value string) string {
|
||||
return value
|
||||
}
|
||||
|
||||
// supplementEventFactsFromURL 从交易跳转链接补齐订单、商品、买家和会话标识。
|
||||
// supplementEventFactsFromURL 从交易跳转链接补齐订单、商品、买家、会话和买卖角色。
|
||||
func supplementEventFactsFromURL(fields *rawFields, rawURL string) {
|
||||
if fields == nil || strings.TrimSpace(rawURL) == "" {
|
||||
return
|
||||
@@ -331,6 +341,9 @@ func supplementEventFactsFromURL(fields *rawFields, rawURL string) {
|
||||
if fields.orderID == "" {
|
||||
fields.orderID = matchOrderID(rawURL)
|
||||
}
|
||||
if fields.orderRole == "" {
|
||||
fields.orderRole = orderRoleFromURL(rawURL)
|
||||
}
|
||||
}
|
||||
|
||||
// isOrderPaidEvent 封装is订单PaidEvent业务协调。
|
||||
@@ -515,9 +528,16 @@ func orderRoleFromURL(rawURL string) string {
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(u.Query().Get("role"))) {
|
||||
return normalizedOrderRole(u.Query().Get("role"))
|
||||
}
|
||||
|
||||
// normalizedOrderRole 只接受平台协议中可识别的买卖双方角色,未知值不得影响事件归属判断。
|
||||
func normalizedOrderRole(value string) string {
|
||||
// role 是去除大小写和空白差异后的平台角色字段。
|
||||
role := strings.ToLower(strings.TrimSpace(value))
|
||||
switch role {
|
||||
case "seller", "buyer":
|
||||
return strings.ToLower(strings.TrimSpace(u.Query().Get("role")))
|
||||
return role
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -176,6 +176,40 @@ func TestExtractTaskFromWS_OrderCreatedUsesNestedFallbackFacts(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractTaskFromWS_OrderEventWithoutOrderIDRetained 验证订单 ID 尚未出现在卡片中时仍保留事件,供后续使用 updateKey 作为防重键完成卡密投递。
|
||||
func TestExtractTaskFromWS_OrderEventWithoutOrderIDRetained(t *testing.T) {
|
||||
// raw 是仅含待付款展示文案、没有订单链接或业务键的非完整交易提示。
|
||||
raw := mustMap(t, `{
|
||||
"1": {"2": "63107041124@goofish", "10": {
|
||||
"redReminder": "等待买家付款",
|
||||
"reminderContent": "[我已拍下,待付款]"
|
||||
}}
|
||||
}`)
|
||||
// task 是解析结果;订单 ID 缺失不应吞掉系统卡片,协调器仍可根据 updateKey 或最终的空键门禁决定是否执行。
|
||||
task := ExtractTaskFromWS("acc1", "cookie", raw)
|
||||
if task == nil || task.TriggerType != TriggerOrderCreated || task.OrderID != "" {
|
||||
t.Fatalf("缺少订单 ID 的交易提示应保留为待协调事件: %+v", task)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractTaskFromWS_NestedBuyerRoleIgnored 验证角色仅存在于备用嵌套链接时,买家侧付款卡片仍不会进入卖家自动化。
|
||||
func TestExtractTaskFromWS_NestedBuyerRoleIgnored(t *testing.T) {
|
||||
// raw 保留完整订单事实,但买卖角色位于新版嵌套 targetUrl,而非旧固定路径。
|
||||
raw := mustMap(t, `{
|
||||
"1": {"2": "63107041124@goofish", "10": {
|
||||
"redReminder": "等待卖家发货",
|
||||
"reminderContent": "[我已付款,等待你发货]",
|
||||
"extJson": "{\"updateKey\":\"63107041124:3310145690545023994:10:TRADE_PAID:26\"}"
|
||||
}},
|
||||
"payload": {"targetUrl": "fleamarket://order_detail?id=3310145690545023994&role=buyer"}
|
||||
}`)
|
||||
// task 是解析结果;当前账号作为买家时不能触发其卖家发货规则。
|
||||
task := ExtractTaskFromWS("acc1", "cookie", raw)
|
||||
if task != nil {
|
||||
t.Fatalf("嵌套买家角色不应进入卖家自动化: %+v", task)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractTaskFromWS_PriceModifiedEventIgnored 验证改价确认卡片不会因“等待买家付款”提示被重复识别为订单创建。
|
||||
func TestExtractTaskFromWS_PriceModifiedEventIgnored(t *testing.T) {
|
||||
// raw 是闲鱼在卖家改价成功后推送的确认卡片,沿用待付款提醒但业务键明确为改价。
|
||||
|
||||
@@ -25,6 +25,8 @@ type automationRunCoordinator struct {
|
||||
actionDelaySeconds func(context.Context, db.AutomationAction) (int, error)
|
||||
// accountAutomationAllowed 检查账号是否仍允许执行外部自动化动作。
|
||||
accountAutomationAllowed func(context.Context, string) (bool, error)
|
||||
// accountSenderReady 判断账号是否已具备可立即发送消息的闲鱼 WebSocket 连接。
|
||||
accountSenderReady func(string) bool
|
||||
// deferTask 持久化等待延迟后继续执行的任务。
|
||||
deferTask func(context.Context, Task, int64) error
|
||||
// executeAction 执行一个已经通过账号门禁的具体外部动作。
|
||||
@@ -45,6 +47,9 @@ func (r automationRunCoordinator) executeRule(ctx context.Context, task Task, ru
|
||||
if skipped {
|
||||
return nil
|
||||
}
|
||||
if run == nil {
|
||||
return errors.New("自动化运行记录缺失,已停止执行外部动作")
|
||||
}
|
||||
task = preparedTask
|
||||
// status 是运行完成时写入数据库的结果状态。
|
||||
status := "success"
|
||||
@@ -190,9 +195,13 @@ func (r automationRunCoordinator) prepareRuleRun(ctx context.Context, task Task,
|
||||
}
|
||||
// runID 是新建运行的数据库主键;started 表示当前事件是否抢到唯一执行权。
|
||||
runID, started, startErr := r.store.Automation.TryStartRun(ctx, newRun)
|
||||
if startErr != nil || !started {
|
||||
if startErr != nil {
|
||||
return Task{}, nil, false, startErr
|
||||
}
|
||||
if !started {
|
||||
// 同一规则的同一事件已由其他投递处理或已完成,不能把空运行记录交给执行阶段。
|
||||
return preparedTask, nil, true, nil
|
||||
}
|
||||
// createdRun 是重新读取的完整运行状态,包含动作游标和累计发送数。
|
||||
createdRun, getErr := r.store.Automation.GetRun(ctx, runID)
|
||||
if getErr != nil {
|
||||
@@ -297,5 +306,18 @@ func (r automationRunCoordinator) executeActionNow(ctx context.Context, task Tas
|
||||
if !allowed {
|
||||
return 0, fmt.Errorf("账号已暂停或停用,取消自动化动作")
|
||||
}
|
||||
if actionNeedsOnlineSender(action) && r.accountSenderReady != nil && !r.accountSenderReady(task.AccountID) {
|
||||
return 0, fmt.Errorf("%w: 账号 %s 的 WebSocket 尚未就绪,未执行消息或卡密动作", ErrMessageNotSent, task.AccountID)
|
||||
}
|
||||
return r.executeAction(ctx, task, action)
|
||||
}
|
||||
|
||||
// actionNeedsOnlineSender 判断动作是否会向买家发送消息;这类动作必须先确认账号 WebSocket 已就绪,避免 API 卡密已领取但无法投递。
|
||||
func actionNeedsOnlineSender(action db.AutomationAction) bool {
|
||||
switch action.ActionType {
|
||||
case ActionSendCard, ActionSendText:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// RecordOutgoingSent 记录已被平台接受的自动化、本程序或官方客户端出站消息。
|
||||
// ctx 控制持久化生命周期;session 提供非敏感会话摘要;key 可能为本地待发送键或平台 PNM 键;text 是用户可见正文;返回已保存消息或持久化错误。
|
||||
func (s *Service) RecordOutgoingSent(ctx context.Context, session db.ChatSession, key, text string) (*db.ChatMessage, error) {
|
||||
// normalizedKey 保存去除空白后的幂等键;本程序发送使用本地键,官方客户端回显使用平台 PNM 键。
|
||||
normalizedKey := strings.TrimSpace(key)
|
||||
if normalizedKey != "" {
|
||||
// existing、updateErr 保存本地待发送记录的状态更新结果;找不到本地键时才把官方回显作为新的权威出站消息写入。
|
||||
existing, updateErr := s.SetOutgoingStatus(ctx, session.CookieID, normalizedKey, "sent")
|
||||
if updateErr == nil {
|
||||
return existing, nil
|
||||
}
|
||||
if !errors.Is(updateErr, db.ErrNotFound) {
|
||||
return nil, updateErr
|
||||
}
|
||||
}
|
||||
// messageKey 保存新出站记录的稳定键;官方回显优先保留平台键以便重复回显幂等,自动化消息仍使用本地生成键。
|
||||
messageKey := normalizedKey
|
||||
if messageKey == "" {
|
||||
messageKey = "sent-" + randomID()
|
||||
}
|
||||
// message 保存已被平台接受、可立即展示的出站消息;它不增加会话未读数。
|
||||
message := db.ChatMessage{MessageKey: messageKey, Direction: "outgoing", SenderID: session.CookieID,
|
||||
SenderName: "我", MessageType: "text", Content: strings.TrimSpace(text), Status: "sent",
|
||||
SentAt: time.Now().UTC().UnixMilli()}
|
||||
// stored、saveErr 保存幂等写入的出站消息及其错误;只有首次写入才广播创建事件。
|
||||
stored, inserted, saveErr := s.repository.SaveMessage(ctx, session, message, false)
|
||||
if saveErr == nil && inserted {
|
||||
s.Publish(session.CookieID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||
}
|
||||
return stored, saveErr
|
||||
}
|
||||
@@ -731,25 +731,6 @@ func (s *Service) CreateOutgoingMedia(ctx context.Context, session db.ChatSessio
|
||||
return stored, err
|
||||
}
|
||||
|
||||
// RecordOutgoingSent captures automatic replies and automation messages. A
|
||||
// supplied key correlates a UI pending message and only updates its status.
|
||||
// RecordOutgoingSent 封装RecordOutgoingSent业务协调。
|
||||
func (s *Service) RecordOutgoingSent(ctx context.Context, session db.ChatSession, key, text string) (*db.ChatMessage, error) {
|
||||
if strings.TrimSpace(key) != "" {
|
||||
return s.SetOutgoingStatus(ctx, session.CookieID, key, "sent")
|
||||
}
|
||||
// message 用于本次流程后续判断的消息
|
||||
message := db.ChatMessage{MessageKey: "sent-" + randomID(), Direction: "outgoing", SenderID: session.CookieID,
|
||||
SenderName: "我", MessageType: "text", Content: strings.TrimSpace(text), Status: "sent",
|
||||
SentAt: time.Now().UTC().UnixMilli()}
|
||||
// stored、err 用于本次流程后续判断的stored、err
|
||||
stored, _, err := s.repository.SaveMessage(ctx, session, message, false)
|
||||
if err == nil {
|
||||
s.Publish(session.CookieID, Event{Type: "message.created", Message: stored, Session: &session})
|
||||
}
|
||||
return stored, err
|
||||
}
|
||||
|
||||
// SetOutgoingStatus 设置Outgoing状态。
|
||||
func (s *Service) SetOutgoingStatus(ctx context.Context, accountID, key, status string) (*db.ChatMessage, error) {
|
||||
// message、err 用于本次流程后续判断的message、err
|
||||
|
||||
@@ -70,6 +70,95 @@ func TestRecordHistoryPageParsesDirectionMediaAndDeduplicates(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordOutgoingSentCreatesPlatformEcho 验证没有本地待发送记录时,官方客户端的稳定平台键仍会创建并广播出站消息。
|
||||
func TestRecordOutgoingSentCreatesPlatformEcho(t *testing.T) {
|
||||
// store、cleanup 保存隔离的 SQLite 聊天存储及其资源释放函数。
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存本次出站回显写入使用的非取消上下文。
|
||||
ctx := context.Background()
|
||||
// service 保存被测聊天领域服务,负责持久化和实时事件发布。
|
||||
service := New(store)
|
||||
// owner 保存账号 account-1 的所有者,用于订阅其应收到的实时消息事件。
|
||||
owner, ownerErr := store.Users.GetByUsername(ctx, "owner")
|
||||
if ownerErr != nil {
|
||||
t.Fatal(ownerErr)
|
||||
}
|
||||
// events、cancel、subscribeErr 保存账号归属过滤后的实时事件流及清理函数。
|
||||
events, cancel, subscribeErr := service.Subscribe(ctx, owner.ID)
|
||||
if subscribeErr != nil {
|
||||
t.Fatal(subscribeErr)
|
||||
}
|
||||
defer cancel()
|
||||
// session 保存官方客户端回显所属的既有会话摘要,不含账号凭证。
|
||||
session := db.ChatSession{CookieID: "account-1", ChatID: "official-client", BuyerID: "buyer-1", BuyerName: "买家"}
|
||||
// message、recordErr 保存首次写入后的出站消息和持久化错误。
|
||||
message, recordErr := service.RecordOutgoingSent(ctx, session, "official-client.PNM", "官方客户端发送")
|
||||
if recordErr != nil {
|
||||
t.Fatal(recordErr)
|
||||
}
|
||||
if message.MessageKey != "official-client.PNM" || message.Direction != "outgoing" || message.Status != "sent" || message.Content != "官方客户端发送" {
|
||||
t.Fatalf("官方客户端回显保存错误: %+v", message)
|
||||
}
|
||||
select {
|
||||
case // event 保存订阅者收到的首次创建事件,必须使用同一平台消息键。
|
||||
event := <-events:
|
||||
if event.Type != "message.created" || event.Message == nil || event.Message.MessageKey != "official-client.PNM" {
|
||||
t.Fatalf("官方客户端回显实时事件错误: %+v", event)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("官方客户端回显未发布实时事件")
|
||||
}
|
||||
// repeated、repeatErr 保存同一平台回显重复到达后的状态更新结果;它必须命中已有消息而不是再插入一条。
|
||||
repeated, repeatErr := service.RecordOutgoingSent(ctx, session, "official-client.PNM", "官方客户端发送")
|
||||
if repeatErr != nil || repeated.ID != message.ID {
|
||||
t.Fatalf("重复官方客户端回显未保持幂等: message=%+v repeated=%+v err=%v", message, repeated, repeatErr)
|
||||
}
|
||||
// rows、listErr 保存会话全部消息,用于确认重复回显没有制造第二个气泡。
|
||||
rows, listErr := store.Chats.ListMessages(ctx, owner.ID, "account-1", "official-client", 0, 20)
|
||||
if listErr != nil || len(rows) != 1 {
|
||||
t.Fatalf("重复官方客户端回显应只有一条消息: rows=%+v err=%v", rows, listErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordOutgoingSentKeepsExistingSessionIdentity 验证未携带对端身份的官方回显不会清空已知会话资料。
|
||||
func TestRecordOutgoingSentKeepsExistingSessionIdentity(t *testing.T) {
|
||||
// store、cleanup 保存隔离数据库及其清理函数。
|
||||
store, cleanup := chatTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存本次会话和消息写入使用的非取消上下文。
|
||||
ctx := context.Background()
|
||||
// service 保存被测聊天服务。
|
||||
service := New(store)
|
||||
// knownSession 保存联系人历史已经解析出的会话身份。
|
||||
knownSession := db.ChatSession{CookieID: "account-1", ChatID: "known-peer", BuyerID: "buyer-1", BuyerName: "已知买家", ItemID: "item-1", ItemTitle: "已知商品"}
|
||||
// upsertErr 保存预置既有会话身份时的数据库错误。
|
||||
if upsertErr := store.Chats.UpsertSession(ctx, knownSession); upsertErr != nil {
|
||||
t.Fatal(upsertErr)
|
||||
}
|
||||
// incompleteSession 模拟少数官方回显缺少 peerUserId 时只能提供账号和会话 ID 的情形。
|
||||
incompleteSession := db.ChatSession{CookieID: "account-1", ChatID: "known-peer"}
|
||||
// recordErr 保存写入缺失对端身份的官方回显时产生的错误。
|
||||
if _, recordErr := service.RecordOutgoingSent(ctx, incompleteSession, "known-peer.PNM", "缺少对端字段的官方回显"); recordErr != nil {
|
||||
t.Fatal(recordErr)
|
||||
}
|
||||
// owner、ownerErr 保存账号归属用户,用于读取最终会话摘要。
|
||||
owner, ownerErr := store.Users.GetByUsername(ctx, "owner")
|
||||
if ownerErr != nil {
|
||||
t.Fatal(ownerErr)
|
||||
}
|
||||
// sessions、listErr 保存写入回显后的联系人列表;原有买家和商品字段必须仍可展示。
|
||||
sessions, listErr := store.Chats.ListSessions(ctx, owner.ID, "account-1", 20)
|
||||
if listErr != nil || len(sessions) != 1 {
|
||||
t.Fatalf("读取官方回显后的会话失败: sessions=%+v err=%v", sessions, listErr)
|
||||
}
|
||||
// session 保存唯一会话,确认缺失字段没有覆盖已知身份。
|
||||
session := sessions[0]
|
||||
if session.BuyerID != "buyer-1" || session.BuyerName != "已知买家" || session.ItemID != "item-1" || session.ItemTitle != "已知商品" {
|
||||
t.Fatalf("官方回显清空了既有会话资料: %+v", session)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecordHistoryPageRepairsStoredAudioPlaceholder 验证历史刷新能把旧版已落库的“[语音]”占位行升级为可播放 AMR 地址。
|
||||
func TestRecordHistoryPageRepairsStoredAudioPlaceholder(t *testing.T) {
|
||||
// store 和 cleanup 分别是 SQLite 测试存储及资源释放函数。
|
||||
|
||||
@@ -114,6 +114,8 @@ type Services struct {
|
||||
automationRules *automationapp.RuleService
|
||||
// cards 是卡券 CRUD、输入校验和所有权编排应用服务。
|
||||
cards *cardsapp.Service
|
||||
// apiCardTester 是卡券 API 测试请求端口。
|
||||
apiCardTester cardsapp.APIRequestTester
|
||||
// publishAutomationRules 是批量发布成功后幂等准备自动化规则的应用服务。
|
||||
publishAutomationRules *automationapp.PublishRuleService
|
||||
// defaultReplies 是默认回复配置与投递记录应用服务。
|
||||
@@ -311,11 +313,13 @@ type TransportPorts struct {
|
||||
AutomationIssues *automationapp.IssueService
|
||||
AutomationRules *automationapp.RuleService
|
||||
Cards *cardsapp.Service
|
||||
PublishAutomationRules *automationapp.PublishRuleService
|
||||
DefaultReplies *defaultreplyapp.Service
|
||||
Keywords *keywordsapp.Service
|
||||
Settings *settingsapp.Service
|
||||
Admin *adminapp.Service
|
||||
// APICardTester 是卡券 API 测试请求应用端口。
|
||||
APICardTester cardsapp.APIRequestTester
|
||||
PublishAutomationRules *automationapp.PublishRuleService
|
||||
DefaultReplies *defaultreplyapp.Service
|
||||
Keywords *keywordsapp.Service
|
||||
Settings *settingsapp.Service
|
||||
Admin *adminapp.Service
|
||||
}
|
||||
|
||||
// TransportPorts 返回已完成构造的只读服务引用;调用方不得在运行期替换任何字段。
|
||||
@@ -335,7 +339,7 @@ func (services *Services) TransportPorts() TransportPorts {
|
||||
AccountSummaries: services.accountSummaries, AccountTasks: services.accountTasks, Chat: services.chat,
|
||||
UncertainNotifications: services.uncertainNotifications, NotificationChannels: services.notificationChannels,
|
||||
Analytics: services.analytics, AutomationIssues: services.automationIssues, AutomationRules: services.automationRules,
|
||||
Cards: services.cards, PublishAutomationRules: services.publishAutomationRules, DefaultReplies: services.defaultReplies,
|
||||
Cards: services.cards, APICardTester: services.apiCardTester, PublishAutomationRules: services.publishAutomationRules, DefaultReplies: services.defaultReplies,
|
||||
Keywords: services.keywords, Settings: services.settings, Admin: services.admin,
|
||||
}
|
||||
}
|
||||
@@ -499,6 +503,7 @@ func New(dependencies Dependencies) (*Services, error) {
|
||||
analytics: dependencies.TransportApplications.Analytics,
|
||||
automationRules: dependencies.TransportApplications.AutomationRules,
|
||||
cards: dependencies.TransportApplications.Cards,
|
||||
apiCardTester: dependencies.TransportApplications.APICardTester,
|
||||
publishAutomationRules: dependencies.TransportApplications.PublishAutomationRules,
|
||||
automationIssues: dependencies.TransportApplications.AutomationIssues,
|
||||
defaultReplies: dependencies.TransportApplications.DefaultReplies,
|
||||
@@ -593,7 +598,7 @@ func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error
|
||||
return nil, "", fmt.Errorf("图片 URL 无效: %s", rawURL)
|
||||
}
|
||||
// client 是限制内网访问的公网 HTTP 客户端;response、responseErr 是下载响应及其网络错误。
|
||||
client := netguard.PublicHTTPClient(30 * time.Second)
|
||||
client := netguard.ConfiguredHTTPClient(30 * time.Second)
|
||||
// response、responseErr 分别是远端图片响应及网络失败;正文必须在本函数返回前关闭。
|
||||
response, responseErr := client.Do(request)
|
||||
if responseErr != nil {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"xianyu-go/internal/browser"
|
||||
composition "xianyu-go/internal/composition"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/netguard"
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/server"
|
||||
)
|
||||
@@ -147,7 +148,7 @@ func BuildRuntime(options RuntimeOptions, infrastructure RuntimeInfrastructure)
|
||||
// transportApplications、transportErr 分别是通知等共享应用服务集合及其构造错误。
|
||||
transportApplications, transportErr := adapter.NewTransportApplicationServices(adapter.TransportApplicationServiceOptions{
|
||||
AutomationDependencies: automationDependencies, MiscDependencies: miscDependencies, AdminSettingsDependencies: adminSettingsDependencies,
|
||||
AdminRuntime: runtimeBundle.Manager, AccountTaskRunner: adapter.NewAccountTaskRunner(runtimeBundle.Automation), ChannelSender: runtimeBundle.Notifier, ModelClient: adapter.NewAIModelClient(),
|
||||
AdminRuntime: runtimeBundle.Manager, AccountTaskRunner: adapter.NewAccountTaskRunner(runtimeBundle.Automation), ChannelSender: runtimeBundle.Notifier, ModelClient: adapter.NewAIModelClient(), OutboundPolicy: netguard.DefaultPolicy(),
|
||||
})
|
||||
if transportErr != nil {
|
||||
return Runtime{}, fmt.Errorf("构造 transport 应用服务失败: %w", transportErr)
|
||||
|
||||
@@ -216,7 +216,7 @@ func ServerDependencies(services *composition.Services, base HTTPDependencies, s
|
||||
AccountSummaries: ports.AccountSummaries, AccountTasks: ports.AccountTasks, Chat: ports.Chat,
|
||||
UncertainNotifications: ports.UncertainNotifications, NotificationChannels: ports.NotificationChannels,
|
||||
Analytics: ports.Analytics, AutomationIssues: ports.AutomationIssues, AutomationRules: ports.AutomationRules,
|
||||
Cards: ports.Cards, PublishAutomationRules: ports.PublishAutomationRules, DefaultReplies: ports.DefaultReplies,
|
||||
Cards: ports.Cards, APIRequestTester: ports.APICardTester, PublishAutomationRules: ports.PublishAutomationRules, DefaultReplies: ports.DefaultReplies,
|
||||
Keywords: ports.Keywords, Settings: ports.Settings, Admin: ports.Admin,
|
||||
}),
|
||||
}, nil
|
||||
|
||||
@@ -14,6 +14,9 @@ var ErrAutomationRunActive = errors.New("规则仍有待处理的自动化运行
|
||||
// SafeRetryErrorPrefix 标记当前动作明确没有产生外部副作用,可以从动作游标安全恢复。
|
||||
const SafeRetryErrorPrefix = "[safe_retry]"
|
||||
|
||||
// NoRetryErrorPrefix 标记当前动作明确不应进入自动化恢复队列。
|
||||
const NoRetryErrorPrefix = "[no_retry]"
|
||||
|
||||
// AutomationRules 管理自动化规则、动作和执行记录。
|
||||
//
|
||||
// 自动化中心不区分触发来源:WS 系统事件、计划任务、后台手动触发都通过
|
||||
@@ -466,7 +469,7 @@ func (a *AutomationRules) Delete(ctx context.Context, userID, ruleID int64) erro
|
||||
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND user_id=? AND deleted_at IS NULL AND NOT EXISTS (
|
||||
SELECT 1 FROM automation_runs ar WHERE ar.rule_id=automation_rules.id
|
||||
AND (ar.status IN ('running','needs_review') OR (ar.status='failed' AND ar.sent_count=0 AND ar.attempt_count<3)))`, ruleID, userID)
|
||||
AND (ar.status IN ('running','needs_review') OR (ar.status='failed' AND ar.sent_count=0 AND ar.attempt_count<3 AND ar.error_message NOT LIKE '[no_retry]%')))`, ruleID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -575,7 +578,7 @@ func (a *AutomationRules) reclaimRun(ctx context.Context, ruleID int64, triggerK
|
||||
WHERE rule_id=? AND trigger_key=?
|
||||
AND ((status='running' AND action_started=0 AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND action_started=0 AND attempt_count<3 AND next_retry_at<=?
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')))`,
|
||||
AND ((sent_count=0 AND error_message NOT LIKE '[no_retry]%') OR error_message LIKE '[safe_retry]%')))`,
|
||||
leaseExpiresAt, ruleID, triggerKey, now, now)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
@@ -708,7 +711,7 @@ func (a *AutomationRules) ClaimRecoveryRun(ctx context.Context, runID, leaseExpi
|
||||
SET status='running',error_message='',lease_expires_at=?,next_retry_at=0,attempt_count=attempt_count+1,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND action_started=0 AND ((status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND attempt_count<3 AND next_retry_at<=?
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')))`, leaseExpiresAt, runID, now, now)
|
||||
AND ((sent_count=0 AND error_message NOT LIKE '[no_retry]%') OR error_message LIKE '[safe_retry]%')))`, leaseExpiresAt, runID, now, now)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -721,7 +724,7 @@ func (a *AutomationRules) ClaimRecoveryRun(ctx context.Context, runID, leaseExpi
|
||||
func (a *AutomationRules) FinishRun(ctx context.Context, id int64, attempt int, status string, sentCount int, errMsg string) error {
|
||||
// nextRetryAt 用于本次流程后续判断的next重试At
|
||||
nextRetryAt := int64(0)
|
||||
if status == "failed" && (sentCount == 0 || strings.HasPrefix(errMsg, SafeRetryErrorPrefix)) {
|
||||
if status == "failed" && (strings.HasPrefix(errMsg, SafeRetryErrorPrefix) || sentCount == 0 && !strings.HasPrefix(errMsg, NoRetryErrorPrefix)) {
|
||||
nextRetryAt = time.Now().UTC().Add(time.Minute).Unix()
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
@@ -764,7 +767,7 @@ SELECT id,rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigg
|
||||
FROM automation_runs
|
||||
WHERE (status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND action_started=0 AND attempt_count<3 AND next_retry_at<=?
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%'))
|
||||
AND ((sent_count=0 AND error_message NOT LIKE '[no_retry]%') OR error_message LIKE '[safe_retry]%'))
|
||||
ORDER BY updated_at,id LIMIT ?`, now, now, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -325,7 +325,7 @@ func (a *AutomationRules) WakeCredentialBlocked(ctx context.Context, cookieID st
|
||||
_, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET next_retry_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND status='failed' AND action_started=0
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')
|
||||
AND ((sent_count=0 AND error_message NOT LIKE '[no_retry]%') OR error_message LIKE '[safe_retry]%')
|
||||
AND (LOWER(error_message) LIKE '%session%' OR error_message LIKE '%登录凭证%'
|
||||
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%'
|
||||
OR LOWER(error_message) LIKE '%websocket%' OR LOWER(error_message) LIKE '%token%'
|
||||
|
||||
@@ -537,6 +537,50 @@ func TestAutomation_TryStartRunRecoversStaleAndUnsentFailedRuns(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomation_NoRetryFailureIsNotRecovered 验证明确不可重试的外部失败不会因零发送量重新入队。
|
||||
func TestAutomation_NoRetryFailureIsNotRecovered(t *testing.T) {
|
||||
// s、cleanup 是本测试使用的临时 SQLite 数据库及清理函数。
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
// ctx 是本测试数据库操作使用的非取消上下文。
|
||||
ctx := context.Background()
|
||||
// userID、cookieID 是规则所属用户和账号标识。
|
||||
userID, cookieID := seedAccount(t, s)
|
||||
// ruleID 是用于创建自动化运行的规则标识。
|
||||
ruleID, err := s.Automation.Create(ctx, makeAutomationRule(cookieID, userID, "i-no-retry", "paid", true, 100))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// runID、started 是新建运行记录的标识和启动结果。
|
||||
runID, started, err := s.Automation.TryStartRun(ctx, AutomationRun{
|
||||
RuleID: ruleID, CookieID: cookieID, OrderID: "order-no-retry", TriggerType: "paid", TriggerKey: "paid:order-no-retry",
|
||||
})
|
||||
if err != nil || !started {
|
||||
t.Fatalf("TryStartRun: id=%d started=%v err=%v", runID, started, err)
|
||||
}
|
||||
// run 是当前运行的尝试信息。
|
||||
run, err := s.Automation.GetRun(ctx, runID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// err 表示完成不可重试运行的持久化错误。
|
||||
if err := s.Automation.FinishRun(ctx, runID, run.AttemptCount, "failed", 0, NoRetryErrorPrefix+": HTTP 400"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// err 表示清除退避时间测试数据的 SQL 错误。
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_runs SET next_retry_at=0 WHERE id=?`, runID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// recoveredStarted 表示清除退避时间后是否错误地重新启动了不可重试运行。
|
||||
_, recoveredStarted, err := s.Automation.TryStartRun(ctx, AutomationRun{RuleID: ruleID, CookieID: cookieID, OrderID: "order-no-retry", TriggerType: "paid", TriggerKey: "paid:order-no-retry"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if recoveredStarted {
|
||||
t.Fatal("不可重试失败不应被自动恢复")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRunAttemptFencesStaleWorker 封装Test自动化运行尝试次数FencesStale工作器业务协调。
|
||||
func TestAutomationRunAttemptFencesStaleWorker(t *testing.T) {
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CardAPIConfigSummary 是数据库向普通查询路径提供的 API 卡脱敏摘要。
|
||||
type CardAPIConfigSummary struct {
|
||||
// URL 是 API 端点地址,不包含请求模板内容。
|
||||
URL string `json:"url"`
|
||||
// Method 是 API 请求方法。
|
||||
Method string `json:"method"`
|
||||
// TimeoutSeconds 是请求超时时间,单位为秒。
|
||||
TimeoutSeconds int `json:"timeout_seconds"`
|
||||
// ResponsePath 是响应提取路径。
|
||||
ResponsePath string `json:"response_path,omitempty"`
|
||||
// RetryEnabled 表示是否启用幂等重试。
|
||||
RetryEnabled bool `json:"retry_enabled"`
|
||||
// HeadersConfigured 表示是否配置了请求头模板。
|
||||
HeadersConfigured bool `json:"headers_configured"`
|
||||
// ParamsConfigured 表示是否配置了请求参数模板。
|
||||
ParamsConfigured bool `json:"params_configured"`
|
||||
// Ready 表示配置能否进入自动化规则选择。
|
||||
Ready bool `json:"ready"`
|
||||
// ValidationError 是不包含秘密值的配置错误。
|
||||
ValidationError string `json:"validation_error,omitempty"`
|
||||
}
|
||||
|
||||
// GetForDelivery 读取自动发货专用的完整卡券配置,普通查询不得调用此方法。
|
||||
func (c *Cards) GetForDelivery(ctx context.Context, cardID int64) (*CardFull, error) {
|
||||
return c.Get(ctx, cardID)
|
||||
}
|
||||
|
||||
// GetSummary 读取单个卡券的脱敏摘要,完整 API 模板不会离开数据库层。
|
||||
func (c *Cards) GetSummary(ctx context.Context, cardID int64) (*CardFull, error) {
|
||||
// card 是内部完整读取后立即脱敏的卡券记录。
|
||||
card, err := c.Get(ctx, cardID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if card.Type == "api" {
|
||||
card.APIConfigSummary = summarizeCardAPIConfig(card.Type, card.APIConfig)
|
||||
card.APIConfig = ""
|
||||
}
|
||||
return card, nil
|
||||
}
|
||||
|
||||
// AllForUserSummary 读取用户卡券列表的脱敏摘要,避免把 API 模板带入应用层。
|
||||
func (c *Cards) AllForUserSummary(ctx context.Context, userID int64) ([]CardFull, error) {
|
||||
// cards 是内部完整读取后逐条脱敏的卡券记录。
|
||||
cards, err := c.AllForUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// i 表示当前需要脱敏处理的卡券列表下标。
|
||||
for i := range cards {
|
||||
if cards[i].Type == "api" {
|
||||
cards[i].APIConfigSummary = summarizeCardAPIConfig(cards[i].Type, cards[i].APIConfig)
|
||||
cards[i].APIConfig = ""
|
||||
}
|
||||
}
|
||||
return cards, nil
|
||||
}
|
||||
|
||||
// summarizeCardAPIConfig 将已解密的 API 配置转换为不含敏感模板的摘要。
|
||||
func summarizeCardAPIConfig(cardType, raw string) *CardAPIConfigSummary {
|
||||
if cardType != "api" {
|
||||
return nil
|
||||
}
|
||||
// summary 是普通卡券查询使用的脱敏结果。
|
||||
summary := &CardAPIConfigSummary{}
|
||||
// fields 是只用于解析非敏感字段和模板是否存在的 JSON 对象。
|
||||
var fields map[string]json.RawMessage
|
||||
// err 表示 API 配置 JSON 解析错误。
|
||||
if err := json.Unmarshal([]byte(raw), &fields); err != nil || fields == nil {
|
||||
summary.ValidationError = "API 配置 JSON 无效"
|
||||
return summary
|
||||
}
|
||||
summary.URL = summaryRawString(fields["url"])
|
||||
summary.Method = strings.ToUpper(summaryRawString(fields["method"]))
|
||||
if summary.Method == "" {
|
||||
summary.Method = "GET"
|
||||
}
|
||||
summary.TimeoutSeconds = parseSummaryTimeout(fields)
|
||||
summary.ResponsePath = summaryRawString(fields["response_path"])
|
||||
summary.RetryEnabled = strings.EqualFold(summaryRawString(fields["retry_enabled"]), "true")
|
||||
summary.HeadersConfigured = templateConfigured(fields["headers"])
|
||||
summary.ParamsConfigured = templateConfigured(fields["params"])
|
||||
// templates 是只在本地校验幂等占位符的临时 JSON 值,不进入返回结构。
|
||||
templates := make(map[string]any, 2)
|
||||
// name 表示当前待读取的敏感模板字段名。
|
||||
for _, name := range []string{"headers", "params"} {
|
||||
// value 保存模板的临时 JSON 值,函数返回前不会写入摘要。
|
||||
var value any
|
||||
// err 表示模板字段解析错误;错误模板不影响公开字段读取。
|
||||
if err := json.Unmarshal(fields[name], &value); err == nil {
|
||||
templates[name] = value
|
||||
}
|
||||
}
|
||||
// err 表示摘要公开字段或重试约束校验错误。
|
||||
if err := validateSummaryAPIConfig(*summary, templates); err != nil {
|
||||
summary.ValidationError = err.Error()
|
||||
return summary
|
||||
}
|
||||
summary.Ready = true
|
||||
return summary
|
||||
}
|
||||
|
||||
// parseSummaryTimeout 兼容历史配置中的 timeout 字段并返回摘要超时。
|
||||
func parseSummaryTimeout(fields map[string]json.RawMessage) int {
|
||||
// raw 保存优先使用的新字段或历史字段。
|
||||
raw := fields["timeout_seconds"]
|
||||
if len(raw) == 0 {
|
||||
raw = fields["timeout"]
|
||||
}
|
||||
// value 保存兼容超时字段的文本值。
|
||||
value := summaryRawString(raw)
|
||||
if value == "" {
|
||||
return 10
|
||||
}
|
||||
// timeout 保存解析后的秒数。
|
||||
timeout, err := strconv.Atoi(strings.TrimSpace(value))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return timeout
|
||||
}
|
||||
|
||||
// summaryRawString 读取摘要解析所需的 JSON 标量文本,不保留原始模板值。
|
||||
func summaryRawString(raw json.RawMessage) string {
|
||||
if len(raw) == 0 {
|
||||
return ""
|
||||
}
|
||||
// value 保存字符串类型 JSON 标量。
|
||||
var value string
|
||||
if json.Unmarshal(raw, &value) == nil {
|
||||
return value
|
||||
}
|
||||
// generic 保存数字或布尔类型 JSON 标量。
|
||||
var generic any
|
||||
if json.Unmarshal(raw, &generic) == nil {
|
||||
return fmt.Sprint(generic)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// templateConfigured 判断模板字段是否存在且不是空对象或空字符串。
|
||||
func templateConfigured(raw json.RawMessage) bool {
|
||||
// value 保存模板字段的紧凑 JSON 形式,仅用于判断是否已配置。
|
||||
value := strings.TrimSpace(string(raw))
|
||||
return value != "" && value != "null" && value != "{}" && value != `""`
|
||||
}
|
||||
|
||||
// validateSummaryAPIConfig 校验摘要中的公开字段及重试占位符约束。
|
||||
func validateSummaryAPIConfig(summary CardAPIConfigSummary, templates map[string]any) error {
|
||||
// parsed 保存公开 API 地址解析结果。
|
||||
parsed, err := url.Parse(strings.TrimSpace(summary.URL))
|
||||
if err != nil || parsed.Hostname() == "" || parsed.User != nil || parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||||
return errors.New("API 地址必须是 HTTP(S) 地址且不能包含用户凭据")
|
||||
}
|
||||
if summary.Method != "GET" && summary.Method != "POST" {
|
||||
return errors.New("API 请求方法只能是 GET 或 POST")
|
||||
}
|
||||
if summary.TimeoutSeconds < 1 || summary.TimeoutSeconds > 60 {
|
||||
return errors.New("API 超时时间必须在 1 到 60 秒之间")
|
||||
}
|
||||
if summary.RetryEnabled && !summaryTemplateContains(templates, "{idempotency_key}") {
|
||||
return errors.New("启用 API 重试时,请求头或请求参数必须包含 {idempotency_key}")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// summaryTemplateContains 递归检查模板是否包含指定占位符。
|
||||
func summaryTemplateContains(value any, placeholder string) bool {
|
||||
// current 保存当前递归节点的模板值。
|
||||
switch current := value.(type) {
|
||||
case string:
|
||||
return strings.Contains(current, placeholder)
|
||||
case map[string]any:
|
||||
// child 表示当前对象中的模板子节点。
|
||||
for _, child := range current {
|
||||
if summaryTemplateContains(child, placeholder) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
// child 表示当前数组中的模板子节点。
|
||||
for _, child := range current {
|
||||
if summaryTemplateContains(child, placeholder) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
+6
-4
@@ -240,12 +240,14 @@ func (s *ChatStore) SaveMessage(ctx context.Context, session ChatSession, messag
|
||||
unreadDelta = 1
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE chat_sessions SET buyer_id=?,buyer_name=?,buyer_avatar_url=?,
|
||||
item_id=?,item_title=?,item_image_url=CASE WHEN ?<>'' THEN ? ELSE item_image_url END,last_message=CASE WHEN last_message_at<=? THEN ? ELSE last_message END,
|
||||
_, err := tx.ExecContext(ctx, `UPDATE chat_sessions SET buyer_id=CASE WHEN ?<>'' THEN ? ELSE buyer_id END,
|
||||
buyer_name=CASE WHEN ?<>'' THEN ? ELSE buyer_name END,buyer_avatar_url=CASE WHEN ?<>'' THEN ? ELSE buyer_avatar_url END,
|
||||
item_id=CASE WHEN ?<>'' THEN ? ELSE item_id END,item_title=CASE WHEN ?<>'' THEN ? ELSE item_title END,
|
||||
item_image_url=CASE WHEN ?<>'' THEN ? ELSE item_image_url END,last_message=CASE WHEN last_message_at<=? THEN ? ELSE last_message END,
|
||||
last_message_at=CASE WHEN last_message_at<=? THEN ? ELSE last_message_at END,
|
||||
unread_count=unread_count+?,updated_at=?
|
||||
WHERE cookie_id=? AND chat_id=?`, session.BuyerID, session.BuyerName, session.BuyerAvatar,
|
||||
session.ItemID, session.ItemTitle, session.ItemImageURL, session.ItemImageURL, message.SentAt, message.Content, message.SentAt, message.SentAt, unreadDelta, now,
|
||||
WHERE cookie_id=? AND chat_id=?`, session.BuyerID, session.BuyerID, session.BuyerName, session.BuyerName, session.BuyerAvatar, session.BuyerAvatar,
|
||||
session.ItemID, session.ItemID, session.ItemTitle, session.ItemTitle, session.ItemImageURL, session.ItemImageURL, message.SentAt, message.Content, message.SentAt, message.SentAt, unreadDelta, now,
|
||||
session.CookieID, session.ChatID); err != nil {
|
||||
return nil, false, fmt.Errorf("更新聊天会话: %w", err)
|
||||
}
|
||||
|
||||
@@ -163,6 +163,8 @@ func (i *Items) MultiQuantityDelivery(ctx context.Context, cookieID, itemID stri
|
||||
type Cards struct {
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
// codec 负责 API 卡请求模板的静态加密与解密;只有完整卡券读取和写入路径使用它。
|
||||
codec *secretCodec
|
||||
}
|
||||
|
||||
// ConsumeBatchData 原子预留一条批量数据卡券(data 类型),返回内容。
|
||||
|
||||
@@ -22,6 +22,30 @@ func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRo
|
||||
return scanItemInfoRows(rows)
|
||||
}
|
||||
|
||||
// GetByCookieItem 读取账号下指定商品的详情文本,供 API 发货模板使用;不存在时返回空记录而非猜测商品内容。
|
||||
func (i *Items) GetByCookieItem(ctx context.Context, cookieID, itemID string) (ItemInfoRow, error) {
|
||||
// row 保存当前账号与商品标识匹配到的本地商品详情。
|
||||
var row ItemInfoRow
|
||||
// isMulti、multiQty 保存数据库整数标记的布尔转换中间值。
|
||||
var isMulti, multiQty int
|
||||
// err 表示商品详情查询或扫描错误。
|
||||
err := i.DB.QueryRowContext(ctx,
|
||||
`SELECT id, cookie_id, item_id, COALESCE(item_title,''), COALESCE(item_description,''),
|
||||
COALESCE(item_category,''), COALESCE(item_price,''), COALESCE(item_detail,''),
|
||||
is_multi_spec, COALESCE(multi_quantity_delivery,0)
|
||||
FROM item_info WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID).Scan(
|
||||
&row.ID, &row.CookieID, &row.ItemID, &row.ItemTitle, &row.ItemDescription,
|
||||
&row.ItemCategory, &row.ItemPrice, &row.ItemDetail, &isMulti, &multiQty)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ItemInfoRow{}, ErrNotFound
|
||||
}
|
||||
return ItemInfoRow{}, err
|
||||
}
|
||||
row.IsMultiSpec, row.MultiQuantityDelivery = isMulti != 0, multiQty != 0
|
||||
return row, nil
|
||||
}
|
||||
|
||||
// ListForUser 一次查询用户范围内的全部商品,可选按账号 ID 过滤。
|
||||
func (i *Items) ListForUser(ctx context.Context, userID int64, cookieID string) ([]ItemInfoRow, error) {
|
||||
// rows、err 保存用户范围商品查询结果及错误。
|
||||
|
||||
@@ -146,13 +146,13 @@ func TestMigrate_UpgradesDatabaseWithMainChatVersions(t *testing.T) {
|
||||
if !tableExists(t, rawDB, "chat_quick_replies") || !tableExists(t, rawDB, "chat_buyer_notes") {
|
||||
t.Fatal("chat quick reply and buyer note tables should be created by the latest migration")
|
||||
}
|
||||
// finalVersion 验证迁移账本已推进到包含聊天元数据的最新 dev schema 版本。
|
||||
// finalVersion 验证迁移账本已推进到包含 API 发货策略的最新 dev schema 版本。
|
||||
finalVersion, versionErr := goose.GetDBVersion(rawDB)
|
||||
if versionErr != nil {
|
||||
t.Fatalf("read final migration version: %v", versionErr)
|
||||
}
|
||||
if finalVersion != 36 {
|
||||
t.Fatalf("final migration version=%d, want 36", finalVersion)
|
||||
if finalVersion != 37 {
|
||||
t.Fatalf("final migration version=%d, want 37", finalVersion)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ CREATE TABLE ai_bargain_quotes (
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_ai_bargain_quotes_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE,
|
||||
UNIQUE KEY uq_ai_bargain_quotes_order (cookie_id, order_id),
|
||||
KEY idx_ai_bargain_quotes_pending (cookie_id, buyer_id, item_id, chat_id, status, expires_at, id)
|
||||
KEY idx_ai_bargain_quotes_pending (cookie_id(64), buyer_id(64), item_id(64), chat_id(64), status, expires_at, id)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
INSERT INTO system_settings (`key`, value, description)
|
||||
VALUES ('outbound_http_public_only', 'false', '是否限制用户配置的 HTTP 出站请求只能访问公网地址')
|
||||
ON DUPLICATE KEY UPDATE `key`=`key`;
|
||||
-- +goose Down
|
||||
DELETE FROM system_settings WHERE `key` = 'outbound_http_public_only';
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
INSERT INTO "system_settings" ("key", value, description)
|
||||
VALUES ('outbound_http_public_only', 'false', '是否限制用户配置的 HTTP 出站请求只能访问公网地址')
|
||||
ON CONFLICT ("key") DO NOTHING;
|
||||
-- +goose Down
|
||||
DELETE FROM "system_settings" WHERE "key" = 'outbound_http_public_only';
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
INSERT OR IGNORE INTO system_settings (key, value, description)
|
||||
VALUES ('outbound_http_public_only', 'false', '是否限制用户配置的 HTTP 出站请求只能访问公网地址');
|
||||
-- +goose Down
|
||||
DELETE FROM system_settings WHERE key = 'outbound_http_public_only';
|
||||
+52
-19
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -364,20 +365,22 @@ func (i *Items) AllTitles(ctx context.Context) (map[string]string, error) {
|
||||
|
||||
// CardFull 卡券完整信息(CRUD 用)。
|
||||
type CardFull struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
APIConfig string `json:"api_config"`
|
||||
TextContent string `json:"text_content"`
|
||||
DataContent string `json:"data_content"`
|
||||
ImageURL string `json:"image_url"`
|
||||
Description string `json:"description"`
|
||||
Enabled bool `json:"enabled"`
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
IsMultiSpec bool `json:"is_multi_spec"`
|
||||
SpecName string `json:"spec_name"`
|
||||
SpecValue string `json:"spec_value"`
|
||||
UserID int64 `json:"user_id"`
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
APIConfig string `json:"api_config"`
|
||||
// APIConfigSummary 是脱敏查询路径使用的摘要;数据库层不会把完整模板交给上层。
|
||||
APIConfigSummary *CardAPIConfigSummary `json:"-"`
|
||||
TextContent string `json:"text_content"`
|
||||
DataContent string `json:"data_content"`
|
||||
ImageURL string `json:"image_url"`
|
||||
Description string `json:"description"`
|
||||
Enabled bool `json:"enabled"`
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
IsMultiSpec bool `json:"is_multi_spec"`
|
||||
SpecName string `json:"spec_name"`
|
||||
SpecValue string `json:"spec_value"`
|
||||
UserID int64 `json:"user_id"`
|
||||
}
|
||||
|
||||
// ExistsOwned 判断卡密组是否属于指定用户。
|
||||
@@ -410,7 +413,9 @@ func (c *Cards) Get(ctx context.Context, cardID int64) (*CardFull, error) {
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
cf.APIConfig = apiCfg.String
|
||||
if cf.APIConfig, err = c.decryptAPIConfig(cf.Type, cf.UserID, apiCfg.String); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cf.TextContent = textContent.String
|
||||
cf.DataContent = dataContent.String
|
||||
cf.ImageURL = imageURL.String
|
||||
@@ -447,7 +452,9 @@ func (c *Cards) AllForUser(ctx context.Context, userID int64) ([]CardFull, error
|
||||
&enabled, &cf.DelaySeconds, &isMultiSpec, &specName, &specValue, &cf.UserID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cf.APIConfig = apiCfg.String
|
||||
if cf.APIConfig, err = c.decryptAPIConfig(cf.Type, cf.UserID, apiCfg.String); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cf.TextContent = textContent.String
|
||||
cf.DataContent = dataContent.String
|
||||
cf.ImageURL = imageURL.String
|
||||
@@ -463,28 +470,54 @@ func (c *Cards) AllForUser(ctx context.Context, userID int64) ([]CardFull, error
|
||||
|
||||
// Create 创建卡券,返回新 ID。
|
||||
func (c *Cards) Create(ctx context.Context, cf *CardFull) (int64, error) {
|
||||
// apiConfig 保存写入数据库前按用户所有权加密后的 API 请求模板。
|
||||
apiConfig, err := c.encryptAPIConfig(cf.Type, cf.UserID, cf.APIConfig)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return insertReturningID(ctx, c.DB, c.Dialect,
|
||||
`INSERT INTO cards (name, type, api_config, text_content, data_content, image_url, description,
|
||||
enabled, delay_seconds, is_multi_spec, spec_name, spec_value, user_id)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
cf.Name, cf.Type, nullable(cf.APIConfig), nullable(cf.TextContent), nullable(cf.DataContent),
|
||||
cf.Name, cf.Type, nullable(apiConfig), nullable(cf.TextContent), nullable(cf.DataContent),
|
||||
nullable(cf.ImageURL), nullable(cf.Description), boolToInt(cf.Enabled), cf.DelaySeconds,
|
||||
boolToInt(cf.IsMultiSpec), nullable(cf.SpecName), nullable(cf.SpecValue), cf.UserID)
|
||||
}
|
||||
|
||||
// Update 更新卡券。
|
||||
func (c *Cards) Update(ctx context.Context, cf *CardFull) error {
|
||||
// apiConfig 保存更新写入数据库前按用户所有权加密后的 API 请求模板。
|
||||
apiConfig, err := c.encryptAPIConfig(cf.Type, cf.UserID, cf.APIConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := c.DB.ExecContext(ctx,
|
||||
_, err = c.DB.ExecContext(ctx,
|
||||
`UPDATE cards SET name=?, type=?, api_config=?, text_content=?, data_content=?, image_url=?,
|
||||
description=?, enabled=?, delay_seconds=?, is_multi_spec=?, spec_name=?, spec_value=?, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=?`,
|
||||
cf.Name, cf.Type, nullable(cf.APIConfig), nullable(cf.TextContent), nullable(cf.DataContent),
|
||||
cf.Name, cf.Type, nullable(apiConfig), nullable(cf.TextContent), nullable(cf.DataContent),
|
||||
nullable(cf.ImageURL), nullable(cf.Description), boolToInt(cf.Enabled), cf.DelaySeconds,
|
||||
boolToInt(cf.IsMultiSpec), nullable(cf.SpecName), nullable(cf.SpecValue), cf.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
// encryptAPIConfig 仅对 API 卡券的完整请求模板做静态加密,其他卡券类型保持原有存储语义。
|
||||
func (c *Cards) encryptAPIConfig(cardType string, userID int64, value string) (string, error) {
|
||||
if strings.ToLower(strings.TrimSpace(cardType)) != "api" || strings.TrimSpace(value) == "" {
|
||||
return value, nil
|
||||
}
|
||||
return c.codec.encrypt(cardAPIConfigScope, fmt.Sprint(userID), value)
|
||||
}
|
||||
|
||||
// decryptAPIConfig 读取完整 API 卡券配置;数据库密钥错误时拒绝继续执行自动化。
|
||||
func (c *Cards) decryptAPIConfig(cardType string, userID int64, value string) (string, error) {
|
||||
if strings.ToLower(strings.TrimSpace(cardType)) != "api" || strings.TrimSpace(value) == "" {
|
||||
return value, nil
|
||||
}
|
||||
return c.codec.decrypt(cardAPIConfigScope, fmt.Sprint(userID), value)
|
||||
}
|
||||
|
||||
// Delete 删除卡券。
|
||||
func (c *Cards) Delete(ctx context.Context, cardID int64) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
|
||||
+11
-156
@@ -19,6 +19,7 @@ import (
|
||||
const (
|
||||
encryptedValuePrefix = "enc:v1:"
|
||||
cookieMetadataScope = "cookie-metadata"
|
||||
cardAPIConfigScope = "card-api-config"
|
||||
)
|
||||
|
||||
// secretCodec 对数据库敏感字段做 AES-256-GCM 信封加密。未配置密钥时保持
|
||||
@@ -95,173 +96,27 @@ func (s *Store) EncryptLegacySecrets(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// cookieSecret 用于本次流程后续判断的登录凭证Secret
|
||||
type cookieSecret struct{ id, value, password, metadata string }
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := tx.QueryContext(ctx, `SELECT id,value,COALESCE(password,''),COALESCE(metadata_json,'') FROM cookies`)
|
||||
if err != nil {
|
||||
// err 表示历史账号秘密迁移错误。
|
||||
if err := migrateLegacyCookies(ctx, tx, codec); err != nil {
|
||||
return err
|
||||
}
|
||||
// cookies 用于本次流程后续判断的cookies
|
||||
var cookies []cookieSecret
|
||||
for rows.Next() {
|
||||
// row 用于本次流程后续判断的row
|
||||
var row cookieSecret
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&row.id, &row.value, &row.password, &row.metadata); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
cookies = append(cookies, row)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Close(); err != nil {
|
||||
// err 表示历史账号令牌迁移错误。
|
||||
if err := migrateLegacyTokens(ctx, tx, codec); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前遍历过程中的row
|
||||
for _, row := range cookies {
|
||||
// value、err 用于本次流程后续判断的value、err
|
||||
value, err := codec.encrypt("cookie", row.id, row.value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s Cookie: %w", row.id, err)
|
||||
}
|
||||
// password、err 用于本次流程后续判断的password、err
|
||||
password, err := codec.encrypt("login-password", row.id, row.password)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s 登录密码: %w", row.id, err)
|
||||
}
|
||||
// metadata、err 用于本次流程后续判断的metadata、err
|
||||
metadata, err := codec.encrypt(cookieMetadataScope, row.id, row.metadata)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s Cookie metadata: %w", row.id, err)
|
||||
}
|
||||
if value != row.value || password != row.password || metadata != row.metadata {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE cookies SET value=?,password=?,metadata_json=? WHERE id=?`, value, password, metadata, row.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
// tokenSecret 用于本次流程后续判断的令牌Secret
|
||||
type tokenSecret struct{ cookieID, deviceID, accessToken string }
|
||||
rows, err = tx.QueryContext(ctx, `SELECT cookie_id,device_id,access_token FROM account_tokens`)
|
||||
if err != nil {
|
||||
// err 表示历史敏感系统设置迁移错误。
|
||||
if err := migrateLegacySettings(ctx, tx, codec, s.Dialect); err != nil {
|
||||
return err
|
||||
}
|
||||
// tokens 用于本次流程后续判断的tokens
|
||||
var tokens []tokenSecret
|
||||
for rows.Next() {
|
||||
// row 用于本次流程后续判断的row
|
||||
var row tokenSecret
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&row.cookieID, &row.deviceID, &row.accessToken); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
tokens = append(tokens, row)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Close(); err != nil {
|
||||
// err 表示历史通知渠道迁移错误。
|
||||
if err := migrateLegacyNotificationChannels(ctx, tx, codec); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前遍历过程中的row
|
||||
for _, row := range tokens {
|
||||
// deviceID、err 用于本次流程后续判断的deviceID、err
|
||||
deviceID, err := codec.encrypt("device-id", row.cookieID, row.deviceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// accessToken、err 用于本次流程后续判断的accessToken、err
|
||||
accessToken, err := codec.encrypt("access-token", row.cookieID, row.accessToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if deviceID != row.deviceID || accessToken != row.accessToken {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE account_tokens SET device_id=?,access_token=? WHERE cookie_id=?`, deviceID, accessToken, row.cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// keyCol 用于本次流程后续判断的keyCol
|
||||
keyCol := dialectQuote(s.Dialect, "key")
|
||||
rows, err = tx.QueryContext(ctx, `SELECT `+keyCol+`,value FROM system_settings`)
|
||||
if err != nil {
|
||||
// err 表示历史 API 卡券配置迁移错误。
|
||||
if err := migrateLegacyCardAPIConfigs(ctx, tx, codec); err != nil {
|
||||
return err
|
||||
}
|
||||
// settings 用于本次流程后续判断的设置
|
||||
settings := make(map[string]string)
|
||||
for rows.Next() {
|
||||
// key、value 用于本次流程后续判断的key、value
|
||||
var key, value string
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&key, &value); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if isSensitiveSettingKey(key) {
|
||||
settings[key] = value
|
||||
}
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
// key、value 表示当前遍历过程中的key、value
|
||||
for key, value := range settings {
|
||||
// encrypted、err 用于本次流程后续判断的encrypted、err
|
||||
encrypted, err := codec.encrypt("system-setting", key, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if encrypted != value {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE system_settings SET value=? WHERE `+keyCol+`=?`, encrypted, key); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// channelSecret 用于本次流程后续判断的渠道Secret
|
||||
type channelSecret struct {
|
||||
id, userID int64
|
||||
config string
|
||||
}
|
||||
rows, err = tx.QueryContext(ctx, `SELECT id,COALESCE(user_id,1),config FROM notification_channels`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// channels 用于本次流程后续判断的渠道列表
|
||||
var channels []channelSecret
|
||||
for rows.Next() {
|
||||
// row 用于本次流程后续判断的row
|
||||
var row channelSecret
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&row.id, &row.userID, &row.config); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
channels = append(channels, row)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前遍历过程中的row
|
||||
for _, row := range channels {
|
||||
// encrypted、err 用于本次流程后续判断的encrypted、err
|
||||
encrypted, err := codec.encrypt("notification-config", fmt.Sprint(row.userID), row.config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if encrypted != row.config {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE notification_channels SET config=? WHERE id=?`, encrypted, row.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// legacyCardAPIConfig 保存待迁移 API 卡券的所属用户和完整请求模板。
|
||||
type legacyCardAPIConfig struct {
|
||||
// id 是 API 卡券数据库主键。
|
||||
id int64
|
||||
// userID 是卡券所属用户,用于绑定加密附加数据。
|
||||
userID int64
|
||||
// config 是尚未迁移或待校验的完整配置文本。
|
||||
config string
|
||||
}
|
||||
|
||||
// migrateLegacyCardAPIConfigs 在启动事务中迁移并校验历史 API 卡券配置。
|
||||
func migrateLegacyCardAPIConfigs(ctx context.Context, tx *sql.Tx, codec *secretCodec) error {
|
||||
// rows、err 保存 API 卡券迁移查询游标及查询错误。
|
||||
rows, err := tx.QueryContext(ctx, `SELECT id,user_id,COALESCE(api_config,'') FROM cards WHERE type='api' AND api_config IS NOT NULL AND api_config<>''`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
// cards 保存需要迁移或校验的 API 卡券配置。
|
||||
var cards []legacyCardAPIConfig
|
||||
for rows.Next() {
|
||||
// row 保存当前 API 卡券的持久化敏感字段。
|
||||
var row legacyCardAPIConfig
|
||||
// err 表示当前 API 卡券敏感字段扫描错误。
|
||||
if err := rows.Scan(&row.id, &row.userID, &row.config); err != nil {
|
||||
return err
|
||||
}
|
||||
cards = append(cards, row)
|
||||
}
|
||||
// err 表示查询游标遍历过程中的错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前需要加密或校验的 API 卡券配置。
|
||||
for _, row := range cards {
|
||||
// encrypted、err 保存 API 配置密文及加密错误。
|
||||
encrypted, err := codec.encrypt(cardAPIConfigScope, fmt.Sprint(row.userID), row.config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验卡券 %d API 配置: %w", row.id, err)
|
||||
}
|
||||
if encrypted != row.config {
|
||||
// err 表示回写 API 卡券密文时的数据库错误。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE cards SET api_config=? WHERE id=?`, encrypted, row.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// legacyCookieSecret 保存历史账号凭证和登录元数据,迁移时只在事务内部使用。
|
||||
type legacyCookieSecret struct {
|
||||
// id 是账号稳定标识。
|
||||
id string
|
||||
// value 是闲鱼 Cookie 或其密文。
|
||||
value string
|
||||
// password 是密码登录秘密或其密文。
|
||||
password string
|
||||
// metadata 是账号登录元数据或其密文。
|
||||
metadata string
|
||||
}
|
||||
|
||||
// migrateLegacyCookies 加密并校验历史账号 Cookie、密码和登录元数据。
|
||||
func migrateLegacyCookies(ctx context.Context, tx *sql.Tx, codec *secretCodec) error {
|
||||
// rows、err 保存账号秘密查询游标及查询错误。
|
||||
rows, err := tx.QueryContext(ctx, `SELECT id,value,COALESCE(password,''),COALESCE(metadata_json,'') FROM cookies`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
// cookies 保存待迁移的账号秘密。
|
||||
var cookies []legacyCookieSecret
|
||||
for rows.Next() {
|
||||
// row 保存当前账号的全部敏感字段。
|
||||
var row legacyCookieSecret
|
||||
// err 表示账号秘密扫描错误。
|
||||
if err := rows.Scan(&row.id, &row.value, &row.password, &row.metadata); err != nil {
|
||||
return err
|
||||
}
|
||||
cookies = append(cookies, row)
|
||||
}
|
||||
// err 表示账号秘密查询游标遍历错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前需要加密或校验的账号秘密。
|
||||
for _, row := range cookies {
|
||||
// value、err 保存 Cookie 密文及加密错误。
|
||||
value, err := codec.encrypt("cookie", row.id, row.value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s Cookie: %w", row.id, err)
|
||||
}
|
||||
// password、err 保存登录密码密文及加密错误。
|
||||
password, err := codec.encrypt("login-password", row.id, row.password)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s 登录密码: %w", row.id, err)
|
||||
}
|
||||
// metadata、err 保存登录元数据密文及加密错误。
|
||||
metadata, err := codec.encrypt(cookieMetadataScope, row.id, row.metadata)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s Cookie metadata: %w", row.id, err)
|
||||
}
|
||||
if value != row.value || password != row.password || metadata != row.metadata {
|
||||
// err 表示回写账号敏感字段时的数据库错误。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE cookies SET value=?,password=?,metadata_json=? WHERE id=?`, value, password, metadata, row.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// legacyTokenSecret 保存历史账号令牌,迁移时只在事务内部使用。
|
||||
type legacyTokenSecret struct {
|
||||
// cookieID 是令牌所属账号标识。
|
||||
cookieID string
|
||||
// deviceID 是设备标识或其密文。
|
||||
deviceID string
|
||||
// accessToken 是访问令牌或其密文。
|
||||
accessToken string
|
||||
}
|
||||
|
||||
// migrateLegacyTokens 加密并校验历史账号设备标识和访问令牌。
|
||||
func migrateLegacyTokens(ctx context.Context, tx *sql.Tx, codec *secretCodec) error {
|
||||
// rows、err 保存令牌查询游标及查询错误。
|
||||
rows, err := tx.QueryContext(ctx, `SELECT cookie_id,device_id,access_token FROM account_tokens`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
// tokens 保存待迁移的账号令牌。
|
||||
var tokens []legacyTokenSecret
|
||||
for rows.Next() {
|
||||
// row 保存当前账号令牌。
|
||||
var row legacyTokenSecret
|
||||
// err 表示账号令牌扫描错误。
|
||||
if err := rows.Scan(&row.cookieID, &row.deviceID, &row.accessToken); err != nil {
|
||||
return err
|
||||
}
|
||||
tokens = append(tokens, row)
|
||||
}
|
||||
// err 表示账号令牌查询游标遍历错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前需要加密或校验的账号令牌。
|
||||
for _, row := range tokens {
|
||||
// deviceID、err 保存设备标识密文及加密错误。
|
||||
deviceID, err := codec.encrypt("device-id", row.cookieID, row.deviceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// accessToken、err 保存访问令牌密文及加密错误。
|
||||
accessToken, err := codec.encrypt("access-token", row.cookieID, row.accessToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if deviceID != row.deviceID || accessToken != row.accessToken {
|
||||
// err 表示回写账号令牌时的数据库错误。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE account_tokens SET device_id=?,access_token=? WHERE cookie_id=?`, deviceID, accessToken, row.cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrateLegacySettings 加密并校验历史敏感系统设置。
|
||||
func migrateLegacySettings(ctx context.Context, tx *sql.Tx, codec *secretCodec, dialect Dialect) error {
|
||||
// keyCol 是当前数据库方言的设置键列引用。
|
||||
keyCol := dialectQuote(dialect, "key")
|
||||
// rows、err 保存系统设置查询游标及查询错误。
|
||||
rows, err := tx.QueryContext(ctx, `SELECT `+keyCol+`,value FROM system_settings`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
// settings 保存需要迁移的敏感设置。
|
||||
settings := make(map[string]string)
|
||||
for rows.Next() {
|
||||
// key、value 保存当前系统设置键和值。
|
||||
var key, value string
|
||||
// err 表示系统设置扫描错误。
|
||||
if err := rows.Scan(&key, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
if isSensitiveSettingKey(key) {
|
||||
settings[key] = value
|
||||
}
|
||||
}
|
||||
// err 表示系统设置查询游标遍历错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// key、value 表示当前需要迁移的敏感设置。
|
||||
for key, value := range settings {
|
||||
// encrypted、err 保存设置密文及加密错误。
|
||||
encrypted, err := codec.encrypt("system-setting", key, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if encrypted != value {
|
||||
// err 表示回写系统设置时的数据库错误。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE system_settings SET value=? WHERE `+keyCol+`=?`, encrypted, key); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// legacyNotificationChannel 保存历史通知渠道的所属用户和完整配置。
|
||||
type legacyNotificationChannel struct {
|
||||
// id 是渠道数据库主键。
|
||||
id int64
|
||||
// userID 是渠道所属用户。
|
||||
userID int64
|
||||
// config 是渠道配置或其密文。
|
||||
config string
|
||||
}
|
||||
|
||||
// migrateLegacyNotificationChannels 加密并校验历史通知渠道配置。
|
||||
func migrateLegacyNotificationChannels(ctx context.Context, tx *sql.Tx, codec *secretCodec) error {
|
||||
// rows、err 保存通知渠道查询游标及查询错误。
|
||||
rows, err := tx.QueryContext(ctx, `SELECT id,COALESCE(user_id,1),config FROM notification_channels`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
// channels 保存待迁移的通知渠道。
|
||||
var channels []legacyNotificationChannel
|
||||
for rows.Next() {
|
||||
// row 保存当前通知渠道的敏感字段。
|
||||
var row legacyNotificationChannel
|
||||
// err 表示通知渠道扫描错误。
|
||||
if err := rows.Scan(&row.id, &row.userID, &row.config); err != nil {
|
||||
return err
|
||||
}
|
||||
channels = append(channels, row)
|
||||
}
|
||||
// err 表示通知渠道查询游标遍历错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前需要加密或校验的通知渠道。
|
||||
for _, row := range channels {
|
||||
// encrypted、err 保存渠道密文及加密错误。
|
||||
encrypted, err := codec.encrypt("notification-config", fmt.Sprint(row.userID), row.config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if encrypted != row.config {
|
||||
// err 表示回写通知渠道配置时的数据库错误。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE notification_channels SET config=? WHERE id=?`, encrypted, row.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -363,6 +363,16 @@ func TestEncryptLegacySecretsUpgradesPlaintextAndValidatesKey(t *testing.T) {
|
||||
_, err := store.DB.ExecContext(ctx, `INSERT INTO cookies (id,value,user_id,password) VALUES (?,?,?,?)`, "legacy-secret", "legacy-cookie", owner.ID, "legacy-password"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// cardResult、cardInsertErr 保存插入历史明文 API 卡券配置的结果。
|
||||
cardResult, cardInsertErr := store.DB.ExecContext(ctx, `INSERT INTO cards (name,type,api_config,user_id) VALUES (?,?,?,?)`, "legacy-api", "api", `{"url":"https://example.com","headers":{"Authorization":"legacy-card-secret"}}`, owner.ID)
|
||||
if cardInsertErr != nil {
|
||||
t.Fatal(cardInsertErr)
|
||||
}
|
||||
// cardID 保存需要启动迁移的历史 API 卡券标识。
|
||||
cardID, cardIDErr := cardResult.LastInsertId()
|
||||
if cardIDErr != nil {
|
||||
t.Fatal(cardIDErr)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := store.EncryptLegacySecrets(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -376,6 +386,20 @@ func TestEncryptLegacySecretsUpgradesPlaintextAndValidatesKey(t *testing.T) {
|
||||
if !strings.HasPrefix(raw, encryptedValuePrefix) {
|
||||
t.Fatalf("legacy value was not upgraded: %q", raw)
|
||||
}
|
||||
// cardRaw 保存 API 卡券数据库中的原始配置,确认请求模板没有以明文留存。
|
||||
var cardRaw string
|
||||
// err 表示读取 API 卡券密文时的数据库错误。
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT api_config FROM cards WHERE id=?`, cardID).Scan(&cardRaw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(cardRaw, encryptedValuePrefix) || strings.Contains(cardRaw, "legacy-card-secret") {
|
||||
t.Fatalf("legacy API config was not encrypted: %q", cardRaw)
|
||||
}
|
||||
// card、cardErr 保存专用完整读取路径解密后的 API 配置。
|
||||
card, cardErr := store.Cards.Get(ctx, cardID)
|
||||
if cardErr != nil || card == nil || !strings.Contains(card.APIConfig, "legacy-card-secret") {
|
||||
t.Fatalf("API config decrypt failed card=%+v err=%v", card, cardErr)
|
||||
}
|
||||
// wrongCodec 用于本次流程后续判断的wrongCodec
|
||||
wrongCodec, _ := newSecretCodec("wrong-key")
|
||||
// wrongStore 用于本次流程后续判断的wrongStore
|
||||
|
||||
@@ -80,7 +80,7 @@ func NewStore(db *sql.DB, dialect Dialect) *Store {
|
||||
Sessions: &Sessions{DB: db},
|
||||
Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec},
|
||||
Items: items,
|
||||
Cards: &Cards{DB: db, Dialect: dialect},
|
||||
Cards: &Cards{DB: db, Dialect: dialect, codec: codec},
|
||||
Automation: &AutomationRules{DB: db, Dialect: dialect},
|
||||
Orders: orders,
|
||||
OrderWrites: newOrderWriteUnitOfWork(db, orders, items),
|
||||
|
||||
@@ -28,7 +28,7 @@ const (
|
||||
|
||||
// newAIHTTPClient 用于本次流程后续判断的newAIHTTPClient
|
||||
var newAIHTTPClient = func(baseURL string) (*http.Client, error) {
|
||||
return netguard.TrustedEndpointHTTPClient(baseURL, 30*time.Second)
|
||||
return netguard.ConfiguredEndpointHTTPClient(baseURL, 30*time.Second)
|
||||
}
|
||||
|
||||
// AIReplierImpl AI 回复实现。
|
||||
|
||||
@@ -301,6 +301,69 @@ func extractChatMessage(decrypted map[string]any, accountID, cookieStr string) *
|
||||
}
|
||||
}
|
||||
|
||||
// extractOwnWebSocketEcho 识别官方客户端发出后回显到当前账号 WebSocket 的普通消息。
|
||||
// decrypted 是已解密平台帧;accountID 和 cookieStr 用于归属与自身身份判断;返回值仅供出站持久化观察,绝不进入自动回复链。
|
||||
func extractOwnWebSocketEcho(decrypted map[string]any, accountID, cookieStr string) *OutgoingChatMessage {
|
||||
// m1 保存平台聊天信封主体;ok 表示帧是否具备普通聊天的顶层结构。
|
||||
m1, ok := decrypted["1"].(map[string]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
// m10 保存消息展示扩展;缺失时无法安全取得文本和发送者身份。
|
||||
m10, _ := m1["10"].(map[string]any)
|
||||
if m10 == nil {
|
||||
return nil
|
||||
}
|
||||
// text 保存平台通知层给出的消息摘要;空摘要不创建无内容出站记录。
|
||||
text, _ := m10["reminderContent"].(string)
|
||||
if text == "" || isNonUserChatNotice(m1, m10, text) {
|
||||
return nil
|
||||
}
|
||||
// senderUserID 保存归一化后的发送者身份,必须与当前账号身份一致才是自身回显。
|
||||
senderUserID := extractChatSenderUserIDFromMaps(m1, m10)
|
||||
// selfUserID 保存当前账号的非敏感平台身份,仅用于区分自身回显与买家入站消息。
|
||||
selfUserID := protocol.TransCookies(cookieStr)["unb"]
|
||||
if !isSelfUserID(senderUserID, selfUserID) {
|
||||
return nil
|
||||
}
|
||||
// chatID 保存去除协议后缀后的会话标识,供出站消息与既有会话关联。
|
||||
chatID := toString(m1["2"])
|
||||
// suffixIndex 保存会话协议后缀的起始下标,存在时只保留平台原始会话 ID。
|
||||
if suffixIndex := strings.Index(chatID, "@"); suffixIndex >= 0 {
|
||||
chatID = chatID[:suffixIndex]
|
||||
}
|
||||
if strings.TrimSpace(chatID) == "" {
|
||||
return nil
|
||||
}
|
||||
// reminderURL 保存通知深链,用于从 peerUserId 恢复会话对端身份。
|
||||
reminderURL, _ := m10["reminderUrl"].(string)
|
||||
// buyerID 保存深链中的对端用户标识;它不能等于当前账号,缺失时由既有会话保留原身份。
|
||||
buyerID := extractChatPeerUserID(reminderURL, selfUserID)
|
||||
return &OutgoingChatMessage{
|
||||
AccountID: accountID,
|
||||
ChatID: chatID,
|
||||
BuyerID: buyerID,
|
||||
Text: text,
|
||||
MessageKey: extractMessageID(decrypted),
|
||||
}
|
||||
}
|
||||
|
||||
// extractChatPeerUserID 从闲鱼聊天深链读取对端用户标识,并拒绝误填为当前账号的值。
|
||||
// reminderURL 是平台通知深链;selfUserID 是当前账号身份;返回空字符串表示深链缺失或身份不可信。
|
||||
func extractChatPeerUserID(reminderURL, selfUserID string) string {
|
||||
// parsed 保存深链解析结果;parseErr 表示平台提供了无法按 URL 解释的兼容字符串。
|
||||
parsed, parseErr := url.Parse(strings.TrimSpace(reminderURL))
|
||||
if parseErr != nil {
|
||||
return ""
|
||||
}
|
||||
// peerUserID 保存深链查询参数中的会话对端身份,并移除 IM 协议后缀。
|
||||
peerUserID := strings.TrimSuffix(strings.TrimSpace(parsed.Query().Get("peerUserId")), "@goofish")
|
||||
if peerUserID == "" || isSelfUserID(peerUserID, selfUserID) {
|
||||
return ""
|
||||
}
|
||||
return peerUserID
|
||||
}
|
||||
|
||||
// extractChatSenderUserIDFromMaps 优先读取展示扩展,并兼容紧凑信封中的发送者账号 ID。
|
||||
func extractChatSenderUserIDFromMaps(m1, m10 map[string]any) string {
|
||||
if m10 != nil {
|
||||
|
||||
@@ -146,22 +146,36 @@ func TestHandleMessage_DedupSkipsRepeat(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMessage_IgnoresOwnWebSocketEcho 验证当前账号的 WS 回显不会触发自动回复。
|
||||
func TestHandleMessage_IgnoresOwnWebSocketEcho(t *testing.T) {
|
||||
// TestHandleMessage_RecordsOwnWebSocketEchoWithoutAutoReply 验证官方客户端回显会走出站观察持久化,但绝不触发自动回复。
|
||||
func TestHandleMessage_RecordsOwnWebSocketEchoWithoutAutoReply(t *testing.T) {
|
||||
// acc 是待测账号;h 记录业务处理调用;cleanup 释放测试数据库和运行时资源。
|
||||
acc, h, _, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
defer acc.Stop()
|
||||
|
||||
// newAccountForTest 使用 unb=123;模拟同一账号在闲鱼官方客户端发出的
|
||||
// 消息回显,不能进入自动回复或业务消息处理链。
|
||||
acc.handleMessage(plainChatMessage(t, "官方客户端发送", "123", "chat-own"))
|
||||
// decrypted 模拟官方客户端发送的文本回显,深链提供真实买家身份,PNM 键用于后续持久化幂等。
|
||||
decrypted := plainChatMessage(t, "官方客户端发送", "123", "chat-own")
|
||||
// envelope 保存可变测试消息信封,用于补齐官方回显的 PNM 键和对端用户标识。
|
||||
envelope := decrypted["1"].(map[string]any)
|
||||
envelope["3"] = "own-message.PNM"
|
||||
// extension 保存消息展示扩展;深链中的 peerUserId 必须指向买家而不是当前账号。
|
||||
extension := envelope["10"].(map[string]any)
|
||||
extension["reminderUrl"] = "fleamarket://message_chat?itemId=item-chat-own&peerUserId=buyer-own"
|
||||
acc.handleMessage(decrypted)
|
||||
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if len(h.chats) != 0 {
|
||||
t.Fatalf("账号自身消息回显不应触发自动回复,got %d", len(h.chats))
|
||||
}
|
||||
if len(h.outgoing) != 1 {
|
||||
t.Fatalf("账号自身消息回显应交给出站观察器,got %d", len(h.outgoing))
|
||||
}
|
||||
// echo 保存观察器收到的出站回显,用于断言会话、买家和平台幂等键未丢失。
|
||||
echo := h.outgoing[0]
|
||||
if echo.AccountID != "cid" || echo.ChatID != "chat-own" || echo.BuyerID != "buyer-own" || echo.MessageKey != "own-message.PNM" || echo.Text != "官方客户端发送" {
|
||||
t.Fatalf("官方客户端出站回显字段错误: %+v", echo)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleMessage_NoReminderNoOp 无 reminderContent 的消息不进入回复链也不报错。
|
||||
|
||||
@@ -15,8 +15,13 @@ import (
|
||||
|
||||
// recordingHandler 记录收到的聊天消息,用于断言防抖与去重行为。
|
||||
type recordingHandler struct {
|
||||
mu sync.Mutex
|
||||
chats []ChatMessage
|
||||
// mu 保护聊天回调、出站回显和续期计数,测试中的异步防抖回调可与断言并发执行。
|
||||
mu sync.Mutex
|
||||
// chats 保存进入自动回复旁路的买家入站消息。
|
||||
chats []ChatMessage
|
||||
// outgoing 保存官方客户端或本程序发送后观察到的出站消息回显。
|
||||
outgoing []OutgoingChatMessage
|
||||
// refresh 保存密码登录续期回调次数。
|
||||
refresh int
|
||||
}
|
||||
|
||||
@@ -47,6 +52,14 @@ func (h *recordingHandler) OnPasswordLoginRefresh(_ context.Context, _ string) b
|
||||
// OnAccountAlert 封装On账号Alert业务协调。
|
||||
func (h *recordingHandler) OnAccountAlert(_ context.Context, _, _, _, _ string) {}
|
||||
|
||||
// HandleOutgoingChatMessage 记录出站观察消息,供测试确认官方客户端回显不进入自动回复链但仍可被持久化。
|
||||
func (h *recordingHandler) HandleOutgoingChatMessage(_ context.Context, message OutgoingChatMessage) error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
h.outgoing = append(h.outgoing, message)
|
||||
return nil
|
||||
}
|
||||
|
||||
// newAccountForTest 封装new账号ForTest业务协调。
|
||||
func newAccountForTest(t *testing.T) (*Account, *recordingHandler, *db.Store, func()) {
|
||||
t.Helper()
|
||||
@@ -330,16 +343,16 @@ func mustRefundTradeCard(t *testing.T) map[string]any {
|
||||
return m
|
||||
}
|
||||
|
||||
// mustPaidDeliveryCard 封装mustPaid发货卡密业务协调。
|
||||
// mustPaidDeliveryCard 构造卖家收到的完整付款待发货卡片,包含自动化防重和订单归属所需的 updateKey。
|
||||
func mustPaidDeliveryCard(t *testing.T) map[string]any {
|
||||
t.Helper()
|
||||
// s 用于本次流程后续判断的s
|
||||
// s 是模拟闲鱼付款系统卡片的 JSON;订单 ID 由 extJson 中的 updateKey 提供。
|
||||
s := "{" +
|
||||
"\"1\":{" +
|
||||
"\"2\":\"63107041124@goofish\"," +
|
||||
"\"10\":{" +
|
||||
"\"bizTag\":\"{\\\"sourceId\\\":\\\"C2C:4Ytd4BSQKIiz\\\",\\\"taskName\\\":\\\"付款完成待发货_卖家-正向升级\\\"}\"," +
|
||||
"\"extJson\":\"{\\\"msgArg1\\\":\\\"MsgCard\\\",\\\"contentType\\\":\\\"26\\\",\\\"messageId\\\":\\\"4e449a32c59c499594c4c5dffa5ddef0\\\"}\"," +
|
||||
"\"extJson\":\"{\\\"msgArg1\\\":\\\"MsgCard\\\",\\\"contentType\\\":\\\"26\\\",\\\"messageId\\\":\\\"4e449a32c59c499594c4c5dffa5ddef0\\\",\\\"updateKey\\\":\\\"63107041124:3310145690545023994:10:TRADE_PAID:26\\\"}\"," +
|
||||
"\"redReminder\":\"等待卖家发货\"," +
|
||||
"\"reminderContent\":\"[我已付款,等待你发货]\"," +
|
||||
"\"senderUserId\":\"2222315258815\"," +
|
||||
|
||||
@@ -184,6 +184,20 @@ func (d *messageDispatcher) handleMessageContext(ctx context.Context, decrypted
|
||||
}
|
||||
return
|
||||
}
|
||||
// ownEcho 保存当前账号从官方客户端发出后回显的消息;它必须实时落库,但绝不能进入自动回复防抖链。
|
||||
if ownEcho := extractOwnWebSocketEcho(decrypted, d.cookieID, d.currentCookie()); ownEcho != nil {
|
||||
// handler 保存当前可选业务处理器;旧集成未实现出站观察能力时保持原有仅过滤语义。
|
||||
if handler := d.currentHandler(); handler != nil {
|
||||
// observer、supported 保存出站观察接口及其实现判断,避免扩大基础 Handler 的必选职责。
|
||||
if observer, supported := handler.(outgoingChatHandler); supported {
|
||||
// err 保存自身回显持久化或实时发布失败;失败不应影响 WebSocket 接收循环或误触发自动回复。
|
||||
if err := observer.HandleOutgoingChatMessage(ctx, *ownEcho); err != nil {
|
||||
d.logger.Warn("处理官方客户端出站消息回显失败", "err", err, "chat_id", ownEcho.ChatID)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// chat 用于本次流程后续判断的聊天
|
||||
chat := extractChatMessage(decrypted, d.cookieID, d.currentCookie())
|
||||
|
||||
+160
-4
@@ -5,14 +5,63 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ConfiguredResponseBodyLimit 是用户可配置 HTTP 客户端允许读取的最大响应体大小。
|
||||
const ConfiguredResponseBodyLimit int64 = 10 << 20
|
||||
|
||||
// OutboundPolicy 保存服务端用户可配置 HTTP 请求的公网访问策略。
|
||||
type OutboundPolicy struct {
|
||||
// publicOnly 表示是否只允许解析到公网 IP 的目标地址。
|
||||
publicOnly atomic.Bool
|
||||
}
|
||||
|
||||
// defaultOutboundPolicy 是进程内所有用户可配置 HTTP 客户端共享的策略快照。
|
||||
var defaultOutboundPolicy = NewOutboundPolicy(false)
|
||||
|
||||
// NewOutboundPolicy 创建一个出站访问策略;默认值由调用方明确传入。
|
||||
func NewOutboundPolicy(publicOnly bool) *OutboundPolicy {
|
||||
// policy 保存新建的原子出站策略对象。
|
||||
policy := &OutboundPolicy{}
|
||||
policy.publicOnly.Store(publicOnly)
|
||||
return policy
|
||||
}
|
||||
|
||||
// SetPublicOnly 原子切换是否只允许访问公网地址。
|
||||
func (p *OutboundPolicy) SetPublicOnly(publicOnly bool) {
|
||||
if p != nil {
|
||||
p.publicOnly.Store(publicOnly)
|
||||
}
|
||||
}
|
||||
|
||||
// PublicOnly 返回当前是否启用公网地址限制。
|
||||
func (p *OutboundPolicy) PublicOnly() bool {
|
||||
return p != nil && p.publicOnly.Load()
|
||||
}
|
||||
|
||||
// SetDefaultPublicOnly 更新默认策略,供进程组合根和系统设置保存后调用。
|
||||
func SetDefaultPublicOnly(publicOnly bool) {
|
||||
defaultOutboundPolicy.SetPublicOnly(publicOnly)
|
||||
}
|
||||
|
||||
// DefaultPolicy 返回进程默认出站策略,供组合根注入应用服务而非让仓储修改全局状态。
|
||||
func DefaultPolicy() *OutboundPolicy {
|
||||
return defaultOutboundPolicy
|
||||
}
|
||||
|
||||
// DefaultPublicOnly 返回默认策略当前是否只允许公网地址。
|
||||
func DefaultPublicOnly() bool {
|
||||
return defaultOutboundPolicy.PublicOnly()
|
||||
}
|
||||
|
||||
// nonPublicPrefixes 用于本次流程后续判断的nonPublicPrefixes
|
||||
var nonPublicPrefixes = []netip.Prefix{
|
||||
netip.MustParsePrefix("0.0.0.0/8"), netip.MustParsePrefix("10.0.0.0/8"),
|
||||
@@ -29,15 +78,70 @@ var nonPublicPrefixes = []netip.Prefix{
|
||||
|
||||
// PublicHTTPClient 返回只允许连接公网 IP 的客户端。DNS 与每次重定向都会重新校验。
|
||||
func PublicHTTPClient(timeout time.Duration) *http.Client {
|
||||
// transport 用于本次流程后续判断的transport
|
||||
return policyHTTPClient(NewOutboundPolicy(true), timeout, 10*time.Second, 10*time.Second)
|
||||
}
|
||||
|
||||
// ConfiguredHTTPClient 返回遵循默认运行时策略的用户配置 HTTP 客户端。
|
||||
func ConfiguredHTTPClient(timeout time.Duration) *http.Client {
|
||||
return policyHTTPClient(defaultOutboundPolicy, timeout, 10*time.Second, 10*time.Second)
|
||||
}
|
||||
|
||||
// ConfiguredEndpointHTTPClient 校验用户配置的 HTTP(S) 基础地址并返回策略客户端。
|
||||
func ConfiguredEndpointHTTPClient(rawBaseURL string, timeout time.Duration) (*http.Client, error) {
|
||||
// baseURL、err 保存用户配置地址的解析结果及格式错误。
|
||||
baseURL, err := url.Parse(strings.TrimSpace(rawBaseURL))
|
||||
if err != nil || baseURL.Hostname() == "" {
|
||||
return nil, fmt.Errorf("服务地址无效")
|
||||
}
|
||||
if baseURL.Scheme != "http" && baseURL.Scheme != "https" {
|
||||
return nil, fmt.Errorf("服务地址只支持 http 或 https")
|
||||
}
|
||||
return ConfiguredHTTPClient(timeout), nil
|
||||
}
|
||||
|
||||
// PolicyHTTPClient 返回绑定指定运行时策略的 HTTP 客户端,测试和组合根可使用它隔离全局默认值。
|
||||
func PolicyHTTPClient(policy *OutboundPolicy, timeout time.Duration) *http.Client {
|
||||
if policy == nil {
|
||||
policy = defaultOutboundPolicy
|
||||
}
|
||||
return policyHTTPClient(policy, timeout, 10*time.Second, 10*time.Second)
|
||||
}
|
||||
|
||||
// PolicyHTTPClientWithTimeouts 返回可保留特殊响应头和 TLS 超时约束的策略客户端。
|
||||
func PolicyHTTPClientWithTimeouts(policy *OutboundPolicy, timeout, responseHeaderTimeout, tlsHandshakeTimeout time.Duration) *http.Client {
|
||||
if policy == nil {
|
||||
policy = defaultOutboundPolicy
|
||||
}
|
||||
return policyHTTPClient(policy, timeout, responseHeaderTimeout, tlsHandshakeTimeout)
|
||||
}
|
||||
|
||||
// policyHTTPClient 创建每次连接和重定向都遵循同一公网策略的 HTTP 客户端。
|
||||
func policyHTTPClient(policy *OutboundPolicy, timeout, responseHeaderTimeout, tlsHandshakeTimeout time.Duration) *http.Client {
|
||||
// transport 保存统一出站策略客户端的连接和重定向规则。
|
||||
transport := &http.Transport{
|
||||
Proxy: func(request *http.Request) (*url.URL, error) {
|
||||
if policy.PublicOnly() {
|
||||
return nil, nil
|
||||
}
|
||||
return http.ProxyFromEnvironment(request)
|
||||
},
|
||||
// 禁用连接复用,确保公网开关切换后每个新请求都重新解析并校验目标地址。
|
||||
DisableKeepAlives: true,
|
||||
ForceAttemptHTTP2: false,
|
||||
TLSHandshakeTimeout: tlsHandshakeTimeout,
|
||||
ResponseHeaderTimeout: responseHeaderTimeout,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
return DialPublicContext(ctx, network, address, 10*time.Second)
|
||||
if policy.PublicOnly() {
|
||||
return DialPublicContext(ctx, network, address, 10*time.Second)
|
||||
}
|
||||
// dialer 保存允许内网模式下的普通 TCP 拨号器。
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
|
||||
return dialer.DialContext(ctx, network, address)
|
||||
},
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
}
|
||||
return &http.Client{
|
||||
Transport: transport,
|
||||
Transport: limitedResponseBodyTransport{base: transport},
|
||||
Timeout: timeout,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 5 {
|
||||
@@ -46,11 +150,63 @@ func PublicHTTPClient(timeout time.Duration) *http.Client {
|
||||
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
|
||||
return fmt.Errorf("重定向协议不安全")
|
||||
}
|
||||
if len(via) > 0 && req.URL.Host != via[0].URL.Host {
|
||||
return fmt.Errorf("不允许跨主机重定向")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// limitedResponseBody 把用户可配置端点的响应体限制在固定大小以内。
|
||||
type limitedResponseBody struct {
|
||||
// body 是底层远端响应体,关闭责任仍由当前 HTTP 客户端持有。
|
||||
body io.ReadCloser
|
||||
// remaining 是尚未读取的允许字节数。
|
||||
remaining int64
|
||||
}
|
||||
|
||||
// Read 读取响应体并在尝试读取超限内容时返回错误。
|
||||
func (b *limitedResponseBody) Read(p []byte) (int, error) {
|
||||
if b.remaining == 0 {
|
||||
// probe 用于探测底层响应是否仍有超出上限的字节。
|
||||
var probe [1]byte
|
||||
// n、err 保存探测读取的字节数及底层读取结果。
|
||||
n, err := b.body.Read(probe[:])
|
||||
if n > 0 {
|
||||
return 0, errors.New("HTTP 响应超过大小限制")
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
if int64(len(p)) > b.remaining {
|
||||
p = p[:int(b.remaining)]
|
||||
}
|
||||
// n、err 保存本次受限读取的字节数及底层读取结果。
|
||||
n, err := b.body.Read(p)
|
||||
b.remaining -= int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Close 关闭底层响应体并释放远端连接资源。
|
||||
func (b *limitedResponseBody) Close() error { return b.body.Close() }
|
||||
|
||||
// limitedResponseBodyTransport 为响应体附加统一大小边界。
|
||||
type limitedResponseBodyTransport struct {
|
||||
// base 是执行 DNS、连接和重定向策略的底层 Transport。
|
||||
base http.RoundTripper
|
||||
}
|
||||
|
||||
// RoundTrip 执行请求并包装远端响应体,不改变状态码和响应头语义。
|
||||
func (t limitedResponseBodyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
// response、err 保存底层传输返回的响应和网络错误。
|
||||
response, err := t.base.RoundTrip(req)
|
||||
if err != nil || response == nil || response.Body == nil {
|
||||
return response, err
|
||||
}
|
||||
response.Body = &limitedResponseBody{body: response.Body, remaining: ConfiguredResponseBodyLimit}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// TrustedEndpointHTTPClient 用于管理员明确配置的集成端点。目标地址完全由管理员
|
||||
// 信任并负责,因此不限制 IP 类型、DNS 结果或 HTTP 重定向;仅校验 HTTP(S) URL。
|
||||
// TrustedEndpointHTTPClient 封装TrustedEndpointHTTPClient业务协调。
|
||||
|
||||
@@ -2,6 +2,7 @@ package netguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -99,3 +100,77 @@ func TestTrustedEndpointHTTPClientValidatesBaseURL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfiguredHTTPClientSwitchesRuntimePolicy 验证用户配置 HTTP 客户端可在运行时即时切换公网限制。
|
||||
func TestConfiguredHTTPClientSwitchesRuntimePolicy(t *testing.T) {
|
||||
// server 是本地测试端点,用于代表默认关闭时允许的内网地址。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
writer.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
// policy 是本次测试独立持有的运行时策略。
|
||||
policy := NewOutboundPolicy(false)
|
||||
// allowedClient 是关闭公网限制时创建的策略客户端。
|
||||
allowedClient := PolicyHTTPClient(policy, 0)
|
||||
// allowedResponse、allowedErr 保存关闭公网限制时的本地请求结果。
|
||||
allowedResponse, allowedErr := allowedClient.Get(server.URL)
|
||||
if allowedErr != nil {
|
||||
t.Fatalf("关闭公网限制时本地端点应可访问: %v", allowedErr)
|
||||
}
|
||||
allowedResponse.Body.Close()
|
||||
policy.SetPublicOnly(true)
|
||||
// blockedResponse、blockedErr 保存同一 HTTP 客户端在开启公网限制后的本地请求结果。
|
||||
blockedResponse, blockedErr := allowedClient.Get(server.URL)
|
||||
if blockedResponse != nil {
|
||||
blockedResponse.Body.Close()
|
||||
}
|
||||
if blockedErr == nil {
|
||||
t.Fatal("打开公网限制后回环端点必须被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfiguredHTTPClientRejectsCrossHostRedirect 验证用户配置端点不能借助跳转切换到另一主机。
|
||||
func TestConfiguredHTTPClientRejectsCrossHostRedirect(t *testing.T) {
|
||||
// target 是不应被跨主机跳转访问的第二个本地端点。
|
||||
target := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
writer.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
t.Cleanup(target.Close)
|
||||
// redirector 是返回跨主机跳转响应的第一个本地端点。
|
||||
redirector := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
http.Redirect(writer, request, target.URL, http.StatusFound)
|
||||
}))
|
||||
t.Cleanup(redirector.Close)
|
||||
// client 是使用独立运行时策略的用户配置客户端。
|
||||
client := PolicyHTTPClient(NewOutboundPolicy(false), 0)
|
||||
// response、err 保存跳转请求的响应和错误。
|
||||
response, err := client.Get(redirector.URL)
|
||||
if response != nil {
|
||||
response.Body.Close()
|
||||
}
|
||||
// errText 保存跳转错误的非敏感文本,用于稳定断言拒绝原因。
|
||||
if err == nil || !strings.Contains(err.Error(), "不允许跨主机重定向") {
|
||||
t.Fatalf("跨主机跳转应被拒绝 response=%v err=%v", response, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfiguredHTTPClientLimitsResponseBody 验证统一用户配置客户端拒绝超出响应体上限的内容。
|
||||
func TestConfiguredHTTPClientLimitsResponseBody(t *testing.T) {
|
||||
// server 是返回刚好超过统一响应上限的本地端点。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write(make([]byte, ConfiguredResponseBodyLimit+1))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
// client 是使用关闭公网限制的用户配置客户端。
|
||||
client := PolicyHTTPClient(NewOutboundPolicy(false), 0)
|
||||
// response、err 保存读取超大响应的结果。
|
||||
response, err := client.Get(server.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
// err 表示读取超大响应时返回的大小限制错误。
|
||||
if _, err := io.ReadAll(response.Body); err == nil {
|
||||
t.Fatal("超大响应应返回大小限制错误")
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ type Notifier struct {
|
||||
}
|
||||
|
||||
// newOutboundHTTPClient 用于本次流程后续判断的newOutboundHTTPClient
|
||||
var newOutboundHTTPClient = func() *http.Client { return netguard.PublicHTTPClient(10 * time.Second) }
|
||||
var newOutboundHTTPClient = func() *http.Client { return netguard.ConfiguredHTTPClient(10 * time.Second) }
|
||||
|
||||
// dialPublicSMTP 用于本次流程后续判断的dialPublicSMTP
|
||||
var dialPublicSMTP = netguard.DialPublicContext
|
||||
|
||||
@@ -225,8 +225,18 @@ func TestPendingAPIRenewLogsPendingAndRestartsAfterLateCookie(t *testing.T) {
|
||||
if !strings.Contains(detail.Value, "sdkSilent=") {
|
||||
t.Fatalf("迟到 Cookie 未保存: %q", detail.Value)
|
||||
}
|
||||
if // got 用于本次流程后续判断的got
|
||||
got := lastAPIRenewLog(t, store, account.ID).status; got != "cookie_updated" {
|
||||
// finalDeadline 限制 watcher 写入终态日志的等待时间;Restart 返回早于终态日志持久化,不能把重启完成当作 watcher 已收束。
|
||||
finalDeadline := time.Now().Add(time.Second)
|
||||
for time.Now().Before(finalDeadline) {
|
||||
// status 保存当前轮询到的续期日志状态;在迟到响应 watcher 尚未收束时可暂时保持 pending。
|
||||
status := lastAPIRenewLog(t, store, account.ID).status
|
||||
if status == "cookie_updated" {
|
||||
return
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
// got 保存等待截止后最后一次读取到的状态,便于失败时区分 watcher 未完成和写入错误。
|
||||
if got := lastAPIRenewLog(t, store, account.ID).status; got != "cookie_updated" {
|
||||
t.Fatalf("迟到响应最终状态=%q want cookie_updated", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -302,6 +302,11 @@ type CardsPort interface {
|
||||
AppendData(context.Context, int64, int64, string) (int, error)
|
||||
}
|
||||
|
||||
// APIRequestTesterPort 定义卡券 API 测试请求所需的最小应用能力。
|
||||
type APIRequestTesterPort interface {
|
||||
Test(context.Context, cardsapp.APIRequestTestInput) (cardsapp.APIRequestTestResult, error)
|
||||
}
|
||||
|
||||
// DefaultRepliesPort 定义默认回复配置能力。
|
||||
type DefaultRepliesPort interface {
|
||||
Get(context.Context, int64, string) (defaultreplyapp.Reply, error)
|
||||
@@ -415,6 +420,8 @@ type ApplicationPorts struct {
|
||||
automationRules AutomationRulesPort
|
||||
// cards 是卡券库存用例。
|
||||
cards CardsPort
|
||||
// apiRequestTester 执行临时 API 测试请求并返回非敏感诊断。
|
||||
apiRequestTester APIRequestTesterPort
|
||||
// publishAutomationRules 是发布后自动化规则用例。
|
||||
publishAutomationRules PublishAutomationRulesPort
|
||||
// defaultReplies 是默认回复用例。
|
||||
@@ -462,6 +469,7 @@ type ApplicationPortsInput struct {
|
||||
AutomationIssues AutomationIssuesPort
|
||||
AutomationRules AutomationRulesPort
|
||||
Cards CardsPort
|
||||
APIRequestTester APIRequestTesterPort
|
||||
PublishAutomationRules PublishAutomationRulesPort
|
||||
DefaultReplies DefaultRepliesPort
|
||||
Keywords KeywordsPort
|
||||
@@ -484,7 +492,7 @@ func NewApplicationPorts(input ApplicationPortsInput) *ApplicationPorts {
|
||||
accountSummaries: input.AccountSummaries, accountTasks: input.AccountTasks, chat: input.Chat,
|
||||
uncertainNotifications: input.UncertainNotifications, notificationChannels: input.NotificationChannels,
|
||||
analytics: input.Analytics, automationIssues: input.AutomationIssues, automationRules: input.AutomationRules,
|
||||
cards: input.Cards, publishAutomationRules: input.PublishAutomationRules, defaultReplies: input.DefaultReplies,
|
||||
cards: input.Cards, apiRequestTester: input.APIRequestTester, publishAutomationRules: input.PublishAutomationRules, defaultReplies: input.DefaultReplies,
|
||||
keywords: input.Keywords, settings: input.Settings, admin: input.Admin,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,8 +241,8 @@ func TestAutomationRuleBadActionType(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleRejectsAPICard 封装Test自动化规则RejectsAPI卡密业务协调。
|
||||
func TestAutomationRuleRejectsAPICard(t *testing.T) {
|
||||
// TestAutomationRuleAcceptsAPICard 验证已配置的 API 卡券可以加入自动化规则。
|
||||
func TestAutomationRuleAcceptsAPICard(t *testing.T) {
|
||||
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
@@ -265,7 +265,7 @@ func TestAutomationRuleRejectsAPICard(t *testing.T) {
|
||||
// rec 用于本次流程后续判断的rec
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "API 卡密暂不支持") {
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,13 +89,9 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
|
||||
continue
|
||||
}
|
||||
switch cardType {
|
||||
case "text", "data", "image":
|
||||
case "api":
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "API 卡密暂不支持自动发货,不能新建"})
|
||||
failed++
|
||||
continue
|
||||
case "text", "data", "image", "api":
|
||||
default:
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "类型必须为 text/data/image"})
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "类型必须为 text/data/image/api"})
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
@@ -132,6 +128,8 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
|
||||
draft.TextContent = content
|
||||
case "data":
|
||||
draft.DataContent = content
|
||||
case "api":
|
||||
draft.APIConfig = content
|
||||
case "image":
|
||||
draft.ImageURL = content
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package server
|
||||
|
||||
import cardsapp "xianyu-go/internal/application/cards"
|
||||
|
||||
// apiCardConfigResponse 是 API 卡券查询接口的脱敏响应 DTO。
|
||||
type apiCardConfigResponse struct {
|
||||
// URL 是固定的 HTTP(S) 请求地址,不包含请求凭据。
|
||||
URL string `json:"url"`
|
||||
// Method 是 GET 或 POST。
|
||||
Method string `json:"method"`
|
||||
// TimeoutSeconds 是单次 API 请求超时秒数。
|
||||
TimeoutSeconds int `json:"timeout_seconds"`
|
||||
// ContentType 是 POST 请求正文的 Content-Type。
|
||||
ContentType string `json:"content_type"`
|
||||
// ResponsePath 是可选的响应提取路径。
|
||||
ResponsePath string `json:"response_path,omitempty"`
|
||||
// RetryEnabled 表示是否启用带幂等键的暂时性失败重试。
|
||||
RetryEnabled bool `json:"retry_enabled"`
|
||||
// HeadersConfigured 表示服务端是否保存了请求头模板,但不返回模板内容。
|
||||
HeadersConfigured bool `json:"headers_configured"`
|
||||
// ParamsConfigured 表示服务端是否保存了请求参数模板,但不返回模板内容。
|
||||
ParamsConfigured bool `json:"params_configured"`
|
||||
// Ready 表示当前配置可被规则选择和自动化执行。
|
||||
Ready bool `json:"ready"`
|
||||
// ValidationError 保存脱敏后的配置校验错误。
|
||||
ValidationError string `json:"validation_error,omitempty"`
|
||||
}
|
||||
|
||||
// newCardResponse 将应用层卡券模型转换为 HTTP DTO。
|
||||
func newCardResponse(card cardsapp.Card) cardResponse {
|
||||
// apiConfig 是仅对 API 卡券生成的脱敏配置摘要。
|
||||
var apiConfig *apiCardConfigResponse
|
||||
if card.Type == "api" {
|
||||
// summary 保存应用层校验后的非敏感 API 配置状态。
|
||||
var summary cardsapp.APIConfigSummary
|
||||
if card.APIConfigSummary != nil {
|
||||
summary = *card.APIConfigSummary
|
||||
} else {
|
||||
summary = cardsapp.SummarizeAPIConfig(card.APIConfig)
|
||||
}
|
||||
apiConfig = &apiCardConfigResponse{
|
||||
URL: summary.URL, Method: summary.Method, TimeoutSeconds: summary.TimeoutSeconds, ContentType: summary.ContentType,
|
||||
ResponsePath: summary.ResponsePath, RetryEnabled: summary.RetryEnabled,
|
||||
HeadersConfigured: summary.HeadersConfigured, ParamsConfigured: summary.ParamsConfigured,
|
||||
Ready: summary.Ready, ValidationError: summary.ValidationError,
|
||||
}
|
||||
}
|
||||
return cardResponse{
|
||||
ID: card.ID, Name: card.Name, Type: card.Type, APIConfig: apiConfig,
|
||||
TextContent: card.TextContent, DataContent: card.DataContent, ImageURL: card.ImageURL,
|
||||
Description: card.Description, Enabled: card.Enabled, DelaySeconds: card.DelaySeconds,
|
||||
IsMultiSpec: card.IsMultiSpec, SpecName: card.SpecName, SpecValue: card.SpecValue, UserID: card.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
// newCardResponses 批量转换应用层卡券列表,避免 HTTP 层暴露数据库模型。
|
||||
func newCardResponses(cards []cardsapp.Card) []cardResponse {
|
||||
// result 是转换后的卡券 DTO 列表。
|
||||
result := make([]cardResponse, 0, len(cards))
|
||||
// card 是当前待转换的卡券应用模型。
|
||||
for _, card := range cards {
|
||||
result = append(result, newCardResponse(card))
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -17,8 +19,8 @@ type cardMutationRequest struct {
|
||||
Name string `json:"name"`
|
||||
// Type 是 text、data、image 或历史兼容的 api 类型。
|
||||
Type string `json:"type"`
|
||||
// APIConfig 是历史 API 卡券配置文本。
|
||||
APIConfig string `json:"api_config"`
|
||||
// APIConfig 同时接收新版具名对象和历史完整 JSON 字符串。
|
||||
APIConfig json.RawMessage `json:"api_config"`
|
||||
// TextContent 是 text 类型自动发货时发送的文本内容。
|
||||
TextContent string `json:"text_content"`
|
||||
// DataContent 是 data 类型尚未消费的逐行卡密库存。
|
||||
@@ -45,10 +47,33 @@ type cardAppendRequest struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// cardAPITestRequest 是临时 API 测试请求的具名 DTO。
|
||||
type cardAPITestRequest struct {
|
||||
// APIConfig 是与卡券保存接口一致的 API 配置对象或历史 JSON 字符串。
|
||||
APIConfig json.RawMessage `json:"api_config"`
|
||||
}
|
||||
|
||||
// cardAPITestResponse 是临时 API 测试结果的具名脱敏 DTO。
|
||||
type cardAPITestResponse struct {
|
||||
// Status 表示远端请求是否成功。
|
||||
Status string `json:"status"`
|
||||
// StatusCode 是远端 HTTP 状态码。
|
||||
StatusCode int `json:"status_code"`
|
||||
// ResponseContentType 是远端响应媒体类型。
|
||||
ResponseContentType string `json:"response_content_type"`
|
||||
// ResponseFields 是 JSON 顶层字段名称。
|
||||
ResponseFields []string `json:"response_fields"`
|
||||
// ExtractedValue 是按配置路径提取的值。
|
||||
ExtractedValue string `json:"extracted_value,omitempty"`
|
||||
// ResponsePreview 是限长响应预览。
|
||||
ResponsePreview string `json:"response_preview,omitempty"`
|
||||
}
|
||||
|
||||
// mountCardsReal 挂载卡券 CRUD、批量创建和库存追加路由;发货规则由 automation_rules 负责。
|
||||
func (s *Server) mountCardsReal(r chi.Router) {
|
||||
r.Get("/cards", s.listCards)
|
||||
r.Post("/cards", s.createCard)
|
||||
r.Post("/cards/test-api", s.testCardAPI)
|
||||
r.Post("/cards/batch", s.batchCreateCards)
|
||||
r.Post("/cards/{card_id}/append-data", s.appendCardData)
|
||||
r.Get("/cards/{card_id}/details", s.getCard)
|
||||
@@ -57,6 +82,34 @@ func (s *Server) mountCardsReal(r chi.Router) {
|
||||
r.Delete("/cards/{card_id}", s.deleteCard)
|
||||
}
|
||||
|
||||
// testCardAPI 发送一次临时 API 请求并返回状态、字段和提取结果诊断。
|
||||
func (s *Server) testCardAPI(w http.ResponseWriter, r *http.Request) {
|
||||
if s.applications == nil || s.applications.apiRequestTester == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "API 测试服务不可用")
|
||||
return
|
||||
}
|
||||
// request 是当前 API 测试请求的具名 HTTP DTO。
|
||||
var request cardAPITestRequest
|
||||
// err 是当前请求 JSON 解码错误,不包含用户填写的敏感模板值。
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
// config、err 分别是可供应用 Port 解析的配置文本和兼容解码错误。
|
||||
config, err := decodeCardAPIConfig(request.APIConfig)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
// result、err 分别是临时远端调用的脱敏诊断和本地配置或网络错误。
|
||||
result, err := s.applications.apiRequestTester.Test(r.Context(), cardsapp.APIRequestTestInput{Config: config})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, cardAPITestResponse{Status: result.Status, StatusCode: result.StatusCode, ResponseContentType: result.ResponseContentType, ResponseFields: result.ResponseFields, ExtractedValue: result.ExtractedValue, ResponsePreview: result.ResponsePreview})
|
||||
}
|
||||
|
||||
// listCards 将认证用户交给应用服务,并把卡券应用模型转换为 HTTP DTO。
|
||||
func (s *Server) listCards(w http.ResponseWriter, r *http.Request) {
|
||||
// session 是认证中间件注入的当前用户会话。
|
||||
@@ -110,8 +163,6 @@ func (s *Server) createCard(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case errors.As(err, &validationError):
|
||||
writeErr(w, http.StatusBadRequest, validationError.Error())
|
||||
case errors.Is(err, cardsapp.ErrUnsupportedAPIType):
|
||||
writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能新建")
|
||||
default:
|
||||
writeErr(w, http.StatusInternalServerError, "创建失败")
|
||||
}
|
||||
@@ -144,8 +195,6 @@ func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case errors.As(err, &validationError):
|
||||
writeErr(w, http.StatusBadRequest, validationError.Error())
|
||||
case errors.Is(err, cardsapp.ErrUnsupportedAPIType):
|
||||
writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能转换为该类型")
|
||||
case errors.Is(err, cardsapp.ErrNotFound) || errors.Is(err, cardsapp.ErrInvalidCardID):
|
||||
writeErr(w, http.StatusNotFound, "卡券不存在")
|
||||
case errors.Is(err, cardsapp.ErrForbidden):
|
||||
@@ -192,14 +241,49 @@ func decodeCardDraft(r *http.Request) (cardsapp.Draft, error) {
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
return cardsapp.Draft{}, err
|
||||
}
|
||||
// apiConfig、apiConfigErr 保存兼容解码后的 API 配置文本及格式错误。
|
||||
apiConfig, apiConfigErr := decodeCardAPIConfig(request.APIConfig)
|
||||
if apiConfigErr != nil {
|
||||
return cardsapp.Draft{}, apiConfigErr
|
||||
}
|
||||
return cardsapp.Draft{
|
||||
Name: request.Name, Type: request.Type, APIConfig: request.APIConfig,
|
||||
Name: request.Name, Type: request.Type, APIConfig: apiConfig,
|
||||
TextContent: request.TextContent, DataContent: request.DataContent, ImageURL: request.ImageURL,
|
||||
Description: request.Description, Enabled: request.Enabled, DelaySeconds: request.DelaySeconds,
|
||||
IsMultiSpec: request.IsMultiSpec, SpecName: request.SpecName, SpecValue: request.SpecValue,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// decodeCardAPIConfig 兼容历史字符串配置,并把新版对象保持为 JSON 文本交给应用服务校验。
|
||||
func decodeCardAPIConfig(raw json.RawMessage) (string, error) {
|
||||
// trimmed 保存去除空白后的请求字段。
|
||||
trimmed := bytes.TrimSpace(raw)
|
||||
if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
|
||||
return "", nil
|
||||
}
|
||||
if trimmed[0] == '"' {
|
||||
// legacy 保存旧客户端提交的完整 JSON 字符串。
|
||||
var legacy string
|
||||
// err 表示历史字符串字段解码错误。
|
||||
if err := json.Unmarshal(trimmed, &legacy); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return legacy, nil
|
||||
}
|
||||
// object 保存新版具名 API 配置对象的字段。
|
||||
var object map[string]json.RawMessage
|
||||
// err 表示新版 API 配置对象解码错误。
|
||||
if err := json.Unmarshal(trimmed, &object); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// encoded、err 保存新版 API 配置对象的规范 JSON 和编码错误。
|
||||
encoded, err := json.Marshal(object)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(encoded), nil
|
||||
}
|
||||
|
||||
// writeCardReadError 将详情查询的应用错误映射为既有 HTTP 状态和统一错误响应。
|
||||
func writeCardReadError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
|
||||
@@ -198,5 +198,48 @@ func TestCardCRUD(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCardAPIDTOIsRedacted 验证 API 卡券支持具名配置请求,响应只返回脱敏摘要而不回显模板秘密。
|
||||
func TestCardAPIDTOIsRedacted(t *testing.T) {
|
||||
// srv、cleanup 保存契约测试服务器及其清理函数。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 是本次测试使用的完整路由处理器。
|
||||
handler := srv.Router()
|
||||
// cookie 是已认证管理员会话。
|
||||
cookie := loginHelper(t, handler)
|
||||
// request 是提交请求头和参数模板的新版 API 卡请求。
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/cards", strings.NewReader(`{"name":"API 脱敏卡","type":"api","api_config":{"url":"https://example.com/card","method":"POST","timeout_seconds":10,"headers":{"Authorization":"Bearer super-secret"},"params":{"code":"{order_id}"},"response_path":"data.card.code"},"enabled":true}`))
|
||||
request.AddCookie(cookie)
|
||||
// response 保存创建请求的 HTTP 响应。
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("API 卡创建失败 status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
// listRequest 是读取卡券摘要的请求。
|
||||
listRequest := httptest.NewRequest(http.MethodGet, "/api/v1/cards", nil)
|
||||
listRequest.AddCookie(cookie)
|
||||
// listResponse 保存卡券列表响应。
|
||||
listResponse := httptest.NewRecorder()
|
||||
handler.ServeHTTP(listResponse, listRequest)
|
||||
if listResponse.Code != http.StatusOK {
|
||||
t.Fatalf("API 卡列表失败 status=%d body=%s", listResponse.Code, listResponse.Body.String())
|
||||
}
|
||||
// rows 保存脱敏卡券列表。
|
||||
var rows []map[string]any
|
||||
// err 表示脱敏卡券列表 JSON 解码错误。
|
||||
if err := json.Unmarshal(listResponse.Body.Bytes(), &rows); err != nil || len(rows) != 1 {
|
||||
t.Fatalf("API 卡列表格式错误 rows=%v err=%v", rows, err)
|
||||
}
|
||||
// summary 保存响应中的 API 脱敏摘要。
|
||||
summary, ok := rows[0]["api_config"].(map[string]any)
|
||||
if !ok || summary["ready"] != true || summary["url"] != "https://example.com/card" {
|
||||
t.Fatalf("API 卡摘要错误: %+v", rows[0]["api_config"])
|
||||
}
|
||||
if strings.Contains(listResponse.Body.String(), "super-secret") || strings.Contains(listResponse.Body.String(), "Authorization") {
|
||||
t.Fatalf("API 卡响应泄漏敏感模板: %s", listResponse.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// itoa 封装itoa业务协调。
|
||||
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
|
||||
@@ -207,7 +207,7 @@ func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error
|
||||
|
||||
// publicHTTPClient 只允许连接公网地址,防止批量铺货图片 URL 访问本机或内网服务。
|
||||
func publicHTTPClient() *http.Client {
|
||||
return netguard.PublicHTTPClient(30 * time.Second)
|
||||
return netguard.ConfiguredHTTPClient(30 * time.Second)
|
||||
}
|
||||
|
||||
// validateBatchImageRef 封装validate批次图片Ref业务协调。
|
||||
|
||||
@@ -197,7 +197,15 @@ func validateSystemSettingValues(values map[string]string) error {
|
||||
if level, ok := values["log_level"]; ok {
|
||||
// err 是日志级别解析错误。
|
||||
_, err := logging.ParseLevel(level)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// raw、ok 保存公网限制设置的原始值及是否包含该字段。
|
||||
if raw, ok := values["outbound_http_public_only"]; ok {
|
||||
if !strings.EqualFold(strings.TrimSpace(raw), "true") && !strings.EqualFold(strings.TrimSpace(raw), "false") {
|
||||
return errors.New("outbound_http_public_only 必须是布尔值")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -273,12 +281,16 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if key == "log_level" {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := logging.SetLevel(req.Value); err != nil {
|
||||
// err 表示单项日志级别校验错误。
|
||||
if _, err := logging.ParseLevel(req.Value); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if key == "outbound_http_public_only" && !strings.EqualFold(strings.TrimSpace(req.Value), "true") && !strings.EqualFold(strings.TrimSpace(req.Value), "false") {
|
||||
writeErr(w, http.StatusBadRequest, "outbound_http_public_only 必须是布尔值")
|
||||
return
|
||||
}
|
||||
// sess 保存当前管理员会话,用于应用服务执行普通设置写入。
|
||||
sess := authSess(r)
|
||||
if sess == nil {
|
||||
@@ -290,6 +302,9 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
}
|
||||
if key == "log_level" {
|
||||
_ = logging.SetLevel(req.Value)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
|
||||
@@ -9,9 +9,18 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// apiRequestTesterStub 是卡券 API 测试请求的确定性替身,避免 OpenAPI 契约测试访问真实远端地址。
|
||||
type apiRequestTesterStub struct{}
|
||||
|
||||
// Test 返回固定的非敏感测试诊断结果。
|
||||
func (apiRequestTesterStub) Test(context.Context, cardsapp.APIRequestTestInput) (cardsapp.APIRequestTestResult, error) {
|
||||
return cardsapp.APIRequestTestResult{Status: "success", StatusCode: http.StatusOK, ResponseContentType: "application/json", ResponseFields: []string{"code", "data"}, ExtractedValue: "TEST-CODE", ResponsePreview: `{"data":{"code":"TEST-CODE"}}`}, nil
|
||||
}
|
||||
|
||||
// TestNamedSuccessResponseContracts 验证认证、订单和聊天主链路使用具名成功响应 DTO。
|
||||
func TestNamedSuccessResponseContracts(t *testing.T) {
|
||||
// srv 是用于验证成功响应 DTO 的 HTTP 测试服务。
|
||||
@@ -198,6 +207,8 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
|
||||
defer cleanup()
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := contractRecordingHandler(t, srv.Router())
|
||||
// apiRequestTester 使用确定性替身验证 HTTP DTO 和 OpenAPI 响应契约。
|
||||
srv.applications.apiRequestTester = apiRequestTesterStub{}
|
||||
// sessionCookie 是管理员登录后得到的认证会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
|
||||
@@ -277,6 +288,25 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
|
||||
t.Fatalf("card response=%+v", cardCreateResponse)
|
||||
}
|
||||
|
||||
// apiTestReq 是使用临时卡券配置执行 API 测试的版本化请求。
|
||||
apiTestReq := httptest.NewRequest(http.MethodPost, "/api/v1/cards/test-api", strings.NewReader(`{"api_config":{"url":"https://example.com/test","method":"GET","timeout_seconds":10}}`))
|
||||
apiTestReq.AddCookie(sessionCookie)
|
||||
// apiTestRecorder 捕获测试请求的具名诊断响应。
|
||||
apiTestRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(apiTestRecorder, apiTestReq)
|
||||
if apiTestRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("api test status=%d body=%s", apiTestRecorder.Code, apiTestRecorder.Body.String())
|
||||
}
|
||||
// apiTestResponse 是 API 测试响应 DTO。
|
||||
var apiTestResponse cardAPITestResponse
|
||||
// apiTestDecodeErr 是 API 测试响应解码失败原因。
|
||||
if apiTestDecodeErr := json.Unmarshal(apiTestRecorder.Body.Bytes(), &apiTestResponse); apiTestDecodeErr != nil {
|
||||
t.Fatalf("decode api test response: %v", apiTestDecodeErr)
|
||||
}
|
||||
if apiTestResponse.Status != "success" || apiTestResponse.StatusCode != http.StatusOK || apiTestResponse.ExtractedValue != "TEST-CODE" {
|
||||
t.Fatalf("api test response=%+v", apiTestResponse)
|
||||
}
|
||||
|
||||
// cardGetReq 是读取卡券详情的请求。
|
||||
cardGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/cards/"+strconv.FormatInt(cardCreateResponse.ID, 10), nil)
|
||||
cardGetReq.AddCookie(sessionCookie)
|
||||
|
||||
@@ -3,7 +3,6 @@ package server
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
defaultreplyapp "xianyu-go/internal/application/defaultreply"
|
||||
notificationsapp "xianyu-go/internal/application/notifications"
|
||||
)
|
||||
@@ -46,8 +45,8 @@ type cardResponse struct {
|
||||
Name string `json:"name"`
|
||||
// Type 是卡券类型。
|
||||
Type string `json:"type"`
|
||||
// APIConfig 是 API 卡券配置 JSON。
|
||||
APIConfig string `json:"api_config"`
|
||||
// APIConfig 是不含请求头、参数和密钥的 API 配置摘要;非 API 卡券省略该字段。
|
||||
APIConfig *apiCardConfigResponse `json:"api_config,omitempty"`
|
||||
// TextContent 是文本卡券内容。
|
||||
TextContent string `json:"text_content"`
|
||||
// DataContent 是批量数据卡券内容。
|
||||
@@ -70,27 +69,6 @@ type cardResponse struct {
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
// newCardResponse 将应用层卡券模型转换为 HTTP DTO。
|
||||
func newCardResponse(card cardsapp.Card) cardResponse {
|
||||
return cardResponse{
|
||||
ID: card.ID, Name: card.Name, Type: card.Type, APIConfig: card.APIConfig,
|
||||
TextContent: card.TextContent, DataContent: card.DataContent, ImageURL: card.ImageURL,
|
||||
Description: card.Description, Enabled: card.Enabled, DelaySeconds: card.DelaySeconds,
|
||||
IsMultiSpec: card.IsMultiSpec, SpecName: card.SpecName, SpecValue: card.SpecValue, UserID: card.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
// newCardResponses 批量转换应用层卡券列表,避免 HTTP 层暴露数据库模型。
|
||||
func newCardResponses(cards []cardsapp.Card) []cardResponse {
|
||||
// result 是转换后的卡券 DTO 列表。
|
||||
result := make([]cardResponse, 0, len(cards))
|
||||
// card 是当前待转换的卡券应用模型。
|
||||
for _, card := range cards {
|
||||
result = append(result, newCardResponse(card))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// cardBatchResponse 是卡券批量创建接口的具名响应 DTO。
|
||||
type cardBatchResponse struct {
|
||||
// Success 表示批量解析和处理流程已完成。
|
||||
|
||||
@@ -37,6 +37,7 @@ func (s *Server) mountVersionedSettingsCardNotificationRoutes(r chi.Router) {
|
||||
|
||||
r.Get("/api/v1/cards", s.listCards)
|
||||
r.Post("/api/v1/cards", s.createCard)
|
||||
r.Post("/api/v1/cards/test-api", s.testCardAPI)
|
||||
r.Post("/api/v1/cards/batch", s.batchCreateCards)
|
||||
r.Post("/api/v1/cards/{card_id}/append-data", s.appendCardData)
|
||||
r.Get("/api/v1/cards/{card_id}/details", s.getCard)
|
||||
|
||||
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user