API契约:收尾兼容响应并审计版本入口
This commit is contained in:
1 parent
929b3fd8a9
commit
6ff3499ca9
8 files changed
+317
-37
No files matched your search
@@ -12,7 +12,7 @@
|
||||
| 商品批量 | `/items/publish-batches...` | `/api/v1/items/publish-batches...` | 旧路径保留,类目推荐/预检/任务 DTO 已落地 |
|
||||
| 自动化 | `/automation-rules...` | `/api/v1/automation-rules...` | 旧路径保留,规则分页/异常 DTO 已落地 |
|
||||
| 订单 | `/api/orders...` | `/api/v1/orders...` | 旧路径保留,列表/详情/刷新/批量外层 DTO 已落地 |
|
||||
| 设置 | `/system-settings...`、`/user-settings...`、`/ai-reply-settings...` | `/api/v1/settings/...` | 旧路径保留,变更/查询 DTO 已落地;动态键仍由边界适配 |
|
||||
| 设置 | `/system-settings...`、`/user-settings...`、`/ai-reply-settings...` | `/api/v1/settings/...` | 旧路径保留,变更/查询 DTO 已落地;`settingsResponse` 明确动态字符串键值边界,动态键仍由边界适配 |
|
||||
| 卡券 | `/cards...` | `/api/v1/cards...` | 旧路径保留,CRUD/批量 DTO 已落地 |
|
||||
| 通知 | `/notification-channels...`、`/message-notifications...` | `/api/v1/notifications/...` | 旧路径保留,渠道/绑定/变更 DTO 已落地 |
|
||||
| 聊天 | `/api/chat...` | `/api/v1/chat...` | 旧路径保留,会话/消息 DTO 已落地 |
|
||||
@@ -21,7 +21,7 @@
|
||||
| 账号任务 | `/api/account-tasks...` | `/api/v1/account-tasks...` | 旧路径保留,设置、运行记录和执行摘要 DTO 已落地 |
|
||||
| 管理员 | `/admin/users...`、`/admin/cookies...`、`/admin/stats` | `/api/v1/admin/...` | 旧路径保留,用户/账号/全局统计 DTO 已落地 |
|
||||
| 统计 | `/dashboard/stats`、`/analytics/orders...` | `/api/v1/analytics/...` | 旧路径保留,概览、收益、维度和有效订单分页 DTO 已落地 |
|
||||
| 二维码生成 | `/qr-login/generate` | `/api/v1/qr-login/generate` | 旧路径保留,二维码生成 DTO 已落地;状态响应继续保留动态兼容字段 |
|
||||
| 二维码生成 | `/qr-login/generate` | `/api/v1/qr-login/generate` | 旧路径保留,二维码生成、状态和验证完成 DTO 已落地;`qrLoginStatusResponse` 仅保留非敏感动态字段,状态响应继续保留兼容扩展 |
|
||||
|
||||
## 迁移规则
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
- 设置、卡券和通知分别使用 `operationResponse`、`aiReplySettingsResponse`、`aiModelsResponse`、`userSettingResponse`、`cardResponse`、`cardBatchResponse`、`notificationChannelResponse`、`notificationBindingResponse` 与 `accountBindingsResponse`。
|
||||
- 关键词回复、默认回复和账号任务分别使用 `keywordBasicResponse`/`keywordItemResponse`/`keywordTypedResponse`、`itemReplyResponse`、`defaultReplyResponse`、`accountTaskSettingsResponse`、`accountTaskRunsResponse` 与 `accountTaskRunResponseEnvelope`。
|
||||
- 管理员和统计分别使用 `adminUserResponse`/`adminCookieResponse`/`adminStatsResponse`、`dashboardStatsResponse`、`orderAnalyticsResponse` 与 `validOrdersResponse`;二维码生成使用 `qrLoginGenerateResponse`。
|
||||
- 动态设置和二维码兼容边界分别使用 `settingsResponse`、`qrLoginStatusResponse` 与 `qrLoginVerificationResponse`;二维码状态契约测试确认 `cookies` 等敏感字段不会回传。
|
||||
- 聊天会话、消息分页和发送结果使用独立 DTO,不直接暴露数据库模型。
|
||||
- React `frontend/types.ts` 与 `frontend/services/api.ts` 已同步具名成功响应类型,同时保留旧字段归一逻辑。
|
||||
- 旧路径仍由现有路由提供,尚未宣称 `/api/v1` 已经可用。
|
||||
@@ -525,3 +525,4 @@ npm --prefix frontend run build
|
||||
| 2026-08-14 | 完成阶段 3 第八个 PR 切片“剩余商品批量操作与设置/卡券/通知成功响应收口” | 商品类目推荐、批量发布预检/任务、系统与用户设置、账号 AI 设置、卡券 CRUD/批量、通知渠道与账号绑定已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:剩余关键词回复、默认回复与账号任务成功响应收口 |
|
||||
| 2026-08-14 | 完成阶段 3 第九个 PR 切片“剩余关键词回复、默认回复与账号任务成功响应收口” | 关键词基础/商品/类型规则、指定商品回复、默认回复、账号任务设置与运行记录已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:分析统计、管理员与剩余公共成功响应收口 |
|
||||
| 2026-08-14 | 完成阶段 3 第十个 PR 切片“分析统计、管理员与剩余公共成功响应收口” | 管理员用户/账号/统计、用户仪表盘、订单分析、有效订单分页和二维码生成已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:公共成功响应兼容收尾与版本化迁移入口审计 |
|
||||
| 2026-08-14 | 完成阶段 3 第十一个 PR 切片“公共成功响应兼容收尾与版本化迁移入口审计” | 系统、管理员和用户动态设置统一通过具名 map 边界类型;二维码状态保留非敏感扩展字段并过滤 Cookie,验证完成使用具名 DTO;React API 清理剩余 `Promise<any>`/`get<any>` 成功响应并补齐兼容类型;新增动态设置与二维码契约测试,明确旧路径仍保留、尚未宣称 `/api/v1` 可用;所有修改合并为一个可回滚提交 | 阶段 3:HTTP API 版本化兼容入口落地与调用方迁移 |
|
||||
+25
-25
@@ -3,8 +3,8 @@ import {
|
||||
LoginResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
AdminStats, DashboardStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
|
||||
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
|
||||
CookieSettingsResponse, CookieProfileResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
|
||||
} from '../types';
|
||||
import { formatLocalDate } from '../dateRange';
|
||||
|
||||
@@ -168,37 +168,37 @@ export const generateQRLogin = async (options?: RequestControlOptions): Promise<
|
||||
return post('/qr-login/generate', undefined, { ...options, timeoutMs: options?.timeoutMs ?? 130_000 });
|
||||
};
|
||||
|
||||
export const checkQRLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<any> => {
|
||||
export const checkQRLoginStatus = async (sessionId: string, signal?: AbortSignal): Promise<QRLoginStatusResponse> => {
|
||||
return get(`/qr-login/check/${sessionId}`, undefined, { signal, timeoutMs: 10_000 });
|
||||
};
|
||||
|
||||
export const completeQRVerification = async (
|
||||
sessionId: string,
|
||||
targetAccountId?: string,
|
||||
): Promise<{
|
||||
success: boolean;
|
||||
account_id?: string;
|
||||
scanned_account_id?: string;
|
||||
message?: string;
|
||||
}> => {
|
||||
): Promise<QRLoginVerificationResponse> => {
|
||||
return post(`/qr-login/complete-verification/${sessionId}`, {
|
||||
target_account_id: targetAccountId || '',
|
||||
});
|
||||
};
|
||||
|
||||
export const updateAccountStatus = async (id: string, enabled: boolean): Promise<any> => {
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export const updateAccountStatus = async (id: string, enabled: boolean): Promise<OperationResponse> => {
|
||||
return put(`/cookies/${id}/status`, { enabled });
|
||||
};
|
||||
|
||||
export const deleteAccount = async (id: string): Promise<any> => {
|
||||
export const deleteAccount = async (id: string): Promise<OperationResponse> => {
|
||||
return del(`/cookies/${id}`);
|
||||
};
|
||||
|
||||
export const updateAccountRemark = async (id: string, remark: string): Promise<any> => {
|
||||
export const updateAccountRemark = async (id: string, remark: string): Promise<OperationResponse> => {
|
||||
return put(`/cookies/${id}/remark`, { remark });
|
||||
};
|
||||
|
||||
export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean): Promise<any> => {
|
||||
export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean): Promise<OperationResponse> => {
|
||||
return put(`/cookies/${id}/auto-confirm`, { auto_confirm: autoConfirm });
|
||||
};
|
||||
|
||||
@@ -206,7 +206,7 @@ export const updateAccountPauseDuration = async (id: string, pauseDuration: numb
|
||||
return put(`/cookies/${id}/pause-duration`, { pause_duration: pauseDuration });
|
||||
};
|
||||
|
||||
export const updateAccountCookie = async (id: string, value: string, loginMethod?: string): Promise<any> => {
|
||||
export const updateAccountCookie = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
|
||||
return put(`/cookies/${id}`, { id, value, login_method: loginMethod });
|
||||
};
|
||||
|
||||
@@ -285,7 +285,7 @@ export const updateAccountLoginInfo = async (id: string, data: {
|
||||
login_password?: string;
|
||||
clear_password?: boolean;
|
||||
show_browser?: boolean;
|
||||
}): Promise<any> => {
|
||||
}): Promise<OperationResponse> => {
|
||||
return put(`/cookies/${id}/login-info`, data);
|
||||
};
|
||||
|
||||
@@ -350,7 +350,7 @@ export const deleteOrder = async (orderId: string): Promise<ApiResponse> => {
|
||||
return del(`/api/orders/${orderId}`);
|
||||
};
|
||||
|
||||
export const syncOrders = async (cookieId?: string, status?: string): Promise<any> => {
|
||||
export const syncOrders = async (cookieId?: string, status?: string): Promise<OrderRefreshResponse> => {
|
||||
const formData = new FormData();
|
||||
if (cookieId) formData.append('cookie_id', cookieId);
|
||||
if (status) formData.append('status', status);
|
||||
@@ -494,7 +494,7 @@ const normalizeBooleanFlag = (value: unknown): boolean =>
|
||||
value === true || value === 1 || value === '1';
|
||||
|
||||
export const getItems = async (cookieId?: string): Promise<Item[]> => {
|
||||
const res = await get<any>('/items', cookieId ? { cookie_id: cookieId } : undefined);
|
||||
const res = await get<Item[] | ItemListEnvelope>('/items', cookieId ? { cookie_id: cookieId } : undefined);
|
||||
const items = Array.isArray(res) ? res : (res.items || []);
|
||||
return items.map((item: any) => ({
|
||||
...item,
|
||||
@@ -509,11 +509,11 @@ export const syncItemsFromAccount = async (cookieId: string): Promise<ItemSyncRe
|
||||
return post('/items/get-all-from-account', { cookie_id: cookieId });
|
||||
}
|
||||
|
||||
export const deleteItem = async (cookieId: string, itemId: string): Promise<any> => {
|
||||
export const deleteItem = async (cookieId: string, itemId: string): Promise<OperationResponse> => {
|
||||
return del(`/items/${cookieId}/${itemId}`);
|
||||
}
|
||||
|
||||
export const createItem = async (cookieId: string, data: any): Promise<any> => {
|
||||
export const createItem = async (cookieId: string, data: Partial<Item>): Promise<OperationResponse> => {
|
||||
return post(`/items/${cookieId}`, data);
|
||||
}
|
||||
|
||||
@@ -617,7 +617,7 @@ export const retryFailedItemPublishBatch = async (batchId: string): Promise<Batc
|
||||
return post(`/items/publish-batches/${batchId}/retry-failed`, {});
|
||||
}
|
||||
|
||||
export const updateItem = async (cookieId: string, itemId: string, data: Partial<Item>): Promise<any> => {
|
||||
export const updateItem = async (cookieId: string, itemId: string, data: Partial<Item>): Promise<OperationResponse> => {
|
||||
return put(`/items/${cookieId}/${itemId}`, data);
|
||||
}
|
||||
|
||||
@@ -727,7 +727,7 @@ const orderAutomationActions = (triggerType: string, actions: AutomationAction[]
|
||||
];
|
||||
};
|
||||
|
||||
export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<any> => {
|
||||
export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<OperationResponse | MutationIDResponse> => {
|
||||
const triggerType = rule.trigger_type || 'order_paid';
|
||||
const triggerName: Record<string, string> = {
|
||||
order_paid: '付款后自动发货',
|
||||
@@ -783,7 +783,7 @@ export const updateShippingRule = async (rule: Partial<ShippingRule>): Promise<a
|
||||
return rule.id ? put(`/automation-rules/${rule.id}`, payload) : post('/automation-rules', payload);
|
||||
}
|
||||
|
||||
export const deleteShippingRule = async (id: string): Promise<any> => del(`/automation-rules/${id}`);
|
||||
export const deleteShippingRule = async (id: string): Promise<OperationResponse> => del(`/automation-rules/${id}`);
|
||||
|
||||
export interface AutomationRunIssue {
|
||||
id: number;
|
||||
@@ -808,17 +808,17 @@ export interface DeferredAutomationIssue {
|
||||
}
|
||||
|
||||
export const getAutomationIssues = async (): Promise<{ runs: AutomationRunIssue[]; pending_tasks: DeferredAutomationIssue[] }> => {
|
||||
const result = await get<any>('/automation-issues');
|
||||
const result = await get<AutomationIssuesEnvelope>('/automation-issues');
|
||||
return {
|
||||
runs: Array.isArray(result?.runs) ? result.runs : [],
|
||||
pending_tasks: Array.isArray(result?.pending_tasks) ? result.pending_tasks : [],
|
||||
};
|
||||
};
|
||||
|
||||
export const resolveAutomationRun = async (id: number, resolution: 'continue' | 'retry' | 'cancel'): Promise<any> =>
|
||||
export const resolveAutomationRun = async (id: number, resolution: 'continue' | 'retry' | 'cancel'): Promise<OperationResponse> =>
|
||||
post(`/automation-runs/${id}/resolve`, { resolution });
|
||||
|
||||
export const resolveDeferredAutomationTask = async (id: number, resolution: 'retry' | 'dismiss'): Promise<any> =>
|
||||
export const resolveDeferredAutomationTask = async (id: number, resolution: 'retry' | 'dismiss'): Promise<OperationResponse> =>
|
||||
post(`/automation-pending-tasks/${id}/resolve`, { resolution });
|
||||
|
||||
// Rules - 关键词回复规则 (使用关键词API)
|
||||
|
||||
@@ -1238,3 +1238,139 @@ export interface QRLoginGenerateResponse {
|
||||
/** 可选的提示文本。 */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** 二维码登录状态响应。 */
|
||||
export interface QRLoginStatusResponse {
|
||||
/** 当前二维码会话状态。 */
|
||||
status: string;
|
||||
/** 扫码登录会话标识。 */
|
||||
session_id?: string;
|
||||
/** 平台账号标识。 */
|
||||
unb?: string;
|
||||
/** 持久化后的本地账号标识。 */
|
||||
account_id?: string;
|
||||
/** 是否新建了本地账号。 */
|
||||
is_new_account?: boolean;
|
||||
/** 状态提示文本。 */
|
||||
message?: string;
|
||||
/** 兼容上游可能扩展的非敏感状态字段。 */
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
/** 二维码验证完成响应。 */
|
||||
export interface QRLoginVerificationResponse {
|
||||
/** 验证结果是否成功。 */
|
||||
success: boolean;
|
||||
/** 平台账号标识。 */
|
||||
unb?: string;
|
||||
/** 持久化后的本地账号标识。 */
|
||||
account_id?: string;
|
||||
/** 是否新建了本地账号。 */
|
||||
is_new_account?: boolean;
|
||||
/** 扫码账号与目标账号不一致时的提示标识。 */
|
||||
scanned_account_id?: string;
|
||||
/** 验证结果提示文本。 */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** 订单列表刷新逐项结果。 */
|
||||
export interface OrderRefreshResultResponse {
|
||||
/** 结果所属账号标识。 */
|
||||
cookie_id?: string;
|
||||
/** 当前处理阶段。 */
|
||||
stage?: string;
|
||||
/** 当前项是否处理成功。 */
|
||||
success: boolean;
|
||||
/** 结果说明。 */
|
||||
message?: string;
|
||||
/** 发现的新订单数量。 */
|
||||
discovered?: number;
|
||||
/** 更新的订单数量。 */
|
||||
updated?: number;
|
||||
/** 标记删除的订单数量。 */
|
||||
soft_deleted?: number;
|
||||
/** 订单平台标识。 */
|
||||
order_id?: string;
|
||||
/** 结果错误说明。 */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** 订单列表刷新统计摘要。 */
|
||||
export interface OrderRefreshSummaryResponse {
|
||||
/** 发现的新订单数量。 */
|
||||
discovered: number;
|
||||
/** 订单列表更新数量。 */
|
||||
list_updated: number;
|
||||
/** 标记删除数量。 */
|
||||
soft_deleted: number;
|
||||
/** 需要补全详情的订单数量。 */
|
||||
detail_total: number;
|
||||
/** 本次处理订单总数。 */
|
||||
total: number;
|
||||
/** 状态发生变化数量。 */
|
||||
updated: number;
|
||||
/** 状态未变化数量。 */
|
||||
no_change: number;
|
||||
/** 刷新失败数量。 */
|
||||
failed: number;
|
||||
}
|
||||
|
||||
/** 订单列表刷新响应。 */
|
||||
export interface OrderRefreshResponse {
|
||||
/** 是否存在部分失败。 */
|
||||
partial_failure: boolean;
|
||||
/** 刷新结果说明。 */
|
||||
message: string;
|
||||
/** 刷新统计摘要。 */
|
||||
summary: OrderRefreshSummaryResponse;
|
||||
/** 逐项兼容结果。 */
|
||||
results: OrderRefreshResultResponse[];
|
||||
}
|
||||
|
||||
// ItemListEnvelope 是商品列表接口的兼容分页响应。
|
||||
export interface ItemListEnvelope {
|
||||
/** items 是兼容分页响应中的商品列表。 */
|
||||
items?: Item[];
|
||||
}
|
||||
|
||||
// AutomationIssuesEnvelope 是自动化异常接口的兼容响应。
|
||||
export interface AutomationIssuesEnvelope {
|
||||
/** runs 是待处理的自动化运行记录。 */
|
||||
runs?: Array<{
|
||||
/** 记录标识。 */
|
||||
id: number;
|
||||
/** 所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 所属订单标识。 */
|
||||
order_id: string;
|
||||
/** 自动化触发类型。 */
|
||||
trigger_type: string;
|
||||
/** 外部错误说明。 */
|
||||
error_message: string;
|
||||
/** 异常类别。 */
|
||||
issue_kind: 'external_result_unknown' | 'invalid_snapshot' | 'rule_unavailable' | 'partial_failure' | 'execution_failed';
|
||||
/** 允许的处理动作。 */
|
||||
allowed_resolutions: Array<'continue' | 'retry' | 'cancel'>;
|
||||
/** 当前动作游标。 */
|
||||
action_cursor: number;
|
||||
/** 已发送数量。 */
|
||||
sent_count: number;
|
||||
/** 更新时间。 */
|
||||
updated_at: string;
|
||||
}>;
|
||||
/** pending_tasks 是延迟自动化任务列表。 */
|
||||
pending_tasks?: Array<{
|
||||
/** 任务标识。 */
|
||||
id: number;
|
||||
/** 所属账号标识。 */
|
||||
cookie_id: string;
|
||||
/** 自动化触发类型。 */
|
||||
trigger_type: string;
|
||||
/** 错误说明。 */
|
||||
error_message: string;
|
||||
/** 当前重试次数。 */
|
||||
attempt_count: number;
|
||||
/** 更新时间。 */
|
||||
updated_at: string;
|
||||
}>;
|
||||
}
|
||||
@@ -155,9 +155,9 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
|
||||
"", map[string]any{"scanned_account_id": unb})
|
||||
return
|
||||
}
|
||||
resp := map[string]any{
|
||||
"success": true,
|
||||
"unb": unb,
|
||||
resp := qrLoginVerificationResponse{
|
||||
Success: true, UNB: unb,
|
||||
// 验证完成响应保留平台账号标识,兼容旧客户端。
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if sess != nil {
|
||||
@@ -181,8 +181,8 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
|
||||
"保存扫码登录结果失败: "+persistErr.Error(), "")
|
||||
return
|
||||
}
|
||||
resp["account_id"] = persisted.AccountID
|
||||
resp["is_new_account"] = persisted.IsNew
|
||||
resp.AccountID = persisted.AccountID
|
||||
resp.IsNewAccount = persisted.IsNew
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
@@ -352,8 +352,8 @@ func cloneQRStatus(src map[string]any) map[string]any {
|
||||
|
||||
// publicQRStatus 返回可暴露给浏览器的扫码状态。闲鱼 Cookie 只在服务端持久化,
|
||||
// 永远不进入前端、浏览器日志或代理响应。
|
||||
func publicQRStatus(src map[string]any) map[string]any {
|
||||
dst := cloneQRStatus(src)
|
||||
func publicQRStatus(src map[string]any) qrLoginStatusResponse {
|
||||
dst := qrLoginStatusResponse(cloneQRStatus(src))
|
||||
delete(dst, "cookies")
|
||||
delete(dst, "cookie_snapshot")
|
||||
return dst
|
||||
|
||||
@@ -73,7 +73,7 @@ func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) {
|
||||
writeErrRequest(w, r, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, m)
|
||||
writeJSON(w, http.StatusOK, settingsResponse(m))
|
||||
}
|
||||
|
||||
func (s *Server) allSettings(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -82,7 +82,7 @@ func (s *Server) allSettings(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, m)
|
||||
writeJSON(w, http.StatusOK, settingsResponse(m))
|
||||
}
|
||||
|
||||
func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -398,7 +398,7 @@ func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, m)
|
||||
writeJSON(w, http.StatusOK, settingsResponse(m))
|
||||
}
|
||||
|
||||
func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -371,6 +371,130 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDynamicCompatibilitySuccessContracts 验证动态设置与二维码兼容响应保留明确边界。
|
||||
func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
|
||||
// srv 是用于验证动态成功响应的 HTTP 测试服务。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := srv.Router()
|
||||
// sessionCookie 是管理员登录后得到的认证会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
|
||||
// publicSettingsReq 是读取公开系统设置的请求。
|
||||
publicSettingsReq := httptest.NewRequest(http.MethodGet, "/system-settings/public", nil)
|
||||
// publicSettingsRecorder 是捕获公开设置响应的记录器。
|
||||
publicSettingsRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(publicSettingsRecorder, publicSettingsReq)
|
||||
if publicSettingsRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("public settings status=%d body=%s", publicSettingsRecorder.Code, publicSettingsRecorder.Body.String())
|
||||
}
|
||||
// publicSettingsValue 是公开设置动态键值响应。
|
||||
var publicSettingsValue settingsResponse
|
||||
// publicSettingsDecodeErr 是公开设置响应反序列化失败的原因。
|
||||
if publicSettingsDecodeErr := json.Unmarshal(publicSettingsRecorder.Body.Bytes(), &publicSettingsValue); publicSettingsDecodeErr != nil {
|
||||
t.Fatalf("decode public settings response: %v", publicSettingsDecodeErr)
|
||||
}
|
||||
if publicSettingsValue == nil {
|
||||
t.Fatal("public settings response must be an object")
|
||||
}
|
||||
|
||||
// allSettingsReq 是读取管理员系统设置的请求。
|
||||
allSettingsReq := httptest.NewRequest(http.MethodGet, "/system-settings", nil)
|
||||
allSettingsReq.AddCookie(sessionCookie)
|
||||
// allSettingsRecorder 是捕获管理员设置响应的记录器。
|
||||
allSettingsRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(allSettingsRecorder, allSettingsReq)
|
||||
if allSettingsRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("all settings status=%d body=%s", allSettingsRecorder.Code, allSettingsRecorder.Body.String())
|
||||
}
|
||||
// allSettingsValue 是管理员设置动态键值响应。
|
||||
var allSettingsValue settingsResponse
|
||||
// allSettingsDecodeErr 是管理员设置响应反序列化失败的原因。
|
||||
if allSettingsDecodeErr := json.Unmarshal(allSettingsRecorder.Body.Bytes(), &allSettingsValue); allSettingsDecodeErr != nil {
|
||||
t.Fatalf("decode all settings response: %v", allSettingsDecodeErr)
|
||||
}
|
||||
if allSettingsValue == nil {
|
||||
t.Fatal("all settings response must be an object")
|
||||
}
|
||||
|
||||
// userSettingsReq 是读取当前用户设置的请求。
|
||||
userSettingsReq := httptest.NewRequest(http.MethodGet, "/user-settings", nil)
|
||||
userSettingsReq.AddCookie(sessionCookie)
|
||||
// userSettingsRecorder 是捕获用户设置响应的记录器。
|
||||
userSettingsRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(userSettingsRecorder, userSettingsReq)
|
||||
if userSettingsRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("user settings status=%d body=%s", userSettingsRecorder.Code, userSettingsRecorder.Body.String())
|
||||
}
|
||||
// userSettingsValue 是用户设置动态键值响应。
|
||||
var userSettingsValue settingsResponse
|
||||
// userSettingsDecodeErr 是用户设置响应反序列化失败的原因。
|
||||
if userSettingsDecodeErr := json.Unmarshal(userSettingsRecorder.Body.Bytes(), &userSettingsValue); userSettingsDecodeErr != nil {
|
||||
t.Fatalf("decode user settings response: %v", userSettingsDecodeErr)
|
||||
}
|
||||
if userSettingsValue == nil {
|
||||
t.Fatal("user settings response must be an object")
|
||||
}
|
||||
|
||||
// srv.QRLogin 是二维码状态与验证的测试替身。
|
||||
srv.QRLogin = &fakeQRLoginService{status: map[string]any{
|
||||
"status": "waiting",
|
||||
"session_id": "contract-qr",
|
||||
"custom_field": "kept",
|
||||
"cookies": "must-not-leak",
|
||||
}}
|
||||
// statusSessionID 是二维码状态测试会话标识。
|
||||
statusSessionID := "contract-qr"
|
||||
ownQRSession(t, srv, store, statusSessionID)
|
||||
// qrStatusReq 是读取二维码状态的请求。
|
||||
qrStatusReq := httptest.NewRequest(http.MethodGet, "/qr-login/check/"+statusSessionID, nil)
|
||||
qrStatusReq.AddCookie(sessionCookie)
|
||||
// qrStatusRecorder 是捕获二维码状态响应的记录器。
|
||||
qrStatusRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(qrStatusRecorder, qrStatusReq)
|
||||
if qrStatusRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("qr status=%d body=%s", qrStatusRecorder.Code, qrStatusRecorder.Body.String())
|
||||
}
|
||||
// qrStatusValue 是二维码状态兼容响应。
|
||||
var qrStatusValue qrLoginStatusResponse
|
||||
// qrStatusDecodeErr 是二维码状态响应反序列化失败的原因。
|
||||
if qrStatusDecodeErr := json.Unmarshal(qrStatusRecorder.Body.Bytes(), &qrStatusValue); qrStatusDecodeErr != nil {
|
||||
t.Fatalf("decode qr status response: %v", qrStatusDecodeErr)
|
||||
}
|
||||
if qrStatusValue["status"] != "waiting" || qrStatusValue["custom_field"] != "kept" {
|
||||
t.Fatalf("qr status response=%+v", qrStatusValue)
|
||||
}
|
||||
// leaked 表示二维码状态响应是否意外包含敏感 Cookie 字段。
|
||||
if _, leaked := qrStatusValue["cookies"]; leaked {
|
||||
t.Fatalf("qr status response leaked cookies: %+v", qrStatusValue)
|
||||
}
|
||||
|
||||
// srv.QRLogin 替换为完成验证场景的测试替身。
|
||||
srv.QRLogin = &fakeQRLoginService{completeCookies: "unb=contract-unb; _m_h5_tk=token;", completeUNB: "contract-unb"}
|
||||
// completeSessionID 是二维码验证完成测试会话标识。
|
||||
completeSessionID := "contract-complete"
|
||||
ownQRSession(t, srv, store, completeSessionID)
|
||||
// completeReq 是提交二维码风控验证完成的请求。
|
||||
completeReq := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/"+completeSessionID, nil)
|
||||
completeReq.AddCookie(sessionCookie)
|
||||
// completeRecorder 是捕获验证完成响应的记录器。
|
||||
completeRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(completeRecorder, completeReq)
|
||||
if completeRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("complete verification status=%d body=%s", completeRecorder.Code, completeRecorder.Body.String())
|
||||
}
|
||||
// completeValue 是二维码验证完成具名响应。
|
||||
var completeValue qrLoginVerificationResponse
|
||||
// completeDecodeErr 是验证完成响应反序列化失败的原因。
|
||||
if completeDecodeErr := json.Unmarshal(completeRecorder.Body.Bytes(), &completeValue); completeDecodeErr != nil {
|
||||
t.Fatalf("decode complete verification response: %v", completeDecodeErr)
|
||||
}
|
||||
if !completeValue.Success || completeValue.UNB != "contract-unb" || completeValue.AccountID != "contract-unb" {
|
||||
t.Fatalf("complete verification response=%+v", completeValue)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReplyAndAccountTaskSuccessResponseContracts 验证回复规则、默认回复和账号任务成功响应的具名 DTO。
|
||||
func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
|
||||
// srv 是用于验证回复和账号任务响应的 HTTP 测试服务。
|
||||
|
||||
@@ -1251,3 +1251,21 @@ type qrLoginGenerateResponse struct {
|
||||
// Message 是可选的提示文本。
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// settingsResponse 是动态设置查询的具名边界类型,键和值仍由设置仓库定义。
|
||||
type settingsResponse map[string]string
|
||||
|
||||
// qrLoginStatusResponse 是二维码状态的兼容响应类型,允许上游扩展非敏感字段。
|
||||
type qrLoginStatusResponse map[string]any
|
||||
|
||||
// qrLoginVerificationResponse 是二维码风控验证完成的具名响应 DTO。
|
||||
type qrLoginVerificationResponse struct {
|
||||
// Success 表示验证结果是否成功。
|
||||
Success bool `json:"success"`
|
||||
// UNB 是平台账号标识。
|
||||
UNB string `json:"unb"`
|
||||
// AccountID 是持久化后的本地账号标识。
|
||||
AccountID string `json:"account_id,omitempty"`
|
||||
// IsNewAccount 表示是否新建了本地账号。
|
||||
IsNewAccount bool `json:"is_new_account,omitempty"`
|
||||
}
|
||||
Reference in new issue
Block a user