From f5064254dc989bf870394ba4866291343a57e9a4 Mon Sep 17 00:00:00 2001 From: Christ Date: Fri, 21 Aug 2026 22:14:39 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=9F=E8=83=BD=EF=BC=9A=E5=AE=8C=E5=96=84?= =?UTF-8?q?=20API=20=E5=8D=A1=E5=AF=86=E5=8F=91=E8=B4=A7=E4=B8=8E=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E5=8C=96=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- api/openapi.yaml | 118 +++- cmd/server/main.go | 8 + docs/slider-captcha-frozen-spec.md | 8 + docs/wiki/账号、库存与商品.md | 8 +- frontend/app/features/apiAdapters.test.ts | 2 +- frontend/app/features/cards/api.ts | 44 +- .../app/features/cards/cardActions.test.tsx | 36 + frontend/app/features/cards/cardActions.ts | 40 +- .../cards/components/APIRequestBuilder.tsx | 357 ++++++++++ frontend/app/features/cards/models.ts | 87 ++- .../features/cards/pages/CardList.test.tsx | 30 + .../app/features/cards/pages/CardList.tsx | 171 ++--- frontend/app/features/cards/types.ts | 20 + frontend/app/features/rules/models.ts | 18 +- frontend/app/features/rules/pages/Rules.tsx | 2 +- frontend/app/features/settings/api.ts | 4 + frontend/app/features/settings/models.ts | 2 + .../app/features/settings/pages/Settings.tsx | 8 + .../shared/api-contract/generated/schema.ts | 138 +++- internal/adapter/adapter.go | 1 + internal/adapter/adapter_events.go | 3 +- internal/adapter/adapter_test.go | 32 + internal/adapter/ai_model_client.go | 2 +- internal/adapter/api_delivery_client.go | 636 ++++++++++++++++++ internal/adapter/api_delivery_client_test.go | 238 +++++++ internal/adapter/automation_image_sender.go | 15 +- .../adapter/automation_image_sender_test.go | 23 + internal/adapter/automation_repository.go | 4 +- internal/adapter/cards_repository.go | 36 +- internal/adapter/misc_dependencies.go | 10 + internal/adapter/settings_repository.go | 6 +- internal/adapter/token_captcha_remote.go | 18 +- .../adapter/transport_application_services.go | 10 +- internal/application/automation/rules.go | 8 +- internal/application/automation/rules_test.go | 3 +- internal/application/cards/api_config.go | 361 ++++++++++ internal/application/cards/api_config_test.go | 68 ++ internal/application/cards/service.go | 63 +- internal/application/cards/service_test.go | 23 +- internal/application/settings/service.go | 58 +- internal/application/settings/service_test.go | 38 ++ internal/automation/action_executor.go | 48 +- internal/automation/action_executor_test.go | 48 ++ internal/automation/ai_pricing.go | 4 +- internal/automation/api_delivery.go | 53 ++ internal/automation/center.go | 28 +- internal/automation/center_dependencies.go | 23 + internal/automation/center_test.go | 148 +++- internal/automation/error_classification.go | 19 + internal/automation/events.go | 38 +- internal/automation/events_test.go | 34 + internal/automation/run_coordinator.go | 24 +- internal/composition/application_services.go | 19 +- internal/composition/runtime/runtime.go | 3 +- .../runtime/server_dependencies.go | 2 +- internal/db/automation.go | 13 +- internal/db/automation_recovery.go | 2 +- internal/db/automation_test.go | 44 ++ internal/db/cards_summary.go | 201 ++++++ internal/db/delivery.go | 2 + internal/db/items.go | 24 + internal/db/migrate_test.go | 6 +- .../mysql/00034_ai_bargain_auto_price.sql | 2 +- .../00037_api_delivery_outbound_policy.sql | 6 + .../00037_api_delivery_outbound_policy.sql | 6 + .../00037_api_delivery_outbound_policy.sql | 5 + internal/db/orders_ext.go | 71 +- internal/db/secrets.go | 167 +---- internal/db/secrets_cards.go | 57 ++ internal/db/secrets_legacy.go | 218 ++++++ internal/db/secrets_test.go | 24 + internal/db/store.go | 2 +- internal/engine/ai.go | 2 +- internal/engine/engine_test.go | 6 +- internal/netguard/http.go | 164 ++++- internal/netguard/http_test.go | 75 +++ internal/notify/notifier.go | 2 +- internal/server/application_ports.go | 10 +- internal/server/automation_extra_test.go | 6 +- internal/server/card_batch_handlers.go | 10 +- internal/server/card_contract_support.go | 65 ++ internal/server/card_handlers.go | 98 ++- internal/server/endpoint_test.go | 43 ++ internal/server/item_publish_images.go | 2 +- internal/server/settings_handlers.go | 21 +- internal/server/success_api_contract_test.go | 30 + internal/server/success_contract_support.go | 26 +- ...ioned_settings_card_notification_routes.go | 1 + ...st-D1PDvKjr.js => AccountList-bZfynCVm.js} | 2 +- .../webui/static/assets/CardList-BG11KU7H.js | 17 - .../webui/static/assets/CardList-C4GnPAQ5.js | 19 + .../{Chat-Di7cjGAh.js => Chat-BJnFncX8.js} | 2 +- ...oard-DBUkwLYQ.js => Dashboard-Dp8ltpET.js} | 2 +- ...mList-D-9IbEjX.js => ItemList-rJmjsGj7.js} | 2 +- ...-xaqRCmgU.js => Notifications-Bn70UZXF.js} | 2 +- ...List-CKY0um79.js => OrderList-BD2f1aOo.js} | 2 +- .../webui/static/assets/Rules-BTlditSE.js | 1 + .../webui/static/assets/Rules-DCuiI2LD.js | 1 - .../webui/static/assets/Settings-BffAa0e7.js | 1 + .../webui/static/assets/Settings-CbgtqNcx.js | 1 - ...-74T0w35U.js => chat-metadata-CxFNzZmJ.js} | 2 +- ...r-BSp7PTZg.js => icons-vendor-eB2mgMyz.js} | 175 ++--- .../webui/static/assets/index-BhNIzeuC.css | 1 + .../webui/static/assets/index-Bu1X-GTG.css | 1 - .../{index-Q3nlx6gR.js => index-DO3sL4lx.js} | 4 +- internal/webui/static/index.html | 8 +- 106 files changed, 4302 insertions(+), 600 deletions(-) create mode 100644 frontend/app/features/cards/components/APIRequestBuilder.tsx create mode 100644 internal/adapter/api_delivery_client.go create mode 100644 internal/adapter/api_delivery_client_test.go create mode 100644 internal/application/cards/api_config.go create mode 100644 internal/application/cards/api_config_test.go create mode 100644 internal/automation/api_delivery.go create mode 100644 internal/automation/center_dependencies.go create mode 100644 internal/automation/error_classification.go create mode 100644 internal/db/cards_summary.go create mode 100644 internal/db/migrations/mysql/00037_api_delivery_outbound_policy.sql create mode 100644 internal/db/migrations/postgres/00037_api_delivery_outbound_policy.sql create mode 100644 internal/db/migrations/sqlite/00037_api_delivery_outbound_policy.sql create mode 100644 internal/db/secrets_cards.go create mode 100644 internal/db/secrets_legacy.go create mode 100644 internal/server/card_contract_support.go rename internal/webui/static/assets/{AccountList-D1PDvKjr.js => AccountList-bZfynCVm.js} (99%) delete mode 100644 internal/webui/static/assets/CardList-BG11KU7H.js create mode 100644 internal/webui/static/assets/CardList-C4GnPAQ5.js rename internal/webui/static/assets/{Chat-Di7cjGAh.js => Chat-BJnFncX8.js} (99%) rename internal/webui/static/assets/{Dashboard-DBUkwLYQ.js => Dashboard-Dp8ltpET.js} (99%) rename internal/webui/static/assets/{ItemList-D-9IbEjX.js => ItemList-rJmjsGj7.js} (99%) rename internal/webui/static/assets/{Notifications-xaqRCmgU.js => Notifications-Bn70UZXF.js} (99%) rename internal/webui/static/assets/{OrderList-CKY0um79.js => OrderList-BD2f1aOo.js} (99%) create mode 100644 internal/webui/static/assets/Rules-BTlditSE.js delete mode 100644 internal/webui/static/assets/Rules-DCuiI2LD.js create mode 100644 internal/webui/static/assets/Settings-BffAa0e7.js delete mode 100644 internal/webui/static/assets/Settings-CbgtqNcx.js rename internal/webui/static/assets/{chat-metadata-74T0w35U.js => chat-metadata-CxFNzZmJ.js} (99%) rename internal/webui/static/assets/{icons-vendor-BSp7PTZg.js => icons-vendor-eB2mgMyz.js} (75%) create mode 100644 internal/webui/static/assets/index-BhNIzeuC.css delete mode 100644 internal/webui/static/assets/index-Bu1X-GTG.css rename internal/webui/static/assets/{index-Q3nlx6gR.js => index-DO3sL4lx.js} (94%) diff --git a/api/openapi.yaml b/api/openapi.yaml index 5b1e1bb..17ab30f 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -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: diff --git a/cmd/server/main.go b/cmd/server/main.go index 6cb2411..bd607b8 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -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) != "" { diff --git a/docs/slider-captcha-frozen-spec.md b/docs/slider-captcha-frozen-spec.md index 65a6246..7df1c2f 100644 --- a/docs/slider-captcha-frozen-spec.md +++ b/docs/slider-captcha-frozen-spec.md @@ -6,6 +6,14 @@ 本文记录 `internal/browser` 中当前滑块认证的完整行为契约。它是维护边界,不是待办方案。后续任务即使涉及登录、Cookie、浏览器自动化、风控恢复或代码清理,也必须保持本文行为逐项不变。 +## 本次 API 发货 Feature 的远程服务网络补充 + +本次用户明确授权仅调整远程滑块服务的网络准入:远程滑块服务请求现在使用统一的用户配置 HTTP 出站策略。系统设置 +`outbound_http_public_only` 默认关闭;关闭时允许内网 HTTP(S) 地址,但仍限制协议、重定向次数和响应大小;开启时会在 DNS +解析和每次重定向连接前拒绝回环、私网、链路本地、保留地址及元数据地址。该开关保存后立即生效。 + +这项补充不改变滑块选择器、轨迹、拖动距离、重试顺序、Cookie 合并、成功判定、本地浏览器回退或日志语义。除网络目标校验外,本文其余冻结条款继续优先适用。 + ## 1. 保护范围 以下文件为直接保护对象: diff --git a/docs/wiki/账号、库存与商品.md b/docs/wiki/账号、库存与商品.md index 1d8bf53..c1e4a83 100644 --- a/docs/wiki/账号、库存与商品.md +++ b/docs/wiki/账号、库存与商品.md @@ -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. 同步或发布商品 diff --git a/frontend/app/features/apiAdapters.test.ts b/frontend/app/features/apiAdapters.test.ts index f3f893b..9d835b9 100644 --- a/frontend/app/features/apiAdapters.test.ts +++ b/frontend/app/features/apiAdapters.test.ts @@ -875,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(); }); diff --git a/frontend/app/features/cards/api.ts b/frontend/app/features/cards/api.ts index 6b6a0da..be454eb 100644 --- a/frontend/app/features/cards/api.ts +++ b/frontend/app/features/cards/api.ts @@ -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) => ({ +// parseTemplateJSON 将表单中的 JSON 模板转换为请求对象,空模板交给服务端执行保留语义。 +const parseTemplateJSON = (value: unknown): Record | undefined => { + if (value && typeof value === 'object' && !Array.isArray(value)) return value as Record; + 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; +}; + +// 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 }; // createCard 创建卡密组。 -export const createCard = async (data: Partial): Promise => { +export const createCard = async (data: CardMutation): Promise => { return runContractRequest(/* signal 控制卡券创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards', { body: cardPayload(data), signal })); }; // updateCard 更新卡密组。 -export const updateCard = async (cardId: string | number, data: Partial): Promise => { +export const updateCard = async (cardId: string | number, data: CardMutation): Promise => { 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 => { 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 => { + 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, + })); +}; diff --git a/frontend/app/features/cards/cardActions.test.tsx b/frontend/app/features/cards/cardActions.test.tsx index a9e67d6..e07d873 100644 --- a/frontend/app/features/cards/cardActions.test.tsx +++ b/frontend/app/features/cards/cardActions.test.tsx @@ -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(); diff --git a/frontend/app/features/cards/cardActions.ts b/frontend/app/features/cards/cardActions.ts index 39d4170..a2e997c 100644 --- a/frontend/app/features/cards/cardActions.ts +++ b/frontend/app/features/cards/cardActions.ts @@ -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 = { + 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 = { + 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); diff --git a/frontend/app/features/cards/components/APIRequestBuilder.tsx b/frontend/app/features/cards/components/APIRequestBuilder.tsx new file mode 100644 index 0000000..e714283 --- /dev/null +++ b/frontend/app/features/cards/components/APIRequestBuilder.tsx @@ -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; +} + +// 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); + 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>(/* 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(() => 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 ( +
+
+ + +
+
+
+ KEY + VALUE +
+
+ {rows.map(/* rowRenderer 渲染当前键值编辑行。 */ (row, index) => ( +
+ ) => 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" + /> + ) => 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" + /> + +
+ ))} +
+
+
+ ); +}; + +// 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({ 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 ( +
+
+
+

API 请求配置

+

按 Postman 的请求结构填写,敏感模板只会加密保存在服务端。

+
+ API +
+ {onTest && ( +
+ + {testState.error && {testState.error}} + {testState.result && ( +
+
+ {testState.result.status === 'success' ? '测试成功' : '测试失败'} + HTTP 状态:{testState.result.status_code || '网络错误'} + 响应类型:{testState.result.response_content_type || '未知'} +
+
响应字段:{testState.result.response_fields.length ? testState.result.response_fields.join('、') : '未识别 JSON 字段'}提取结果:{testState.result.extracted_value || '未提取到内容'}
+ {testState.result.response_preview &&
{testState.result.response_preview}
} +
+ )} +
+ )} + +
+
+ + ) => 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" + /> +
+
+ + +
+
+ + ) => onChange('timeout', Number(event.target.value) || 10)} className="w-full ios-input rounded-xl px-3 py-3" /> +
+
+ +
+ onChange('headers', nextValue)} placeholder="Authorization" /> + {headersAction && ( + + )} + + onChange('params', nextValue)} placeholder="order_id" /> + {paramsAction && ( + + )} + +
+
+ + +
+ {jsonBody ? ( +